task.py 30 KB

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