Python twisted.internet.reactor.callWhenRunning() Examples

The following are 30 code examples of twisted.internet.reactor.callWhenRunning(). 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: test_coinswap.py    From CoinSwapCS with GNU General Public License v3.0 6 votes vote down vote up
def runcase(alice_class, carol_class, fail_alice_state=None, fail_carol_state=None):
    options_server = Options()
    wallets = make_wallets(num_alices + 1,
                               wallet_structures=wallet_structures,
                               mean_amt=funding_amount)
    args_server = ["dummy"]
    test_data_server = (wallets[num_alices]['seed'], args_server, options_server,
                        False, None, carol_class, None, fail_carol_state)
    carol_bbmb = main_cs(test_data_server)
    options_alice = Options()
    options_alice.serve = False
    alices = []
    for i in range(num_alices):
        args_alice = ["dummy", amounts[i]]
        if dest_addr:
            args_alice.append(dest_addr)
        test_data_alice = (wallets[i]['seed'], args_alice, options_alice, False,
                           alice_class, None, fail_alice_state, None)
        alices.append(main_cs(test_data_alice))
    l = task.LoopingCall(miner)
    reactor.callWhenRunning(start_mining, l)
    reactor.run()
    return (alices, carol_bbmb, wallets[num_alices]['wallet']) 
Example #2
Source File: test_task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_synchronousStop(self):
        """
        L{task.react} handles when the reactor is stopped just before the
        returned L{Deferred} fires.
        """
        def main(reactor):
            d = defer.Deferred()
            def stop():
                reactor.stop()
                d.callback(None)
            reactor.callWhenRunning(stop)
            return d
        r = _FakeReactor()
        exitError = self.assertRaises(
            SystemExit, task.react, main, [], _reactor=r)
        self.assertEqual(0, exitError.code) 
Example #3
Source File: test_task.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_synchronousStop(self):
        """
        L{task.react} handles when the reactor is stopped just before the
        returned L{Deferred} fires.
        """
        def main(reactor):
            d = defer.Deferred()
            def stop():
                reactor.stop()
                d.callback(None)
            reactor.callWhenRunning(stop)
            return d
        r = _FakeReactor()
        exitError = self.assertRaises(
            SystemExit, task.react, main, [], _reactor=r)
        self.assertEqual(0, exitError.code) 
Example #4
Source File: threads.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def install_database_unpool(maxthreads=max_threads_for_database_pool):
    """Install a pool for database activity particularly suited to testing.

    See `make_database_unpool` for details.
    """
    try:
        reactor.threadpoolForDatabase
    except AttributeError:
        reactor.threadpoolForDatabase = make_database_unpool(maxthreads)
        reactor.callInDatabase = reactor.threadpoolForDatabase.callInThread
        reactor.callWhenRunning(reactor.threadpoolForDatabase.start)
        reactor.addSystemEventTrigger(
            "during", "shutdown", reactor.threadpoolForDatabase.stop
        )
    else:
        raise AssertionError(
            "Too late; database thread-pool has already "
            "been configured and installed."
        ) 
Example #5
Source File: threads.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def install_database_pool(maxthreads=max_threads_for_database_pool):
    """Install a pool for database activity."""
    if getattr(reactor, "threadpoolForDatabase", None) is None:
        # Start with ZERO threads to avoid pulling in all of Django's
        # configuration straight away; it may not be ready yet.
        reactor.threadpoolForDatabase = make_database_pool(maxthreads)
        reactor.callInDatabase = reactor.threadpoolForDatabase.callInThread
        reactor.callWhenRunning(reactor.threadpoolForDatabase.start)
        reactor.addSystemEventTrigger(
            "during", "shutdown", reactor.threadpoolForDatabase.stop
        )
    else:
        raise AssertionError(
            "Too late; database thread-pool has already "
            "been configured and installed."
        ) 
Example #6
Source File: threads.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def install_default_pool(maxthreads=max_threads_for_default_pool):
    """Install a custom pool as Twisted's global/reactor thread-pool.

    Disallow all database activity in the reactor thread-pool. Why such a
    strict policy? We've been following Django's model, where threads and
    database connections are wedded together. In MAAS this limits concurrency,
    contributes to crashes and deadlocks, and has spawned workarounds like
    post-commit hooks. From here on, using a database connection requires the
    use of a specific, separate, carefully-sized, thread-pool.
    """
    if reactor.threadpool is None:
        # Start with ZERO threads to avoid pulling in all of Django's
        # configuration straight away; it may not be ready yet.
        reactor.threadpool = make_default_pool(maxthreads)
        reactor.callWhenRunning(reactor.threadpool.start)
        reactor.addSystemEventTrigger(
            "during", "shutdown", reactor.threadpool.stop
        )
    else:
        raise AssertionError(
            "Too late; global/reactor thread-pool has "
            "already been configured and installed."
        ) 
