amqp.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.app.amqp
  4. ~~~~~~~~~~~~~~~
  5. Sending and receiving messages using Kombu.
  6. """
  7. from __future__ import absolute_import
  8. import numbers
  9. from collections import Mapping, namedtuple
  10. from datetime import timedelta
  11. from weakref import WeakValueDictionary
  12. from kombu import Connection, Consumer, Exchange, Producer, Queue
  13. from kombu.common import Broadcast
  14. from kombu.pools import ProducerPool
  15. from kombu.utils import cached_property
  16. from kombu.utils.encoding import safe_repr
  17. from kombu.utils.functional import maybe_list
  18. from celery import signals
  19. from celery.five import items, string_t
  20. from celery.utils.text import indent as textindent
  21. from celery.utils.timeutils import to_utc
  22. from . import routes as _routes
  23. __all__ = ['AMQP', 'Queues', 'task_message']
  24. #: Human readable queue declaration.
  25. QUEUE_FORMAT = """
  26. .> {0.name:<16} exchange={0.exchange.name}({0.exchange.type}) \
  27. key={0.routing_key}
  28. """
  29. task_message = namedtuple('task_message',
  30. ('headers', 'properties', 'body', 'sent_event'))
  31. class Queues(dict):
  32. """Queue name⇒ declaration mapping.
  33. :param queues: Initial list/tuple or dict of queues.
  34. :keyword create_missing: By default any unknown queues will be
  35. added automatically, but if disabled
  36. the occurrence of unknown queues
  37. in `wanted` will raise :exc:`KeyError`.
  38. :keyword ha_policy: Default HA policy for queues with none set.
  39. """
  40. #: If set, this is a subset of queues to consume from.
  41. #: The rest of the queues are then used for routing only.
  42. _consume_from = None
  43. def __init__(self, queues=None, default_exchange=None,
  44. create_missing=True, ha_policy=None, autoexchange=None):
  45. dict.__init__(self)
  46. self.aliases = WeakValueDictionary()
  47. self.default_exchange = default_exchange
  48. self.create_missing = create_missing
  49. self.ha_policy = ha_policy
  50. self.autoexchange = Exchange if autoexchange is None else autoexchange
  51. if isinstance(queues, (tuple, list)):
  52. queues = {q.name: q for q in queues}
  53. for name, q in items(queues or {}):
  54. self.add(q) if isinstance(q, Queue) else self.add_compat(name, **q)
  55. def __getitem__(self, name):
  56. try:
  57. return self.aliases[name]
  58. except KeyError:
  59. return dict.__getitem__(self, name)
  60. def __setitem__(self, name, queue):
  61. if self.default_exchange and (not queue.exchange or
  62. not queue.exchange.name):
  63. queue.exchange = self.default_exchange
  64. dict.__setitem__(self, name, queue)
  65. if queue.alias:
  66. self.aliases[queue.alias] = queue
  67. def __missing__(self, name):
  68. if self.create_missing:
  69. return self.add(self.new_missing(name))
  70. raise KeyError(name)
  71. def add(self, queue, **kwargs):
  72. """Add new queue.
  73. The first argument can either be a :class:`kombu.Queue` instance,
  74. or the name of a queue. If the former the rest of the keyword
  75. arguments are ignored, and options are simply taken from the queue
  76. instance.
  77. :param queue: :class:`kombu.Queue` instance or name of the queue.
  78. :keyword exchange: (if named) specifies exchange name.
  79. :keyword routing_key: (if named) specifies binding key.
  80. :keyword exchange_type: (if named) specifies type of exchange.
  81. :keyword \*\*options: (if named) Additional declaration options.
  82. """
  83. if not isinstance(queue, Queue):
  84. return self.add_compat(queue, **kwargs)
  85. if self.ha_policy:
  86. if queue.queue_arguments is None:
  87. queue.queue_arguments = {}
  88. self._set_ha_policy(queue.queue_arguments)
  89. self[queue.name] = queue
  90. return queue
  91. def add_compat(self, name, **options):
  92. # docs used to use binding_key as routing key
  93. options.setdefault('routing_key', options.get('binding_key'))
  94. if options['routing_key'] is None:
  95. options['routing_key'] = name
  96. if self.ha_policy is not None:
  97. self._set_ha_policy(options.setdefault('queue_arguments', {}))
  98. q = self[name] = Queue.from_dict(name, **options)
  99. return q
  100. def _set_ha_policy(self, args):
  101. policy = self.ha_policy
  102. if isinstance(policy, (list, tuple)):
  103. return args.update({'x-ha-policy': 'nodes',
  104. 'x-ha-policy-params': list(policy)})
  105. args['x-ha-policy'] = policy
  106. def format(self, indent=0, indent_first=True):
  107. """Format routing table into string for log dumps."""
  108. active = self.consume_from
  109. if not active:
  110. return ''
  111. info = [QUEUE_FORMAT.strip().format(q)
  112. for _, q in sorted(items(active))]
  113. if indent_first:
  114. return textindent('\n'.join(info), indent)
  115. return info[0] + '\n' + textindent('\n'.join(info[1:]), indent)
  116. def select_add(self, queue, **kwargs):
  117. """Add new task queue that will be consumed from even when
  118. a subset has been selected using the :option:`-Q` option."""
  119. q = self.add(queue, **kwargs)
  120. if self._consume_from is not None:
  121. self._consume_from[q.name] = q
  122. return q
  123. def select(self, include):
  124. """Sets :attr:`consume_from` by selecting a subset of the
  125. currently defined queues.
  126. :param include: Names of queues to consume from.
  127. Can be iterable or string.
  128. """
  129. if include:
  130. self._consume_from = {
  131. name: self[name] for name in maybe_list(include)
  132. }
  133. select_subset = select # XXX compat
  134. def deselect(self, exclude):
  135. """Deselect queues so that they will not be consumed from.
  136. :param exclude: Names of queues to avoid consuming from.
  137. Can be iterable or string.
  138. """
  139. if exclude:
  140. exclude = maybe_list(exclude)
  141. if self._consume_from is None:
  142. # using selection
  143. return self.select(k for k in self if k not in exclude)
  144. # using all queues
  145. for queue in exclude:
  146. self._consume_from.pop(queue, None)
  147. select_remove = deselect # XXX compat
  148. def new_missing(self, name):
  149. return Queue(name, self.autoexchange(name), name)
  150. @property
  151. def consume_from(self):
  152. if self._consume_from is not None:
  153. return self._consume_from
  154. return self
  155. class AMQP(object):
  156. Connection = Connection
  157. Consumer = Consumer
  158. Producer = Producer
  159. #: compat alias to Connection
  160. BrokerConnection = Connection
  161. queues_cls = Queues
  162. #: Cached and prepared routing table.
  163. _rtable = None
  164. #: Underlying producer pool instance automatically
  165. #: set by the :attr:`producer_pool`.
  166. _producer_pool = None
  167. # Exchange class/function used when defining automatic queues.
  168. # E.g. you can use ``autoexchange = lambda n: None`` to use the
  169. # amqp default exchange, which is a shortcut to bypass routing
  170. # and instead send directly to the queue named in the routing key.
  171. autoexchange = None
  172. def __init__(self, app):
  173. self.app = app
  174. self.task_protocols = {
  175. 1: self.as_task_v1,
  176. 2: self.as_task_v2,
  177. }
  178. @cached_property
  179. def create_task_message(self):
  180. return self.task_protocols[self.app.conf.CELERY_TASK_PROTOCOL]
  181. @cached_property
  182. def send_task_message(self):
  183. return self._create_task_sender()
  184. def Queues(self, queues, create_missing=None, ha_policy=None,
  185. autoexchange=None):
  186. """Create new :class:`Queues` instance, using queue defaults
  187. from the current configuration."""
  188. conf = self.app.conf
  189. if create_missing is None:
  190. create_missing = conf.CELERY_CREATE_MISSING_QUEUES
  191. if ha_policy is None:
  192. ha_policy = conf.CELERY_QUEUE_HA_POLICY
  193. if not queues and conf.CELERY_DEFAULT_QUEUE:
  194. queues = (Queue(conf.CELERY_DEFAULT_QUEUE,
  195. exchange=self.default_exchange,
  196. routing_key=conf.CELERY_DEFAULT_ROUTING_KEY), )
  197. autoexchange = (self.autoexchange if autoexchange is None
  198. else autoexchange)
  199. return self.queues_cls(
  200. queues, self.default_exchange, create_missing,
  201. ha_policy, autoexchange,
  202. )
  203. def Router(self, queues=None, create_missing=None):
  204. """Return the current task router."""
  205. return _routes.Router(self.routes, queues or self.queues,
  206. self.app.either('CELERY_CREATE_MISSING_QUEUES',
  207. create_missing), app=self.app)
  208. def flush_routes(self):
  209. self._rtable = _routes.prepare(self.app.conf.CELERY_ROUTES)
  210. def TaskConsumer(self, channel, queues=None, accept=None, **kw):
  211. if accept is None:
  212. accept = self.app.conf.CELERY_ACCEPT_CONTENT
  213. return self.Consumer(
  214. channel, accept=accept,
  215. queues=queues or list(self.queues.consume_from.values()),
  216. **kw
  217. )
  218. def as_task_v2(self, task_id, name, args=None, kwargs=None,
  219. countdown=None, eta=None, group_id=None,
  220. expires=None, retries=0, chord=None,
  221. callbacks=None, errbacks=None, reply_to=None,
  222. time_limit=None, soft_time_limit=None,
  223. create_sent_event=False, now=None, timezone=None):
  224. args = args or ()
  225. kwargs = kwargs or {}
  226. utc = self.utc
  227. if not isinstance(args, (list, tuple)):
  228. raise ValueError('task args must be a list or tuple')
  229. if not isinstance(kwargs, Mapping):
  230. raise ValueError('task keyword arguments must be a mapping')
  231. if countdown: # convert countdown to ETA
  232. now = now or self.app.now()
  233. timezone = timezone or self.app.timezone
  234. eta = now + timedelta(seconds=countdown)
  235. if utc:
  236. eta = to_utc(eta).astimezone(timezone)
  237. if isinstance(expires, numbers.Real):
  238. now = now or self.app.now()
  239. timezone = timezone or self.app.timezone
  240. expires = now + timedelta(seconds=expires)
  241. if utc:
  242. expires = to_utc(expires).astimezone(timezone)
  243. eta = eta and eta.isoformat()
  244. expires = expires and expires.isoformat()
  245. return task_message(
  246. headers={
  247. 'lang': 'py',
  248. 'c_type': name,
  249. 'eta': eta,
  250. 'expires': expires,
  251. 'callbacks': callbacks,
  252. 'errbacks': errbacks,
  253. 'chain': None, # TODO
  254. 'group': group_id,
  255. 'chord': chord,
  256. 'retries': retries,
  257. 'timelimit': (time_limit, soft_time_limit),
  258. },
  259. properties={
  260. 'correlation_id': task_id,
  261. 'reply_to': reply_to or '',
  262. },
  263. body=(args, kwargs),
  264. sent_event={
  265. 'uuid': task_id,
  266. 'name': name,
  267. 'args': safe_repr(args),
  268. 'kwargs': safe_repr(kwargs),
  269. 'retries': retries,
  270. 'eta': eta,
  271. 'expires': expires,
  272. } if create_sent_event else None,
  273. )
  274. def as_task_v1(self, task_id, name, args=None, kwargs=None,
  275. countdown=None, eta=None, group_id=None,
  276. expires=None, retries=0,
  277. chord=None, callbacks=None, errbacks=None, reply_to=None,
  278. time_limit=None, soft_time_limit=None,
  279. create_sent_event=False, now=None, timezone=None):
  280. args = args or ()
  281. kwargs = kwargs or {}
  282. utc = self.utc
  283. if not isinstance(args, (list, tuple)):
  284. raise ValueError('task args must be a list or tuple')
  285. if not isinstance(kwargs, Mapping):
  286. raise ValueError('task keyword arguments must be a mapping')
  287. if countdown: # convert countdown to ETA
  288. now = now or self.app.now()
  289. timezone = timezone or self.app.timezone
  290. eta = now + timedelta(seconds=countdown)
  291. if utc:
  292. eta = to_utc(eta).astimezone(timezone)
  293. if isinstance(expires, numbers.Real):
  294. now = now or self.app.now()
  295. timezone = timezone or self.app.timezone
  296. expires = now + timedelta(seconds=expires)
  297. if utc:
  298. expires = to_utc(expires).astimezone(timezone)
  299. eta = eta and eta.isoformat()
  300. expires = expires and expires.isoformat()
  301. return task_message(
  302. headers={},
  303. properties={
  304. 'correlation_id': task_id,
  305. 'reply_to': reply_to or '',
  306. },
  307. body={
  308. 'task': name,
  309. 'id': task_id,
  310. 'args': args,
  311. 'kwargs': kwargs,
  312. 'retries': retries,
  313. 'eta': eta,
  314. 'expires': expires,
  315. 'utc': utc,
  316. 'callbacks': callbacks,
  317. 'errbacks': errbacks,
  318. 'timelimit': (time_limit, soft_time_limit),
  319. 'taskset': group_id,
  320. 'chord': chord,
  321. },
  322. sent_event={
  323. 'uuid': task_id,
  324. 'name': name,
  325. 'args': safe_repr(args),
  326. 'kwargs': safe_repr(kwargs),
  327. 'retries': retries,
  328. 'eta': eta,
  329. 'expires': expires,
  330. } if create_sent_event else None,
  331. )
  332. def _create_task_sender(self):
  333. default_retry = self.app.conf.CELERY_TASK_PUBLISH_RETRY
  334. default_policy = self.app.conf.CELERY_TASK_PUBLISH_RETRY_POLICY
  335. default_delivery_mode = self.app.conf.CELERY_DEFAULT_DELIVERY_MODE
  336. default_queue = self.default_queue
  337. queues = self.queues
  338. send_before_publish = signals.before_task_publish.send
  339. before_receivers = signals.before_task_publish.receivers
  340. send_after_publish = signals.after_task_publish.send
  341. after_receivers = signals.after_task_publish.receivers
  342. send_task_sent = signals.task_sent.send # XXX compat
  343. sent_receivers = signals.task_sent.receivers
  344. default_evd = self._event_dispatcher
  345. default_exchange = self.default_exchange
  346. default_rkey = self.app.conf.CELERY_DEFAULT_ROUTING_KEY
  347. default_serializer = self.app.conf.CELERY_TASK_SERIALIZER
  348. default_compressor = self.app.conf.CELERY_MESSAGE_COMPRESSION
  349. def publish_task(producer, name, message,
  350. exchange=None, routing_key=None, queue=None,
  351. event_dispatcher=None, retry=None, retry_policy=None,
  352. serializer=None, delivery_mode=None,
  353. compression=None, declare=None,
  354. headers=None, **kwargs):
  355. retry = default_retry if retry is None else retry
  356. headers, properties, body, sent_event = message
  357. if kwargs:
  358. properties.update(kwargs)
  359. qname = queue
  360. if queue is None and exchange is None:
  361. queue = default_queue
  362. if queue is not None:
  363. if isinstance(queue, string_t):
  364. qname, queue = queue, queues[queue]
  365. else:
  366. qname = queue.name
  367. if delivery_mode is None:
  368. try:
  369. delivery_mode = queue.exchange.delivery_mode
  370. except AttributeError:
  371. delivery_mode = default_delivery_mode
  372. exchange = exchange or queue.exchange.name
  373. routing_key = routing_key or queue.routing_key
  374. if declare is None and queue and not isinstance(queue, Broadcast):
  375. declare = [queue]
  376. # merge default and custom policy
  377. retry = default_retry if retry is None else retry
  378. _rp = (dict(default_policy, **retry_policy) if retry_policy
  379. else default_policy)
  380. if before_receivers:
  381. send_before_publish(
  382. sender=name, body=body,
  383. exchange=exchange, routing_key=routing_key,
  384. declare=declare, headers=headers,
  385. properties=kwargs, retry_policy=retry_policy,
  386. )
  387. ret = producer.publish(
  388. body,
  389. exchange=exchange or default_exchange,
  390. routing_key=routing_key or default_rkey,
  391. serializer=serializer or default_serializer,
  392. compression=compression or default_compressor,
  393. retry=retry, retry_policy=_rp,
  394. delivery_mode=delivery_mode, declare=declare,
  395. headers=headers,
  396. **properties
  397. )
  398. if after_receivers:
  399. send_after_publish(sender=name, body=body,
  400. exchange=exchange, routing_key=routing_key)
  401. if sent_receivers: # XXX deprecated
  402. send_task_sent(sender=name, task_id=body['id'], task=name,
  403. args=body['args'], kwargs=body['kwargs'],
  404. eta=body['eta'], taskset=body['taskset'])
  405. if sent_event:
  406. evd = event_dispatcher or default_evd
  407. exname = exchange or self.exchange
  408. if isinstance(name, Exchange):
  409. exname = exname.name
  410. sent_event.update({
  411. 'queue': qname,
  412. 'exchange': exname,
  413. 'routing_key': routing_key,
  414. })
  415. evd.publish('task-sent', sent_event,
  416. self, retry=retry, retry_policy=retry_policy)
  417. return ret
  418. return publish_task
  419. @cached_property
  420. def default_queue(self):
  421. return self.queues[self.app.conf.CELERY_DEFAULT_QUEUE]
  422. @cached_property
  423. def queues(self):
  424. """Queue name⇒ declaration mapping."""
  425. return self.Queues(self.app.conf.CELERY_QUEUES)
  426. @queues.setter # noqa
  427. def queues(self, queues):
  428. return self.Queues(queues)
  429. @property
  430. def routes(self):
  431. if self._rtable is None:
  432. self.flush_routes()
  433. return self._rtable
  434. @cached_property
  435. def router(self):
  436. return self.Router()
  437. @property
  438. def producer_pool(self):
  439. if self._producer_pool is None:
  440. self._producer_pool = ProducerPool(
  441. self.app.pool,
  442. limit=self.app.pool.limit,
  443. Producer=self.Producer,
  444. )
  445. return self._producer_pool
  446. publisher_pool = producer_pool # compat alias
  447. @cached_property
  448. def default_exchange(self):
  449. return Exchange(self.app.conf.CELERY_DEFAULT_EXCHANGE,
  450. self.app.conf.CELERY_DEFAULT_EXCHANGE_TYPE)
  451. @cached_property
  452. def utc(self):
  453. return self.app.conf.CELERY_ENABLE_UTC
  454. @cached_property
  455. def _event_dispatcher(self):
  456. # We call Dispatcher.publish with a custom producer
  457. # so don't need the diuspatcher to be enabled.
  458. return self.app.events.Dispatcher(enabled=False)