Python twisted.internet.reactor.running() Examples

The following are 30 code examples of twisted.internet.reactor.running(). 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: __init__.py    From maas with GNU Affero General Public License v3.0 7 votes vote down vote up
def execute_from_command_line():
    # Limit concurrency in all thread-pools to ONE.
    from maasserver.utils import threads

    threads.install_default_pool(maxthreads=1)
    threads.install_database_unpool(maxthreads=1)
    # Disable all database connections in the reactor.
    from maasserver.utils import orm
    from twisted.internet import reactor

    assert not reactor.running, "The reactor has been started too early."
    reactor.callFromThread(orm.disable_all_database_connections)
    # Configure logging; Django is no longer responsible for this. Behave as
    # if we're always at an interactive terminal (i.e. do not wrap stdout or
    # stderr with log machinery).
    from provisioningserver import logger

    logger.configure(mode=logger.LoggingMode.COMMAND)
    # Hand over to Django.
    from django.core import management

    management.execute_from_command_line() 
Example #2
Source File: wallet_service.py    From joinmarket-clientserver with GNU General Public License v3.0 6 votes vote down vote up
def start_wallet_monitoring(self, syncresult):
        """ Once the initialization of the service
        (currently, means: wallet sync) is complete,
        we start the main monitoring jobs of the
        wallet service (currently, means: monitoring
        all new transactions on the blockchain that
        are recognised as belonging to the Bitcoin
        Core wallet with the JM wallet's label).
        """
        if not syncresult:
            jlog.error("Failed to sync the bitcoin wallet. Shutting down.")
            self.stopService()
            if reactor.running:
                reactor.stop()
            return
        jlog.info("Starting transaction monitor in walletservice")
        self.monitor_loop = task.LoopingCall(
            self.transaction_monitor)
        self.monitor_loop.start(5.0) 
Example #3
Source File: test_watchdog.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def test_dont_write_pid_file_until_we_really_start(
            self, mock_watchdog, mock_daemonize, mock_reactor):
        """
        If the client can't be started because another client is still running,
        the client shouldn't be daemonized and the pid file shouldn't be
        written.
        """
        mock_watchdog().check_running.return_value = succeed([StubDaemon()])
        mock_reactor.crash.return_value = None
        self.log_helper.ignore_errors(
            "ERROR: The following daemons are already running: program-name")
        pid_file = self.makeFile()

        self.configuration.daemon = True
        self.configuration.pid_file = pid_file
        service = WatchDogService(self.configuration)

        service.startService()
        self.assertFalse(os.path.exists(pid_file))
        mock_daemonize.assert_not_called()
        mock_watchdog().check_running.assert_called_once_with()
        mock_watchdog().start.assert_not_called()
        mock_reactor.crash.assert_called_once_with() 
Example #4
Source File: bitmask_cli.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def execute():
    cfg = Configuration(".bitmaskctl")
    print_json = '--json' in sys.argv

    cli = BitmaskCLI(cfg)
    cli.data = ['core', 'version']
    args = None if '--noverbose' in sys.argv else ['--verbose']

    if should_start(sys.argv):
        timeout_fun = cli.start
    else:
        def status_timeout(args):
            raise RuntimeError('bitmaskd is not running')
        timeout_fun = status_timeout

    try:
        yield cli._send(
            timeout=0.1, printer=_null_printer,
            errb=lambda: timeout_fun(args))
    except Exception, e:
        print(Fore.RED + "ERROR: " + Fore.RESET +
              "%s" % str(e))
        yield reactor.stop() 
Example #5
Source File: util.py    From tapas with GNU General Public License v2.0 6 votes vote down vote up
def calc_iteration(self):
        if not self.running or not reactor.running:
            debug(1, '%s exiting', self)
            return False
        if not self.last_t:
            self.last_t = time()
        now = time()
        if now - self.last_t >= self.period:
            self.rate = self.alpha*self.rate + \
                (1.0-self.alpha)*self.last_data/(now - self.last_t)
            self.last_data = 0
            self.last_t = now
            self.rate_vec.add(self.rate)
            #self.rate_filt = self.harmonic_mean(self.rate_vec.getBuffer())
            self.emit('update')
        reactor.callLater(self.period, self.calc_iteration)
        #return True 
