Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  1. # -*- test-case-name: twisted.test.test_internet,twisted.internet.test.test_core -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Very basic functionality for a Reactor implementation.
  6. """
  7. import builtins
  8. import socket # needed only for sync-dns
  9. import warnings
  10. from abc import ABC, abstractmethod
  11. from heapq import heapify, heappop, heappush
  12. from traceback import format_stack
  13. from types import FrameType
  14. from typing import (
  15. TYPE_CHECKING,
  16. Any,
  17. Callable,
  18. Dict,
  19. List,
  20. NewType,
  21. Optional,
  22. Sequence,
  23. Set,
  24. Tuple,
  25. Union,
  26. cast,
  27. )
  28. from zope.interface import classImplements, implementer
  29. from twisted.internet import abstract, defer, error, fdesc, main, threads
  30. from twisted.internet._resolver import (
  31. ComplexResolverSimplifier as _ComplexResolverSimplifier,
  32. GAIResolver as _GAIResolver,
  33. SimpleResolverComplexifier as _SimpleResolverComplexifier,
  34. )
  35. from twisted.internet.defer import Deferred, DeferredList
  36. from twisted.internet.interfaces import (
  37. IAddress,
  38. IConnector,
  39. IDelayedCall,
  40. IHostnameResolver,
  41. IProtocol,
  42. IReactorCore,
  43. IReactorPluggableNameResolver,
  44. IReactorPluggableResolver,
  45. IReactorThreads,
  46. IReactorTime,
  47. IReadDescriptor,
  48. IResolverSimple,
  49. IWriteDescriptor,
  50. _ISupportsExitSignalCapturing,
  51. )
  52. from twisted.internet.protocol import ClientFactory
  53. from twisted.python import log, reflect
  54. from twisted.python.failure import Failure
  55. from twisted.python.runtime import platform, seconds as runtimeSeconds
  56. if TYPE_CHECKING:
  57. from twisted.internet.tcp import Client
  58. # This import is for side-effects! Even if you don't see any code using it
  59. # in this module, don't delete it.
  60. from twisted.python import threadable
  61. if platform.supportsThreads():
  62. from twisted.python.threadpool import ThreadPool
  63. else:
  64. ThreadPool = None # type: ignore[misc, assignment]
  65. @implementer(IDelayedCall)
  66. class DelayedCall:
  67. # enable .debug to record creator call stack, and it will be logged if
  68. # an exception occurs while the function is being run
  69. debug = False
  70. _repr: Optional[str] = None
  71. # In debug mode, the call stack at the time of instantiation.
  72. creator: Optional[Sequence[str]] = None
  73. def __init__(
  74. self,
  75. time: float,
  76. func: Callable[..., Any],
  77. args: Sequence[object],
  78. kw: Dict[str, object],
  79. cancel: Callable[["DelayedCall"], None],
  80. reset: Callable[["DelayedCall"], None],
  81. seconds: Callable[[], float] = runtimeSeconds,
  82. ) -> None:
  83. """
  84. @param time: Seconds from the epoch at which to call C{func}.
  85. @param func: The callable to call.
  86. @param args: The positional arguments to pass to the callable.
  87. @param kw: The keyword arguments to pass to the callable.
  88. @param cancel: A callable which will be called with this
  89. DelayedCall before cancellation.
  90. @param reset: A callable which will be called with this
  91. DelayedCall after changing this DelayedCall's scheduled
  92. execution time. The callable should adjust any necessary
  93. scheduling details to ensure this DelayedCall is invoked
  94. at the new appropriate time.
  95. @param seconds: If provided, a no-argument callable which will be
  96. used to determine the current time any time that information is
  97. needed.
  98. """
  99. self.time, self.func, self.args, self.kw = time, func, args, kw
  100. self.resetter = reset
  101. self.canceller = cancel
  102. self.seconds = seconds
  103. self.cancelled = self.called = 0
  104. self.delayed_time = 0.0
  105. if self.debug:
  106. self.creator = format_stack()[:-2]
  107. def getTime(self) -> float:
  108. """
  109. Return the time at which this call will fire
  110. @return: The number of seconds after the epoch at which this call is
  111. scheduled to be made.
  112. """
  113. return self.time + self.delayed_time
  114. def cancel(self) -> None:
  115. """
  116. Unschedule this call
  117. @raise AlreadyCancelled: Raised if this call has already been
  118. unscheduled.
  119. @raise AlreadyCalled: Raised if this call has already been made.
  120. """
  121. if self.cancelled:
  122. raise error.AlreadyCancelled
  123. elif self.called:
  124. raise error.AlreadyCalled
  125. else:
  126. self.canceller(self)
  127. self.cancelled = 1
  128. if self.debug:
  129. self._repr = repr(self)
  130. del self.func, self.args, self.kw
  131. def reset(self, secondsFromNow: float) -> None:
  132. """
  133. Reschedule this call for a different time
  134. @param secondsFromNow: The number of seconds from the time of the
  135. C{reset} call at which this call will be scheduled.
  136. @raise AlreadyCancelled: Raised if this call has been cancelled.
  137. @raise AlreadyCalled: Raised if this call has already been made.
  138. """
  139. if self.cancelled:
  140. raise error.AlreadyCancelled
  141. elif self.called:
  142. raise error.AlreadyCalled
  143. else:
  144. newTime = self.seconds() + secondsFromNow
  145. if newTime < self.time:
  146. self.delayed_time = 0.0
  147. self.time = newTime
  148. self.resetter(self)
  149. else:
  150. self.delayed_time = newTime - self.time
  151. def delay(self, secondsLater: float) -> None:
  152. """
  153. Reschedule this call for a later time
  154. @param secondsLater: The number of seconds after the originally
  155. scheduled time for which to reschedule this call.
  156. @raise AlreadyCancelled: Raised if this call has been cancelled.
  157. @raise AlreadyCalled: Raised if this call has already been made.
  158. """
  159. if self.cancelled:
  160. raise error.AlreadyCancelled
  161. elif self.called:
  162. raise error.AlreadyCalled
  163. else:
  164. self.delayed_time += secondsLater
  165. if self.delayed_time < 0.0:
  166. self.activate_delay()
  167. self.resetter(self)
  168. def activate_delay(self) -> None:
  169. self.time += self.delayed_time
  170. self.delayed_time = 0.0
  171. def active(self) -> bool:
  172. """Determine whether this call is still pending
  173. @return: True if this call has not yet been made or cancelled,
  174. False otherwise.
  175. """
  176. return not (self.cancelled or self.called)
  177. def __le__(self, other: object) -> bool:
  178. """
  179. Implement C{<=} operator between two L{DelayedCall} instances.
  180. Comparison is based on the C{time} attribute (unadjusted by the
  181. delayed time).
  182. """
  183. if isinstance(other, DelayedCall):
  184. return self.time <= other.time
  185. else:
  186. return NotImplemented
  187. def __lt__(self, other: object) -> bool:
  188. """
  189. Implement C{<} operator between two L{DelayedCall} instances.
  190. Comparison is based on the C{time} attribute (unadjusted by the
  191. delayed time).
  192. """
  193. if isinstance(other, DelayedCall):
  194. return self.time < other.time
  195. else:
  196. return NotImplemented
  197. def __repr__(self) -> str:
  198. """
  199. Implement C{repr()} for L{DelayedCall} instances.
  200. @returns: String containing details of the L{DelayedCall}.
  201. """
  202. if self._repr is not None:
  203. return self._repr
  204. if hasattr(self, "func"):
  205. # This code should be replaced by a utility function in reflect;
  206. # see ticket #6066:
  207. func = getattr(self.func, "__qualname__", None)
  208. if func is None:
  209. func = getattr(self.func, "__name__", None)
  210. if func is not None:
  211. imClass = getattr(self.func, "im_class", None)
  212. if imClass is not None:
  213. func = f"{imClass}.{func}"
  214. if func is None:
  215. func = reflect.safe_repr(self.func)
  216. else:
  217. func = None
  218. now = self.seconds()
  219. L = [
  220. "<DelayedCall 0x%x [%ss] called=%s cancelled=%s"
  221. % (id(self), self.time - now, self.called, self.cancelled)
  222. ]
  223. if func is not None:
  224. L.extend((" ", func, "("))
  225. if self.args:
  226. L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
  227. if self.kw:
  228. L.append(", ")
  229. if self.kw:
  230. L.append(
  231. ", ".join(
  232. [f"{k}={reflect.safe_repr(v)}" for (k, v) in self.kw.items()]
  233. )
  234. )
  235. L.append(")")
  236. if self.creator is not None:
  237. L.append("\n\ntraceback at creation: \n\n%s" % (" ".join(self.creator)))
  238. L.append(">")
  239. return "".join(L)
  240. @implementer(IResolverSimple)
  241. class ThreadedResolver:
  242. """
  243. L{ThreadedResolver} uses a reactor, a threadpool, and
  244. L{socket.gethostbyname} to perform name lookups without blocking the
  245. reactor thread. It also supports timeouts indepedently from whatever
  246. timeout logic L{socket.gethostbyname} might have.
  247. @ivar reactor: The reactor the threadpool of which will be used to call
  248. L{socket.gethostbyname} and the I/O thread of which the result will be
  249. delivered.
  250. """
  251. def __init__(self, reactor: "ReactorBase") -> None:
  252. self.reactor = reactor
  253. self._runningQueries: Dict[
  254. Deferred[str], Tuple[Deferred[str], IDelayedCall]
  255. ] = {}
  256. def _fail(self, name: str, err: str) -> Failure:
  257. lookupError = error.DNSLookupError(f"address {name!r} not found: {err}")
  258. return Failure(lookupError)
  259. def _cleanup(self, name: str, lookupDeferred: Deferred[str]) -> None:
  260. userDeferred, cancelCall = self._runningQueries[lookupDeferred]
  261. del self._runningQueries[lookupDeferred]
  262. userDeferred.errback(self._fail(name, "timeout error"))
  263. def _checkTimeout(
  264. self, result: str, name: str, lookupDeferred: Deferred[str]
  265. ) -> None:
  266. try:
  267. userDeferred, cancelCall = self._runningQueries[lookupDeferred]
  268. except KeyError:
  269. pass
  270. else:
  271. del self._runningQueries[lookupDeferred]
  272. cancelCall.cancel()
  273. if isinstance(result, Failure):
  274. userDeferred.errback(self._fail(name, result.getErrorMessage()))
  275. else:
  276. userDeferred.callback(result)
  277. def getHostByName(
  278. self, name: str, timeout: Sequence[int] = (1, 3, 11, 45)
  279. ) -> Deferred[str]:
  280. """
  281. See L{twisted.internet.interfaces.IResolverSimple.getHostByName}.
  282. Note that the elements of C{timeout} are summed and the result is used
  283. as a timeout for the lookup. Any intermediate timeout or retry logic
  284. is left up to the platform via L{socket.gethostbyname}.
  285. """
  286. if timeout:
  287. timeoutDelay = sum(timeout)
  288. else:
  289. timeoutDelay = 60
  290. userDeferred: Deferred[str] = Deferred()
  291. lookupDeferred = threads.deferToThreadPool(
  292. self.reactor,
  293. cast(IReactorThreads, self.reactor).getThreadPool(),
  294. socket.gethostbyname,
  295. name,
  296. )
  297. cancelCall = cast(IReactorTime, self.reactor).callLater(
  298. timeoutDelay, self._cleanup, name, lookupDeferred
  299. )
  300. self._runningQueries[lookupDeferred] = (userDeferred, cancelCall)
  301. lookupDeferred.addBoth(self._checkTimeout, name, lookupDeferred)
  302. return userDeferred
  303. @implementer(IResolverSimple)
  304. class BlockingResolver:
  305. def getHostByName(
  306. self, name: str, timeout: Sequence[int] = (1, 3, 11, 45)
  307. ) -> Deferred[str]:
  308. try:
  309. address = socket.gethostbyname(name)
  310. except OSError:
  311. msg = f"address {name!r} not found"
  312. err = error.DNSLookupError(msg)
  313. return defer.fail(err)
  314. else:
  315. return defer.succeed(address)
  316. _ThreePhaseEventTriggerCallable = Callable[..., Any]
  317. _ThreePhaseEventTrigger = Tuple[
  318. _ThreePhaseEventTriggerCallable, Tuple[object, ...], Dict[str, object]
  319. ]
  320. _ThreePhaseEventTriggerHandle = NewType(
  321. "_ThreePhaseEventTriggerHandle",
  322. Tuple[str, _ThreePhaseEventTriggerCallable, Tuple[object, ...], Dict[str, object]],
  323. )
  324. class _ThreePhaseEvent:
  325. """
  326. Collection of callables (with arguments) which can be invoked as a group in
  327. a particular order.
  328. This provides the underlying implementation for the reactor's system event
  329. triggers. An instance of this class tracks triggers for all phases of a
  330. single type of event.
  331. @ivar before: A list of the before-phase triggers containing three-tuples
  332. of a callable, a tuple of positional arguments, and a dict of keyword
  333. arguments
  334. @ivar finishedBefore: A list of the before-phase triggers which have
  335. already been executed. This is only populated in the C{'BEFORE'} state.
  336. @ivar during: A list of the during-phase triggers containing three-tuples
  337. of a callable, a tuple of positional arguments, and a dict of keyword
  338. arguments
  339. @ivar after: A list of the after-phase triggers containing three-tuples
  340. of a callable, a tuple of positional arguments, and a dict of keyword
  341. arguments
  342. @ivar state: A string indicating what is currently going on with this
  343. object. One of C{'BASE'} (for when nothing in particular is happening;
  344. this is the initial value), C{'BEFORE'} (when the before-phase triggers
  345. are in the process of being executed).
  346. """
  347. def __init__(self) -> None:
  348. self.before: List[_ThreePhaseEventTrigger] = []
  349. self.during: List[_ThreePhaseEventTrigger] = []
  350. self.after: List[_ThreePhaseEventTrigger] = []
  351. self.state = "BASE"
  352. def addTrigger(
  353. self,
  354. phase: str,
  355. callable: _ThreePhaseEventTriggerCallable,
  356. *args: object,
  357. **kwargs: object,
  358. ) -> _ThreePhaseEventTriggerHandle:
  359. """
  360. Add a trigger to the indicate phase.
  361. @param phase: One of C{'before'}, C{'during'}, or C{'after'}.
  362. @param callable: An object to be called when this event is triggered.
  363. @param args: Positional arguments to pass to C{callable}.
  364. @param kwargs: Keyword arguments to pass to C{callable}.
  365. @return: An opaque handle which may be passed to L{removeTrigger} to
  366. reverse the effects of calling this method.
  367. """
  368. if phase not in ("before", "during", "after"):
  369. raise KeyError("invalid phase")
  370. getattr(self, phase).append((callable, args, kwargs))
  371. return _ThreePhaseEventTriggerHandle((phase, callable, args, kwargs))
  372. def removeTrigger(self, handle: _ThreePhaseEventTriggerHandle) -> None:
  373. """
  374. Remove a previously added trigger callable.
  375. @param handle: An object previously returned by L{addTrigger}. The
  376. trigger added by that call will be removed.
  377. @raise ValueError: If the trigger associated with C{handle} has already
  378. been removed or if C{handle} is not a valid handle.
  379. """
  380. getattr(self, "removeTrigger_" + self.state)(handle)
  381. def removeTrigger_BASE(self, handle: _ThreePhaseEventTriggerHandle) -> None:
  382. """
  383. Just try to remove the trigger.
  384. @see: removeTrigger
  385. """
  386. try:
  387. phase, callable, args, kwargs = handle
  388. except (TypeError, ValueError):
  389. raise ValueError("invalid trigger handle")
  390. else:
  391. if phase not in ("before", "during", "after"):
  392. raise KeyError("invalid phase")
  393. getattr(self, phase).remove((callable, args, kwargs))
  394. def removeTrigger_BEFORE(self, handle: _ThreePhaseEventTriggerHandle) -> None:
  395. """
  396. Remove the trigger if it has yet to be executed, otherwise emit a
  397. warning that in the future an exception will be raised when removing an
  398. already-executed trigger.
  399. @see: removeTrigger
  400. """
  401. phase, callable, args, kwargs = handle
  402. if phase != "before":
  403. return self.removeTrigger_BASE(handle)
  404. if (callable, args, kwargs) in self.finishedBefore:
  405. warnings.warn(
  406. "Removing already-fired system event triggers will raise an "
  407. "exception in a future version of Twisted.",
  408. category=DeprecationWarning,
  409. stacklevel=3,
  410. )
  411. else:
  412. self.removeTrigger_BASE(handle)
  413. def fireEvent(self) -> None:
  414. """
  415. Call the triggers added to this event.
  416. """
  417. self.state = "BEFORE"
  418. self.finishedBefore = []
  419. beforeResults: List[Deferred[object]] = []
  420. while self.before:
  421. callable, args, kwargs = self.before.pop(0)
  422. self.finishedBefore.append((callable, args, kwargs))
  423. try:
  424. result = callable(*args, **kwargs)
  425. except BaseException:
  426. log.err()
  427. else:
  428. if isinstance(result, Deferred):
  429. beforeResults.append(result)
  430. DeferredList(beforeResults).addCallback(self._continueFiring)
  431. def _continueFiring(self, ignored: object) -> None:
  432. """
  433. Call the during and after phase triggers for this event.
  434. """
  435. self.state = "BASE"
  436. self.finishedBefore = []
  437. for phase in self.during, self.after:
  438. while phase:
  439. callable, args, kwargs = phase.pop(0)
  440. try:
  441. callable(*args, **kwargs)
  442. except BaseException:
  443. log.err()
  444. @implementer(IReactorPluggableNameResolver, IReactorPluggableResolver)
  445. class PluggableResolverMixin:
  446. """
  447. A mixin which implements the pluggable resolver reactor interfaces.
  448. @ivar resolver: The installed L{IResolverSimple}.
  449. @ivar _nameResolver: The installed L{IHostnameResolver}.
  450. """
  451. resolver: IResolverSimple = BlockingResolver()
  452. _nameResolver: IHostnameResolver = _SimpleResolverComplexifier(resolver)
  453. # IReactorPluggableResolver
  454. def installResolver(self, resolver: IResolverSimple) -> IResolverSimple:
  455. """
  456. See L{IReactorPluggableResolver}.
  457. @param resolver: see L{IReactorPluggableResolver}.
  458. @return: see L{IReactorPluggableResolver}.
  459. """
  460. assert IResolverSimple.providedBy(resolver)
  461. oldResolver = self.resolver
  462. self.resolver = resolver
  463. self._nameResolver = _SimpleResolverComplexifier(resolver)
  464. return oldResolver
  465. # IReactorPluggableNameResolver
  466. def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
  467. """
  468. See L{IReactorPluggableNameResolver}.
  469. @param resolver: See L{IReactorPluggableNameResolver}.
  470. @return: see L{IReactorPluggableNameResolver}.
  471. """
  472. previousNameResolver = self._nameResolver
  473. self._nameResolver = resolver
  474. self.resolver = _ComplexResolverSimplifier(resolver)
  475. return previousNameResolver
  476. @property
  477. def nameResolver(self) -> IHostnameResolver:
  478. """
  479. Implementation of read-only
  480. L{IReactorPluggableNameResolver.nameResolver}.
  481. """
  482. return self._nameResolver
  483. _SystemEventID = NewType("_SystemEventID", Tuple[str, _ThreePhaseEventTriggerHandle])
  484. _ThreadCall = Tuple[Callable[..., Any], Tuple[object, ...], Dict[str, object]]
  485. @implementer(IReactorCore, IReactorTime, _ISupportsExitSignalCapturing)
  486. class ReactorBase(PluggableResolverMixin):
  487. """
  488. Default base class for Reactors.
  489. @ivar _stopped: A flag which is true between paired calls to C{reactor.run}
  490. and C{reactor.stop}. This should be replaced with an explicit state
  491. machine.
  492. @ivar _justStopped: A flag which is true between the time C{reactor.stop}
  493. is called and the time the shutdown system event is fired. This is
  494. used to determine whether that event should be fired after each
  495. iteration through the mainloop. This should be replaced with an
  496. explicit state machine.
  497. @ivar _started: A flag which is true from the time C{reactor.run} is called
  498. until the time C{reactor.run} returns. This is used to prevent calls
  499. to C{reactor.run} on a running reactor. This should be replaced with
  500. an explicit state machine.
  501. @ivar running: See L{IReactorCore.running}
  502. @ivar _registerAsIOThread: A flag controlling whether the reactor will
  503. register the thread it is running in as the I/O thread when it starts.
  504. If C{True}, registration will be done, otherwise it will not be.
  505. @ivar _exitSignal: See L{_ISupportsExitSignalCapturing._exitSignal}
  506. """
  507. _registerAsIOThread = True
  508. _stopped = True
  509. installed = False
  510. usingThreads = False
  511. _exitSignal = None
  512. __name__ = "twisted.internet.reactor"
  513. def __init__(self) -> None:
  514. super().__init__()
  515. self.threadCallQueue: List[_ThreadCall] = []
  516. self._eventTriggers: Dict[str, _ThreePhaseEvent] = {}
  517. self._pendingTimedCalls: List[DelayedCall] = []
  518. self._newTimedCalls: List[DelayedCall] = []
  519. self._cancellations = 0
  520. self.running = False
  521. self._started = False
  522. self._justStopped = False
  523. self._startedBefore = False
  524. # reactor internal readers, e.g. the waker.
  525. # Using Any as the type here… unable to find a suitable defined interface
  526. self._internalReaders: Set[Any] = set()
  527. self.waker: Any = None
  528. # Arrange for the running attribute to change to True at the right time
  529. # and let a subclass possibly do other things at that time (eg install
  530. # signal handlers).
  531. self.addSystemEventTrigger("during", "startup", self._reallyStartRunning)
  532. self.addSystemEventTrigger("during", "shutdown", self.crash)
  533. self.addSystemEventTrigger("during", "shutdown", self.disconnectAll)
  534. if platform.supportsThreads():
  535. self._initThreads()
  536. self.installWaker()
  537. # override in subclasses
  538. _lock = None
  539. def installWaker(self) -> None:
  540. raise NotImplementedError(
  541. reflect.qual(self.__class__) + " did not implement installWaker"
  542. )
  543. def wakeUp(self) -> None:
  544. """
  545. Wake up the event loop.
  546. """
  547. if self.waker:
  548. self.waker.wakeUp()
  549. # if the waker isn't installed, the reactor isn't running, and
  550. # therefore doesn't need to be woken up
  551. def doIteration(self, delay: Optional[float]) -> None:
  552. """
  553. Do one iteration over the readers and writers which have been added.
  554. """
  555. raise NotImplementedError(
  556. reflect.qual(self.__class__) + " did not implement doIteration"
  557. )
  558. def addReader(self, reader: IReadDescriptor) -> None:
  559. raise NotImplementedError(
  560. reflect.qual(self.__class__) + " did not implement addReader"
  561. )
  562. def addWriter(self, writer: IWriteDescriptor) -> None:
  563. raise NotImplementedError(
  564. reflect.qual(self.__class__) + " did not implement addWriter"
  565. )
  566. def removeReader(self, reader: IReadDescriptor) -> None:
  567. raise NotImplementedError(
  568. reflect.qual(self.__class__) + " did not implement removeReader"
  569. )
  570. def removeWriter(self, writer: IWriteDescriptor) -> None:
  571. raise NotImplementedError(
  572. reflect.qual(self.__class__) + " did not implement removeWriter"
  573. )
  574. def removeAll(self) -> List[Union[IReadDescriptor, IWriteDescriptor]]:
  575. raise NotImplementedError(
  576. reflect.qual(self.__class__) + " did not implement removeAll"
  577. )
  578. def getReaders(self) -> List[IReadDescriptor]:
  579. raise NotImplementedError(
  580. reflect.qual(self.__class__) + " did not implement getReaders"
  581. )
  582. def getWriters(self) -> List[IWriteDescriptor]:
  583. raise NotImplementedError(
  584. reflect.qual(self.__class__) + " did not implement getWriters"
  585. )
  586. # IReactorCore
  587. def resolve(
  588. self, name: str, timeout: Sequence[int] = (1, 3, 11, 45)
  589. ) -> Deferred[str]:
  590. """
  591. Return a Deferred that will resolve a hostname."""
  592. if not name:
  593. # XXX - This is *less than* '::', and will screw up IPv6 servers
  594. return defer.succeed("0.0.0.0")
  595. if abstract.isIPAddress(name):
  596. return defer.succeed(name)
  597. return self.resolver.getHostByName(name, timeout)
  598. def stop(self) -> None:
  599. """
  600. See twisted.internet.interfaces.IReactorCore.stop.
  601. """
  602. if self._stopped:
  603. raise error.ReactorNotRunning("Can't stop reactor that isn't running.")
  604. self._stopped = True
  605. self._justStopped = True
  606. self._startedBefore = True
  607. def crash(self) -> None:
  608. """
  609. See twisted.internet.interfaces.IReactorCore.crash.
  610. Reset reactor state tracking attributes and re-initialize certain
  611. state-transition helpers which were set up in C{__init__} but later
  612. destroyed (through use).
  613. """
  614. self._started = False
  615. self.running = False
  616. self.addSystemEventTrigger("during", "startup", self._reallyStartRunning)
  617. def sigInt(self, number: int, frame: Optional[FrameType] = None) -> None:
  618. """
  619. Handle a SIGINT interrupt.
  620. @param number: See handler specification in L{signal.signal}
  621. @param frame: See handler specification in L{signal.signal}
  622. """
  623. log.msg("Received SIGINT, shutting down.")
  624. self.callFromThread(self.stop)
  625. self._exitSignal = number
  626. def sigBreak(self, number: int, frame: Optional[FrameType] = None) -> None:
  627. """
  628. Handle a SIGBREAK interrupt.
  629. @param number: See handler specification in L{signal.signal}
  630. @param frame: See handler specification in L{signal.signal}
  631. """
  632. log.msg("Received SIGBREAK, shutting down.")
  633. self.callFromThread(self.stop)
  634. self._exitSignal = number
  635. def sigTerm(self, number: int, frame: Optional[FrameType] = None) -> None:
  636. """
  637. Handle a SIGTERM interrupt.
  638. @param number: See handler specification in L{signal.signal}
  639. @param frame: See handler specification in L{signal.signal}
  640. """
  641. log.msg("Received SIGTERM, shutting down.")
  642. self.callFromThread(self.stop)
  643. self._exitSignal = number
  644. def disconnectAll(self) -> None:
  645. """Disconnect every reader, and writer in the system."""
  646. selectables = self.removeAll()
  647. for reader in selectables:
  648. log.callWithLogger(
  649. reader, reader.connectionLost, Failure(main.CONNECTION_LOST)
  650. )
  651. def iterate(self, delay: float = 0.0) -> None:
  652. """
  653. See twisted.internet.interfaces.IReactorCore.iterate.
  654. """
  655. self.runUntilCurrent()
  656. self.doIteration(delay)
  657. def fireSystemEvent(self, eventType: str) -> None:
  658. """
  659. See twisted.internet.interfaces.IReactorCore.fireSystemEvent.
  660. """
  661. event = self._eventTriggers.get(eventType)
  662. if event is not None:
  663. event.fireEvent()
  664. def addSystemEventTrigger(
  665. self,
  666. phase: str,
  667. eventType: str,
  668. callable: Callable[..., Any],
  669. *args: object,
  670. **kwargs: object,
  671. ) -> _SystemEventID:
  672. """
  673. See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
  674. """
  675. assert builtins.callable(callable), f"{callable} is not callable"
  676. if eventType not in self._eventTriggers:
  677. self._eventTriggers[eventType] = _ThreePhaseEvent()
  678. return _SystemEventID(
  679. (
  680. eventType,
  681. self._eventTriggers[eventType].addTrigger(
  682. phase, callable, *args, **kwargs
  683. ),
  684. )
  685. )
  686. def removeSystemEventTrigger(self, triggerID: _SystemEventID) -> None:
  687. """
  688. See twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
  689. """
  690. eventType, handle = triggerID
  691. self._eventTriggers[eventType].removeTrigger(handle)
  692. def callWhenRunning(
  693. self, callable: Callable[..., Any], *args: object, **kwargs: object
  694. ) -> Optional[_SystemEventID]:
  695. """
  696. See twisted.internet.interfaces.IReactorCore.callWhenRunning.
  697. """
  698. if self.running:
  699. callable(*args, **kwargs)
  700. return None
  701. else:
  702. return self.addSystemEventTrigger(
  703. "after", "startup", callable, *args, **kwargs
  704. )
  705. def startRunning(self) -> None:
  706. """
  707. Method called when reactor starts: do some initialization and fire
  708. startup events.
  709. Don't call this directly, call reactor.run() instead: it should take
  710. care of calling this.
  711. This method is somewhat misnamed. The reactor will not necessarily be
  712. in the running state by the time this method returns. The only
  713. guarantee is that it will be on its way to the running state.
  714. """
  715. if self._started:
  716. raise error.ReactorAlreadyRunning()
  717. if self._startedBefore:
  718. raise error.ReactorNotRestartable()
  719. self._started = True
  720. self._stopped = False
  721. if self._registerAsIOThread:
  722. threadable.registerAsIOThread()
  723. self.fireSystemEvent("startup")
  724. def _reallyStartRunning(self) -> None:
  725. """
  726. Method called to transition to the running state. This should happen
  727. in the I{during startup} event trigger phase.
  728. """
  729. self.running = True
  730. def run(self) -> None:
  731. # IReactorCore.run
  732. raise NotImplementedError()
  733. # IReactorTime
  734. seconds = staticmethod(runtimeSeconds)
  735. def callLater(
  736. self, delay: float, callable: Callable[..., Any], *args: object, **kw: object
  737. ) -> DelayedCall:
  738. """
  739. See twisted.internet.interfaces.IReactorTime.callLater.
  740. """
  741. assert builtins.callable(callable), f"{callable} is not callable"
  742. assert delay >= 0, f"{delay} is not greater than or equal to 0 seconds"
  743. delayedCall = DelayedCall(
  744. self.seconds() + delay,
  745. callable,
  746. args,
  747. kw,
  748. self._cancelCallLater,
  749. self._moveCallLaterSooner,
  750. seconds=self.seconds,
  751. )
  752. self._newTimedCalls.append(delayedCall)
  753. return delayedCall
  754. def _moveCallLaterSooner(self, delayedCall: DelayedCall) -> None:
  755. # Linear time find: slow.
  756. heap = self._pendingTimedCalls
  757. try:
  758. pos = heap.index(delayedCall)
  759. # Move elt up the heap until it rests at the right place.
  760. elt = heap[pos]
  761. while pos != 0:
  762. parent = (pos - 1) // 2
  763. if heap[parent] <= elt:
  764. break
  765. # move parent down
  766. heap[pos] = heap[parent]
  767. pos = parent
  768. heap[pos] = elt
  769. except ValueError:
  770. # element was not found in heap - oh well...
  771. pass
  772. def _cancelCallLater(self, delayedCall: DelayedCall) -> None:
  773. self._cancellations += 1
  774. def getDelayedCalls(self) -> Sequence[IDelayedCall]:
  775. """
  776. See L{twisted.internet.interfaces.IReactorTime.getDelayedCalls}
  777. """
  778. return [
  779. x
  780. for x in (self._pendingTimedCalls + self._newTimedCalls)
  781. if not x.cancelled
  782. ]
  783. def _insertNewDelayedCalls(self) -> None:
  784. for call in self._newTimedCalls:
  785. if call.cancelled:
  786. self._cancellations -= 1
  787. else:
  788. call.activate_delay()
  789. heappush(self._pendingTimedCalls, call)
  790. self._newTimedCalls = []
  791. def timeout(self) -> Optional[float]:
  792. """
  793. Determine the longest time the reactor may sleep (waiting on I/O
  794. notification, perhaps) before it must wake up to service a time-related
  795. event.
  796. @return: The maximum number of seconds the reactor may sleep.
  797. """
  798. # insert new delayed calls to make sure to include them in timeout value
  799. self._insertNewDelayedCalls()
  800. if not self._pendingTimedCalls:
  801. return None
  802. delay = self._pendingTimedCalls[0].time - self.seconds()
  803. # Pick a somewhat arbitrary maximum possible value for the timeout.
  804. # This value is 2 ** 31 / 1000, which is the number of seconds which can
  805. # be represented as an integer number of milliseconds in a signed 32 bit
  806. # integer. This particular limit is imposed by the epoll_wait(3)
  807. # interface which accepts a timeout as a C "int" type and treats it as
  808. # representing a number of milliseconds.
  809. longest = 2147483
  810. # Don't let the delay be in the past (negative) or exceed a plausible
  811. # maximum (platform-imposed) interval.
  812. return max(0, min(longest, delay))
  813. def runUntilCurrent(self) -> None:
  814. """
  815. Run all pending timed calls.
  816. """
  817. if self.threadCallQueue:
  818. # Keep track of how many calls we actually make, as we're
  819. # making them, in case another call is added to the queue
  820. # while we're in this loop.
  821. count = 0
  822. total = len(self.threadCallQueue)
  823. for (f, a, kw) in self.threadCallQueue:
  824. try:
  825. f(*a, **kw)
  826. except BaseException:
  827. log.err()
  828. count += 1
  829. if count == total:
  830. break
  831. del self.threadCallQueue[:count]
  832. if self.threadCallQueue:
  833. self.wakeUp()
  834. # insert new delayed calls now
  835. self._insertNewDelayedCalls()
  836. now = self.seconds()
  837. while self._pendingTimedCalls and (self._pendingTimedCalls[0].time <= now):
  838. call = heappop(self._pendingTimedCalls)
  839. if call.cancelled:
  840. self._cancellations -= 1
  841. continue
  842. if call.delayed_time > 0.0:
  843. call.activate_delay()
  844. heappush(self._pendingTimedCalls, call)
  845. continue
  846. try:
  847. call.called = 1
  848. call.func(*call.args, **call.kw)
  849. except BaseException:
  850. log.err()
  851. if call.creator is not None:
  852. e = "\n"
  853. e += (
  854. " C: previous exception occurred in "
  855. + "a DelayedCall created here:\n"
  856. )
  857. e += " C:"
  858. e += "".join(call.creator).rstrip().replace("\n", "\n C:")
  859. e += "\n"
  860. log.msg(e)
  861. if (
  862. self._cancellations > 50
  863. and self._cancellations > len(self._pendingTimedCalls) >> 1
  864. ):
  865. self._cancellations = 0
  866. self._pendingTimedCalls = [
  867. x for x in self._pendingTimedCalls if not x.cancelled
  868. ]
  869. heapify(self._pendingTimedCalls)
  870. if self._justStopped:
  871. self._justStopped = False
  872. self.fireSystemEvent("shutdown")
  873. # IReactorThreads
  874. if platform.supportsThreads():
  875. assert ThreadPool is not None
  876. threadpool = None
  877. # ID of the trigger starting the threadpool
  878. _threadpoolStartupID = None
  879. # ID of the trigger stopping the threadpool
  880. threadpoolShutdownID = None
  881. def _initThreads(self) -> None:
  882. self.installNameResolver(_GAIResolver(self, self.getThreadPool))
  883. self.usingThreads = True
  884. # `IReactorFromThreads` defines the first named argument as
  885. # `callable: Callable[..., Any]` but this defines it as `f`
  886. # really both should be defined using py3.8 positional only
  887. def callFromThread( # type: ignore[override]
  888. self, f: Callable[..., Any], *args: object, **kwargs: object
  889. ) -> None:
  890. """
  891. See
  892. L{twisted.internet.interfaces.IReactorFromThreads.callFromThread}.
  893. """
  894. assert callable(f), f"{f} is not callable"
  895. # lists are thread-safe in CPython, but not in Jython
  896. # this is probably a bug in Jython, but until fixed this code
  897. # won't work in Jython.
  898. self.threadCallQueue.append((f, args, kwargs))
  899. self.wakeUp()
  900. def _initThreadPool(self) -> None:
  901. """
  902. Create the threadpool accessible with callFromThread.
  903. """
  904. self.threadpool = ThreadPool(0, 10, "twisted.internet.reactor")
  905. self._threadpoolStartupID = self.callWhenRunning(self.threadpool.start)
  906. self.threadpoolShutdownID = self.addSystemEventTrigger(
  907. "during", "shutdown", self._stopThreadPool
  908. )
  909. def _uninstallHandler(self) -> None:
  910. pass
  911. def _stopThreadPool(self) -> None:
  912. """
  913. Stop the reactor threadpool. This method is only valid if there
  914. is currently a threadpool (created by L{_initThreadPool}). It
  915. is not intended to be called directly; instead, it will be
  916. called by a shutdown trigger created in L{_initThreadPool}.
  917. """
  918. triggers = [self._threadpoolStartupID, self.threadpoolShutdownID]
  919. for trigger in filter(None, triggers):
  920. try:
  921. self.removeSystemEventTrigger(trigger)
  922. except ValueError:
  923. pass
  924. self._threadpoolStartupID = None
  925. self.threadpoolShutdownID = None
  926. assert self.threadpool is not None
  927. self.threadpool.stop()
  928. self.threadpool = None
  929. def getThreadPool(self) -> ThreadPool:
  930. """
  931. See L{twisted.internet.interfaces.IReactorThreads.getThreadPool}.
  932. """
  933. if self.threadpool is None:
  934. self._initThreadPool()
  935. assert self.threadpool is not None
  936. return self.threadpool
  937. # `IReactorInThreads` defines the first named argument as
  938. # `callable: Callable[..., Any]` but this defines it as `_callable`
  939. # really both should be defined using py3.8 positional only
  940. def callInThread( # type: ignore[override]
  941. self, _callable: Callable[..., Any], *args: object, **kwargs: object
  942. ) -> None:
  943. """
  944. See L{twisted.internet.interfaces.IReactorInThreads.callInThread}.
  945. """
  946. self.getThreadPool().callInThread(_callable, *args, **kwargs)
  947. def suggestThreadPoolSize(self, size: int) -> None:
  948. """
  949. See L{twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}.
  950. """
  951. self.getThreadPool().adjustPoolsize(maxthreads=size)
  952. else:
  953. # This is for signal handlers.
  954. def callFromThread(
  955. self, f: Callable[..., Any], *args: object, **kwargs: object
  956. ) -> None:
  957. assert callable(f), f"{f} is not callable"
  958. # See comment in the other callFromThread implementation.
  959. self.threadCallQueue.append((f, args, kwargs))
  960. if platform.supportsThreads():
  961. classImplements(ReactorBase, IReactorThreads)
  962. @implementer(IConnector)
  963. class BaseConnector(ABC):
  964. """
  965. Basic implementation of L{IConnector}.
  966. State can be: "connecting", "connected", "disconnected"
  967. """
  968. timeoutID = None
  969. factoryStarted = 0
  970. def __init__(
  971. self, factory: ClientFactory, timeout: float, reactor: ReactorBase
  972. ) -> None:
  973. self.state = "disconnected"
  974. self.reactor = reactor
  975. self.factory = factory
  976. self.timeout = timeout
  977. def disconnect(self) -> None:
  978. """Disconnect whatever our state is."""
  979. if self.state == "connecting":
  980. self.stopConnecting()
  981. elif self.state == "connected":
  982. assert self.transport is not None
  983. self.transport.loseConnection()
  984. @abstractmethod
  985. def _makeTransport(self) -> "Client":
  986. pass
  987. def connect(self) -> None:
  988. """Start connection to remote server."""
  989. if self.state != "disconnected":
  990. raise RuntimeError("can't connect in this state")
  991. self.state = "connecting"
  992. if not self.factoryStarted:
  993. self.factory.doStart()
  994. self.factoryStarted = 1
  995. self.transport: Optional[Client] = self._makeTransport()
  996. if self.timeout is not None:
  997. self.timeoutID = self.reactor.callLater(
  998. self.timeout, self.transport.failIfNotConnected, error.TimeoutError()
  999. )
  1000. self.factory.startedConnecting(self)
  1001. def stopConnecting(self) -> None:
  1002. """Stop attempting to connect."""
  1003. if self.state != "connecting":
  1004. raise error.NotConnectingError("we're not trying to connect")
  1005. assert self.transport is not None
  1006. self.state = "disconnected"
  1007. self.transport.failIfNotConnected(error.UserError())
  1008. del self.transport
  1009. def cancelTimeout(self) -> None:
  1010. if self.timeoutID is not None:
  1011. try:
  1012. self.timeoutID.cancel()
  1013. except ValueError:
  1014. pass
  1015. del self.timeoutID
  1016. def buildProtocol(self, addr: IAddress) -> Optional[IProtocol]:
  1017. self.state = "connected"
  1018. self.cancelTimeout()
  1019. return self.factory.buildProtocol(addr)
  1020. def connectionFailed(self, reason: Failure) -> None:
  1021. self.cancelTimeout()
  1022. self.transport = None
  1023. self.state = "disconnected"
  1024. self.factory.clientConnectionFailed(self, reason)
  1025. if self.state == "disconnected":
  1026. # factory hasn't called our connect() method
  1027. self.factory.doStop()
  1028. self.factoryStarted = 0
  1029. def connectionLost(self, reason: Failure) -> None:
  1030. self.state = "disconnected"
  1031. self.factory.clientConnectionLost(self, reason)
  1032. if self.state == "disconnected":
  1033. # factory hasn't called our connect() method
  1034. self.factory.doStop()
  1035. self.factoryStarted = 0
  1036. def getDestination(self) -> IAddress:
  1037. raise NotImplementedError(
  1038. reflect.qual(self.__class__) + " did not implement " "getDestination"
  1039. )
  1040. def __repr__(self) -> str:
  1041. return "<{} instance at 0x{:x} {} {}>".format(
  1042. reflect.qual(self.__class__),
  1043. id(self),
  1044. self.state,
  1045. self.getDestination(),
  1046. )
  1047. class BasePort(abstract.FileDescriptor):
  1048. """Basic implementation of a ListeningPort.
  1049. Note: This does not actually implement IListeningPort.
  1050. """
  1051. addressFamily: socket.AddressFamily = None # type: ignore[assignment]
  1052. socketType: socket.SocketKind = None # type: ignore[assignment]
  1053. def createInternetSocket(self) -> socket.socket:
  1054. s = socket.socket(self.addressFamily, self.socketType)
  1055. s.setblocking(False)
  1056. fdesc._setCloseOnExec(s.fileno())
  1057. return s
  1058. def doWrite(self) -> Optional[Failure]:
  1059. """Raises a RuntimeError"""
  1060. raise RuntimeError("doWrite called on a %s" % reflect.qual(self.__class__))
  1061. class _SignalReactorMixin:
  1062. """
  1063. Private mixin to manage signals: it installs signal handlers at start time,
  1064. and define run method.
  1065. It can only be used mixed in with L{ReactorBase}, and has to be defined
  1066. first in the inheritance (so that method resolution order finds
  1067. startRunning first).
  1068. @ivar _installSignalHandlers: A flag which indicates whether any signal
  1069. handlers will be installed during startup. This includes handlers for
  1070. SIGCHLD to monitor child processes, and SIGINT, SIGTERM, and SIGBREAK
  1071. to stop the reactor.
  1072. """
  1073. _installSignalHandlers = False
  1074. def _handleSignals(self) -> None:
  1075. """
  1076. Install the signal handlers for the Twisted event loop.
  1077. """
  1078. try:
  1079. import signal
  1080. except ImportError:
  1081. log.msg(
  1082. "Warning: signal module unavailable -- "
  1083. "not installing signal handlers."
  1084. )
  1085. return
  1086. reactorBaseSelf = cast(ReactorBase, self)
  1087. if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
  1088. # only handle if there isn't already a handler, e.g. for Pdb.
  1089. signal.signal(signal.SIGINT, reactorBaseSelf.sigInt)
  1090. signal.signal(signal.SIGTERM, reactorBaseSelf.sigTerm)
  1091. # Catch Ctrl-Break in windows
  1092. SIGBREAK = getattr(signal, "SIGBREAK", None)
  1093. if SIGBREAK is not None:
  1094. signal.signal(SIGBREAK, reactorBaseSelf.sigBreak)
  1095. def startRunning(self, installSignalHandlers: bool = True) -> None:
  1096. """
  1097. Extend the base implementation in order to remember whether signal
  1098. handlers should be installed later.
  1099. @param installSignalHandlers: A flag which, if set, indicates that
  1100. handlers for a number of (implementation-defined) signals should be
  1101. installed during startup.
  1102. """
  1103. self._installSignalHandlers = installSignalHandlers
  1104. ReactorBase.startRunning(cast(ReactorBase, self))
  1105. def _reallyStartRunning(self) -> None:
  1106. """
  1107. Extend the base implementation by also installing signal handlers, if
  1108. C{self._installSignalHandlers} is true.
  1109. """
  1110. ReactorBase._reallyStartRunning(cast(ReactorBase, self))
  1111. if self._installSignalHandlers:
  1112. # Make sure this happens before after-startup events, since the
  1113. # expectation of after-startup is that the reactor is fully
  1114. # initialized. Don't do it right away for historical reasons
  1115. # (perhaps some before-startup triggers don't want there to be a
  1116. # custom SIGCHLD handler so that they can run child processes with
  1117. # some blocking api).
  1118. self._handleSignals()
  1119. def run(self, installSignalHandlers: bool = True) -> None:
  1120. self.startRunning(installSignalHandlers=installSignalHandlers)
  1121. self.mainLoop()
  1122. def mainLoop(self) -> None:
  1123. reactorBaseSelf = cast(ReactorBase, self)
  1124. while reactorBaseSelf._started:
  1125. try:
  1126. while reactorBaseSelf._started:
  1127. # Advance simulation time in delayed event
  1128. # processors.
  1129. reactorBaseSelf.runUntilCurrent()
  1130. t2 = reactorBaseSelf.timeout()
  1131. t = reactorBaseSelf.running and t2
  1132. reactorBaseSelf.doIteration(t)
  1133. except BaseException:
  1134. log.msg("Unexpected error in main loop.")
  1135. log.err()
  1136. else:
  1137. log.msg("Main loop terminated.") # type:ignore[unreachable]
  1138. __all__: List[str] = []