base.py 44 KB

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