Example #6
Source File: test_watchdog.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def test_check_daemons(self):
        """
        The daemons are checked to be running every so often. When N=5 of these
        checks fail, the daemon will be restarted.
        """
        clock = Clock()
        dog = WatchDog(clock,
                       broker=AsynchronousPingDaemon("test-broker"),
                       monitor=AsynchronousPingDaemon("test-monitor"),
                       manager=AsynchronousPingDaemon("test-manager"))
        dog.start_monitoring()

        for i in range(4):
            clock.advance(5)
            dog.broker.fire_running(False)
            dog.monitor.fire_running(True)
            dog.manager.fire_running(True)
            self.assertEqual(dog.broker.boots, [])

        clock.advance(5)
        dog.broker.fire_running(False)
        dog.monitor.fire_running(True)
        dog.manager.fire_running(True)
        self.assertEqual(dog.broker.boots, [STOP, START]) 
Example #7
Source File: joinmarket-qt.py    From joinmarket-clientserver with GNU General Public License v3.0 6 votes vote down vote up
def toggleButtons(self):
        """Refreshes accessibility of buttons in the (single, multiple) join
        tabs based on the current state as defined by the SpendStateMgr instance.
        Thus, should always be called on any update to that instance.
        """
        #The first two buttons are for the single join tab; the remaining 4
        #are for the multijoin tab.
        btns = (self.startButton, self.abortButton,
                self.schedule_set_button, self.schedule_generate_button,
                self.sch_startButton, self.sch_abortButton)
        if self.spendstate.runstate == 'ready':
            btnsettings = (True, False, True, True, True, False)
        elif self.spendstate.runstate == 'running':
            if self.spendstate.typestate == 'single':
                #can only abort current run, nothing else
                btnsettings = (False, True, False, False, False, False)
            elif self.spendstate.typestate == 'multiple':
                btnsettings = (False, False, False, False, False, True)
            else:
                assert False
        else:
            assert False

        for b, s in zip(btns, btnsettings):
            b.setEnabled(s) 
Example #8
Source File: start.py    From RAFCON with Eclipse Public License 1.0 6 votes vote down vote up
def signal_handler(signal, frame):
    global _user_abort

    state_machine_execution_engine = core_singletons.state_machine_execution_engine
    core_singletons.shut_down_signal = signal

    logger.info("Shutting down ...")

    try:
        if not state_machine_execution_engine.finished_or_stopped():
            state_machine_execution_engine.stop()
            state_machine_execution_engine.join(3)  # Wait max 3 sec for the execution to stop
    except Exception:
        logger.exception("Could not stop state machine")

    _user_abort = True

    # shutdown twisted correctly
    if reactor_required():
        from twisted.internet import reactor
        if reactor.running:
            plugins.run_hook("pre_destruction")
            reactor.callFromThread(reactor.stop)

    logging.shutdown() 
Example #9
Source File: gamespy_gamestats_server.py    From dwc_network_server_emulator with GNU Affero General Public License v3.0 5 votes vote down vote up
def start(self):
        endpoint_search = serverFromString(
            reactor,
            "tcp:%d:interface=%s" % (address[1], address[0])
        )
        conn_search = endpoint_search.listen(GamestatsFactory())

        try:
            if not reactor.running:
                reactor.run(installSignalHandlers=0)
        except ReactorAlreadyRunning:
            pass 
Example #10
Source File: admin_page_server.py    From dwc_network_server_emulator with GNU Affero General Public License v3.0 5 votes vote down vote up
def start(self):
        site = server.Site(AdminPage(self))
        reactor.listenTCP(port, site)
        logger.log(logging.INFO,
                   "Now listening for connections on port %d...",
                   port)
        try:
            if not reactor.running:
                reactor.run(installSignalHandlers=0)
        except ReactorAlreadyRunning:
            pass 
