task.py 34 KB

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