task.py 32 KB

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