result.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. """
  2. Asynchronous result types.
  3. """
  4. import time
  5. from itertools import imap
  6. from celery.utils import any, all
  7. from celery.backends import default_backend
  8. from celery.exceptions import TimeoutError
  9. from celery.datastructures import PositionQueue
  10. class BaseAsyncResult(object):
  11. """Base class for pending result, supports custom
  12. task meta :attr:`backend`
  13. :param task_id: see :attr:`task_id`.
  14. :param backend: see :attr:`backend`.
  15. .. attribute:: task_id
  16. The unique identifier for this task.
  17. .. attribute:: backend
  18. The task result backend used.
  19. """
  20. TimeoutError = TimeoutError
  21. def __init__(self, task_id, backend):
  22. self.task_id = task_id
  23. self.backend = backend
  24. def get(self):
  25. """Alias to :meth:`wait`."""
  26. return self.wait()
  27. def wait(self, timeout=None):
  28. """Wait for task, and return the result when it arrives.
  29. :keyword timeout: How long to wait in seconds, before the
  30. operation times out.
  31. :raises celery.exceptions.TimeoutError: if ``timeout`` is not ``None``
  32. and the result does not arrive within ``timeout`` seconds.
  33. If the remote call raised an exception then that
  34. exception will be re-raised.
  35. """
  36. return self.backend.wait_for(self.task_id, timeout=timeout)
  37. def ready(self):
  38. """Returns ``True`` if the task executed successfully, or raised
  39. an exception. If the task is still pending, or is waiting for retry
  40. then ``False`` is returned.
  41. :rtype: bool
  42. """
  43. status = self.backend.get_status(self.task_id)
  44. return status not in ["PENDING", "RETRY"]
  45. def successful(self):
  46. """Returns ``True`` if the task executed successfully.
  47. :rtype: bool
  48. """
  49. return self.backend.is_successful(self.task_id)
  50. def __str__(self):
  51. """``str(self)`` -> ``self.task_id``"""
  52. return self.task_id
  53. def __repr__(self):
  54. return "<AsyncResult: %s>" % self.task_id
  55. @property
  56. def result(self):
  57. """When the task has been executed, this contains the return value.
  58. If the task raised an exception, this will be the exception instance.
  59. """
  60. if self.status == "SUCCESS" or self.status == "FAILURE":
  61. return self.backend.get_result(self.task_id)
  62. return None
  63. @property
  64. def traceback(self):
  65. """Get the traceback of a failed task."""
  66. return self.backend.get_traceback(self.task_id)
  67. @property
  68. def status(self):
  69. """The current status of the task.
  70. Can be one of the following:
  71. *PENDING*
  72. The task is waiting for execution.
  73. *RETRY*
  74. The task is to be retried, possibly because of failure.
  75. *FAILURE*
  76. The task raised an exception, or has been retried more times
  77. than its limit. The :attr:`result` attribute contains the
  78. exception raised.
  79. *SUCCESS*
  80. The task executed successfully. The :attr:`result` attribute
  81. contains the resulting value.
  82. """
  83. return self.backend.get_status(self.task_id)
  84. class AsyncResult(BaseAsyncResult):
  85. """Pending task result using the default backend.
  86. :param task_id: see :attr:`task_id`.
  87. .. attribute:: task_id
  88. The unique identifier for this task.
  89. .. attribute:: backend
  90. Instance of :class:`celery.backends.DefaultBackend`.
  91. """
  92. def __init__(self, task_id):
  93. super(AsyncResult, self).__init__(task_id, backend=default_backend)
  94. class TaskSetResult(object):
  95. """Working with :class:`celery.task.TaskSet` results.
  96. An instance of this class is returned by
  97. :meth:`celery.task.TaskSet.run()`. It lets you inspect the status and
  98. return values of the taskset as a single entity.
  99. :option taskset_id: see :attr:`taskset_id`.
  100. :option subtasks: see :attr:`subtasks`.
  101. .. attribute:: taskset_id
  102. The UUID of the taskset itself.
  103. .. attribute:: subtasks
  104. A list of :class:`AsyncResult` instances for all of the subtasks.
  105. """
  106. def __init__(self, taskset_id, subtasks):
  107. self.taskset_id = taskset_id
  108. self.subtasks = subtasks
  109. def itersubtasks(self):
  110. """Taskset subtask iterator.
  111. :returns: an iterator for iterating over the tasksets
  112. :class:`AsyncResult` objects.
  113. """
  114. return (subtask for subtask in self.subtasks)
  115. def successful(self):
  116. """Was the taskset successful?
  117. :returns: ``True`` if all of the tasks in the taskset finished
  118. successfully (i.e. did not raise an exception).
  119. """
  120. return all((subtask.successful()
  121. for subtask in self.itersubtasks()))
  122. def failed(self):
  123. """Did the taskset fail?
  124. :returns: ``True`` if any of the tasks in the taskset failed.
  125. (i.e., raised an exception)
  126. """
  127. return any((not subtask.successful()
  128. for subtask in self.itersubtasks()))
  129. def waiting(self):
  130. """Is the taskset waiting?
  131. :returns: ``True`` if any of the tasks in the taskset is still
  132. waiting for execution.
  133. """
  134. return any((not subtask.ready()
  135. for subtask in self.itersubtasks()))
  136. def ready(self):
  137. """Is the task ready?
  138. :returns: ``True`` if all of the tasks in the taskset has been
  139. executed.
  140. """
  141. return all((subtask.ready()
  142. for subtask in self.itersubtasks()))
  143. def completed_count(self):
  144. """Task completion count.
  145. :returns: the number of tasks completed.
  146. """
  147. return sum(imap(int, (subtask.successful()
  148. for subtask in self.itersubtasks())))
  149. def __iter__(self):
  150. """``iter(res)`` -> ``res.iterate()``."""
  151. return self.iterate()
  152. def iterate(self):
  153. """Iterate over the return values of the tasks as they finish
  154. one by one.
  155. :raises: The exception if any of the tasks raised an exception.
  156. """
  157. results = dict((subtask.task_id, AsyncResult(subtask.task_id))
  158. for subtask in self.subtasks)
  159. while results:
  160. for task_id, pending_result in results.items():
  161. if pending_result.status == "SUCCESS":
  162. del(results[task_id])
  163. yield pending_result.result
  164. elif pending_result.status == "FAILURE":
  165. raise pending_result.result
  166. def join(self, timeout=None):
  167. """Gather the results for all of the tasks in the taskset,
  168. and return a list with them ordered by the order of which they
  169. were called.
  170. :keyword timeout: The time in seconds, how long
  171. it will wait for results, before the operation times out.
  172. :raises celery.exceptions.TimeoutError: if ``timeout`` is not ``None``
  173. and the operation takes longer than ``timeout`` seconds.
  174. If any of the tasks raises an exception, the exception
  175. will be reraised by :meth:`join`.
  176. :returns: list of return values for all tasks in the taskset.
  177. """
  178. time_start = time.time()
  179. def on_timeout():
  180. raise TimeoutError("The operation timed out.")
  181. results = PositionQueue(length=self.total)
  182. while True:
  183. for position, pending_result in enumerate(self.subtasks):
  184. if pending_result.status == "SUCCESS":
  185. results[position] = pending_result.result
  186. elif pending_result.status == "FAILURE":
  187. raise pending_result.result
  188. if results.full():
  189. # Make list copy, so the returned type is not a position
  190. # queue.
  191. return list(results)
  192. else:
  193. if timeout is not None and \
  194. time.time() >= time_start + timeout:
  195. on_timeout()
  196. @property
  197. def total(self):
  198. """The total number of tasks in the :class:`celery.task.TaskSet`."""
  199. return len(self.subtasks)
  200. class EagerResult(BaseAsyncResult):
  201. """Result that we know has already been executed. """
  202. TimeoutError = TimeoutError
  203. def __init__(self, task_id, ret_value, status, traceback=None):
  204. self.task_id = task_id
  205. self._result = ret_value
  206. self._status = status
  207. self._traceback = traceback
  208. def successful(self):
  209. """Returns ``True`` if the task executed without failure."""
  210. return self.status == "SUCCESS"
  211. def ready(self):
  212. """Returns ``True`` if the task has been executed."""
  213. return True
  214. def wait(self, timeout=None):
  215. """Wait until the task has been executed and return its result."""
  216. if self.status == "SUCCESS":
  217. return self.result
  218. elif self.status == "FAILURE":
  219. raise self.result.exception
  220. @property
  221. def result(self):
  222. """The tasks return value"""
  223. return self._result
  224. @property
  225. def status(self):
  226. """The tasks status"""
  227. return self._status
  228. @property
  229. def traceback(self):
  230. """The traceback if the task failed."""
  231. return self._traceback
  232. def __repr__(self):
  233. return "<EagerResult: %s>" % self.task_id