Example #7
Source File: test_reporter.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def test_run_apt_update_report_timestamp(self):
        """
        The package-report-result message includes a timestamp of the apt
        update run.
        """
        message_store = self.broker_service.message_store
        message_store.set_accepted_types(["package-reporter-result"])
        self._make_fake_apt_update(err="")
        deferred = Deferred()

        def do_test():
            self.reactor.advance(10)
            result = self.reporter.run_apt_update()

            def callback(ignore):
                self.assertMessages(
                    message_store.get_pending_messages(),
                    [{"type": "package-reporter-result",
                      "report-timestamp": 10.0, "code": 0, "err": u""}])
            result.addCallback(callback)
            self.reactor.advance(0)
            result.chainDeferred(deferred)

        reactor.callWhenRunning(do_test)
        return deferred 
Example #8
Source File: test_reporter.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def test_run_apt_update_report_apt_failure(self):
        """
        If L{PackageReporter.run_apt_update} fails, a message is sent to the
        server reporting the error, to be able to fix the problem centrally.
        """
        message_store = self.broker_service.message_store
        message_store.set_accepted_types(["package-reporter-result"])
        self._make_fake_apt_update(code=2)
        deferred = Deferred()

        def do_test():
            result = self.reporter.run_apt_update()

            def callback(ignore):
                self.assertMessages(
                    message_store.get_pending_messages(),
                    [{"type": "package-reporter-result",
                      "report-timestamp": 0.0, "code": 2, "err": u"error"}])
            result.addCallback(callback)
            self.reactor.advance(0)
            result.chainDeferred(deferred)

        reactor.callWhenRunning(do_test)
        return deferred 
Example #9
Source File: create_users.py    From pixelated-user-agent with GNU Affero General Public License v3.0 6 votes vote down vote up
def run():
    args = _parse_args()

    def show_error(err):
        print "ERROR: %s" % err.getErrorMessage()

    def shut_down(_):
        reactor.stop()

    def _run():
        d = mass_register(args.number, args.invite_code, args.provider)
        d.addErrback(show_error)
        d.addBoth(shut_down)

    reactor.callWhenRunning(_run)
    reactor.run() 
Example #10
Source File: test_reporter.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def test_run_apt_update_touches_stamp_file(self):
        """
        The L{PackageReporter.run_apt_update} method touches a stamp file
        after running the apt-update wrapper.
        """
        self.reporter.sources_list_filename = "/I/Dont/Exist"
        self._make_fake_apt_update()
        deferred = Deferred()

        def do_test():
            result = self.reporter.run_apt_update()

            def callback(ignored):
                self.assertTrue(
                    os.path.exists(self.config.update_stamp_filename))
            result.addCallback(callback)
            self.reactor.advance(0)
            result.chainDeferred(deferred)

        reactor.callWhenRunning(do_test)
        return deferred 
Example #11
Source File: register.py    From pixelated-user-agent with GNU Affero General Public License v3.0 6 votes vote down vote up
def initialize():
    logger_config.init(debug=False)
    args = arguments.parse_register_args()
    leap_provider = _set_leap_provider(args)

    def show_error(err):
        logger.info('error: %s' % err)

    def shut_down(_):
        reactor.stop()

    def _register():
        d = register(
            args.username,
            args.password,
            leap_provider,
            args.invite_code)
        d.addErrback(show_error)
        d.addBoth(shut_down)

    reactor.callWhenRunning(_register)
    reactor.run() 
Example #12
Source File: maintenance.py    From pixelated-user-agent with GNU Affero General Public License v3.0 6 votes vote down vote up
def initialize():
    args = arguments.parse_maintenance_args()

    logger.init(debug=args.debug)

    @defer.inlineCallbacks
    def _run():
        leap_session = yield initialize_leap_single_user(
            args.leap_provider_cert,
            args.leap_provider_cert_fingerprint,
            args.credentials_file,
            leap_home=args.leap_home)

        execute_command(args, leap_session)

    reactor.callWhenRunning(_run)
    reactor.run() 
