task.py 31 KB

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