def run(self):
'''
Called by twisted
'''
# load initial config
self.refresh_config()
if self.config is None:
logging.critical("cannot start due to error in config file")
return
# refresh and check status every event_period seconds
self.refresh_task = task.LoopingCall(self.refresh_loop)
refresh_deferred = self.refresh_task.start(self.config['event_period'], now=False)
refresh_deferred.addErrback(errorCallback)
# setup server for receiving blinded counts from the DC nodes and key shares from the SK nodes
listen_port = self.config['listen_port']
key_path = self.config['key']
cert_path = self.config['cert']
ssl_context = ssl.DefaultOpenSSLContextFactory(key_path, cert_path)
logging.info("Tally Server listening on port {}".format(listen_port))
reactor.listenSSL(listen_port, self, ssl_context)
reactor.run()
python类LoopingCall()的实例源码
def handle_checkin_event(self, event_type, event_payload):
if event_type == "CHECKIN":
parts = event_payload.split()
if len(parts) == 1:
period = int(parts[0])
# we have to store the checkin task in the factory,
# because the protocol is re-created on every connection
checkin_task = self.factory.get_checkin_task()
if checkin_task is not None and checkin_task.running:
checkin_task.stop()
self.factory.set_checkin_task(None)
checkin_task = task.LoopingCall(self.factory.do_checkin)
self.factory.set_checkin_task(checkin_task)
# we ignore any errors from do_checkin, see bug #47
checkin_deferred = checkin_task.start(period, now=False)
checkin_deferred.addErrback(errorCallback)
self.sendLine("CHECKIN SUCCESS")
self.protocol_succeeded()
return True
return False
def __init__(self, settings, crawl_keypair_filename=None, dispersy_port=-1):
if Tunnel.__single:
raise RuntimeError("Tunnel is singleton")
Tunnel.__single = self
self.settings = settings
self.should_run = True
self.crawl_keypair_filename = crawl_keypair_filename
self.dispersy_port = dispersy_port
self.crawl_data = defaultdict(lambda: [])
self.crawl_message = {}
self.current_stats = [0, 0, 0]
self.history_stats = deque(maxlen=180)
self.start_tribler()
self.dispersy = self.session.lm.dispersy
self.multichain_community = None
self.community = None
self.clean_messages_lc = LoopingCall(self.clean_messages)
self.clean_messages_lc.start(1800)
self.build_history_lc = LoopingCall(self.build_history)
self.build_history_lc.start(60, now=True)
def drive_to_resolution(self):
"""
Note: this overrides the method defined in ResolutionStrategyMixin
"""
if self.master_uid == self.network_uid:
self.stop_driving()
if self.paxos.proposal_id.number == 1:
self.send_accept(self.paxos.proposal_id, self.paxos.proposed_value)
else:
self.paxos.prepare()
self.retransmit_task = task.LoopingCall( lambda : self.send_prepare(self.paxos.proposal_id) )
self.retransmit_task.start( self.retransmit_interval/1000.0, now=False )
else:
super(DedicatedMasterStrategyMixin,self).drive_to_resolution()
def main():
# Setup the blockchain
blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
Blockchain.RegisterBlockchain(blockchain)
dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
dbloop.start(.1)
NodeLeader.Instance().Start()
# Start a thread with custom code
d = threading.Thread(target=custom_background_code)
d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit
d.start()
# Run all the things (blocking call)
reactor.run()
logger.info("Shutting down.")
def main():
# Setup the blockchain
blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
Blockchain.RegisterBlockchain(blockchain)
dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
dbloop.start(.1)
NodeLeader.Instance().Start()
# Disable smart contract events for external smart contracts
settings.set_log_smart_contract_events(False)
# Start a thread with custom code
d = threading.Thread(target=custom_background_code)
d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit
d.start()
# Hook up Klein API to Twisted reactor
endpoint_description = "tcp:port=%s:interface=localhost" % API_PORT
endpoint = endpoints.serverFromString(reactor, endpoint_description)
endpoint.listen(Site(app.resource()))
# Run all the things (blocking call)
logger.info("Everything setup and running. Waiting for events...")
reactor.run()
logger.info("Shutting down.")
def main():
# Setup the blockchain
blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
Blockchain.RegisterBlockchain(blockchain)
dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
dbloop.start(.1)
NodeLeader.Instance().Start()
# Disable smart contract events for external smart contracts
settings.set_log_smart_contract_events(False)
# Start a thread with custom code
d = threading.Thread(target=custom_background_code)
d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit
d.start()
# Run all the things (blocking call)
logger.info("Everything setup and running. Waiting for events...")
reactor.run()
logger.info("Shutting down.")
def startup(urls, loop_times, stats_man, ep_man):
stats_man.initialize_client_list(ep_man.endpoints)
# start loop to periodically collect and report stats
stats_loop = task.LoopingCall(stats_man.stats_loop)
stats_loop_deferred = stats_loop.start(loop_times["stats"])
stats_loop_deferred.addCallback(stats_man.stats_loop_done)
stats_loop_deferred.addErrback(stats_man.stats_loop_failed)
# start loop to periodically update the list of validator endpoints
# and call WorkManager.update_client_list
ep_loop = task.LoopingCall(ep_man.update_endpoint_discovery,
stats_man.update_client_list)
ep_loop_deferred = ep_loop.start(loop_times["endpoint"], now=False)
ep_loop_deferred.addCallback(ep_man.update_endpoint_done)
ep_loop_deferred.addErrback(ep_man.update_endpoint_failed)
def init_linuxcnc(self):
self.stat = linuxcnc.stat()
self.command = linuxcnc.command()
self.error_channel = linuxcnc.error_channel()
try:
self.stat.poll()
except linuxcnc.error as e:
self.error('Unable to poll linuxcnc, is it running?')
self.error('Error message: {}'.format(e))
return
self.serial = self.stat.echo_serial_number
self.cmd_serial = self.serial + 1
self.error_channel.poll()
self.last_interp_state = self.stat.interp_state
self.poll_task = task.LoopingCall(self.poll_linuxcnc)
self.poll_task.start(0.1)
self.state = 'READY'
def __init__(self, feedurl, pollinterval=3600):
"""
@type feedurl: string
@param feedurl: The Atom feed URL of the GoogleCode repo
(e.g. http://code.google.com/feeds/p/ostinato/hgchanges/basic)
@type pollinterval: int
@param pollinterval: The time (in seconds) between queries for
changes (default is 1 hour)
"""
self.feedurl = feedurl
self.branch = None
self.pollinterval = pollinterval
self.lastChange = None
self.loop = LoopingCall(self.poll)
def send_tx4_sig(self):
"""Send partial signature on TX4 (out of TX0)
to Carol for her to complete sign and broadcast.
"""
utxo_in = self.tx0.txid + ":" + str(self.tx0.pay_out_index)
self.tx4 = CoinSwapTX45.from_params(self.coinswap_parameters.pubkeys["key_2_2_AC_0"],
self.coinswap_parameters.pubkeys["key_2_2_AC_1"],
utxo_in=utxo_in,
destination_address=self.coinswap_parameters.output_addresses["tx4_address"],
destination_amount=self.coinswap_parameters.tx4_amounts["carol"],
carol_change_address=None,
carol_change_amount=None)
self.tx4.sign_at_index(self.keyset["key_2_2_AC_0"][0], 0)
sig = self.tx4.signatures[0][0]
self.send(sig, self.tx5.txid)
self.tx4broadcast_counter = 0
self.loop_tx4 = task.LoopingCall(self.wait_for_tx4_confirmation)
self.loop_tx4.start(3.0)
return (True, "TX4 signature sent.")
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'])
def start(self, netserver):
"""Start the application interface
Args:
netserver (NetServer): The LoRa network server
Returns True on success, False otherwise
"""
self.netserver = netserver
self.polling = False
if not hasattr(self, 'task'):
self.task = task.LoopingCall(self._pollInboundMessages)
# Setup the looping task to query for messages
self.task.start(self.poll_interval * 60)
# Set the running flag
self.started = True
returnValue(True)
yield
def syncWalletUpdate(self, fast, restart_cb=None):
if restart_cb:
fast=False
#Special syncing condition for Electrum
iselectrum = jm_single().config.get("BLOCKCHAIN",
"blockchain_source") == "electrum-server"
if iselectrum:
jm_single().bc_interface.synctype = "with-script"
jm_single().bc_interface.sync_wallet(self.wallet, fast=fast,
restart_cb=restart_cb)
if iselectrum:
#sync_wallet only initialises, we must manually call its entry
#point here (because we can't use connectionMade as a trigger)
jm_single().bc_interface.sync_addresses(self.wallet)
self.wait_for_sync_loop = task.LoopingCall(self.updateWalletInfo)
self.wait_for_sync_loop.start(0.2)
else:
self.updateWalletInfo()
client_protocol.py 文件源码
项目:joinmarket-clientserver
作者: JoinMarket-Org
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def confirm_callback(self, txd, txid, confirmations):
#find the offer for this tx
offerinfo = None
for k,v in self.finalized_offers.iteritems():
#Tx considered defined by its output set
if v["txd"]["outs"] == txd["outs"]:
offerinfo = v
break
if not offerinfo:
jlog.info("Failed to find notified unconfirmed transaction: " + txid)
return
jm_single().bc_interface.wallet_synced = False
jm_single().bc_interface.sync_unspent(self.client.wallet)
jlog.info('tx in a block: ' + txid)
self.wait_for_sync_loop = task.LoopingCall(self.modify_orders, offerinfo,
confirmations, txid)
self.wait_for_sync_loop.start(2.0)
blockchaininterface.py 文件源码
项目:joinmarket-clientserver
作者: JoinMarket-Org
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def __init__(self, jsonRpc, network):
super(BitcoinCoreInterface, self).__init__()
self.jsonRpc = jsonRpc
self.fast_sync_called = False
blockchainInfo = self.jsonRpc.call("getblockchaininfo", [])
actualNet = blockchainInfo['chain']
netmap = {'main': 'mainnet', 'test': 'testnet', 'regtest': 'regtest'}
if netmap[actualNet] != network:
raise Exception('wrong network configured')
self.txnotify_fun = []
self.wallet_synced = False
#task.LoopingCall objects that track transactions, keyed by txids.
#Format: {"txid": (loop, unconfirmed true/false, confirmed true/false,
#spent true/false), ..}
self.tx_watcher_loops = {}
def __init__(self, host=defaultHost, port=4400, redisPort=6379, neo4jPort=7474, initialKey=None):
#self.protocol = Peer(self)
self.host = host
self.port = port
self.users = {} # maps user names to Chat instances
self.redisPort = redisPort
self.neo4jPort = neo4jPort
if initialKey: # need test case
self.commandKeys.append(initialKey)
# self.redis.addToKeys(initialKey)
"""Add loops to factory? why not add loops to main reactor??"""
defly = task.deferLater(reactor, 10, self.ping)
defly.addErrback(whoops)
#reactor.callLater(2, redis_test)
#task.deferLater(reactor, 60, hiya).addCallback(lambda _: reactor.stop())
loop = task.LoopingCall(peerBeat)
loopDeferred = loop.start(15.0)
loopDeferred.addCallback(peerSuccess)
loopDeferred.addErrback(peerFailure)
# pylint: disable=no-self-use
def __init__(self, task_id, cid, vservice):
"""Constructor"""
self._task_id = task_id
self._cid = cid
self._vservice = vservice
assert isinstance(self._vservice, VService)
self._conn = vservice.get_conn_by_cid(cid)
# pri attrs
self._result = None
self._ack_flag = False
self._STATE = client.TASK_STATE_PENDING
self._retry_times = 0
self._waitingack = False
#
# looping call to ack
#
self._loopingcall_ack = LoopingCall(self._checking_ack)
#----------------------------------------------------------------------
def register_task(self, name, task, delay=None, value=None, interval=None):
"""
Register a task so it can be canceled at shutdown time or by name.
"""
assert not self.is_pending_task_active(name), name
assert isinstance(task, (Deferred, DelayedCall, LoopingCall)), (task, type(task) == type(Deferred))
if delay is not None:
if isinstance(task, Deferred):
if value is None:
raise ValueError("Expecting value to fire the Deferred with")
dc = self._reactor.callLater(delay, task.callback, value)
elif isinstance(task, LoopingCall):
if interval is None:
raise ValueError("Expecting interval for delayed LoopingCall")
dc = self._reactor.callLater(delay, task.start, interval)
else:
raise ValueError("Expecting Deferred or LoopingCall if task is delayed")
task = (dc, task)
self._maybe_clean_task_list()
with self._task_lock:
self._pending_tasks[name] = task
return task
def _get_isactive_stopper(self, name):
"""
Return a boolean determining if a task is active and its cancel/stop method if the task is registered.
"""
task = self._pending_tasks.get(name, None)
def do_get(task):
if isinstance(task, Deferred):
# Have in mind that any deferred in the pending tasks list should have been constructed with a
# canceller function.
return not task.called, getattr(task, 'cancel', None)
elif isinstance(task, DelayedCall):
return task.active(), task.cancel
elif isinstance(task, LoopingCall):
return task.running, task.stop
elif isinstance(task, tuple):
if task[0].active():
return task[0].active(), task[0].cancel
else:
return do_get(task[1])
else:
return False, None
return do_get(task)
def test_delayed_looping_call_register_wait_and_cancel(self):
self.assertFalse(self.tm.is_pending_task_active("test"))
lc = LoopingCall(self.count)
lc.clock = self.tm._reactor
self.tm.register_task("test", lc, delay=1, interval=1)
self.assertTrue(self.tm.is_pending_task_active("test"))
# After one second, the counter has increased by one and the task is still active.
self.tm._reactor.advance(1)
self.assertEquals(1, self.counter)
self.assertTrue(self.tm.is_pending_task_active("test"))
# After one more second, the counter should be 2
self.tm._reactor.advance(1)
self.assertEquals(2, self.counter)
# After canceling the task the counter should stop increasing
self.tm.cancel_pending_task("test")
self.assertFalse(self.tm.is_pending_task_active("test"))
self.tm._reactor.advance(10)
self.assertEquals(2, self.counter)
def stop(self):
"""
Cleanup our LoopingCall and any outstanding deferreds...
"""
self.stopping = True
# Cancel any outstanding request to our client
if self._batch_send_d:
self._batch_send_d.cancel()
# Do we have to worry about our looping call?
if self.batch_every_t is not None:
# Stop our looping call, and wait for the deferred to be called
if self.sendLooper is not None:
self.sendLooper.stop()
# Make sure requests that wasn't cancelled above are now
self._cancel_outstanding()
# # Private Methods # #
def __init__(self, factory):
self.tc = TrustChain()
self.factory = factory
self.collect_rubbish_lc = task.LoopingCall(self._collect_rubbish)
self.collect_rubbish_lc.start(5, False).addErrback(my_err_back)
self.log_tx_count_lc = task.LoopingCall(self._log_info)
self.log_tx_count_lc.start(5, False).addErrback(my_err_back)
self.bootstrap_lc = None
self.random_node_for_tx = False
# attributes below are states for building new CP blocks
self.round_states = defaultdict(RoundState)
self._initial_promoters = []
random.seed()
def initServer(self):
self.password = os.environ['LABRADPASSWORD']
self.name = socket.gethostname() + ' Single Channel Lock Server'
self.set_frequency = 658.116220
self.timer = 0.1
self.low_rail = 0
self.high_rail =30.0
self.p_gain = 1e-3 # Gain of piezo controller is 15V/V
self.i_gain = 1e-5 # Not using now since lock is pretty good
self.integral = 0 # to use for I
self.prev_output = 0.0
self.dac_chan = 7
self.lasers = multiplexer_config.info
self.laser_chan = '455nm'
self.lc = LoopingCall(self.loop)
self.output = 0.0
self.connect()
def connect(self):
"""
Connect to MQTT broker.
"""
# TODO: This is currently done synchronous which could have issues in timeout situations
# because it would block other subsystems.
# => Check if we can do asynchronous connection establishment.
self.client = mqtt.Client(client_id=self.name, clean_session=True, userdata={'foo': 'bar'})
if self.broker_username:
self.client.username_pw_set(self.broker_username, self.broker_password)
self.client.on_connect = lambda *args: reactor.callFromThread(self.on_connect, *args)
self.client.on_message = lambda *args: reactor.callFromThread(self.on_message, *args)
self.client.on_log = lambda *args: reactor.callFromThread(self.on_log, *args)
# Connect with retry
self.connect_loop = LoopingCall(self.connect_with_retry)
self.connect_loop.start(self.retry_interval, now=True)
def _checkLoop(self):
"""
Start or stop a C{LoopingCall} based on whether there are readers and
writers.
"""
if self._readers or self._writers:
if self._loop is None:
from twisted.internet.task import LoopingCall, _EPSILON
self._loop = LoopingCall(self.iterate)
self._loop.clock = self._reactor
# LoopingCall seems unhappy with timeout of 0, so use very
# small number:
self._loop.start(_EPSILON, now=False)
elif self._loop:
self._loop.stop()
self._loop = None
def loopUntil(predicate, interval=0):
"""
Poor excuse for an event notification helper. This polls a condition and
calls back a Deferred when it is seen to be true.
Do not use this function.
"""
from twisted.internet import task
d = defer.Deferred()
def check():
res = predicate()
if res:
d.callback(res)
call = task.LoopingCall(check)
def stop(result):
call.stop()
return result
d.addCallback(stop)
d2 = call.start(interval)
d2.addErrback(d.errback)
return d
def test_reset(self):
"""
Test that L{LoopingCall} can be reset.
"""
ran = []
def foo():
ran.append(None)
c = task.Clock()
lc = TestableLoopingCall(c, foo)
lc.start(2, now=False)
c.advance(1)
lc.reset()
c.advance(1)
self.assertEqual(ran, [])
c.advance(1)
self.assertEqual(ran, [None])
def test_deferredDeprecation(self):
"""
L{LoopingCall.deferred} is deprecated.
"""
loop = task.LoopingCall(lambda: None)
loop.deferred
message = (
'twisted.internet.task.LoopingCall.deferred was deprecated in '
'Twisted 16.0.0; '
'please use the deferred returned by start() instead'
)
warnings = self.flushWarnings([self.test_deferredDeprecation])
self.assertEqual(1, len(warnings))
self.assertEqual(DeprecationWarning, warnings[0]['category'])
self.assertEqual(message, warnings[0]['message'])
def __init__(self, *a):
Output.__init__(self, *a)
self.events = []
self.timer = task.LoopingCall(self.tick)
self.inter = float(self.config.get('interval', 1.0)) # tick interval
self.maxsize = int(self.config.get('maxsize', 250000))
self.user = self.config.get('user')
self.password = self.config.get('password')
self.client = None
self.url = self.config.get('url', 'http://localhost:4242')
maxrate = int(self.config.get('maxrate', 100))
if maxrate > 0:
self.queueDepth = int(maxrate * self.inter)
else:
self.queueDepth = None