Python twisted.internet.reactor.stop() Examples

The following are 30 code examples of twisted.internet.reactor.stop(). 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: twistedtools.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def stop_reactor():
    """Stop the reactor and join the reactor thread until it stops.
    Call this function in teardown at the module or package level to
    reset the twisted system after your tests. You *must* do this if
    you mix tests using these tools and tests using twisted.trial.
    """
    global _twisted_thread

    def stop_reactor():
        '''Helper for calling stop from withing the thread.'''
        reactor.stop()

    reactor.callFromThread(stop_reactor)
    reactor_thread.join()
    for p in reactor.getDelayedCalls():
        if p.active():
            p.cancel()
    _twisted_thread = None 
Example #2
Source File: head_request.py    From hyper-h2 with MIT License 6 votes vote down vote up
def dataReceived(self, data):
        if not self.known_proto:
            self.known_proto = self.transport.negotiatedProtocol
            assert self.known_proto == b'h2'

        events = self.conn.receive_data(data)

        for event in events:
            if isinstance(event, ResponseReceived):
                self.handleResponse(event.headers, event.stream_id)
            elif isinstance(event, DataReceived):
                self.handleData(event.data, event.stream_id)
            elif isinstance(event, StreamEnded):
                self.endStream(event.stream_id)
            elif isinstance(event, SettingsAcknowledged):
                self.settingsAcked(event)
            elif isinstance(event, StreamReset):
                reactor.stop()
                raise RuntimeError("Stream reset: %d" % event.error_code)
            else:
                print(event)

        data = self.conn.data_to_send()
        if data:
            self.transport.write(data) 
Example #3
Source File: app.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def fixPdb():
    def do_stop(self, arg):
        self.clear_all_breaks()
        self.set_continue()
        from twisted.internet import reactor
        reactor.callLater(0, reactor.stop)
        return 1


    def help_stop(self):
        print("stop - Continue execution, then cleanly shutdown the twisted "
              "reactor.")


    def set_quit(self):
        os._exit(0)

    pdb.Pdb.set_quit = set_quit
    pdb.Pdb.do_stop = do_stop
    pdb.Pdb.help_stop = help_stop 
Example #4
Source File: test_gireactor.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_cantRegisterAfterRun(self):
        """
        It is not possible to register a C{Application} after the reactor has
        already started.
        """
        reactor = gireactor.GIReactor(useGtk=False)
        self.addCleanup(self.unbuildReactor, reactor)
        app = Gio.Application(
            application_id='com.twistedmatrix.trial.gireactor',
            flags=Gio.ApplicationFlags.FLAGS_NONE)

        def tryRegister():
            exc = self.assertRaises(ReactorAlreadyRunning,
                                    reactor.registerGApplication, app)
            self.assertEqual(exc.args[0],
                             "Can't register application after reactor was started.")
            reactor.stop()
        reactor.callLater(0, tryRegister)
        ReactorBuilder.runReactor(self, reactor) 
Example #5
Source File: converter.py    From worker with GNU General Public License v3.0 6 votes vote down vote up
def convert(db):

    log.info(db.rc)
    log.info("Reading metrics keys")
    keys = yield db.rc.keys(METRIC_OLD_PREFIX.format("*"))
    log.info("Converting ...")
    for key in keys:
        _, name = key.split(':')
        try:
            pipe = yield db.rc.pipeline()
            metrics = yield db.rc.zrange(key)
            for metric in metrics:
                value, timestamp = metric.split()
                pipe.zadd(METRIC_PREFIX.format(name), timestamp, "{0} {1}".format(timestamp, value))
            yield pipe.execute_pipeline()
        except txredisapi.ResponseError as e:
            log.error("Can not convert {key}: {e}", key=key, e=e)
        log.info("Metric {name} converted", name=name)

    yield db.stopService()
    reactor.stop() 
Example #6
Source File: base.py    From invana-bot with MIT License 6 votes vote down vote up
def callback(self, callback_fn=None):
        all_data_storages = self.manifest.get('data_storages', [])
        if len(all_data_storages) == 0:
            print("There are no callback notifications associated with the indexing jobs. So we are Done here.")
        else:
            print("Initiating, sending the callback notifications after the respective transformations ")
            for index in all_data_storages:
                data_storage_id = index.get('data_storage_id')
                callback_config = self.get_callback_for_index(data_storage_id=data_storage_id)
                if callback_config:
                    try:
                        self.trigger_callback(callback_config=callback_config)
                    except Exception as e:
                        print("Failed to send callback[{}] with error: {}".format(callback_config.get("callback_id"),
                                                                                  e))

        if callback_fn is None:
            reactor.stop()
        else:
            callback_fn() 
