task.py 31 KB

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