示例#1
0
    def __init__(self):
        super(ReactorBase, self).__init__()
        self.threadCallQueue = []
        self._eventTriggers = {}
        self._pendingTimedCalls = []
        self._newTimedCalls = []
        self._cancellations = 0
        self.running = False
        self._started = False
        self._justStopped = False
        self._startedBefore = 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()
示例#2
0
    def __init__(self):
        self.threadCallQueue = []
        self._eventTriggers = {}
        self._pendingTimedCalls = []
        self._newTimedCalls = []
        self._cancellations = 0
        self.running = False
        self._started = False
        self._justStopped = False
        self._startedBefore = False
        # reactor internal readers, e.g. the waker.
        self._internalReaders = set()
        self._nameResolver = None
        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()
示例#3
0
    def __init__(self) -> None:
        super().__init__()
        self.threadCallQueue: List[_ThreadCall] = []
        self._eventTriggers: Dict[str, _ThreePhaseEvent] = {}
        self._pendingTimedCalls: List[DelayedCall] = []
        self._newTimedCalls: List[DelayedCall] = []
        self._cancellations = 0
        self.running = False
        self._started = False
        self._justStopped = False
        self._startedBefore = False
        # reactor internal readers, e.g. the waker.
        # Using Any as the type here… unable to find a suitable defined interface
        self._internalReaders: Set[Any] = set()
        self.waker: Any = 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()
示例#4
0
 def _handleSigchld(self,
                    signum,
                    frame,
                    _threadSupport=platform.supportsThreads()):
     from twisted.internet.process import reapAllProcesses
     if _threadSupport:
         self.callFromThread(reapAllProcesses)
     else:
         self.callLater(0, reapAllProcesses)
示例#5
0
 def __init__(self):
     self.threadCallQueue = []
     self._eventTriggers = {}
     self._pendingTimedCalls = []
     self._newTimedCalls = []
     self._cancellations = 0
     self.running = 0
     self.waker = None
     self.addSystemEventTrigger('during', 'shutdown', self.crash)
     self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)
     if platform.supportsThreads():
         self._initThreads()
示例#6
0
 def _handleSigchld(self, signum, frame, _threadSupport=platform.supportsThreads()):
     """Reap all processes on SIGCHLD.
     This gets called on SIGCHLD. We do no processing inside a signal
     handler, as the calls we make here could occur between any two
     python bytecode instructions. Deferring processing to the next
     eventloop round prevents us from violating the state constraints
     of arbitrary classes.
     """
     if _threadSupport:
         self.callFromThread(process.reapAllProcesses)
     else:
         self.callLater(0, process.reapAllProcesses)
示例#7
0
    def _handleSigchld(self, signum, frame, _threadSupport=platform.supportsThreads()):
        """Reap all processes on SIGCHLD.

        This gets called on SIGCHLD. We do no processing inside a signal
        handler, as the calls we make here could occur between any two
        python bytecode instructions. Deferring processing to the next
        eventloop round prevents us from violating the state constraints
        of arbitrary classes.
        """
        if _threadSupport:
            self.callFromThread(process.reapAllProcesses)
        else:
            self.callLater(0, process.reapAllProcesses)
示例#8
0
    def __init__(self):
        self.threadCallQueue = []
        self._eventTriggers = {}
        self._pendingTimedCalls = []
        self._newTimedCalls = []
        self._cancellations = 0
        self.running = 0
        self.waker = None

        self.addSystemEventTrigger('during', 'shutdown', self.crash)
        self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)

        if platform.supportsThreads():
            self._initThreads()
示例#9
0
 def _handleSigchld(self, signum, frame, _threadSupport=platform.supportsThreads()):
     from twisted.internet.process import reapAllProcesses
     if _threadSupport:
         self.callFromThread(reapAllProcesses)
     else:
         self.callLater(0, reapAllProcesses)
