result.py 9.3 KB

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