task.py 31 KB

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