task.py 29 KB

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