beat.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. # -*- coding: utf-8 -*-
  2. """The periodic task scheduler."""
  3. from __future__ import absolute_import, unicode_literals
  4. import copy
  5. import errno
  6. import heapq
  7. import os
  8. import shelve
  9. import sys
  10. import time
  11. import traceback
  12. from collections import namedtuple
  13. from functools import total_ordering
  14. from threading import Event, Thread
  15. from billiard import ensure_multiprocessing
  16. from billiard.common import reset_signals
  17. from billiard.context import Process
  18. from kombu.utils.functional import maybe_evaluate, reprcall
  19. from kombu.utils.objects import cached_property
  20. from . import __version__, platforms, signals
  21. from .five import (items, monotonic, python_2_unicode_compatible, reraise,
  22. values)
  23. from .schedules import crontab, maybe_schedule
  24. from .utils.imports import load_extension_class_names, symbol_by_name
  25. from .utils.log import get_logger, iter_open_logger_fds
  26. from .utils.time import humanize_seconds
  27. __all__ = (
  28. 'SchedulingError', 'ScheduleEntry', 'Scheduler',
  29. 'PersistentScheduler', 'Service', 'EmbeddedService',
  30. )
  31. event_t = namedtuple('event_t', ('time', 'priority', 'entry'))
  32. logger = get_logger(__name__)
  33. debug, info, error, warning = (logger.debug, logger.info,
  34. logger.error, logger.warning)
  35. DEFAULT_MAX_INTERVAL = 300 # 5 minutes
  36. class SchedulingError(Exception):
  37. """An error occurred while scheduling a task."""
  38. @total_ordering
  39. @python_2_unicode_compatible
  40. class ScheduleEntry(object):
  41. """An entry in the scheduler.
  42. Arguments:
  43. name (str): see :attr:`name`.
  44. schedule (~celery.schedules.schedule): see :attr:`schedule`.
  45. args (Tuple): see :attr:`args`.
  46. kwargs (Dict): see :attr:`kwargs`.
  47. options (Dict): see :attr:`options`.
  48. last_run_at (~datetime.datetime): see :attr:`last_run_at`.
  49. total_run_count (int): see :attr:`total_run_count`.
  50. relative (bool): Is the time relative to when the server starts?
  51. """
  52. #: The task name
  53. name = None
  54. #: The schedule (:class:`~celery.schedules.schedule`)
  55. schedule = None
  56. #: Positional arguments to apply.
  57. args = None
  58. #: Keyword arguments to apply.
  59. kwargs = None
  60. #: Task execution options.
  61. options = None
  62. #: The time and date of when this task was last scheduled.
  63. last_run_at = None
  64. #: Total number of times this task has been scheduled.
  65. total_run_count = 0
  66. def __init__(self, name=None, task=None, last_run_at=None,
  67. total_run_count=None, schedule=None, args=(), kwargs={},
  68. options={}, relative=False, app=None):
  69. self.app = app
  70. self.name = name
  71. self.task = task
  72. self.args = args
  73. self.kwargs = kwargs
  74. self.options = options
  75. self.schedule = maybe_schedule(schedule, relative, app=self.app)
  76. self.last_run_at = last_run_at or self.default_now()
  77. self.total_run_count = total_run_count or 0
  78. def default_now(self):
  79. return self.schedule.now() if self.schedule else self.app.now()
  80. _default_now = default_now # compat
  81. def _next_instance(self, last_run_at=None):
  82. """Return new instance, with date and count fields updated."""
  83. return self.__class__(**dict(
  84. self,
  85. last_run_at=last_run_at or self.default_now(),
  86. total_run_count=self.total_run_count + 1,
  87. ))
  88. __next__ = next = _next_instance # for 2to3
  89. def __reduce__(self):
  90. return self.__class__, (
  91. self.name, self.task, self.last_run_at, self.total_run_count,
  92. self.schedule, self.args, self.kwargs, self.options,
  93. )
  94. def update(self, other):
  95. """Update values from another entry.
  96. Will only update "editable" fields:
  97. ``task``, ``schedule``, ``args``, ``kwargs``, ``options``.
  98. """
  99. self.__dict__.update({
  100. 'task': other.task, 'schedule': other.schedule,
  101. 'args': other.args, 'kwargs': other.kwargs,
  102. 'options': other.options,
  103. })
  104. def is_due(self):
  105. """See :meth:`~celery.schedule.schedule.is_due`."""
  106. return self.schedule.is_due(self.last_run_at)
  107. def __iter__(self):
  108. return iter(items(vars(self)))
  109. def __repr__(self):
  110. return '<{name}: {0.name} {call} {0.schedule}'.format(
  111. self,
  112. call=reprcall(self.task, self.args or (), self.kwargs or {}),
  113. name=type(self).__name__,
  114. )
  115. def __lt__(self, other):
  116. if isinstance(other, ScheduleEntry):
  117. # How the object is ordered doesn't really matter, as
  118. # in the scheduler heap, the order is decided by the
  119. # preceding members of the tuple ``(time, priority, entry)``.
  120. #
  121. # If all that's left to order on is the entry then it can
  122. # just as well be random.
  123. return id(self) < id(other)
  124. return NotImplemented
  125. def editable_fields_equal(self, other):
  126. for attr in ('task', 'args', 'kwargs', 'options', 'schedule'):
  127. if getattr(self, attr) != getattr(other, attr):
  128. return False
  129. return True
  130. def __eq__(self, other):
  131. """Test schedule entries equality.
  132. Will only compare "editable" fields:
  133. ``task``, ``schedule``, ``args``, ``kwargs``, ``options``.
  134. """
  135. return self.editable_fields_equal(other)
  136. def __ne__(self, other):
  137. """Test schedule entries inequality.
  138. Will only compare "editable" fields:
  139. ``task``, ``schedule``, ``args``, ``kwargs``, ``options``.
  140. """
  141. return not self == other
  142. class Scheduler(object):
  143. """Scheduler for periodic tasks.
  144. The :program:`celery beat` program may instantiate this class
  145. multiple times for introspection purposes, but then with the
  146. ``lazy`` argument set. It's important for subclasses to
  147. be idempotent when this argument is set.
  148. Arguments:
  149. schedule (~celery.schedules.schedule): see :attr:`schedule`.
  150. max_interval (int): see :attr:`max_interval`.
  151. lazy (bool): Don't set up the schedule.
  152. """
  153. Entry = ScheduleEntry
  154. #: The schedule dict/shelve.
  155. schedule = None
  156. #: Maximum time to sleep between re-checking the schedule.
  157. max_interval = DEFAULT_MAX_INTERVAL
  158. #: How often to sync the schedule (3 minutes by default)
  159. sync_every = 3 * 60
  160. #: How many tasks can be called before a sync is forced.
  161. sync_every_tasks = None
  162. _last_sync = None
  163. _tasks_since_sync = 0
  164. logger = logger # compat
  165. def __init__(self, app, schedule=None, max_interval=None,
  166. Producer=None, lazy=False, sync_every_tasks=None, **kwargs):
  167. self.app = app
  168. self.data = maybe_evaluate({} if schedule is None else schedule)
  169. self.max_interval = (max_interval or
  170. app.conf.beat_max_loop_interval or
  171. self.max_interval)
  172. self.Producer = Producer or app.amqp.Producer
  173. self._heap = None
  174. self.old_schedulers = None
  175. self.sync_every_tasks = (
  176. app.conf.beat_sync_every if sync_every_tasks is None
  177. else sync_every_tasks)
  178. if not lazy:
  179. self.setup_schedule()
  180. def install_default_entries(self, data):
  181. entries = {}
  182. if self.app.conf.result_expires and \
  183. not self.app.backend.supports_autoexpire:
  184. if 'celery.backend_cleanup' not in data:
  185. entries['celery.backend_cleanup'] = {
  186. 'task': 'celery.backend_cleanup',
  187. 'schedule': crontab('0', '4', '*'),
  188. 'options': {'expires': 12 * 3600}}
  189. self.update_from_dict(entries)
  190. def apply_entry(self, entry, producer=None):
  191. info('Scheduler: Sending due task %s (%s)', entry.name, entry.task)
  192. try:
  193. result = self.apply_async(entry, producer=producer, advance=False)
  194. except Exception as exc: # pylint: disable=broad-except
  195. error('Message Error: %s\n%s',
  196. exc, traceback.format_stack(), exc_info=True)
  197. else:
  198. debug('%s sent. id->%s', entry.task, result.id)
  199. def adjust(self, n, drift=-0.010):
  200. if n and n > 0:
  201. return n + drift
  202. return n
  203. def is_due(self, entry):
  204. return entry.is_due()
  205. def _when(self, entry, next_time_to_run, mktime=time.mktime):
  206. adjust = self.adjust
  207. return (mktime(entry.default_now().timetuple()) +
  208. (adjust(next_time_to_run) or 0))
  209. def populate_heap(self, event_t=event_t, heapify=heapq.heapify):
  210. """Populate the heap with the data contained in the schedule."""
  211. self._heap = [event_t(self._when(e, e.is_due()[1]) or 0, 5, e)
  212. for e in values(self.schedule)]
  213. heapify(self._heap)
  214. # pylint disable=redefined-outer-name
  215. def tick(self, event_t=event_t, min=min, heappop=heapq.heappop,
  216. heappush=heapq.heappush):
  217. """Run a tick - one iteration of the scheduler.
  218. Executes one due task per call.
  219. Returns:
  220. float: preferred delay in seconds for next call.
  221. """
  222. adjust = self.adjust
  223. max_interval = self.max_interval
  224. if (self._heap is None or
  225. not self.schedules_equal(self.old_schedulers, self.schedule)):
  226. self.old_schedulers = copy.copy(self.schedule)
  227. self.populate_heap()
  228. H = self._heap
  229. if not H:
  230. return max_interval
  231. event = H[0]
  232. entry = event[2]
  233. is_due, next_time_to_run = self.is_due(entry)
  234. if is_due:
  235. verify = heappop(H)
  236. if verify is event:
  237. next_entry = self.reserve(entry)
  238. self.apply_entry(entry, producer=self.producer)
  239. heappush(H, event_t(self._when(next_entry, next_time_to_run),
  240. event[1], next_entry))
  241. return 0
  242. else:
  243. heappush(H, verify)
  244. return min(verify[0], max_interval)
  245. return min(adjust(next_time_to_run) or max_interval, max_interval)
  246. def schedules_equal(self, old_schedules, new_schedules):
  247. if set(old_schedules.keys()) != set(new_schedules.keys()):
  248. return False
  249. for name, old_entry in old_schedules.items():
  250. new_entry = new_schedules.get(name)
  251. if not new_entry:
  252. return False
  253. if new_entry != old_entry:
  254. return False
  255. return True
  256. def should_sync(self):
  257. return (
  258. (not self._last_sync or
  259. (monotonic() - self._last_sync) > self.sync_every) or
  260. (self.sync_every_tasks and
  261. self._tasks_since_sync >= self.sync_every_tasks)
  262. )
  263. def reserve(self, entry):
  264. new_entry = self.schedule[entry.name] = next(entry)
  265. return new_entry
  266. def apply_async(self, entry, producer=None, advance=True, **kwargs):
  267. # Update time-stamps and run counts before we actually execute,
  268. # so we have that done if an exception is raised (doesn't schedule
  269. # forever.)
  270. entry = self.reserve(entry) if advance else entry
  271. task = self.app.tasks.get(entry.task)
  272. try:
  273. if task:
  274. return task.apply_async(entry.args, entry.kwargs,
  275. producer=producer,
  276. **entry.options)
  277. else:
  278. return self.send_task(entry.task, entry.args, entry.kwargs,
  279. producer=producer,
  280. **entry.options)
  281. except Exception as exc: # pylint: disable=broad-except
  282. reraise(SchedulingError, SchedulingError(
  283. "Couldn't apply scheduled task {0.name}: {exc}".format(
  284. entry, exc=exc)), sys.exc_info()[2])
  285. finally:
  286. self._tasks_since_sync += 1
  287. if self.should_sync():
  288. self._do_sync()
  289. def send_task(self, *args, **kwargs):
  290. return self.app.send_task(*args, **kwargs)
  291. def setup_schedule(self):
  292. self.install_default_entries(self.data)
  293. def _do_sync(self):
  294. try:
  295. debug('beat: Synchronizing schedule...')
  296. self.sync()
  297. finally:
  298. self._last_sync = monotonic()
  299. self._tasks_since_sync = 0
  300. def sync(self):
  301. pass
  302. def close(self):
  303. self.sync()
  304. def add(self, **kwargs):
  305. entry = self.Entry(app=self.app, **kwargs)
  306. self.schedule[entry.name] = entry
  307. return entry
  308. def _maybe_entry(self, name, entry):
  309. if isinstance(entry, self.Entry):
  310. entry.app = self.app
  311. return entry
  312. return self.Entry(**dict(entry, name=name, app=self.app))
  313. def update_from_dict(self, dict_):
  314. self.schedule.update({
  315. name: self._maybe_entry(name, entry)
  316. for name, entry in items(dict_)
  317. })
  318. def merge_inplace(self, b):
  319. schedule = self.schedule
  320. A, B = set(schedule), set(b)
  321. # Remove items from disk not in the schedule anymore.
  322. for key in A ^ B:
  323. schedule.pop(key, None)
  324. # Update and add new items in the schedule
  325. for key in B:
  326. entry = self.Entry(**dict(b[key], name=key, app=self.app))
  327. if schedule.get(key):
  328. schedule[key].update(entry)
  329. else:
  330. schedule[key] = entry
  331. def _ensure_connected(self):
  332. # callback called for each retry while the connection
  333. # can't be established.
  334. def _error_handler(exc, interval):
  335. error('beat: Connection error: %s. '
  336. 'Trying again in %s seconds...', exc, interval)
  337. return self.connection.ensure_connection(
  338. _error_handler, self.app.conf.broker_connection_max_retries
  339. )
  340. def get_schedule(self):
  341. return self.data
  342. def set_schedule(self, schedule):
  343. self.data = schedule
  344. schedule = property(get_schedule, set_schedule)
  345. @cached_property
  346. def connection(self):
  347. return self.app.connection_for_write()
  348. @cached_property
  349. def producer(self):
  350. return self.Producer(self._ensure_connected(), auto_declare=False)
  351. @property
  352. def info(self):
  353. return ''
  354. class PersistentScheduler(Scheduler):
  355. """Scheduler backed by :mod:`shelve` database."""
  356. persistence = shelve
  357. known_suffixes = ('', '.db', '.dat', '.bak', '.dir')
  358. _store = None
  359. def __init__(self, *args, **kwargs):
  360. self.schedule_filename = kwargs.get('schedule_filename')
  361. Scheduler.__init__(self, *args, **kwargs)
  362. def _remove_db(self):
  363. for suffix in self.known_suffixes:
  364. with platforms.ignore_errno(errno.ENOENT):
  365. os.remove(self.schedule_filename + suffix)
  366. def _open_schedule(self):
  367. return self.persistence.open(self.schedule_filename, writeback=True)
  368. def _destroy_open_corrupted_schedule(self, exc):
  369. error('Removing corrupted schedule file %r: %r',
  370. self.schedule_filename, exc, exc_info=True)
  371. self._remove_db()
  372. return self._open_schedule()
  373. def setup_schedule(self):
  374. try:
  375. self._store = self._open_schedule()
  376. # In some cases there may be different errors from a storage
  377. # backend for corrupted files. Example - DBPageNotFoundError
  378. # exception from bsddb. In such case the file will be
  379. # successfully opened but the error will be raised on first key
  380. # retrieving.
  381. self._store.keys()
  382. except Exception as exc: # pylint: disable=broad-except
  383. self._store = self._destroy_open_corrupted_schedule(exc)
  384. self._create_schedule()
  385. tz = self.app.conf.timezone
  386. stored_tz = self._store.get(str('tz'))
  387. if stored_tz is not None and stored_tz != tz:
  388. warning('Reset: Timezone changed from %r to %r', stored_tz, tz)
  389. self._store.clear() # Timezone changed, reset db!
  390. utc = self.app.conf.enable_utc
  391. stored_utc = self._store.get(str('utc_enabled'))
  392. if stored_utc is not None and stored_utc != utc:
  393. choices = {True: 'enabled', False: 'disabled'}
  394. warning('Reset: UTC changed from %s to %s',
  395. choices[stored_utc], choices[utc])
  396. self._store.clear() # UTC setting changed, reset db!
  397. entries = self._store.setdefault(str('entries'), {})
  398. self.merge_inplace(self.app.conf.beat_schedule)
  399. self.install_default_entries(self.schedule)
  400. self._store.update({
  401. str('__version__'): __version__,
  402. str('tz'): tz,
  403. str('utc_enabled'): utc,
  404. })
  405. self.sync()
  406. debug('Current schedule:\n' + '\n'.join(
  407. repr(entry) for entry in values(entries)))
  408. def _create_schedule(self):
  409. for _ in (1, 2):
  410. try:
  411. self._store[str('entries')]
  412. except KeyError:
  413. # new schedule db
  414. try:
  415. self._store[str('entries')] = {}
  416. except KeyError as exc:
  417. self._store = self._destroy_open_corrupted_schedule(exc)
  418. continue
  419. else:
  420. if str('__version__') not in self._store:
  421. warning('DB Reset: Account for new __version__ field')
  422. self._store.clear() # remove schedule at 2.2.2 upgrade.
  423. elif str('tz') not in self._store:
  424. warning('DB Reset: Account for new tz field')
  425. self._store.clear() # remove schedule at 3.0.8 upgrade
  426. elif str('utc_enabled') not in self._store:
  427. warning('DB Reset: Account for new utc_enabled field')
  428. self._store.clear() # remove schedule at 3.0.9 upgrade
  429. break
  430. def get_schedule(self):
  431. return self._store[str('entries')]
  432. def set_schedule(self, schedule):
  433. self._store[str('entries')] = schedule
  434. schedule = property(get_schedule, set_schedule)
  435. def sync(self):
  436. if self._store is not None:
  437. self._store.sync()
  438. def close(self):
  439. self.sync()
  440. self._store.close()
  441. @property
  442. def info(self):
  443. return ' . db -> {self.schedule_filename}'.format(self=self)
  444. class Service(object):
  445. """Celery periodic task service."""
  446. scheduler_cls = PersistentScheduler
  447. def __init__(self, app, max_interval=None, schedule_filename=None,
  448. scheduler_cls=None):
  449. self.app = app
  450. self.max_interval = (max_interval or
  451. app.conf.beat_max_loop_interval)
  452. self.scheduler_cls = scheduler_cls or self.scheduler_cls
  453. self.schedule_filename = (
  454. schedule_filename or app.conf.beat_schedule_filename)
  455. self._is_shutdown = Event()
  456. self._is_stopped = Event()
  457. def __reduce__(self):
  458. return self.__class__, (self.max_interval, self.schedule_filename,
  459. self.scheduler_cls, self.app)
  460. def start(self, embedded_process=False):
  461. info('beat: Starting...')
  462. debug('beat: Ticking with max interval->%s',
  463. humanize_seconds(self.scheduler.max_interval))
  464. signals.beat_init.send(sender=self)
  465. if embedded_process:
  466. signals.beat_embedded_init.send(sender=self)
  467. platforms.set_process_title('celery beat')
  468. try:
  469. while not self._is_shutdown.is_set():
  470. interval = self.scheduler.tick()
  471. if interval and interval > 0.0:
  472. debug('beat: Waking up %s.',
  473. humanize_seconds(interval, prefix='in '))
  474. time.sleep(interval)
  475. if self.scheduler.should_sync():
  476. self.scheduler._do_sync()
  477. except (KeyboardInterrupt, SystemExit):
  478. self._is_shutdown.set()
  479. finally:
  480. self.sync()
  481. def sync(self):
  482. self.scheduler.close()
  483. self._is_stopped.set()
  484. def stop(self, wait=False):
  485. info('beat: Shutting down...')
  486. self._is_shutdown.set()
  487. wait and self._is_stopped.wait() # block until shutdown done.
  488. def get_scheduler(self, lazy=False,
  489. extension_namespace='celery.beat_schedulers'):
  490. filename = self.schedule_filename
  491. aliases = dict(
  492. load_extension_class_names(extension_namespace) or {})
  493. return symbol_by_name(self.scheduler_cls, aliases=aliases)(
  494. app=self.app,
  495. schedule_filename=filename,
  496. max_interval=self.max_interval,
  497. lazy=lazy,
  498. )
  499. @cached_property
  500. def scheduler(self):
  501. return self.get_scheduler()
  502. class _Threaded(Thread):
  503. """Embedded task scheduler using threading."""
  504. def __init__(self, app, **kwargs):
  505. super(_Threaded, self).__init__()
  506. self.app = app
  507. self.service = Service(app, **kwargs)
  508. self.daemon = True
  509. self.name = 'Beat'
  510. def run(self):
  511. self.app.set_current()
  512. self.service.start()
  513. def stop(self):
  514. self.service.stop(wait=True)
  515. try:
  516. ensure_multiprocessing()
  517. except NotImplementedError: # pragma: no cover
  518. _Process = None
  519. else:
  520. class _Process(Process): # noqa
  521. def __init__(self, app, **kwargs):
  522. super(_Process, self).__init__()
  523. self.app = app
  524. self.service = Service(app, **kwargs)
  525. self.name = 'Beat'
  526. def run(self):
  527. reset_signals(full=False)
  528. platforms.close_open_fds([
  529. sys.__stdin__, sys.__stdout__, sys.__stderr__,
  530. ] + list(iter_open_logger_fds()))
  531. self.app.set_default()
  532. self.app.set_current()
  533. self.service.start(embedded_process=True)
  534. def stop(self):
  535. self.service.stop()
  536. self.terminate()
  537. def EmbeddedService(app, max_interval=None, **kwargs):
  538. """Return embedded clock service.
  539. Arguments:
  540. thread (bool): Run threaded instead of as a separate process.
  541. Uses :mod:`multiprocessing` by default, if available.
  542. """
  543. if kwargs.pop('thread', False) or _Process is None:
  544. # Need short max interval to be able to stop thread
  545. # in reasonable time.
  546. return _Threaded(app, max_interval=1, **kwargs)
  547. return _Process(app, max_interval=max_interval, **kwargs)