Example #11
Source File: gamespy_player_search_server.py    From dwc_network_server_emulator with GNU Affero General Public License v3.0 5 votes vote down vote up
def start(self):
        endpoint_search = serverFromString(
            reactor,
            "tcp:%d:interface=%s" % (address[1], address[0])
        )
        conn_search = endpoint_search.listen(PlayerSearchFactory())

        try:
            if not reactor.running:
                reactor.run(installSignalHandlers=0)
        except ReactorAlreadyRunning:
            pass 
Example #12
Source File: util.py    From tapas with GNU General Public License v2.0 5 votes vote down vote up
def stop(self):
        self.running = False
        if self.calc_iteration_id:
            gobject.source_remove(self.calc_iteration_id)
            self.calc_iteration_id = None 
Example #13
Source File: scripts.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def run_region():
    """Entry point for region test runner."""
    options = [
        "--with-crochet",
        "--with-resources",
        "--with-scenarios",
        "--with-select",
        "--select-dir=src/maasserver",
        "--select-dir=src/metadataserver",
        "--cover-package=maas,maasserver,metadataserver",
        "--cover-branches",
        # Reduce the logging level to INFO here as
        # DebuggingLoggerMiddleware logs the content of all the
        # requests at DEBUG level: we don't want this in the
        # tests as it's too verbose.
        "--logging-level=INFO",
        "--logging-clear-handlers",
        # Do not run tests tagged "legacy".
        "-a",
        "!legacy",
    ]
    inject_test_options(options)
    update_environ()
    init_asyncio_reactor()

    logger.configure(mode=logger.LoggingMode.COMMAND)
    # Limit concurrency in all thread-pools to ONE.
    threads.install_default_pool(maxthreads=1)
    threads.install_database_unpool(maxthreads=1)

    # Disable all database connections in the reactor.
    assert not reactor.running, "The reactor has been started too early."
    reactor.callFromThread(orm.disable_all_database_connections)

    # Configure Django
    import django

    django.setup()
    test_main() 
Example #14
Source File: util.py    From tapas with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, period=0.5, alpha=0.5):
        gobject.GObject.__init__(self)
        self.period = period
        self.alpha = alpha
        self.last_t = 0.0
        self.last_data = 0
        self.rate = 0.0
        self.rate_filt = -1
        self.horizon = 5
        self.rate_vec = CircularBuffer(self.horizon)
        self.running = False
        self.calc_iteration_id = None 
Example #15
Source File: util.py    From tapas with GNU General Public License v2.0 5 votes vote down vote up
def start(self):
        #debug(1, "%s start", self)
        self.running = True
        #self.calc_iteration_id = gobject.timeout_add(int(self.period*1000),
        #    self.calc_iteration)
        reactor.callLater(self.period, self.calc_iteration) 
Example #16
Source File: core.py    From dtella with GNU General Public License v2.0 5 votes vote down vote up
def stopProtocol(self):
        # If this is the final termination, don't do anything.
        if not reactor.running:
            return

        self.main.showLoginStatus("UDP socket was reset.")

        # Otherwise, our UDP port randomly died, so try reconnecting.
        # Disable transmits during the shutdown.
        self.stopping_protocol = True
        try:
            self.main.shutdown(reconnect='instant')
        finally:
            self.stopping_protocol = False 
Example #17
Source File: core.py    From dtella with GNU General Public License v2.0 5 votes vote down vote up
def stopProtocol(self):
        # If this is the final termination, don't do anything.
        if not reactor.running:
            return

        self.main.showLoginStatus("UDP socket was reset.")

        # Otherwise, our UDP port randomly died, so try reconnecting.
        # Disable transmits during the shutdown.
        self.stopping_protocol = True
        try:
            self.main.shutdown(reconnect='instant')
        finally:
            self.stopping_protocol = False 
