本文整理汇总了Python中twisted.application.internet.TimerService.startService方法的典型用法代码示例。如果您正苦于以下问题:Python TimerService.startService方法的具体用法?Python TimerService.startService怎么用?Python TimerService.startService使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.application.internet.TimerService
的用法示例。
在下文中一共展示了TimerService.startService方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: startService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
def startService(self):
"""
Start this service. This will start buckets partitioning
"""
self.kz_partition = self.kz_client.SetPartitioner(
self.zk_partition_path, set=set(self.buckets),
time_boundary=self.time_boundary)
TimerService.startService(self)
示例2: test_pickleTimerServiceNotPickleLoopFinished
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
def test_pickleTimerServiceNotPickleLoopFinished(self):
"""
When pickling L{internet.TimerService}, it won't pickle
L{internet.TimerService._loopFinished}.
"""
# We need a pickleable callable to test pickling TimerService. So we
# can't use self.timer
timer = TimerService(1, fakeTargetFunction)
timer.startService()
dumpedTimer = pickle.dumps(timer)
timer.stopService()
loadedTimer = pickle.loads(dumpedTimer)
nothing = object()
value = getattr(loadedTimer, "_loopFinished", nothing)
self.assertIdentical(nothing, value)
示例3: stopService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
def stopService(self):
self.command_helper.de_register()
self.command_helper.remove_responder(self.complete_command, self.complete)
self.command_helper.remove_responder(self.failed_command, self.failed)
TimerService.startService(self)
示例4: startService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
def startService(self):
self.command_helper.responder(self.complete_command)(self.complete)
self.command_helper.responder(self.failed_command)(self.failed)
self.command_helper.register()
TimerService.startService(self)
示例5: MetricsService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
class MetricsService(Service, object):
"""
Service collects metrics on continuous basis
"""
def __init__(self, reactor, config, log, clock=None, collect=None):
"""
Initialize the service by connecting to Cassandra and setting up
authenticator
:param reactor: Twisted reactor for connection purposes
:param dict config: All the config necessary to run the service.
Comes from config file
:param IReactorTime clock: Optional reactor for timer purpose
"""
self._client = connect_cass_servers(reactor, config['cassandra'])
self.log = log
self.reactor = reactor
self._divergent_groups = {}
self.divergent_timeout = get_in(
['metrics', 'divergent_timeout'], config, 3600)
self._service = TimerService(
get_in(['metrics', 'interval'], config, default=60),
collect or self.collect,
reactor,
config,
self.log,
client=self._client,
authenticator=generate_authenticator(reactor, config['identity']))
self._service.clock = clock or reactor
@defer.inlineCallbacks
def collect(self, *a, **k):
try:
metrics = yield collect_metrics(*a, **k)
self._divergent_groups, to_log = unchanged_divergent_groups(
self.reactor, self._divergent_groups, self.divergent_timeout,
metrics)
for group, duration in to_log:
self.log.err(
ValueError(""), # Need to give an exception to log err
("Group {group_id} of {tenant_id} remains diverged "
"and unchanged for {divergent_time}"),
tenant_id=group.tenant_id, group_id=group.group_id,
desired=group.desired, actual=group.actual,
pending=group.pending,
divergent_time=str(timedelta(seconds=duration)))
except Exception:
self.log.err(None, "Error collecting metrics")
def startService(self):
"""
Start this service by starting internal TimerService
"""
Service.startService(self)
return self._service.startService()
def stopService(self):
"""
Stop service by stopping the timerservice and disconnecting cass client
"""
Service.stopService(self)
d = self._service.stopService()
return d.addCallback(lambda _: self._client.disconnect())
示例6: AcmeIssuingService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
#.........这里部分代码省略.........
Key(key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()))]
def answer_and_poll(authzr):
def got_challenge(stop_responding):
return (
poll_until_valid(authzr, self._clock, client)
.addBoth(tap(lambda _: stop_responding())))
return (
answer_challenge(authzr, client, self._responders)
.addCallback(got_challenge))
def got_cert(certr):
objects.append(
Certificate(
x509.load_der_x509_certificate(
certr.body, default_backend())
.public_bytes(serialization.Encoding.PEM)))
return certr
def got_chain(chain):
for certr in chain:
got_cert(certr)
log.info(
'Received certificate for {server_name!r}.',
server_name=server_name)
return objects
return (
client.request_challenges(fqdn_identifier(server_name))
.addCallback(answer_and_poll)
.addCallback(lambda ign: client.request_issuance(
CertificateRequest(
csr=csr_for_names([server_name], key))))
.addCallback(got_cert)
.addCallback(client.fetch_chain)
.addCallback(got_chain)
.addCallback(partial(self.cert_store.store, server_name)))
def _ensure_registered(self):
"""
Register if needed.
"""
if self._registered:
return succeed(None)
else:
return self._with_client(self._register)
def _register(self, client):
"""
Register and agree to the TOS.
"""
def _registered(regr):
self._regr = regr
self._registered = True
regr = messages.NewRegistration.from_data(email=self._email)
return (
client.register(regr)
.addCallback(client.agree_to_tos)
.addCallback(_registered))
def when_certs_valid(self):
"""
Get a notification once the startup check has completed.
When the service starts, an initial check is made immediately; the
deferred returned by this function will only fire once reissue has been
attempted for any certificates within the panic interval.
.. note:: The reissue for any of these certificates may not have been
successful; the panic callback will be invoked for any certificates
in the panic interval that failed reissue.
:rtype: ``Deferred``
:return: A deferred that fires once the initial check has resolved.
"""
if self.ready:
return succeed(None)
d = Deferred()
self._waiting.append(d)
return d
def startService(self):
Service.startService(self)
self._registered = False
self._timer_service = TimerService(
self.check_interval.total_seconds(), self._check_certs)
self._timer_service.clock = self._clock
self._timer_service.startService()
def stopService(self):
Service.stopService(self)
self.ready = False
self._registered = False
for d in list(self._waiting):
d.cancel()
self._waiting = []
return self._timer_service.stopService()
示例7: TimerServiceTests
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
class TimerServiceTests(TestCase):
"""
Tests for L{twisted.application.internet.TimerService}.
@type timer: L{TimerService}
@ivar timer: service to test
@type clock: L{task.Clock}
@ivar clock: source of time
@type deferred: L{Deferred}
@ivar deferred: deferred returned by L{TimerServiceTests.call}.
"""
def setUp(self):
"""
Set up a timer service to test.
"""
self.timer = TimerService(2, self.call)
self.clock = self.timer.clock = task.Clock()
self.deferred = Deferred()
def call(self):
"""
Function called by L{TimerService} being tested.
@returns: C{self.deferred}
@rtype: L{Deferred}
"""
return self.deferred
def test_startService(self):
"""
When L{TimerService.startService} is called, it marks itself
as running, creates a L{task.LoopingCall} and starts it.
"""
self.timer.startService()
self.assertTrue(self.timer.running, "Service is started")
self.assertIsInstance(self.timer._loop, task.LoopingCall)
self.assertIdentical(self.clock, self.timer._loop.clock)
self.assertTrue(self.timer._loop.running, "LoopingCall is started")
def test_startServiceRunsCallImmediately(self):
"""
When L{TimerService.startService} is called, it calls the function
immediately.
"""
result = []
self.timer.call = (result.append, (None,), {})
self.timer.startService()
self.assertEqual([None], result)
def test_startServiceUsesGlobalReactor(self):
"""
L{TimerService.startService} uses L{internet._maybeGlobalReactor} to
choose the reactor to pass to L{task.LoopingCall}
uses the global reactor.
"""
otherClock = task.Clock()
def getOtherClock(maybeReactor):
return otherClock
self.patch(internet, "_maybeGlobalReactor", getOtherClock)
self.timer.startService()
self.assertIdentical(otherClock, self.timer._loop.clock)
def test_stopServiceWaits(self):
"""
When L{TimerService.stopService} is called while a call is in progress.
the L{Deferred} returned doesn't fire until after the call finishes.
"""
self.timer.startService()
d = self.timer.stopService()
self.assertNoResult(d)
self.assertEqual(True, self.timer.running)
self.deferred.callback(object())
self.assertIdentical(self.successResultOf(d), None)
def test_stopServiceImmediately(self):
"""
When L{TimerService.stopService} is called while a call isn't in progress.
the L{Deferred} returned has already been fired.
"""
self.timer.startService()
self.deferred.callback(object())
d = self.timer.stopService()
self.assertIdentical(self.successResultOf(d), None)
def test_failedCallLogsError(self):
"""
When function passed to L{TimerService} returns a deferred that errbacks,
the exception is logged, and L{TimerService.stopService} doesn't raise an error.
"""
self.timer.startService()
#.........这里部分代码省略.........
示例8: AcmeIssuingService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
#.........这里部分代码省略.........
def _issue_cert(self, server_name):
"""
Issue a new cert for a particular name.
"""
key = self._generate_key()
objects = [
Key(key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()))]
def answer_and_poll(authzr):
def got_challenge(r):
responder, response = r
def stop_responding(result):
return responder.stop_responding(response)
return (
poll_until_valid(authzr, self._clock, self._client)
.addBoth(tap(stop_responding)))
return (
answer_challenge(authzr, self._client, self._responders)
.addCallback(got_challenge))
def got_cert(certr):
objects.append(
Certificate(
x509.load_der_x509_certificate(
certr.body, default_backend())
.public_bytes(serialization.Encoding.PEM)))
return certr
def got_chain(chain):
for certr in chain:
got_cert(certr)
return objects
return (
self._client.request_challenges(fqdn_identifier(server_name))
.addCallback(answer_and_poll)
.addCallback(lambda ign: self._client.request_issuance(
CertificateRequest(
csr=csr_for_names([server_name], key))))
.addCallback(got_cert)
.addCallback(self._client.fetch_chain)
.addCallback(got_chain)
.addCallback(partial(self.cert_store.store, server_name)))
def _register(self):
"""
Register if needed.
"""
def _registered(ign):
self._registered = True
if self._registered:
return succeed(None)
else:
return (
self._client.register()
.addCallback(self._client.agree_to_tos)
.addCallback(_registered))
def when_certs_valid(self):
"""
Get a notification once the startup check has completed.
When the service starts, an initial check is made immediately; the
deferred returned by this function will only fire once reissue has been
attempted for any certificates within the panic interval.
.. note:: The reissue for any of these certificates may not have been
successful; the panic callback will be invoked for any certificates
in the panic interval that failed reissue.
:rtype: ``Deferred``
:return: A deferred that fires once the initial check has resolved.
"""
if self.ready:
return succeed(None)
d = Deferred()
self._waiting.append(d)
return d
def startService(self):
Service.startService(self)
self._registered = False
self._timer_service = TimerService(
self.check_interval.total_seconds(), self._check_certs)
self._timer_service.clock = self._clock
self._timer_service.startService()
def stopService(self):
Service.stopService(self)
self.ready = False
self._registered = False
for d in list(self._waiting):
d.cancel()
self._waiting = []
return self._timer_service.stopService()
示例9: BackupScheduler
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
class BackupScheduler(object):
"""The container for the backup schedules.
Internally, it keeps the list of schedules in always-sorted state;
they are sorted by the expected time of fire (then by UUID;
but two schedules with the same UUID always match).
@todo: The scheduler must be dynamically updated:
1. if some "backup scheduled" settings are changed;
2. if some "timezone" setting is changed.
@note: schedule support is disabled, so this class is not used anymore.
"""
__slots__ = ('server_process', 'lock',
'__schedules', '__schedules_by_host_uuid',
'__schedule_check_timer', '__last_reread_from_db')
@exceptions_logged(logger)
def __init__(self, server_process):
assert isinstance(server_process, ServerProcess), \
repr(server_process)
self.server_process = server_process
self.lock = RLock()
self.__schedule_check_timer = \
TimerService(BACKUP_SCHEDULES_CHECK_PERIOD.total_seconds(),
self.__on_schedule_check_timer)
self.reread_cache()
def __repr__(self):
return u'<BackupScheduler: {} schedule(s)>'\
.format(len(self.__schedules))
@property
def app(self):
"""
@rtype: NodeApp
"""
return self.server_process.app
@exceptions_logged(logger)
def __reset(self):
self.__schedules = []
self.__schedules_by_host_uuid = defaultdict(set)
@exceptions_logged(logger)
def start(self):
self.__schedule_check_timer.startService()
@exceptions_logged(logger)
def stop(self):
"""
@todo: It is nowhere stopped at the moment, should it be?
"""
self.__schedule_check_timer.stopService()
@contract_epydoc
def add(self, schedule):
"""
@type schedule: BackupSchedule
"""
with self.lock:
assert schedule not in self.__schedules, repr(schedule)
bisect.insort(self.__schedules, schedule)
self.__schedules_by_host_uuid[schedule.host_uuid].add(schedule)
assert self.__schedules == sorted(self.__schedules), 'Not sorted!'
@contract_epydoc
def remove(self, schedule):
"""
@type schedule: BackupSchedule
"""
with self.lock:
assert schedule in self.__schedules, repr(schedule)
index = bisect.bisect(self.__schedules, schedule) - 1
assert schedule == self.__schedules[index], \
(index, schedule, self.__schedules)
del self.__schedules[index]
self.__schedules_by_host_uuid[schedule.host_uuid].remove(schedule)
assert self.__schedules == sorted(self.__schedules), 'Not sorted!'
@contract_epydoc
def get_schedules_by_host_uuid(self, host_uuid):
"""
@type host_uuid: UUID
@rtype: frozenset
"""
return frozenset(self.__schedules_by_host_uuid[host_uuid])
#.........这里部分代码省略.........
示例10: startService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
def startService(self):
log.msg("Starting up script runner service ...")
return TimerService.startService(self)
示例11: TrafficMeter
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
class TrafficMeter(object):
"""
Traffic meter, measuring all the traffic to some direction.
@note: At the moment, restart of the service (after it has been started)
is not supported.
@ivar __start_time: the time of the first registered traffic "tick".
@type __start_time: datetime
@ivar __ticks: the sequence of TrafficTick objects
(always sorted by the time, increasing!)
registering each successfully passed bunch of bytes.
@invariant: consists_of(self.__ticks, TrafficTick)
"""
__slots__ = ('__direction_incoming', '__total_bytes', '__ticks',
'__ticks_lock', '__start_time', '__timer_service',
'__started')
def __init__(self, is_direction_incoming):
"""
@param is_direction_incoming: whether the measured direction
is incoming (otherwise outgoing).
@type is_direction_incoming: bool
"""
self.__direction_incoming = is_direction_incoming
self.__total_bytes = 0
self.__ticks = deque()
self.__ticks_lock = Lock()
self.__start_time = None
self.__timer_service = TimerService(
TRAFFIC_NOTIFICATION_PERIOD.total_seconds(),
self.__on_timer)
self.__started = False
@property
def started(self):
return self.__started
def start(self):
"""
Start monitoring and reporting.
"""
with self.__ticks_lock:
assert not self.__started
self.__timer_service.startService()
self.__started = True
logger.debug('%s traffic meter started', self._name)
@property
def _name(self):
return 'Inbound' if self.__direction_incoming else 'Outbound'
def stop(self):
"""
Stop monitoring and reporting.
"""
with self.__ticks_lock:
assert self.__started
self.__started = False
self.__timer_service.stopService()
logger.debug('%s traffic meter stopped', self._name)
@exceptions_logged(logger)
def __on_timer(self):
_now = datetime.utcnow()
_oldest_time_to_consider = _now - THROUGHPUT_SMA_PERIOD
# Even if the timer is started, we don't report throughput
# until the first ticks are registered.
if self.__ticks:
with self.__ticks_lock:
# Remove (leftmost) ticks which are too old to consider.
while (self.__ticks and
self.__ticks[0].time < _oldest_time_to_consider):
self.__ticks.popleft()
# All the remaining ticks now serve for the throughput
# calculation, and comprise the current SMA window.
sma_kilobytes = sum(i.bytes for i in self.__ticks) / 1000.0
# (btw, done with the lock, remaining calculation
# can be unlocked)
# How much time passed since the traffic meter has been started?
uptime_td = TimeDeltaEx.from_timedelta(_now - self.__start_time)
# If the meter has just been started,
# we calculate the throughput dividing to the actual uptime
# rather than the period window.
sma_td = min(uptime_td, THROUGHPUT_SMA_PERIOD)
sma_seconds = sma_td.in_seconds()
kBps = sma_kilobytes / sma_seconds
#.........这里部分代码省略.........
示例12: aLongMethod
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
def aLongMethod(filename, file, sp, protocol):
import time
time.sleep(2)
protocol.message(b"hello!!!")
#flen = os.path.getsize(filename)
#if sp > 0 and sp < flen:
# myfile.seek(sp+1)
# for line in myfile:
# protocol.send(line);
# myfile.seek(0, os.SEEK_END)
# sp = myfile.tell()
reactor.callInThread(aLongMethod, filename, file, sp, protocol)
factory = Factory()
factory.clients = []
factory.protocol = FlowPush
s = TimerService(2, watch)
s.startService()
reactor.listenTCP(8080, factory)
#other = ReadThread()
#other.start()
print "Flowpussh server started!"
FLOWFILE = "/root/flows.txt"
myfile = open(FLOWFILE, "rt")
sp = os.path.getsize(FLOWFILE)
#reactor.callInThread(aLongMethod, FLOWFILE, myfile, sp, factory.protocol)
reactor.run()
示例13: FeedPollerService
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
class FeedPollerService(Service):
"""
Polls AtomHopper feeds
"""
def __init__(self, agent, url, event_listeners, interval=DEFAULT_INTERVAL,
state_store=None,
TimerService=TimerService, coiterate=coiterate):
"""
:param agent: a :class:`twisted.web.client.Agent` to use to poll
:param url: the url to poll
:param event_listeners: listeners that handle a particular event
:type event_listeners: `iterable` of `callables` that take an event
as an argument
:param interval: how often to poll, given in seconds - defaults to 10
:type interval: ``int`` or ``float``
:param state_store: where to store the current polling state
:type state_store: :class:`otter.indexer.state.IStateStore` provider
:param TimerService: factory (not instance) that produces something
like a :class:`twisted.application.internet.TimerService` -
defaults to :class:`twisted.application.internet.TimerService`
(this parameter is mainly used for dependency injection for
testing)
:type TimerService: ``callable``
:param coiterate: function that is used to coiterate tasks - defaults
to :func:`twisted.internet.task.coiterate` - (this parameter is
mainly used for dependency injection for testing)
:type coiterate: ``callable``
"""
self._url = url
self._interval = interval
self._timer_service = TimerService(interval, self._do_poll)
self._next_url = None
self._agent = agent
self._state_store = state_store or DummyStateStore()
self._event_listeners = event_listeners
self._poll_timer = timer('FeedPollerService.poll.{0}'.format(url))
self._fetch_timer = timer('FeedPollerService.fetch.{0}'.format(url))
self._coiterate = coiterate
def startService(self):
"""
Start the feed polling service - called by the twisted
application when starting up
"""
self._timer_service.startService()
def stopService(self):
"""
Stop the feed polling service - called by the twisted
application when shutting down
:return: ``Deferred``
"""
return self._timer_service.stopService()
def _fetch(self, url):
"""
Get atom feed from AtomHopper url
"""
def _parse(data):
e = parse(data)
return e
def _gotResponse(resp):
br = _BodyReceiver()
resp.deliverBody(br)
return br.finish
log.msg(format="Fetching url: %(url)r", url=url)
d = self._agent.request('GET', url, Headers({}), None)
d.addCallback(_gotResponse)
d.addCallback(_parse)
return d
def _do_poll(self):
"""
Do one interation of polling AtomHopper.
"""
start = time.time()
def _get_next_url(feed):
self._fetch_timer.update(time.time() - start)
# next is previous, because AtomHopper is backwards in time
next_url = previous_link(feed)
if next_url is not None:
#.........这里部分代码省略.........
示例14: SyncDirFSNotifyProxy
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
#.........这里部分代码省略.........
# Explicitly watched paths have their cb's passed without alteration.
self.__inner_fsnotify_manager.watch(path, cb)
# Maps full path of symlink to SymlinkInfo,..
links_in_this_path_pair = self.__rescan_watched_dir_for_map(path)
assert isinstance(links_in_this_path_pair, LinksMapPair), \
repr(links_in_this_path_pair)
cls._inmerge_link_map_pair(into=self.__links_map_pair,
merge=links_in_this_path_pair)
# ... and start ("implicitly") watch for every symlink
# (its target, actually)
for link, linkinfo in links_in_this_path_pair.links.iteritems():
assert path == linkinfo.base_dir, \
(path, linkinfo.base_dir)
logger.debug(u'Starting to (impl.) watch %r in %r with %r',
linkinfo.linked_path, path, cb)
self.__implicitly_watched_dirs.add(linkinfo.linked_path)
# For every watched symlink, we call our own cb.
self.__inner_fsnotify_manager.watch(
linkinfo.linked_path,
partial(self.__cb_with_symlink_reversing,
original_cb=cb,
linked_base_dir=linkinfo.linked_path))
# The service starts the calls when it starts.
# self.__links_map_pair should already be initialized before starting
# this service!
if not self.__poll_sync_dir_timer.running and do_start_timer:
logger.debug(u'Started to poll watched directories (%r)',
self.__watched_dir_to_cb.keys())
self.__poll_sync_dir_timer.startService()
@contract_epydoc
def __cb_with_symlink_reversing(self, event, original_cb, linked_base_dir):
r"""
>>> from uhost.fs_notify.events import \
... CreateEvent, DeleteEvent, MoveEvent, Event
>>> src_path = '/mnt/net/homes/john/hello'
>>> dst_path = '/mnt/net/homes/john/goodby'
>>> create_event = CreateEvent(filepath.FilePath(src_path))
>>> move_event = MoveEvent(filepath.FilePath(src_path),
... filepath.FilePath(dst_path))
>>> delete_event = DeleteEvent(filepath.FilePath(dst_path))
>>> def printer(event):
... print event
>>> class DummySyncDirFSNotifyProxy(SyncDirFSNotifyProxy):
... def __init__(self):
... self._SyncDirFSNotifyProxy__links_map_pair =\
... LinksMapPair(links={
... '/home/john':
... SymlinkInfo(
... base_dir='/home',
... linked_path=
... '/mnt/net/homes/john')},
... reverse_links={
... '/mnt/net/homes/john': {'/home/john'}}
... )
... def cb_with_symlink_reversing(self, event, original_cb,
... linked_base_dir):
... self._SyncDirFSNotifyProxy__cb_with_symlink_reversing(
示例15: RestoreRequestProcessor
# 需要导入模块: from twisted.application.internet import TimerService [as 别名]
# 或者: from twisted.application.internet.TimerService import startService [as 别名]
class RestoreRequestProcessor(object):
"""
The processor for the externally initiated restore requests.
"""
__slots__ = ('__server_process', '__restore_timer')
def __init__(self, server_process):
assert isinstance(server_process, ServerProcess), \
repr(server_process)
self.__server_process = server_process
self.__restore_timer = \
TimerService(WEB_RESTORE_PERIOD.total_seconds(),
exceptions_logged(logger)(callInThread),
self.__poll_restore_requests_in_thread)
def __poll_restore_requests_in_thread(self):
"""Perform another iteration of polling the restore requests."""
assert not in_main_thread()
poll_uuid = gen_uuid()
logger.debug('Polling restore requests (%s)', poll_uuid)
restore_request = True
while restore_request is not None:
with ds.FDB() as fdbw:
restore_request = \
FDBQueries.RestoreRequests \
.atomic_start_oldest_restore_request(fdbw=fdbw)
logger.debug('Poll (%s) returned %r', poll_uuid, restore_request)
if restore_request is not None:
# We've indeed have some restore request that needs processing.
# Create new "virtual" dataset with all the data
# to be restored.
with db.RDB() as rdbw:
new_ds_uuid = \
Queries.Datasets.restore_files_to_dataset_clone(
restore_request.base_ds_uuid,
restore_request.paths,
restore_request.ts_start,
rdbw)
# Now we know the new dataset to be restored.
# Btw, write it into the docstore.
# Doesn't need to be atomic, as only a single node
# may be processing it at a time.
with ds.FDB() as fdbw:
FDBQueries.RestoreRequests.set_ds_uuid(
_id=restore_request._id,
new_ds_uuid=new_ds_uuid,
fdbw=fdbw)
# After creating the dataset, let's restore it to all host
# which are alive.
_syncer = self.__server_process.app.syncer
_syncer.restore_dataset_to_lacking_hosts(
me=self.__server_process.me,
host=None,
ds_uuid=new_ds_uuid)
logger.debug('Polling restore requests (%s) - done', poll_uuid)
def start(self):
"""Start the processor."""
assert in_main_thread()
self.__restore_timer.startService()
def stop(self):
"""Stop the processor."""
assert in_main_thread()
self.__restore_timer.stopService()