amqp.py 9.8 KB

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