task.py 34 KB

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