Python twisted.internet.reactor.addSystemEventTrigger() Examples

The following are 30 code examples of twisted.internet.reactor.addSystemEventTrigger(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.reactor , or try the search function .
Example #1
Source File: server.py    From worker with GNU General Public License v3.0 7 votes vote down vote up
def run():

    config.read()
    logs.api()

    top_service = service.MultiService()

    db = Db()
    datalib.db = db
    db.setServiceParent(top_service)

    http_service = internet.TCPServer(config.HTTP_PORT, Site(db), interface=config.HTTP_ADDR)
    http_service.setServiceParent(top_service)

    top_service.startService()

    reactor.addSystemEventTrigger('before', 'shutdown', top_service.stopService)

    reactor.run() 
Example #2
Source File: nfqueue.py    From packet-queue with Apache License 2.0 7 votes vote down vote up
def configure(protocol, port, pipes, interface):
  remove_all()
  reactor.addSystemEventTrigger('after', 'shutdown', remove_all)

  # gets default (outward-facing) network interface (e.g. deciding which of
  # eth0, eth1, wlan0 is being used by the system to connect to the internet)
  if interface == "auto":
    interface = netifaces.gateways()['default'][netifaces.AF_INET][1]
  else:
    if interface not in netifaces.interfaces():
      raise ValueError("Given interface does not exist.", interface)

  add(protocol, port, interface)
  manager = libnetfilter_queue.Manager()

  manager.bind(UP_QUEUE, packet_handler(manager, pipes.up))
  manager.bind(DOWN_QUEUE, packet_handler(manager, pipes.down))

  reader = abstract.FileDescriptor()
  reader.doRead = manager.process
  reader.fileno = lambda: manager.fileno
  reactor.addReader(reader) 
Example #3
Source File: test_task.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_singleStopErrback(self):
        """
        L{task.react} doesn't try to stop the reactor if the L{defer.Deferred}
        the function it is passed is errbacked after the reactor has already
        been stopped.
        """
        class ExpectedException(Exception):
            pass

        def main(reactor):
            reactor.callLater(1, reactor.stop)
            finished = defer.Deferred()
            reactor.addSystemEventTrigger(
                'during', 'shutdown', finished.errback, ExpectedException())
            return finished
        r = _FakeReactor()
        exitError = self.assertRaises(
            SystemExit, task.react, main, _reactor=r)

        self.assertEqual(1, exitError.code)

        self.assertEqual(r.seconds(), 1)
        errors = self.flushLoggedErrors(ExpectedException)
        self.assertEqual(len(errors), 1) 
Example #4
Source File: test_internet.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_duringPreceedsAfter(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'during'} phase before it calls triggers added to the C{'after'}
        phase.
        """
        eventType = 'test'
        events = []
        def duringTrigger():
            events.append('during')
        def afterTrigger():
            events.append('after')
        self.addTrigger('during', eventType, duringTrigger)
        self.addTrigger('after', eventType, afterTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['during', 'after']) 
Example #5
Source File: paho.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def connect_with_retry(self):
        try:
            self.client.connect(self.broker_host, port=self.broker_port, keepalive=60)
            self.connect_loop.stop()
        except:
            log.failure(u'Error connecting to MQTT broker but retrying each {retry_interval} seconds',
                retry_interval=self.retry_interval)
            return

        """
        This is part of the threaded client interface. Call this once to
        start a new thread to process network traffic. This provides an
        alternative to repeatedly calling loop() yourself.
        """
        self.client.loop_start()
        reactor.addSystemEventTrigger('before', 'shutdown', self.client.loop_stop, True)

    # The callback for when the client receives a CONNACK response from the server. 
Example #6
Source File: test_internet.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_beforePreceedsDuring(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'before'} phase before it calls triggers added to the C{'during'}
        phase.
        """
        eventType = 'test'
        events = []
        def beforeTrigger():
            events.append('before')
        def duringTrigger():
            events.append('during')
        self.addTrigger('before', eventType, beforeTrigger)
        self.addTrigger('during', eventType, duringTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['before', 'during']) 
Example #7
Source File: server.py    From worker with GNU General Public License v3.0 6 votes vote down vote up
def run():

    config.read()
    logs.checker_master()

    if config.ARGS.t:
        check(config.ARGS.t)
        return

    top_service = TopService()

    db = Db()
    datalib.db = db
    db.setServiceParent(top_service)

    sub_service = MasterService(db)
    sub_service.setServiceParent(top_service)

    top_service.startService()

    reactor.addSystemEventTrigger('before', 'shutdown', top_service.stopService)

    reactor.run() 
Example #8
Source File: worker.py    From worker with GNU General Public License v3.0 6 votes vote down vote up
def main(number):

    def get_metrics():
        return [
            ("checker.time.%s.%s" %
             (config.HOSTNAME,
              number),
                spy.TRIGGER_CHECK.get_metrics()["sum"]),
            ("checker.triggers.%s.%s" %
             (config.HOSTNAME,
              number),
                spy.TRIGGER_CHECK.get_metrics()["count"]),
            ("checker.errors.%s.%s" %
             (config.HOSTNAME,
              number),
                spy.TRIGGER_CHECK_ERRORS.get_metrics()["count"])]

    graphite.sending(get_metrics)

    def start(db):
        checker = TriggersCheck(db)
        checker.start()
        reactor.addSystemEventTrigger('before', 'shutdown', checker.stop)

    run(start) 
Example #9
Source File: app.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def run(self, save=1, installSignalHandlers=1):
        """run(save=1, installSignalHandlers=1)
        Run this application, running the main loop if necessary.
        If 'save' is true, then when this Application is shut down, it
        will be persisted to a pickle.
        'installSignalHandlers' is passed through to reactor.run(), the
        function that starts the mainloop.
        """
        from twisted.internet import reactor
        if not self._boundPorts:
            self.bindPorts()
        self._save = save
        reactor.addSystemEventTrigger('before', 'shutdown', self._beforeShutDown)
        reactor.addSystemEventTrigger('after', 'shutdown', self._afterShutDown)
        global theApplication
        theApplication = self
        log.callWithLogger(self, reactor.run, installSignalHandlers=installSignalHandlers)


#
# These are dummy classes for backwards-compatibility!
# 
Example #10
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_singleStopErrback(self):
        """
        L{task.react} doesn't try to stop the reactor if the L{defer.Deferred}
        the function it is passed is errbacked after the reactor has already
        been stopped.
        """
        class ExpectedException(Exception):
            pass

        def main(reactor):
            reactor.callLater(1, reactor.stop)
            finished = defer.Deferred()
            reactor.addSystemEventTrigger(
                'during', 'shutdown', finished.errback, ExpectedException())
            return finished
        r = _FakeReactor()
        exitError = self.assertRaises(
            SystemExit, task.react, main, _reactor=r)

        self.assertEqual(1, exitError.code)

        self.assertEqual(r.seconds(), 1)
        errors = self.flushLoggedErrors(ExpectedException)
        self.assertEqual(len(errors), 1) 
Example #11
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_beforePreceedsDuring(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'before'} phase before it calls triggers added to the C{'during'}
        phase.
        """
        eventType = 'test'
        events = []
        def beforeTrigger():
            events.append('before')
        def duringTrigger():
            events.append('during')
        self.addTrigger('before', eventType, beforeTrigger)
        self.addTrigger('during', eventType, duringTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['before', 'during']) 
Example #12
Source File: gpio.py    From python-sysfs-gpio with MIT License 6 votes vote down vote up
def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            instance = super(Controller, cls).__new__(cls)
            instance._allocated_pins = {}
            instance._poll_queue = select.epoll()

            instance._available_pins = []
            instance._running = True

            # Cleanup before stopping reactor
            reactor.addSystemEventTrigger('before', 'shutdown', instance.stop)

            # Run the EPoll in a Thread, as it blocks.
            reactor.callInThread(instance._poll_queue_loop)

            cls._instance = instance
        return cls._instance 
Example #13
Source File: test_internet.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_removeNonExistentSystemEventTrigger(self):
        """
        Passing an object to L{IReactorCore.removeSystemEventTrigger} which was
        not returned by a previous call to
        L{IReactorCore.addSystemEventTrigger} or which has already been passed
        to C{removeSystemEventTrigger} should result in L{TypeError},
        L{KeyError}, or L{ValueError} being raised.
        """
        b = self.addTrigger('during', 'test', lambda: None)
        self.removeTrigger(b)
        self.assertRaises(
            TypeError, reactor.removeSystemEventTrigger, None)
        self.assertRaises(
            ValueError, reactor.removeSystemEventTrigger, b)
        self.assertRaises(
            KeyError,
            reactor.removeSystemEventTrigger,
            (b[0], ('xxx',) + b[1][1:])) 
Example #14
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_removeNonExistentSystemEventTrigger(self):
        """
        Passing an object to L{IReactorCore.removeSystemEventTrigger} which was
        not returned by a previous call to
        L{IReactorCore.addSystemEventTrigger} or which has already been passed
        to C{removeSystemEventTrigger} should result in L{TypeError},
        L{KeyError}, or L{ValueError} being raised.
        """
        b = self.addTrigger('during', 'test', lambda: None)
        self.removeTrigger(b)
        self.assertRaises(
            TypeError, reactor.removeSystemEventTrigger, None)
        self.assertRaises(
            ValueError, reactor.removeSystemEventTrigger, b)
        self.assertRaises(
            KeyError,
            reactor.removeSystemEventTrigger,
            (b[0], ('xxx',) + b[1][1:])) 
Example #15
Source File: test_internet.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_duringPreceedsAfter(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'during'} phase before it calls triggers added to the C{'after'}
        phase.
        """
        eventType = 'test'
        events = []
        def duringTrigger():
            events.append('during')
        def afterTrigger():
            events.append('after')
        self.addTrigger('during', eventType, duringTrigger)
        self.addTrigger('after', eventType, afterTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['during', 'after']) 
Example #16
Source File: crawler.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def start(self, stop_after_crawl=True):
        """
        This method starts a Twisted `reactor`_, adjusts its pool size to
        :setting:`REACTOR_THREADPOOL_MAXSIZE`, and installs a DNS cache based
        on :setting:`DNSCACHE_ENABLED` and :setting:`DNSCACHE_SIZE`.

        If ``stop_after_crawl`` is True, the reactor will be stopped after all
        crawlers have finished, using :meth:`join`.

        :param boolean stop_after_crawl: stop or not the reactor when all
            crawlers have finished
        """
        if stop_after_crawl:
            d = self.join()
            # Don't start the reactor if the deferreds are already fired
            if d.called:
                return
            d.addBoth(self._stop_reactor)

        reactor.installResolver(self._get_dns_resolver())
        tp = reactor.getThreadPool()
        tp.adjustPoolsize(maxthreads=self.settings.getint('REACTOR_THREADPOOL_MAXSIZE'))
        reactor.addSystemEventTrigger('before', 'shutdown', self.stop)
        reactor.run(installSignalHandlers=False)  # blocking call 
Example #17
Source File: test_internet.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_beforePreceedsDuring(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'before'} phase before it calls triggers added to the C{'during'}
        phase.
        """
        eventType = 'test'
        events = []
        def beforeTrigger():
            events.append('before')
        def duringTrigger():
            events.append('during')
        self.addTrigger('before', eventType, beforeTrigger)
        self.addTrigger('during', eventType, duringTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['before', 'during']) 
Example #18
Source File: nexus.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def __init__(self, stealStdio=True, printToConsole=True):
        '''
        The one big thing this function leaves out is reactor.start(). Call this externally
        *after * initializing a nexus object.
        '''
        self.session = None
        self.wamp_connected = False
        self.jwt_valid = False

        self.info = AttrWrapper()
        resolveInfo(self, settings.CONFIG_FILE)
        self.info.setOnChange(self.onInfoChange)

        # initialize output. If filepath is set, logs to file.
        # If stealStdio is set intercepts all stderr and stdout and interprets it internally
        # If printToConsole is set (defaults True) all final output is rendered to stdout
        output.out.startLogging(filePath=settings.LOG_DIR, stealStdio=stealStdio, printToConsole=printToConsole)

        # register onStop for the shutdown call
        reactor.addSystemEventTrigger('before', 'shutdown', self.onStop)

        # The reactor needs to be runnnig before this call is fired, since we start the session
        # here. Assuming callLater doesn't fire until thats happened
        reactor.callLater(0, self.onStart) 
Example #19
Source File: test_task.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_singleStopCallback(self):
        """
        L{task.react} doesn't try to stop the reactor if the L{defer.Deferred}
        the function it is passed is called back after the reactor has already
        been stopped.
        """
        def main(reactor):
            reactor.callLater(1, reactor.stop)
            finished = defer.Deferred()
            reactor.addSystemEventTrigger(
                'during', 'shutdown', finished.callback, None)
            return finished
        r = _FakeReactor()
        exitError = self.assertRaises(
            SystemExit, task.react, main, _reactor=r)
        self.assertEqual(r.seconds(), 1)

        self.assertEqual(0, exitError.code) 
Example #20
Source File: test_internet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_duringPreceedsAfter(self):
        """
        L{IReactorCore.addSystemEventTrigger} should call triggers added to the
        C{'during'} phase before it calls triggers added to the C{'after'}
        phase.
        """
        eventType = 'test'
        events = []
        def duringTrigger():
            events.append('during')
        def afterTrigger():
            events.append('after')
        self.addTrigger('during', eventType, duringTrigger)
        self.addTrigger('after', eventType, afterTrigger)
        self.assertEqual(events, [])
        reactor.fireSystemEvent(eventType)
        self.assertEqual(events, ['during', 'after']) 
Example #21
Source File: savemap.py    From piqueserver with GNU General Public License v3.0 5 votes vote down vote up
def apply_script(protocol, connection, config):
    class SaveMapProtocol(protocol):
        def __init__(self, *arg, **kw):
            protocol.__init__(self, *arg, **kw)
            def call():
                if savemap_config.option('save_at_shutdown', False).get():
                    self.save_map()
            reactor.addSystemEventTrigger('before', 'shutdown', call)

        async def set_map_name(self, rot_info: RotationInfo) -> None:
            if savemap_config.option('load_saved_map', False).get():
                if os.path.isfile(get_path(rot_info.name)):
                    log.info("Saved version of '%s' found" % rot_info.name)
                    rot_info.name += '.saved'
            await protocol.set_map_name(self, rot_info)

        def save_map(self, custom_name=None):
            if custom_name:
                path = os.path.join(config_dir, 'maps', custom_name) + '.vxl'
            else:
                path = get_path(self.map_info.rot_info.name)
            with open(path, 'wb') as f:
                f.write(self.map.generate())
            log.info("Map saved to '{path}'", path=path)
            return path

    return SaveMapProtocol, connection 
Example #22
Source File: bottle.py    From slack-machine with MIT License 5 votes vote down vote up
def run(self, handler):
        from twisted.web import server, wsgi
        from twisted.python.threadpool import ThreadPool
        from twisted.internet import reactor
        thread_pool = ThreadPool()
        thread_pool.start()
        reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
        factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
        reactor.listenTCP(self.port, factory, interface=self.host)
        if not reactor.running:
            reactor.run() 
Example #23
Source File: test_internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_afterPhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should accept the C{'after'}
        phase and not call the given object until the right event is fired.
        """
        self._addSystemEventTriggerTest('after') 
Example #24
Source File: test_internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_beforePhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should accept the C{'before'}
        phase and not call the given object until the right event is fired.
        """
        self._addSystemEventTriggerTest('before') 
Example #25
Source File: test_internet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_unknownPhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should reject phases other than
        C{'before'}, C{'during'}, or C{'after'}.
        """
        eventType = 'test'
        self.assertRaises(
            KeyError, self.addTrigger, 'xxx', eventType, lambda: None) 
Example #26
Source File: test_internet.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_unknownPhase(self):
        """
        L{IReactorCore.addSystemEventTrigger} should reject phases other than
        C{'before'}, C{'during'}, or C{'after'}.
        """
        eventType = 'test'
        self.assertRaises(
            KeyError, self.addTrigger, 'xxx', eventType, lambda: None) 
Example #27
Source File: bottle.py    From teye_scanner_for_book with GNU General Public License v3.0 5 votes vote down vote up
def run(self, handler):
        from twisted.web import server, wsgi
        from twisted.python.threadpool import ThreadPool
        from twisted.internet import reactor
        thread_pool = ThreadPool()
        thread_pool.start()
        reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
        factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
        reactor.listenTCP(self.port, factory, interface=self.host)
        reactor.run() 
Example #28
Source File: util.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def childStore(self):
        """
        Create a store suitable for use in a child process, that is hooked up
        to the store that a parent test process is managing.
        """
        disableMemcacheForTest(TestCase())
        staticQuota = 3000
        attachmentRoot = (FilePath(self.sharedDBPath).child("attachments"))
        stubsvc = self.createService(lambda cf: Service())

        cp = ConnectionPool(
            stubsvc.produceConnection,
            maxConnections=1,
            dbtype=DatabaseType(DB_TYPE[0], DB_TYPE[1]),
        )
        # Attach the service to the running reactor.
        cp.startService()
        reactor.addSystemEventTrigger("before", "shutdown", cp.stopService)
        cds = CommonDataStore(
            cp.connection,
            {"push": StubNotifierFactory(), },
            None,
            attachmentRoot, "",
            quota=staticQuota
        )
        return cds 
Example #29
Source File: memcachepool.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def __init__(self, endpoint, maxClients=5, reactor=None):
        """
        @param endpoint: An L{IStreamClientEndpoint} indicating the server to
            connect to.

        @param maxClients: A C{int} indicating the maximum number of clients.

        @param reactor: An L{IReactorTCP} provider used to initiate new
            connections.
        """
        self._endpoint = endpoint
        self._maxClients = maxClients

        if reactor is None:
            from twisted.internet import reactor
        self._reactor = reactor

        self.shutdown_deferred = None
        self.shutdown_requested = False
        reactor.addSystemEventTrigger(
            'before', 'shutdown', self._shutdownCallback
        )

        self._busyClients = set([])
        self._freeClients = set([])
        self._pendingConnects = 0
        self._commands = [] 
Example #30
Source File: pool.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def __init__(self, name, scheme, endpoint, secureEndpoint,
                 maxClients=5, reactor=None):
        """
        @param endpoint: An L{IStreamClientEndpoint} indicating the server to
            connect to.

        @param maxClients: A C{int} indicating the maximum number of clients.

        @param reactor: An L{IReactorTCP} provider used to initiate new
            connections.
        """

        self._name = name
        self._scheme = scheme
        self._endpoint = endpoint
        self._secureEndpoint = secureEndpoint
        self._maxClients = maxClients

        if reactor is None:
            from twisted.internet import reactor
        self._reactor = reactor

        self.shutdown_deferred = None
        self.shutdown_requested = False
        reactor.addSystemEventTrigger('before', 'shutdown', self._shutdownCallback)

        self._busyClients = set([])
        self._freeClients = set([])
        self._pendingConnects = 0
        self._pendingRequests = []