Example #18
Source File: test_secappend.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def __init__(self, number, server_type=AppendServer):
        self.nodes = []
        self.boot_strap = None

        if not reactor.running:
            print "Starting reactor only once"
            self.reactor_thread = Thread(target=reactor.run, args=(False,)).start()

        for a in xrange(number):
            self.nodes.append(ServerApp(server_type)) 
Example #19
Source File: bottle.py    From aws-mock-metadata 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 #20
Source File: register_page.py    From dwc_network_server_emulator with GNU Affero General Public License v3.0 5 votes vote down vote up
def start(self):
        site = server.Site(RegPage(self))
        reactor.listenTCP(port, site)
        logger.log(logging.INFO,
                   "Now listening for connections on port %d...",
                   port)
        try:
            if not reactor.running:
                reactor.run(installSignalHandlers=0)
        except ReactorAlreadyRunning:
            pass 
Example #21
Source File: gamespy_profile_server.py    From dwc_network_server_emulator with GNU Affero General Public License v3.0 5 votes vote down vote up
def start(self):
        endpoint = serverFromString(
            reactor,
            "tcp:%d:interface=%s" % (address[1], address[0])
        )
        conn = endpoint.listen(PlayerFactory())

        try:
            if not reactor.running:
                reactor.run(installSignalHandlers=0)
        except ReactorAlreadyRunning:
            pass 
Example #22
Source File: comm_autobahn.py    From roslibpy with MIT License 5 votes vote down vote up
def run(self):
        """Kick-starts a non-blocking event loop.

        This implementation starts the Twisted Reactor
        on a separate thread to avoid blocking."""

        if reactor.running:
            return

        self._thread = threading.Thread(target=reactor.run, args=(False,))
        self._thread.daemon = True
        self._thread.start() 
Example #23
Source File: vnc.py    From Map-A-Droid with GNU General Public License v3.0 5 votes vote down vote up
def connect(server, password=None,
        factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None):
    """ Connect to a VNCServer and return a Client instance that is usable
    in the main thread of non-Twisted Python Applications, EXPERIMENTAL.

    >>> from vncdotool import api
    >>> with api.connect('host') as client
    >>>     client.keyPress('c')

    You may then call any regular VNCDoToolClient method on client from your
    application code.

    If you are using a GUI toolkit or other major async library please read
    http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html
    for a better method of intergrating vncdotool.
    """
    if not reactor.running:
        global _THREAD
        _THREAD = threading.Thread(target=reactor.run, name='VNCPic',
                         kwargs={'installSignalHandlers': False})
        _THREAD.daemon = True
        _THREAD.start()

        observer = PythonLoggingObserver()
        observer.start()

    factory = factory_class()

    if password is not None:
        factory.password = password

    family, host, port = command.parse_server(server)
    client = proxy(factory, timeout)
    client.connect(host, port=port, family=family)

    return client 
Example #24
Source File: vnc.py    From Map-A-Droid with GNU General Public License v3.0 5 votes vote down vote up
def shutdown():
    if not reactor.running:
        return

    reactor.callFromThread(reactor.stop)
    _THREAD.join() 
Example #25
Source File: joinmarket-qt.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def updateWalletInfo(self):
        t = self.centralWidget().widget(0)
        if not self.wallet_service:  #failure to sync in constructor means object is not created
            newsyncmsg = "Unable to sync wallet - see error in console."
        elif not self.wallet_service.isRunning():
            JMQtMessageBox(self,
                           "The Joinmarket wallet service has stopped; this is usually caused "
                           "by a Bitcoin Core RPC connection failure. Is your node running?",
                           mbtype='crit',
                           title="Error")
            qApp.exit(EXIT_FAILURE)
            return
        elif not self.wallet_service.synced:
            return
        else:
            try:
                t.updateWalletInfo(get_wallet_printout(self.wallet_service))
            except Exception:
                # this is very likely to happen in case Core RPC connection goes
                # down (but, order of events means it is not deterministic).
                log.debug("Failed to get wallet information, is there a problem with "
                          "the blockchain interface?")
                return
            newsyncmsg = "Wallet synced successfully."
        if newsyncmsg != self.syncmsg:
            self.syncmsg = newsyncmsg
            self.statusBar().showMessage(self.syncmsg) 
