task.py 29 KB

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