task.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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.__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_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. 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: {0!r}>'.format(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. return ('<class {0.__name__} of {0._app}>' if cls._app
  101. else '<unbound {0.__name__}>').format(cls)
  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. def __reduce__(self):
  256. # - tasks are pickled into the name of the task only, and the reciever
  257. # - simply grabs it from the local registry.
  258. # - in later versions the module of the task is also included,
  259. # - and the receiving side tries to import that module so that
  260. # - it will work even if the task has not been registered.
  261. mod = type(self).__module__
  262. mod = mod if mod and mod in sys.modules else None
  263. return (_unpickle_task_v2, (self.name, mod), None)
  264. def run(self, *args, **kwargs):
  265. """The body of the task executed by workers."""
  266. raise NotImplementedError('Tasks must define the run method.')
  267. def start_strategy(self, app, consumer):
  268. return instantiate(self.Strategy, self, app, consumer)
  269. def delay(self, *args, **kwargs):
  270. """Star argument version of :meth:`apply_async`.
  271. Does not support the extra options enabled by :meth:`apply_async`.
  272. :param \*args: positional arguments passed on to the task.
  273. :param \*\*kwargs: keyword arguments passed on to the task.
  274. :returns :class:`celery.result.AsyncResult`:
  275. """
  276. return self.apply_async(args, kwargs)
  277. def apply_async(self, args=None, kwargs=None,
  278. task_id=None, producer=None, connection=None, router=None,
  279. link=None, link_error=None, publisher=None, add_to_parent=True,
  280. **options):
  281. """Apply tasks asynchronously by sending a message.
  282. :keyword args: The positional arguments to pass on to the
  283. task (a :class:`list` or :class:`tuple`).
  284. :keyword kwargs: The keyword arguments to pass on to the
  285. task (a :class:`dict`)
  286. :keyword countdown: Number of seconds into the future that the
  287. task should execute. Defaults to immediate
  288. execution (do not confuse with the
  289. `immediate` flag, as they are unrelated).
  290. :keyword eta: A :class:`~datetime.datetime` object describing
  291. the absolute time and date of when the task should
  292. be executed. May not be specified if `countdown`
  293. is also supplied. (Do not confuse this with the
  294. `immediate` flag, as they are unrelated).
  295. :keyword expires: Either a :class:`int`, describing the number of
  296. seconds, or a :class:`~datetime.datetime` object
  297. that describes the absolute time and date of when
  298. the task should expire. The task will not be
  299. executed after the expiration time.
  300. :keyword connection: Re-use existing broker connection instead
  301. of establishing a new one.
  302. :keyword retry: If enabled sending of the task message will be retried
  303. in the event of connection loss or failure. Default
  304. is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
  305. setting. Note you need to handle the
  306. producer/connection manually for this to work.
  307. :keyword retry_policy: Override the retry policy used. See the
  308. :setting:`CELERY_TASK_PUBLISH_RETRY` setting.
  309. :keyword routing_key: The routing key used to route the task to a
  310. worker server. Defaults to the
  311. :attr:`routing_key` attribute.
  312. :keyword exchange: The named exchange to send the task to.
  313. Defaults to the :attr:`exchange` attribute.
  314. :keyword exchange_type: The exchange type to initialize the exchange
  315. if not already declared. Defaults to the
  316. :attr:`exchange_type` attribute.
  317. :keyword immediate: Request immediate delivery. Will raise an
  318. exception if the task cannot be routed to a worker
  319. immediately. (Do not confuse this parameter with
  320. the `countdown` and `eta` settings, as they are
  321. unrelated). Defaults to the :attr:`immediate`
  322. attribute.
  323. :keyword mandatory: Mandatory routing. Raises an exception if
  324. there's no running workers able to take on this
  325. task. Defaults to the :attr:`mandatory`
  326. attribute.
  327. :keyword priority: The task priority, a number between 0 and 9.
  328. Defaults to the :attr:`priority` attribute.
  329. :keyword serializer: A string identifying the default
  330. serialization method to use. Can be `pickle`,
  331. `json`, `yaml`, `msgpack` or any custom
  332. serialization method that has been registered
  333. with :mod:`kombu.serialization.registry`.
  334. Defaults to the :attr:`serializer` attribute.
  335. :keyword compression: A string identifying the compression method
  336. to use. Can be one of ``zlib``, ``bzip2``,
  337. or any custom compression methods registered with
  338. :func:`kombu.compression.register`. Defaults to
  339. the :setting:`CELERY_MESSAGE_COMPRESSION`
  340. setting.
  341. :keyword link: A single, or a list of subtasks to apply if the
  342. task exits successfully.
  343. :keyword link_error: A single, or a list of subtasks to apply
  344. if an error occurs while executing the task.
  345. :keyword producer: :class:~@amqp.TaskProducer` instance to use.
  346. :keyword add_to_parent: If set to True (default) and the task
  347. is applied while executing another task, then the result
  348. will be appended to the parent tasks ``request.children``
  349. attribute.
  350. :keyword publisher: Deprecated alias to ``producer``.
  351. .. note::
  352. If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
  353. be replaced by a local :func:`apply` call instead.
  354. """
  355. producer = producer or publisher
  356. app = self._get_app()
  357. router = router or self.app.amqp.router
  358. conf = app.conf
  359. # add 'self' if this is a bound method.
  360. if self.__self__ is not None:
  361. args = (self.__self__, ) + tuple(args)
  362. if conf.CELERY_ALWAYS_EAGER:
  363. return self.apply(args, kwargs, task_id=task_id, **options)
  364. options = dict(extract_exec_options(self), **options)
  365. options = router.route(options, self.name, args, kwargs)
  366. if connection:
  367. producer = app.amqp.TaskProducer(connection)
  368. with app.producer_or_acquire(producer) as P:
  369. evd = None
  370. if conf.CELERY_SEND_TASK_SENT_EVENT:
  371. evd = app.events.Dispatcher(channel=P.channel,
  372. buffer_while_offline=False)
  373. task_id = P.publish_task(self.name, args, kwargs,
  374. task_id=task_id,
  375. event_dispatcher=evd,
  376. callbacks=maybe_list(link),
  377. errbacks=maybe_list(link_error),
  378. **options)
  379. result = self.AsyncResult(task_id)
  380. if add_to_parent:
  381. parent = get_current_worker_task()
  382. if parent:
  383. parent.request.children.append(result)
  384. return result
  385. def retry(self, args=None, kwargs=None, exc=None, throw=True,
  386. eta=None, countdown=None, max_retries=None, **options):
  387. """Retry the task.
  388. :param args: Positional arguments to retry with.
  389. :param kwargs: Keyword arguments to retry with.
  390. :keyword exc: Optional exception to raise instead of
  391. :exc:`~celery.exceptions.MaxRetriesExceededError`
  392. when the max restart limit has been exceeded.
  393. :keyword countdown: Time in seconds to delay the retry for.
  394. :keyword eta: Explicit time and date to run the retry at
  395. (must be a :class:`~datetime.datetime` instance).
  396. :keyword max_retries: If set, overrides the default retry limit.
  397. :keyword timeout: If set, overrides the default timeout.
  398. :keyword soft_timeout: If set, overrides the default soft timeout.
  399. :keyword \*\*options: Any extra options to pass on to
  400. meth:`apply_async`.
  401. :keyword throw: If this is :const:`False`, do not raise the
  402. :exc:`~celery.exceptions.RetryTaskError` exception,
  403. that tells the worker to mark the task as being
  404. retried. Note that this means the task will be
  405. marked as failed if the task raises an exception,
  406. or successful if it returns.
  407. :raises celery.exceptions.RetryTaskError: To tell the worker that
  408. the task has been re-sent for retry. This always happens,
  409. unless the `throw` keyword argument has been explicitly set
  410. to :const:`False`, and is considered normal operation.
  411. **Example**
  412. .. code-block:: python
  413. >>> @task()
  414. >>> def tweet(auth, message):
  415. ... twitter = Twitter(oauth=auth)
  416. ... try:
  417. ... twitter.post_status_update(message)
  418. ... except twitter.FailWhale as exc:
  419. ... # Retry in 5 minutes.
  420. ... raise tweet.retry(countdown=60 * 5, exc=exc)
  421. Although the task will never return above as `retry` raises an
  422. exception to notify the worker, we use `return` in front of the retry
  423. to convey that the rest of the block will not be executed.
  424. """
  425. request = self.request
  426. max_retries = self.max_retries if max_retries is None else max_retries
  427. args = request.args if args is None else args
  428. kwargs = request.kwargs if kwargs is None else kwargs
  429. delivery_info = request.delivery_info
  430. # Not in worker or emulated by (apply/always_eager),
  431. # so just raise the original exception.
  432. if request.called_directly:
  433. maybe_reraise()
  434. raise exc or RetryTaskError('Task can be retried', None)
  435. if delivery_info:
  436. options.setdefault('exchange', delivery_info.get('exchange'))
  437. options.setdefault('routing_key', delivery_info.get('routing_key'))
  438. if not eta and countdown is None:
  439. countdown = self.default_retry_delay
  440. options.update({'retries': request.retries + 1,
  441. 'task_id': request.id,
  442. 'countdown': countdown,
  443. 'eta': eta,
  444. 'link': request.callbacks,
  445. 'link_error': request.errbacks})
  446. if max_retries is not None and options['retries'] > max_retries:
  447. if exc:
  448. maybe_reraise()
  449. raise self.MaxRetriesExceededError(
  450. "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
  451. self.name, options['task_id'], args, kwargs))
  452. # If task was executed eagerly using apply(),
  453. # then the retry must also be executed eagerly.
  454. if request.is_eager:
  455. self.apply(args=args, kwargs=kwargs, **options).get()
  456. else:
  457. self.apply_async(args=args, kwargs=kwargs, **options)
  458. ret = RetryTaskError(exc=exc, when=eta or countdown)
  459. if throw:
  460. raise ret
  461. return ret
  462. def apply(self, args=None, kwargs=None, **options):
  463. """Execute this task locally, by blocking until the task returns.
  464. :param args: positional arguments passed on to the task.
  465. :param kwargs: keyword arguments passed on to the task.
  466. :keyword throw: Re-raise task exceptions. Defaults to
  467. the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
  468. setting.
  469. :rtype :class:`celery.result.EagerResult`:
  470. """
  471. # trace imports Task, so need to import inline.
  472. from celery.task.trace import eager_trace_task
  473. app = self._get_app()
  474. args = args or []
  475. kwargs = kwargs or {}
  476. task_id = options.get('task_id') or uuid()
  477. retries = options.get('retries', 0)
  478. throw = app.either('CELERY_EAGER_PROPAGATES_EXCEPTIONS',
  479. options.pop('throw', None))
  480. # Make sure we get the task instance, not class.
  481. task = app._tasks[self.name]
  482. request = {'id': task_id,
  483. 'retries': retries,
  484. 'is_eager': True,
  485. 'logfile': options.get('logfile'),
  486. 'loglevel': options.get('loglevel', 0),
  487. 'delivery_info': {'is_eager': True}}
  488. if self.accept_magic_kwargs:
  489. default_kwargs = {'task_name': task.name,
  490. 'task_id': task_id,
  491. 'task_retries': retries,
  492. 'task_is_eager': True,
  493. 'logfile': options.get('logfile'),
  494. 'loglevel': options.get('loglevel', 0),
  495. 'delivery_info': {'is_eager': True}}
  496. supported_keys = fun_takes_kwargs(task.run, default_kwargs)
  497. extend_with = dict((key, val)
  498. for key, val in default_kwargs.items()
  499. if key in supported_keys)
  500. kwargs.update(extend_with)
  501. tb = None
  502. retval, info = eager_trace_task(task, task_id, args, kwargs,
  503. request=request, propagate=throw)
  504. if isinstance(retval, ExceptionInfo):
  505. retval, tb = retval.exception, retval.traceback
  506. state = states.SUCCESS if info is None else info.state
  507. return EagerResult(task_id, retval, state, traceback=tb)
  508. def AsyncResult(self, task_id):
  509. """Get AsyncResult instance for this kind of task.
  510. :param task_id: Task id to get result for.
  511. """
  512. return self._get_app().AsyncResult(task_id, backend=self.backend,
  513. task_name=self.name)
  514. def subtask(self, *args, **kwargs):
  515. """Returns :class:`~celery.subtask` object for
  516. this task, wrapping arguments and execution options
  517. for a single task invocation."""
  518. from celery.canvas import subtask
  519. return subtask(self, *args, **kwargs)
  520. def s(self, *args, **kwargs):
  521. """``.s(*a, **k) -> .subtask(a, k)``"""
  522. return self.subtask(args, kwargs)
  523. def si(self, *args, **kwargs):
  524. """``.si(*a, **k) -> .subtask(a, k, immutable=True)``"""
  525. return self.subtask(args, kwargs, immutable=True)
  526. def chunks(self, it, n):
  527. """Creates a :class:`~celery.canvas.chunks` task for this task."""
  528. from celery import chunks
  529. return chunks(self.s(), it, n)
  530. def map(self, it):
  531. """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
  532. from celery import xmap
  533. return xmap(self.s(), it)
  534. def starmap(self, it):
  535. """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
  536. from celery import xstarmap
  537. return xstarmap(self.s(), it)
  538. def update_state(self, task_id=None, state=None, meta=None):
  539. """Update task state.
  540. :keyword task_id: Id of the task to update, defaults to the
  541. id of the current task
  542. :keyword state: New state (:class:`str`).
  543. :keyword meta: State metadata (:class:`dict`).
  544. """
  545. if task_id is None:
  546. task_id = self.request.id
  547. self.backend.store_result(task_id, meta, state)
  548. def on_success(self, retval, task_id, args, kwargs):
  549. """Success handler.
  550. Run by the worker if the task executes successfully.
  551. :param retval: The return value of the task.
  552. :param task_id: Unique id of the executed task.
  553. :param args: Original arguments for the executed task.
  554. :param kwargs: Original keyword arguments for the executed task.
  555. The return value of this handler is ignored.
  556. """
  557. pass
  558. def on_retry(self, exc, task_id, args, kwargs, einfo):
  559. """Retry handler.
  560. This is run by the worker when the task is to be retried.
  561. :param exc: The exception sent to :meth:`retry`.
  562. :param task_id: Unique id of the retried task.
  563. :param args: Original arguments for the retried task.
  564. :param kwargs: Original keyword arguments for the retried task.
  565. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  566. instance, containing the traceback.
  567. The return value of this handler is ignored.
  568. """
  569. pass
  570. def on_failure(self, exc, task_id, args, kwargs, einfo):
  571. """Error handler.
  572. This is run by the worker when the task fails.
  573. :param exc: The exception raised by the task.
  574. :param task_id: Unique id of the failed task.
  575. :param args: Original arguments for the task that failed.
  576. :param kwargs: Original keyword arguments for the task
  577. that failed.
  578. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  579. instance, containing the traceback.
  580. The return value of this handler is ignored.
  581. """
  582. pass
  583. def after_return(self, status, retval, task_id, args, kwargs, einfo):
  584. """Handler called after the task returns.
  585. :param status: Current task state.
  586. :param retval: Task return value/exception.
  587. :param task_id: Unique id of the task.
  588. :param args: Original arguments for the task that failed.
  589. :param kwargs: Original keyword arguments for the task
  590. that failed.
  591. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  592. instance, containing the traceback (if any).
  593. The return value of this handler is ignored.
  594. """
  595. pass
  596. def send_error_email(self, context, exc, **kwargs):
  597. if self.send_error_emails and \
  598. not getattr(self, 'disable_error_emails', None):
  599. self.ErrorMail(self, **kwargs).send(context, exc)
  600. def execute(self, request, pool, loglevel, logfile, **kwargs):
  601. """The method the worker calls to execute the task.
  602. :param request: A :class:`~celery.worker.job.Request`.
  603. :param pool: A task pool.
  604. :param loglevel: Current loglevel.
  605. :param logfile: Name of the currently used logfile.
  606. :keyword consumer: The :class:`~celery.worker.consumer.Consumer`.
  607. """
  608. request.execute_using_pool(pool, loglevel, logfile)
  609. def push_request(self, *args, **kwargs):
  610. self.request_stack.push(Context(*args, **kwargs))
  611. def pop_request(self):
  612. self.request_stack.pop()
  613. def __repr__(self):
  614. """`repr(task)`"""
  615. return '<@task: {0.name}>'.format(self)
  616. @property
  617. def request(self):
  618. """Current request object."""
  619. return self.request_stack.top
  620. @property
  621. def __name__(self):
  622. return self.__class__.__name__
  623. BaseTask = Task # compat alias