amqp.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. from __future__ import with_statement
  4. import socket
  5. import threading
  6. import time
  7. from itertools import count
  8. from kombu.entity import Exchange, Queue
  9. from kombu.messaging import Consumer, Producer
  10. from .. import states
  11. from ..exceptions import TimeoutError
  12. from .base import BaseDictBackend
  13. class BacklogLimitExceeded(Exception):
  14. """Too much state history to fast-forward."""
  15. def repair_uuid(s):
  16. # Historically the dashes in UUIDS are removed from AMQ entity names,
  17. # but there is no known reason to. Hopefully we'll be able to fix
  18. # this in v3.0.
  19. return "%s-%s-%s-%s-%s" % (s[:8], s[8:12], s[12:16], s[16:20], s[20:])
  20. class AMQPBackend(BaseDictBackend):
  21. """Publishes results by sending messages."""
  22. Exchange = Exchange
  23. Queue = Queue
  24. Consumer = Consumer
  25. Producer = Producer
  26. BacklogLimitExceeded = BacklogLimitExceeded
  27. supports_native_join = True
  28. def __init__(self, connection=None, exchange=None, exchange_type=None,
  29. persistent=None, serializer=None, auto_delete=True,
  30. **kwargs):
  31. super(AMQPBackend, self).__init__(**kwargs)
  32. conf = self.app.conf
  33. self._connection = connection
  34. self.queue_arguments = {}
  35. self.persistent = (conf.CELERY_RESULT_PERSISTENT if persistent is None
  36. else persistent)
  37. delivery_mode = persistent and "persistent" or "transient"
  38. exchange = exchange or conf.CELERY_RESULT_EXCHANGE
  39. exchange_type = exchange_type or conf.CELERY_RESULT_EXCHANGE_TYPE
  40. self.exchange = self.Exchange(name=exchange,
  41. type=exchange_type,
  42. delivery_mode=delivery_mode,
  43. durable=self.persistent,
  44. auto_delete=False)
  45. self.serializer = serializer or conf.CELERY_RESULT_SERIALIZER
  46. self.auto_delete = auto_delete
  47. # AMQP_TASK_RESULT_EXPIRES setting is deprecated and will be
  48. # removed in version 3.0.
  49. dexpires = conf.CELERY_AMQP_TASK_RESULT_EXPIRES
  50. self.expires = None
  51. if "expires" in kwargs:
  52. if kwargs["expires"] is not None:
  53. self.expires = self.prepare_expires(kwargs["expires"])
  54. else:
  55. self.expires = self.prepare_expires(dexpires)
  56. if self.expires:
  57. self.queue_arguments["x-expires"] = int(self.expires * 1000)
  58. self.mutex = threading.Lock()
  59. def _create_binding(self, task_id):
  60. name = task_id.replace("-", "")
  61. return self.Queue(name=name,
  62. exchange=self.exchange,
  63. routing_key=name,
  64. durable=self.persistent,
  65. auto_delete=self.auto_delete,
  66. queue_arguments=self.queue_arguments)
  67. def _create_producer(self, task_id, connection):
  68. self._create_binding(task_id)(connection.default_channel).declare()
  69. return self.Producer(connection, exchange=self.exchange,
  70. routing_key=task_id.replace("-", ""),
  71. serializer=self.serializer)
  72. def _create_consumer(self, bindings, channel):
  73. return self.Consumer(channel, bindings, no_ack=True)
  74. def _publish_result(self, connection, task_id, meta):
  75. # cache single channel
  76. self._create_producer(task_id, connection).publish(meta)
  77. def revive(self, channel):
  78. pass
  79. def _store_result(self, task_id, result, status, traceback=None,
  80. max_retries=20, interval_start=0, interval_step=1,
  81. interval_max=1):
  82. """Send task return value and status."""
  83. with self.mutex:
  84. with self.app.pool.acquire(block=True) as conn:
  85. def errback(error, delay):
  86. print("Couldn't send result for %r: %r. Retry in %rs." % (
  87. task_id, error, delay))
  88. send = conn.ensure(self, self._publish_result,
  89. max_retries=max_retries,
  90. errback=errback,
  91. interval_start=interval_start,
  92. interval_step=interval_step,
  93. interval_max=interval_max)
  94. send(conn, task_id, {"task_id": task_id, "status": status,
  95. "result": self.encode_result(result, status),
  96. "traceback": traceback})
  97. return result
  98. def get_task_meta(self, task_id, cache=True):
  99. return self.poll(task_id)
  100. def wait_for(self, task_id, timeout=None, cache=True, propagate=True,
  101. **kwargs):
  102. cached_meta = self._cache.get(task_id)
  103. if cache and cached_meta and \
  104. cached_meta["status"] in states.READY_STATES:
  105. meta = cached_meta
  106. else:
  107. try:
  108. meta = self.consume(task_id, timeout=timeout)
  109. except socket.timeout:
  110. raise TimeoutError("The operation timed out.")
  111. state = meta["status"]
  112. if state == states.SUCCESS:
  113. return meta["result"]
  114. elif state in states.PROPAGATE_STATES:
  115. if propagate:
  116. raise self.exception_to_python(meta["result"])
  117. return meta["result"]
  118. else:
  119. return self.wait_for(task_id, timeout, cache)
  120. def poll(self, task_id, backlog_limit=100):
  121. with self.app.pool.acquire_channel(block=True) as (_, channel):
  122. binding = self._create_binding(task_id)(channel)
  123. binding.declare()
  124. latest, acc = None, None
  125. for i in count(): # fast-forward
  126. latest, acc = acc, binding.get(no_ack=True)
  127. if not acc:
  128. break
  129. if i > backlog_limit:
  130. raise self.BacklogLimitExceeded(task_id)
  131. if latest:
  132. payload = self._cache[task_id] = latest.payload
  133. return payload
  134. elif task_id in self._cache: # use previously received state.
  135. return self._cache[task_id]
  136. return {"status": states.PENDING, "result": None}
  137. def drain_events(self, connection, consumer, timeout=None, now=time.time):
  138. wait = connection.drain_events
  139. results = {}
  140. def callback(meta, message):
  141. if meta["status"] in states.READY_STATES:
  142. uuid = repair_uuid(message.delivery_info["routing_key"])
  143. results[uuid] = meta
  144. consumer.callbacks[:] = [callback]
  145. time_start = now()
  146. while 1:
  147. # Total time spent may exceed a single call to wait()
  148. if timeout and now() - time_start >= timeout:
  149. raise socket.timeout()
  150. wait(timeout=timeout)
  151. if results: # got event on the wanted channel.
  152. break
  153. self._cache.update(results)
  154. return results
  155. def consume(self, task_id, timeout=None):
  156. with self.app.pool.acquire_channel(block=True) as (conn, channel):
  157. binding = self._create_binding(task_id)
  158. with self._create_consumer(binding, channel) as consumer:
  159. return self.drain_events(conn, consumer, timeout).values()[0]
  160. def get_many(self, task_ids, timeout=None, **kwargs):
  161. with self.app.pool.acquire_channel(block=True) as (conn, channel):
  162. ids = set(task_ids)
  163. cached_ids = set()
  164. for task_id in ids:
  165. try:
  166. cached = self._cache[task_id]
  167. except KeyError:
  168. pass
  169. else:
  170. if cached["status"] in states.READY_STATES:
  171. yield task_id, cached
  172. cached_ids.add(task_id)
  173. ids ^= cached_ids
  174. bindings = [self._create_binding(task_id) for task_id in task_ids]
  175. with self._create_consumer(bindings, channel) as consumer:
  176. while ids:
  177. r = self.drain_events(conn, consumer, timeout)
  178. ids ^= set(r)
  179. for ready_id, ready_meta in r.iteritems():
  180. yield ready_id, ready_meta
  181. def reload_task_result(self, task_id):
  182. raise NotImplementedError(
  183. "reload_task_result is not supported by this backend.")
  184. def reload_taskset_result(self, task_id):
  185. """Reload taskset result, even if it has been previously fetched."""
  186. raise NotImplementedError(
  187. "reload_taskset_result is not supported by this backend.")
  188. def save_taskset(self, taskset_id, result):
  189. raise NotImplementedError(
  190. "save_taskset is not supported by this backend.")
  191. def restore_taskset(self, taskset_id, cache=True):
  192. raise NotImplementedError(
  193. "restore_taskset is not supported by this backend.")
  194. def delete_taskset(self, taskset_id):
  195. raise NotImplementedError(
  196. "delete_taskset is not supported by this backend.")
  197. def __reduce__(self, args=(), kwargs={}):
  198. kwargs.update(
  199. dict(connection=self._connection,
  200. exchange=self.exchange.name,
  201. exchange_type=self.exchange.type,
  202. persistent=self.persistent,
  203. serializer=self.serializer,
  204. auto_delete=self.auto_delete,
  205. expires=self.expires))
  206. return super(AMQPBackend, self).__reduce__(args, kwargs)