def __init__(self): self.threadCallQueue = [] self._eventTriggers = {} self._pendingTimedCalls = [] self._newTimedCalls = [] self._cancellations = 0 self.running = False self._started = False self._justStopped = False # reactor internal readers, e.g. the waker. self._internalReaders = set() self.waker = None # Arrange for the running attribute to change to True at the right time # and let a subclass possibly do other things at that time (eg install # signal handlers). self.addSystemEventTrigger("during", "startup", self._reallyStartRunning) self.addSystemEventTrigger("during", "shutdown", self.crash) self.addSystemEventTrigger("during", "shutdown", self.disconnectAll) if platform.supportsThreads(): self._initThreads() self.installWaker()
def __init__(self): self.threadCallQueue = [] self._eventTriggers = {} self._pendingTimedCalls = [] self._newTimedCalls = [] self._cancellations = 0 self.running = False self._started = False self._justStopped = False # reactor internal readers, e.g. the waker. self._internalReaders = set() self.waker = None # Arrange for the running attribute to change to True at the right time # and let a subclass possibly do other things at that time (eg install # signal handlers). self.addSystemEventTrigger( 'during', 'startup', self._reallyStartRunning) self.addSystemEventTrigger('during', 'shutdown', self.crash) self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll) if platform.supportsThreads(): self._initThreads() self.installWaker()
class ReactorBase(object): """ Default base class for Reactors. @type _stopped: C{bool} @ivar _stopped: A flag which is true between paired calls to C{reactor.run} and C{reactor.stop}. This should be replaced with an explicit state machine. @type _justStopped: C{bool} @ivar _justStopped: A flag which is true between the time C{reactor.stop} is called and the time the shutdown system event is fired. This is used to determine whether that event should be fired after each iteration through the mainloop. This should be replaced with an explicit state machine. @type _started: C{bool} @ivar _started: A flag which is true from the time C{reactor.run} is called until the time C{reactor.run} returns. This is used to prevent calls to C{reactor.run} on a running reactor. This should be replaced with an explicit state machine. @ivar running: See L{IReactorCore.running} """ implements(IReactorCore, IReactorTime, IReactorPluggableResolver) _stopped = True installed = False usingThreads = False resolver = BlockingResolver() __name__ = "lib.twisted.internet.reactor" def __init__(self): self.threadCallQueue = [] self._eventTriggers = {} self._pendingTimedCalls = [] self._newTimedCalls = [] self._cancellations = 0 self.running = False self._started = False self._justStopped = False # reactor internal readers, e.g. the waker. self._internalReaders = set() self.waker = None # Arrange for the running attribute to change to True at the right time # and let a subclass possibly do other things at that time (eg install # signal handlers). self.addSystemEventTrigger( 'during', 'startup', self._reallyStartRunning) self.addSystemEventTrigger('during', 'shutdown', self.crash) self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll) if platform.supportsThreads(): self._initThreads() self.installWaker() # override in subclasses _lock = None def installWaker(self): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement installWaker") def installResolver(self, resolver): assert IResolverSimple.providedBy(resolver) oldResolver = self.resolver self.resolver = resolver return oldResolver def wakeUp(self): """ Wake up the event loop. """ if self.waker: self.waker.wakeUp() # if the waker isn't installed, the reactor isn't running, and # therefore doesn't need to be woken up def doIteration(self, delay): """ Do one iteration over the readers and writers which have been added. """ raise NotImplementedError( reflect.qual(self.__class__) + " did not implement doIteration") def addReader(self, reader): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement addReader") def addWriter(self, writer): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement addWriter") def removeReader(self, reader): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement removeReader") def removeWriter(self, writer): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement removeWriter") def removeAll(self): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement removeAll") def getReaders(self): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement getReaders") def getWriters(self): raise NotImplementedError( reflect.qual(self.__class__) + " did not implement getWriters") def resolve(self, name, timeout = (1, 3, 11, 45)): """Return a Deferred that will resolve a hostname. """ if not name: # XXX - This is *less than* '::', and will screw up IPv6 servers return defer.succeed('0.0.0.0') if abstract.isIPAddress(name): return defer.succeed(name) return self.resolver.getHostByName(name, timeout) # Installation. # IReactorCore def stop(self): """ See lib.twisted.internet.interfaces.IReactorCore.stop. """ if self._stopped: raise error.ReactorNotRunning( "Can't stop reactor that isn't running.") self._stopped = True self._justStopped = True def crash(self): """ See lib.twisted.internet.interfaces.IReactorCore.crash. Reset reactor state tracking attributes and re-initialize certain state-transition helpers which were set up in C{__init__} but later destroyed (through use). """ self._started = False self.running = False self.addSystemEventTrigger( 'during', 'startup', self._reallyStartRunning) def sigInt(self, *args): """Handle a SIGINT interrupt. """ log.msg("Received SIGINT, shutting down.") self.callFromThread(self.stop) def sigBreak(self, *args): """Handle a SIGBREAK interrupt. """ log.msg("Received SIGBREAK, shutting down.") self.callFromThread(self.stop) def sigTerm(self, *args): """Handle a SIGTERM interrupt. """ log.msg("Received SIGTERM, shutting down.") self.callFromThread(self.stop) def disconnectAll(self): """Disconnect every reader, and writer in the system. """ selectables = self.removeAll() for reader in selectables: log.callWithLogger(reader, reader.connectionLost, failure.Failure(main.CONNECTION_LOST)) def iterate(self, delay=0): """See lib.twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doIteration(delay) def fireSystemEvent(self, eventType): """See lib.twisted.internet.interfaces.IReactorCore.fireSystemEvent. """ event = self._eventTriggers.get(eventType) if event is not None: event.fireEvent() def addSystemEventTrigger(self, _phase, _eventType, _f, *args, **kw): """See lib.twisted.internet.interfaces.IReactorCore.addSystemEventTrigger. """ assert callable(_f), "%s is not callable" % _f if _eventType not in self._eventTriggers: self._eventTriggers[_eventType] = _ThreePhaseEvent() return (_eventType, self._eventTriggers[_eventType].addTrigger( _phase, _f, *args, **kw)) def removeSystemEventTrigger(self, triggerID): """See lib.twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger. """ eventType, handle = triggerID self._eventTriggers[eventType].removeTrigger(handle) def callWhenRunning(self, _callable, *args, **kw): """See lib.twisted.internet.interfaces.IReactorCore.callWhenRunning. """ if self.running: _callable(*args, **kw) else: return self.addSystemEventTrigger('after', 'startup', _callable, *args, **kw) def startRunning(self): """ Method called when reactor starts: do some initialization and fire startup events. Don't call this directly, call reactor.run() instead: it should take care of calling this. This method is somewhat misnamed. The reactor will not necessarily be in the running state by the time this method returns. The only guarantee is that it will be on its way to the running state. """ if self._started: raise error.ReactorAlreadyRunning() self._started = True self._stopped = False threadable.registerAsIOThread() self.fireSystemEvent('startup') def _reallyStartRunning(self): """ Method called to transition to the running state. This should happen in the I{during startup} event trigger phase. """ self.running = True # IReactorTime seconds = staticmethod(runtimeSeconds) def callLater(self, _seconds, _f, *args, **kw): """See lib.twisted.internet.interfaces.IReactorTime.callLater. """ assert callable(_f), "%s is not callable" % _f assert sys.maxint >= _seconds >= 0, \ "%s is not greater than or equal to 0 seconds" % (_seconds,) tple = DelayedCall(self.seconds() + _seconds, _f, args, kw, self._cancelCallLater, self._moveCallLaterSooner, seconds=self.seconds) self._newTimedCalls.append(tple) return tple def _moveCallLaterSooner(self, tple): # Linear time find: slow. heap = self._pendingTimedCalls try: pos = heap.index(tple) # Move elt up the heap until it rests at the right place. elt = heap[pos] while pos != 0: parent = (pos-1) // 2 if heap[parent] <= elt: break # move parent down heap[pos] = heap[parent] pos = parent heap[pos] = elt except ValueError: # element was not found in heap - oh well... pass def _cancelCallLater(self, tple): self._cancellations+=1 def getDelayedCalls(self): """Return all the outstanding delayed calls in the system. They are returned in no particular order. This method is not efficient -- it is really only meant for test cases.""" return [x for x in (self._pendingTimedCalls + self._newTimedCalls) if not x.cancelled] def _insertNewDelayedCalls(self): for call in self._newTimedCalls: if call.cancelled: self._cancellations-=1 else: call.activate_delay() heappush(self._pendingTimedCalls, call) self._newTimedCalls = [] def timeout(self): # insert new delayed calls to make sure to include them in timeout value self._insertNewDelayedCalls() if not self._pendingTimedCalls: return None return max(0, self._pendingTimedCalls[0].time - self.seconds()) def runUntilCurrent(self): """Run all pending timed calls. """ if self.threadCallQueue: # Keep track of how many calls we actually make, as we're # making them, in case another call is added to the queue # while we're in this loop. count = 0 total = len(self.threadCallQueue) for (f, a, kw) in self.threadCallQueue: try: f(*a, **kw) except: log.err() count += 1 if count == total: break del self.threadCallQueue[:count] if self.threadCallQueue: self.wakeUp() # insert new delayed calls now self._insertNewDelayedCalls() now = self.seconds() while self._pendingTimedCalls and (self._pendingTimedCalls[0].time <= now): call = heappop(self._pendingTimedCalls) if call.cancelled: self._cancellations-=1 continue if call.delayed_time > 0: call.activate_delay() heappush(self._pendingTimedCalls, call) continue try: call.called = 1 call.func(*call.args, **call.kw) except: log.deferr() if hasattr(call, "creator"): e = "\n" e += " C: previous exception occurred in " + \ "a DelayedCall created here:\n" e += " C:" e += "".join(call.creator).rstrip().replace("\n","\n C:") e += "\n" log.msg(e) if (self._cancellations > 50 and self._cancellations > len(self._pendingTimedCalls) >> 1): self._cancellations = 0 self._pendingTimedCalls = [x for x in self._pendingTimedCalls if not x.cancelled] heapify(self._pendingTimedCalls) if self._justStopped: self._justStopped = False self.fireSystemEvent("shutdown") # IReactorProcess def _checkProcessArgs(self, args, env): """ Check for valid arguments and environment to spawnProcess. @return: A two element tuple giving values to use when creating the process. The first element of the tuple is a C{list} of C{str} giving the values for argv of the child process. The second element of the tuple is either C{None} if C{env} was C{None} or a C{dict} mapping C{str} environment keys to C{str} environment values. """ # Any unicode string which Python would successfully implicitly # encode to a byte string would have worked before these explicit # checks were added. Anything which would have failed with a # UnicodeEncodeError during that implicit encoding step would have # raised an exception in the child process and that would have been # a pain in the butt to debug. # # So, we will explicitly attempt the same encoding which Python # would implicitly do later. If it fails, we will report an error # without ever spawning a child process. If it succeeds, we'll save # the result so that Python doesn't need to do it implicitly later. # # For any unicode which we can actually encode, we'll also issue a # deprecation warning, because no one should be passing unicode here # anyway. # # -exarkun defaultEncoding = sys.getdefaultencoding() # Common check function def argChecker(arg): """ Return either a str or None. If the given value is not allowable for some reason, None is returned. Otherwise, a possibly different object which should be used in place of arg is returned. This forces unicode encoding to happen now, rather than implicitly later. """ if isinstance(arg, unicode): try: arg = arg.encode(defaultEncoding) except UnicodeEncodeError: return None warnings.warn( "Argument strings and environment keys/values passed to " "reactor.spawnProcess should be str, not unicode.", category=DeprecationWarning, stacklevel=4) if isinstance(arg, str) and '\0' not in arg: return arg return None # Make a few tests to check input validity if not isinstance(args, (tuple, list)): raise TypeError("Arguments must be a tuple or list") outputArgs = [] for arg in args: arg = argChecker(arg) if arg is None: raise TypeError("Arguments contain a non-string value") else: outputArgs.append(arg) outputEnv = None if env is not None: outputEnv = {} for key, val in env.iteritems(): key = argChecker(key) if key is None: raise TypeError("Environment contains a non-string key") val = argChecker(val) if val is None: raise TypeError("Environment contains a non-string value") outputEnv[key] = val return outputArgs, outputEnv # IReactorThreads if platform.supportsThreads(): threadpool = None # ID of the trigger starting the threadpool _threadpoolStartupID = None # ID of the trigger stopping the threadpool threadpoolShutdownID = None def _initThreads(self): self.usingThreads = True self.resolver = ThreadedResolver(self) def callFromThread(self, f, *args, **kw): """ See L{lib.twisted.internet.interfaces.IReactorThreads.callFromThread}. """ assert callable(f), "%s is not callable" % (f,) # lists are thread-safe in CPython, but not in Jython # this is probably a bug in Jython, but until fixed this code # won't work in Jython. self.threadCallQueue.append((f, args, kw)) self.wakeUp() def _initThreadPool(self): """ Create the threadpool accessible with callFromThread. """ from lib.twisted.python import threadpool self.threadpool = threadpool.ThreadPool( 0, 10, 'lib.twisted.internet.reactor') self._threadpoolStartupID = self.callWhenRunning( self.threadpool.start) self.threadpoolShutdownID = self.addSystemEventTrigger( 'during', 'shutdown', self._stopThreadPool) def _uninstallHandler(self): pass def _stopThreadPool(self): """ Stop the reactor threadpool. This method is only valid if there is currently a threadpool (created by L{_initThreadPool}). It is not intended to be called directly; instead, it will be called by a shutdown trigger created in L{_initThreadPool}. """ triggers = [self._threadpoolStartupID, self.threadpoolShutdownID] for trigger in filter(None, triggers): try: self.removeSystemEventTrigger(trigger) except ValueError: pass self._threadpoolStartupID = None self.threadpoolShutdownID = None self.threadpool.stop() self.threadpool = None def getThreadPool(self): """ See L{lib.twisted.internet.interfaces.IReactorThreads.getThreadPool}. """ if self.threadpool is None: self._initThreadPool() return self.threadpool def callInThread(self, _callable, *args, **kwargs): """ See L{lib.twisted.internet.interfaces.IReactorThreads.callInThread}. """ self.getThreadPool().callInThread(_callable, *args, **kwargs) def suggestThreadPoolSize(self, size): """ See L{lib.twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}. """ self.getThreadPool().adjustPoolsize(maxthreads=size) else: # This is for signal handlers. def callFromThread(self, f, *args, **kw): assert callable(f), "%s is not callable" % (f,) # See comment in the other callFromThread implementation. self.threadCallQueue.append((f, args, kw))
""" self.getThreadPool().callInThread(_callable, *args, **kwargs) def suggestThreadPoolSize(self, size): """ See L{lib.twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}. """ self.getThreadPool().adjustPoolsize(maxthreads=size) else: # This is for signal handlers. def callFromThread(self, f, *args, **kw): assert callable(f), "%s is not callable" % (f,) # See comment in the other callFromThread implementation. self.threadCallQueue.append((f, args, kw)) if platform.supportsThreads(): classImplements(ReactorBase, IReactorThreads) class BaseConnector(styles.Ephemeral): """Basic implementation of connector. State can be: "connecting", "connected", "disconnected" """ implements(IConnector) timeoutID = None factoryStarted = 0 def __init__(self, factory, timeout, reactor):
def suggestThreadPoolSize(self, size): """ See L{lib.twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}. """ self.getThreadPool().adjustPoolsize(maxthreads=size) else: # This is for signal handlers. def callFromThread(self, f, *args, **kw): assert callable(f), "%s is not callable" % (f,) # See comment in the other callFromThread implementation. self.threadCallQueue.append((f, args, kw)) if platform.supportsThreads(): classImplements(ReactorBase, IReactorThreads) class BaseConnector(styles.Ephemeral): """Basic implementation of connector. State can be: "connecting", "connected", "disconnected" """ implements(IConnector) timeoutID = None factoryStarted = 0 def __init__(self, factory, timeout, reactor):