task.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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 billiard.einfo import ExceptionInfo
  10. from celery import current_app, group
  11. from celery import states
  12. from celery._state import _task_stack
  13. from celery.canvas import signature
  14. from celery.exceptions import Ignore, MaxRetriesExceededError, Reject, Retry
  15. from celery.five import class_property, items
  16. from celery.result import EagerResult
  17. from celery.utils import uuid, maybe_reraise
  18. from celery.utils.functional import mattrgetter, maybe_list
  19. from celery.utils.imports import instantiate
  20. from celery.utils.mail import ErrorMail
  21. from .annotations import resolve_all as resolve_all_annotations
  22. from .registry import _unpickle_task_v2
  23. from .utils import appstr
  24. __all__ = ['Context', 'Task']
  25. #: extracts attributes related to publishing a message from an object.
  26. extract_exec_options = mattrgetter(
  27. 'queue', 'routing_key', 'exchange', 'priority', 'expires',
  28. 'serializer', 'delivery_mode', 'compression', 'time_limit',
  29. 'soft_time_limit', 'immediate', 'mandatory', # imm+man is deprecated
  30. )
  31. # We take __repr__ very seriously around here ;)
  32. R_BOUND_TASK = '<class {0.__name__} of {app}{flags}>'
  33. R_UNBOUND_TASK = '<unbound {0.__name__}{flags}>'
  34. R_SELF_TASK = '<@task {0.name} bound to other {0.__self__}>'
  35. R_INSTANCE = '<@task: {0.name} of {app}{flags}>'
  36. #: Here for backwards compatibility as tasks no longer use a custom metaclass.
  37. TaskType = type
  38. def _strflags(flags, default=''):
  39. if flags:
  40. return ' ({0})'.format(', '.join(flags))
  41. return default
  42. def _reprtask(task, fmt=None, flags=None):
  43. flags = list(flags) if flags is not None else []
  44. flags.append('v2 compatible') if task.__v2_compat__ else None
  45. if not fmt:
  46. fmt = R_BOUND_TASK if task._app else R_UNBOUND_TASK
  47. return fmt.format(
  48. task, flags=_strflags(flags),
  49. app=appstr(task._app) if task._app else None,
  50. )
  51. class Context(object):
  52. # Default context
  53. logfile = None
  54. loglevel = None
  55. hostname = None
  56. id = None
  57. args = None
  58. kwargs = None
  59. retries = 0
  60. eta = None
  61. expires = None
  62. is_eager = False
  63. headers = None
  64. delivery_info = None
  65. reply_to = None
  66. root_id = None
  67. parent_id = None
  68. correlation_id = None
  69. taskset = None # compat alias to group
  70. group = None
  71. chord = None
  72. utc = None
  73. called_directly = True
  74. callbacks = None
  75. errbacks = None
  76. timelimit = None
  77. _children = None # see property
  78. _protected = 0
  79. def __init__(self, *args, **kwargs):
  80. self.update(*args, **kwargs)
  81. def update(self, *args, **kwargs):
  82. return self.__dict__.update(*args, **kwargs)
  83. def clear(self):
  84. return self.__dict__.clear()
  85. def get(self, key, default=None):
  86. return getattr(self, key, default)
  87. def __repr__(self):
  88. return '<Context: {0!r}>'.format(vars(self))
  89. @property
  90. def children(self):
  91. # children must be an empy list for every thread
  92. if self._children is None:
  93. self._children = []
  94. return self._children
  95. class Task(object):
  96. """Task base class.
  97. When called tasks apply the :meth:`run` method. This method must
  98. be defined by all tasks (that is unless the :meth:`__call__` method
  99. is overridden).
  100. """
  101. __trace__ = None
  102. __v2_compat__ = False # set by old base in celery.task.base
  103. ErrorMail = ErrorMail
  104. MaxRetriesExceededError = MaxRetriesExceededError
  105. #: Execution strategy used, or the qualified name of one.
  106. Strategy = 'celery.worker.strategy:default'
  107. #: This is the instance bound to if the task is a method of a class.
  108. __self__ = None
  109. #: The application instance associated with this task class.
  110. _app = None
  111. #: Name of the task.
  112. name = None
  113. #: If :const:`True` the task is an abstract base class.
  114. abstract = True
  115. #: Maximum number of retries before giving up. If set to :const:`None`,
  116. #: it will **never** stop retrying.
  117. max_retries = 3
  118. #: Default time in seconds before a retry of the task should be
  119. #: executed. 3 minutes by default.
  120. default_retry_delay = 3 * 60
  121. #: Rate limit for this task type. Examples: :const:`None` (no rate
  122. #: limit), `'100/s'` (hundred tasks a second), `'100/m'` (hundred tasks
  123. #: a minute),`'100/h'` (hundred tasks an hour)
  124. rate_limit = None
  125. #: If enabled the worker will not store task state and return values
  126. #: for this task. Defaults to the :setting:`CELERY_IGNORE_RESULT`
  127. #: setting.
  128. ignore_result = None
  129. #: If enabled the request will keep track of subtasks started by
  130. #: this task, and this information will be sent with the result
  131. #: (``result.children``).
  132. trail = True
  133. #: When enabled errors will be stored even if the task is otherwise
  134. #: configured to ignore results.
  135. store_errors_even_if_ignored = None
  136. #: If enabled an email will be sent to :setting:`ADMINS` whenever a task
  137. #: of this type fails.
  138. send_error_emails = None
  139. #: The name of a serializer that are registered with
  140. #: :mod:`kombu.serialization.registry`. Default is `'pickle'`.
  141. serializer = None
  142. #: Hard time limit.
  143. #: Defaults to the :setting:`CELERYD_TASK_TIME_LIMIT` setting.
  144. time_limit = None
  145. #: Soft time limit.
  146. #: Defaults to the :setting:`CELERYD_TASK_SOFT_TIME_LIMIT` setting.
  147. soft_time_limit = None
  148. #: The result store backend used for this task.
  149. backend = None
  150. #: If disabled this task won't be registered automatically.
  151. autoregister = True
  152. #: If enabled the task will report its status as 'started' when the task
  153. #: is executed by a worker. Disabled by default as the normal behaviour
  154. #: is to not report that level of granularity. Tasks are either pending,
  155. #: finished, or waiting to be retried.
  156. #:
  157. #: Having a 'started' status can be useful for when there are long
  158. #: running tasks and there is a need to report which task is currently
  159. #: running.
  160. #:
  161. #: The application default can be overridden using the
  162. #: :setting:`CELERY_TRACK_STARTED` setting.
  163. track_started = None
  164. #: When enabled messages for this task will be acknowledged **after**
  165. #: the task has been executed, and not *just before* which is the
  166. #: default behavior.
  167. #:
  168. #: Please note that this means the task may be executed twice if the
  169. #: worker crashes mid execution (which may be acceptable for some
  170. #: applications).
  171. #:
  172. #: The application default can be overridden with the
  173. #: :setting:`CELERY_ACKS_LATE` setting.
  174. acks_late = None
  175. #: Tuple of expected exceptions.
  176. #:
  177. #: These are errors that are expected in normal operation
  178. #: and that should not be regarded as a real error by the worker.
  179. #: Currently this means that the state will be updated to an error
  180. #: state, but the worker will not log the event as an error.
  181. throws = ()
  182. #: Default task expiry time.
  183. expires = None
  184. #: Some may expect a request to exist even if the task has not been
  185. #: called. This should probably be deprecated.
  186. _default_request = None
  187. _exec_options = None
  188. __bound__ = False
  189. from_config = (
  190. ('send_error_emails', 'CELERY_SEND_TASK_ERROR_EMAILS'),
  191. ('serializer', 'CELERY_TASK_SERIALIZER'),
  192. ('rate_limit', 'CELERY_DEFAULT_RATE_LIMIT'),
  193. ('track_started', 'CELERY_TRACK_STARTED'),
  194. ('acks_late', 'CELERY_ACKS_LATE'),
  195. ('ignore_result', 'CELERY_IGNORE_RESULT'),
  196. ('store_errors_even_if_ignored',
  197. 'CELERY_STORE_ERRORS_EVEN_IF_IGNORED'),
  198. )
  199. #: ignored
  200. accept_magic_kwargs = False
  201. _backend = None # set by backend property.
  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. self._exec_options = None # clear option cache
  211. for attr_name, config_name in self.from_config:
  212. if getattr(self, attr_name, None) is None:
  213. setattr(self, attr_name, conf[config_name])
  214. # decorate with annotations from config.
  215. if not was_bound:
  216. self.annotate()
  217. from celery.utils.threads import LocalStack
  218. self.request_stack = LocalStack()
  219. # PeriodicTask uses this to add itself to the PeriodicTask schedule.
  220. self.on_bound(app)
  221. return app
  222. @classmethod
  223. def on_bound(self, app):
  224. """This method can be defined to do additional actions when the
  225. task class is bound to an app."""
  226. pass
  227. @classmethod
  228. def _get_app(self):
  229. if self._app is None:
  230. self._app = current_app
  231. if not self.__bound__:
  232. # The app property's __set__ method is not called
  233. # if Task.app is set (on the class), so must bind on use.
  234. self.bind(self._app)
  235. return self._app
  236. app = class_property(_get_app, bind)
  237. @classmethod
  238. def annotate(self):
  239. for d in resolve_all_annotations(self.app.annotations, self):
  240. for key, value in items(d):
  241. if key.startswith('@'):
  242. self.add_around(key[1:], value)
  243. else:
  244. setattr(self, key, value)
  245. @classmethod
  246. def add_around(self, attr, around):
  247. orig = getattr(self, attr)
  248. if getattr(orig, '__wrapped__', None):
  249. orig = orig.__wrapped__
  250. meth = around(orig)
  251. meth.__wrapped__ = orig
  252. setattr(self, attr, meth)
  253. def __call__(self, *args, **kwargs):
  254. _task_stack.push(self)
  255. self.push_request(args=args, kwargs=kwargs)
  256. try:
  257. # add self if this is a bound task
  258. if self.__self__ is not None:
  259. return self.run(self.__self__, *args, **kwargs)
  260. return self.run(*args, **kwargs)
  261. finally:
  262. self.pop_request()
  263. _task_stack.pop()
  264. def __reduce__(self):
  265. # - tasks are pickled into the name of the task only, and the reciever
  266. # - simply grabs it from the local registry.
  267. # - in later versions the module of the task is also included,
  268. # - and the receiving side tries to import that module so that
  269. # - it will work even if the task has not been registered.
  270. mod = type(self).__module__
  271. mod = mod if mod and mod in sys.modules else None
  272. return (_unpickle_task_v2, (self.name, mod), None)
  273. def run(self, *args, **kwargs):
  274. """The body of the task executed by workers."""
  275. raise NotImplementedError('Tasks must define the run method.')
  276. def start_strategy(self, app, consumer, **kwargs):
  277. return instantiate(self.Strategy, self, app, consumer, **kwargs)
  278. def delay(self, *args, **kwargs):
  279. """Star argument version of :meth:`apply_async`.
  280. Does not support the extra options enabled by :meth:`apply_async`.
  281. :param \*args: positional arguments passed on to the task.
  282. :param \*\*kwargs: keyword arguments passed on to the task.
  283. :returns :class:`celery.result.AsyncResult`:
  284. """
  285. return self.apply_async(args, kwargs)
  286. def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
  287. link=None, link_error=None, shadow=None, **options):
  288. """Apply tasks asynchronously by sending a message.
  289. :keyword args: The positional arguments to pass on to the
  290. task (a :class:`list` or :class:`tuple`).
  291. :keyword kwargs: The keyword arguments to pass on to the
  292. task (a :class:`dict`)
  293. :keyword countdown: Number of seconds into the future that the
  294. task should execute. Defaults to immediate
  295. execution.
  296. :keyword eta: A :class:`~datetime.datetime` object describing
  297. the absolute time and date of when the task should
  298. be executed. May not be specified if `countdown`
  299. is also supplied.
  300. :keyword expires: Either a :class:`int`, describing the number of
  301. seconds, or a :class:`~datetime.datetime` object
  302. that describes the absolute time and date of when
  303. the task should expire. The task will not be
  304. executed after the expiration time.
  305. :keyword shadow: Override task name used in logs/monitoring
  306. (default from :meth:`shadow_name`).
  307. :keyword connection: Re-use existing broker connection instead
  308. of establishing a new one.
  309. :keyword retry: If enabled sending of the task message will be retried
  310. in the event of connection loss or failure. Default
  311. is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
  312. setting. Note that you need to handle the
  313. producer/connection manually for this to work.
  314. :keyword retry_policy: Override the retry policy used. See the
  315. :setting:`CELERY_TASK_PUBLISH_RETRY_POLICY`
  316. setting.
  317. :keyword routing_key: Custom routing key used to route the task to a
  318. worker server. If in combination with a
  319. ``queue`` argument only used to specify custom
  320. routing keys to topic exchanges.
  321. :keyword queue: The queue to route the task to. This must be a key
  322. present in :setting:`CELERY_QUEUES`, or
  323. :setting:`CELERY_CREATE_MISSING_QUEUES` must be
  324. enabled. See :ref:`guide-routing` for more
  325. information.
  326. :keyword exchange: Named custom exchange to send the task to.
  327. Usually not used in combination with the ``queue``
  328. argument.
  329. :keyword priority: The task priority, a number between 0 and 9.
  330. Defaults to the :attr:`priority` attribute.
  331. :keyword serializer: A string identifying the default
  332. serialization method to use. Can be `pickle`,
  333. `json`, `yaml`, `msgpack` or any custom
  334. serialization method that has been registered
  335. with :mod:`kombu.serialization.registry`.
  336. Defaults to the :attr:`serializer` attribute.
  337. :keyword compression: A string identifying the compression method
  338. to use. Can be one of ``zlib``, ``bzip2``,
  339. or any custom compression methods registered with
  340. :func:`kombu.compression.register`. Defaults to
  341. the :setting:`CELERY_MESSAGE_COMPRESSION`
  342. setting.
  343. :keyword link: A single, or a list of tasks to apply if the
  344. task exits successfully.
  345. :keyword link_error: A single, or a list of tasks to apply
  346. if an error occurs while executing the task.
  347. :keyword producer: :class:`kombu.Producer` instance to use.
  348. :keyword add_to_parent: If set to True (default) and the task
  349. is applied while executing another task, then the result
  350. will be appended to the parent tasks ``request.children``
  351. attribute. Trailing can also be disabled by default using the
  352. :attr:`trail` attribute
  353. :keyword publisher: Deprecated alias to ``producer``.
  354. :rtype :class:`celery.result.AsyncResult`: if
  355. :setting:`CELERY_ALWAYS_EAGER` is not set, otherwise
  356. :class:`celery.result.EagerResult`:
  357. Also supports all keyword arguments supported by
  358. :meth:`kombu.Producer.publish`.
  359. .. note::
  360. If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
  361. be replaced by a local :func:`apply` call instead.
  362. """
  363. try:
  364. check_arguments = self.__header__
  365. except AttributeError:
  366. pass
  367. else:
  368. check_arguments(*args or (), **kwargs or {})
  369. app = self._get_app()
  370. if app.conf.CELERY_ALWAYS_EAGER:
  371. return self.apply(args, kwargs, task_id=task_id or uuid(),
  372. link=link, link_error=link_error, **options)
  373. # add 'self' if this is a "task_method".
  374. if self.__self__ is not None:
  375. args = args if isinstance(args, tuple) else tuple(args or ())
  376. args = (self.__self__,) + args
  377. preopts = self._get_exec_options()
  378. options = dict(preopts, **options) if options else preopts
  379. return app.send_task(
  380. self.name, args, kwargs, task_id=task_id, producer=producer,
  381. link=link, link_error=link_error, result_cls=self.AsyncResult,
  382. shadow=shadow or self.shadow_name(args, kwargs, options),
  383. **options
  384. )
  385. def shadow_name(self, args, kwargs, options):
  386. """Override for custom task name in worker logs/monitoring.
  387. :param args: Task positional arguments.
  388. :param kwargs: Task keyword arguments.
  389. :param options: Task execution options.
  390. **Example**:
  391. .. code-block:: python
  392. from celery.utils.imports import qualname
  393. def shadow_name(task, args, kwargs, options):
  394. return qualname(args[0])
  395. @app.task(shadow_name=shadow_name, serializer='pickle')
  396. def apply_function_async(fun, *args, **kwargs):
  397. return fun(*args, **kwargs)
  398. """
  399. pass
  400. def signature_from_request(self, request=None, args=None, kwargs=None,
  401. queue=None, **extra_options):
  402. request = self.request if request is None else request
  403. args = request.args if args is None else args
  404. kwargs = request.kwargs if kwargs is None else kwargs
  405. limit_hard, limit_soft = request.timelimit or (None, None)
  406. options = {
  407. 'task_id': request.id,
  408. 'link': request.callbacks,
  409. 'link_error': request.errbacks,
  410. 'group_id': request.group,
  411. 'chord': request.chord,
  412. 'soft_time_limit': limit_soft,
  413. 'time_limit': limit_hard,
  414. 'reply_to': request.reply_to,
  415. }
  416. options.update(
  417. {'queue': queue} if queue else (request.delivery_info or {})
  418. )
  419. return self.signature(
  420. args, kwargs, options, type=self, **extra_options
  421. )
  422. subtask_from_request = signature_from_request
  423. def retry(self, args=None, kwargs=None, exc=None, throw=True,
  424. eta=None, countdown=None, max_retries=None, **options):
  425. """Retry the task.
  426. :param args: Positional arguments to retry with.
  427. :param kwargs: Keyword arguments to retry with.
  428. :keyword exc: Custom exception to report when the max restart
  429. limit has been exceeded (default:
  430. :exc:`~@MaxRetriesExceededError`).
  431. If this argument is set and retry is called while
  432. an exception was raised (``sys.exc_info()`` is set)
  433. it will attempt to reraise the current exception.
  434. If no exception was raised it will raise the ``exc``
  435. argument provided.
  436. :keyword countdown: Time in seconds to delay the retry for.
  437. :keyword eta: Explicit time and date to run the retry at
  438. (must be a :class:`~datetime.datetime` instance).
  439. :keyword max_retries: If set, overrides the default retry limit.
  440. A value of :const:`None`, means "use the default", so if you want
  441. infinite retries you would have to set the :attr:`max_retries`
  442. attribute of the task to :const:`None` first.
  443. :keyword time_limit: If set, overrides the default time limit.
  444. :keyword soft_time_limit: If set, overrides the default soft
  445. time limit.
  446. :keyword \*\*options: Any extra options to pass on to
  447. meth:`apply_async`.
  448. :keyword throw: If this is :const:`False`, do not raise the
  449. :exc:`~@Retry` exception,
  450. that tells the worker to mark the task as being
  451. retried. Note that this means the task will be
  452. marked as failed if the task raises an exception,
  453. or successful if it returns.
  454. :raises celery.exceptions.Retry: To tell the worker that
  455. the task has been re-sent for retry. This always happens,
  456. unless the `throw` keyword argument has been explicitly set
  457. to :const:`False`, and is considered normal operation.
  458. **Example**
  459. .. code-block:: python
  460. >>> from imaginary_twitter_lib import Twitter
  461. >>> from proj.celery import app
  462. >>> @app.task(bind=True)
  463. ... def tweet(self, auth, message):
  464. ... twitter = Twitter(oauth=auth)
  465. ... try:
  466. ... twitter.post_status_update(message)
  467. ... except twitter.FailWhale as exc:
  468. ... # Retry in 5 minutes.
  469. ... raise self.retry(countdown=60 * 5, exc=exc)
  470. Although the task will never return above as `retry` raises an
  471. exception to notify the worker, we use `raise` in front of the retry
  472. to convey that the rest of the block will not be executed.
  473. """
  474. request = self.request
  475. retries = request.retries + 1
  476. max_retries = self.max_retries if max_retries is None else max_retries
  477. # Not in worker or emulated by (apply/always_eager),
  478. # so just raise the original exception.
  479. if request.called_directly:
  480. maybe_reraise() # raise orig stack if PyErr_Occurred
  481. raise exc or Retry('Task can be retried', None)
  482. if not eta and countdown is None:
  483. countdown = self.default_retry_delay
  484. is_eager = request.is_eager
  485. S = self.signature_from_request(
  486. request, args, kwargs,
  487. countdown=countdown, eta=eta, retries=retries,
  488. **options
  489. )
  490. if max_retries is not None and retries > max_retries:
  491. if exc:
  492. # first try to reraise the original exception
  493. maybe_reraise()
  494. # or if not in an except block then raise the custom exc.
  495. raise exc
  496. raise self.MaxRetriesExceededError(
  497. "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
  498. self.name, request.id, S.args, S.kwargs))
  499. ret = Retry(exc=exc, when=eta or countdown)
  500. if is_eager:
  501. # if task was executed eagerly using apply(),
  502. # then the retry must also be executed eagerly.
  503. S.apply().get()
  504. if throw:
  505. raise ret
  506. return ret
  507. try:
  508. S.apply_async()
  509. except Exception as exc:
  510. raise Reject(exc, requeue=False)
  511. if throw:
  512. raise ret
  513. return ret
  514. def apply(self, args=None, kwargs=None,
  515. link=None, link_error=None, **options):
  516. """Execute this task locally, by blocking until the task returns.
  517. :param args: positional arguments passed on to the task.
  518. :param kwargs: keyword arguments passed on to the task.
  519. :keyword throw: Re-raise task exceptions. Defaults to
  520. the :setting:`CELERY_EAGER_PROPAGATES_EXCEPTIONS`
  521. setting.
  522. :rtype :class:`celery.result.EagerResult`:
  523. """
  524. # trace imports Task, so need to import inline.
  525. from celery.app.trace import build_tracer
  526. app = self._get_app()
  527. args = args or ()
  528. # add 'self' if this is a bound method.
  529. if self.__self__ is not None:
  530. args = (self.__self__,) + tuple(args)
  531. kwargs = kwargs or {}
  532. task_id = options.get('task_id') or uuid()
  533. retries = options.get('retries', 0)
  534. throw = app.either('CELERY_EAGER_PROPAGATES_EXCEPTIONS',
  535. options.pop('throw', None))
  536. # Make sure we get the task instance, not class.
  537. task = app._tasks[self.name]
  538. request = {'id': task_id,
  539. 'retries': retries,
  540. 'is_eager': True,
  541. 'logfile': options.get('logfile'),
  542. 'loglevel': options.get('loglevel', 0),
  543. 'callbacks': maybe_list(link),
  544. 'errbacks': maybe_list(link_error),
  545. 'headers': options.get('headers'),
  546. 'delivery_info': {'is_eager': True}}
  547. tb = None
  548. tracer = build_tracer(
  549. task.name, task, eager=True,
  550. propagate=throw, app=self._get_app(),
  551. )
  552. ret = tracer(task_id, args, kwargs, request)
  553. retval = ret.retval
  554. if isinstance(retval, ExceptionInfo):
  555. retval, tb = retval.exception, retval.traceback
  556. state = states.SUCCESS if ret.info is None else ret.info.state
  557. return EagerResult(task_id, retval, state, traceback=tb)
  558. def AsyncResult(self, task_id, **kwargs):
  559. """Get AsyncResult instance for this kind of task.
  560. :param task_id: Task id to get result for.
  561. """
  562. return self._get_app().AsyncResult(task_id, backend=self.backend,
  563. task_name=self.name, **kwargs)
  564. def signature(self, args=None, *starargs, **starkwargs):
  565. """Return :class:`~celery.signature` object for
  566. this task, wrapping arguments and execution options
  567. for a single task invocation."""
  568. starkwargs.setdefault('app', self.app)
  569. return signature(self, args, *starargs, **starkwargs)
  570. subtask = signature
  571. def s(self, *args, **kwargs):
  572. """``.s(*a, **k) -> .signature(a, k)``"""
  573. return self.signature(args, kwargs)
  574. def si(self, *args, **kwargs):
  575. """``.si(*a, **k) -> .signature(a, k, immutable=True)``"""
  576. return self.signature(args, kwargs, immutable=True)
  577. def chunks(self, it, n):
  578. """Creates a :class:`~celery.canvas.chunks` task for this task."""
  579. from celery import chunks
  580. return chunks(self.s(), it, n, app=self.app)
  581. def map(self, it):
  582. """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
  583. from celery import xmap
  584. return xmap(self.s(), it, app=self.app)
  585. def starmap(self, it):
  586. """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
  587. from celery import xstarmap
  588. return xstarmap(self.s(), it, app=self.app)
  589. def send_event(self, type_, **fields):
  590. req = self.request
  591. with self.app.events.default_dispatcher(hostname=req.hostname) as d:
  592. return d.send(type_, uuid=req.id, **fields)
  593. def replace(self, sig):
  594. """Replace the current task, with a new task inheriting the
  595. same task id.
  596. :param sig: :class:`@signature`
  597. Note: This will raise :exc:`~@Ignore`, so the best practice
  598. is to always use ``raise self.replace_in_chord(...)`` to convey
  599. to the reader that the task will not continue after being replaced.
  600. :param: Signature of new task.
  601. """
  602. chord = self.request.chord
  603. if isinstance(sig, group):
  604. sig |= self.app.tasks['celery.accumulate'].s(index=0).set(
  605. chord=chord,
  606. )
  607. chord = None
  608. sig.freeze(self.request.id,
  609. group_id=self.request.group,
  610. chord=chord,
  611. root_id=self.request.root_id)
  612. sig.delay()
  613. raise Ignore('Chord member replaced by new task')
  614. def add_to_chord(self, sig, lazy=False):
  615. """Add signature to the chord the current task is a member of.
  616. :param sig: Signature to extend chord with.
  617. :param lazy: If enabled the new task will not actually be called,
  618. and ``sig.delay()`` must be called manually.
  619. Currently only supported by the Redis result backend when
  620. ``?new_join=1`` is enabled.
  621. """
  622. if not self.request.chord:
  623. raise ValueError('Current task is not member of any chord')
  624. result = sig.freeze(group_id=self.request.group,
  625. chord=self.request.chord,
  626. root_id=self.request.root_id)
  627. self.backend.add_to_chord(self.request.group, result)
  628. return sig.delay() if not lazy else sig
  629. def update_state(self, task_id=None, state=None, meta=None):
  630. """Update task state.
  631. :keyword task_id: Id of the task to update, defaults to the
  632. id of the current task
  633. :keyword state: New state (:class:`str`).
  634. :keyword meta: State metadata (:class:`dict`).
  635. """
  636. if task_id is None:
  637. task_id = self.request.id
  638. self.backend.store_result(task_id, meta, state)
  639. def on_success(self, retval, task_id, args, kwargs):
  640. """Success handler.
  641. Run by the worker if the task executes successfully.
  642. :param retval: The return value of the task.
  643. :param task_id: Unique id of the executed task.
  644. :param args: Original arguments for the executed task.
  645. :param kwargs: Original keyword arguments for the executed task.
  646. The return value of this handler is ignored.
  647. """
  648. pass
  649. def on_retry(self, exc, task_id, args, kwargs, einfo):
  650. """Retry handler.
  651. This is run by the worker when the task is to be retried.
  652. :param exc: The exception sent to :meth:`retry`.
  653. :param task_id: Unique id of the retried task.
  654. :param args: Original arguments for the retried task.
  655. :param kwargs: Original keyword arguments for the retried task.
  656. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  657. instance, containing the traceback.
  658. The return value of this handler is ignored.
  659. """
  660. pass
  661. def on_failure(self, exc, task_id, args, kwargs, einfo):
  662. """Error handler.
  663. This is run by the worker when the task fails.
  664. :param exc: The exception raised by the task.
  665. :param task_id: Unique id of the failed task.
  666. :param args: Original arguments for the task that failed.
  667. :param kwargs: Original keyword arguments for the task
  668. that failed.
  669. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  670. instance, containing the traceback.
  671. The return value of this handler is ignored.
  672. """
  673. pass
  674. def after_return(self, status, retval, task_id, args, kwargs, einfo):
  675. """Handler called after the task returns.
  676. :param status: Current task state.
  677. :param retval: Task return value/exception.
  678. :param task_id: Unique id of the task.
  679. :param args: Original arguments for the task.
  680. :param kwargs: Original keyword arguments for the task.
  681. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  682. instance, containing the traceback (if any).
  683. The return value of this handler is ignored.
  684. """
  685. pass
  686. def send_error_email(self, context, exc, **kwargs):
  687. if self.send_error_emails and \
  688. not getattr(self, 'disable_error_emails', None):
  689. self.ErrorMail(self, **kwargs).send(context, exc)
  690. def add_trail(self, result):
  691. if self.trail:
  692. self.request.children.append(result)
  693. return result
  694. def push_request(self, *args, **kwargs):
  695. self.request_stack.push(Context(*args, **kwargs))
  696. def pop_request(self):
  697. self.request_stack.pop()
  698. def __repr__(self):
  699. """`repr(task)`"""
  700. return _reprtask(self, R_SELF_TASK if self.__self__ else R_INSTANCE)
  701. def _get_request(self):
  702. """Get current request object."""
  703. req = self.request_stack.top
  704. if req is None:
  705. # task was not called, but some may still expect a request
  706. # to be there, perhaps that should be deprecated.
  707. if self._default_request is None:
  708. self._default_request = Context()
  709. return self._default_request
  710. return req
  711. request = property(_get_request)
  712. def _get_exec_options(self):
  713. if self._exec_options is None:
  714. self._exec_options = extract_exec_options(self)
  715. return self._exec_options
  716. @property
  717. def backend(self):
  718. backend = self._backend
  719. if backend is None:
  720. return self.app.backend
  721. return backend
  722. @backend.setter
  723. def backend(self, value): # noqa
  724. self._backend = value
  725. @property
  726. def __name__(self):
  727. return self.__class__.__name__
  728. BaseTask = Task # compat alias