base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. import sys
  2. import warnings
  3. from celery import conf
  4. from celery.backends import default_backend
  5. from celery.exceptions import MaxRetriesExceededError, RetryTaskError
  6. from celery.execute import apply_async, apply
  7. from celery.log import setup_task_logger
  8. from celery.messaging import TaskPublisher, TaskConsumer
  9. from celery.messaging import establish_connection as _establish_connection
  10. from celery.registry import tasks
  11. from celery.result import BaseAsyncResult, EagerResult
  12. from celery.schedules import maybe_schedule
  13. from celery.utils.timeutils import timedelta_seconds
  14. from celery.task.sets import TaskSet, subtask
  15. PERIODIC_DEPRECATION_TEXT = """\
  16. Periodic task classes has been deprecated and will be removed
  17. in celery v3.0.
  18. Please use the CELERYBEAT_SCHEDULE setting instead:
  19. CELERYBEAT_SCHEDULE = {
  20. name: dict(task=task_name, schedule=run_every,
  21. args=(), kwargs={}, options={}, relative=False)
  22. }
  23. """
  24. def _unpickle_task(name):
  25. return tasks[name]
  26. class TaskType(type):
  27. """Metaclass for tasks.
  28. Automatically registers the task in the task registry, except
  29. if the ``abstract`` attribute is set.
  30. If no ``name`` attribute is provided, the name is automatically
  31. set to the name of the module it was defined in, and the class name.
  32. """
  33. def __new__(cls, name, bases, attrs):
  34. super_new = super(TaskType, cls).__new__
  35. task_module = attrs["__module__"]
  36. # Abstract class, remove the abstract attribute so
  37. # any class inheriting from this won't be abstract by default.
  38. if attrs.pop("abstract", None) or not attrs.get("autoregister", True):
  39. return super_new(cls, name, bases, attrs)
  40. # Automatically generate missing name.
  41. if not attrs.get("name"):
  42. task_module = sys.modules[task_module]
  43. task_name = ".".join([task_module.__name__, name])
  44. attrs["name"] = task_name
  45. # Because of the way import happens (recursively)
  46. # we may or may not be the first time the task tries to register
  47. # with the framework. There should only be one class for each task
  48. # name, so we always return the registered version.
  49. task_name = attrs["name"]
  50. if task_name not in tasks:
  51. task_cls = super_new(cls, name, bases, attrs)
  52. tasks.register(task_cls)
  53. return tasks[task_name].__class__
  54. class Task(object):
  55. """A celery task.
  56. All subclasses of :class:`Task` must define the :meth:`run` method,
  57. which is the actual method the ``celery`` daemon executes.
  58. The :meth:`run` method can take use of the default keyword arguments,
  59. as listed in the :meth:`run` documentation.
  60. The resulting class is callable, which if called will apply the
  61. :meth:`run` method.
  62. .. attribute:: name
  63. Name of the task.
  64. .. attribute:: abstract
  65. If ``True`` the task is an abstract base class.
  66. .. attribute:: type
  67. The type of task, currently this can be ``regular``, or ``periodic``,
  68. however if you want a periodic task, you should subclass
  69. :class:`PeriodicTask` instead.
  70. .. attribute:: queue
  71. Select a destination queue for this task. The queue needs to exist
  72. in ``CELERY_QUEUES``. The ``routing_key``, ``exchange`` and
  73. ``exchange_type`` attributes will be ignored if this is set.
  74. .. attribute:: routing_key
  75. Override the global default ``routing_key`` for this task.
  76. .. attribute:: exchange
  77. Override the global default ``exchange`` for this task.
  78. .. attribute:: exchange_type
  79. Override the global default exchange type for this task.
  80. .. attribute:: delivery_mode
  81. Override the global default delivery mode for this task.
  82. By default this is set to ``2`` (persistent). You can change this
  83. to ``1`` to get non-persistent behavior, which means the messages
  84. are lost if the broker is restarted.
  85. .. attribute:: mandatory
  86. Mandatory message routing. An exception will be raised if the task
  87. can't be routed to a queue.
  88. .. attribute:: immediate:
  89. Request immediate delivery. An exception will be raised if the task
  90. can't be routed to a worker immediately.
  91. .. attribute:: priority:
  92. The message priority. A number from ``0`` to ``9``, where ``0`` is the
  93. highest. Note that RabbitMQ doesn't support priorities yet.
  94. .. attribute:: max_retries
  95. Maximum number of retries before giving up.
  96. If set to ``None``, it will never stop retrying.
  97. .. attribute:: default_retry_delay
  98. Default time in seconds before a retry of the task should be
  99. executed. Default is a 3 minute delay.
  100. .. attribute:: rate_limit
  101. Set the rate limit for this task type, Examples: ``None`` (no rate
  102. limit), ``"100/s"`` (hundred tasks a second), ``"100/m"`` (hundred
  103. tasks a minute), ``"100/h"`` (hundred tasks an hour)
  104. .. attribute:: ignore_result
  105. Don't store the return value of this task.
  106. .. attribute:: disable_error_emails
  107. Disable all error e-mails for this task (only applicable if
  108. ``settings.CELERY_SEND_TASK_ERROR_EMAILS`` is on.)
  109. .. attribute:: serializer
  110. The name of a serializer that has been registered with
  111. :mod:`carrot.serialization.registry`. Example: ``"json"``.
  112. .. attribute:: backend
  113. The result store backend used for this task.
  114. .. attribute:: autoregister
  115. If ``True`` the task is automatically registered in the task
  116. registry, which is the default behaviour.
  117. .. attribute:: track_started
  118. If ``True`` the task will report its status as "started"
  119. when the task is executed by a worker.
  120. The default value is ``False`` as the normal behaviour is to not
  121. report that level of granularity. Tasks are either pending, finished,
  122. or waiting to be retried. Having a "started" status can be useful for
  123. when there are long running tasks and there is a need to report which
  124. task is currently running.
  125. The global default can be overridden by the ``CELERY_TRACK_STARTED``
  126. setting.
  127. .. attribute:: acks_late
  128. If set to ``True`` messages for this task will be acknowledged
  129. **after** the task has been executed, not *just before*, which is
  130. the default behavior.
  131. Note that this means the task may be executed twice if the worker
  132. crashes in the middle of execution, which may be acceptable for some
  133. applications.
  134. The global default can be overriden by the ``CELERY_ACKS_LATE``
  135. setting.
  136. """
  137. __metaclass__ = TaskType
  138. name = None
  139. abstract = True
  140. autoregister = True
  141. type = "regular"
  142. queue = None
  143. routing_key = None
  144. exchange = None
  145. exchange_type = conf.DEFAULT_EXCHANGE_TYPE
  146. delivery_mode = conf.DEFAULT_DELIVERY_MODE
  147. immediate = False
  148. mandatory = False
  149. priority = None
  150. ignore_result = conf.IGNORE_RESULT
  151. disable_error_emails = False
  152. max_retries = 3
  153. default_retry_delay = 3 * 60
  154. expires = None
  155. serializer = conf.TASK_SERIALIZER
  156. rate_limit = conf.DEFAULT_RATE_LIMIT
  157. backend = default_backend
  158. track_started = conf.TRACK_STARTED
  159. acks_late = conf.ACKS_LATE
  160. MaxRetriesExceededError = MaxRetriesExceededError
  161. def __call__(self, *args, **kwargs):
  162. return self.run(*args, **kwargs)
  163. def __reduce__(self):
  164. return (_unpickle_task, (self.name, ), None)
  165. def run(self, *args, **kwargs):
  166. """The body of the task executed by the worker.
  167. The following standard keyword arguments are reserved and is passed
  168. by the worker if the function/method supports them:
  169. * task_id
  170. * task_name
  171. * task_retries
  172. * task_is_eager
  173. * logfile
  174. * loglevel
  175. * delivery_info
  176. Additional standard keyword arguments may be added in the future.
  177. To take these default arguments, the task can either list the ones
  178. it wants explicitly or just take an arbitrary list of keyword
  179. arguments (\*\*kwargs).
  180. """
  181. raise NotImplementedError("Tasks must define the run method.")
  182. @classmethod
  183. def get_logger(self, loglevel=None, logfile=None, **kwargs):
  184. """Get task-aware logger object.
  185. See :func:`celery.log.setup_task_logger`.
  186. """
  187. return setup_task_logger(loglevel=loglevel, logfile=logfile,
  188. task_kwargs=kwargs)
  189. @classmethod
  190. def establish_connection(self,
  191. connect_timeout=conf.BROKER_CONNECTION_TIMEOUT):
  192. """Establish a connection to the message broker."""
  193. return _establish_connection(connect_timeout=connect_timeout)
  194. @classmethod
  195. def get_publisher(self, connection=None, exchange=None,
  196. connect_timeout=conf.BROKER_CONNECTION_TIMEOUT,
  197. exchange_type=None):
  198. """Get a celery task message publisher.
  199. :rtype :class:`celery.messaging.TaskPublisher`:
  200. Please be sure to close the AMQP connection when you're done
  201. with this object, i.e.:
  202. >>> publisher = self.get_publisher()
  203. >>> # do something with publisher
  204. >>> publisher.connection.close()
  205. """
  206. if exchange is None:
  207. exchange = self.exchange
  208. if exchange_type is None:
  209. exchange_type = self.exchange_type
  210. connection = connection or self.establish_connection(connect_timeout)
  211. return TaskPublisher(connection=connection,
  212. exchange=exchange,
  213. exchange_type=exchange_type,
  214. routing_key=self.routing_key)
  215. @classmethod
  216. def get_consumer(self, connection=None,
  217. connect_timeout=conf.BROKER_CONNECTION_TIMEOUT):
  218. """Get a celery task message consumer.
  219. :rtype :class:`celery.messaging.TaskConsumer`:
  220. Please be sure to close the AMQP connection when you're done
  221. with this object. i.e.:
  222. >>> consumer = self.get_consumer()
  223. >>> # do something with consumer
  224. >>> consumer.connection.close()
  225. """
  226. connection = connection or self.establish_connection(connect_timeout)
  227. return TaskConsumer(connection=connection, exchange=self.exchange,
  228. routing_key=self.routing_key)
  229. @classmethod
  230. def delay(self, *args, **kwargs):
  231. """Shortcut to :meth:`apply_async`, with star arguments,
  232. but doesn't support the extra options.
  233. :param \*args: positional arguments passed on to the task.
  234. :param \*\*kwargs: keyword arguments passed on to the task.
  235. :returns :class:`celery.result.AsyncResult`:
  236. """
  237. return self.apply_async(args, kwargs)
  238. @classmethod
  239. def apply_async(self, args=None, kwargs=None, **options):
  240. """Delay this task for execution by the ``celery`` daemon(s).
  241. :param args: positional arguments passed on to the task.
  242. :param kwargs: keyword arguments passed on to the task.
  243. :keyword \*\*options: Any keyword arguments to pass on to
  244. :func:`celery.execute.apply_async`.
  245. See :func:`celery.execute.apply_async` for more information.
  246. :returns :class:`celery.result.AsyncResult`:
  247. """
  248. return apply_async(self, args, kwargs, **options)
  249. @classmethod
  250. def retry(self, args=None, kwargs=None, exc=None, throw=True, **options):
  251. """Retry the task.
  252. :param args: Positional arguments to retry with.
  253. :param kwargs: Keyword arguments to retry with.
  254. :keyword exc: Optional exception to raise instead of
  255. :exc:`~celery.exceptions.MaxRetriesExceededError` when the max
  256. restart limit has been exceeded.
  257. :keyword countdown: Time in seconds to delay the retry for.
  258. :keyword eta: Explicit time and date to run the retry at (must be a
  259. :class:`datetime.datetime` instance).
  260. :keyword \*\*options: Any extra options to pass on to
  261. meth:`apply_async`. See :func:`celery.execute.apply_async`.
  262. :keyword throw: If this is ``False``, do not raise the
  263. :exc:`~celery.exceptions.RetryTaskError` exception,
  264. that tells the worker to mark the task as being retried.
  265. Note that this means the task will be marked as failed
  266. if the task raises an exception, or successful if it
  267. returns.
  268. :raises celery.exceptions.RetryTaskError: To tell the worker that the
  269. task has been re-sent for retry. This always happens, unless
  270. the ``throw`` keyword argument has been explicitly set
  271. to ``False``, and is considered normal operation.
  272. Example
  273. >>> class TwitterPostStatusTask(Task):
  274. ...
  275. ... def run(self, username, password, message, **kwargs):
  276. ... twitter = Twitter(username, password)
  277. ... try:
  278. ... twitter.post_status(message)
  279. ... except twitter.FailWhale, exc:
  280. ... # Retry in 5 minutes.
  281. ... self.retry([username, password, message], kwargs,
  282. ... countdown=60 * 5, exc=exc)
  283. """
  284. if not kwargs:
  285. raise TypeError(
  286. "kwargs argument to retries can't be empty. "
  287. "Task must accept **kwargs, see http://bit.ly/cAx3Bg")
  288. delivery_info = kwargs.pop("delivery_info", {})
  289. options.setdefault("exchange", delivery_info.get("exchange"))
  290. options.setdefault("routing_key", delivery_info.get("routing_key"))
  291. options["retries"] = kwargs.pop("task_retries", 0) + 1
  292. options["task_id"] = kwargs.pop("task_id", None)
  293. options["countdown"] = options.get("countdown",
  294. self.default_retry_delay)
  295. max_exc = exc or self.MaxRetriesExceededError(
  296. "Can't retry %s[%s] args:%s kwargs:%s" % (
  297. self.name, options["task_id"], args, kwargs))
  298. max_retries = self.max_retries
  299. if max_retries is not None and options["retries"] > max_retries:
  300. raise max_exc
  301. # If task was executed eagerly using apply(),
  302. # then the retry must also be executed eagerly.
  303. if kwargs.get("task_is_eager", False):
  304. result = self.apply(args=args, kwargs=kwargs, **options)
  305. if isinstance(result, EagerResult):
  306. return result.get() # propogates exceptions.
  307. return result
  308. self.apply_async(args=args, kwargs=kwargs, **options)
  309. if throw:
  310. message = "Retry in %d seconds." % options["countdown"]
  311. raise RetryTaskError(message, exc)
  312. @classmethod
  313. def apply(self, args=None, kwargs=None, **options):
  314. """Execute this task locally, by blocking until the task
  315. has finished executing.
  316. :param args: positional arguments passed on to the task.
  317. :param kwargs: keyword arguments passed on to the task.
  318. :keyword throw: Re-raise task exceptions. Defaults to
  319. the ``CELERY_EAGER_PROPAGATES_EXCEPTIONS`` setting.
  320. :rtype :class:`celery.result.EagerResult`:
  321. See :func:`celery.execute.apply`.
  322. """
  323. return apply(self, args, kwargs, **options)
  324. @classmethod
  325. def AsyncResult(self, task_id):
  326. """Get AsyncResult instance for this kind of task.
  327. :param task_id: Task id to get result for.
  328. """
  329. return BaseAsyncResult(task_id, backend=self.backend)
  330. def on_retry(self, exc, task_id, args, kwargs, einfo=None):
  331. """Retry handler.
  332. This is run by the worker when the task is to be retried.
  333. :param exc: The exception sent to :meth:`retry`.
  334. :param task_id: Unique id of the retried task.
  335. :param args: Original arguments for the retried task.
  336. :param kwargs: Original keyword arguments for the retried task.
  337. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo` instance,
  338. containing the traceback.
  339. The return value of this handler is ignored.
  340. """
  341. pass
  342. def after_return(self, status, retval, task_id, args, kwargs, einfo=None):
  343. """Handler called after the task returns.
  344. :param status: Current task state.
  345. :param retval: Task return value/exception.
  346. :param task_id: Unique id of the task.
  347. :param args: Original arguments for the task that failed.
  348. :param kwargs: Original keyword arguments for the task that failed.
  349. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo` instance,
  350. containing the traceback (if any).
  351. The return value of this handler is ignored.
  352. """
  353. pass
  354. def on_failure(self, exc, task_id, args, kwargs, einfo=None):
  355. """Error handler.
  356. This is run by the worker when the task fails.
  357. :param exc: The exception raised by the task.
  358. :param task_id: Unique id of the failed task.
  359. :param args: Original arguments for the task that failed.
  360. :param kwargs: Original keyword arguments for the task that failed.
  361. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo` instance,
  362. containing the traceback.
  363. The return value of this handler is ignored.
  364. """
  365. pass
  366. def on_success(self, retval, task_id, args, kwargs):
  367. """Success handler.
  368. Run by the worker if the task executes successfully.
  369. :param retval: The return value of the task.
  370. :param task_id: Unique id of the executed task.
  371. :param args: Original arguments for the executed task.
  372. :param kwargs: Original keyword arguments for the executed task.
  373. The return value of this handler is ignored.
  374. """
  375. pass
  376. def execute(self, wrapper, pool, loglevel, logfile):
  377. """The method the worker calls to execute the task.
  378. :param wrapper: A :class:`~celery.worker.job.TaskRequest`.
  379. :param pool: A task pool.
  380. :param loglevel: Current loglevel.
  381. :param logfile: Name of the currently used logfile.
  382. """
  383. wrapper.execute_using_pool(pool, loglevel, logfile)
  384. def __repr__(self):
  385. """repr(task)"""
  386. try:
  387. kind = self.__class__.mro()[1].__name__
  388. except (AttributeError, IndexError):
  389. kind = "%s(Task)" % self.__class__.__name__
  390. return "<%s: %s (%s)>" % (kind, self.name, self.type)
  391. @classmethod
  392. def subtask(cls, *args, **kwargs):
  393. """Returns a :class:`~celery.task.sets.subtask` object for
  394. this task that wraps arguments and execution options
  395. for a single task invocation."""
  396. return subtask(cls, *args, **kwargs)
  397. @property
  398. def __name__(self):
  399. return self.__class__.__name__
  400. class PeriodicTask(Task):
  401. """A periodic task is a task that behaves like a :manpage:`cron` job.
  402. Results of periodic tasks are not stored by default.
  403. .. attribute:: run_every
  404. *REQUIRED* Defines how often the task is run (its interval),
  405. it can be a :class:`~datetime.timedelta` object, a
  406. :class:`~celery.task.schedules.crontab` object or an integer
  407. specifying the time in seconds.
  408. .. attribute:: relative
  409. If set to ``True``, run times are relative to the time when the
  410. server was started. This was the previous behaviour, periodic tasks
  411. are now scheduled by the clock.
  412. :raises NotImplementedError: if the :attr:`run_every` attribute is
  413. not defined.
  414. Example
  415. >>> from celery.task import tasks, PeriodicTask
  416. >>> from datetime import timedelta
  417. >>> class EveryThirtySecondsTask(PeriodicTask):
  418. ... run_every = timedelta(seconds=30)
  419. ...
  420. ... def run(self, **kwargs):
  421. ... logger = self.get_logger(**kwargs)
  422. ... logger.info("Execute every 30 seconds")
  423. >>> from celery.task import PeriodicTask
  424. >>> from celery.task.schedules import crontab
  425. >>> class EveryMondayMorningTask(PeriodicTask):
  426. ... run_every = crontab(hour=7, minute=30, day_of_week=1)
  427. ...
  428. ... def run(self, **kwargs):
  429. ... logger = self.get_logger(**kwargs)
  430. ... logger.info("Execute every Monday at 7:30AM.")
  431. >>> class EveryMorningTask(PeriodicTask):
  432. ... run_every = crontab(hours=7, minute=30)
  433. ...
  434. ... def run(self, **kwargs):
  435. ... logger = self.get_logger(**kwargs)
  436. ... logger.info("Execute every day at 7:30AM.")
  437. >>> class EveryQuarterPastTheHourTask(PeriodicTask):
  438. ... run_every = crontab(minute=15)
  439. ...
  440. ... def run(self, **kwargs):
  441. ... logger = self.get_logger(**kwargs)
  442. ... logger.info("Execute every 0:15 past the hour every day.")
  443. """
  444. abstract = True
  445. ignore_result = True
  446. type = "periodic"
  447. relative = False
  448. def __init__(self):
  449. if not hasattr(self, "run_every"):
  450. raise NotImplementedError(
  451. "Periodic tasks must have a run_every attribute")
  452. self.run_every = maybe_schedule(self.run_every, self.relative)
  453. # Periodic task classes is pending deprecation.
  454. warnings.warn(PendingDeprecationWarning(PERIODIC_DEPRECATION_TEXT))
  455. # For backward compatibility, add the periodic task to the
  456. # configuration schedule instead.
  457. conf.CELERYBEAT_SCHEDULE[self.name] = {
  458. "task": self.name,
  459. "schedule": self.run_every,
  460. "args": (),
  461. "kwargs": {},
  462. "options": {},
  463. "relative": self.relative,
  464. }
  465. super(PeriodicTask, self).__init__()
  466. def timedelta_seconds(self, delta):
  467. """Convert :class:`~datetime.timedelta` to seconds.
  468. Doesn't account for negative timedeltas.
  469. """
  470. return timedelta_seconds(delta)
  471. def is_due(self, last_run_at):
  472. """Returns tuple of two items ``(is_due, next_time_to_run)``,
  473. where next time to run is in seconds.
  474. e.g.
  475. * ``(True, 20)``, means the task should be run now, and the next
  476. time to run is in 20 seconds.
  477. * ``(False, 12)``, means the task should be run in 12 seconds.
  478. You can override this to decide the interval at runtime,
  479. but keep in mind the value of ``CELERYBEAT_MAX_LOOP_INTERVAL``, which
  480. decides the maximum number of seconds celerybeat can sleep between
  481. re-checking the periodic task intervals. So if you dynamically change
  482. the next run at value, and the max interval is set to 5 minutes, it
  483. will take 5 minutes for the change to take effect, so you may
  484. consider lowering the value of ``CELERYBEAT_MAX_LOOP_INTERVAL`` if
  485. responsiveness if of importance to you.
  486. """
  487. return self.run_every.is_due(last_run_at)
  488. def remaining_estimate(self, last_run_at):
  489. """Returns when the periodic task should run next as a timedelta."""
  490. return self.run_every.remaining_estimate(last_run_at)