messaging.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. """Sending and receiving messages."""
  2. from __future__ import absolute_import, unicode_literals
  3. from itertools import count
  4. from .common import maybe_declare
  5. from .compression import compress
  6. from .connection import maybe_channel, is_connection
  7. from .entity import Exchange, Queue, maybe_delivery_mode
  8. from .exceptions import ContentDisallowed
  9. from .five import items, python_2_unicode_compatible, text_t, values
  10. from .serialization import dumps, prepare_accept_content
  11. from .utils.functional import ChannelPromise, maybe_list
  12. __all__ = ('Exchange', 'Queue', 'Producer', 'Consumer')
  13. @python_2_unicode_compatible
  14. class Producer(object):
  15. """Message Producer.
  16. Arguments:
  17. channel (kombu.Connection, ChannelT): Connection or channel.
  18. exchange (kombu.entity.Exchange, str): Optional default exchange.
  19. routing_key (str): Optional default routing key.
  20. serializer (str): Default serializer. Default is `"json"`.
  21. compression (str): Default compression method.
  22. Default is no compression.
  23. auto_declare (bool): Automatically declare the default exchange
  24. at instantiation. Default is :const:`True`.
  25. on_return (Callable): Callback to call for undeliverable messages,
  26. when the `mandatory` or `immediate` arguments to
  27. :meth:`publish` is used. This callback needs the following
  28. signature: `(exception, exchange, routing_key, message)`.
  29. Note that the producer needs to drain events to use this feature.
  30. """
  31. #: Default exchange
  32. exchange = None
  33. #: Default routing key.
  34. routing_key = ''
  35. #: Default serializer to use. Default is JSON.
  36. serializer = None
  37. #: Default compression method. Disabled by default.
  38. compression = None
  39. #: By default, if a defualt exchange is set,
  40. #: that exchange will be declare when publishing a message.
  41. auto_declare = True
  42. #: Basic return callback.
  43. on_return = None
  44. #: Set if channel argument was a Connection instance (using
  45. #: default_channel).
  46. __connection__ = None
  47. def __init__(self, channel, exchange=None, routing_key=None,
  48. serializer=None, auto_declare=None, compression=None,
  49. on_return=None):
  50. self._channel = channel
  51. self.exchange = exchange
  52. self.routing_key = routing_key or self.routing_key
  53. self.serializer = serializer or self.serializer
  54. self.compression = compression or self.compression
  55. self.on_return = on_return or self.on_return
  56. self._channel_promise = None
  57. if self.exchange is None:
  58. self.exchange = Exchange('')
  59. if auto_declare is not None:
  60. self.auto_declare = auto_declare
  61. if self._channel:
  62. self.revive(self._channel)
  63. def __repr__(self):
  64. return '<Producer: {0._channel}>'.format(self)
  65. def __reduce__(self):
  66. return self.__class__, self.__reduce_args__()
  67. def __reduce_args__(self):
  68. return (None, self.exchange, self.routing_key, self.serializer,
  69. self.auto_declare, self.compression)
  70. def declare(self):
  71. """Declare the exchange.
  72. Note:
  73. This happens automatically at instantiation when
  74. the :attr:`auto_declare` flag is enabled.
  75. """
  76. if self.exchange.name:
  77. self.exchange.declare()
  78. def maybe_declare(self, entity, retry=False, **retry_policy):
  79. """Declare exchange if not already declared during this session."""
  80. if entity:
  81. return maybe_declare(entity, self.channel, retry, **retry_policy)
  82. def _delivery_details(self, exchange, delivery_mode=None,
  83. maybe_delivery_mode=maybe_delivery_mode,
  84. Exchange=Exchange):
  85. if isinstance(exchange, Exchange):
  86. return exchange.name, maybe_delivery_mode(
  87. delivery_mode or exchange.delivery_mode,
  88. )
  89. # exchange is string, so inherit the delivery
  90. # mode of our default exchange.
  91. return exchange, maybe_delivery_mode(
  92. delivery_mode or self.exchange.delivery_mode,
  93. )
  94. def publish(self, body, routing_key=None, delivery_mode=None,
  95. mandatory=False, immediate=False, priority=0,
  96. content_type=None, content_encoding=None, serializer=None,
  97. headers=None, compression=None, exchange=None, retry=False,
  98. retry_policy=None, declare=None, expiration=None,
  99. **properties):
  100. """Publish message to the specified exchange.
  101. Arguments:
  102. body (Any): Message body.
  103. routing_key (str): Message routing key.
  104. delivery_mode (enum): See :attr:`delivery_mode`.
  105. mandatory (bool): Currently not supported.
  106. immediate (bool): Currently not supported.
  107. priority (int): Message priority. A number between 0 and 9.
  108. content_type (str): Content type. Default is auto-detect.
  109. content_encoding (str): Content encoding. Default is auto-detect.
  110. serializer (str): Serializer to use. Default is auto-detect.
  111. compression (str): Compression method to use. Default is none.
  112. headers (Dict): Mapping of arbitrary headers to pass along
  113. with the message body.
  114. exchange (kombu.entity.Exchange, str): Override the exchange.
  115. Note that this exchange must have been declared.
  116. declare (Sequence[EntityT]): Optional list of required entities
  117. that must have been declared before publishing the message.
  118. The entities will be declared using
  119. :func:`~kombu.common.maybe_declare`.
  120. retry (bool): Retry publishing, or declaring entities if the
  121. connection is lost.
  122. retry_policy (Dict): Retry configuration, this is the keywords
  123. supported by :meth:`~kombu.Connection.ensure`.
  124. expiration (float): A TTL in seconds can be specified per message.
  125. Default is no expiration.
  126. **properties (Any): Additional message properties, see AMQP spec.
  127. """
  128. _publish = self._publish
  129. declare = [] if declare is None else declare
  130. headers = {} if headers is None else headers
  131. retry_policy = {} if retry_policy is None else retry_policy
  132. routing_key = self.routing_key if routing_key is None else routing_key
  133. compression = self.compression if compression is None else compression
  134. exchange_name, properties['delivery_mode'] = self._delivery_details(
  135. exchange or self.exchange, delivery_mode,
  136. )
  137. if expiration is not None:
  138. properties['expiration'] = str(int(expiration * 1000))
  139. body, content_type, content_encoding = self._prepare(
  140. body, serializer, content_type, content_encoding,
  141. compression, headers)
  142. if self.auto_declare and self.exchange.name:
  143. if self.exchange not in declare:
  144. # XXX declare should be a Set.
  145. declare.append(self.exchange)
  146. if retry:
  147. _publish = self.connection.ensure(self, _publish, **retry_policy)
  148. return _publish(
  149. body, priority, content_type, content_encoding,
  150. headers, properties, routing_key, mandatory, immediate,
  151. exchange_name, declare,
  152. )
  153. def _publish(self, body, priority, content_type, content_encoding,
  154. headers, properties, routing_key, mandatory,
  155. immediate, exchange, declare):
  156. channel = self.channel
  157. message = channel.prepare_message(
  158. body, priority, content_type,
  159. content_encoding, headers, properties,
  160. )
  161. if declare:
  162. maybe_declare = self.maybe_declare
  163. [maybe_declare(entity) for entity in declare]
  164. # handle autogenerated queue names for reply_to
  165. reply_to = properties.get('reply_to')
  166. if isinstance(reply_to, Queue):
  167. properties['reply_to'] = reply_to.name
  168. return channel.basic_publish(
  169. message,
  170. exchange=exchange, routing_key=routing_key,
  171. mandatory=mandatory, immediate=immediate,
  172. )
  173. def _get_channel(self):
  174. channel = self._channel
  175. if isinstance(channel, ChannelPromise):
  176. channel = self._channel = channel()
  177. self.exchange.revive(channel)
  178. if self.on_return:
  179. channel.events['basic_return'].add(self.on_return)
  180. return channel
  181. def _set_channel(self, channel):
  182. self._channel = channel
  183. channel = property(_get_channel, _set_channel)
  184. def revive(self, channel):
  185. """Revive the producer after connection loss."""
  186. if is_connection(channel):
  187. connection = channel
  188. self.__connection__ = connection
  189. channel = ChannelPromise(lambda: connection.default_channel)
  190. if isinstance(channel, ChannelPromise):
  191. self._channel = channel
  192. self.exchange = self.exchange(channel)
  193. else:
  194. # Channel already concrete
  195. self._channel = channel
  196. if self.on_return:
  197. self._channel.events['basic_return'].add(self.on_return)
  198. self.exchange = self.exchange(channel)
  199. def __enter__(self):
  200. return self
  201. def __exit__(self, *exc_info):
  202. self.release()
  203. def release(self):
  204. pass
  205. close = release
  206. def _prepare(self, body, serializer=None, content_type=None,
  207. content_encoding=None, compression=None, headers=None):
  208. # No content_type? Then we're serializing the data internally.
  209. if not content_type:
  210. serializer = serializer or self.serializer
  211. (content_type, content_encoding,
  212. body) = dumps(body, serializer=serializer)
  213. else:
  214. # If the programmer doesn't want us to serialize,
  215. # make sure content_encoding is set.
  216. if isinstance(body, text_t):
  217. if not content_encoding:
  218. content_encoding = 'utf-8'
  219. body = body.encode(content_encoding)
  220. # If they passed in a string, we can't know anything
  221. # about it. So assume it's binary data.
  222. elif not content_encoding:
  223. content_encoding = 'binary'
  224. if compression:
  225. body, headers['compression'] = compress(body, compression)
  226. return body, content_type, content_encoding
  227. @property
  228. def connection(self):
  229. try:
  230. return self.__connection__ or self.channel.connection.client
  231. except AttributeError:
  232. pass
  233. @python_2_unicode_compatible
  234. class Consumer(object):
  235. """Message consumer.
  236. Arguments:
  237. channel (kombu.Connection, ChannelT): see :attr:`channel`.
  238. queues (Sequence[kombu.Queue]): see :attr:`queues`.
  239. no_ack (bool): see :attr:`no_ack`.
  240. auto_declare (bool): see :attr:`auto_declare`
  241. callbacks (Sequence[Callable]): see :attr:`callbacks`.
  242. on_message (Callable): See :attr:`on_message`
  243. on_decode_error (Callable): see :attr:`on_decode_error`.
  244. prefetch_count (int): see :attr:`prefetch_count`.
  245. """
  246. ContentDisallowed = ContentDisallowed
  247. #: The connection/channel to use for this consumer.
  248. channel = None
  249. #: A single :class:`~kombu.Queue`, or a list of queues to
  250. #: consume from.
  251. queues = None
  252. #: Flag for automatic message acknowledgment.
  253. #: If enabled the messages are automatically acknowledged by the
  254. #: broker. This can increase performance but means that you
  255. #: have no control of when the message is removed.
  256. #:
  257. #: Disabled by default.
  258. no_ack = None
  259. #: By default all entities will be declared at instantiation, if you
  260. #: want to handle this manually you can set this to :const:`False`.
  261. auto_declare = True
  262. #: List of callbacks called in order when a message is received.
  263. #:
  264. #: The signature of the callbacks must take two arguments:
  265. #: `(body, message)`, which is the decoded message body and
  266. #: the :class:`~kombu.Message` instance.
  267. callbacks = None
  268. #: Optional function called whenever a message is received.
  269. #:
  270. #: When defined this function will be called instead of the
  271. #: :meth:`receive` method, and :attr:`callbacks` will be disabled.
  272. #:
  273. #: So this can be used as an alternative to :attr:`callbacks` when
  274. #: you don't want the body to be automatically decoded.
  275. #: Note that the message will still be decompressed if the message
  276. #: has the ``compression`` header set.
  277. #:
  278. #: The signature of the callback must take a single argument,
  279. #: which is the :class:`~kombu.Message` object.
  280. #:
  281. #: Also note that the ``message.body`` attribute, which is the raw
  282. #: contents of the message body, may in some cases be a read-only
  283. #: :class:`buffer` object.
  284. on_message = None
  285. #: Callback called when a message can't be decoded.
  286. #:
  287. #: The signature of the callback must take two arguments: `(message,
  288. #: exc)`, which is the message that can't be decoded and the exception
  289. #: that occurred while trying to decode it.
  290. on_decode_error = None
  291. #: List of accepted content-types.
  292. #:
  293. #: An exception will be raised if the consumer receives
  294. #: a message with an untrusted content type.
  295. #: By default all content-types are accepted, but not if
  296. #: :func:`kombu.disable_untrusted_serializers` was called,
  297. #: in which case only json is allowed.
  298. accept = None
  299. #: Initial prefetch count
  300. #:
  301. #: If set, the consumer will set the prefetch_count QoS value at startup.
  302. #: Can also be changed using :meth:`qos`.
  303. prefetch_count = None
  304. #: Mapping of queues we consume from.
  305. _queues = None
  306. _tags = count(1) # global
  307. def __init__(self, channel, queues=None, no_ack=None, auto_declare=None,
  308. callbacks=None, on_decode_error=None, on_message=None,
  309. accept=None, prefetch_count=None, tag_prefix=None):
  310. self.channel = channel
  311. self.queues = maybe_list(queues or [])
  312. self.no_ack = self.no_ack if no_ack is None else no_ack
  313. self.callbacks = (self.callbacks or [] if callbacks is None
  314. else callbacks)
  315. self.on_message = on_message
  316. self.tag_prefix = tag_prefix
  317. self._active_tags = {}
  318. if auto_declare is not None:
  319. self.auto_declare = auto_declare
  320. if on_decode_error is not None:
  321. self.on_decode_error = on_decode_error
  322. self.accept = prepare_accept_content(accept)
  323. self.prefetch_count = prefetch_count
  324. if self.channel:
  325. self.revive(self.channel)
  326. @property
  327. def queues(self):
  328. return list(self._queues.values())
  329. @queues.setter
  330. def queues(self, queues):
  331. self._queues = {q.name: q for q in queues}
  332. def revive(self, channel):
  333. """Revive consumer after connection loss."""
  334. self._active_tags.clear()
  335. channel = self.channel = maybe_channel(channel)
  336. # modify dict size while iterating over it is not allowed
  337. for qname, queue in list(items(self._queues)):
  338. # name may have changed after declare
  339. self._queues.pop(qname, None)
  340. queue = self._queues[queue.name] = queue(self.channel)
  341. queue.revive(channel)
  342. if self.auto_declare:
  343. self.declare()
  344. if self.prefetch_count is not None:
  345. self.qos(prefetch_count=self.prefetch_count)
  346. def declare(self):
  347. """Declare queues, exchanges and bindings.
  348. Note:
  349. This is done automatically at instantiation
  350. when :attr:`auto_declare` is set.
  351. """
  352. for queue in values(self._queues):
  353. queue.declare()
  354. def register_callback(self, callback):
  355. """Register a new callback to be called when a message is received.
  356. Note:
  357. The signature of the callback needs to accept two arguments:
  358. `(body, message)`, which is the decoded message body
  359. and the :class:`~kombu.Message` instance.
  360. """
  361. self.callbacks.append(callback)
  362. def __enter__(self):
  363. self.consume()
  364. return self
  365. def __exit__(self, exc_type, exc_val, exc_tb):
  366. if self.channel and self.channel.connection:
  367. conn_errors = self.channel.connection.client.connection_errors
  368. if not isinstance(exc_val, conn_errors):
  369. try:
  370. self.cancel()
  371. except Exception:
  372. pass
  373. def add_queue(self, queue):
  374. """Add a queue to the list of queues to consume from.
  375. Note:
  376. This will not start consuming from the queue,
  377. for that you will have to call :meth:`consume` after.
  378. """
  379. queue = queue(self.channel)
  380. if self.auto_declare:
  381. queue.declare()
  382. self._queues[queue.name] = queue
  383. return queue
  384. def consume(self, no_ack=None):
  385. """Start consuming messages.
  386. Can be called multiple times, but note that while it
  387. will consume from new queues added since the last call,
  388. it will not cancel consuming from removed queues (
  389. use :meth:`cancel_by_queue`).
  390. Arguments:
  391. no_ack (bool): See :attr:`no_ack`.
  392. """
  393. queues = list(values(self._queues))
  394. if queues:
  395. no_ack = self.no_ack if no_ack is None else no_ack
  396. H, T = queues[:-1], queues[-1]
  397. for queue in H:
  398. self._basic_consume(queue, no_ack=no_ack, nowait=True)
  399. self._basic_consume(T, no_ack=no_ack, nowait=False)
  400. def cancel(self):
  401. """End all active queue consumers.
  402. Note:
  403. This does not affect already delivered messages, but it does
  404. mean the server will not send any more messages for this consumer.
  405. """
  406. cancel = self.channel.basic_cancel
  407. for tag in values(self._active_tags):
  408. cancel(tag)
  409. self._active_tags.clear()
  410. close = cancel
  411. def cancel_by_queue(self, queue):
  412. """Cancel consumer by queue name."""
  413. qname = queue.name if isinstance(queue, Queue) else queue
  414. try:
  415. tag = self._active_tags.pop(qname)
  416. except KeyError:
  417. pass
  418. else:
  419. self.channel.basic_cancel(tag)
  420. finally:
  421. self._queues.pop(qname, None)
  422. def consuming_from(self, queue):
  423. """Return :const:`True` if currently consuming from queue'."""
  424. name = queue
  425. if isinstance(queue, Queue):
  426. name = queue.name
  427. return name in self._active_tags
  428. def purge(self):
  429. """Purge messages from all queues.
  430. Warning:
  431. This will *delete all ready messages*, there is no undo operation.
  432. """
  433. return sum(queue.purge() for queue in values(self._queues))
  434. def flow(self, active):
  435. """Enable/disable flow from peer.
  436. This is a simple flow-control mechanism that a peer can use
  437. to avoid overflowing its queues or otherwise finding itself
  438. receiving more messages than it can process.
  439. The peer that receives a request to stop sending content
  440. will finish sending the current content (if any), and then wait
  441. until flow is reactivated.
  442. """
  443. self.channel.flow(active)
  444. def qos(self, prefetch_size=0, prefetch_count=0, apply_global=False):
  445. """Specify quality of service.
  446. The client can request that messages should be sent in
  447. advance so that when the client finishes processing a message,
  448. the following message is already held locally, rather than needing
  449. to be sent down the channel. Prefetching gives a performance
  450. improvement.
  451. The prefetch window is Ignored if the :attr:`no_ack` option is set.
  452. Arguments:
  453. prefetch_size (int): Specify the prefetch window in octets.
  454. The server will send a message in advance if it is equal to
  455. or smaller in size than the available prefetch size (and
  456. also falls within other prefetch limits). May be set to zero,
  457. meaning "no specific limit", although other prefetch limits
  458. may still apply.
  459. prefetch_count (int): Specify the prefetch window in terms of
  460. whole messages.
  461. apply_global (bool): Apply new settings globally on all channels.
  462. """
  463. return self.channel.basic_qos(prefetch_size,
  464. prefetch_count,
  465. apply_global)
  466. def recover(self, requeue=False):
  467. """Redeliver unacknowledged messages.
  468. Asks the broker to redeliver all unacknowledged messages
  469. on the specified channel.
  470. Arguments:
  471. requeue (bool): By default the messages will be redelivered
  472. to the original recipient. With `requeue` set to true, the
  473. server will attempt to requeue the message, potentially then
  474. delivering it to an alternative subscriber.
  475. """
  476. return self.channel.basic_recover(requeue=requeue)
  477. def receive(self, body, message):
  478. """Method called when a message is received.
  479. This dispatches to the registered :attr:`callbacks`.
  480. Arguments:
  481. body (Any): The decoded message body.
  482. message (~kombu.Message): The message instance.
  483. Raises:
  484. NotImplementedError: If no consumer callbacks have been
  485. registered.
  486. """
  487. callbacks = self.callbacks
  488. if not callbacks:
  489. raise NotImplementedError('Consumer does not have any callbacks')
  490. [callback(body, message) for callback in callbacks]
  491. def _basic_consume(self, queue, consumer_tag=None,
  492. no_ack=no_ack, nowait=True):
  493. tag = self._active_tags.get(queue.name)
  494. if tag is None:
  495. tag = self._add_tag(queue, consumer_tag)
  496. queue.consume(tag, self._receive_callback,
  497. no_ack=no_ack, nowait=nowait)
  498. return tag
  499. def _add_tag(self, queue, consumer_tag=None):
  500. tag = consumer_tag or '{0}{1}'.format(
  501. self.tag_prefix, next(self._tags))
  502. self._active_tags[queue.name] = tag
  503. return tag
  504. def _receive_callback(self, message):
  505. accept = self.accept
  506. on_m, channel, decoded = self.on_message, self.channel, None
  507. try:
  508. m2p = getattr(channel, 'message_to_python', None)
  509. if m2p:
  510. message = m2p(message)
  511. if accept is not None:
  512. message.accept = accept
  513. if message.errors:
  514. return message._reraise_error(self.on_decode_error)
  515. decoded = None if on_m else message.decode()
  516. except Exception as exc:
  517. if not self.on_decode_error:
  518. raise
  519. self.on_decode_error(message, exc)
  520. else:
  521. return on_m(message) if on_m else self.receive(decoded, message)
  522. def __repr__(self):
  523. return '<{name}: {0.queues}>'.format(self, name=type(self).__name__)
  524. @property
  525. def connection(self):
  526. try:
  527. return self.channel.connection.client
  528. except AttributeError:
  529. pass