result.py 16 KB

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