task.py 31 KB

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