示例#10
0
文件: base.py 项目: emragins/tribal
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__ = "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
        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()

    # 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 not threadable.isInIOThread():
            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 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 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 twisted.internet.interfaces.IReactorCore.iterate.
        """
        self.runUntilCurrent()
        self.doIteration(delay)


    def fireSystemEvent(self, eventType):
        """See 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 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 twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
        """
        eventType, handle = triggerID
        self._eventTriggers[eventType].removeTrigger(handle)


    def callWhenRunning(self, _callable, *args, **kw):
        """See 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:
            warnings.warn(
                    "Reactor already running! This behavior is deprecated "
                    "since Twisted 8.0",
                    category=DeprecationWarning, stacklevel=4)
        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 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 cancelCallLater(self, callID):
        """See twisted.internet.interfaces.IReactorTime.cancelCallLater.
        """
        # DO NOT DELETE THIS - this is documented in Python in a Nutshell, so we
        # we can't get rid of it for a long time.
        warnings.warn("reactor.cancelCallLater(callID) is deprecated - use callID.cancel() instead")
        callID.cancel()

    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:
                if self.waker:
                    self.waker.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 stopping the threadpool
        threadpoolShutdownID = None

        def _initThreads(self):
            self.usingThreads = True
            self.resolver = ThreadedResolver(self)
            self.installWaker()

        def callFromThread(self, f, *args, **kw):
            """
            See L{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 twisted.python import threadpool
            self.threadpool = threadpool.ThreadPool(0, 10, 'twisted.internet.reactor')
            self.callWhenRunning(self.threadpool.start)
            self.threadpoolShutdownID = self.addSystemEventTrigger(
                'during', 'shutdown', self._stopThreadPool)

        def _stopThreadPool(self):
            """
            Stop the reactor threadpool.
            """
            self.threadpoolShutdownID = None
            self.threadpool.stop()
            self.threadpool = None

        def callInThread(self, _callable, *args, **kwargs):
            """
            See L{twisted.internet.interfaces.IReactorThreads.callInThread}.
            """
            if self.threadpool is None:
                self._initThreadPool()
            self.threadpool.callInThread(_callable, *args, **kwargs)

        def suggestThreadPoolSize(self, size):
            """
            See L{twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}.
            """
            if size == 0 and self.threadpool is None:
                return
            if self.threadpool is None:
                self._initThreadPool()
            self.threadpool.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))
示例#11
0
文件: base.py 项目: emragins/tribal
            """
            See L{twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}.
            """
            if size == 0 and self.threadpool is None:
                return
            if self.threadpool is None:
                self._initThreadPool()
            self.threadpool.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):
示例#12
0
class ReactorBase(object):
    """Default base class for Reactors.
    """

    implements(IReactorCore, IReactorTime, IReactorPluggableResolver)

    installed = 0
    usingThreads = 0
    resolver = BlockingResolver()

    __name__ = "twisted.internet.reactor"

    def __init__(self):
        self.threadCallQueue = []
        self._eventTriggers = {}
        self._pendingTimedCalls = []
        self._newTimedCalls = []
        self._cancellations = 0
        self.running = 0
        self.waker = None

        self.addSystemEventTrigger('during', 'shutdown', self.crash)
        self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)

        if platform.supportsThreads():
            self._initThreads()

    # override in subclasses

    _lock = None

    def installWaker(self):
        raise NotImplementedError()

    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 not threadable.isInIOThread():
            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 we know about."""
        raise NotImplementedError

    def addReader(self, reader):
        raise NotImplementedError

    def addWriter(self, writer):
        raise NotImplementedError

    def removeReader(self, reader):
        raise NotImplementedError

    def removeWriter(self, writer):
        raise NotImplementedError

    def removeAll(self):
        raise NotImplementedError

    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 twisted.internet.interfaces.IReactorCore.stop.
        """
        if not self.running:
            raise RuntimeError, "can't stop reactor that isn't running"
        self.fireSystemEvent("shutdown")

    def crash(self):
        """See twisted.internet.interfaces.IReactorCore.crash.
        """
        self.running = 0

    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 twisted.internet.interfaces.IReactorCore.iterate.
        """
        self.runUntilCurrent()
        self.doIteration(delay)

    def fireSystemEvent(self, eventType):
        """See twisted.internet.interfaces.IReactorCore.fireSystemEvent.
        """
        sysEvtTriggers = self._eventTriggers.get(eventType)
        if not sysEvtTriggers:
            return
        defrList = []
        for callable, args, kw in sysEvtTriggers[0]:
            try:
                d = callable(*args, **kw)
            except:
                log.deferr()
            else:
                if isinstance(d, Deferred):
                    defrList.append(d)
        if defrList:
            DeferredList(defrList).addBoth(self._cbContinueSystemEvent,
                                           eventType)
        else:
            self.callLater(0, self._continueSystemEvent, eventType)

    def _cbContinueSystemEvent(self, result, eventType):
        self._continueSystemEvent(eventType)

    def _continueSystemEvent(self, eventType):
        sysEvtTriggers = self._eventTriggers.get(eventType)
        for callList in sysEvtTriggers[1], sysEvtTriggers[2]:
            for callable, args, kw in callList:
                try:
                    callable(*args, **kw)
                except:
                    log.deferr()
        # now that we've called all callbacks, no need to store
        # references to them anymore, in fact this can cause problems.
        del self._eventTriggers[eventType]

    def addSystemEventTrigger(self, _phase, _eventType, _f, *args, **kw):
        """See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
        """
        assert callable(_f), "%s is not callable" % _f
        if self._eventTriggers.has_key(_eventType):
            triglist = self._eventTriggers[_eventType]
        else:
            triglist = [[], [], []]
            self._eventTriggers[_eventType] = triglist
        evtList = triglist[{"before": 0, "during": 1, "after": 2}[_phase]]
        evtList.append((_f, args, kw))
        return (_phase, _eventType, (_f, args, kw))

    def removeSystemEventTrigger(self, triggerID):
        """See twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
        """
        phase, eventType, item = triggerID
        self._eventTriggers[eventType][{
            "before": 0,
            "during": 1,
            "after": 2
        }[phase]].remove(item)

    def callWhenRunning(self, _callable, *args, **kw):
        """See twisted.internet.interfaces.IReactorCore.callWhenRunning.
        """
        if self.running:
            _callable(*args, **kw)
        else:
            return self.addSystemEventTrigger('after', 'startup', _callable,
                                              *args, **kw)

    # IReactorTime

    def callLater(self, _seconds, _f, *args, **kw):
        """See 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(seconds() + _seconds, _f, args, kw,
                           self._cancelCallLater, self._moveCallLaterSooner)
        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 cancelCallLater(self, callID):
        """See twisted.internet.interfaces.IReactorTime.cancelCallLater.
        """
        # DO NOT DELETE THIS - this is documented in Python in a Nutshell, so we
        # we can't get rid of it for a long time.
        warnings.warn(
            "reactor.cancelCallLater(callID) is deprecated - use callID.cancel() instead"
        )
        callID.cancel()

    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 - 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:
                if self.waker:
                    self.waker.wakeUp()

        # insert new delayed calls now
        self._insertNewDelayedCalls()

        now = 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)

    # IReactorThreads
    if platform.supportsThreads():
        threadpool = None

        def _initThreads(self):
            self.usingThreads = 1
            self.resolver = ThreadedResolver(self)
            self.installWaker()

        def callFromThread(self, f, *args, **kw):
            """See 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):
            from twisted.python import threadpool
            self.threadpool = threadpool.ThreadPool(
                0, 10, 'twisted.internet.reactor')
            self.callWhenRunning(self.threadpool.start)
            self.addSystemEventTrigger('during', 'shutdown',
                                       self.threadpool.stop)

        def callInThread(self, _callable, *args, **kwargs):
            """See twisted.internet.interfaces.IReactorThreads.callInThread.
            """
            if self.threadpool is None:
                self._initThreadPool()
            self.threadpool.callInThread(_callable, *args, **kwargs)

        def suggestThreadPoolSize(self, size):
            """See twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize.
            """
            if size == 0 and not self.threadpool:
                return
            if not self.threadpool:
                self._initThreadPool()
            self.threadpool.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))
