amqp.py 9.4 KB

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