task.py 36 KB

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