beat.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.beat
  4. ~~~~~~~~~~~
  5. The Celery periodic task scheduler.
  6. :copyright: (c) 2009 - 2012 by Ask Solem.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from __future__ import absolute_import
  10. import errno
  11. import os
  12. import time
  13. import shelve
  14. import sys
  15. import threading
  16. import traceback
  17. try:
  18. import multiprocessing
  19. except ImportError:
  20. multiprocessing = None # noqa
  21. from . import __version__
  22. from . import platforms
  23. from . import registry
  24. from . import signals
  25. from . import current_app
  26. from .app import app_or_default
  27. from .log import SilenceRepeated
  28. from .schedules import maybe_schedule, crontab
  29. from .utils import cached_property, instantiate, maybe_promise
  30. from .utils.timeutils import humanize_seconds
  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.task.base.PeriodicTask.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: %(name)s %(task)s(*%(args)s, **%(kwargs)s) "
  93. "{%(schedule)s}>" % vars(self))
  94. class Scheduler(object):
  95. """Scheduler for periodic tasks.
  96. :keyword schedule: see :attr:`schedule`.
  97. :keyword logger: see :attr:`logger`.
  98. :keyword max_interval: see :attr:`max_interval`.
  99. """
  100. Entry = ScheduleEntry
  101. #: The schedule dict/shelve.
  102. schedule = None
  103. #: Current logger.
  104. logger = None
  105. #: Maximum time to sleep between re-checking the schedule.
  106. max_interval = 1
  107. #: How often to sync the schedule (3 minutes by default)
  108. sync_every = 3 * 60
  109. _last_sync = None
  110. def __init__(self, schedule=None, logger=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.logger = logger or app.log.get_default_logger(name="celery.beat")
  115. self.max_interval = max_interval or \
  116. app.conf.CELERYBEAT_MAX_LOOP_INTERVAL
  117. self.Publisher = Publisher or app.amqp.TaskPublisher
  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. self.logger.debug("Scheduler: Sending due task %s", entry.task)
  133. try:
  134. result = self.apply_async(entry, publisher=publisher)
  135. except Exception, exc:
  136. self.logger.error("Message Error: %s\n%s", exc,
  137. traceback.format_stack(),
  138. exc_info=sys.exc_info())
  139. else:
  140. self.logger.debug("%s sent. id->%s", entry.task,
  141. result.task_id)
  142. return next_time_to_run
  143. def tick(self):
  144. """Run a tick, that is one iteration of the scheduler.
  145. Executes all due tasks.
  146. """
  147. remaining_times = []
  148. try:
  149. for entry in self.schedule.itervalues():
  150. next_time_to_run = self.maybe_due(entry, self.publisher)
  151. if next_time_to_run:
  152. remaining_times.append(next_time_to_run)
  153. except RuntimeError:
  154. pass
  155. return min(remaining_times + [self.max_interval])
  156. def should_sync(self):
  157. return (not self._last_sync or
  158. (time.time() - self._last_sync) > self.sync_every)
  159. def reserve(self, entry):
  160. new_entry = self.schedule[entry.name] = entry.next()
  161. return new_entry
  162. def apply_async(self, entry, publisher=None, **kwargs):
  163. # Update timestamps and run counts before we actually execute,
  164. # so we have that done if an exception is raised (doesn't schedule
  165. # forever.)
  166. entry = self.reserve(entry)
  167. task = registry.tasks.get(entry.task)
  168. try:
  169. if task:
  170. result = task.apply_async(entry.args, entry.kwargs,
  171. publisher=publisher,
  172. **entry.options)
  173. else:
  174. result = self.send_task(entry.task, entry.args, entry.kwargs,
  175. publisher=publisher,
  176. **entry.options)
  177. except Exception, exc:
  178. raise SchedulingError, SchedulingError(
  179. "Couldn't apply scheduled task %s: %s" % (
  180. entry.name, exc)), sys.exc_info()[2]
  181. if self.should_sync():
  182. self._do_sync()
  183. return result
  184. def send_task(self, *args, **kwargs): # pragma: no cover
  185. return self.app.send_task(*args, **kwargs)
  186. def setup_schedule(self):
  187. self.install_default_entries(self.data)
  188. def _do_sync(self):
  189. try:
  190. self.logger.debug("Celerybeat: Synchronizing schedule...")
  191. self.sync()
  192. finally:
  193. self._last_sync = time.time()
  194. def sync(self):
  195. pass
  196. def close(self):
  197. self.sync()
  198. def add(self, **kwargs):
  199. entry = self.Entry(**kwargs)
  200. self.schedule[entry.name] = entry
  201. return entry
  202. def _maybe_entry(self, name, entry):
  203. if isinstance(entry, self.Entry):
  204. return entry
  205. return self.Entry(**dict(entry, name=name))
  206. def update_from_dict(self, dict_):
  207. self.schedule.update(dict((name, self._maybe_entry(name, entry))
  208. for name, entry in dict_.items()))
  209. def merge_inplace(self, b):
  210. schedule = self.schedule
  211. A, B = set(schedule), set(b)
  212. # Remove items from disk not in the schedule anymore.
  213. for key in A ^ B:
  214. schedule.pop(key, None)
  215. # Update and add new items in the schedule
  216. for key in B:
  217. entry = self.Entry(**dict(b[key], name=key))
  218. if schedule.get(key):
  219. schedule[key].update(entry)
  220. else:
  221. schedule[key] = entry
  222. def get_schedule(self):
  223. return self.data
  224. def set_schedule(self, schedule):
  225. self.data = schedule
  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. self.logger.error("Celerybeat: Connection error: %s. "
  231. "Trying again in %s seconds...", exc, interval)
  232. return self.connection.ensure_connection(_error_handler,
  233. self.app.conf.BROKER_CONNECTION_MAX_RETRIES)
  234. @cached_property
  235. def connection(self):
  236. return self.app.broker_connection()
  237. @cached_property
  238. def publisher(self):
  239. return self.Publisher(connection=self._ensure_connected())
  240. @property
  241. def schedule(self):
  242. return self.get_schedule()
  243. @property
  244. def info(self):
  245. return ""
  246. class PersistentScheduler(Scheduler):
  247. persistence = shelve
  248. _store = None
  249. def __init__(self, *args, **kwargs):
  250. self.schedule_filename = kwargs.get("schedule_filename")
  251. Scheduler.__init__(self, *args, **kwargs)
  252. def _remove_db(self):
  253. for suffix in "", ".db", ".dat", ".bak", ".dir":
  254. try:
  255. os.remove(self.schedule_filename + suffix)
  256. except OSError, exc:
  257. if exc.errno != errno.ENOENT:
  258. raise
  259. def setup_schedule(self):
  260. try:
  261. self._store = self.persistence.open(self.schedule_filename,
  262. writeback=True)
  263. entries = self._store.setdefault("entries", {})
  264. except Exception, exc:
  265. self.logger.error("Removing corrupted schedule file %r: %r",
  266. self.schedule_filename, exc, exc_info=True)
  267. self._remove_db()
  268. self._store = self.persistence.open(self.schedule_filename,
  269. writeback=True)
  270. else:
  271. if "__version__" not in self._store:
  272. self._store.clear() # remove schedule at 2.2.2 upgrade.
  273. entries = self._store.setdefault("entries", {})
  274. self.merge_inplace(self.app.conf.CELERYBEAT_SCHEDULE)
  275. self.install_default_entries(self.schedule)
  276. self._store["__version__"] = __version__
  277. self.sync()
  278. self.logger.debug("Current schedule:\n" +
  279. "\n".join(repr(entry)
  280. for entry in entries.itervalues()))
  281. def get_schedule(self):
  282. return self._store["entries"]
  283. def sync(self):
  284. if self._store is not None:
  285. self._store.sync()
  286. def close(self):
  287. self.sync()
  288. self._store.close()
  289. @property
  290. def info(self):
  291. return " . db -> %s" % (self.schedule_filename, )
  292. class Service(object):
  293. scheduler_cls = PersistentScheduler
  294. def __init__(self, logger=None, max_interval=None, schedule_filename=None,
  295. scheduler_cls=None, app=None):
  296. app = self.app = app_or_default(app)
  297. self.max_interval = max_interval or \
  298. app.conf.CELERYBEAT_MAX_LOOP_INTERVAL
  299. self.scheduler_cls = scheduler_cls or self.scheduler_cls
  300. self.logger = logger or app.log.get_default_logger(name="celery.beat")
  301. self.schedule_filename = schedule_filename or \
  302. app.conf.CELERYBEAT_SCHEDULE_FILENAME
  303. self._is_shutdown = threading.Event()
  304. self._is_stopped = threading.Event()
  305. self.debug = SilenceRepeated(self.logger.debug,
  306. 10 if self.max_interval < 60 else 1)
  307. def start(self, embedded_process=False):
  308. self.logger.info("Celerybeat: Starting...")
  309. self.logger.debug("Celerybeat: Ticking with max interval->%s",
  310. humanize_seconds(self.scheduler.max_interval))
  311. signals.beat_init.send(sender=self)
  312. if embedded_process:
  313. signals.beat_embedded_init.send(sender=self)
  314. platforms.set_process_title("celerybeat")
  315. try:
  316. while not self._is_shutdown.isSet():
  317. interval = self.scheduler.tick()
  318. self.debug("Celerybeat: Waking up %s." % (
  319. humanize_seconds(interval, prefix="in ")))
  320. time.sleep(interval)
  321. except (KeyboardInterrupt, SystemExit):
  322. self._is_shutdown.set()
  323. finally:
  324. self.sync()
  325. def sync(self):
  326. self.scheduler.close()
  327. self._is_stopped.set()
  328. def stop(self, wait=False):
  329. self.logger.info("Celerybeat: Shutting down...")
  330. self._is_shutdown.set()
  331. wait and self._is_stopped.wait() # block until shutdown done.
  332. def get_scheduler(self, lazy=False):
  333. filename = self.schedule_filename
  334. scheduler = instantiate(self.scheduler_cls,
  335. app=self.app,
  336. schedule_filename=filename,
  337. logger=self.logger,
  338. max_interval=self.max_interval,
  339. lazy=lazy)
  340. return scheduler
  341. @cached_property
  342. def scheduler(self):
  343. return self.get_scheduler()
  344. class _Threaded(threading.Thread):
  345. """Embedded task scheduler using threading."""
  346. def __init__(self, *args, **kwargs):
  347. super(_Threaded, self).__init__()
  348. self.service = Service(*args, **kwargs)
  349. self.setDaemon(True)
  350. self.setName("Beat")
  351. def run(self):
  352. self.service.start()
  353. def stop(self):
  354. self.service.stop(wait=True)
  355. if multiprocessing is not None:
  356. class _Process(multiprocessing.Process):
  357. """Embedded task scheduler using multiprocessing."""
  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. else:
  369. _Process = None
  370. def EmbeddedService(*args, **kwargs):
  371. """Return embedded clock service.
  372. :keyword thread: Run threaded instead of as a separate process.
  373. Default is :const:`False`.
  374. """
  375. if kwargs.pop("thread", False) or _Process is None:
  376. # Need short max interval to be able to stop thread
  377. # in reasonable time.
  378. kwargs.setdefault("max_interval", 1)
  379. return _Threaded(*args, **kwargs)
  380. return _Process(*args, **kwargs)