beat.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 os
  10. import time
  11. import shelve
  12. import sys
  13. import traceback
  14. from threading import Event, Thread
  15. from billiard import Process, ensure_multiprocessing
  16. from kombu.utils import cached_property, reprcall
  17. from kombu.utils.functional import maybe_evaluate
  18. from . import __version__
  19. from . import platforms
  20. from . import signals
  21. from .five import items, reraise, values, monotonic
  22. from .schedules import maybe_schedule, crontab
  23. from .utils.imports import instantiate
  24. from .utils.timeutils import humanize_seconds
  25. from .utils.log import get_logger, iter_open_logger_fds
  26. __all__ = ['SchedulingError', 'ScheduleEntry', 'Scheduler',
  27. 'PersistentScheduler', 'Service', 'EmbeddedService']
  28. logger = get_logger(__name__)
  29. debug, info, error, warning = (logger.debug, logger.info,
  30. logger.error, logger.warning)
  31. DEFAULT_MAX_INTERVAL = 300 # 5 minutes
  32. class SchedulingError(Exception):
  33. """An error occured while scheduling a task."""
  34. class ScheduleEntry(object):
  35. """An entry in the scheduler.
  36. :keyword name: see :attr:`name`.
  37. :keyword schedule: see :attr:`schedule`.
  38. :keyword args: see :attr:`args`.
  39. :keyword kwargs: see :attr:`kwargs`.
  40. :keyword options: see :attr:`options`.
  41. :keyword last_run_at: see :attr:`last_run_at`.
  42. :keyword total_run_count: see :attr:`total_run_count`.
  43. :keyword relative: Is the time relative to when the server starts?
  44. """
  45. #: The task name
  46. name = None
  47. #: The schedule (run_every/crontab)
  48. schedule = None
  49. #: Positional arguments to apply.
  50. args = None
  51. #: Keyword arguments to apply.
  52. kwargs = None
  53. #: Task execution options.
  54. options = None
  55. #: The time and date of when this task was last scheduled.
  56. last_run_at = None
  57. #: Total number of times this task has been scheduled.
  58. total_run_count = 0
  59. def __init__(self, name=None, task=None, last_run_at=None,
  60. total_run_count=None, schedule=None, args=(), kwargs={},
  61. options={}, relative=False, app=None):
  62. self.app = app
  63. self.name = name
  64. self.task = task
  65. self.args = args
  66. self.kwargs = kwargs
  67. self.options = options
  68. self.schedule = maybe_schedule(schedule, relative, app=self.app)
  69. self.last_run_at = last_run_at or self._default_now()
  70. self.total_run_count = total_run_count or 0
  71. def _default_now(self):
  72. return self.schedule.now() if self.schedule else self.app.now()
  73. def _next_instance(self, last_run_at=None):
  74. """Return a new instance of the same class, but with
  75. its date and count fields updated."""
  76. return self.__class__(**dict(
  77. self,
  78. last_run_at=last_run_at or self._default_now(),
  79. total_run_count=self.total_run_count + 1,
  80. ))
  81. __next__ = next = _next_instance # for 2to3
  82. def __reduce__(self):
  83. return self.__class__, (
  84. self.name, self.task, self.last_run_at, self.total_run_count,
  85. self.schedule, self.args, self.kwargs, self.options,
  86. )
  87. def update(self, other):
  88. """Update values from another entry.
  89. Does only update "editable" fields (task, schedule, args, kwargs,
  90. options).
  91. """
  92. self.__dict__.update({'task': other.task, 'schedule': other.schedule,
  93. 'args': other.args, 'kwargs': other.kwargs,
  94. 'options': other.options})
  95. def is_due(self):
  96. """See :meth:`~celery.schedule.schedule.is_due`."""
  97. return self.schedule.is_due(self.last_run_at)
  98. def __iter__(self):
  99. return iter(items(vars(self)))
  100. def __repr__(self):
  101. return '<Entry: {0.name} {call} {0.schedule}'.format(
  102. self,
  103. call=reprcall(self.task, self.args or (), self.kwargs or {}),
  104. )
  105. class Scheduler(object):
  106. """Scheduler for periodic tasks.
  107. The :program:`celery beat` program may instantiate this class
  108. multiple times for introspection purposes, but then with the
  109. ``lazy`` argument set. It is important for subclasses to
  110. be idempotent when this argument is set.
  111. :keyword schedule: see :attr:`schedule`.
  112. :keyword max_interval: see :attr:`max_interval`.
  113. :keyword lazy: Do not set up the schedule.
  114. """
  115. Entry = ScheduleEntry
  116. #: The schedule dict/shelve.
  117. schedule = None
  118. #: Maximum time to sleep between re-checking the schedule.
  119. max_interval = DEFAULT_MAX_INTERVAL
  120. #: How often to sync the schedule (3 minutes by default)
  121. sync_every = 3 * 60
  122. _last_sync = None
  123. logger = logger # compat
  124. def __init__(self, app, schedule=None, max_interval=None,
  125. Publisher=None, lazy=False, **kwargs):
  126. self.app = app
  127. self.data = maybe_evaluate({} if schedule is None else schedule)
  128. self.max_interval = (max_interval
  129. or app.conf.CELERYBEAT_MAX_LOOP_INTERVAL
  130. or self.max_interval)
  131. self.Publisher = Publisher or app.amqp.TaskProducer
  132. if not lazy:
  133. self.setup_schedule()
  134. def install_default_entries(self, data):
  135. entries = {}
  136. if self.app.conf.CELERY_TASK_RESULT_EXPIRES and \
  137. not self.app.backend.supports_autoexpire:
  138. if 'celery.backend_cleanup' not in data:
  139. entries['celery.backend_cleanup'] = {
  140. 'task': 'celery.backend_cleanup',
  141. 'schedule': crontab('0', '4', '*'),
  142. 'options': {'expires': 12 * 3600}}
  143. self.update_from_dict(entries)
  144. def maybe_due(self, entry, publisher=None):
  145. is_due, next_time_to_run = entry.is_due()
  146. if is_due:
  147. info('Scheduler: Sending due task %s (%s)', entry.name, entry.task)
  148. try:
  149. result = self.apply_async(entry, publisher=publisher)
  150. except Exception as exc:
  151. error('Message Error: %s\n%s',
  152. exc, traceback.format_stack(), exc_info=True)
  153. else:
  154. debug('%s sent. id->%s', entry.task, result.id)
  155. return next_time_to_run
  156. def tick(self):
  157. """Run a tick, that is one iteration of the scheduler.
  158. Executes all due tasks.
  159. """
  160. remaining_times = []
  161. try:
  162. for entry in values(self.schedule):
  163. next_time_to_run = self.maybe_due(entry, self.publisher)
  164. if next_time_to_run:
  165. remaining_times.append(next_time_to_run)
  166. except RuntimeError:
  167. pass
  168. return min(remaining_times + [self.max_interval])
  169. def should_sync(self):
  170. return (not self._last_sync or
  171. (monotonic() - self._last_sync) > self.sync_every)
  172. def reserve(self, entry):
  173. new_entry = self.schedule[entry.name] = next(entry)
  174. return new_entry
  175. def apply_async(self, entry, publisher=None, **kwargs):
  176. # Update timestamps and run counts before we actually execute,
  177. # so we have that done if an exception is raised (doesn't schedule
  178. # forever.)
  179. entry = self.reserve(entry)
  180. task = self.app.tasks.get(entry.task)
  181. try:
  182. if task:
  183. result = task.apply_async(entry.args, entry.kwargs,
  184. publisher=publisher,
  185. **entry.options)
  186. else:
  187. result = self.send_task(entry.task, entry.args, entry.kwargs,
  188. publisher=publisher,
  189. **entry.options)
  190. except Exception as exc:
  191. reraise(SchedulingError, SchedulingError(
  192. "Couldn't apply scheduled task {0.name}: {exc}".format(
  193. entry, exc=exc)), sys.exc_info()[2])
  194. finally:
  195. if self.should_sync():
  196. self._do_sync()
  197. return result
  198. def send_task(self, *args, **kwargs):
  199. return self.app.send_task(*args, **kwargs)
  200. def setup_schedule(self):
  201. self.install_default_entries(self.data)
  202. def _do_sync(self):
  203. try:
  204. debug('beat: Synchronizing schedule...')
  205. self.sync()
  206. finally:
  207. self._last_sync = monotonic()
  208. def sync(self):
  209. pass
  210. def close(self):
  211. self.sync()
  212. def add(self, **kwargs):
  213. entry = self.Entry(app=self.app, **kwargs)
  214. self.schedule[entry.name] = entry
  215. return entry
  216. def _maybe_entry(self, name, entry):
  217. if isinstance(entry, self.Entry):
  218. entry.app = self.app
  219. return entry
  220. return self.Entry(**dict(entry, name=name, app=self.app))
  221. def update_from_dict(self, dict_):
  222. self.schedule.update(dict(
  223. (name, self._maybe_entry(name, entry))
  224. for name, entry in items(dict_)))
  225. def merge_inplace(self, b):
  226. schedule = self.schedule
  227. A, B = set(schedule), set(b)
  228. # Remove items from disk not in the schedule anymore.
  229. for key in A ^ B:
  230. schedule.pop(key, None)
  231. # Update and add new items in the schedule
  232. for key in B:
  233. entry = self.Entry(**dict(b[key], name=key, app=self.app))
  234. if schedule.get(key):
  235. schedule[key].update(entry)
  236. else:
  237. schedule[key] = entry
  238. def _ensure_connected(self):
  239. # callback called for each retry while the connection
  240. # can't be established.
  241. def _error_handler(exc, interval):
  242. error('beat: Connection error: %s. '
  243. 'Trying again in %s seconds...', exc, interval)
  244. return self.connection.ensure_connection(
  245. _error_handler, self.app.conf.BROKER_CONNECTION_MAX_RETRIES
  246. )
  247. def get_schedule(self):
  248. return self.data
  249. def set_schedule(self, schedule):
  250. self.data = schedule
  251. schedule = property(get_schedule, set_schedule)
  252. @cached_property
  253. def connection(self):
  254. return self.app.connection()
  255. @cached_property
  256. def publisher(self):
  257. return self.Publisher(self._ensure_connected())
  258. @property
  259. def info(self):
  260. return ''
  261. class PersistentScheduler(Scheduler):
  262. persistence = shelve
  263. known_suffixes = ('', '.db', '.dat', '.bak', '.dir')
  264. _store = None
  265. def __init__(self, *args, **kwargs):
  266. self.schedule_filename = kwargs.get('schedule_filename')
  267. Scheduler.__init__(self, *args, **kwargs)
  268. def _remove_db(self):
  269. for suffix in self.known_suffixes:
  270. with platforms.ignore_errno(errno.ENOENT):
  271. os.remove(self.schedule_filename + suffix)
  272. def setup_schedule(self):
  273. try:
  274. self._store = self.persistence.open(self.schedule_filename,
  275. writeback=True)
  276. entries = self._store.setdefault('entries', {})
  277. except Exception as exc:
  278. error('Removing corrupted schedule file %r: %r',
  279. self.schedule_filename, exc, exc_info=True)
  280. self._remove_db()
  281. self._store = self.persistence.open(self.schedule_filename,
  282. writeback=True)
  283. else:
  284. if '__version__' not in self._store:
  285. warning('Reset: Account for new __version__ field')
  286. self._store.clear() # remove schedule at 2.2.2 upgrade.
  287. if 'tz' not in self._store:
  288. warning('Reset: Account for new tz field')
  289. self._store.clear() # remove schedule at 3.0.8 upgrade
  290. if 'utc_enabled' not in self._store:
  291. warning('Reset: Account for new utc_enabled field')
  292. self._store.clear() # remove schedule at 3.0.9 upgrade
  293. tz = self.app.conf.CELERY_TIMEZONE
  294. stored_tz = self._store.get('tz')
  295. if stored_tz is not None and stored_tz != tz:
  296. warning('Reset: Timezone changed from %r to %r', stored_tz, tz)
  297. self._store.clear() # Timezone changed, reset db!
  298. utc = self.app.conf.CELERY_ENABLE_UTC
  299. stored_utc = self._store.get('utc_enabled')
  300. if stored_utc is not None and stored_utc != utc:
  301. choices = {True: 'enabled', False: 'disabled'}
  302. warning('Reset: UTC changed from %s to %s',
  303. choices[stored_utc], choices[utc])
  304. self._store.clear() # UTC setting changed, reset db!
  305. entries = self._store.setdefault('entries', {})
  306. self.merge_inplace(self.app.conf.CELERYBEAT_SCHEDULE)
  307. self.install_default_entries(self.schedule)
  308. self._store.update(__version__=__version__, tz=tz, utc_enabled=utc)
  309. self.sync()
  310. debug('Current schedule:\n' + '\n'.join(
  311. repr(entry) for entry in values(entries)))
  312. def get_schedule(self):
  313. return self._store['entries']
  314. def set_schedule(self, schedule):
  315. self._store['entries'] = schedule
  316. schedule = property(get_schedule, set_schedule)
  317. def sync(self):
  318. if self._store is not None:
  319. self._store.sync()
  320. def close(self):
  321. self.sync()
  322. self._store.close()
  323. @property
  324. def info(self):
  325. return ' . db -> {self.schedule_filename}'.format(self=self)
  326. class Service(object):
  327. scheduler_cls = PersistentScheduler
  328. def __init__(self, app, max_interval=None, schedule_filename=None,
  329. scheduler_cls=None):
  330. self.app = app
  331. self.max_interval = (max_interval
  332. or app.conf.CELERYBEAT_MAX_LOOP_INTERVAL)
  333. self.scheduler_cls = scheduler_cls or self.scheduler_cls
  334. self.schedule_filename = (
  335. schedule_filename or app.conf.CELERYBEAT_SCHEDULE_FILENAME)
  336. self._is_shutdown = Event()
  337. self._is_stopped = Event()
  338. def __reduce__(self):
  339. return self.__class__, (self.max_interval, self.schedule_filename,
  340. self.scheduler_cls, self.app)
  341. def start(self, embedded_process=False):
  342. info('beat: Starting...')
  343. debug('beat: Ticking with max interval->%s',
  344. humanize_seconds(self.scheduler.max_interval))
  345. signals.beat_init.send(sender=self)
  346. if embedded_process:
  347. signals.beat_embedded_init.send(sender=self)
  348. platforms.set_process_title('celery beat')
  349. try:
  350. while not self._is_shutdown.is_set():
  351. interval = self.scheduler.tick()
  352. debug('beat: Waking up %s.',
  353. humanize_seconds(interval, prefix='in '))
  354. time.sleep(interval)
  355. except (KeyboardInterrupt, SystemExit):
  356. self._is_shutdown.set()
  357. finally:
  358. self.sync()
  359. def sync(self):
  360. self.scheduler.close()
  361. self._is_stopped.set()
  362. def stop(self, wait=False):
  363. info('beat: Shutting down...')
  364. self._is_shutdown.set()
  365. wait and self._is_stopped.wait() # block until shutdown done.
  366. def get_scheduler(self, lazy=False):
  367. filename = self.schedule_filename
  368. scheduler = instantiate(self.scheduler_cls,
  369. app=self.app,
  370. schedule_filename=filename,
  371. max_interval=self.max_interval,
  372. lazy=lazy)
  373. return scheduler
  374. @cached_property
  375. def scheduler(self):
  376. return self.get_scheduler()
  377. class _Threaded(Thread):
  378. """Embedded task scheduler using threading."""
  379. def __init__(self, *args, **kwargs):
  380. super(_Threaded, self).__init__()
  381. self.service = Service(*args, **kwargs)
  382. self.daemon = True
  383. self.name = 'Beat'
  384. def run(self):
  385. self.service.start()
  386. def stop(self):
  387. self.service.stop(wait=True)
  388. try:
  389. ensure_multiprocessing()
  390. except NotImplementedError: # pragma: no cover
  391. _Process = None
  392. else:
  393. class _Process(Process): # noqa
  394. def __init__(self, *args, **kwargs):
  395. super(_Process, self).__init__()
  396. self.service = Service(*args, **kwargs)
  397. self.name = 'Beat'
  398. def run(self):
  399. platforms.signals.reset('SIGTERM')
  400. platforms.close_open_fds([
  401. sys.__stdin__, sys.__stdout__, sys.__stderr__,
  402. ] + list(iter_open_logger_fds()))
  403. self.service.start(embedded_process=True)
  404. def stop(self):
  405. self.service.stop()
  406. self.terminate()
  407. def EmbeddedService(*args, **kwargs):
  408. """Return embedded clock service.
  409. :keyword thread: Run threaded instead of as a separate process.
  410. Uses :mod:`multiprocessing` by default, if available.
  411. """
  412. if kwargs.pop('thread', False) or _Process is None:
  413. # Need short max interval to be able to stop thread
  414. # in reasonable time.
  415. kwargs.setdefault('max_interval', 1)
  416. return _Threaded(*args, **kwargs)
  417. return _Process(*args, **kwargs)