beat.py 20 KB

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