Example #7
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 #8
Source File: task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _completeWith(self, completionState, deferredResult):
        """
        @param completionState: a L{TaskFinished} exception or a subclass
            thereof, indicating what exception should be raised when subsequent
            operations are performed.

        @param deferredResult: the result to fire all the deferreds with.
        """
        self._completionState = completionState
        self._completionResult = deferredResult
        if not self._pauseCount:
            self._cooperator._removeTask(self)

        # The Deferreds need to be invoked after all this is completed, because
        # a Deferred may want to manipulate other tasks in a Cooperator.  For
        # example, if you call "stop()" on a cooperator in a callback on a
        # Deferred returned from whenDone(), this CooperativeTask must be gone
        # from the Cooperator by that point so that _completeWith is not
        # invoked reentrantly; that would cause these Deferreds to blow up with
        # an AlreadyCalledError, or the _removeTask to fail with a ValueError.
        for d in self._deferreds:
            d.callback(deferredResult) 
Example #9
Source File: twistedtools.py    From Computable with MIT License 6 votes vote down vote up
def stop_reactor():
    """Stop the reactor and join the reactor thread until it stops.
    Call this function in teardown at the module or package level to
    reset the twisted system after your tests. You *must* do this if
    you mix tests using these tools and tests using twisted.trial.
    """
    global _twisted_thread

    def stop_reactor():
        '''Helper for calling stop from withing the thread.'''
        reactor.stop()

    reactor.callFromThread(stop_reactor)
    reactor_thread.join()
    for p in reactor.getDelayedCalls():
        if p.active():
            p.cancel()
    _twisted_thread = None 
Example #10
Source File: base.py    From CoinSwapCS with GNU General Public License v3.0 6 votes vote down vote up
def check_for_phase1_utxos(self, utxos, cb=None):
        """Any participant needs to wait for completion of phase 1 through
        seeing the utxos on the network. Optionally pass callback for start
        of phase2 (redemption phase), else default is state machine tick();
        must have signature callback(utxolist).
        Triggered on number of confirmations as set by config.
        This should be fired by task looptask, which is stopped on success.
        """
        result = cs_single().bc_interface.query_utxo_set(utxos,
                                                         includeconf=True)
        if None in result:
            return
        for u in result:
            if u['confirms'] < self.coinswap_parameters.tx01_confirm_wait:
                return
        self.loop.stop()
        if cb:
            cb()
        else:
            self.sm.tick() 
Example #11
Source File: wamp.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def make(self):

        # connect to crossbar router/broker
        self.runner = ApplicationRunner(self.url, self.realm, extra=dict(self.config))

        # run application session
        self.deferred = self.runner.run(self.session_class, start_reactor=False)

        def croak(ex, *args):
            log.error('Problem in {name}, please check if "crossbar" WAMP broker is running. args={args}'.format(
                name=self.__class__.__name__, args=args))
            log.error("{ex}, args={args!s}", ex=ex.getTraceback(), args=args)
            reactor.stop()
            raise ex

        self.deferred.addErrback(croak) 
Example #12
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 #13
Source File: pyuisupport.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _guiUpdate(reactor, delay):
    pyui.draw()
    if pyui.update() == 0:
        pyui.quit()
        reactor.stop()
    else:
        reactor.callLater(delay, _guiUpdate, reactor, delay) 
Example #14
Source File: task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def start(self, interval, now=True):
        """
        Start running function every interval seconds.

        @param interval: The number of seconds between calls.  May be
        less than one.  Precision will depend on the underlying
        platform, the available hardware, and the load on the system.

        @param now: If True, run this call right now.  Otherwise, wait
        until the interval has elapsed before beginning.

        @return: A Deferred whose callback will be invoked with
        C{self} when C{self.stop} is called, or whose errback will be
        invoked when the function raises an exception or returned a
        deferred that has its errback invoked.
        """
        assert not self.running, ("Tried to start an already running "
                                  "LoopingCall.")
        if interval < 0:
            raise ValueError("interval must be >= 0")
        self.running = True
        # Loop might fail to start and then self._deferred will be cleared.
        # This why the local C{deferred} variable is used.
        deferred = self._deferred = defer.Deferred()
        self.starttime = self.clock.seconds()
        self.interval = interval
        self._runAtStart = now
        if now:
            self()
        else:
            self._scheduleFrom(self.starttime)
        return deferred 
