task.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. #: Default task expiry time.
  251. expires = None
  252. #: Some may expect a request to exist even if the task has not been
  253. #: called. This should probably be deprecated.
  254. _default_request = None
  255. _exec_options = None
  256. __bound__ = False
  257. from_config = (
  258. ('send_error_emails', 'CELERY_SEND_TASK_ERROR_EMAILS'),
  259. ('serializer', 'CELERY_TASK_SERIALIZER'),
  260. ('rate_limit', 'CELERY_DEFAULT_RATE_LIMIT'),
  261. ('track_started', 'CELERY_TRACK_STARTED'),
  262. ('acks_late', 'CELERY_ACKS_LATE'),
  263. ('ignore_result', 'CELERY_IGNORE_RESULT'),
  264. ('store_errors_even_if_ignored',
  265. 'CELERY_STORE_ERRORS_EVEN_IF_IGNORED'),
  266. )
  267. __bound__ = False
  268. # - Tasks are lazily bound, so that configuration is not set
  269. # - until the task is actually used
  270. @classmethod
  271. def bind(self, app):
  272. was_bound, self.__bound__ = self.__bound__, True
  273. self._app = app
  274. conf = app.conf
  275. self._exec_options = None # clear option cache
  276. for attr_name, config_name in self.from_config:
  277. if getattr(self, attr_name, None) is None:
  278. setattr(self, attr_name, conf[config_name])
  279. if self.accept_magic_kwargs is None:
  280. self.accept_magic_kwargs = app.accept_magic_kwargs
  281. self.backend = app.backend
  282. # decorate with annotations from config.
  283. if not was_bound:
  284. self.annotate()
  285. from celery.utils.threads import LocalStack
  286. self.request_stack = LocalStack()
  287. # PeriodicTask uses this to add itself to the PeriodicTask schedule.
  288. self.on_bound(app)
  289. return app
  290. @classmethod
  291. def on_bound(self, app):
  292. """This method can be defined to do additional actions when the
  293. task class is bound to an app."""
  294. pass
  295. @classmethod
  296. def _get_app(self):
  297. if self._app is None:
  298. self._app = current_app
  299. if not self.__bound__:
  300. # The app property's __set__ method is not called
  301. # if Task.app is set (on the class), so must bind on use.
  302. self.bind(self._app)
  303. return self._app
  304. app = class_property(_get_app, bind)
  305. @classmethod
  306. def annotate(self):
  307. for d in resolve_all_annotations(self.app.annotations, self):
  308. for key, value in items(d):
  309. if key.startswith('@'):
  310. self.add_around(key[1:], value)
  311. else:
  312. setattr(self, key, value)
  313. @classmethod
  314. def add_around(self, attr, around):
  315. orig = getattr(self, attr)
  316. if getattr(orig, '__wrapped__', None):
  317. orig = orig.__wrapped__
  318. meth = around(orig)
  319. meth.__wrapped__ = orig
  320. setattr(self, attr, meth)
  321. def __call__(self, *args, **kwargs):
  322. _task_stack.push(self)
  323. self.push_request()
  324. try:
  325. # add self if this is a bound task
  326. if self.__self__ is not None:
  327. return self.run(self.__self__, *args, **kwargs)
  328. return self.run(*args, **kwargs)
  329. finally:
  330. self.pop_request()
  331. _task_stack.pop()
  332. def __reduce__(self):
  333. # - tasks are pickled into the name of the task only, and the reciever
  334. # - simply grabs it from the local registry.
  335. # - in later versions the module of the task is also included,
  336. # - and the receiving side tries to import that module so that
  337. # - it will work even if the task has not been registered.
  338. mod = type(self).__module__
  339. mod = mod if mod and mod in sys.modules else None
  340. return (_unpickle_task_v2, (self.name, mod), None)
  341. def run(self, *args, **kwargs):
  342. """The body of the task executed by workers."""
  343. raise NotImplementedError('Tasks must define the run method.')
  344. def start_strategy(self, app, consumer, **kwargs):
  345. return instantiate(self.Strategy, self, app, consumer, **kwargs)
  346. def delay(self, *args, **kwargs):
  347. """Star argument version of :meth:`apply_async`.
  348. Does not support the extra options enabled by :meth:`apply_async`.
  349. :param \*args: positional arguments passed on to the task.
  350. :param \*\*kwargs: keyword arguments passed on to the task.
  351. :returns :class:`celery.result.AsyncResult`:
  352. """
  353. return self.apply_async(args, kwargs)
  354. def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,
  355. link=None, link_error=None, **options):
  356. """Apply tasks asynchronously by sending a message.
  357. :keyword args: The positional arguments to pass on to the
  358. task (a :class:`list` or :class:`tuple`).
  359. :keyword kwargs: The keyword arguments to pass on to the
  360. task (a :class:`dict`)
  361. :keyword countdown: Number of seconds into the future that the
  362. task should execute. Defaults to immediate
  363. execution.
  364. :keyword eta: A :class:`~datetime.datetime` object describing
  365. the absolute time and date of when the task should
  366. be executed. May not be specified if `countdown`
  367. is also supplied.
  368. :keyword expires: Either a :class:`int`, describing the number of
  369. seconds, or a :class:`~datetime.datetime` object
  370. that describes the absolute time and date of when
  371. the task should expire. The task will not be
  372. executed after the expiration time.
  373. :keyword connection: Re-use existing broker connection instead
  374. of establishing a new one.
  375. :keyword retry: If enabled sending of the task message will be retried
  376. in the event of connection loss or failure. Default
  377. is taken from the :setting:`CELERY_TASK_PUBLISH_RETRY`
  378. setting. Note you need to handle the
  379. producer/connection manually for this to work.
  380. :keyword retry_policy: Override the retry policy used. See the
  381. :setting:`CELERY_TASK_PUBLISH_RETRY` setting.
  382. :keyword routing_key: Custom routing key used to route the task to a
  383. worker server. If in combination with a
  384. ``queue`` argument only used to specify custom
  385. routing keys to topic exchanges.
  386. :keyword queue: The queue to route the task to. This must be a key
  387. present in :setting:`CELERY_QUEUES`, or
  388. :setting:`CELERY_CREATE_MISSING_QUEUES` must be
  389. enabled. See :ref:`guide-routing` for more
  390. information.
  391. :keyword exchange: Named custom exchange to send the task to.
  392. Usually not used in combination with the ``queue``
  393. argument.
  394. :keyword priority: The task priority, a number between 0 and 9.
  395. Defaults to the :attr:`priority` attribute.
  396. :keyword serializer: A string identifying the default
  397. serialization method to use. Can be `pickle`,
  398. `json`, `yaml`, `msgpack` or any custom
  399. serialization method that has been registered
  400. with :mod:`kombu.serialization.registry`.
  401. Defaults to the :attr:`serializer` attribute.
  402. :keyword compression: A string identifying the compression method
  403. to use. Can be one of ``zlib``, ``bzip2``,
  404. or any custom compression methods registered with
  405. :func:`kombu.compression.register`. Defaults to
  406. the :setting:`CELERY_MESSAGE_COMPRESSION`
  407. setting.
  408. :keyword link: A single, or a list of tasks to apply if the
  409. task exits successfully.
  410. :keyword link_error: A single, or a list of tasks to apply
  411. if an error occurs while executing the task.
  412. :keyword producer: :class:~@amqp.TaskProducer` instance to use.
  413. :keyword add_to_parent: If set to True (default) and the task
  414. is applied while executing another task, then the result
  415. will be appended to the parent tasks ``request.children``
  416. attribute. Trailing can also be disabled by default using the
  417. :attr:`trail` attribute
  418. :keyword publisher: Deprecated alias to ``producer``.
  419. Also supports all keyword arguments supported by
  420. :meth:`kombu.Producer.publish`.
  421. .. note::
  422. If the :setting:`CELERY_ALWAYS_EAGER` setting is set, it will
  423. be replaced by a local :func:`apply` call instead.
  424. """
  425. app = self._get_app()
  426. if app.conf.CELERY_ALWAYS_EAGER:
  427. return self.apply(args, kwargs, task_id=task_id or uuid(),
  428. link=link, link_error=link_error, **options)
  429. # add 'self' if this is a "task_method".
  430. if self.__self__ is not None:
  431. args = args if isinstance(args, tuple) else tuple(args or ())
  432. args = (self.__self__, ) + args
  433. return app.send_task(
  434. self.name, args, kwargs, task_id=task_id, producer=producer,
  435. link=link, link_error=link_error, result_cls=self.AsyncResult,
  436. **dict(self._get_exec_options(), **options)
  437. )
  438. def subtask_from_request(self, request=None, args=None, kwargs=None,
  439. **extra_options):
  440. request = self.request if request is None else request
  441. args = request.args if args is None else args
  442. kwargs = request.kwargs if kwargs is None else kwargs
  443. limit_hard, limit_soft = request.timelimit or (None, None)
  444. options = dict({
  445. 'task_id': request.id,
  446. 'link': request.callbacks,
  447. 'link_error': request.errbacks,
  448. 'group_id': request.group,
  449. 'chord': request.chord,
  450. 'soft_time_limit': limit_soft,
  451. 'time_limit': limit_hard,
  452. }, **request.delivery_info or {})
  453. return self.subtask(args, kwargs, options, type=self, **extra_options)
  454. def retry(self, args=None, kwargs=None, exc=None, throw=True,
  455. eta=None, countdown=None, max_retries=None, **options):
  456. """Retry the task.
  457. :param args: Positional arguments to retry with.
  458. :param kwargs: Keyword arguments to retry with.
  459. :keyword exc: Custom exception to report when the max restart
  460. limit has been exceeded (default:
  461. :exc:`~@MaxRetriesExceededError`).
  462. If this argument is set and retry is called while
  463. an exception was raised (``sys.exc_info()`` is set)
  464. it will attempt to reraise the current exception.
  465. If no exception was raised it will raise the ``exc``
  466. argument provided.
  467. :keyword countdown: Time in seconds to delay the retry for.
  468. :keyword eta: Explicit time and date to run the retry at
  469. (must be a :class:`~datetime.datetime` instance).
  470. :keyword max_retries: If set, overrides the default retry limit.
  471. :keyword time_limit: If set, overrides the default time limit.
  472. :keyword soft_time_limit: If set, overrides the default soft
  473. time limit.
  474. :keyword \*\*options: Any extra options to pass on to
  475. meth:`apply_async`.
  476. :keyword throw: If this is :const:`False`, do not raise the
  477. :exc:`~@Retry` exception,
  478. that tells the worker to mark the task as being
  479. retried. Note that this means the task will be
  480. marked as failed if the task raises an exception,
  481. or successful if it returns.
  482. :raises celery.exceptions.Retry: To tell the worker that
  483. the task has been re-sent for retry. This always happens,
  484. unless the `throw` keyword argument has been explicitly set
  485. to :const:`False`, and is considered normal operation.
  486. **Example**
  487. .. code-block:: python
  488. >>> from imaginary_twitter_lib import Twitter
  489. >>> from proj.celery import app
  490. >>> @app.task()
  491. ... def tweet(auth, message):
  492. ... twitter = Twitter(oauth=auth)
  493. ... try:
  494. ... twitter.post_status_update(message)
  495. ... except twitter.FailWhale as exc:
  496. ... # Retry in 5 minutes.
  497. ... raise tweet.retry(countdown=60 * 5, exc=exc)
  498. Although the task will never return above as `retry` raises an
  499. exception to notify the worker, we use `raise` in front of the retry
  500. to convey that the rest of the block will not be executed.
  501. """
  502. request = self.request
  503. retries = request.retries + 1
  504. max_retries = self.max_retries if max_retries is None else max_retries
  505. # Not in worker or emulated by (apply/always_eager),
  506. # so just raise the original exception.
  507. if request.called_directly:
  508. maybe_reraise() # raise orig stack if PyErr_Occurred
  509. raise exc or Retry('Task can be retried', None)
  510. if not eta and countdown is None:
  511. countdown = self.default_retry_delay
  512. is_eager = request.is_eager
  513. S = self.subtask_from_request(
  514. request, args, kwargs,
  515. countdown=countdown, eta=eta, retries=retries,
  516. **options
  517. )
  518. if max_retries is not None and retries > max_retries:
  519. if exc:
  520. maybe_reraise()
  521. raise self.MaxRetriesExceededError(
  522. "Can't retry {0}[{1}] args:{2} kwargs:{3}".format(
  523. self.name, request.id, S.args, S.kwargs))
  524. # If task was executed eagerly using apply(),
  525. # then the retry must also be executed eagerly.
  526. try:
  527. S.apply().get() if is_eager else S.apply_async()
  528. except Exception as exc:
  529. if is_eager:
  530. raise
  531. raise Reject(exc, requeue=True)
  532. ret = Retry(exc=exc, when=eta or countdown)
  533. if throw:
  534. raise ret
  535. return ret
  536. def replace(self, sig):
  537. request = self.request
  538. sig.set_immutable(True)
  539. chord_id, request.chord = request.chord, None
  540. group_id, request.group = request.group, None
  541. callbacks, request.callbacks = request.callbacks, [sig]
  542. if group_id or chord_id:
  543. sig.set(group=group_id, chord=chord_id)
  544. sig |= callbacks[0]
  545. return sig
  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. 'delivery_info': {'is_eager': True}}
  578. if self.accept_magic_kwargs:
  579. default_kwargs = {'task_name': task.name,
  580. 'task_id': task_id,
  581. 'task_retries': retries,
  582. 'task_is_eager': True,
  583. 'logfile': options.get('logfile'),
  584. 'loglevel': options.get('loglevel', 0),
  585. 'delivery_info': {'is_eager': True}}
  586. supported_keys = fun_takes_kwargs(task.run, default_kwargs)
  587. extend_with = dict((key, val)
  588. for key, val in items(default_kwargs)
  589. if key in supported_keys)
  590. kwargs.update(extend_with)
  591. tb = None
  592. retval, info = eager_trace_task(task, task_id, args, kwargs,
  593. app=self._get_app(),
  594. request=request, propagate=throw)
  595. if isinstance(retval, ExceptionInfo):
  596. retval, tb = retval.exception, retval.traceback
  597. state = states.SUCCESS if info is None else info.state
  598. return EagerResult(task_id, retval, state, traceback=tb)
  599. def AsyncResult(self, task_id, **kwargs):
  600. """Get AsyncResult instance for this kind of task.
  601. :param task_id: Task id to get result for.
  602. """
  603. return self._get_app().AsyncResult(task_id, backend=self.backend,
  604. task_name=self.name, **kwargs)
  605. def subtask(self, args=None, *starargs, **starkwargs):
  606. """Return :class:`~celery.signature` object for
  607. this task, wrapping arguments and execution options
  608. for a single task invocation."""
  609. starkwargs.setdefault('app', self.app)
  610. return signature(self, args, *starargs, **starkwargs)
  611. def s(self, *args, **kwargs):
  612. """``.s(*a, **k) -> .subtask(a, k)``"""
  613. return self.subtask(args, kwargs)
  614. def si(self, *args, **kwargs):
  615. """``.si(*a, **k) -> .subtask(a, k, immutable=True)``"""
  616. return self.subtask(args, kwargs, immutable=True)
  617. def chunks(self, it, n):
  618. """Creates a :class:`~celery.canvas.chunks` task for this task."""
  619. from celery import chunks
  620. return chunks(self.s(), it, n, app=self.app)
  621. def map(self, it):
  622. """Creates a :class:`~celery.canvas.xmap` task from ``it``."""
  623. from celery import xmap
  624. return xmap(self.s(), it, app=self.app)
  625. def starmap(self, it):
  626. """Creates a :class:`~celery.canvas.xstarmap` task from ``it``."""
  627. from celery import xstarmap
  628. return xstarmap(self.s(), it, app=self.app)
  629. def update_state(self, task_id=None, state=None, meta=None):
  630. """Update task state.
  631. :keyword task_id: Id of the task to update, defaults to the
  632. id of the current task
  633. :keyword state: New state (:class:`str`).
  634. :keyword meta: State metadata (:class:`dict`).
  635. """
  636. if task_id is None:
  637. task_id = self.request.id
  638. self.backend.store_result(task_id, meta, state)
  639. def on_success(self, retval, task_id, args, kwargs):
  640. """Success handler.
  641. Run by the worker if the task executes successfully.
  642. :param retval: The return value of the task.
  643. :param task_id: Unique id of the executed task.
  644. :param args: Original arguments for the executed task.
  645. :param kwargs: Original keyword arguments for the executed task.
  646. The return value of this handler is ignored.
  647. """
  648. pass
  649. def on_retry(self, exc, task_id, args, kwargs, einfo):
  650. """Retry handler.
  651. This is run by the worker when the task is to be retried.
  652. :param exc: The exception sent to :meth:`retry`.
  653. :param task_id: Unique id of the retried task.
  654. :param args: Original arguments for the retried task.
  655. :param kwargs: Original keyword arguments for the retried task.
  656. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  657. instance, containing the traceback.
  658. The return value of this handler is ignored.
  659. """
  660. pass
  661. def on_failure(self, exc, task_id, args, kwargs, einfo):
  662. """Error handler.
  663. This is run by the worker when the task fails.
  664. :param exc: The exception raised by the task.
  665. :param task_id: Unique id of the failed task.
  666. :param args: Original arguments for the task that failed.
  667. :param kwargs: Original keyword arguments for the task
  668. that failed.
  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 after_return(self, status, retval, task_id, args, kwargs, einfo):
  675. """Handler called after the task returns.
  676. :param status: Current task state.
  677. :param retval: Task return value/exception.
  678. :param task_id: Unique id of the 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 (if any).
  684. The return value of this handler is ignored.
  685. """
  686. pass
  687. def send_error_email(self, context, exc, **kwargs):
  688. if self.send_error_emails and \
  689. not getattr(self, 'disable_error_emails', None):
  690. self.ErrorMail(self, **kwargs).send(context, exc)
  691. def add_trail(self, result):
  692. if self.trail:
  693. self.request.children.append(result)
  694. return result
  695. def push_request(self, *args, **kwargs):
  696. self.request_stack.push(Context(*args, **kwargs))
  697. def pop_request(self):
  698. self.request_stack.pop()
  699. def __repr__(self):
  700. """`repr(task)`"""
  701. return _reprtask(self, R_SELF_TASK if self.__self__ else R_INSTANCE)
  702. def _get_request(self):
  703. """Get current request object."""
  704. req = self.request_stack.top
  705. if req is None:
  706. # task was not called, but some may still expect a request
  707. # to be there, perhaps that should be deprecated.
  708. if self._default_request is None:
  709. self._default_request = Context()
  710. return self._default_request
  711. return req
  712. request = property(_get_request)
  713. def _get_exec_options(self):
  714. if self._exec_options is None:
  715. self._exec_options = extract_exec_options(self)
  716. return self._exec_options
  717. @property
  718. def __name__(self):
  719. return self.__class__.__name__
  720. BaseTask = Task # compat alias