Example #13
Source File: plugin.py    From dvol with Apache License 2.0 6 votes vote down vote up
def main():
    plugins_dir = FilePath("/run/docker/plugins/")
    if not plugins_dir.exists():
        plugins_dir.makedirs()

    dvol_path = FilePath("/var/lib/dvol/volumes")
    if not dvol_path.exists():
        dvol_path.makedirs()
    voluminous = Voluminous(dvol_path.path)

    sock = plugins_dir.child("%s.sock" % (VOLUME_DRIVER_NAME,))
    if sock.exists():
        sock.remove()

    adapterServer = internet.UNIXServer(
            sock.path, getAdapter(voluminous))
    reactor.callWhenRunning(adapterServer.startService)
    reactor.run() 
Example #14
Source File: test_reporter.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def test_run_apt_update_report_apt_failure_no_sources(self):
        """
        If L{PackageReporter.run_apt_update} fails and there are no
        APT sources configured, the APT error takes precedence.
        """
        self.facade.reset_channels()
        message_store = self.broker_service.message_store
        message_store.set_accepted_types(["package-reporter-result"])
        self._make_fake_apt_update(code=2)
        deferred = Deferred()

        def do_test():
            result = self.reporter.run_apt_update()

            def callback(ignore):
                self.assertMessages(
                    message_store.get_pending_messages(),
                    [{"type": "package-reporter-result",
                      "report-timestamp": 0.0, "code": 2, "err": u"error"}])
            result.addCallback(callback)
            self.reactor.advance(0)
            result.chainDeferred(deferred)

        reactor.callWhenRunning(do_test)
        return deferred 
Example #15
Source File: test_deferredruntest.py    From pth-toolkit with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_fast_keyboard_interrupt_stops_test_run(self):
        # If we get a SIGINT during a test run, the test stops and no more
        # tests run.
        SIGINT = getattr(signal, 'SIGINT', None)
        if not SIGINT:
            raise self.skipTest("SIGINT unavailable")
        class SomeCase(TestCase):
            def test_pause(self):
                return defer.Deferred()
        test = SomeCase('test_pause')
        reactor = self.make_reactor()
        timeout = self.make_timeout()
        runner = self.make_runner(test, timeout * 5)
        result = self.make_result()
        reactor.callWhenRunning(os.kill, os.getpid(), SIGINT)
        self.assertThat(lambda:runner.run(result),
            Raises(MatchesException(KeyboardInterrupt))) 
Example #16
Source File: monast.py    From monast with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _processClientActions(self):
		log.debug("Processing Client Actions...")
		while self.clientActions:
			session, action = self.clientActions.pop(0)
			servername      = action['server'][0]
			role, handler   = self.actionHandlers.get(action['action'][0], (None, None))
			if handler:
				if self.authRequired:
					if role in self.authUsers[session.username].servers.get(servername):
						reactor.callWhenRunning(handler, session, action)
					else:
						self.http._addUpdate(servername = servername, sessid = session.uid, action = "RequestError", message = "You do not have permission to execute this action.")
				else:
					reactor.callWhenRunning(handler, session, action)
			else:
				log.error("ClientActionHandler for action %s does not exixts..." % action['action'][0]) 
Example #17
Source File: main.py    From voltha with Apache License 2.0 5 votes vote down vote up
def start_reactor(self):
        from twisted.internet import reactor
        reactor.callWhenRunning(
            lambda: self.log.info('twisted-reactor-started'))
        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdown_components)
        reactor.run() 
Example #18
Source File: mockserver.py    From autologin with Apache License 2.0 5 votes vote down vote up
def main():
    http_port = reactor.listenTCP(PORT, Site(Root()))
    def print_listening():
        host = http_port.getHost()
        print('Mock server running at http://{}:{}'.format(
            host.host, host.port))
    reactor.callWhenRunning(print_listening)
    reactor.run() 
Example #19
Source File: main.py    From voltha with Apache License 2.0 5 votes vote down vote up
def start_reactor(self):
        reactor.callWhenRunning(
            lambda: self.log.info('twisted-reactor-started'))

        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdown_components)
        reactor.run() 
Example #20
Source File: main.py    From voltha with Apache License 2.0 5 votes vote down vote up
def start_reactor(self):
        from twisted.internet import reactor
        reactor.callWhenRunning(
            lambda: self.log.info('twisted-reactor-started'))
        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdown_components)
        reactor.run() 
Example #21
Source File: main.py    From voltha with Apache License 2.0 5 votes vote down vote up
def start_reactor(self):
        reactor.callWhenRunning(
            lambda: self.log.info('twisted-reactor-started'))

        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdown_components)
        reactor.run() 
