task.py 30 KB

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