beat.py 16 KB

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