Python源码示例:twisted.internet.reactor.running()
示例1
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()
示例2
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()
示例3
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])
示例4
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()
示例5
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)
示例6
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)
示例7
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()
示例8
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
示例9
def connectionLost(self, reason=None):
"""
Called by Twisted when the connection is gone. Regardless of whether
it was clean or not, we want to stop the reactor.
"""
if self.fileobj is not None:
self.fileobj.close()
if reactor.running:
reactor.stop()
示例10
def processEnded(self, reason):
log.info("Checker process ended with reason: {reason}", reason=reason)
if reactor.running:
reactor.stop()
示例11
def onExitSignal(*a):
print 'Closing Timeline?'
if not reactor.running:
os._exit(1)
reactor.callFromThread(reactor.stop)
示例12
def start(self, raw_args):
# XXX careful! Should see if the process in PID is running,
# avoid launching again.
import commands
cmd = 'bitmaskd'
if raw_args and ('--verbose' in raw_args or '-v' in raw_args):
cmd += ' --verbose'
commands.getoutput(cmd)
self.cfg.set('bonafide', 'active', "")
return defer.succeed(None)
示例13
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()
示例14
def clientConnectionFailed(self, connector, reason):
self.rx._callback('error', 'connection %s failed, reason=%s' % (connector, reason))
if reactor.running:
try:
reactor.stop()
except error.ReactorNotRunning:
pass
示例15
def clientConnectionLost(self, connector, reason):
self.rx._callback('error', 'connection %s lost, reason=%s' % (connector, reason))
if reactor.running:
try:
reactor.stop()
except error.ReactorNotRunning:
pass
示例16
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()
示例17
def run(self):
if not reactor.running:
Thread(target=reactor.run, args=(False,)).start()
示例18
def stop_gtk():
# shutdown twisted correctly
if reactor_required():
from twisted.internet import reactor
if reactor.running:
reactor.callFromThread(reactor.stop)
# Twisted can be imported without the reactor being used
# => check if GTK main loop is running
elif Gtk.main_level() > 0:
GLib.idle_add(Gtk.main_quit)
else:
GLib.idle_add(Gtk.main_quit)
# Run the GTK loop until no more events are being generated and thus the GUI is fully destroyed
wait_for_gui()
示例19
def stop_reactor_on_state_machine_finish(state_machine):
""" Wait for a state machine to be finished and stops the reactor
:param state_machine: the state machine to synchronize with
"""
wait_for_state_machine_finished(state_machine)
from twisted.internet import reactor
if reactor.running:
plugins.run_hook("pre_destruction")
reactor.callFromThread(reactor.stop)
示例20
def writeForever():
while reactor.running:
write = False
try:
file_cache_idxs = MetricCache.writableFileCaches()
if file_cache_idxs:
write = writeCachedDataPoints(file_cache_idxs)
except Exception as e:
log.err('write error: %s' % e)
# The writer thread only sleeps when there is no write
# or an error occurs
if not write:
time.sleep(1)
示例21
def whoops(err):
if reactor.running:
log.err(err)
reactor.stop()
示例22
def whoops(err):
if reactor.running:
log.err(err)
reactor.stop()
示例23
def runDispatcher(self, timeout=0.0):
if not reactor.running:
try:
reactor.run()
except KeyboardInterrupt:
raise
except:
raise PySnmpError('reactor error: %s' % ';'.join(traceback.format_exception(*sys.exc_info())))
# jobstarted/jobfinished might be okay as-is
示例24
def registerTransport(self, tDomain, transport):
if not self.loopingcall.running and self.getTimerResolution() > 0:
self.loopingcall.start(self.getTimerResolution(), now = False)
AbstractTransportDispatcher.registerTransport(
self, tDomain, transport
)
self.__transportCount = self.__transportCount + 1
示例25
def unregisterTransport(self, tDomain):
t = AbstractTransportDispatcher.getTransport(self, tDomain)
if t is not None:
AbstractTransportDispatcher.unregisterTransport(self, tDomain)
self.__transportCount = self.__transportCount - 1
# The last transport has been removed, stop the timeout
if self.__transportCount == 0 and self.loopingcall.running:
self.loopingcall.stop()
示例26
def is_running(self):
self.pings += 1
if self.deferred is not None:
raise AssertionError(
"is_running called while it's already running!")
self.deferred = Deferred()
return self.deferred
示例27
def test_die_when_broker_unavailable(self):
"""
If the broker is not running, the client should still be able to shut
down.
"""
self.log_helper.ignore_errors(
"Couldn't request that broker gracefully shut down; "
"killing forcefully.")
clock = Clock()
dog = WatchDog(clock,
broker=BoringDaemon("test-broker"),
monitor=BoringDaemon("test-monitor"),
manager=BoringDaemon("test-manager"))
# request_exit returns False when there's no broker, as tested by
# DaemonTest.test_request_exit_without_broker
dog.broker.request_exit = lambda: succeed(False)
# The manager's wait method never fires its deferred because nothing
# told it to die because the broker is dead!
manager_result = Deferred()
dog.manager.wait = lambda: manager_result
def stop():
manager_result.callback(True)
return succeed(True)
dog.manager.stop = stop
result = dog.request_exit()
return result
示例28
def test_simulate_broker_not_starting_up(self):
"""
When a daemon repeatedly dies, the watchdog gives up entirely and shuts
down.
"""
stop = []
stopped = []
self.log_helper.ignore_errors("Can't keep landscape-broker running. "
"Exiting.")
output_filename = self.makeFile("NOT RUN")
self._write_script(
"#!/bin/sh\necho RUN >> %s" % output_filename)
def got_result(result):
self.assertEqual(len(list(open(output_filename))),
MAXIMUM_CONSECUTIVE_RESTARTS)
self.assertTrue("Can't keep landscape-broker running." in
self.logfile.getvalue())
self.assertCountEqual([True], stopped)
reactor.stop = stop[0]
result = Deferred()
result.addCallback(got_result)
def mock_reactor_stop():
stop.append(reactor.stop)
reactor.stop = lambda: stopped.append(True)
reactor.callLater(0, mock_reactor_stop)
reactor.callLater(1, result.callback, None)
daemon = self.get_daemon(reactor=reactor)
daemon.BIN_DIR = self.config.bindir
daemon.start()
return result
示例29
def test_spawn_process_same_uid(self, getuid, getgid):
"""
If the daemon is specified to run as root, and the watchdog is running
as root, no uid or gid switching will occur.
"""
self._write_script("#!/bin/sh")
reactor = mock.Mock()
daemon = self.get_daemon(reactor=reactor, username="root")
daemon.BIN_DIR = self.config.bindir
daemon.start()
reactor.spawnProcess.assert_called_with(
mock.ANY, mock.ANY, args=mock.ANY, env=mock.ANY, uid=None,
gid=None)
示例30
def test_start_service_exits_when_already_running(
self, mock_bootstrap_list, mock_reactor):
self.log_helper.ignore_errors(
"ERROR: The following daemons are already running: program-name")
service = WatchDogService(self.configuration)
service.watchdog = mock.Mock()
service.watchdog.check_running.return_value = succeed([StubDaemon()])
result = service.startService()
self.assertEqual(service.exit_code, 1)
mock_bootstrap_list.bootstrap.assert_called_once_with(
data_path=self.data_path, log_dir=self.log_dir)
service.watchdog.check_running.assert_called_once_with()
self.assertTrue(mock_reactor.crash.called)
return result