Example #22
Source File: main.py    From voltha with Apache License 2.0 5 votes vote down vote up
def start_reactor(self):
        reactor.callWhenRunning(
            lambda: self.log.info('twisted-reactor-started'))

        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdown_components)
        reactor.suggestThreadPoolSize(30)
        reactor.run() 
Example #23
Source File: kafka-consumer.py    From voltha with Apache License 2.0 5 votes vote down vote up
def main():
    logging.basicConfig(
        format='%(asctime)s:%(name)s:' +
               '%(levelname)s:%(process)d:%(message)s',
        level=logging.INFO
    )

    args = parse_options()

    consumer_example = ConsumerExample(args.consul, args.topic,
                                       int(args.runtime))
    reactor.callWhenRunning(consumer_example.start)
    reactor.run()
    log.info("completed!") 
Example #24
Source File: tap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def opt_wsgi(self, name):
        """
        The FQPN of a WSGI application object to serve as the root resource of
        the webserver.
        """
        pool = threadpool.ThreadPool()
        reactor.callWhenRunning(pool.start)
        reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
        try:
            application = reflect.namedAny(name)
        except (AttributeError, ValueError):
            raise usage.UsageError("No such WSGI application: %r" % (name,))
        self['root'] = wsgi.WSGIResource(reactor, pool, application) 
Example #25
Source File: monast.py    From monast with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def doAction(self, request):
		session = request.getSession()
		self.monast.clientActions.append((session, request.args))
		reactor.callWhenRunning(self.monast._processClientActions)
		request.write("OK")
		request.finish()

##
## Monast AMI
## 
Example #26
Source File: monast.py    From monast with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __start(self):
		log.info("Starting Monast Services...")
		for servername in self.servers:
			reactor.callWhenRunning(self.connect, servername) 
Example #27
Source File: test_releaseupgrader.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def test_finish_with_config_file(self):
        """
        The L{ReleaseUpgrader.finish} method passes over to the reporter the
        configuration file the release-upgrader was called with.
        """
        self.write_script(
            self.config,
            "landscape-package-reporter",
            "#!/bin/sh\necho $@\n")
        self.config.config = "/some/config"

        deferred = Deferred()

        def do_test():
            result = self.upgrader.finish()

            def check_result(args):
                out, err, code = args
                self.assertEqual(out, b"--force-apt-update "
                                      b"--config=/some/config\n")
                self.assertEqual(err, b"")
                self.assertEqual(code, 0)

            result.addCallback(check_result)
            result.chainDeferred(deferred)

        reactor.callWhenRunning(do_test)
        return deferred 
Example #28
Source File: test_spinner.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_fast_sigint_raises_no_result_error(self):
        # If we get a SIGINT during a run, we raise _spinner.NoResultError.
        SIGINT = getattr(signal, 'SIGINT', None)
        if not SIGINT:
            self.skipTest("SIGINT not available")
        reactor = self.make_reactor()
        spinner = self.make_spinner(reactor)
        timeout = self.make_timeout()
        reactor.callWhenRunning(os.kill, os.getpid(), SIGINT)
        self.assertThat(lambda:spinner.run(timeout * 5, defer.Deferred),
            Raises(MatchesException(_spinner.NoResultError)))
        self.assertEqual([], spinner._clean()) 
Example #29
Source File: cli.py    From wifibroadcast with GNU General Public License v3.0 5 votes vote down vote up
def main():
    stderr = sys.stderr

    if len(sys.argv) != 2:
        print("Usage: %s <profile>" % (sys.argv[0],), file=stderr)
        sys.exit(1)

    fd = tempfile.TemporaryFile()
    log.startLogging(fd)

    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    stdscr.keypad(1)

    reactor.callWhenRunning(lambda: defer.maybeDeferred(init, stdscr, sys.argv[1])\
                            .addErrback(abort_on_crash))
    reactor.run()
    curses.endwin()
    rc = exit_status()

    if rc:
        log.msg('Exiting with code %d' % rc)
        fd.seek(0)
        for l in fd:
            stderr.write(l)

    sys.exit(rc) 
Example #30
Source File: server.py    From wifibroadcast with GNU General Public License v3.0 5 votes vote down vote up
def main():
    log.startLogging(sys.stdout)
    profile, wlans = sys.argv[1], list(wlan for arg in sys.argv[2:] for wlan in arg.split())
    reactor.callWhenRunning(lambda: defer.maybeDeferred(init, profile, wlans)\
                            .addErrback(abort_on_crash))
    reactor.run()

    rc = exit_status()
    log.msg('Exiting with code %d' % rc)
    sys.exit(rc)