Example #15
Source File: full_analysis.py    From jd_analysis with GNU Lesser General Public License v3.0 5 votes vote down vote up
def runspider(self):
        configure_logging(install_root_handler = False)
        s = get_project_settings()
        runner = CrawlerRunner(settings = s)

        @defer.inlineCallbacks
        def crawl(**spargs):
            yield runner.crawl(JDItemInfoSpider, **spargs)
            yield runner.crawl(JDCommentSpider, **spargs)
            reactor.stop()

        crawl(**self.spargs)
        reactor.run()  # the script will block here until the last crawl call is finished

    # 调度分析 
Example #16
Source File: spawn_process.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def main():
    """Run a test from the command line."""

    def on_test_exit(out_data, err_data, reason):
        """Called by SpawnProcess when the test process exits."""
        LOG.d("  Callback out_data:", out_data)
        LOG.d("  Callback err_data:", err_data)
        LOG.d("  Callback reason:", reason)
        # Quit a bit later in order to test if events occur properly
        # noinspection PyUnresolvedReferences
        reactor.callLater(3, reactor.stop)

    script = """# Produce some output with delays
i=0
while [ $i -lt 5 ]; do
    echo "process stdout line #$i"
    echo "process stderr line #$i" >&2
    sleep 1
    i=$(($i+1))
done
"""
    tests = ['process-error']
    print("Running tests:", tests)
    if 'normal-termination' in tests:
        SpawnProcess(on_test_exit).spawn(['sh', '-c', script])
    if 'lines_max' in tests:
        SpawnProcess(on_test_exit).spawn(
            ['sh', '-c', 'trap "" TERM\n' + script], lines_max=3)
    if 'timeout' in tests:
        SpawnProcess(on_test_exit).spawn(['sh', '-c', script], timeout=3)
    if 'event-driven' in tests:  # e.g. a cancel button
        proc = SpawnProcess(on_test_exit)
        proc.spawn(['sh', '-c', script])
        # noinspection PyUnresolvedReferences
        reactor.callLater(3, proc.stop, 'cancelled')
    if 'process-error' in tests:
        SpawnProcess(on_test_exit).spawn(
            ['sh', '-c', 'echo Started && sleep 1 && invalid-command'])

    # noinspection PyUnresolvedReferences
    reactor.run() 
Example #17
Source File: spawn_process.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def outReceived(self, data):
        """Override ProcessProtocol.outReceived."""
        old_lines_count = self.lines_count
        self.lines_count += data.count(b'\n')
        LOG.d("outReceived, lines_count = %s:" % self.lines_count, data)
        self.out_data += data
        # If this is the first time lines_max is exceeded, call stop
        if self.lines_count >= self.lines_max > old_lines_count:
            self.stop("lines_max") 
Example #18
Source File: spawn_process.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def stop(self, reason=""):
        """Send TERM, TERM, KILL, with 0.5 sec delays."""
        LOG.d("stop('{}')".format(reason))
        assert self.state != "idle"
        assert self.transport
        # Once stopping started, only accept calls from stop itself,
        # and not for example lines_max calls.
        if self.state.startswith("stopping") \
                and not reason.startswith("stopping"):
            return
        # Only keep the initial reason
        if not self.reason:
            self.reason = reason
        # Cancel the timeout callback
        if self.dc_timeout:
            if self.reason != "timeout":
                self.dc_timeout.cancel()
            self.dc_timeout = None
        if self.state == "running":
            self.state = "stopping1"
            self.transport.signalProcess('TERM')
        elif self.state == "stopping1":
            self.state = "stopping2"
            # iperf2 requests 2 TERM signals to abort waiting open connections
            # Additionally, help it by closing its stdio
            self.transport.loseConnection()
            self.transport.signalProcess('TERM')
        elif self.state == "stopping2":
            self.state = "stopping3"
            # Kill it, don't wait any longer
            self.transport.signalProcess('KILL')
        else:
            assert False, "Unable to kill child process!"
        # noinspection PyUnresolvedReferences
        self.dc_stop = reactor.callLater(0.5, self.stop, self.state) 
Example #19
Source File: spawn_process.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def spawn(self, cmdline, timeout=0, lines_max=0):
        """Spawn the process and run on_exit on exit, timeout, or lines_max."""
        LOG.d("spawn: {}, timeout: {}, lines_max: {}".format(
            cmdline, timeout, lines_max))
        assert self.state == "idle"
        # Reinitialize vars without duplicating a lot of code
        self.__init__(self.on_exit)
        self.lines_max = lines_max
        if timeout:
            # noinspection PyUnresolvedReferences
            self.dc_timeout = reactor.callLater(timeout, self.stop, "timeout")
        else:
            self.dc_timeout = None
        # noinspection PyUnresolvedReferences
        reactor.spawnProcess(self, cmdline[0], cmdline) 
