amqp.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. # -*- coding: utf-8 -*-
  2. """Sending/Receiving Messages (Kombu integration)."""
  3. from __future__ import absolute_import, unicode_literals
  4. import numbers
  5. import sys
  6. from collections import Mapping, namedtuple
  7. from datetime import timedelta
  8. from weakref import WeakValueDictionary
  9. from kombu import pools
  10. from kombu import Connection, Consumer, Exchange, Producer, Queue
  11. from kombu.common import Broadcast
  12. from kombu.utils import cached_property
  13. from kombu.utils.functional import maybe_list
  14. from celery import signals
  15. from celery.local import try_import
  16. from celery.utils.nodenames import anon_nodename
  17. from celery.utils.saferepr import saferepr
  18. from celery.utils.text import indent as textindent
  19. from celery.utils.timeutils import maybe_make_aware, to_utc
  20. from . import routes as _routes
  21. __all__ = ['AMQP', 'Queues', 'task_message']
  22. PY3 = sys.version_info[0] == 3
  23. #: earliest date supported by time.mktime.
  24. INT_MIN = -2147483648
  25. # json in Python 2.7 borks if dict contains byte keys.
  26. JSON_NEEDS_UNICODE_KEYS = not PY3 and not try_import('simplejson')
  27. #: Human readable queue declaration.
  28. QUEUE_FORMAT = """
  29. .> {0.name:<16} exchange={0.exchange.name}({0.exchange.type}) \
  30. key={0.routing_key}
  31. """
  32. task_message = namedtuple('task_message',
  33. ('headers', 'properties', 'body', 'sent_event'))
  34. def utf8dict(d, encoding='utf-8'):
  35. return {k.decode(encoding) if isinstance(k, bytes) else k: v
  36. for k, v in d.items()}
  37. class Queues(dict):
  38. """Queue name⇒ declaration mapping.
  39. Arguments:
  40. queues (Iterable): Initial list/tuple or dict of queues.
  41. create_missing (bool): By default any unknown queues will be
  42. added automatically, but if this flag is disabled the occurrence
  43. of unknown queues in `wanted` will raise :exc:`KeyError`.
  44. ha_policy (Sequence, str): Default HA policy for queues with none set.
  45. max_priority (int): Default x-max-priority for queues with none set.
  46. """
  47. #: If set, this is a subset of queues to consume from.
  48. #: The rest of the queues are then used for routing only.
  49. _consume_from = None
  50. def __init__(self, queues=None, default_exchange=None,
  51. create_missing=True, ha_policy=None, autoexchange=None,
  52. max_priority=None):
  53. dict.__init__(self)
  54. self.aliases = WeakValueDictionary()
  55. self.default_exchange = default_exchange
  56. self.create_missing = create_missing
  57. self.ha_policy = ha_policy
  58. self.autoexchange = Exchange if autoexchange is None else autoexchange
  59. self.max_priority = max_priority
  60. if isinstance(queues, (tuple, list)):
  61. queues = {q.name: q for q in queues}
  62. for name, q in (queues or {}).items():
  63. self.add(q) if isinstance(q, Queue) else self.add_compat(name, **q)
  64. def __getitem__(self, name):
  65. try:
  66. return self.aliases[name]
  67. except KeyError:
  68. return dict.__getitem__(self, name)
  69. def __setitem__(self, name, queue):
  70. if self.default_exchange and not queue.exchange:
  71. queue.exchange = self.default_exchange
  72. dict.__setitem__(self, name, queue)
  73. if queue.alias:
  74. self.aliases[queue.alias] = queue
  75. def __missing__(self, name):
  76. if self.create_missing:
  77. return self.add(self.new_missing(name))
  78. raise KeyError(name)
  79. def add(self, queue, **kwargs):
  80. """Add new queue.
  81. The first argument can either be a :class:`kombu.Queue` instance,
  82. or the name of a queue. If the former the rest of the keyword
  83. arguments are ignored, and options are simply taken from the queue
  84. instance.
  85. Arguments:
  86. queue (kombu.Queue, str): Queue to add.
  87. exchange (kombu.Exchange, str):
  88. if queue is str, specifies exchange name.
  89. routing_key (str): if queue is str, specifies binding key.
  90. exchange_type (str): if queue is str, specifies type of exchange.
  91. **options (Any): Additional declaration options used when
  92. queue is a str.
  93. """
  94. if not isinstance(queue, Queue):
  95. return self.add_compat(queue, **kwargs)
  96. if self.ha_policy:
  97. if queue.queue_arguments is None:
  98. queue.queue_arguments = {}
  99. self._set_ha_policy(queue.queue_arguments)
  100. if self.max_priority is not None:
  101. if queue.queue_arguments is None:
  102. queue.queue_arguments = {}
  103. self._set_max_priority(queue.queue_arguments)
  104. self[queue.name] = queue
  105. return queue
  106. def add_compat(self, name, **options):
  107. # docs used to use binding_key as routing key
  108. options.setdefault('routing_key', options.get('binding_key'))
  109. if options['routing_key'] is None:
  110. options['routing_key'] = name
  111. if self.ha_policy is not None:
  112. self._set_ha_policy(options.setdefault('queue_arguments', {}))
  113. if self.max_priority is not None:
  114. self._set_max_priority(options.setdefault('queue_arguments', {}))
  115. q = self[name] = Queue.from_dict(name, **options)
  116. return q
  117. def _set_ha_policy(self, args):
  118. policy = self.ha_policy
  119. if isinstance(policy, (list, tuple)):
  120. return args.update({'x-ha-policy': 'nodes',
  121. 'x-ha-policy-params': list(policy)})
  122. args['x-ha-policy'] = policy
  123. def _set_max_priority(self, args):
  124. if 'x-max-priority' not in args and self.max_priority is not None:
  125. return args.update({'x-max-priority': self.max_priority})
  126. def format(self, indent=0, indent_first=True):
  127. """Format routing table into string for log dumps."""
  128. active = self.consume_from
  129. if not active:
  130. return ''
  131. info = [QUEUE_FORMAT.strip().format(q)
  132. for _, q in sorted(active.items())]
  133. if indent_first:
  134. return textindent('\n'.join(info), indent)
  135. return info[0] + '\n' + textindent('\n'.join(info[1:]), indent)
  136. def select_add(self, queue, **kwargs):
  137. """Add new task queue that will be consumed from even when
  138. a subset has been selected using the
  139. :option:`celery worker -Q` option."""
  140. q = self.add(queue, **kwargs)
  141. if self._consume_from is not None:
  142. self._consume_from[q.name] = q
  143. return q
  144. def select(self, include):
  145. """Sets :attr:`consume_from` by selecting a subset of the
  146. currently defined queues.
  147. Arguments:
  148. include (Sequence[str], str): Names of queues to consume from.
  149. """
  150. if include:
  151. self._consume_from = {
  152. name: self[name] for name in maybe_list(include)
  153. }
  154. def deselect(self, exclude):
  155. """Deselect queues so that they will not be consumed from.
  156. Arguments:
  157. exclude (Sequence[str], str): Names of queues to avoid
  158. consuming from.
  159. """
  160. if exclude:
  161. exclude = maybe_list(exclude)
  162. if self._consume_from is None:
  163. # using selection
  164. return self.select(k for k in self if k not in exclude)
  165. # using all queues
  166. for queue in exclude:
  167. self._consume_from.pop(queue, None)
  168. def new_missing(self, name):
  169. return Queue(name, self.autoexchange(name), name)
  170. @property
  171. def consume_from(self):
  172. if self._consume_from is not None:
  173. return self._consume_from
  174. return self
  175. class AMQP:
  176. Connection = Connection
  177. Consumer = Consumer
  178. Producer = Producer
  179. #: compat alias to Connection
  180. BrokerConnection = Connection
  181. queues_cls = Queues
  182. #: Cached and prepared routing table.
  183. _rtable = None
  184. #: Underlying producer pool instance automatically
  185. #: set by the :attr:`producer_pool`.
  186. _producer_pool = None
  187. # Exchange class/function used when defining automatic queues.
  188. # E.g. you can use ``autoexchange = lambda n: None`` to use the
  189. # AMQP default exchange, which is a shortcut to bypass routing
  190. # and instead send directly to the queue named in the routing key.
  191. autoexchange = None
  192. #: Max size of positional argument representation used for
  193. #: logging purposes.
  194. argsrepr_maxsize = 1024
  195. #: Max size of keyword argument representation used for logging purposes.
  196. kwargsrepr_maxsize = 1024
  197. def __init__(self, app):
  198. self.app = app
  199. self.task_protocols = {
  200. 1: self.as_task_v1,
  201. 2: self.as_task_v2,
  202. }
  203. @cached_property
  204. def create_task_message(self):
  205. return self.task_protocols[self.app.conf.task_protocol]
  206. @cached_property
  207. def send_task_message(self):
  208. return self._create_task_sender()
  209. def Queues(self, queues, create_missing=None, ha_policy=None,
  210. autoexchange=None, max_priority=None):
  211. """Create new :class:`Queues` instance, using queue defaults
  212. from the current configuration."""
  213. conf = self.app.conf
  214. if create_missing is None:
  215. create_missing = conf.task_create_missing_queues
  216. if ha_policy is None:
  217. ha_policy = conf.task_queue_ha_policy
  218. if max_priority is None:
  219. max_priority = conf.task_queue_max_priority
  220. if not queues and conf.task_default_queue:
  221. queues = (Queue(conf.task_default_queue,
  222. exchange=self.default_exchange,
  223. routing_key=conf.task_default_routing_key),)
  224. autoexchange = (self.autoexchange if autoexchange is None
  225. else autoexchange)
  226. return self.queues_cls(
  227. queues, self.default_exchange, create_missing,
  228. ha_policy, autoexchange, max_priority,
  229. )
  230. def Router(self, queues=None, create_missing=None):
  231. """Return the current task router."""
  232. return _routes.Router(self.routes, queues or self.queues,
  233. self.app.either('task_create_missing_queues',
  234. create_missing), app=self.app)
  235. def flush_routes(self):
  236. self._rtable = _routes.prepare(self.app.conf.task_routes)
  237. def TaskConsumer(self, channel, queues=None, accept=None, **kw):
  238. if accept is None:
  239. accept = self.app.conf.accept_content
  240. return self.Consumer(
  241. channel, accept=accept,
  242. queues=queues or list(self.queues.consume_from.values()),
  243. **kw
  244. )
  245. def as_task_v2(self, task_id, name, args=None, kwargs=None,
  246. countdown=None, eta=None, group_id=None,
  247. expires=None, retries=0, chord=None,
  248. callbacks=None, errbacks=None, reply_to=None,
  249. time_limit=None, soft_time_limit=None,
  250. create_sent_event=False, root_id=None, parent_id=None,
  251. shadow=None, chain=None, now=None, timezone=None,
  252. origin=None, argsrepr=None, kwargsrepr=None):
  253. args = args or ()
  254. kwargs = kwargs or {}
  255. if not isinstance(args, (list, tuple)):
  256. raise TypeError('task args must be a list or tuple')
  257. if not isinstance(kwargs, Mapping):
  258. raise TypeError('task keyword arguments must be a mapping')
  259. if countdown: # convert countdown to ETA
  260. self._verify_seconds(countdown, 'countdown')
  261. now = now or self.app.now()
  262. timezone = timezone or self.app.timezone
  263. eta = maybe_make_aware(
  264. now + timedelta(seconds=countdown), tz=timezone,
  265. )
  266. if isinstance(expires, numbers.Real):
  267. self._verify_seconds(expires, 'expires')
  268. now = now or self.app.now()
  269. timezone = timezone or self.app.timezone
  270. expires = maybe_make_aware(
  271. now + timedelta(seconds=expires), tz=timezone,
  272. )
  273. eta = eta and eta.isoformat()
  274. expires = expires and expires.isoformat()
  275. if argsrepr is None:
  276. argsrepr = saferepr(args, self.argsrepr_maxsize)
  277. if kwargsrepr is None:
  278. kwargsrepr = saferepr(kwargs, self.kwargsrepr_maxsize)
  279. if JSON_NEEDS_UNICODE_KEYS: # pragma: no cover
  280. if callbacks:
  281. callbacks = [utf8dict(callback) for callback in callbacks]
  282. if errbacks:
  283. errbacks = [utf8dict(errback) for errback in errbacks]
  284. if chord:
  285. chord = utf8dict(chord)
  286. return task_message(
  287. headers={
  288. 'lang': 'py',
  289. 'task': name,
  290. 'id': task_id,
  291. 'eta': eta,
  292. 'expires': expires,
  293. 'group': group_id,
  294. 'retries': retries,
  295. 'timelimit': [time_limit, soft_time_limit],
  296. 'root_id': root_id,
  297. 'parent_id': parent_id,
  298. 'argsrepr': argsrepr,
  299. 'kwargsrepr': kwargsrepr,
  300. 'origin': origin or anon_nodename()
  301. },
  302. properties={
  303. 'correlation_id': task_id,
  304. 'reply_to': reply_to or '',
  305. },
  306. body=(
  307. args, kwargs, {
  308. 'callbacks': callbacks,
  309. 'errbacks': errbacks,
  310. 'chain': chain,
  311. 'chord': chord,
  312. },
  313. ),
  314. sent_event={
  315. 'uuid': task_id,
  316. 'root_id': root_id,
  317. 'parent_id': parent_id,
  318. 'name': name,
  319. 'args': argsrepr,
  320. 'kwargs': kwargsrepr,
  321. 'retries': retries,
  322. 'eta': eta,
  323. 'expires': expires,
  324. } if create_sent_event else None,
  325. )
  326. def as_task_v1(self, task_id, name, args=None, kwargs=None,
  327. countdown=None, eta=None, group_id=None,
  328. expires=None, retries=0,
  329. chord=None, callbacks=None, errbacks=None, reply_to=None,
  330. time_limit=None, soft_time_limit=None,
  331. create_sent_event=False, root_id=None, parent_id=None,
  332. shadow=None, now=None, timezone=None):
  333. args = args or ()
  334. kwargs = kwargs or {}
  335. utc = self.utc
  336. if not isinstance(args, (list, tuple)):
  337. raise ValueError('task args must be a list or tuple')
  338. if not isinstance(kwargs, Mapping):
  339. raise ValueError('task keyword arguments must be a mapping')
  340. if countdown: # convert countdown to ETA
  341. self._verify_seconds(countdown, 'countdown')
  342. now = now or self.app.now()
  343. timezone = timezone or self.app.timezone
  344. eta = now + timedelta(seconds=countdown)
  345. if utc:
  346. eta = to_utc(eta).astimezone(timezone)
  347. if isinstance(expires, numbers.Real):
  348. self._verify_seconds(expires, 'expires')
  349. now = now or self.app.now()
  350. timezone = timezone or self.app.timezone
  351. expires = now + timedelta(seconds=expires)
  352. if utc:
  353. expires = to_utc(expires).astimezone(timezone)
  354. eta = eta and eta.isoformat()
  355. expires = expires and expires.isoformat()
  356. if JSON_NEEDS_UNICODE_KEYS: # pragma: no cover
  357. if callbacks:
  358. callbacks = [utf8dict(callback) for callback in callbacks]
  359. if errbacks:
  360. errbacks = [utf8dict(errback) for errback in errbacks]
  361. if chord:
  362. chord = utf8dict(chord)
  363. return task_message(
  364. headers={},
  365. properties={
  366. 'correlation_id': task_id,
  367. 'reply_to': reply_to or '',
  368. },
  369. body={
  370. 'task': name,
  371. 'id': task_id,
  372. 'args': args,
  373. 'kwargs': kwargs,
  374. 'group': group_id,
  375. 'retries': retries,
  376. 'eta': eta,
  377. 'expires': expires,
  378. 'utc': utc,
  379. 'callbacks': callbacks,
  380. 'errbacks': errbacks,
  381. 'timelimit': (time_limit, soft_time_limit),
  382. 'taskset': group_id,
  383. 'chord': chord,
  384. },
  385. sent_event={
  386. 'uuid': task_id,
  387. 'name': name,
  388. 'args': saferepr(args),
  389. 'kwargs': saferepr(kwargs),
  390. 'retries': retries,
  391. 'eta': eta,
  392. 'expires': expires,
  393. } if create_sent_event else None,
  394. )
  395. def _verify_seconds(self, s, what):
  396. if s < INT_MIN:
  397. raise ValueError('%s is out of range: %r' % (what, s))
  398. return s
  399. def _create_task_sender(self):
  400. default_retry = self.app.conf.task_publish_retry
  401. default_policy = self.app.conf.task_publish_retry_policy
  402. default_delivery_mode = self.app.conf.task_default_delivery_mode
  403. default_queue = self.default_queue
  404. queues = self.queues
  405. send_before_publish = signals.before_task_publish.send
  406. before_receivers = signals.before_task_publish.receivers
  407. send_after_publish = signals.after_task_publish.send
  408. after_receivers = signals.after_task_publish.receivers
  409. send_task_sent = signals.task_sent.send # XXX compat
  410. sent_receivers = signals.task_sent.receivers
  411. default_evd = self._event_dispatcher
  412. default_exchange = self.default_exchange
  413. default_rkey = self.app.conf.task_default_routing_key
  414. default_serializer = self.app.conf.task_serializer
  415. default_compressor = self.app.conf.result_compression
  416. def send_task_message(producer, name, message,
  417. exchange=None, routing_key=None, queue=None,
  418. event_dispatcher=None,
  419. retry=None, retry_policy=None,
  420. serializer=None, delivery_mode=None,
  421. compression=None, declare=None,
  422. headers=None, exchange_type=None, **kwargs):
  423. retry = default_retry if retry is None else retry
  424. headers2, properties, body, sent_event = message
  425. if headers:
  426. headers2.update(headers)
  427. if kwargs:
  428. properties.update(kwargs)
  429. qname = queue
  430. if queue is None and exchange is None:
  431. queue = default_queue
  432. if queue is not None:
  433. if isinstance(queue, str):
  434. qname, queue = queue, queues[queue]
  435. else:
  436. qname = queue.name
  437. if delivery_mode is None:
  438. try:
  439. delivery_mode = queue.exchange.delivery_mode
  440. except AttributeError:
  441. pass
  442. delivery_mode = delivery_mode or default_delivery_mode
  443. if exchange_type is None:
  444. try:
  445. exchange_type = queue.exchange.type
  446. except AttributeError:
  447. exchange_type = 'direct'
  448. if not exchange and not routing_key and exchange_type == 'direct':
  449. exchange, routing_key = '', qname
  450. else:
  451. exchange = exchange or queue.exchange.name or default_exchange
  452. routing_key = routing_key or queue.routing_key or default_rkey
  453. if declare is None and queue and not isinstance(queue, Broadcast):
  454. declare = [queue]
  455. # merge default and custom policy
  456. retry = default_retry if retry is None else retry
  457. _rp = (dict(default_policy, **retry_policy) if retry_policy
  458. else default_policy)
  459. if before_receivers:
  460. send_before_publish(
  461. sender=name, body=body,
  462. exchange=exchange, routing_key=routing_key,
  463. declare=declare, headers=headers2,
  464. properties=kwargs, retry_policy=retry_policy,
  465. )
  466. ret = producer.publish(
  467. body,
  468. exchange=exchange,
  469. routing_key=routing_key,
  470. serializer=serializer or default_serializer,
  471. compression=compression or default_compressor,
  472. retry=retry, retry_policy=_rp,
  473. delivery_mode=delivery_mode, declare=declare,
  474. headers=headers2,
  475. **properties
  476. )
  477. if after_receivers:
  478. send_after_publish(sender=name, body=body, headers=headers2,
  479. exchange=exchange, routing_key=routing_key)
  480. if sent_receivers: # XXX deprecated
  481. send_task_sent(sender=name, task_id=body['id'], task=name,
  482. args=body['args'], kwargs=body['kwargs'],
  483. eta=body['eta'], taskset=body['taskset'])
  484. if sent_event:
  485. evd = event_dispatcher or default_evd
  486. exname = exchange
  487. if isinstance(exname, Exchange):
  488. exname = exname.name
  489. sent_event.update({
  490. 'queue': qname,
  491. 'exchange': exname,
  492. 'routing_key': routing_key,
  493. })
  494. evd.publish('task-sent', sent_event,
  495. self, retry=retry, retry_policy=retry_policy)
  496. return ret
  497. return send_task_message
  498. @cached_property
  499. def default_queue(self):
  500. return self.queues[self.app.conf.task_default_queue]
  501. @cached_property
  502. def queues(self):
  503. """Queue name⇒ declaration mapping."""
  504. return self.Queues(self.app.conf.task_queues)
  505. @queues.setter # noqa
  506. def queues(self, queues):
  507. return self.Queues(queues)
  508. @property
  509. def routes(self):
  510. if self._rtable is None:
  511. self.flush_routes()
  512. return self._rtable
  513. @cached_property
  514. def router(self):
  515. return self.Router()
  516. @property
  517. def producer_pool(self):
  518. if self._producer_pool is None:
  519. self._producer_pool = pools.producers[
  520. self.app.connection_for_write()]
  521. self._producer_pool.limit = self.app.pool.limit
  522. return self._producer_pool
  523. publisher_pool = producer_pool # compat alias
  524. @cached_property
  525. def default_exchange(self):
  526. return Exchange(self.app.conf.task_default_exchange,
  527. self.app.conf.task_default_exchange_type)
  528. @cached_property
  529. def utc(self):
  530. return self.app.conf.enable_utc
  531. @cached_property
  532. def _event_dispatcher(self):
  533. # We call Dispatcher.publish with a custom producer
  534. # so don't need the diuspatcher to be enabled.
  535. return self.app.events.Dispatcher(enabled=False)