beat.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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 billiard import Process, ensure_multiprocessing
  15. from kombu.utils import reprcall
  16. from kombu.utils.functional import maybe_promise
  17. from . import __version__
  18. from . import platforms
  19. from . import signals
  20. from . import current_app
  21. from .app import app_or_default
  22. from .schedules import maybe_schedule, crontab
  23. from .utils import cached_property
  24. from .utils.imports import instantiate
  25. from .utils.threads import Event, Thread
  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, 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] = entry.next()
  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, 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, 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, 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. entries = self._store.setdefault('entries', {})
  271. self.merge_inplace(self.app.conf.CELERYBEAT_SCHEDULE)
  272. self.install_default_entries(self.schedule)
  273. self._store['__version__'] = __version__
  274. self.sync()
  275. debug('Current schedule:\n' + '\n'.join(repr(entry)
  276. for entry in entries.itervalues()))
  277. def get_schedule(self):
  278. return self._store['entries']
  279. def set_schedule(self, schedule):
  280. self._store['entries'] = schedule
  281. schedule = property(get_schedule, set_schedule)
  282. def sync(self):
  283. if self._store is not None:
  284. self._store.sync()
  285. def close(self):
  286. self.sync()
  287. self._store.close()
  288. @property
  289. def info(self):
  290. return ' . db -> %s' % (self.schedule_filename, )
  291. class Service(object):
  292. scheduler_cls = PersistentScheduler
  293. def __init__(self, max_interval=None, schedule_filename=None,
  294. scheduler_cls=None, app=None):
  295. app = self.app = app_or_default(app)
  296. self.max_interval = (max_interval
  297. or app.conf.CELERYBEAT_MAX_LOOP_INTERVAL)
  298. self.scheduler_cls = scheduler_cls or self.scheduler_cls
  299. self.schedule_filename = schedule_filename or \
  300. app.conf.CELERYBEAT_SCHEDULE_FILENAME
  301. self._is_shutdown = Event()
  302. self._is_stopped = Event()
  303. def start(self, embedded_process=False):
  304. info('Celerybeat: Starting...')
  305. debug('Celerybeat: Ticking with max interval->%s',
  306. humanize_seconds(self.scheduler.max_interval))
  307. signals.beat_init.send(sender=self)
  308. if embedded_process:
  309. signals.beat_embedded_init.send(sender=self)
  310. platforms.set_process_title('celerybeat')
  311. try:
  312. while not self._is_shutdown.is_set():
  313. interval = self.scheduler.tick()
  314. debug('Celerybeat: Waking up %s.',
  315. humanize_seconds(interval, prefix='in '))
  316. time.sleep(interval)
  317. except (KeyboardInterrupt, SystemExit):
  318. self._is_shutdown.set()
  319. finally:
  320. self.sync()
  321. def sync(self):
  322. self.scheduler.close()
  323. self._is_stopped.set()
  324. def stop(self, wait=False):
  325. info('Celerybeat: Shutting down...')
  326. self._is_shutdown.set()
  327. wait and self._is_stopped.wait() # block until shutdown done.
  328. def get_scheduler(self, lazy=False):
  329. filename = self.schedule_filename
  330. scheduler = instantiate(self.scheduler_cls,
  331. app=self.app,
  332. schedule_filename=filename,
  333. max_interval=self.max_interval,
  334. lazy=lazy)
  335. return scheduler
  336. @cached_property
  337. def scheduler(self):
  338. return self.get_scheduler()
  339. class _Threaded(Thread):
  340. """Embedded task scheduler using threading."""
  341. def __init__(self, *args, **kwargs):
  342. super(_Threaded, self).__init__()
  343. self.service = Service(*args, **kwargs)
  344. self.daemon = True
  345. self.name = 'Beat'
  346. def run(self):
  347. self.service.start()
  348. def stop(self):
  349. self.service.stop(wait=True)
  350. try:
  351. ensure_multiprocessing()
  352. except NotImplementedError: # pragma: no cover
  353. _Process = None
  354. else:
  355. class _Process(Process): # noqa
  356. def __init__(self, *args, **kwargs):
  357. super(_Process, self).__init__()
  358. self.service = Service(*args, **kwargs)
  359. self.name = 'Beat'
  360. def run(self):
  361. platforms.signals.reset('SIGTERM')
  362. self.service.start(embedded_process=True)
  363. def stop(self):
  364. self.service.stop()
  365. self.terminate()
  366. def EmbeddedService(*args, **kwargs):
  367. """Return embedded clock service.
  368. :keyword thread: Run threaded instead of as a separate process.
  369. Default is :const:`False`.
  370. """
  371. if kwargs.pop('thread', False) or _Process is None:
  372. # Need short max interval to be able to stop thread
  373. # in reasonable time.
  374. kwargs.setdefault('max_interval', 1)
  375. return _Threaded(*args, **kwargs)
  376. return _Process(*args, **kwargs)