task.py 34 KB

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