Python源码示例:twisted.internet.reactor.callWhenRunning()

示例1
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']) 
示例2
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) 
示例3
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) 
示例4
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 
示例5
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 
示例6
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 
示例7
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 
示例8
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))) 
示例9
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() 
示例10
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() 
示例11
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() 
示例12
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() 
示例13
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."
        ) 
示例14
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."
        ) 
示例15
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."
        ) 
示例16
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]) 
示例17
def main():

    def signal_handler(signal, frame):
        if reactor.running:
            reactor.stop()
        sys.exit(0)

    reactor.callWhenRunning(reactor.callLater, 0, execute)
    signal.signal(signal.SIGINT, signal_handler)
    reactor.run() 
示例18
def startService(self):
        zf = ZmqFactory()
        e = ZmqEndpoint(ZmqEndpointType.bind, ENDPOINT)

        self._conn = _DispatcherREPConnection(zf, e, self._core)
        reactor.callWhenRunning(self._conn.do_greet)
        service.Service.startService(self) 
示例19
def opt_wsgi(self, name):
        """
        The FQPN of a WSGI application object to serve as the root resource of
        the webserver.
        """
        try:
            application = reflect.namedAny(name)
        except (AttributeError, ValueError):
            raise usage.UsageError("No such WSGI application: %r" % (name,))
        pool = threadpool.ThreadPool()
        reactor.callWhenRunning(pool.start)
        reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
        self['root'] = wsgi.WSGIResource(reactor, pool, application) 
示例20
def callWhenRunning(self, callable, *args, **kwargs):
        if self._whenRunning is None:
            callable(*args, **kwargs)
        else:
            self._whenRunning.append((callable, args, kwargs)) 
示例21
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('resource')
    parser.add_argument('--port', type=int)
    args = parser.parse_args()
    module_name, name = args.resource.rsplit('.', 1)
    sys.path.append('.')
    resource = getattr(import_module(module_name), name)()
    http_port = reactor.listenTCP(args.port, Site(resource))
    def print_listening():
        host = http_port.getHost()
        print('Mock server {} running at http://{}:{}'.format(
            resource, host.host, host.port))
    reactor.callWhenRunning(print_listening)
    reactor.run() 
示例22
def makeService(self, options):
        """
        Construct a Tribler service.
        """
        tribler_service = MultiService()
        tribler_service.setName("Market")

        reactor.callWhenRunning(self.start_tribler, options)

        return tribler_service 
示例23
def runReactor(self):
        from twisted.internet import reactor
        reactor.callWhenRunning(self.whenRunning)
        self.log.info("Starting reactor...")
        reactor.run() 
示例24
def configure():
  params, pipes, args = command.configure(rest_server=True)
  port = args.rest_api_port

  reactor.listenTCP(port, create_site(params, pipes))
  @reactor.callWhenRunning
  def startup_message():
    print 'Packet Queue is running. Configure at http://localhost:%i' % port
    sys.stdout.flush() 
示例25
def opt_wsgi(self, name):
        """
        The FQPN of a WSGI application object to serve as the root resource of
        the webserver.
        """
        try:
            application = reflect.namedAny(name)
        except (AttributeError, ValueError):
            raise usage.UsageError("No such WSGI application: %r" % (name,))
        pool = threadpool.ThreadPool()
        reactor.callWhenRunning(pool.start)
        reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
        self['root'] = wsgi.WSGIResource(reactor, pool, application) 
示例26
def callWhenRunning(self, callable, *args, **kwargs):
        if self._whenRunning is None:
            callable(*args, **kwargs)
        else:
            self._whenRunning.append((callable, args, kwargs)) 
示例27
def startService(self):
        # Do the actual DB work after the reactor has started up
        from twisted.internet import reactor
        reactor.callWhenRunning(self.initializeWork) 
示例28
def attachService(reactor, loadsim, service):
    """
    Attach a given L{IService} provider to the given L{IReactorCore}; cause it
    to be started when the reactor starts, and stopped when the reactor stops.
    """
    reactor.callWhenRunning(service.startService)
    reactor.addSystemEventTrigger('before', 'shutdown', loadsim.shutdown) 
示例29
def test_run_apt_update(self, warning_mock):
        """
        The L{PackageReporter.run_apt_update} method should run apt-update.
        """
        self.reporter.sources_list_filename = "/I/Dont/Exist"
        self.reporter.sources_list_directory = "/I/Dont/Exist"
        self._make_fake_apt_update()
        debug_patcher = mock.patch.object(reporter.logging, "debug")
        debug_mock = debug_patcher.start()
        self.addCleanup(debug_patcher.stop)

        deferred = Deferred()

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

            def callback(args):
                out, err, code = args
                self.assertEqual("output", out)
                self.assertEqual("error", err)
                self.assertEqual(0, code)
                self.assertFalse(warning_mock.called)
                debug_mock.assert_has_calls([
                    mock.call(
                        "Checking if ubuntu-release-upgrader is running."),
                    mock.call(
                        "'%s' exited with status 0 (out='output', err='error')"
                        % self.reporter.apt_update_filename)
                ])
            result.addCallback(callback)
            self.reactor.advance(0)
            result.chainDeferred(deferred)

        reactor.callWhenRunning(do_test)
        return deferred 
示例30
def test_run_apt_update_report_no_sources(self):
        """
        L{PackageReporter.run_apt_update} reports a failure if apt succeeds but
        there are no APT sources defined. APT doesn't fail if there are no
        sources, but we fake a failure in order to re-use the
        PackageReporterAlert on the server.
        """
        self.facade.reset_channels()
        message_store = self.broker_service.message_store
        message_store.set_accepted_types(["package-reporter-result"])
        self._make_fake_apt_update()
        deferred = Deferred()

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

            def callback(ignore):
                error = "There are no APT sources configured in %s or %s." % (
                    self.reporter.sources_list_filename,
                    self.reporter.sources_list_directory)
                self.assertMessages(
                    message_store.get_pending_messages(),
                    [{"type": "package-reporter-result",
                      "report-timestamp": 0.0, "code": 1, "err": error}])
            result.addCallback(callback)
            self.reactor.advance(0)
            result.chainDeferred(deferred)

        reactor.callWhenRunning(do_test)
        return deferred