amqp.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.backends.amqp
  4. ~~~~~~~~~~~~~~~~~~~~
  5. The AMQP result backend.
  6. This backend publishes results as messages.
  7. """
  8. from __future__ import absolute_import
  9. import socket
  10. from collections import deque
  11. from operator import itemgetter
  12. from kombu import Exchange, Queue, Producer, Consumer
  13. from celery import states
  14. from celery.exceptions import TimeoutError
  15. from celery.five import range, monotonic
  16. from celery.utils.functional import dictfilter
  17. from celery.utils.log import get_logger
  18. from celery.utils.timeutils import maybe_s_to_ms
  19. from .base import BaseBackend
  20. __all__ = ['BacklogLimitExceeded', 'AMQPBackend']
  21. logger = get_logger(__name__)
  22. class BacklogLimitExceeded(Exception):
  23. """Too much state history to fast-forward."""
  24. def repair_uuid(s):
  25. # Historically the dashes in UUIDS are removed from AMQ entity names,
  26. # but there is no known reason to. Hopefully we'll be able to fix
  27. # this in v4.0.
  28. return '%s-%s-%s-%s-%s' % (s[:8], s[8:12], s[12:16], s[16:20], s[20:])
  29. class NoCacheQueue(Queue):
  30. can_cache_declaration = False
  31. class AMQPBackend(BaseBackend):
  32. """Publishes results by sending messages."""
  33. Exchange = Exchange
  34. Queue = NoCacheQueue
  35. Consumer = Consumer
  36. Producer = Producer
  37. BacklogLimitExceeded = BacklogLimitExceeded
  38. supports_autoexpire = True
  39. supports_native_join = True
  40. retry_policy = {
  41. 'max_retries': 20,
  42. 'interval_start': 0,
  43. 'interval_step': 1,
  44. 'interval_max': 1,
  45. }
  46. def __init__(self, app, connection=None, exchange=None, exchange_type=None,
  47. persistent=None, serializer=None, auto_delete=True, **kwargs):
  48. super(AMQPBackend, self).__init__(app, **kwargs)
  49. conf = self.app.conf
  50. self._connection = connection
  51. self.persistent = self.prepare_persistent(persistent)
  52. self.delivery_mode = 2 if self.persistent else 1
  53. exchange = exchange or conf.CELERY_RESULT_EXCHANGE
  54. exchange_type = exchange_type or conf.CELERY_RESULT_EXCHANGE_TYPE
  55. self.exchange = self._create_exchange(
  56. exchange, exchange_type, self.delivery_mode,
  57. )
  58. self.serializer = serializer or conf.CELERY_RESULT_SERIALIZER
  59. self.auto_delete = auto_delete
  60. self.expires = None
  61. if 'expires' not in kwargs or kwargs['expires'] is not None:
  62. self.expires = self.prepare_expires(kwargs.get('expires'))
  63. self.queue_arguments = dictfilter({
  64. 'x-expires': maybe_s_to_ms(self.expires),
  65. })
  66. def _create_exchange(self, name, type='direct', delivery_mode=2):
  67. return self.Exchange(name=name,
  68. type=type,
  69. delivery_mode=delivery_mode,
  70. durable=self.persistent,
  71. auto_delete=False)
  72. def _create_binding(self, task_id):
  73. name = self.rkey(task_id)
  74. return self.Queue(name=name,
  75. exchange=self.exchange,
  76. routing_key=name,
  77. durable=self.persistent,
  78. auto_delete=self.auto_delete,
  79. queue_arguments=self.queue_arguments)
  80. def revive(self, channel):
  81. pass
  82. def rkey(self, task_id):
  83. return task_id.replace('-', '')
  84. def destination_for(self, task_id, request):
  85. if request:
  86. return self.rkey(task_id), request.correlation_id or task_id
  87. return self.rkey(task_id), task_id
  88. def store_result(self, task_id, result, status,
  89. traceback=None, request=None, **kwargs):
  90. """Send task return value and status."""
  91. routing_key, correlation_id = self.destination_for(task_id, request)
  92. if not routing_key:
  93. return
  94. with self.app.amqp.producer_pool.acquire(block=True) as producer:
  95. producer.publish(
  96. {'task_id': task_id, 'status': status,
  97. 'result': self.encode_result(result, status),
  98. 'traceback': traceback,
  99. 'children': self.current_task_children(request)},
  100. exchange=self.exchange,
  101. routing_key=routing_key,
  102. correlation_id=correlation_id,
  103. serializer=self.serializer,
  104. retry=True, retry_policy=self.retry_policy,
  105. declare=self.on_reply_declare(task_id),
  106. delivery_mode=self.delivery_mode,
  107. )
  108. return result
  109. def on_reply_declare(self, task_id):
  110. return [self._create_binding(task_id)]
  111. def wait_for(self, task_id, timeout=None, cache=True, propagate=True,
  112. READY_STATES=states.READY_STATES,
  113. PROPAGATE_STATES=states.PROPAGATE_STATES,
  114. **kwargs):
  115. cached_meta = self._cache.get(task_id)
  116. if cache and cached_meta and \
  117. cached_meta['status'] in READY_STATES:
  118. meta = cached_meta
  119. else:
  120. try:
  121. meta = self.consume(task_id, timeout=timeout)
  122. except socket.timeout:
  123. raise TimeoutError('The operation timed out.')
  124. if meta['status'] in PROPAGATE_STATES and propagate:
  125. raise self.exception_to_python(meta['result'])
  126. # consume() always returns READY_STATE.
  127. return meta['result']
  128. def get_task_meta(self, task_id, backlog_limit=1000):
  129. # Polling and using basic_get
  130. with self.app.pool.acquire_channel(block=True) as (_, channel):
  131. binding = self._create_binding(task_id)(channel)
  132. binding.declare()
  133. prev = latest = acc = None
  134. for i in range(backlog_limit): # spool ffwd
  135. prev, latest, acc = latest, acc, binding.get(
  136. accept=self.accept, no_ack=False,
  137. )
  138. if not acc: # no more messages
  139. break
  140. if prev:
  141. # backends are not expected to keep history,
  142. # so we delete everything except the most recent state.
  143. prev.ack()
  144. else:
  145. raise self.BacklogLimitExceeded(task_id)
  146. if latest:
  147. payload = self._cache[task_id] = latest.payload
  148. latest.requeue()
  149. return payload
  150. else:
  151. # no new state, use previous
  152. try:
  153. return self._cache[task_id]
  154. except KeyError:
  155. # result probably pending.
  156. return {'status': states.PENDING, 'result': None}
  157. poll = get_task_meta # XXX compat
  158. def drain_events(self, connection, consumer,
  159. timeout=None, now=monotonic, wait=None):
  160. wait = wait or connection.drain_events
  161. results = {}
  162. def callback(meta, message):
  163. if meta['status'] in states.READY_STATES:
  164. results[meta['task_id']] = meta
  165. consumer.callbacks[:] = [callback]
  166. time_start = now()
  167. while 1:
  168. # Total time spent may exceed a single call to wait()
  169. if timeout and now() - time_start >= timeout:
  170. raise socket.timeout()
  171. wait(timeout=timeout)
  172. if results: # got event on the wanted channel.
  173. break
  174. self._cache.update(results)
  175. return results
  176. def consume(self, task_id, timeout=None):
  177. wait = self.drain_events
  178. with self.app.pool.acquire_channel(block=True) as (conn, channel):
  179. binding = self._create_binding(task_id)
  180. with self.Consumer(channel, binding,
  181. no_ack=True, accept=self.accept) as consumer:
  182. while 1:
  183. try:
  184. return wait(conn, consumer, timeout)[task_id]
  185. except KeyError:
  186. continue
  187. def _many_bindings(self, ids):
  188. return [self._create_binding(task_id) for task_id in ids]
  189. def get_many(self, task_ids, timeout=None,
  190. now=monotonic, getfields=itemgetter('status', 'task_id'),
  191. READY_STATES=states.READY_STATES,
  192. PROPAGATE_STATES=states.PROPAGATE_STATES, **kwargs):
  193. with self.app.pool.acquire_channel(block=True) as (conn, channel):
  194. ids = set(task_ids)
  195. cached_ids = set()
  196. mark_cached = cached_ids.add
  197. for task_id in ids:
  198. try:
  199. cached = self._cache[task_id]
  200. except KeyError:
  201. pass
  202. else:
  203. if cached['status'] in READY_STATES:
  204. yield task_id, cached
  205. mark_cached(task_id)
  206. ids.difference_update(cached_ids)
  207. results = deque()
  208. push_result = results.append
  209. push_cache = self._cache.__setitem__
  210. to_exception = self.exception_to_python
  211. def on_message(message):
  212. body = message.decode()
  213. state, uid = getfields(body)
  214. if state in READY_STATES:
  215. if state in PROPAGATE_STATES:
  216. body['result'] = to_exception(body['result'])
  217. push_result(body) \
  218. if uid in task_ids else push_cache(uid, body)
  219. bindings = self._many_bindings(task_ids)
  220. with self.Consumer(channel, bindings, on_message=on_message,
  221. accept=self.accept, no_ack=True):
  222. wait = conn.drain_events
  223. popleft = results.popleft
  224. while ids:
  225. wait(timeout=timeout)
  226. while results:
  227. state = popleft()
  228. task_id = state['task_id']
  229. ids.discard(task_id)
  230. push_cache(task_id, state)
  231. yield task_id, state
  232. def reload_task_result(self, task_id):
  233. raise NotImplementedError(
  234. 'reload_task_result is not supported by this backend.')
  235. def reload_group_result(self, task_id):
  236. """Reload group result, even if it has been previously fetched."""
  237. raise NotImplementedError(
  238. 'reload_group_result is not supported by this backend.')
  239. def save_group(self, group_id, result):
  240. raise NotImplementedError(
  241. 'save_group is not supported by this backend.')
  242. def restore_group(self, group_id, cache=True):
  243. raise NotImplementedError(
  244. 'restore_group is not supported by this backend.')
  245. def delete_group(self, group_id):
  246. raise NotImplementedError(
  247. 'delete_group is not supported by this backend.')
  248. def __reduce__(self, args=(), kwargs={}):
  249. kwargs.update(
  250. connection=self._connection,
  251. exchange=self.exchange.name,
  252. exchange_type=self.exchange.type,
  253. persistent=self.persistent,
  254. serializer=self.serializer,
  255. auto_delete=self.auto_delete,
  256. expires=self.expires,
  257. )
  258. return super(AMQPBackend, self).__reduce__(args, kwargs)