task.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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_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. 'headers': self.headers,
  106. 'retries': self.retries,
  107. 'reply_to': self.reply_to,
  108. 'origin': self.origin,
  109. }
  110. @property
  111. def children(self):
  112. # children must be an empty list for every thread
  113. if self._children is None:
  114. self._children = []
  115. return self._children
  116. @abstract.CallableTask.register
  117. @python_2_unicode_compatible
  118. class Task(object):
  119. """Task base class.
  120. Note:
  121. When called tasks apply the :meth:`run` method. This method must
  122. be defined by all tasks (that is unless the :meth:`__call__` method
  123. is overridden).
  124. """
  125. __trace__ = None
  126. __v2_compat__ = False # set by old base in celery.task.base
  127. MaxRetriesExceededError = MaxRetriesExceededError
  128. OperationalError = OperationalError
  129. #: Execution strategy used, or the qualified name of one.
  130. Strategy = 'celery.worker.strategy:default'
  131. #: Request class used, or the qualified name of one.
  132. Request = 'celery.worker.request:Request'
  133. #: The application instance associated with this task class.
  134. _app = None
  135. #: Name of the task.
  136. name = None
  137. #: Enable argument checking.
  138. #: You can set this to false if you don't want the signature to be
  139. #: checked when calling the task.
  140. #: Defaults to :attr:`app.strict_typing <@Celery.strict_typing>`.
  141. typing = None
  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. if cls.typing is None:
  255. cls.typing = app.strict_typing
  256. for attr_name, config_name in cls.from_config:
  257. if getattr(cls, attr_name, None) is None:
  258. setattr(cls, attr_name, conf[config_name])
  259. # decorate with annotations from config.
  260. if not was_bound:
  261. cls.annotate()
  262. from celery.utils.threads import LocalStack
  263. cls.request_stack = LocalStack()
  264. # PeriodicTask uses this to add itself to the PeriodicTask schedule.
  265. cls.on_bound(app)
  266. return app
  267. @classmethod
  268. def on_bound(cls, app):
  269. """Called when the task is bound to an app.
  270. Note:
  271. This class method can be defined to do additional actions when
  272. the task class is bound to an app.
  273. """
  274. @classmethod
  275. def _get_app(cls):
  276. if cls._app is None:
  277. cls._app = current_app
  278. if not cls.__bound__:
  279. # The app property's __set__ method is not called
  280. # if Task.app is set (on the class), so must bind on use.
  281. cls.bind(cls._app)
  282. return cls._app
  283. app = class_property(_get_app, bind)
  284. @classmethod
  285. def annotate(cls):
  286. for d in resolve_all_annotations(cls.app.annotations, cls):
  287. for key, value in items(d):
  288. if key.startswith('@'):
  289. cls.add_around(key[1:], value)
  290. else:
  291. setattr(cls, key, value)
  292. @classmethod
  293. def add_around(cls, attr, around):
  294. orig = getattr(cls, attr)
  295. if getattr(orig, '__wrapped__', None):
  296. orig = orig.__wrapped__
  297. meth = around(orig)
  298. meth.__wrapped__ = orig
  299. setattr(cls, attr, meth)
  300. def __call__(self, *args, **kwargs):
  301. _task_stack.push(self)
  302. self.push_request(args=args, kwargs=kwargs)
  303. try:
  304. return self.run(*args, **kwargs)
  305. finally:
  306. self.pop_request()
  307. _task_stack.pop()
  308. def __reduce__(self):
  309. # - tasks are pickled into the name of the task only, and the receiver
  310. # - simply grabs it from the local registry.
  311. # - in later versions the module of the task is also included,
  312. # - and the receiving side tries to import that module so that
  313. # - it will work even if the task hasn't been registered.
  314. mod = type(self).__module__
  315. mod = mod if mod and mod in sys.modules else None
  316. return (_unpickle_task_v2, (self.name, mod), None)
  317. def run(self, *args, **kwargs):
  318. """The body of the task executed by workers."""
  319. raise NotImplementedError('Tasks must define the run method.')
  320. def start_strategy(self, app, consumer, **kwargs):
  321. return instantiate(self.Strategy, self, app, consumer, **kwargs)
  322. def delay(self, *args, **kwargs):
  323. """Star argument version of :meth:`apply_async`.
  324. Does not support the extra options enabled by :meth:`apply_async`.
  325. Arguments:
  326. *args (Any): Positional arguments passed on to the task.
  327. **kwargs (Any): Keyword arguments passed on to the task.
  328. Returns:
  329. celery.result.AsyncResult: Future promise.
  330. """
  331. return self.apply_async(args, kwargs)
  332. def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
  333. link=None, link_error=None, shadow=None, **options):
  334. """Apply tasks asynchronously by sending a message.
  335. Arguments:
  336. args (Tuple): The positional arguments to pass on to the task.
  337. kwargs (Dict): The keyword arguments to pass on to the task.
  338. countdown (float): Number of seconds into the future that the
  339. task should execute. Defaults to immediate execution.
  340. eta (~datetime.datetime): Absolute time and date of when the task
  341. should be executed. May not be specified if `countdown`
  342. is also supplied.
  343. expires (float, ~datetime.datetime): Datetime or
  344. seconds in the future for the task should expire.
  345. The task won't be executed after the expiration time.
  346. shadow (str): Override task name used in logs/monitoring.
  347. Default is retrieved from :meth:`shadow_name`.
  348. connection (kombu.Connection): Re-use existing broker connection
  349. instead of acquiring one from the connection pool.
  350. retry (bool): If enabled sending of the task message will be
  351. retried in the event of connection loss or failure.
  352. Default is taken from the :setting:`task_publish_retry`
  353. setting. Note that you need to handle the
  354. producer/connection manually for this to work.
  355. retry_policy (Mapping): Override the retry policy used.
  356. See the :setting:`task_publish_retry_policy` setting.
  357. queue (str, kombu.Queue): The queue to route the task to.
  358. This must be a key present in :setting:`task_queues`, or
  359. :setting:`task_create_missing_queues` must be
  360. enabled. See :ref:`guide-routing` for more
  361. information.
  362. exchange (str, kombu.Exchange): Named custom exchange to send the
  363. task to. Usually not used in combination with the ``queue``
  364. argument.
  365. routing_key (str): Custom routing key used to route the task to a
  366. worker server. If in combination with a ``queue`` argument
  367. only used to specify custom routing keys to topic exchanges.
  368. priority (int): The task priority, a number between 0 and 9.
  369. Defaults to the :attr:`priority` attribute.
  370. serializer (str): Serialization method to use.
  371. Can be `pickle`, `json`, `yaml`, `msgpack` or any custom
  372. serialization method that's been registered
  373. with :mod:`kombu.serialization.registry`.
  374. Defaults to the :attr:`serializer` attribute.
  375. compression (str): Optional compression method
  376. to use. Can be one of ``zlib``, ``bzip2``,
  377. or any custom compression methods registered with
  378. :func:`kombu.compression.register`.
  379. Defaults to the :setting:`task_compression` setting.
  380. link (~@Signature): A single, or a list of tasks signatures
  381. to apply if the task returns successfully.
  382. link_error (~@Signature): A single, or a list of task signatures
  383. to apply if an error occurs while executing the task.
  384. producer (kombu.Producer): custom producer to use when publishing
  385. the task.
  386. add_to_parent (bool): If set to True (default) and the task
  387. is applied while executing another task, then the result
  388. will be appended to the parent tasks ``request.children``
  389. attribute. Trailing can also be disabled by default using the
  390. :attr:`trail` attribute
  391. publisher (kombu.Producer): Deprecated alias to ``producer``.
  392. headers (Dict): Message headers to be included in the message.
  393. Returns:
  394. celery.result.AsyncResult: Promise of future evaluation.
  395. Raises:
  396. TypeError: If not enough arguments are passed, or too many
  397. arguments are passed. Note that signature checks may
  398. be disabled by specifying ``@task(typing=False)``.
  399. kombu.exceptions.OperationalError: If a connection to the
  400. transport cannot be made, or if the connection is lost.
  401. Note:
  402. Also supports all keyword arguments supported by
  403. :meth:`kombu.Producer.publish`.
  404. """
  405. if self.typing:
  406. try:
  407. check_arguments = self.__header__
  408. except AttributeError: # pragma: no cover
  409. pass
  410. else:
  411. check_arguments(*(args or ()), **(kwargs or {}))
  412. app = self._get_app()
  413. if app.conf.task_always_eager:
  414. with denied_join_result():
  415. return self.apply(args, kwargs, task_id=task_id or uuid(),
  416. link=link, link_error=link_error, **options)
  417. if self.__v2_compat__:
  418. shadow = shadow or self.shadow_name(self(), args, kwargs, options)
  419. else:
  420. shadow = shadow or self.shadow_name(args, kwargs, options)
  421. preopts = self._get_exec_options()
  422. options = dict(preopts, **options) if options else preopts
  423. options.setdefault('ignore_result', self.ignore_result)
  424. return app.send_task(
  425. self.name, args, kwargs, task_id=task_id, producer=producer,
  426. link=link, link_error=link_error, result_cls=self.AsyncResult,
  427. shadow=shadow, task_type=self,
  428. **options
  429. )
  430. def shadow_name(self, args, kwargs, options):
  431. """Override for custom task name in worker logs/monitoring.
  432. Example:
  433. .. code-block:: python
  434. from celery.utils.imports import qualname
  435. def shadow_name(task, args, kwargs, options):
  436. return qualname(args[0])
  437. @app.task(shadow_name=shadow_name, serializer='pickle')
  438. def apply_function_async(fun, *args, **kwargs):
  439. return fun(*args, **kwargs)
  440. Arguments:
  441. args (Tuple): Task positional arguments.
  442. kwargs (Dict): Task keyword arguments.
  443. options (Dict): Task execution options.
  444. """
  445. def signature_from_request(self, request=None, args=None, kwargs=None,
  446. queue=None, **extra_options):
  447. request = self.request if request is None else request
  448. args = request.args if args is None else args
  449. kwargs = request.kwargs if kwargs is None else kwargs
  450. options = request.as_execution_options()
  451. if queue:
  452. options['queue'] = queue
  453. else:
  454. delivery_info = request.delivery_info or {}
  455. exchange = delivery_info.get('exchange')
  456. routing_key = delivery_info.get('routing_key')
  457. if exchange == '' and routing_key:
  458. # sent to anon-exchange
  459. options['queue'] = routing_key
  460. else:
  461. options.update(delivery_info)
  462. return self.signature(
  463. args, kwargs, options, type=self, **extra_options
  464. )
  465. subtask_from_request = signature_from_request # XXX compat
  466. def retry(self, args=None, kwargs=None, exc=None, throw=True,
  467. eta=None, countdown=None, max_retries=None, **options):
  468. """Retry the task.
  469. Example:
  470. >>> from imaginary_twitter_lib import Twitter
  471. >>> from proj.celery import app
  472. >>> @app.task(bind=True)
  473. ... def tweet(self, auth, message):
  474. ... twitter = Twitter(oauth=auth)
  475. ... try:
  476. ... twitter.post_status_update(message)
  477. ... except twitter.FailWhale as exc:
  478. ... # Retry in 5 minutes.
  479. ... raise self.retry(countdown=60 * 5, exc=exc)
  480. Note:
  481. Although the task will never return above as `retry` raises an
  482. exception to notify the worker, we use `raise` in front of the
  483. retry to convey that the rest of the block won't be executed.
  484. Arguments:
  485. args (Tuple): Positional arguments to retry with.
  486. kwargs (Dict): Keyword arguments to retry with.
  487. exc (Exception): Custom exception to report when the max retry
  488. limit has been exceeded (default:
  489. :exc:`~@MaxRetriesExceededError`).
  490. If this argument is set and retry is called while
  491. an exception was raised (``sys.exc_info()`` is set)
  492. it will attempt to re-raise the current exception.
  493. If no exception was raised it will raise the ``exc``
  494. argument provided.
  495. countdown (float): Time in seconds to delay the retry for.
  496. eta (~datetime.datetime): Explicit time and date to run the
  497. retry at.
  498. max_retries (int): If set, overrides the default retry limit for
  499. this execution. Changes to this parameter don't propagate to
  500. subsequent task retry attempts. A value of :const:`None`,
  501. means "use the default", so if you want infinite retries you'd
  502. have to set the :attr:`max_retries` attribute of the task to
  503. :const:`None` first.
  504. time_limit (int): If set, overrides the default time limit.
  505. soft_time_limit (int): If set, overrides the default soft
  506. time limit.
  507. throw (bool): If this is :const:`False`, don't raise the
  508. :exc:`~@Retry` exception, that tells the worker to mark
  509. the task as being retried. Note that this means the task
  510. will be marked as failed if the task raises an exception,
  511. or successful if it returns after the retry call.
  512. **options (Any): Extra options to pass on to :meth:`apply_async`.
  513. Raises:
  514. celery.exceptions.Retry:
  515. To tell the worker that the task has been re-sent for retry.
  516. This always happens, unless the `throw` keyword argument
  517. has been explicitly set to :const:`False`, and is considered
  518. normal operation.
  519. """
  520. request = self.request
  521. retries = request.retries + 1
  522. max_retries = self.max_retries if max_retries is None else max_retries
  523. # Not in worker or emulated by (apply/always_eager),
  524. # so just raise the original exception.
  525. if request.called_directly:
  526. # raises orig stack if PyErr_Occurred,
  527. # and augments with exc' if that argument is defined.
  528. raise_with_context(exc or Retry('Task can be retried', None))
  529. if not eta and countdown is None:
  530. countdown = self.default_retry_delay
  531. is_eager = request.is_eager
  532. S = self.signature_from_request(
  533. request, args, kwargs,
  534. countdown=countdown, eta=eta, retries=retries,
  535. **options
  536. )
  537. if max_retries is not None and retries > max_retries:
  538. if exc:
  539. # On Py3: will augment any current exception with
  540. # the exc' argument provided (raise exc from orig)
  541. raise_with_context(exc)
  542. raise self.MaxRetriesExceededError(
  543. "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
  544. self.name, request.id, S.args, S.kwargs))
  545. ret = Retry(exc=exc, when=eta or countdown)
  546. if is_eager:
  547. # if task was executed eagerly using apply(),
  548. # then the retry must also be executed eagerly.
  549. S.apply().get()
  550. if throw:
  551. raise ret
  552. return ret
  553. try:
  554. S.apply_async()
  555. except Exception as exc:
  556. raise Reject(exc, requeue=False)
  557. if throw:
  558. raise ret
  559. return ret
  560. def apply(self, args=None, kwargs=None,
  561. link=None, link_error=None,
  562. task_id=None, retries=None, throw=None,
  563. logfile=None, loglevel=None, headers=None, **options):
  564. """Execute this task locally, by blocking until the task returns.
  565. Arguments:
  566. args (Tuple): positional arguments passed on to the task.
  567. kwargs (Dict): keyword arguments passed on to the task.
  568. throw (bool): Re-raise task exceptions.
  569. Defaults to the :setting:`task_eager_propagates` setting.
  570. Returns:
  571. celery.result.EagerResult: pre-evaluated result.
  572. """
  573. # trace imports Task, so need to import inline.
  574. from celery.app.trace import build_tracer
  575. app = self._get_app()
  576. args = args or ()
  577. kwargs = kwargs or {}
  578. task_id = task_id or uuid()
  579. retries = retries or 0
  580. if throw is None:
  581. throw = app.conf.task_eager_propagates
  582. # Make sure we get the task instance, not class.
  583. task = app._tasks[self.name]
  584. request = {
  585. 'id': task_id,
  586. 'retries': retries,
  587. 'is_eager': True,
  588. 'logfile': logfile,
  589. 'loglevel': loglevel or 0,
  590. 'hostname': gethostname(),
  591. 'callbacks': maybe_list(link),
  592. 'errbacks': maybe_list(link_error),
  593. 'headers': headers,
  594. 'delivery_info': {'is_eager': True},
  595. }
  596. tb = None
  597. tracer = build_tracer(
  598. task.name, task, eager=True,
  599. propagate=throw, app=self._get_app(),
  600. )
  601. ret = tracer(task_id, args, kwargs, request)
  602. retval = ret.retval
  603. if isinstance(retval, ExceptionInfo):
  604. retval, tb = retval.exception, retval.traceback
  605. state = states.SUCCESS if ret.info is None else ret.info.state
  606. return EagerResult(task_id, retval, state, traceback=tb)
  607. def AsyncResult(self, task_id, **kwargs):
  608. """Get AsyncResult instance for this kind of task.
  609. Arguments:
  610. task_id (str): Task id to get result for.
  611. """
  612. return self._get_app().AsyncResult(task_id, backend=self.backend,
  613. task_name=self.name, **kwargs)
  614. def signature(self, args=None, *starargs, **starkwargs):
  615. """Create signature.
  616. Returns:
  617. :class:`~celery.signature`: object for
  618. this task, wrapping arguments and execution options
  619. for a single task invocation.
  620. """
  621. starkwargs.setdefault('app', self.app)
  622. return signature(self, args, *starargs, **starkwargs)
  623. subtask = signature
  624. def s(self, *args, **kwargs):
  625. """Create signature.
  626. Shortcut for ``.s(*a, **k) -> .signature(a, k)``.
  627. """
  628. return self.signature(args, kwargs)
  629. def si(self, *args, **kwargs):
  630. """Create immutable signature.
  631. Shortcut for ``.si(*a, **k) -> .signature(a, k, immutable=True)``.
  632. """
  633. return self.signature(args, kwargs, immutable=True)
  634. def chunks(self, it, n):
  635. """Create a :class:`~celery.canvas.chunks` task for this task."""
  636. from celery import chunks
  637. return chunks(self.s(), it, n, app=self.app)
  638. def map(self, it):
  639. """Create a :class:`~celery.canvas.xmap` task from ``it``."""
  640. from celery import xmap
  641. return xmap(self.s(), it, app=self.app)
  642. def starmap(self, it):
  643. """Create a :class:`~celery.canvas.xstarmap` task from ``it``."""
  644. from celery import xstarmap
  645. return xstarmap(self.s(), it, app=self.app)
  646. def send_event(self, type_, retry=True, retry_policy=None, **fields):
  647. """Send monitoring event message.
  648. This can be used to add custom event types in :pypi:`Flower`
  649. and other monitors.
  650. Arguments:
  651. type_ (str): Type of event, e.g. ``"task-failed"``.
  652. Keyword Arguments:
  653. retry (bool): Retry sending the message
  654. if the connection is lost. Default is taken from the
  655. :setting:`task_publish_retry` setting.
  656. retry_policy (Mapping): Retry settings. Default is taken
  657. from the :setting:`task_publish_retry_policy` setting.
  658. **fields (Any): Map containing information about the event.
  659. Must be JSON serializable.
  660. """
  661. req = self.request
  662. if retry_policy is None:
  663. retry_policy = self.app.conf.task_publish_retry_policy
  664. with self.app.events.default_dispatcher(hostname=req.hostname) as d:
  665. return d.send(
  666. type_,
  667. uuid=req.id, retry=retry, retry_policy=retry_policy, **fields)
  668. def replace(self, sig):
  669. """Replace this task, with a new task inheriting the task id.
  670. .. versionadded:: 4.0
  671. Arguments:
  672. sig (~@Signature): signature to replace with.
  673. Raises:
  674. ~@Ignore: This is always raised, so the best practice
  675. is to always use ``raise self.replace(...)`` to convey
  676. to the reader that the task won't continue after being replaced.
  677. """
  678. chord = self.request.chord
  679. if 'chord' in sig.options:
  680. raise ImproperlyConfigured(
  681. "A signature replacing a task must not be part of a chord"
  682. )
  683. if isinstance(sig, group):
  684. sig |= self.app.tasks['celery.accumulate'].s(index=0).set(
  685. link=self.request.callbacks,
  686. link_error=self.request.errbacks,
  687. )
  688. if self.request.chain:
  689. for t in reversed(self.request.chain):
  690. sig |= signature(t, app=self.app)
  691. sig.set(
  692. chord=chord,
  693. group_id=self.request.group,
  694. root_id=self.request.root_id,
  695. )
  696. sig.freeze(self.request.id)
  697. sig.delay()
  698. raise Ignore('Replaced by new task')
  699. def add_to_chord(self, sig, lazy=False):
  700. """Add signature to the chord the current task is a member of.
  701. .. versionadded:: 4.0
  702. Currently only supported by the Redis result backend.
  703. Arguments:
  704. sig (~@Signature): Signature to extend chord with.
  705. lazy (bool): If enabled the new task won't actually be called,
  706. and ``sig.delay()`` must be called manually.
  707. """
  708. if not self.request.chord:
  709. raise ValueError('Current task is not member of any chord')
  710. sig.set(
  711. group_id=self.request.group,
  712. chord=self.request.chord,
  713. root_id=self.request.root_id,
  714. )
  715. result = sig.freeze()
  716. self.backend.add_to_chord(self.request.group, result)
  717. return sig.delay() if not lazy else sig
  718. def update_state(self, task_id=None, state=None, meta=None):
  719. """Update task state.
  720. Arguments:
  721. task_id (str): Id of the task to update.
  722. Defaults to the id of the current task.
  723. state (str): New state.
  724. meta (Dict): State meta-data.
  725. """
  726. if task_id is None:
  727. task_id = self.request.id
  728. self.backend.store_result(task_id, meta, state)
  729. def on_success(self, retval, task_id, args, kwargs):
  730. """Success handler.
  731. Run by the worker if the task executes successfully.
  732. Arguments:
  733. retval (Any): The return value of the task.
  734. task_id (str): Unique id of the executed task.
  735. args (Tuple): Original arguments for the executed task.
  736. kwargs (Dict): Original keyword arguments for the executed task.
  737. Returns:
  738. None: The return value of this handler is ignored.
  739. """
  740. def on_retry(self, exc, task_id, args, kwargs, einfo):
  741. """Retry handler.
  742. This is run by the worker when the task is to be retried.
  743. Arguments:
  744. exc (Exception): The exception sent to :meth:`retry`.
  745. task_id (str): Unique id of the retried task.
  746. args (Tuple): Original arguments for the retried task.
  747. kwargs (Dict): Original keyword arguments for the retried task.
  748. einfo (~billiard.einfo.ExceptionInfo): Exception information.
  749. Returns:
  750. None: The return value of this handler is ignored.
  751. """
  752. def on_failure(self, exc, task_id, args, kwargs, einfo):
  753. """Error handler.
  754. This is run by the worker when the task fails.
  755. Arguments:
  756. exc (Exception): The exception raised by the task.
  757. task_id (str): Unique id of the failed task.
  758. args (Tuple): Original arguments for the task that failed.
  759. kwargs (Dict): Original keyword arguments for the task that failed.
  760. einfo (~billiard.einfo.ExceptionInfo): Exception information.
  761. Returns:
  762. None: The return value of this handler is ignored.
  763. """
  764. def after_return(self, status, retval, task_id, args, kwargs, einfo):
  765. """Handler called after the task returns.
  766. Arguments:
  767. status (str): Current task state.
  768. retval (Any): Task return value/exception.
  769. task_id (str): Unique id of the task.
  770. args (Tuple): Original arguments for the task.
  771. kwargs (Dict): Original keyword arguments for the task.
  772. einfo (~billiard.einfo.ExceptionInfo): Exception information.
  773. Returns:
  774. None: The return value of this handler is ignored.
  775. """
  776. def add_trail(self, result):
  777. if self.trail:
  778. self.request.children.append(result)
  779. return result
  780. def push_request(self, *args, **kwargs):
  781. self.request_stack.push(Context(*args, **kwargs))
  782. def pop_request(self):
  783. self.request_stack.pop()
  784. def __repr__(self):
  785. """``repr(task)``."""
  786. return _reprtask(self, R_INSTANCE)
  787. def _get_request(self):
  788. """Get current request object."""
  789. req = self.request_stack.top
  790. if req is None:
  791. # task was not called, but some may still expect a request
  792. # to be there, perhaps that should be deprecated.
  793. if self._default_request is None:
  794. self._default_request = Context()
  795. return self._default_request
  796. return req
  797. request = property(_get_request)
  798. def _get_exec_options(self):
  799. if self._exec_options is None:
  800. self._exec_options = extract_exec_options(self)
  801. return self._exec_options
  802. @property
  803. def backend(self):
  804. backend = self._backend
  805. if backend is None:
  806. return self.app.backend
  807. return backend
  808. @backend.setter
  809. def backend(self, value): # noqa
  810. self._backend = value
  811. @property
  812. def __name__(self):
  813. return self.__class__.__name__
  814. BaseTask = Task # noqa: E305 XXX compat alias