task.py 31 KB

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