示例#13
0
class ReactorBase(PluggableResolverMixin):
    """
    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}

    @ivar _registerAsIOThread: A flag controlling whether the reactor will
        register the thread it is running in as the I/O thread when it starts.
        If C{True}, registration will be done, otherwise it will not be.

    @ivar _exitSignal: See L{_ISupportsExitSignalCapturing._exitSignal}
    """

    _registerAsIOThread = True

    _stopped = True
    installed = False
    usingThreads = False
    _exitSignal = None

    __name__ = "twisted.internet.reactor"

    def __init__(self):
        super(ReactorBase, self).__init__()
        self.threadCallQueue = []
        self._eventTriggers = {}
        self._pendingTimedCalls = []
        self._newTimedCalls = []
        self._cancellations = 0
        self.running = False
        self._started = False
        self._justStopped = False
        self._startedBefore = 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 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")


    # IReactorCore
    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)


    def stop(self):
        """
        See 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
        self._startedBefore = True


    def crash(self):
        """
        See 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.

        @param args: See handler specification in L{signal.signal}
        """
        log.msg("Received SIGINT, shutting down.")
        self.callFromThread(self.stop)
        self._exitSignal = args[0]


    def sigBreak(self, *args):
        """
        Handle a SIGBREAK interrupt.

        @param args: See handler specification in L{signal.signal}
        """
        log.msg("Received SIGBREAK, shutting down.")
        self.callFromThread(self.stop)
        self._exitSignal = args[0]


    def sigTerm(self, *args):
        """
        Handle a SIGTERM interrupt.

        @param args: See handler specification in L{signal.signal}
        """
        log.msg("Received SIGTERM, shutting down.")
        self.callFromThread(self.stop)
        self._exitSignal = args[0]


    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 twisted.internet.interfaces.IReactorCore.iterate.
        """
        self.runUntilCurrent()
        self.doIteration(delay)


    def fireSystemEvent(self, eventType):
        """See twisted.internet.interfaces.IReactorCore.fireSystemEvent.
        """
        event = self._eventTriggers.get(eventType)
        if event is not None:
            event.fireEvent()


    def addSystemEventTrigger(self, phase: str, eventType: str,
                              callable: Callable[..., Any], *args, **kw):
        """See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
        """
        assert builtins.callable(callable), \
               "{} is not callable".format(callable)
        if eventType not in self._eventTriggers:
            self._eventTriggers[eventType] = _ThreePhaseEvent()
        return (eventType, self._eventTriggers[eventType].addTrigger(
            phase, callable, *args, **kw))


    def removeSystemEventTrigger(self, triggerID):
        """See twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
        """
        eventType, handle = triggerID
        self._eventTriggers[eventType].removeTrigger(handle)


    def callWhenRunning(self, callable: Callable[..., Any], *args, **kw):
        """See 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()
        if self._startedBefore:
            raise error.ReactorNotRestartable()
        self._started = True
        self._stopped = False
        if self._registerAsIOThread:
            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


    def run(self):
        # IReactorCore.run
        raise NotImplementedError()


    # IReactorTime

    seconds = staticmethod(runtimeSeconds)

    def callLater(self, delay, callable: Callable[..., Any], *args, **kw):
        """See twisted.internet.interfaces.IReactorTime.callLater.
        """
        assert builtins.callable(callable), \
               "{} is not callable".format(callable)
        assert delay >= 0, \
               "{} is not greater than or equal to 0 seconds".format(delay)
        tple = DelayedCall(self.seconds() + delay, callable, 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: A list of outstanding delayed calls.
        @type: L{list} of L{DelayedCall}
        """
        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):
        """
        Determine the longest time the reactor may sleep (waiting on I/O
        notification, perhaps) before it must wake up to service a time-related
        event.

        @return: The maximum number of seconds the reactor may sleep.
        @rtype: L{float}
        """
        # insert new delayed calls to make sure to include them in timeout value
        self._insertNewDelayedCalls()

        if not self._pendingTimedCalls:
            return None

        delay = self._pendingTimedCalls[0].time - self.seconds()

        # Pick a somewhat arbitrary maximum possible value for the timeout.
        # This value is 2 ** 31 / 1000, which is the number of seconds which can
        # be represented as an integer number of milliseconds in a signed 32 bit
        # integer.  This particular limit is imposed by the epoll_wait(3)
        # interface which accepts a timeout as a C "int" type and treats it as
        # representing a number of milliseconds.
        longest = 2147483

        # Don't let the delay be in the past (negative) or exceed a plausible
        # maximum (platform-imposed) interval.
        return max(0, min(longest, delay))


    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{bytes}
        giving the values for argv of the child process.  The second element
        of the tuple is either L{None} if C{env} was L{None} or a C{dict}
        mapping C{bytes} environment keys to C{bytes} 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.
        #
        # -exarkun

        # If any of the following environment variables:
        #  - PYTHONUTF8
        #  - PYTHONIOENCODING
        #
        # are set before the Python interpreter runs, they will affect the
        # value of sys.stdout.encoding
        defaultEncoding = sys.stdout.encoding

        # Common check function
        def argChecker(arg):
            """
            Return either L{bytes} or L{None}.  If the given value is not
            allowable for some reason, L{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
            if isinstance(arg, bytes) and b'\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: {}".format(arg))
            else:
                outputArgs.append(_arg)

        outputEnv = None
        if env is not None:
            outputEnv = {}
            for key, val in iteritems(env):
                _key = argChecker(key)
                if _key is None:
                    raise TypeError(
                        "Environment contains a "
                        "non-string key: {}, using encoding: {}".format(
                            key, sys.stdout.encoding))
                _val = argChecker(val)
                if _val is None:
                    raise TypeError(
                        "Environment contains a "
                        "non-string value: {}, using encoding {}".format(
                            val, sys.stdout.encoding))
                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.installNameResolver(_GAIResolver(self, self.getThreadPool))
            self.usingThreads = True


        def callFromThread(self, f, *args, **kw):
            """
            See
            L{twisted.internet.interfaces.IReactorFromThreads.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 twisted.python import threadpool
            self.threadpool = threadpool.ThreadPool(
                0, 10, '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{twisted.internet.interfaces.IReactorThreads.getThreadPool}.
            """
            if self.threadpool is None:
                self._initThreadPool()
            return self.threadpool


        def callInThread(self, _callable, *args, **kwargs):
            """
            See L{twisted.internet.interfaces.IReactorInThreads.callInThread}.
            """
            self.getThreadPool().callInThread(_callable, *args, **kwargs)


        def suggestThreadPoolSize(self, size):
            """
            See L{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))
示例#14
0
class ReactorBase(PluggableResolverMixin):
    """
    Default base class for Reactors.

    @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.
    @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.
    @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}
    @ivar _registerAsIOThread: A flag controlling whether the reactor will
        register the thread it is running in as the I/O thread when it starts.
        If C{True}, registration will be done, otherwise it will not be.
    @ivar _exitSignal: See L{_ISupportsExitSignalCapturing._exitSignal}
    """

    _registerAsIOThread = True

    _stopped = True
    installed = False
    usingThreads = False
    _exitSignal = None

    __name__ = "twisted.internet.reactor"

    def __init__(self) -> None:
        super().__init__()
        self.threadCallQueue: List[_ThreadCall] = []
        self._eventTriggers: Dict[str, _ThreePhaseEvent] = {}
        self._pendingTimedCalls: List[DelayedCall] = []
        self._newTimedCalls: List[DelayedCall] = []
        self._cancellations = 0
        self.running = False
        self._started = False
        self._justStopped = False
        self._startedBefore = False
        # reactor internal readers, e.g. the waker.
        # Using Any as the type here… unable to find a suitable defined interface
        self._internalReaders: Set[Any] = set()
        self.waker: Any = 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) -> None:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement installWaker")

    def wakeUp(self) -> None:
        """
        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: Optional[float]) -> None:
        """
        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: IReadDescriptor) -> None:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement addReader")

    def addWriter(self, writer: IWriteDescriptor) -> None:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement addWriter")

    def removeReader(self, reader: IReadDescriptor) -> None:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement removeReader")

    def removeWriter(self, writer: IWriteDescriptor) -> None:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement removeWriter")

    def removeAll(self) -> List[Union[IReadDescriptor, IWriteDescriptor]]:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement removeAll")

    def getReaders(self) -> List[IReadDescriptor]:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement getReaders")

    def getWriters(self) -> List[IWriteDescriptor]:
        raise NotImplementedError(
            reflect.qual(self.__class__) + " did not implement getWriters")

    # IReactorCore
    def resolve(
        self, name: str,
        timeout: Sequence[int] = (1, 3, 11, 45)) -> Deferred[str]:
        """
        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)

    def stop(self) -> None:
        """
        See 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
        self._startedBefore = True

    def crash(self) -> None:
        """
        See 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, number: int, frame: Optional[FrameType] = None) -> None:
        """
        Handle a SIGINT interrupt.

        @param number: See handler specification in L{signal.signal}
        @param frame: See handler specification in L{signal.signal}
        """
        log.msg("Received SIGINT, shutting down.")
        self.callFromThread(self.stop)
        self._exitSignal = number

    def sigBreak(self, number: int, frame: Optional[FrameType] = None) -> None:
        """
        Handle a SIGBREAK interrupt.

        @param number: See handler specification in L{signal.signal}
        @param frame: See handler specification in L{signal.signal}
        """
        log.msg("Received SIGBREAK, shutting down.")
        self.callFromThread(self.stop)
        self._exitSignal = number

    def sigTerm(self, number: int, frame: Optional[FrameType] = None) -> None:
        """
        Handle a SIGTERM interrupt.

        @param number: See handler specification in L{signal.signal}
        @param frame: See handler specification in L{signal.signal}
        """
        log.msg("Received SIGTERM, shutting down.")
        self.callFromThread(self.stop)
        self._exitSignal = number

    def disconnectAll(self) -> None:
        """Disconnect every reader, and writer in the system."""
        selectables = self.removeAll()
        for reader in selectables:
            log.callWithLogger(reader, reader.connectionLost,
                               Failure(main.CONNECTION_LOST))

    def iterate(self, delay: float = 0.0) -> None:
        """
        See twisted.internet.interfaces.IReactorCore.iterate.
        """
        self.runUntilCurrent()
        self.doIteration(delay)

    def fireSystemEvent(self, eventType: str) -> None:
        """
        See twisted.internet.interfaces.IReactorCore.fireSystemEvent.
        """
        event = self._eventTriggers.get(eventType)
        if event is not None:
            event.fireEvent()

    def addSystemEventTrigger(
        self,
        phase: str,
        eventType: str,
        callable: Callable[..., Any],
        *args: object,
        **kwargs: object,
    ) -> _SystemEventID:
        """
        See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
        """
        assert builtins.callable(callable), f"{callable} is not callable"
        if eventType not in self._eventTriggers:
            self._eventTriggers[eventType] = _ThreePhaseEvent()
        return _SystemEventID((
            eventType,
            self._eventTriggers[eventType].addTrigger(phase, callable, *args,
                                                      **kwargs),
        ))

    def removeSystemEventTrigger(self, triggerID: _SystemEventID) -> None:
        """
        See twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
        """
        eventType, handle = triggerID
        self._eventTriggers[eventType].removeTrigger(handle)

    def callWhenRunning(self, callable: Callable[..., Any], *args: object,
                        **kwargs: object) -> Optional[_SystemEventID]:
        """
        See twisted.internet.interfaces.IReactorCore.callWhenRunning.
        """
        if self.running:
            callable(*args, **kwargs)
            return None
        else:
            return self.addSystemEventTrigger("after", "startup", callable,
                                              *args, **kwargs)

    def startRunning(self) -> None:
        """
        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()
        if self._startedBefore:
            raise error.ReactorNotRestartable()
        self._started = True
        self._stopped = False
        if self._registerAsIOThread:
            threadable.registerAsIOThread()
        self.fireSystemEvent("startup")

    def _reallyStartRunning(self) -> None:
        """
        Method called to transition to the running state.  This should happen
        in the I{during startup} event trigger phase.
        """
        self.running = True

    def run(self) -> None:
        # IReactorCore.run
        raise NotImplementedError()

    # IReactorTime

    seconds = staticmethod(runtimeSeconds)

    def callLater(self, delay: float, callable: Callable[..., Any],
                  *args: object, **kw: object) -> DelayedCall:
        """
        See twisted.internet.interfaces.IReactorTime.callLater.
        """
        assert builtins.callable(callable), f"{callable} is not callable"
        assert delay >= 0, f"{delay} is not greater than or equal to 0 seconds"
        delayedCall = DelayedCall(
            self.seconds() + delay,
            callable,
            args,
            kw,
            self._cancelCallLater,
            self._moveCallLaterSooner,
            seconds=self.seconds,
        )
        self._newTimedCalls.append(delayedCall)
        return delayedCall

    def _moveCallLaterSooner(self, delayedCall: DelayedCall) -> None:
        # Linear time find: slow.
        heap = self._pendingTimedCalls
        try:
            pos = heap.index(delayedCall)

            # 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, delayedCall: DelayedCall) -> None:
        self._cancellations += 1

    def getDelayedCalls(self) -> Sequence[IDelayedCall]:
        """
        See L{twisted.internet.interfaces.IReactorTime.getDelayedCalls}
        """
        return [
            x for x in (self._pendingTimedCalls + self._newTimedCalls)
            if not x.cancelled
        ]

    def _insertNewDelayedCalls(self) -> None:
        for call in self._newTimedCalls:
            if call.cancelled:
                self._cancellations -= 1
            else:
                call.activate_delay()
                heappush(self._pendingTimedCalls, call)
        self._newTimedCalls = []

    def timeout(self) -> Optional[float]:
        """
        Determine the longest time the reactor may sleep (waiting on I/O
        notification, perhaps) before it must wake up to service a time-related
        event.

        @return: The maximum number of seconds the reactor may sleep.
        """
        # insert new delayed calls to make sure to include them in timeout value
        self._insertNewDelayedCalls()

        if not self._pendingTimedCalls:
            return None

        delay = self._pendingTimedCalls[0].time - cast(float, self.seconds())

        # Pick a somewhat arbitrary maximum possible value for the timeout.
        # This value is 2 ** 31 / 1000, which is the number of seconds which can
        # be represented as an integer number of milliseconds in a signed 32 bit
        # integer.  This particular limit is imposed by the epoll_wait(3)
        # interface which accepts a timeout as a C "int" type and treats it as
        # representing a number of milliseconds.
        longest = 2147483

        # Don't let the delay be in the past (negative) or exceed a plausible
        # maximum (platform-imposed) interval.
        return max(0, min(longest, delay))

    def runUntilCurrent(self) -> None:
        """
        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 BaseException:
                    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.0:
                call.activate_delay()
                heappush(self._pendingTimedCalls, call)
                continue

            try:
                call.called = 1
                call.func(*call.args, **call.kw)
            except BaseException:
                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")

    # IReactorThreads
    if platform.supportsThreads():
        assert ThreadPool is not None

        threadpool = None
        # ID of the trigger starting the threadpool
        _threadpoolStartupID = None
        # ID of the trigger stopping the threadpool
        threadpoolShutdownID = None

        def _initThreads(self) -> None:
            self.installNameResolver(_GAIResolver(self, self.getThreadPool))
            self.usingThreads = True

        # `IReactorFromThreads` defines the first named argument as
        # `callable: Callable[..., Any]` but this defines it as `f`
        # really both should be defined using py3.8 positional only
        def callFromThread(  # type: ignore[override]
                self, f: Callable[..., Any], *args: object,
                **kwargs: object) -> None:
            """
            See
            L{twisted.internet.interfaces.IReactorFromThreads.callFromThread}.
            """
            assert callable(f), f"{f} is not callable"
            # 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, kwargs))
            self.wakeUp()

        def _initThreadPool(self) -> None:
            """
            Create the threadpool accessible with callFromThread.
            """
            self.threadpool = ThreadPool(0, 10, "twisted.internet.reactor")
            self._threadpoolStartupID = self.callWhenRunning(
                self.threadpool.start)
            self.threadpoolShutdownID = self.addSystemEventTrigger(
                "during", "shutdown", self._stopThreadPool)

        def _uninstallHandler(self) -> None:
            pass

        def _stopThreadPool(self) -> None:
            """
            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
            assert self.threadpool is not None
            self.threadpool.stop()
            self.threadpool = None

        def getThreadPool(self) -> ThreadPool:
            """
            See L{twisted.internet.interfaces.IReactorThreads.getThreadPool}.
            """
            if self.threadpool is None:
                self._initThreadPool()
                assert self.threadpool is not None
            return self.threadpool

        # `IReactorInThreads` defines the first named argument as
        # `callable: Callable[..., Any]` but this defines it as `_callable`
        # really both should be defined using py3.8 positional only
        def callInThread(  # type: ignore[override]
                self, _callable: Callable[..., Any], *args: object,
                **kwargs: object) -> None:
            """
            See L{twisted.internet.interfaces.IReactorInThreads.callInThread}.
            """
            self.getThreadPool().callInThread(_callable, *args, **kwargs)

        def suggestThreadPoolSize(self, size: int) -> None:
            """
            See L{twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}.
            """
            self.getThreadPool().adjustPoolsize(maxthreads=size)

    else:
        # This is for signal handlers.
        def callFromThread(self, f: Callable[..., Any], *args: object,
                           **kwargs: object) -> None:
            assert callable(f), f"{f} is not callable"
            # See comment in the other callFromThread implementation.
            self.threadCallQueue.append((f, args, kwargs))