task.py 29 KB

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