result.py 16 KB

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