task.py 31 KB

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