task.py 34 KB

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