task.py 36 KB

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