result.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.result
  4. ~~~~~~~~~~~~~
  5. Task results/state and groups of results.
  6. :copyright: (c) 2009 - 2012 by Ask Solem.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from __future__ import absolute_import
  10. from __future__ import with_statement
  11. import time
  12. from copy import copy
  13. from itertools import imap
  14. from . import current_app
  15. from . import states
  16. from .app import app_or_default
  17. from .exceptions import TimeoutError
  18. from .registry import _unpickle_task
  19. from .utils.compat import OrderedDict
  20. def _unpickle_result(task_id, task_name):
  21. return _unpickle_task(task_name).AsyncResult(task_id)
  22. class AsyncResult(object):
  23. """Query task state.
  24. :param task_id: see :attr:`task_id`.
  25. :keyword backend: see :attr:`backend`.
  26. """
  27. #: Error raised for timeouts.
  28. TimeoutError = TimeoutError
  29. #: The task uuid.
  30. task_id = None
  31. #: The task result backend to use.
  32. backend = None
  33. def __init__(self, task_id, backend=None, task_name=None, app=None):
  34. self.app = app_or_default(app)
  35. self.task_id = task_id
  36. self.backend = backend or self.app.backend
  37. self.task_name = task_name
  38. def forget(self):
  39. """Forget about (and possibly remove the result of) this task."""
  40. self.backend.forget(self.task_id)
  41. def revoke(self, connection=None, connect_timeout=None):
  42. """Send revoke signal to all workers.
  43. Any worker receiving the task, or having reserved the
  44. task, *must* ignore it.
  45. """
  46. self.app.control.revoke(self.task_id, connection=connection,
  47. connect_timeout=connect_timeout)
  48. def get(self, timeout=None, propagate=True, interval=0.5):
  49. """Wait until task is ready, and return its result.
  50. .. warning::
  51. Waiting for tasks within a task may lead to deadlocks.
  52. Please read :ref:`task-synchronous-subtasks`.
  53. :keyword timeout: How long to wait, in seconds, before the
  54. operation times out.
  55. :keyword propagate: Re-raise exception if the task failed.
  56. :keyword interval: Time to wait (in seconds) before retrying to
  57. retrieve the result. Note that this does not have any effect
  58. when using the AMQP result store backend, as it does not
  59. use polling.
  60. :raises celery.exceptions.TimeoutError: if `timeout` is not
  61. :const:`None` and the result does not arrive within `timeout`
  62. seconds.
  63. If the remote call raised an exception then that exception will
  64. be re-raised.
  65. """
  66. return self.backend.wait_for(self.task_id, timeout=timeout,
  67. propagate=propagate,
  68. interval=interval)
  69. wait = get # deprecated alias to :meth:`get`.
  70. def ready(self):
  71. """Returns :const:`True` if the task has been executed.
  72. If the task is still running, pending, or is waiting
  73. for retry then :const:`False` is returned.
  74. """
  75. return self.state in self.backend.READY_STATES
  76. def successful(self):
  77. """Returns :const:`True` if the task executed successfully."""
  78. return self.state == states.SUCCESS
  79. def failed(self):
  80. """Returns :const:`True` if the task failed."""
  81. return self.state == states.FAILURE
  82. def __str__(self):
  83. """`str(self) -> self.task_id`"""
  84. return self.task_id
  85. def __hash__(self):
  86. """`hash(self) -> hash(self.task_id)`"""
  87. return hash(self.task_id)
  88. def __repr__(self):
  89. return "<AsyncResult: %s>" % self.task_id
  90. def __eq__(self, other):
  91. if isinstance(other, self.__class__):
  92. return self.task_id == other.task_id
  93. return other == self.task_id
  94. def __copy__(self):
  95. return self.__class__(self.task_id, backend=self.backend)
  96. def __reduce__(self):
  97. if self.task_name:
  98. return (_unpickle_result, (self.task_id, self.task_name))
  99. else:
  100. return (self.__class__, (self.task_id, self.backend,
  101. None, self.app))
  102. @property
  103. def result(self):
  104. """When the task has been executed, this contains the return value.
  105. If the task raised an exception, this will be the exception
  106. instance."""
  107. return self.backend.get_result(self.task_id)
  108. info = result
  109. @property
  110. def traceback(self):
  111. """Get the traceback of a failed task."""
  112. return self.backend.get_traceback(self.task_id)
  113. @property
  114. def state(self):
  115. """The tasks current state.
  116. Possible values includes:
  117. *PENDING*
  118. The task is waiting for execution.
  119. *STARTED*
  120. The task has been started.
  121. *RETRY*
  122. The task is to be retried, possibly because of failure.
  123. *FAILURE*
  124. The task raised an exception, or has exceeded the retry limit.
  125. The :attr:`result` attribute then contains the
  126. exception raised by the task.
  127. *SUCCESS*
  128. The task executed successfully. The :attr:`result` attribute
  129. then contains the tasks return value.
  130. """
  131. return self.backend.get_status(self.task_id)
  132. status = state
  133. BaseAsyncResult = AsyncResult # for backwards compatibility.
  134. class ResultSet(object):
  135. """Working with more than one result.
  136. :param results: List of result instances.
  137. """
  138. #: List of results in in the set.
  139. results = None
  140. def __init__(self, results, app=None, **kwargs):
  141. self.app = app_or_default(app)
  142. self.results = results
  143. def add(self, result):
  144. """Add :class:`AsyncResult` as a new member of the set.
  145. Does nothing if the result is already a member.
  146. """
  147. if result not in self.results:
  148. self.results.append(result)
  149. def remove(self, result):
  150. """Removes result from the set; it must be a member.
  151. :raises KeyError: if the result is not a member.
  152. """
  153. if isinstance(result, basestring):
  154. result = AsyncResult(result)
  155. try:
  156. self.results.remove(result)
  157. except ValueError:
  158. raise KeyError(result)
  159. def discard(self, result):
  160. """Remove result from the set if it is a member.
  161. If it is not a member, do nothing.
  162. """
  163. try:
  164. self.remove(result)
  165. except KeyError:
  166. pass
  167. def update(self, results):
  168. """Update set with the union of itself and an iterable with
  169. results."""
  170. self.results.extend(r for r in results if r not in self.results)
  171. def clear(self):
  172. """Remove all results from this set."""
  173. self.results[:] = [] # don't create new list.
  174. def successful(self):
  175. """Was all of the tasks successful?
  176. :returns: :const:`True` if all of the tasks finished
  177. successfully (i.e. did not raise an exception).
  178. """
  179. return all(result.successful() for result in self.results)
  180. def failed(self):
  181. """Did any of the tasks fail?
  182. :returns: :const:`True` if any of the tasks failed.
  183. (i.e., raised an exception)
  184. """
  185. return any(result.failed() for result in self.results)
  186. def waiting(self):
  187. """Are any of the tasks incomplete?
  188. :returns: :const:`True` if any of the tasks is still
  189. waiting for execution.
  190. """
  191. return any(not result.ready() for result in self.results)
  192. def ready(self):
  193. """Did all of the tasks complete? (either by success of failure).
  194. :returns: :const:`True` if all of the tasks been
  195. executed.
  196. """
  197. return all(result.ready() for result in self.results)
  198. def completed_count(self):
  199. """Task completion count.
  200. :returns: the number of tasks completed.
  201. """
  202. return sum(imap(int, (result.successful() for result in self.results)))
  203. def forget(self):
  204. """Forget about (and possible remove the result of) all the tasks."""
  205. for result in self.results:
  206. result.forget()
  207. def revoke(self, connection=None, connect_timeout=None):
  208. """Revoke all tasks in the set."""
  209. with self.app.default_connection(connection, connect_timeout) as conn:
  210. for result in self.results:
  211. result.revoke(connection=conn)
  212. def __iter__(self):
  213. return self.iterate()
  214. def __getitem__(self, index):
  215. """`res[i] -> res.results[i]`"""
  216. return self.results[index]
  217. def iterate(self, timeout=None, propagate=True, interval=0.5):
  218. """Iterate over the return values of the tasks as they finish
  219. one by one.
  220. :raises: The exception if any of the tasks raised an exception.
  221. """
  222. elapsed = 0.0
  223. results = OrderedDict((result.task_id, copy(result))
  224. for result in self.results)
  225. while results:
  226. removed = set()
  227. for task_id, result in results.iteritems():
  228. if result.ready():
  229. yield result.get(timeout=timeout and timeout - elapsed,
  230. propagate=propagate)
  231. removed.add(task_id)
  232. else:
  233. if result.backend.subpolling_interval:
  234. time.sleep(result.backend.subpolling_interval)
  235. for task_id in removed:
  236. results.pop(task_id, None)
  237. time.sleep(interval)
  238. elapsed += interval
  239. if timeout and elapsed >= timeout:
  240. raise TimeoutError("The operation timed out")
  241. def join(self, timeout=None, propagate=True, interval=0.5):
  242. """Gathers the results of all tasks as a list in order.
  243. .. note::
  244. This can be an expensive operation for result store
  245. backends that must resort to polling (e.g. database).
  246. You should consider using :meth:`join_native` if your backend
  247. supports it.
  248. .. warning::
  249. Waiting for tasks within a task may lead to deadlocks.
  250. Please see :ref:`task-synchronous-subtasks`.
  251. :keyword timeout: The number of seconds to wait for results before
  252. the operation times out.
  253. :keyword propagate: If any of the tasks raises an exception, the
  254. exception will be re-raised.
  255. :keyword interval: Time to wait (in seconds) before retrying to
  256. retrieve a result from the set. Note that this
  257. does not have any effect when using the AMQP
  258. result store backend, as it does not use polling.
  259. :raises celery.exceptions.TimeoutError: if `timeout` is not
  260. :const:`None` and the operation takes longer than `timeout`
  261. seconds.
  262. """
  263. time_start = time.time()
  264. remaining = None
  265. results = []
  266. for result in self.results:
  267. remaining = None
  268. if timeout:
  269. remaining = timeout - (time.time() - time_start)
  270. if remaining <= 0.0:
  271. raise TimeoutError("join operation timed out")
  272. results.append(result.wait(timeout=remaining,
  273. propagate=propagate,
  274. interval=interval))
  275. return results
  276. def iter_native(self, timeout=None, interval=None):
  277. """Backend optimized version of :meth:`iterate`.
  278. .. versionadded:: 2.2
  279. Note that this does not support collecting the results
  280. for different task types using different backends.
  281. This is currently only supported by the AMQP, Redis and cache
  282. result backends.
  283. """
  284. backend = self.results[0].backend
  285. ids = [result.task_id for result in self.results]
  286. return backend.get_many(ids, timeout=timeout, interval=interval)
  287. def join_native(self, timeout=None, propagate=True, interval=0.5):
  288. """Backend optimized version of :meth:`join`.
  289. .. versionadded:: 2.2
  290. Note that this does not support collecting the results
  291. for different task types using different backends.
  292. This is currently only supported by the AMQP, Redis and cache
  293. result backends.
  294. """
  295. results = self.results
  296. acc = [None for _ in xrange(len(self))]
  297. for task_id, meta in self.iter_native(timeout=timeout,
  298. interval=interval):
  299. acc[results.index(task_id)] = meta["result"]
  300. return acc
  301. def __len__(self):
  302. return len(self.results)
  303. @property
  304. def total(self):
  305. """Deprecated: Use ``len(r)``."""
  306. return len(self)
  307. @property
  308. def subtasks(self):
  309. """Deprecated alias to :attr:`results`."""
  310. return self.results
  311. @property
  312. def supports_native_join(self):
  313. return self.results[0].backend.supports_native_join
  314. class TaskSetResult(ResultSet):
  315. """An instance of this class is returned by
  316. `TaskSet`'s :meth:`~celery.task.TaskSet.apply_async` method.
  317. It enables inspection of the tasks state and return values as
  318. a single entity.
  319. :param taskset_id: The id of the taskset.
  320. :param results: List of result instances.
  321. """
  322. #: The UUID of the taskset.
  323. taskset_id = None
  324. #: List/iterator of results in the taskset
  325. results = None
  326. def __init__(self, taskset_id, results=None, **kwargs):
  327. self.taskset_id = taskset_id
  328. # XXX previously the "results" arg was named "subtasks".
  329. if "subtasks" in kwargs:
  330. results = kwargs["subtasks"]
  331. super(TaskSetResult, self).__init__(results, **kwargs)
  332. def save(self, backend=None):
  333. """Save taskset result for later retrieval using :meth:`restore`.
  334. Example::
  335. >>> result.save()
  336. >>> result = TaskSetResult.restore(taskset_id)
  337. """
  338. return (backend or self.app.backend).save_taskset(self.taskset_id,
  339. self)
  340. def delete(self, backend=None):
  341. """Remove this result if it was previously saved."""
  342. (backend or self.app.backend).delete_taskset(self.taskset_id)
  343. def itersubtasks(self):
  344. """Depreacted. Use ``iter(self.results)`` instead."""
  345. return iter(self.results)
  346. def __reduce__(self):
  347. return (self.__class__, (self.taskset_id, self.results))
  348. @classmethod
  349. def restore(self, taskset_id, backend=None):
  350. """Restore previously saved taskset result."""
  351. return (backend or current_app.backend).restore_taskset(taskset_id)
  352. class EagerResult(AsyncResult):
  353. """Result that we know has already been executed."""
  354. def __init__(self, task_id, ret_value, state, traceback=None):
  355. self.task_id = task_id
  356. self._result = ret_value
  357. self._state = state
  358. self._traceback = traceback
  359. def __reduce__(self):
  360. return (self.__class__, (self.task_id, self._result,
  361. self._state, self._traceback))
  362. def __copy__(self):
  363. cls, args = self.__reduce__()
  364. return cls(*args)
  365. def ready(self):
  366. return True
  367. def get(self, timeout=None, propagate=True, **kwargs):
  368. if self.successful():
  369. return self.result
  370. elif self.state in states.PROPAGATE_STATES:
  371. if propagate:
  372. raise self.result
  373. return self.result
  374. wait = get
  375. def forget(self):
  376. pass
  377. def revoke(self):
  378. self._state = states.REVOKED
  379. def __repr__(self):
  380. return "<EagerResult: %s>" % self.task_id
  381. @property
  382. def result(self):
  383. """The tasks return value"""
  384. return self._result
  385. @property
  386. def state(self):
  387. """The tasks state."""
  388. return self._state
  389. status = state
  390. @property
  391. def traceback(self):
  392. """The traceback if the task failed."""
  393. return self._traceback