| 1 |
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 |
# not use this file except in compliance with the License. You may obtain |
| 5 |
# a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 |
# License for the specific language governing permissions and limitations |
| 13 |
# under the License. |
| 14 |
|
| 15 |
import collections |
| 16 |
import fractions |
| 17 |
import functools |
| 18 |
import heapq |
| 19 |
import inspect |
| 20 |
import logging |
| 21 |
import math |
| 22 |
import random |
| 23 |
import threading |
| 24 |
|
| 25 |
from concurrent import futures |
| 26 |
try: |
| 27 |
import prettytable |
| 28 |
except ImportError: |
| 29 |
prettytable = None |
| 30 |
|
| 31 |
import futurist |
| 32 |
from futurist import _utils as utils |
| 33 |
|
| 34 |
LOG = logging.getLogger(__name__) |
| 35 |
|
| 36 |
|
| 37 |
class NeverAgain(Exception): |
| 38 |
"""Exception to raise to stop further periodic calls for a function. |
| 39 |
|
| 40 |
When you want a function never run again you can throw this from |
| 41 |
you periodic function and that will signify to the execution framework |
| 42 |
to remove that function (and never run it again). |
| 43 |
""" |
| 44 |
|
| 45 |
|
| 46 |
_REQUIRED_ATTRS = ('_is_periodic', '_periodic_spacing', |
| 47 |
'_periodic_run_immediately') |
| 48 |
|
| 49 |
_DEFAULT_COLS = ('Name', 'Active', 'Periodicity', 'Runs in', |
| 50 |
'Runs', 'Failures', 'Successes', 'Stop Requested', |
| 51 |
'Average elapsed', 'Average elapsed waiting') |
| 52 |
|
| 53 |
# Constants that are used to determine what 'kind' the current callback |
| 54 |
# is being ran as. |
| 55 |
PERIODIC = 'periodic' |
| 56 |
IMMEDIATE = 'immediate' |
| 57 |
|
| 58 |
|
| 59 |
class Work(collections.namedtuple("Work", |
| 60 |
['name', 'callback', 'args', 'kwargs'])): |
| 61 |
"""Named unit of work that can be periodically scheduled and watched.""" |
| 62 |
|
| 63 |
def __call__(self): |
| 64 |
return self.callback(*self.args, **self.kwargs) |
| 65 |
|
| 66 |
|
| 67 |
class Watcher: |
| 68 |
"""A **read-only** object representing a periodic callback's activities.""" |
| 69 |
|
| 70 |
def __init__(self, metrics, work): |
| 71 |
self._metrics = metrics |
| 72 |
self._work = work |
| 73 |
|
| 74 |
def __repr__(self): |
| 75 |
return ("<Watcher(metrics=%(metrics)s, work=%(work)s)" |
| 76 |
" object at 0x%(ident)x>") % dict(ident=id(self), |
| 77 |
work=self._work, |
| 78 |
metrics=self._metrics) |
| 79 |
|
| 80 |
@property |
| 81 |
def requested_stop(self): |
| 82 |
"""If the work unit being ran has requested to be stopped.""" |
| 83 |
return self._metrics['requested_stop'] |
| 84 |
|
| 85 |
@property |
| 86 |
def work(self): |
| 87 |
"""**Read-only** named work tuple this object watches.""" |
| 88 |
return self._work |
| 89 |
|
| 90 |
@property |
| 91 |
def runs(self): |
| 92 |
"""How many times the periodic callback has been ran.""" |
| 93 |
return self._metrics['runs'] |
| 94 |
|
| 95 |
@property |
| 96 |
def successes(self): |
| 97 |
"""How many times the periodic callback ran successfully.""" |
| 98 |
return self._metrics['successes'] |
| 99 |
|
| 100 |
@property |
| 101 |
def failures(self): |
| 102 |
"""How many times the periodic callback ran unsuccessfully.""" |
| 103 |
return self._metrics['failures'] |
| 104 |
|
| 105 |
@property |
| 106 |
def elapsed(self): |
| 107 |
"""Total amount of time the periodic callback has ran for.""" |
| 108 |
return self._metrics['elapsed'] |
| 109 |
|
| 110 |
@property |
| 111 |
def elapsed_waiting(self): |
| 112 |
"""Total amount of time the periodic callback has waited to run for.""" |
| 113 |
return self._metrics['elapsed_waiting'] |
| 114 |
|
| 115 |
@property |
| 116 |
def average_elapsed_waiting(self): |
| 117 |
"""Avg. amount of time the periodic callback has waited to run for. |
| 118 |
|
| 119 |
This may raise a ``ZeroDivisionError`` if there has been no runs. |
| 120 |
""" |
| 121 |
return self._metrics['elapsed_waiting'] / self._metrics['runs'] |
| 122 |
|
| 123 |
@property |
| 124 |
def average_elapsed(self): |
| 125 |
"""Avg. amount of time the periodic callback has ran for. |
| 126 |
|
| 127 |
This may raise a ``ZeroDivisionError`` if there has been no runs. |
| 128 |
""" |
| 129 |
return self._metrics['elapsed'] / self._metrics['runs'] |
| 130 |
|
| 131 |
|
| 132 |
def _check_attrs(obj): |
| 133 |
"""Checks that a periodic function/method has all the expected attributes. |
| 134 |
|
| 135 |
This will return the expected attributes that were **not** found. |
| 136 |
""" |
| 137 |
missing_attrs = [] |
| 138 |
for attr_name in _REQUIRED_ATTRS: |
| 139 |
if not hasattr(obj, attr_name): |
| 140 |
missing_attrs.append(attr_name) |
| 141 |
return missing_attrs |
| 142 |
|
| 143 |
|
| 144 |
def is_periodic(obj): |
| 145 |
"""Check whether an object is a valid periodic callable. |
| 146 |
|
| 147 |
:param obj: object to inspect |
| 148 |
:type obj: anything |
| 149 |
:return: True if obj is a periodic task, otherwise False |
| 150 |
""" |
| 151 |
return callable(obj) and not _check_attrs(obj) |
| 152 |
|
| 153 |
|
| 154 |
def periodic(spacing, run_immediately=False, enabled=True): |
| 155 |
"""Tags a method/function as wanting/able to execute periodically. |
| 156 |
|
| 157 |
:param spacing: how often to run the decorated function (required) |
| 158 |
:type spacing: float/int |
| 159 |
:param run_immediately: option to specify whether to run |
| 160 |
immediately or wait until the spacing provided has |
| 161 |
elapsed before running for the first time |
| 162 |
:type run_immediately: boolean |
| 163 |
:param enabled: whether the task is enabled to run |
| 164 |
:type enabled: boolean |
| 165 |
""" |
| 166 |
|
| 167 |
if spacing <= 0 and enabled: |
| 168 |
raise ValueError("Periodicity/spacing must be greater than" |
| 169 |
" zero instead of %s" % spacing) |
| 170 |
|
| 171 |
def wrapper(f): |
| 172 |
f._is_periodic = enabled |
| 173 |
f._periodic_spacing = spacing |
| 174 |
f._periodic_run_immediately = run_immediately |
| 175 |
|
| 176 |
@functools.wraps(f) |
| 177 |
def decorator(*args, **kwargs): |
| 178 |
return f(*args, **kwargs) |
| 179 |
|
| 180 |
return decorator |
| 181 |
|
| 182 |
return wrapper |
| 183 |
|
| 184 |
|
| 185 |
def _add_jitter(max_percent_jitter): |
| 186 |
"""Wraps a existing strategy and adds jitter to it. |
| 187 |
|
| 188 |
0% to 100% of the spacing value will be added to this value to ensure |
| 189 |
callbacks do not synchronize. |
| 190 |
""" |
| 191 |
if max_percent_jitter > 1 or max_percent_jitter < 0: |
| 192 |
raise ValueError("Invalid 'max_percent_jitter', must be greater or" |
| 193 |
" equal to 0.0 and less than or equal to 1.0") |
| 194 |
|
| 195 |
def wrapper(func): |
| 196 |
rnd = random.SystemRandom() |
| 197 |
|
| 198 |
@functools.wraps(func) |
| 199 |
def decorator(cb, started_at, finished_at, metrics): |
| 200 |
next_run = func(cb, started_at, finished_at, metrics) |
| 201 |
how_often = cb._periodic_spacing |
| 202 |
jitter = how_often * (rnd.random() * max_percent_jitter) |
| 203 |
return next_run + jitter |
| 204 |
|
| 205 |
decorator.__name__ += "_with_jitter" |
| 206 |
return decorator |
| 207 |
|
| 208 |
return wrapper |
| 209 |
|
| 210 |
|
| 211 |
def _last_finished_strategy(cb, started_at, finished_at, metrics): |
| 212 |
# Determine when the callback should next run based on when it was |
| 213 |
# last finished **only** given metrics about this information. |
| 214 |
how_often = cb._periodic_spacing |
| 215 |
return finished_at + how_often |
| 216 |
|
| 217 |
|
| 218 |
def _last_started_strategy(cb, started_at, finished_at, metrics): |
| 219 |
# Determine when the callback should next run based on when it was |
| 220 |
# last started **only** given metrics about this information. |
| 221 |
how_often = cb._periodic_spacing |
| 222 |
return started_at + how_often |
| 223 |
|
| 224 |
|
| 225 |
def _aligned_last_finished_strategy(cb, started_at, finished_at, metrics): |
| 226 |
# Determine when the callback should next run based on when it was |
| 227 |
# last finished **only** where the last finished time is first aligned to |
| 228 |
# be a multiple of the expected spacing (so that no matter how long or |
| 229 |
# how short the callback takes it is always ran on its next aligned |
| 230 |
# to spacing time). |
| 231 |
how_often = cb._periodic_spacing |
| 232 |
aligned_finished_at = finished_at - math.fmod(finished_at, how_often) |
| 233 |
return aligned_finished_at + how_often |
| 234 |
|
| 235 |
|
| 236 |
def _now_plus_periodicity(cb, now): |
| 237 |
how_often = cb._periodic_spacing |
| 238 |
return how_often + now |
| 239 |
|
| 240 |
|
| 241 |
class _Schedule: |
| 242 |
"""Internal heap-based structure that maintains the schedule/ordering. |
| 243 |
|
| 244 |
This stores a heap composed of the following ``(next_run, index)`` where |
| 245 |
``next_run`` is the next desired runtime for the callback that is stored |
| 246 |
somewhere with the index provided. The index is saved so that if two |
| 247 |
functions with the same ``next_run`` time are inserted, that the one with |
| 248 |
the smaller index is preferred (it is also saved so that on pop we can |
| 249 |
know what the index of the callback we should call is). |
| 250 |
""" |
| 251 |
|
| 252 |
def __init__(self): |
| 253 |
self._ordering = [] |
| 254 |
|
| 255 |
def push(self, next_run, index): |
| 256 |
heapq.heappush(self._ordering, (next_run, index)) |
| 257 |
|
| 258 |
def __len__(self): |
| 259 |
return len(self._ordering) |
| 260 |
|
| 261 |
def fetch_next_run(self, index): |
| 262 |
for (next_run, a_index) in self._ordering: |
| 263 |
if a_index == index: |
| 264 |
return next_run |
| 265 |
return None |
| 266 |
|
| 267 |
def pop(self): |
| 268 |
return heapq.heappop(self._ordering) |
| 269 |
|
| 270 |
|
| 271 |
def _on_failure_log(log, cb, kind, spacing, exc_info, traceback=None): |
| 272 |
cb_name = utils.get_callback_name(cb) |
| 273 |
if all(exc_info) or not traceback: |
| 274 |
log.error("Failed to call %s '%s' (it runs every %0.2f" |
| 275 |
" seconds)", kind, cb_name, spacing, exc_info=exc_info) |
| 276 |
else: |
| 277 |
log.error("Failed to call %s '%s' (it runs every %0.2f" |
| 278 |
" seconds):\n%s", kind, cb_name, spacing, traceback) |
| 279 |
|
| 280 |
|
| 281 |
class _Runner: |
| 282 |
def __init__(self, now_func, retain_traceback=True): |
| 283 |
self.now_func = now_func |
| 284 |
self.retain_traceback = retain_traceback |
| 285 |
|
| 286 |
def run(self, work): |
| 287 |
failure = None |
| 288 |
started_at = self.now_func() |
| 289 |
try: |
| 290 |
work() |
| 291 |
except Exception: |
| 292 |
# Until https://bugs.python.org/issue24451 is merged we have to |
| 293 |
# capture and return the failure, so that we can have reliable |
| 294 |
# timing information. |
| 295 |
failure = utils.Failure(self.retain_traceback) |
| 296 |
finished_at = self.now_func() |
| 297 |
return (started_at, finished_at, failure) |
| 298 |
|
| 299 |
|
| 300 |
def _build(now_func, works, next_run_scheduler): |
| 301 |
schedule = _Schedule() |
| 302 |
now = None |
| 303 |
immediates = collections.deque() |
| 304 |
for index, work in enumerate(works): |
| 305 |
cb = work.callback |
| 306 |
if cb._periodic_run_immediately: |
| 307 |
immediates.append(index) |
| 308 |
else: |
| 309 |
if now is None: |
| 310 |
now = now_func() |
| 311 |
next_run = next_run_scheduler(cb, now) |
| 312 |
schedule.push(next_run, index) |
| 313 |
return immediates, schedule |
| 314 |
|
| 315 |
|
| 316 |
_SCHEDULE_RETRY_EXCEPTIONS = (RuntimeError, futurist.RejectedSubmission) |
| 317 |
|
| 318 |
|
| 319 |
class ExecutorFactory: |
| 320 |
"""Base class for any executor factory.""" |
| 321 |
|
| 322 |
shutdown = True |
| 323 |
"""Whether the executor should be shut down on periodic worker stop.""" |
| 324 |
|
| 325 |
def __call__(self): |
| 326 |
"""Return the executor to be used.""" |
| 327 |
raise NotImplementedError() |
| 328 |
|
| 329 |
|
| 330 |
class ExistingExecutor(ExecutorFactory): |
| 331 |
"""An executor factory returning the existing object.""" |
| 332 |
|
| 333 |
def __init__(self, executor, shutdown=False): |
| 334 |
self._executor = executor |
| 335 |
self.shutdown = shutdown |
| 336 |
|
| 337 |
def __call__(self): |
| 338 |
return self._executor |
| 339 |
|
| 340 |
|
| 341 |
class PeriodicWorker: |
| 342 |
"""Calls a collection of callables periodically (sleeping as needed...). |
| 343 |
|
| 344 |
NOTE(harlowja): typically the :py:meth:`.start` method is executed in a |
| 345 |
background thread so that the periodic callables are executed in |
| 346 |
the background/asynchronously (using the defined periods to determine |
| 347 |
when each is called). |
| 348 |
""" |
| 349 |
|
| 350 |
#: Max amount of time to wait when running (forces a wakeup when elapsed). |
| 351 |
MAX_LOOP_IDLE = 30 |
| 352 |
|
| 353 |
_NO_OP_ARGS = () |
| 354 |
_NO_OP_KWARGS = {} |
| 355 |
_INITIAL_METRICS = { |
| 356 |
'runs': 0, |
| 357 |
'elapsed': 0, |
| 358 |
'elapsed_waiting': 0, |
| 359 |
'failures': 0, |
| 360 |
'successes': 0, |
| 361 |
'requested_stop': False, |
| 362 |
} |
| 363 |
|
| 364 |
# When scheduling fails temporary, use a random delay between 0.9-1.1 sec. |
| 365 |
_RESCHEDULE_DELAY = 0.9 |
| 366 |
_RESCHEDULE_JITTER = 0.2 |
| 367 |
|
| 368 |
DEFAULT_JITTER = fractions.Fraction(5, 100) |
| 369 |
""" |
| 370 |
Default jitter percentage the built-in strategies (that have jitter |
| 371 |
support) will use. |
| 372 |
""" |
| 373 |
|
| 374 |
BUILT_IN_STRATEGIES = { |
| 375 |
'last_started': ( |
| 376 |
_last_started_strategy, |
| 377 |
_now_plus_periodicity, |
| 378 |
), |
| 379 |
'last_started_jitter': ( |
| 380 |
_add_jitter(DEFAULT_JITTER)(_last_started_strategy), |
| 381 |
_now_plus_periodicity, |
| 382 |
), |
| 383 |
'last_finished': ( |
| 384 |
_last_finished_strategy, |
| 385 |
_now_plus_periodicity, |
| 386 |
), |
| 387 |
'last_finished_jitter': ( |
| 388 |
_add_jitter(DEFAULT_JITTER)(_last_finished_strategy), |
| 389 |
_now_plus_periodicity, |
| 390 |
), |
| 391 |
'aligned_last_finished': ( |
| 392 |
_aligned_last_finished_strategy, |
| 393 |
_now_plus_periodicity, |
| 394 |
), |
| 395 |
'aligned_last_finished_jitter': ( |
| 396 |
_add_jitter(DEFAULT_JITTER)(_aligned_last_finished_strategy), |
| 397 |
_now_plus_periodicity, |
| 398 |
), |
| 399 |
} |
| 400 |
""" |
| 401 |
Built in scheduling strategies (used to determine when next to run |
| 402 |
a periodic callable). |
| 403 |
|
| 404 |
The first element is the strategy to use after the initial start |
| 405 |
and the second element is the strategy to use for the initial start. |
| 406 |
|
| 407 |
These are made somewhat pluggable so that we can *easily* add-on |
| 408 |
different types later (perhaps one that uses a cron-style syntax |
| 409 |
for example). |
| 410 |
""" |
| 411 |
|
| 412 |
@classmethod |
| 413 |
def create(cls, objects, exclude_hidden=True, |
| 414 |
log=None, executor_factory=None, |
| 415 |
cond_cls=threading.Condition, event_cls=threading.Event, |
| 416 |
schedule_strategy='last_started', now_func=utils.now, |
| 417 |
on_failure=None, args=_NO_OP_ARGS, kwargs=_NO_OP_KWARGS): |
| 418 |
"""Automatically creates a worker by analyzing object(s) methods. |
| 419 |
|
| 420 |
Only picks up methods that have been tagged/decorated with |
| 421 |
the :py:func:`.periodic` decorator (does not match against private |
| 422 |
or protected methods unless explicitly requested to). |
| 423 |
|
| 424 |
:param objects: the objects to introspect for decorated members |
| 425 |
:type objects: iterable |
| 426 |
:param exclude_hidden: exclude hidden members (ones that start with |
| 427 |
an underscore) |
| 428 |
:type exclude_hidden: bool |
| 429 |
:param log: logger to use when creating a new worker (defaults |
| 430 |
to the module logger if none provided), it is currently |
| 431 |
only used to report callback failures (if they occur) |
| 432 |
:type log: logger |
| 433 |
:param executor_factory: factory callable that can be used to generate |
| 434 |
executor objects that will be used to |
| 435 |
run the periodic callables (if none is |
| 436 |
provided one will be created that uses |
| 437 |
the :py:class:`~futurist.SynchronousExecutor` |
| 438 |
class) |
| 439 |
:type executor_factory: ExecutorFactory or any callable |
| 440 |
:param cond_cls: callable object that can |
| 441 |
produce ``threading.Condition`` |
| 442 |
(or compatible/equivalent) objects |
| 443 |
:type cond_cls: callable |
| 444 |
:param event_cls: callable object that can produce ``threading.Event`` |
| 445 |
(or compatible/equivalent) objects |
| 446 |
:type event_cls: callable |
| 447 |
:param schedule_strategy: string to select one of the built-in |
| 448 |
strategies that can return the |
| 449 |
next time a callable should run |
| 450 |
:type schedule_strategy: string |
| 451 |
:param now_func: callable that can return the current time offset |
| 452 |
from some point (used in calculating elapsed times |
| 453 |
and next times to run); preferably this is |
| 454 |
monotonically increasing |
| 455 |
:type now_func: callable |
| 456 |
:param on_failure: callable that will be called whenever a periodic |
| 457 |
function fails with an error, it will be provided |
| 458 |
four positional arguments and one keyword |
| 459 |
argument, the first positional argument being the |
| 460 |
callable that failed, the second being the type |
| 461 |
of activity under which it failed (``IMMEDIATE`` or |
| 462 |
``PERIODIC``), the third being the spacing that the |
| 463 |
callable runs at and the fourth ``exc_info`` tuple |
| 464 |
of the failure. The keyword argument ``traceback`` |
| 465 |
will also be provided that may be be a string |
| 466 |
that caused the failure (this is required for |
| 467 |
executors which run out of process, as those can not |
| 468 |
*currently* transfer stack frames across process |
| 469 |
boundaries); if no callable is provided then a |
| 470 |
default failure logging function will be used |
| 471 |
instead (do note that |
| 472 |
any user provided callable should not raise |
| 473 |
exceptions on being called) |
| 474 |
:type on_failure: callable |
| 475 |
:param args: positional arguments to be passed to all callables |
| 476 |
:type args: tuple |
| 477 |
:param kwargs: keyword arguments to be passed to all callables |
| 478 |
:type kwargs: dict |
| 479 |
""" |
| 480 |
callables = [] |
| 481 |
for obj in objects: |
| 482 |
for (name, member) in inspect.getmembers(obj): |
| 483 |
if name.startswith("_") and exclude_hidden: |
| 484 |
continue |
| 485 |
if callable(member): |
| 486 |
missing_attrs = _check_attrs(member) |
| 487 |
if not missing_attrs: |
| 488 |
callables.append((member, args, kwargs)) |
| 489 |
return cls(callables, log=log, executor_factory=executor_factory, |
| 490 |
cond_cls=cond_cls, event_cls=event_cls, |
| 491 |
schedule_strategy=schedule_strategy, now_func=now_func, |
| 492 |
on_failure=on_failure) |
| 493 |
|
| 494 |
def __init__(self, callables, log=None, executor_factory=None, |
| 495 |
cond_cls=threading.Condition, event_cls=threading.Event, |
| 496 |
schedule_strategy='last_started', now_func=utils.now, |
| 497 |
on_failure=None): |
| 498 |
"""Creates a new worker using the given periodic callables. |
| 499 |
|
| 500 |
:param callables: a iterable of tuple objects previously decorated |
| 501 |
with the :py:func:`.periodic` decorator, each item |
| 502 |
in the iterable is expected to be in the format |
| 503 |
of ``(cb, args, kwargs)`` where ``cb`` is the |
| 504 |
decorated function and ``args`` and ``kwargs`` are |
| 505 |
any positional and keyword arguments to send into |
| 506 |
the callback when it is activated (both ``args`` |
| 507 |
and ``kwargs`` may be provided as none to avoid |
| 508 |
using them) |
| 509 |
:type callables: iterable |
| 510 |
:param log: logger to use when creating a new worker (defaults |
| 511 |
to the module logger if none provided), it is currently |
| 512 |
only used to report callback failures (if they occur) |
| 513 |
:type log: logger |
| 514 |
:param executor_factory: factory callable that can be used to generate |
| 515 |
executor objects that will be used to |
| 516 |
run the periodic callables (if none is |
| 517 |
provided one will be created that uses |
| 518 |
the :py:class:`~futurist.SynchronousExecutor` |
| 519 |
class) |
| 520 |
:type executor_factory: ExecutorFactory or any callable |
| 521 |
:param cond_cls: callable object that can |
| 522 |
produce ``threading.Condition`` |
| 523 |
(or compatible/equivalent) objects |
| 524 |
:type cond_cls: callable |
| 525 |
:param event_cls: callable object that can produce ``threading.Event`` |
| 526 |
(or compatible/equivalent) objects |
| 527 |
:type event_cls: callable |
| 528 |
:param schedule_strategy: string to select one of the built-in |
| 529 |
strategies that can return the |
| 530 |
next time a callable should run |
| 531 |
:type schedule_strategy: string |
| 532 |
:param now_func: callable that can return the current time offset |
| 533 |
from some point (used in calculating elapsed times |
| 534 |
and next times to run); preferably this is |
| 535 |
monotonically increasing |
| 536 |
:type now_func: callable |
| 537 |
:param on_failure: callable that will be called whenever a periodic |
| 538 |
function fails with an error, it will be provided |
| 539 |
four positional arguments and one keyword |
| 540 |
argument, the first positional argument being the |
| 541 |
callable that failed, the second being the type |
| 542 |
of activity under which it failed (``IMMEDIATE`` or |
| 543 |
``PERIODIC``), the third being the spacing that the |
| 544 |
callable runs at and the fourth ``exc_info`` tuple |
| 545 |
of the failure. The keyword argument ``traceback`` |
| 546 |
will also be provided that may be be a string |
| 547 |
that caused the failure (this is required for |
| 548 |
executors which run out of process, as those can not |
| 549 |
*currently* transfer stack frames across process |
| 550 |
boundaries); if no callable is provided then a |
| 551 |
default failure logging function will be used |
| 552 |
instead (do note that |
| 553 |
any user provided callable should not raise |
| 554 |
exceptions on being called) |
| 555 |
:type on_failure: callable |
| 556 |
""" |
| 557 |
if on_failure is not None and not callable(on_failure): |
| 558 |
raise ValueError("On failure callback %r must be" |
| 559 |
" callable" % on_failure) |
| 560 |
self._tombstone = event_cls() |
| 561 |
self._waiter = cond_cls() |
| 562 |
self._dead = event_cls() |
| 563 |
self._active = event_cls() |
| 564 |
self._cond_cls = cond_cls |
| 565 |
self._watchers = [] |
| 566 |
self._works = [] |
| 567 |
for (cb, args, kwargs) in callables: |
| 568 |
if not callable(cb): |
| 569 |
raise ValueError("Periodic callback %r must be callable" % cb) |
| 570 |
missing_attrs = _check_attrs(cb) |
| 571 |
if missing_attrs: |
| 572 |
raise ValueError("Periodic callback %r missing required" |
| 573 |
" attributes %s" % (cb, missing_attrs)) |
| 574 |
if cb._is_periodic: |
| 575 |
# Ensure these aren't none and if so replace them with |
| 576 |
# something more appropriate... |
| 577 |
if args is None: |
| 578 |
args = self._NO_OP_ARGS |
| 579 |
if kwargs is None: |
| 580 |
kwargs = self._NO_OP_KWARGS.copy() |
| 581 |
cb_metrics = self._INITIAL_METRICS.copy() |
| 582 |
work = Work(utils.get_callback_name(cb), cb, args, kwargs) |
| 583 |
watcher = Watcher(cb_metrics, work) |
| 584 |
self._works.append(work) |
| 585 |
self._watchers.append((cb_metrics, watcher)) |
| 586 |
try: |
| 587 |
strategy = self.BUILT_IN_STRATEGIES[schedule_strategy] |
| 588 |
self._schedule_strategy = strategy[0] |
| 589 |
self._initial_schedule_strategy = strategy[1] |
| 590 |
except KeyError: |
| 591 |
valid_strategies = sorted(self.BUILT_IN_STRATEGIES.keys()) |
| 592 |
raise ValueError("Scheduling strategy '%s' must be one of" |
| 593 |
" %s selectable strategies" |
| 594 |
% (schedule_strategy, valid_strategies)) |
| 595 |
self._immediates, self._schedule = _build( |
| 596 |
now_func, self._works, self._initial_schedule_strategy) |
| 597 |
self._log = log or LOG |
| 598 |
if executor_factory is None: |
| 599 |
executor_factory = lambda: futurist.SynchronousExecutor() |
| 600 |
if on_failure is None: |
| 601 |
on_failure = functools.partial(_on_failure_log, self._log) |
| 602 |
self._on_failure = on_failure |
| 603 |
self._executor_factory = executor_factory |
| 604 |
self._now_func = now_func |
| 605 |
|
| 606 |
def __len__(self): |
| 607 |
"""How many callables/periodic work units are currently active.""" |
| 608 |
return len(self._works) |
| 609 |
|
| 610 |
def _run(self, executor, runner, auto_stop_when_empty): |
| 611 |
"""Main worker run loop.""" |
| 612 |
barrier = utils.Barrier(cond_cls=self._cond_cls) |
| 613 |
rnd = random.SystemRandom() |
| 614 |
|
| 615 |
def _process_scheduled(): |
| 616 |
# Figure out when we should run next (by selecting the |
| 617 |
# minimum item from the heap, where the minimum should be |
| 618 |
# the callable that needs to run next and has the lowest |
| 619 |
# next desired run time). |
| 620 |
with self._waiter: |
| 621 |
while (not self._schedule and |
| 622 |
not self._tombstone.is_set() and |
| 623 |
not self._immediates): |
| 624 |
self._waiter.wait(self.MAX_LOOP_IDLE) |
| 625 |
if self._tombstone.is_set(): |
| 626 |
# We were requested to stop, so stop. |
| 627 |
return |
| 628 |
if self._immediates: |
| 629 |
# This will get processed in _process_immediates() |
| 630 |
# in the next loop call. |
| 631 |
return |
| 632 |
submitted_at = now = self._now_func() |
| 633 |
next_run, index = self._schedule.pop() |
| 634 |
when_next = next_run - now |
| 635 |
if when_next <= 0: |
| 636 |
# Run & schedule its next execution. |
| 637 |
work = self._works[index] |
| 638 |
self._log.debug("Submitting periodic" |
| 639 |
" callback '%s'", work.name) |
| 640 |
try: |
| 641 |
fut = executor.submit(runner.run, work) |
| 642 |
except _SCHEDULE_RETRY_EXCEPTIONS as exc: |
| 643 |
# Restart after a short delay |
| 644 |
delay = (self._RESCHEDULE_DELAY + |
| 645 |
rnd.random() * self._RESCHEDULE_JITTER) |
| 646 |
self._log.error("Failed to submit periodic callback " |
| 647 |
"'%s', retrying after %.2f sec. " |
| 648 |
"Error: %s", |
| 649 |
work.name, delay, exc) |
| 650 |
self._schedule.push(self._now_func() + delay, |
| 651 |
index) |
| 652 |
else: |
| 653 |
barrier.incr() |
| 654 |
fut.add_done_callback(functools.partial(_on_done, |
| 655 |
PERIODIC, |
| 656 |
work, index, |
| 657 |
submitted_at)) |
| 658 |
else: |
| 659 |
# Gotta wait... |
| 660 |
self._schedule.push(next_run, index) |
| 661 |
when_next = min(when_next, self.MAX_LOOP_IDLE) |
| 662 |
self._waiter.wait(when_next) |
| 663 |
|
| 664 |
def _process_immediates(): |
| 665 |
with self._waiter: |
| 666 |
try: |
| 667 |
index = self._immediates.popleft() |
| 668 |
except IndexError: |
| 669 |
pass |
| 670 |
else: |
| 671 |
work = self._works[index] |
| 672 |
submitted_at = self._now_func() |
| 673 |
self._log.debug("Submitting immediate" |
| 674 |
" callback '%s'", work.name) |
| 675 |
try: |
| 676 |
fut = executor.submit(runner.run, work) |
| 677 |
except _SCHEDULE_RETRY_EXCEPTIONS as exc: |
| 678 |
self._log.error("Failed to submit immediate callback " |
| 679 |
"'%s', retrying. Error: %s", work.name, |
| 680 |
exc) |
| 681 |
# Restart as soon as possible |
| 682 |
self._immediates.append(index) |
| 683 |
else: |
| 684 |
barrier.incr() |
| 685 |
fut.add_done_callback(functools.partial(_on_done, |
| 686 |
IMMEDIATE, |
| 687 |
work, index, |
| 688 |
submitted_at)) |
| 689 |
|
| 690 |
def _on_done(kind, work, index, submitted_at, fut): |
| 691 |
cb = work.callback |
| 692 |
started_at, finished_at, failure = fut.result() |
| 693 |
cb_metrics, _watcher = self._watchers[index] |
| 694 |
cb_metrics['runs'] += 1 |
| 695 |
schedule_again = True |
| 696 |
if failure is not None: |
| 697 |
if not issubclass(failure.exc_type, NeverAgain): |
| 698 |
cb_metrics['failures'] += 1 |
| 699 |
try: |
| 700 |
self._on_failure(cb, kind, cb._periodic_spacing, |
| 701 |
failure.exc_info, |
| 702 |
traceback=failure.traceback) |
| 703 |
except Exception as exc: |
| 704 |
self._log.error("On failure callback %r raised an" |
| 705 |
" unhandled exception. Error: %s", |
| 706 |
self._on_failure, exc) |
| 707 |
else: |
| 708 |
cb_metrics['successes'] += 1 |
| 709 |
schedule_again = False |
| 710 |
self._log.debug("Periodic callback '%s' raised " |
| 711 |
"'NeverAgain' " |
| 712 |
"exception, stopping any further " |
| 713 |
"execution of it.", work.name) |
| 714 |
else: |
| 715 |
cb_metrics['successes'] += 1 |
| 716 |
elapsed = max(0, finished_at - started_at) |
| 717 |
elapsed_waiting = max(0, started_at - submitted_at) |
| 718 |
cb_metrics['elapsed'] += elapsed |
| 719 |
cb_metrics['elapsed_waiting'] += elapsed_waiting |
| 720 |
with self._waiter: |
| 721 |
with barrier.decr_cm() as am_left: |
| 722 |
if schedule_again: |
| 723 |
next_run = self._schedule_strategy(cb, started_at, |
| 724 |
finished_at, |
| 725 |
cb_metrics) |
| 726 |
self._schedule.push(next_run, index) |
| 727 |
else: |
| 728 |
cb_metrics['requested_stop'] = True |
| 729 |
if (am_left <= 0 and |
| 730 |
len(self._immediates) == 0 and |
| 731 |
len(self._schedule) == 0 and |
| 732 |
auto_stop_when_empty): |
| 733 |
# Guess nothing left to do, goodbye... |
| 734 |
self._tombstone.set() |
| 735 |
self._waiter.notify_all() |
| 736 |
|
| 737 |
try: |
| 738 |
while not self._tombstone.is_set(): |
| 739 |
_process_immediates() |
| 740 |
_process_scheduled() |
| 741 |
finally: |
| 742 |
barrier.wait() |
| 743 |
|
| 744 |
def _on_finish(self): |
| 745 |
# TODO(harlowja): this may be to verbose for people? |
| 746 |
if not self._log.isEnabledFor(logging.DEBUG): |
| 747 |
return |
| 748 |
cols = list(_DEFAULT_COLS) |
| 749 |
for c in ['Runs in', 'Active', 'Periodicity']: |
| 750 |
cols.remove(c) |
| 751 |
self._log.debug( |
| 752 |
"Stopped running %s callbacks:\n%s", |
| 753 |
len(self._works), |
| 754 |
self.pformat(columns=cols) if prettytable |
| 755 |
else "statistics not available, PrettyTable missing" |
| 756 |
) |
| 757 |
|
| 758 |
def pformat(self, columns=_DEFAULT_COLS): |
| 759 |
if prettytable is None: |
| 760 |
raise ImportError( |
| 761 |
"PrettyTable is required to use the pformat method") |
| 762 |
# Convert to a list to ensure we maintain the same order when used |
| 763 |
# further in this function (since order will matter)... |
| 764 |
if not isinstance(columns, (list, tuple)): |
| 765 |
columns = list(columns) |
| 766 |
if not columns: |
| 767 |
raise ValueError("At least one of %s columns must" |
| 768 |
" be provided" % (set(_DEFAULT_COLS))) |
| 769 |
for c in columns: |
| 770 |
if c not in _DEFAULT_COLS: |
| 771 |
raise ValueError("Unknown column '%s', valid column names" |
| 772 |
" are %s" % (c, set(_DEFAULT_COLS))) |
| 773 |
tbl_rows = [] |
| 774 |
now = self._now_func() |
| 775 |
for index, work in enumerate(self._works): |
| 776 |
_cb_metrics, watcher = self._watchers[index] |
| 777 |
next_run = self._schedule.fetch_next_run(index) |
| 778 |
if watcher.requested_stop: |
| 779 |
active = False |
| 780 |
runs_in = 'n/a' |
| 781 |
elif next_run is None: |
| 782 |
active = True |
| 783 |
runs_in = 'n/a' |
| 784 |
else: |
| 785 |
active = False |
| 786 |
runs_in = "%0.4fs" % (max(0.0, next_run - now)) |
| 787 |
cb_row = { |
| 788 |
'Name': work.name, |
| 789 |
'Active': active, |
| 790 |
'Periodicity': work.callback._periodic_spacing, |
| 791 |
'Runs': watcher.runs, |
| 792 |
'Runs in': runs_in, |
| 793 |
'Failures': watcher.failures, |
| 794 |
'Successes': watcher.successes, |
| 795 |
'Stop Requested': watcher.requested_stop, |
| 796 |
} |
| 797 |
try: |
| 798 |
cb_row_avgs = [ |
| 799 |
"%0.4fs" % watcher.average_elapsed, |
| 800 |
"%0.4fs" % watcher.average_elapsed_waiting, |
| 801 |
] |
| 802 |
except ZeroDivisionError: |
| 803 |
cb_row_avgs = ['.', '.'] |
| 804 |
cb_row['Average elapsed'] = cb_row_avgs[0] |
| 805 |
cb_row['Average elapsed waiting'] = cb_row_avgs[1] |
| 806 |
tbl_rows.append(cb_row) |
| 807 |
# Now form the table, but use only the columns that the caller |
| 808 |
# asked for (and in the order they asked for...) |
| 809 |
tbl = prettytable.PrettyTable(columns) |
| 810 |
for cb_row in tbl_rows: |
| 811 |
tbl_row = [] |
| 812 |
for c in columns: |
| 813 |
tbl_row.append(cb_row[c]) |
| 814 |
tbl.add_row(tbl_row) |
| 815 |
return tbl.get_string() |
| 816 |
|
| 817 |
def add(self, cb, *args, **kwargs): |
| 818 |
"""Adds a new periodic callback to the current worker. |
| 819 |
|
| 820 |
Returns a :py:class:`.Watcher` if added successfully or the value |
| 821 |
``None`` if not (or raises a ``ValueError`` if the callback is not |
| 822 |
correctly formed and/or decorated). |
| 823 |
|
| 824 |
:param cb: a callable object/method/function previously decorated |
| 825 |
with the :py:func:`.periodic` decorator |
| 826 |
:type cb: callable |
| 827 |
""" |
| 828 |
if not callable(cb): |
| 829 |
raise ValueError("Periodic callback %r must be callable" % cb) |
| 830 |
missing_attrs = _check_attrs(cb) |
| 831 |
if missing_attrs: |
| 832 |
raise ValueError("Periodic callback %r missing required" |
| 833 |
" attributes %s" % (cb, missing_attrs)) |
| 834 |
if not cb._is_periodic: |
| 835 |
return None |
| 836 |
now = self._now_func() |
| 837 |
with self._waiter: |
| 838 |
cb_index = len(self._works) |
| 839 |
cb_metrics = self._INITIAL_METRICS.copy() |
| 840 |
work = Work(utils.get_callback_name(cb), cb, args, kwargs) |
| 841 |
watcher = Watcher(cb_metrics, work) |
| 842 |
self._works.append(work) |
| 843 |
self._watchers.append((cb_metrics, watcher)) |
| 844 |
if cb._periodic_run_immediately: |
| 845 |
self._immediates.append(cb_index) |
| 846 |
else: |
| 847 |
next_run = self._initial_schedule_strategy(cb, now) |
| 848 |
self._schedule.push(next_run, cb_index) |
| 849 |
self._waiter.notify_all() |
| 850 |
return watcher |
| 851 |
|
| 852 |
def start(self, allow_empty=False, auto_stop_when_empty=False): |
| 853 |
"""Starts running (will not return until :py:meth:`.stop` is called). |
| 854 |
|
| 855 |
:param allow_empty: instead of running with no callbacks raise when |
| 856 |
this worker has no contained callables (this can be |
| 857 |
set to true and :py:meth:`.add` can be used to add |
| 858 |
new callables on demand), note that when enabled |
| 859 |
and no callbacks exist this will block and |
| 860 |
sleep (until either stopped or callbacks are |
| 861 |
added) |
| 862 |
:type allow_empty: bool |
| 863 |
:param auto_stop_when_empty: when the provided periodic functions have |
| 864 |
all exited and this is false then the |
| 865 |
thread responsible for executing those |
| 866 |
methods will just spin/idle waiting for |
| 867 |
a new periodic function to be added; |
| 868 |
switching it to true will make this |
| 869 |
idling not happen (and instead when no |
| 870 |
more periodic work exists then the |
| 871 |
calling thread will just return). |
| 872 |
:type auto_stop_when_empty: bool |
| 873 |
""" |
| 874 |
if not self._works and not allow_empty: |
| 875 |
raise RuntimeError("A periodic worker can not start" |
| 876 |
" without any callables to process") |
| 877 |
if self._active.is_set(): |
| 878 |
raise RuntimeError("A periodic worker can not be started" |
| 879 |
" twice") |
| 880 |
executor = self._executor_factory() |
| 881 |
# NOTE(harlowja): we compare with the futures process pool executor |
| 882 |
# since its the base type of futurist ProcessPoolExecutor and it is |
| 883 |
# possible for users to pass in there own custom executors, this one |
| 884 |
# is known to not be able to retain tracebacks... |
| 885 |
if isinstance(executor, futures.ProcessPoolExecutor): |
| 886 |
# Pickling a traceback will not work, so do not try to do it... |
| 887 |
# |
| 888 |
# Avoids 'TypeError: can't pickle traceback objects' |
| 889 |
runner = _Runner(self._now_func, retain_traceback=False) |
| 890 |
else: |
| 891 |
runner = _Runner(self._now_func, retain_traceback=True) |
| 892 |
self._dead.clear() |
| 893 |
self._active.set() |
| 894 |
try: |
| 895 |
self._run(executor, runner, auto_stop_when_empty) |
| 896 |
finally: |
| 897 |
if getattr(self._executor_factory, 'shutdown', True): |
| 898 |
executor.shutdown() |
| 899 |
self._dead.set() |
| 900 |
self._active.clear() |
| 901 |
self._on_finish() |
| 902 |
|
| 903 |
def stop(self): |
| 904 |
"""Sets the tombstone (this stops any further executions).""" |
| 905 |
with self._waiter: |
| 906 |
self._tombstone.set() |
| 907 |
self._waiter.notify_all() |
| 908 |
|
| 909 |
def iter_watchers(self): |
| 910 |
"""Iterator/generator over all the currently maintained watchers.""" |
| 911 |
for _cb_metrics, watcher in self._watchers: |
| 912 |
yield watcher |
| 913 |
|
| 914 |
def reset(self): |
| 915 |
"""Resets the workers internal state.""" |
| 916 |
self._tombstone.clear() |
| 917 |
self._dead.clear() |
| 918 |
for cb_metrics, _watcher in self._watchers: |
| 919 |
for k in list(cb_metrics): |
| 920 |
# NOTE(harlowja): mutate the original dictionaries keys |
| 921 |
# so that the watcher (which references the same dictionary |
| 922 |
# keys) is able to see those changes. |
| 923 |
cb_metrics[k] = 0 |
| 924 |
self._immediates, self._schedule = _build( |
| 925 |
self._now_func, self._works, self._initial_schedule_strategy) |
| 926 |
|
| 927 |
def wait(self, timeout=None): |
| 928 |
"""Waits for the :py:meth:`.start` method to gracefully exit. |
| 929 |
|
| 930 |
An optional timeout can be provided, which will cause the method to |
| 931 |
return within the specified timeout. If the timeout is reached, the |
| 932 |
returned value will be False. |
| 933 |
|
| 934 |
:param timeout: Maximum number of seconds that the :meth:`.wait` |
| 935 |
method should block for |
| 936 |
:type timeout: float/int |
| 937 |
""" |
| 938 |
self._dead.wait(timeout) |
| 939 |
return self._dead.is_set() |