base.py 43 KB

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