Example #26
Source File: joinmarket-qt.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def generateTumbleSchedule(self):
        if not mainWindow.wallet_service:
            JMQtMessageBox(self, "Cannot start without a loaded wallet.",
                           mbtype="crit", title="Error")
            return
        #needs a set of tumbler options and destination addresses, so needs
        #a wizard
        wizard = ScheduleWizard()
        wizard_return = wizard.exec_()
        if wizard_return == QDialog.Rejected:
            return
        self.spendstate.loaded_schedule = wizard.get_schedule(
            mainWindow.wallet_service.get_balance_by_mixdepth())
        self.spendstate.schedule_name = wizard.get_name()
        self.updateSchedView()
        self.tumbler_options = wizard.opts
        self.tumbler_destaddrs = wizard.get_destaddrs()
        #tumbler may require more mixdepths; update the wallet
        required_mixdepths = max([tx[0] for tx in self.spendstate.loaded_schedule])
        if required_mixdepths > jm_single().config.getint("GUI", "max_mix_depth"):
            jm_single().config.set("GUI", "max_mix_depth", str(required_mixdepths))
            #recreate wallet and sync again; needed due to cache.
            JMQtMessageBox(self,
            "Max mixdepth has been reset to: " + str(required_mixdepths) + ".\n" +
            "Please choose 'Load' from the Wallet menu and resync before running.",
            title='Wallet resync required')
            return
        self.sch_startButton.setEnabled(True) 
Example #27
Source File: irc.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def build_irc(self):
        """The main starting method that creates a protocol object
        according to the config variables, ready for whenever
        the reactor starts running.
        """
        wlog('building irc')
        if self.tx_irc_client:
            raise Exception('irc already built')
        if self.usessl.lower() == 'true':
            ctx = ClientContextFactory()
        if self.usessl.lower() == 'true' and not self.socks5.lower() == 'true':
            factory = TxIRCFactory(self)
            reactor.connectSSL(self.serverport[0], self.serverport[1],
                               factory, ctx)
        elif self.socks5.lower() == 'true':
            factory = TxIRCFactory(self)
            #str() casts needed else unicode error
            torEndpoint = TCP4ClientEndpoint(reactor, str(self.socks5_host),
                                             self.socks5_port)
            if self.usessl.lower() == 'true':
                use_tls = ctx
            else:
                use_tls = False
            ircEndpoint = TorSocksEndpoint(torEndpoint, self.serverport[0],
                                           self.serverport[1], tls=use_tls)
            myRS = ClientService(ircEndpoint, factory)
            myRS.startService()
        else:
            try:
                factory = TxIRCFactory(self)
                wlog('build_irc: ', self.serverport[0], str(self.serverport[1]),
                     self.channel)
                self.tcp_connector = reactor.connectTCP(
                        self.serverport[0], self.serverport[1], factory)
            except Exception as e:
                wlog('error in buildirc: ' + repr(e)) 
Example #28
Source File: irc.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def clientConnectionFailed(self, connector, reason):
        log.info('IRC connection failed')
        if not self.wrapper.give_up:
            if reactor.running:
                log.info('Attempting to reconnect...')
                protocol.ReconnectingClientFactory.clientConnectionFailed(self,
                                                                connector, reason) 
Example #29
Source File: electruminterface.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def sync_wallet(self, wallet, fast=False, restart_cb=False):
        """This triggers the start of syncing, wiping temporary state
        and starting the reactor for wallet-tool runs. The 'fast'
        and 'restart_cb' parameters are ignored and included only
        for compatibility; they are both only used by Core.
        """
        self.wallet = wallet
        #wipe the temporary cache of address histories
        self.temp_addr_history = {}
        #mark as not currently synced
        self.wallet_synced = False
        if self.synctype == "sync-only":
            if not reactor.running:
                reactor.run() 
Example #30
Source File: wallet_service.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def isRunning(self):
        if self.running == 1:
            return True
        return False