beat.py 15 KB

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