Example #20
Source File: task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def stop(self):
        """Stop running function.
        """
        assert self.running, ("Tried to stop a LoopingCall that was "
                              "not running.")
        self.running = False
        if self.call is not None:
            self.call.cancel()
            self.call = None
            d, self._deferred = self._deferred, None
            d.callback(self) 
Example #21
Source File: spawn_process.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def __del__(self):
        """Kill child processes even on abrupt exits."""
        LOG.d("__del__:")
        if self.state == "running":
            self.stop('destructor') 
Example #22
Source File: spawn_process.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, on_exit):
        self.dc_stop = None  # IDelayedCall, to cancel the stop callback
        self.dc_timeout = None  # IDelayedCall, to cancel the timeout callback
        self.err_data = b''
        self.lines_count = 0
        self.lines_max = 0
        self.on_exit = on_exit
        self.out_data = b''
        self.reason = ''
        self.state = 'idle'  # or: running, stopping1, stopping2, stopping3 
Example #23
Source File: sql.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def onDisconnect(self):
        print("Transport disconnected.")
        #reactor.stop()

    #@inlineCallbacks 
Example #24
Source File: nodeservice.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def onDisconnect(self):
        print("Transport disconnected.")
        #reactor.stop() 
Example #25
Source File: app.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def stop(self):
        """
        Remove all log observers previously set up by L{AppLogger.start}.
        """
        logger._loggerFor(self).info("Server Shut Down.")
        if self._observer is not None:
            logger.globalLogPublisher.removeObserver(self._observer)
            self._observer = None 
Example #26
Source File: client.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def onDisconnect(self):
        print("disconnected")
        reactor.stop() 
Example #27
Source File: client.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def onJoin(self, details):
        print("session attached")

        yield self.publish("de.elmyra.kotori.broadcast.node-activity", {'node_id': 'Hello!', 'state': True}, excludeMe=False)
        yield self.publish("de.elmyra.kotori.broadcast.operator-presence", True, excludeMe=False)
        #yield self.publish("de.elmyra.kotori.broadcast.operator-presence", False, excludeMe=False)

        # send telemetry data
        yield self.publish("de.elmyra.kotori.telemetry.data", 'WAMP hello', excludeMe=False)
        yield self.publish("de.elmyra.kotori.telemetry.data", {'attribute1': 'value1', 'attribute2': 'value2'}, excludeMe=False)

        reactor.callLater(0.1, reactor.stop) 
Example #28
Source File: socks4server.py    From phpsploit with GNU General Public License v3.0 5 votes vote down vote up
def run_proxy():
    reactor.listenTCP(1080, SOCKSv4Factory("/dev/null"), interface="127.0.0.1")
    try:
        reactor.run()
    except (KeyboardInterrupt, SystemExit):
        reactor.stop() 
Example #29
Source File: base.py    From invana-bot with MIT License 5 votes vote down vote up
def start_job(self, job=None, callback_fn=None):
        print(job)
        spider_job = job['spider_job']
        runner = job['runner']
        spider_cls = spider_job['spider_cls']
        spider_settings = spider_job['spider_settings']
        spider_kwargs = spider_job['spider_kwargs']

        def engine_stopped_callback():
            runner.transform_and_index(callback_fn=callback_fn)

        if callback_fn:
            print("""
==========================================================
WARNING: callback_fn is {}
==========================================================
Since start_job is called with callback_fn, make sure you end the reactor if you want the spider process to
stop after the callback function is executed. By default callback_fn=None will close the reactor.

To write a custom callback_fn

def callback_fn():
    print ("Write your own callback logic")
    from twisted.internet import reactor
    reactor.stop()
==========================================================
        """.format(callback_fn))

        spider = Crawler(spider_cls, Settings(spider_settings))
        spider.signals.connect(engine_stopped_callback, signals.engine_stopped)
        self.runner.crawl(spider, **spider_kwargs)
        """
        d = runner.crawl(spider, **spider_kwargs)
        # d.addBoth(engine_stopped_callback)
        """
        reactor.run() 
Example #30
Source File: _asynctest.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _ebDeferSetUp(self, failure, result):
        if failure.check(SkipTest):
            result.addSkip(self, self._getSkipReason(self.setUp, failure.value))
        else:
            result.addError(self, failure)
            if failure.check(KeyboardInterrupt):
                result.stop()
        return self.deferRunCleanups(None, result)