task.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.app.task
  4. ~~~~~~~~~~~~~~~
  5. Tasks Implementation.
  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 logging
  11. import sys
  12. from kombu import Exchange
  13. from kombu.utils import cached_property
  14. from celery import current_app
  15. from celery import states
  16. from celery.__compat__ import class_property
  17. from celery.state import get_current_task
  18. from celery.datastructures import ExceptionInfo
  19. from celery.exceptions import MaxRetriesExceededError, RetryTaskError
  20. from celery.local import LocalStack
  21. from celery.result import EagerResult
  22. from celery.utils import fun_takes_kwargs, uuid, maybe_reraise
  23. from celery.utils.functional import mattrgetter, maybe_list
  24. from celery.utils.imports import instantiate
  25. from celery.utils.log import get_logger
  26. from celery.utils.mail import ErrorMail
  27. from .annotations import resolve_all as resolve_all_annotations
  28. from .registry import _unpickle_task
  29. #: extracts options related to publishing a message from a dict.
  30. extract_exec_options = mattrgetter("queue", "routing_key",
  31. "exchange", "immediate",
  32. "mandatory", "priority",
  33. "serializer", "delivery_mode",
  34. "compression", "expires")
  35. class Context(object):
  36. # Default context
  37. logfile = None
  38. loglevel = None
  39. hostname = None
  40. id = None
  41. args = None
  42. kwargs = None
  43. retries = 0
  44. is_eager = False
  45. delivery_info = None
  46. taskset = None
  47. chord = None
  48. called_directly = True
  49. callbacks = None
  50. errbacks = None
  51. _children = None # see property
  52. def __init__(self, *args, **kwargs):
  53. self.update(*args, **kwargs)
  54. def update(self, *args, **kwargs):
  55. self.__dict__.update(*args, **kwargs)
  56. def clear(self):
  57. self.__dict__.clear()
  58. def get(self, key, default=None):
  59. try:
  60. return getattr(self, key)
  61. except AttributeError:
  62. return default
  63. def __repr__(self):
  64. return "<Context: %r>" % (vars(self, ))
  65. @property
  66. def children(self):
  67. # children must be an empy list for every thread
  68. if self._children is None:
  69. self._children = []
  70. return self._children
  71. class TaskType(type):
  72. """Meta class for tasks.
  73. Automatically registers the task in the task registry, except
  74. if the `abstract` attribute is set.
  75. If no `name` attribute is provided, then no name is automatically
  76. set to the name of the module it was defined in, and the class name.
  77. """
  78. def __new__(cls, name, bases, attrs):
  79. new = super(TaskType, cls).__new__
  80. task_module = attrs.get("__module__") or "__main__"
  81. # - Abstract class: abstract attribute should not be inherited.
  82. if attrs.pop("abstract", None) or not attrs.get("autoregister", True):
  83. return new(cls, name, bases, attrs)
  84. # The 'app' attribute is now a property, with the real app located
  85. # in the '_app' attribute. Previously this was a regular attribute,
  86. # so we should support classes defining it.
  87. _app1, _app2 = attrs.pop("_app", None), attrs.pop("app", None)
  88. app = attrs["_app"] = _app1 or _app2 or current_app
  89. # - Automatically generate missing/empty name.
  90. autoname = False
  91. if not attrs.get("name"):
  92. try:
  93. module_name = sys.modules[task_module].__name__
  94. except KeyError: # pragma: no cover
  95. # Fix for manage.py shell_plus (Issue #366).
  96. module_name = task_module
  97. attrs["name"] = '.'.join([module_name, name])
  98. autoname = True
  99. # - Create and register class.
  100. # Because of the way import happens (recursively)
  101. # we may or may not be the first time the task tries to register
  102. # with the framework. There should only be one class for each task
  103. # name, so we always return the registered version.
  104. tasks = app._tasks
  105. if autoname and task_module == "__main__" and app.main:
  106. attrs["name"] = '.'.join([app.main, name])
  107. task_name = attrs["name"]
  108. if task_name not in tasks:
  109. tasks.register(new(cls, name, bases, attrs))
  110. instance = tasks[task_name]
  111. instance.bind(app)
  112. return instance.__class__
  113. def __repr__(cls):
  114. if cls._app:
  115. return "<class %s of %s>" % (cls.__name__, cls._app, )
  116. return "<unbound %s>" % (cls.__name__, )
  117. class BaseTask(object):
  118. """Task base class.
  119. When called tasks apply the :meth:`run` method. This method must
  120. be defined by all tasks (that is unless the :meth:`__call__` method
  121. is overridden).
  122. """
  123. __metaclass__ = TaskType
  124. __tracer__ = None
  125. ErrorMail = ErrorMail
  126. MaxRetriesExceededError = MaxRetriesExceededError
  127. #: Execution strategy used, or the qualified name of one.
  128. Strategy = "celery.worker.strategy:default"
  129. #: The application instance associated with this task class.
  130. _app = None
  131. #: Name of the task.
  132. name = None
  133. #: If :const:`True` the task is an abstract base class.
  134. abstract = True
  135. #: If disabled the worker will not forward magic keyword arguments.
  136. #: Deprecated and scheduled for removal in v3.0.
  137. accept_magic_kwargs = False
  138. #: Destination queue. The queue needs to exist
  139. #: in :setting:`CELERY_QUEUES`. The `routing_key`, `exchange` and
  140. #: `exchange_type` attributes will be ignored if this is set.
  141. queue = None
  142. #: Overrides the apps default `routing_key` for this task.
  143. routing_key = None
  144. #: Overrides the apps default `exchange` for this task.
  145. exchange = None
  146. #: Overrides the apps default exchange type for this task.
  147. exchange_type = None
  148. #: Override the apps default delivery mode for this task. Default is
  149. #: `"persistent"`, but you can change this to `"transient"`, which means
  150. #: messages will be lost if the broker is restarted. Consult your broker
  151. #: manual for any additional delivery modes.
  152. delivery_mode = None
  153. #: Mandatory message routing.
  154. mandatory = False
  155. #: Request immediate delivery.
  156. immediate = False
  157. #: Default message priority. A number between 0 to 9, where 0 is the
  158. #: highest. Note that RabbitMQ does not support priorities.
  159. priority = None
  160. #: Maximum number of retries before giving up. If set to :const:`None`,
  161. #: it will **never** stop retrying.
  162. max_retries = 3
  163. #: Default time in seconds before a retry of the task should be
  164. #: executed. 3 minutes by default.
  165. default_retry_delay = 3 * 60
  166. #: Rate limit for this task type. Examples: :const:`None` (no rate
  167. #: limit), `"100/s"` (hundred tasks a second), `"100/m"` (hundred tasks
  168. #: a minute),`"100/h"` (hundred tasks an hour)
  169. rate_limit = None
  170. #: If enabled the worker will not store task state and return values
  171. #: for this task. Defaults to the :setting:`CELERY_IGNORE_RESULT`
  172. #: setting.
  173. ignore_result = False
  174. #: When enabled errors will be stored even if the task is otherwise
  175. #: configured to ignore results.
  176. store_errors_even_if_ignored = False
  177. #: If enabled an email will be sent to :setting:`ADMINS` whenever a task
  178. #: of this type fails.
  179. send_error_emails = False
  180. disable_error_emails = False # FIXME
  181. #: List of exception types to send error emails for.
  182. error_whitelist = ()
  183. #: The name of a serializer that are registered with
  184. #: :mod:`kombu.serialization.registry`. Default is `"pickle"`.
  185. serializer = None
  186. #: Hard time limit.
  187. #: Defaults to the :setting:`CELERY_TASK_TIME_LIMIT` setting.
  188. time_limit = None
  189. #: Soft time limit.
  190. #: Defaults to the :setting:`CELERY_TASK_SOFT_TIME_LIMIT` setting.
  191. soft_time_limit = None
  192. #: The result store backend used for this task.
  193. backend = None
  194. #: If disabled this task won't be registered automatically.
  195. autoregister = True
  196. #: If enabled the task will report its status as "started" when the task
  197. #: is executed by a worker. Disabled by default as the normal behaviour
  198. #: is to not report that level of granularity. Tasks are either pending,
  199. #: finished, or waiting to be retried.
  200. #:
  201. #: Having a "started" status can be useful for when there are long
  202. #: running tasks and there is a need to report which task is currently
  203. #: running.
  204. #:
  205. #: The application default can be overridden using the
  206. #: :setting:`CELERY_TRACK_STARTED` setting.
  207. track_started = False
  208. #: When enabled messages for this task will be acknowledged **after**
  209. #: the task has been executed, and not *just before* which is the
  210. #: default behavior.
  211. #:
  212. #: Please note that this means the task may be executed twice if the
  213. #: worker crashes mid execution (which may be acceptable for some
  214. #: applications).
  215. #:
  216. #: The application default can be overridden with the
  217. #: :setting:`CELERY_ACKS_LATE` setting.
  218. acks_late = None
  219. #: Default task expiry time.
  220. expires = None
  221. #: The type of task *(no longer used)*.
  222. type = "regular"
  223. __bound__ = False
  224. from_config = (
  225. ("exchange_type", "CELERY_DEFAULT_EXCHANGE_TYPE"),
  226. ("delivery_mode", "CELERY_DEFAULT_DELIVERY_MODE"),
  227. ("send_error_emails", "CELERY_SEND_TASK_ERROR_EMAILS"),
  228. ("error_whitelist", "CELERY_TASK_ERROR_WHITELIST"),
  229. ("serializer", "CELERY_TASK_SERIALIZER"),
  230. ("rate_limit", "CELERY_DEFAULT_RATE_LIMIT"),
  231. ("track_started", "CELERY_TRACK_STARTED"),
  232. ("acks_late", "CELERY_ACKS_LATE"),
  233. ("ignore_result", "CELERY_IGNORE_RESULT"),
  234. ("store_errors_even_if_ignored",
  235. "CELERY_STORE_ERRORS_EVEN_IF_IGNORED"),
  236. )
  237. __bound__ = False
  238. # - Tasks are lazily bound, so that configuration is not set
  239. # - until the task is actually used
  240. @classmethod
  241. def bind(self, app):
  242. was_bound, self.__bound__ = self.__bound__, True
  243. self._app = app
  244. conf = app.conf
  245. for attr_name, config_name in self.from_config:
  246. if getattr(self, attr_name, None) is None:
  247. setattr(self, attr_name, conf[config_name])
  248. self.accept_magic_kwargs = app.accept_magic_kwargs
  249. if self.accept_magic_kwargs is None:
  250. self.accept_magic_kwargs = app.accept_magic_kwargs
  251. if self.backend is None:
  252. self.backend = app.backend
  253. # decorate with annotations from config.
  254. if not was_bound:
  255. self.annotate()
  256. self.request_stack = LocalStack()
  257. self.request_stack.push(Context())
  258. # PeriodicTask uses this to add itself to the PeriodicTask schedule.
  259. self.on_bound(app)
  260. return app
  261. @classmethod
  262. def on_bound(self, app):
  263. """This method can be defined to do additional actions when the
  264. task class is bound to an app."""
  265. pass
  266. @classmethod
  267. def _get_app(self):
  268. if not self.__bound__ or self._app is None:
  269. # The app property's __set__ method is not called
  270. # if Task.app is set (on the class), so must bind on use.
  271. self.bind(current_app)
  272. return self._app
  273. app = class_property(_get_app, bind)
  274. @classmethod
  275. def annotate(self):
  276. for d in resolve_all_annotations(self.app.annotations, self):
  277. for key, value in d.iteritems():
  278. if key.startswith('@'):
  279. self.add_around(key[1:], value)
  280. else:
  281. setattr(self, key, value)
  282. @classmethod
  283. def add_around(self, attr, around):
  284. orig = getattr(self, attr)
  285. if getattr(orig, "__wrapped__", None):
  286. orig = orig.__wrapped__
  287. meth = around(orig)
  288. meth.__wrapped__ = orig
  289. setattr(self, attr, meth)
  290. def __call__(self, *args, **kwargs):
  291. return self.run(*args, **kwargs)
  292. # - tasks are pickled into the name of the task only, and the reciever
  293. # - simply grabs it from the local registry.
  294. def __reduce__(self):
  295. return (_unpickle_task, (self.name, ), None)
  296. def run(self, *args, **kwargs):
  297. """The body of the task executed by workers."""
  298. raise NotImplementedError("Tasks must define the run method.")
  299. def start_strategy(self, app, consumer):
  300. return instantiate(self.Strategy, self, app, consumer)
  301. def get_logger(self, **kwargs):
  302. """Get task-aware logger object."""
  303. logger = get_logger(self.name)
  304. if logger.parent is logging.root:
  305. logger.parent = get_logger("celery.task")
  306. return logger
  307. def establish_connection(self, connect_timeout=None):
  308. """Establish a connection to the message broker."""
  309. return self._get_app().broker_connection(
  310. connect_timeout=connect_timeout)
  311. def get_publisher(self, connection=None, exchange=None,
  312. connect_timeout=None, exchange_type=None, **options):
  313. """Get a celery task message publisher.
  314. :rtype :class:`~celery.app.amqp.TaskProducer`:
  315. .. warning::
  316. If you don't specify a connection, one will automatically
  317. be established for you, in that case you need to close this
  318. connection after use::
  319. >>> publisher = self.get_publisher()
  320. >>> # ... do something with publisher
  321. >>> publisher.connection.close()
  322. """
  323. exchange = self.exchange if exchange is None else exchange
  324. if exchange_type is None:
  325. exchange_type = self.exchange_type
  326. connection = connection or self.establish_connection(connect_timeout)
  327. return self._get_app().amqp.TaskProducer(connection,
  328. exchange=exchange and Exchange(exchange, exchange_type),
  329. routing_key=self.routing_key, **options)
  330. def get_consumer(self, connection=None, queues=None, **kwargs):
  331. """Get message consumer.
  332. :rtype :class:`kombu.messaging.Consumer`:
  333. .. warning::
  334. If you don't specify a connection, one will automatically
  335. be established for you, in that case you need to close this
  336. connection after use::
  337. >>> consumer = self.get_consumer()
  338. >>> # do something with consumer
  339. >>> consumer.close()
  340. >>> consumer.connection.close()
  341. """
  342. app = self._get_app()
  343. connection = connection or self.establish_connection()
  344. return app.amqp.TaskConsumer(connection,
  345. queues or app.amqp.queue_or_default(self.queue), **kwargs)
  346. def delay(self, *args, **kwargs):
  347. """Star argument version of :meth:`apply_async`.
  348. Does not support the extra options enabled by :meth:`apply_async`.
  349. :param \*args: positional arguments passed on to the task.
  350. :param \*\*kwargs: keyword arguments passed on to the task.
  351. :returns :class:`celery.result.AsyncResult`:
  352. """
  353. return self.apply_async(args, kwargs)
  354. def apply_async(self, args=None, kwargs=None,
  355. task_id=None, publisher=None, connection=None,
  356. router=None, link=None, link_error=None, **options):
  357. """Apply tasks asynchronously by sending a message.
  358. :keyword args: The positional arguments to pass on to the
  359. task (a :class:`list` or :class:`tuple`).
  360. :keyword kwargs: The keyword arguments to pass on to the
  361. task (a :class:`dict`)
  362. :keyword countdown: Number of seconds into the future that the
  363. task should execute. Defaults to immediate
  364. execution (do not confuse with the
  365. `immediate` flag, as they are unrelated).
  366. :keyword eta: A :class:`~datetime.datetime` object describing
  367. the absolute time and date of when the task should
  368. be executed. May not be specified if `countdown`
  369. is also supplied. (Do not confuse this with the
  370. `immediate` flag, as they are unrelated).
  371. :keyword expires: Either a :class:`int`, describing the number of
  372. seconds, or a :class:`~datetime.datetime` object
  373. that describes the absolute time and date of when
  374. the task should expire. The task will not be
  375. executed after the expiration time.
  376. :keyword connection: Re-use existing broker connection instead
  377. of establishing a new one.
  378. :keyword retry: If enabled sending of the task message will be retried
  379. in the event of connection loss or failure. Default
  380. is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
  381. setting. Note you need to handle the
  382. publisher/connection manually for this to work.
  383. :keyword retry_policy: Override the retry policy used. See the
  384. :setting:`CELERY_TASK_PUBLISH_RETRY` setting.
  385. :keyword routing_key: The routing key used to route the task to a
  386. worker server. Defaults to the
  387. :attr:`routing_key` attribute.
  388. :keyword exchange: The named exchange to send the task to.
  389. Defaults to the :attr:`exchange` attribute.
  390. :keyword exchange_type: The exchange type to initialize the exchange
  391. if not already declared. Defaults to the
  392. :attr:`exchange_type` attribute.
  393. :keyword immediate: Request immediate delivery. Will raise an
  394. exception if the task cannot be routed to a worker
  395. immediately. (Do not confuse this parameter with
  396. the `countdown` and `eta` settings, as they are
  397. unrelated). Defaults to the :attr:`immediate`
  398. attribute.
  399. :keyword mandatory: Mandatory routing. Raises an exception if
  400. there's no running workers able to take on this
  401. task. Defaults to the :attr:`mandatory`
  402. attribute.
  403. :keyword priority: The task priority, a number between 0 and 9.
  404. Defaults to the :attr:`priority` attribute.
  405. :keyword serializer: A string identifying the default
  406. serialization method to use. Can be `pickle`,
  407. `json`, `yaml`, `msgpack` or any custom
  408. serialization method that has been registered
  409. with :mod:`kombu.serialization.registry`.
  410. Defaults to the :attr:`serializer` attribute.
  411. :keyword compression: A string identifying the compression method
  412. to use. Can be one of ``zlib``, ``bzip2``,
  413. or any custom compression methods registered with
  414. :func:`kombu.compression.register`. Defaults to
  415. the :setting:`CELERY_MESSAGE_COMPRESSION`
  416. setting.
  417. :keyword link: A single, or a list of subtasks to apply if the
  418. task exits successfully.
  419. :keyword link_error: A single, or a list of subtasks to apply
  420. if an error occurs while executing the task.
  421. .. note::
  422. If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
  423. be replaced by a local :func:`apply` call instead.
  424. """
  425. app = self._get_app()
  426. router = router or self.app.amqp.router
  427. conf = app.conf
  428. if conf.CELERY_ALWAYS_EAGER:
  429. return self.apply(args, kwargs, task_id=task_id, **options)
  430. options = dict(extract_exec_options(self), **options)
  431. options = router.route(options, self.name, args, kwargs)
  432. if connection:
  433. publisher = app.amqp.TaskProducer(connection)
  434. publish = publisher or app.amqp.publisher_pool.acquire(block=True)
  435. evd = None
  436. if conf.CELERY_SEND_TASK_SENT_EVENT:
  437. evd = app.events.Dispatcher(channel=publish.channel,
  438. buffer_while_offline=False)
  439. try:
  440. task_id = publish.delay_task(self.name, args, kwargs,
  441. task_id=task_id,
  442. event_dispatcher=evd,
  443. callbacks=maybe_list(link),
  444. errbacks=maybe_list(link_error),
  445. **options)
  446. finally:
  447. if not publisher:
  448. publish.release()
  449. result = self.AsyncResult(task_id)
  450. parent = get_current_task()
  451. if parent:
  452. parent.request.children.append(result)
  453. return result
  454. def retry(self, args=None, kwargs=None, exc=None, throw=True,
  455. eta=None, countdown=None, max_retries=None, **options):
  456. """Retry the task.
  457. :param args: Positional arguments to retry with.
  458. :param kwargs: Keyword arguments to retry with.
  459. :keyword exc: Optional exception to raise instead of
  460. :exc:`~celery.exceptions.MaxRetriesExceededError`
  461. when the max restart limit has been exceeded.
  462. :keyword countdown: Time in seconds to delay the retry for.
  463. :keyword eta: Explicit time and date to run the retry at
  464. (must be a :class:`~datetime.datetime` instance).
  465. :keyword max_retries: If set, overrides the default retry limit.
  466. :keyword \*\*options: Any extra options to pass on to
  467. meth:`apply_async`.
  468. :keyword throw: If this is :const:`False`, do not raise the
  469. :exc:`~celery.exceptions.RetryTaskError` exception,
  470. that tells the worker to mark the task as being
  471. retried. Note that this means the task will be
  472. marked as failed if the task raises an exception,
  473. or successful if it returns.
  474. :raises celery.exceptions.RetryTaskError: To tell the worker that
  475. the task has been re-sent for retry. This always happens,
  476. unless the `throw` keyword argument has been explicitly set
  477. to :const:`False`, and is considered normal operation.
  478. **Example**
  479. .. code-block:: python
  480. >>> @task
  481. >>> def tweet(auth, message):
  482. ... twitter = Twitter(oauth=auth)
  483. ... try:
  484. ... twitter.post_status_update(message)
  485. ... except twitter.FailWhale, exc:
  486. ... # Retry in 5 minutes.
  487. ... raise tweet.retry(countdown=60 * 5, exc=exc)
  488. Although the task will never return above as `retry` raises an
  489. exception to notify the worker, we use `return` in front of the retry
  490. to convey that the rest of the block will not be executed.
  491. """
  492. request = self.request
  493. max_retries = self.max_retries if max_retries is None else max_retries
  494. args = request.args if args is None else args
  495. kwargs = request.kwargs if kwargs is None else kwargs
  496. delivery_info = request.delivery_info
  497. # Not in worker or emulated by (apply/always_eager),
  498. # so just raise the original exception.
  499. if request.called_directly:
  500. maybe_reraise()
  501. raise exc or RetryTaskError("Task can be retried", None)
  502. if delivery_info:
  503. options.setdefault("exchange", delivery_info.get("exchange"))
  504. options.setdefault("routing_key", delivery_info.get("routing_key"))
  505. if not eta and countdown is None:
  506. countdown = self.default_retry_delay
  507. options.update({"retries": request.retries + 1,
  508. "task_id": request.id,
  509. "countdown": countdown,
  510. "eta": eta})
  511. if max_retries is not None and options["retries"] > max_retries:
  512. if exc:
  513. maybe_reraise()
  514. raise self.MaxRetriesExceededError(
  515. "Can't retry %s[%s] args:%s kwargs:%s" % (
  516. self.name, options["task_id"], args, kwargs))
  517. # If task was executed eagerly using apply(),
  518. # then the retry must also be executed eagerly.
  519. if request.is_eager:
  520. self.apply(args=args, kwargs=kwargs, **options).get()
  521. else:
  522. self.apply_async(args=args, kwargs=kwargs, **options)
  523. ret = RetryTaskError(eta and "Retry at %s" % eta
  524. or "Retry in %s secs." % countdown, exc)
  525. if throw:
  526. raise ret
  527. return ret
  528. def apply(self, args=None, kwargs=None, **options):
  529. """Execute this task locally, by blocking until the task returns.
  530. :param args: positional arguments passed on to the task.
  531. :param kwargs: keyword arguments passed on to the task.
  532. :keyword throw: Re-raise task exceptions. Defaults to
  533. the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
  534. setting.
  535. :rtype :class:`celery.result.EagerResult`:
  536. """
  537. # trace imports BaseTask, so need to import inline.
  538. from celery.task.trace import eager_trace_task
  539. app = self._get_app()
  540. args = args or []
  541. kwargs = kwargs or {}
  542. task_id = options.get("task_id") or uuid()
  543. retries = options.get("retries", 0)
  544. throw = app.either("CELERY_EAGER_PROPAGATES_EXCEPTIONS",
  545. options.pop("throw", None))
  546. # Make sure we get the task instance, not class.
  547. task = app._tasks[self.name]
  548. request = {"id": task_id,
  549. "retries": retries,
  550. "is_eager": True,
  551. "logfile": options.get("logfile"),
  552. "loglevel": options.get("loglevel", 0),
  553. "delivery_info": {"is_eager": True}}
  554. if self.accept_magic_kwargs:
  555. default_kwargs = {"task_name": task.name,
  556. "task_id": task_id,
  557. "task_retries": retries,
  558. "task_is_eager": True,
  559. "logfile": options.get("logfile"),
  560. "loglevel": options.get("loglevel", 0),
  561. "delivery_info": {"is_eager": True}}
  562. supported_keys = fun_takes_kwargs(task.run, default_kwargs)
  563. extend_with = dict((key, val)
  564. for key, val in default_kwargs.items()
  565. if key in supported_keys)
  566. kwargs.update(extend_with)
  567. tb = None
  568. retval, info = eager_trace_task(task, task_id, args, kwargs,
  569. request=request, propagate=throw)
  570. if isinstance(retval, ExceptionInfo):
  571. retval, tb = retval.exception, retval.traceback
  572. state = states.SUCCESS if info is None else info.state
  573. return EagerResult(task_id, retval, state, traceback=tb)
  574. def AsyncResult(self, task_id):
  575. """Get AsyncResult instance for this kind of task.
  576. :param task_id: Task id to get result for.
  577. """
  578. return self._get_app().AsyncResult(task_id, backend=self.backend,
  579. task_name=self.name)
  580. def subtask(self, *args, **kwargs):
  581. """Returns :class:`~celery.subtask` object for
  582. this task, wrapping arguments and execution options
  583. for a single task invocation."""
  584. from celery.canvas import subtask
  585. return subtask(self, *args, **kwargs)
  586. def s(self, *args, **kwargs):
  587. """``.s(*a, **k) -> .subtask(a, k)``"""
  588. return self.subtask(args, kwargs)
  589. def si(self, *args, **kwargs):
  590. """``.si(*a, **k) -> .subtask(a, k, immutable=True)``"""
  591. return self.subtask(args, kwargs, immutable=True)
  592. def chunks(self, it, n):
  593. """Creates a :class:`~celery.canvas.chunks` task for this task."""
  594. from celery import chunks
  595. return chunks(self.s(), it, n)
  596. def map(self, it):
  597. """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
  598. from celery import xmap
  599. return xmap(self.s(), it)
  600. def starmap(self, it):
  601. """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
  602. from celery import xstarmap
  603. return xstarmap(self.s(), it)
  604. def update_state(self, task_id=None, state=None, meta=None):
  605. """Update task state.
  606. :keyword task_id: Id of the task to update, defaults to the
  607. id of the current task
  608. :keyword state: New state (:class:`str`).
  609. :keyword meta: State metadata (:class:`dict`).
  610. """
  611. if task_id is None:
  612. task_id = self.request.id
  613. self.backend.store_result(task_id, meta, state)
  614. def on_retry(self, exc, task_id, args, kwargs, einfo):
  615. """Retry handler.
  616. This is run by the worker when the task is to be retried.
  617. :param exc: The exception sent to :meth:`retry`.
  618. :param task_id: Unique id of the retried task.
  619. :param args: Original arguments for the retried task.
  620. :param kwargs: Original keyword arguments for the retried task.
  621. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  622. instance, containing the traceback.
  623. The return value of this handler is ignored.
  624. """
  625. pass
  626. def after_return(self, status, retval, task_id, args, kwargs, einfo):
  627. """Handler called after the task returns.
  628. :param status: Current task state.
  629. :param retval: Task return value/exception.
  630. :param task_id: Unique id of the task.
  631. :param args: Original arguments for the task that failed.
  632. :param kwargs: Original keyword arguments for the task
  633. that failed.
  634. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  635. instance, containing the traceback (if any).
  636. The return value of this handler is ignored.
  637. """
  638. pass
  639. def on_failure(self, exc, task_id, args, kwargs, einfo):
  640. """Error handler.
  641. This is run by the worker when the task fails.
  642. :param exc: The exception raised by the task.
  643. :param task_id: Unique id of the failed task.
  644. :param args: Original arguments for the task that failed.
  645. :param kwargs: Original keyword arguments for the task
  646. that failed.
  647. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  648. instance, containing the traceback.
  649. The return value of this handler is ignored.
  650. """
  651. pass
  652. def send_error_email(self, context, exc, **kwargs):
  653. if self.send_error_emails and not self.disable_error_emails:
  654. self.ErrorMail(self, **kwargs).send(context, exc)
  655. def on_success(self, retval, task_id, args, kwargs):
  656. """Success handler.
  657. Run by the worker if the task executes successfully.
  658. :param retval: The return value of the task.
  659. :param task_id: Unique id of the executed task.
  660. :param args: Original arguments for the executed task.
  661. :param kwargs: Original keyword arguments for the executed task.
  662. The return value of this handler is ignored.
  663. """
  664. pass
  665. def execute(self, request, pool, loglevel, logfile, **kwargs):
  666. """The method the worker calls to execute the task.
  667. :param request: A :class:`~celery.worker.job.Request`.
  668. :param pool: A task pool.
  669. :param loglevel: Current loglevel.
  670. :param logfile: Name of the currently used logfile.
  671. :keyword consumer: The :class:`~celery.worker.consumer.Consumer`.
  672. """
  673. request.execute_using_pool(pool, loglevel, logfile)
  674. def push_request(self, *args, **kwargs):
  675. self.request_stack.push(Context(*args, **kwargs))
  676. def pop_request(self):
  677. self.request_stack.pop()
  678. def __repr__(self):
  679. """`repr(task)`"""
  680. return "<@task: %s>" % (self.name, )
  681. @cached_property
  682. def logger(self):
  683. return self.get_logger()
  684. @property
  685. def request(self):
  686. return self.request_stack.top
  687. @property
  688. def __name__(self):
  689. return self.__class__.__name__