beat.py 16 KB

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