twisted_connection.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. """Using Pika with a Twisted reactor.
  2. The interfaces in this module are Deferred-based when possible. This means that
  3. the connection.channel() method and most of the channel methods return
  4. Deferreds instead of taking a callback argument and that basic_consume()
  5. returns a Twisted DeferredQueue where messages from the server will be
  6. stored. Refer to the docstrings for TwistedProtocolConnection.channel() and the
  7. TwistedChannel class for details.
  8. """
  9. import functools
  10. import logging
  11. from collections import namedtuple
  12. from twisted.internet import (defer, error as twisted_error, reactor, protocol)
  13. from twisted.python.failure import Failure
  14. import pika.connection
  15. from pika import exceptions, spec
  16. from pika.adapters.utils import nbio_interface
  17. from pika.adapters.utils.io_services_utils import check_callback_arg
  18. # Twistisms
  19. # pylint: disable=C0111,C0103
  20. # Other
  21. # pylint: disable=too-many-lines
  22. LOGGER = logging.getLogger(__name__)
  23. class ClosableDeferredQueue(defer.DeferredQueue):
  24. """
  25. Like the normal Twisted DeferredQueue, but after close() is called with an
  26. exception instance all pending Deferreds are errbacked and further attempts
  27. to call get() or put() return a Failure wrapping that exception.
  28. """
  29. def __init__(self, size=None, backlog=None):
  30. self.closed = None
  31. super(ClosableDeferredQueue, self).__init__(size, backlog)
  32. def put(self, obj):
  33. """
  34. Like the original :meth:`DeferredQueue.put` method, but returns an
  35. errback if the queue is closed.
  36. """
  37. if self.closed:
  38. LOGGER.error('Impossible to put to the queue, it is closed.')
  39. return defer.fail(self.closed)
  40. return defer.DeferredQueue.put(self, obj)
  41. def get(self):
  42. """
  43. Returns a Deferred that will fire with the next item in the queue, when
  44. it's available.
  45. The Deferred will errback if the queue is closed.
  46. :returns: Deferred that fires with the next item.
  47. :rtype: Deferred
  48. """
  49. if self.closed:
  50. LOGGER.error('Impossible to get from the queue, it is closed.')
  51. return defer.fail(self.closed)
  52. return defer.DeferredQueue.get(self)
  53. def close(self, reason):
  54. """Closes the queue.
  55. Errback the pending calls to :meth:`get()`.
  56. """
  57. if self.closed:
  58. LOGGER.warning('Queue was already closed with reason: %s.',
  59. self.closed)
  60. self.closed = reason
  61. while self.waiting:
  62. self.waiting.pop().errback(reason)
  63. self.pending = []
  64. ReceivedMessage = namedtuple("ReceivedMessage",
  65. ["channel", "method", "properties", "body"])
  66. class TwistedChannel(object):
  67. """A wrapper around Pika's Channel.
  68. Channel methods that normally take a callback argument are wrapped to
  69. return a Deferred that fires with whatever would be passed to the callback.
  70. If the channel gets closed, all pending Deferreds are errbacked with a
  71. ChannelClosed exception. The returned Deferreds fire with whatever
  72. arguments the callback to the original method would receive.
  73. Some methods like basic_consume and basic_get are wrapped in a special way,
  74. see their docstrings for details.
  75. """
  76. def __init__(self, channel):
  77. self._channel = channel
  78. self._closed = None
  79. self._calls = set()
  80. self._consumers = {}
  81. # Store Basic.Get calls so we can handle GetEmpty replies
  82. self._basic_get_deferred = None
  83. self._channel.add_callback(self._on_getempty, [spec.Basic.GetEmpty],
  84. False)
  85. # We need this mapping to close the ClosableDeferredQueue when a queue
  86. # is deleted.
  87. self._queue_name_to_consumer_tags = {}
  88. # Whether RabbitMQ delivery confirmation has been enabled
  89. self._delivery_confirmation = False
  90. self._delivery_message_id = None
  91. self._deliveries = {}
  92. # Holds a ReceivedMessage object representing a message received via
  93. # Basic.Return in publisher-acknowledgments mode.
  94. self._puback_return = None
  95. self.on_closed = defer.Deferred()
  96. self._channel.add_on_close_callback(self._on_channel_closed)
  97. self._channel.add_on_cancel_callback(
  98. self._on_consumer_cancelled_by_broker)
  99. def __repr__(self):
  100. return '<{cls} channel={chan!r}>'.format(
  101. cls=self.__class__.__name__, chan=self._channel)
  102. def _on_channel_closed(self, _channel, reason):
  103. # enter the closed state
  104. self._closed = reason
  105. # errback all pending calls
  106. for d in self._calls:
  107. d.errback(self._closed)
  108. # close all open queues
  109. for consumer in self._consumers.values():
  110. consumer.close(self._closed)
  111. # release references to stored objects
  112. self._calls = set()
  113. self._consumers = {}
  114. self.on_closed.callback(self._closed)
  115. def _on_consumer_cancelled_by_broker(self, method_frame):
  116. """Called by impl when broker cancels consumer via Basic.Cancel.
  117. This is a RabbitMQ-specific feature. The circumstances include deletion
  118. of queue being consumed as well as failure of a HA node responsible for
  119. the queue being consumed.
  120. :param pika.frame.Method method_frame: method frame with the
  121. `spec.Basic.Cancel` method
  122. """
  123. return self._on_consumer_cancelled(method_frame)
  124. def _on_consumer_cancelled(self, frame):
  125. """Called when the broker cancels a consumer via Basic.Cancel or when
  126. the broker responds to a Basic.Cancel request by Basic.CancelOk.
  127. :param pika.frame.Method frame: method frame with the
  128. `spec.Basic.Cancel` or `spec.Basic.CancelOk` method
  129. """
  130. consumer_tag = frame.method.consumer_tag
  131. if consumer_tag not in self._consumers:
  132. # Could be cancelled by user or broker earlier
  133. LOGGER.warning('basic_cancel - consumer not found: %s',
  134. consumer_tag)
  135. return frame
  136. self._consumers[consumer_tag].close(exceptions.ConsumerCancelled())
  137. del self._consumers[consumer_tag]
  138. # Remove from the queue-to-ctags index:
  139. for ctags in self._queue_name_to_consumer_tags.values():
  140. try:
  141. ctags.remove(consumer_tag)
  142. except KeyError:
  143. continue
  144. return frame
  145. def _on_getempty(self, _method_frame):
  146. """Callback the Basic.Get deferred with None.
  147. """
  148. if self._basic_get_deferred is None:
  149. LOGGER.warning("Got Basic.GetEmpty but no Basic.Get calls "
  150. "were pending.")
  151. return
  152. self._basic_get_deferred.callback(None)
  153. def _wrap_channel_method(self, name):
  154. """Wrap Pika's Channel method to make it return a Deferred that fires
  155. when the method completes and errbacks if the channel gets closed. If
  156. the original method's callback would receive more than one argument,
  157. the Deferred fires with a tuple of argument values.
  158. """
  159. method = getattr(self._channel, name)
  160. @functools.wraps(method)
  161. def wrapped(*args, **kwargs):
  162. if self._closed:
  163. return defer.fail(self._closed)
  164. d = defer.Deferred()
  165. self._calls.add(d)
  166. d.addCallback(self._clear_call, d)
  167. def single_argument(*args):
  168. """
  169. Make sure that the deferred is called with a single argument.
  170. In case the original callback fires with more than one, convert
  171. to a tuple.
  172. """
  173. if len(args) > 1:
  174. d.callback(tuple(args))
  175. else:
  176. d.callback(*args)
  177. kwargs['callback'] = single_argument
  178. try:
  179. method(*args, **kwargs)
  180. except Exception: # pylint: disable=W0703
  181. return defer.fail()
  182. return d
  183. return wrapped
  184. def _clear_call(self, ret, d):
  185. self._calls.discard(d)
  186. return ret
  187. # Public Channel attributes
  188. @property
  189. def channel_number(self):
  190. return self._channel.channel_number
  191. @property
  192. def connection(self):
  193. return self._channel.connection
  194. @property
  195. def is_closed(self):
  196. """Returns True if the channel is closed.
  197. :rtype: bool
  198. """
  199. return self._channel.is_closed
  200. @property
  201. def is_closing(self):
  202. """Returns True if client-initiated closing of the channel is in
  203. progress.
  204. :rtype: bool
  205. """
  206. return self._channel.is_closing
  207. @property
  208. def is_open(self):
  209. """Returns True if the channel is open.
  210. :rtype: bool
  211. """
  212. return self._channel.is_open
  213. @property
  214. def flow_active(self):
  215. return self._channel.flow_active
  216. @property
  217. def consumer_tags(self):
  218. return self._channel.consumer_tags
  219. # Deferred-equivalents of public Channel methods
  220. def callback_deferred(self, deferred, replies):
  221. """Pass in a Deferred and a list replies from the RabbitMQ broker which
  222. you'd like the Deferred to be callbacked on with the frame as callback
  223. value.
  224. :param Deferred deferred: The Deferred to callback
  225. :param list replies: The replies to callback on
  226. """
  227. self._channel.add_callback(deferred.callback, replies)
  228. # Public Channel methods
  229. def add_on_return_callback(self, callback):
  230. """Pass a callback function that will be called when a published
  231. message is rejected and returned by the server via `Basic.Return`.
  232. :param callable callback: The method to call on callback with the
  233. message as only argument. The message is a named tuple with
  234. the following attributes:
  235. channel: this TwistedChannel
  236. method: pika.spec.Basic.Return
  237. properties: pika.spec.BasicProperties
  238. body: bytes
  239. """
  240. self._channel.add_on_return_callback(
  241. lambda _channel, method, properties, body: callback(
  242. ReceivedMessage(
  243. channel=self,
  244. method=method,
  245. properties=properties,
  246. body=body,
  247. )
  248. )
  249. )
  250. def basic_ack(self, delivery_tag=0, multiple=False):
  251. """Acknowledge one or more messages. When sent by the client, this
  252. method acknowledges one or more messages delivered via the Deliver or
  253. Get-Ok methods. When sent by server, this method acknowledges one or
  254. more messages published with the Publish method on a channel in
  255. confirm mode. The acknowledgement can be for a single message or a
  256. set of messages up to and including a specific message.
  257. :param integer delivery_tag: int/long The server-assigned delivery tag
  258. :param bool multiple: If set to True, the delivery tag is treated as
  259. "up to and including", so that multiple messages
  260. can be acknowledged with a single method. If set
  261. to False, the delivery tag refers to a single
  262. message. If the multiple field is 1, and the
  263. delivery tag is zero, this indicates
  264. acknowledgement of all outstanding messages.
  265. """
  266. return self._channel.basic_ack(
  267. delivery_tag=delivery_tag, multiple=multiple)
  268. def basic_cancel(self, consumer_tag=''):
  269. """This method cancels a consumer. This does not affect already
  270. delivered messages, but it does mean the server will not send any more
  271. messages for that consumer. The client may receive an arbitrary number
  272. of messages in between sending the cancel method and receiving the
  273. cancel-ok reply. It may also be sent from the server to the client in
  274. the event of the consumer being unexpectedly cancelled (i.e. cancelled
  275. for any reason other than the server receiving the corresponding
  276. basic.cancel from the client). This allows clients to be notified of
  277. the loss of consumers due to events such as queue deletion.
  278. This method wraps :meth:`Channel.basic_cancel
  279. <pika.channel.Channel.basic_cancel>` and closes any deferred queue
  280. associated with that consumer.
  281. :param str consumer_tag: Identifier for the consumer
  282. :returns: Deferred that fires on the Basic.CancelOk response
  283. :rtype: Deferred
  284. :raises ValueError:
  285. """
  286. wrapped = self._wrap_channel_method('basic_cancel')
  287. d = wrapped(consumer_tag=consumer_tag)
  288. return d.addCallback(self._on_consumer_cancelled)
  289. def basic_consume(self,
  290. queue,
  291. auto_ack=False,
  292. exclusive=False,
  293. consumer_tag=None,
  294. arguments=None):
  295. """Consume from a server queue.
  296. Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds
  297. messages for the consumer_tag to a
  298. :class:`ClosableDeferredQueue`. If you do not pass in a
  299. consumer_tag, one will be automatically generated for you.
  300. For more information on basic_consume, see:
  301. Tutorial 2 at http://www.rabbitmq.com/getstarted.html
  302. http://www.rabbitmq.com/confirms.html
  303. http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume
  304. :param str queue: The queue to consume from. Use the empty string to
  305. specify the most recent server-named queue for this channel.
  306. :param bool auto_ack: if set to True, automatic acknowledgement mode
  307. will be used (see http://www.rabbitmq.com/confirms.html). This
  308. corresponds with the 'no_ack' parameter in the basic.consume AMQP
  309. 0.9.1 method
  310. :param bool exclusive: Don't allow other consumers on the queue
  311. :param str consumer_tag: Specify your own consumer tag
  312. :param dict arguments: Custom key/value pair arguments for the consumer
  313. :returns: Deferred that fires with a tuple
  314. ``(queue_object, consumer_tag)``. The Deferred will errback with an
  315. instance of :class:`exceptions.ChannelClosed` if the call fails.
  316. The queue object is an instance of :class:`ClosableDeferredQueue`,
  317. where data received from the queue will be stored. Clients should
  318. use its :meth:`get() <ClosableDeferredQueue.get>` method to fetch
  319. an individual message, which will return a Deferred firing with a
  320. namedtuple whose attributes are:
  321. - channel: this TwistedChannel
  322. - method: pika.spec.Basic.Deliver
  323. - properties: pika.spec.BasicProperties
  324. - body: bytes
  325. :rtype: Deferred
  326. """
  327. if self._closed:
  328. return defer.fail(self._closed)
  329. queue_obj = ClosableDeferredQueue()
  330. d = defer.Deferred()
  331. self._calls.add(d)
  332. def on_consume_ok(frame):
  333. consumer_tag = frame.method.consumer_tag
  334. self._queue_name_to_consumer_tags.setdefault(
  335. queue, set()).add(consumer_tag)
  336. self._consumers[consumer_tag] = queue_obj
  337. self._calls.discard(d)
  338. d.callback((queue_obj, consumer_tag))
  339. def on_message_callback(_channel, method, properties, body):
  340. """Add the ReceivedMessage to the queue, while replacing the
  341. channel implementation.
  342. """
  343. queue_obj.put(
  344. ReceivedMessage(
  345. channel=self,
  346. method=method,
  347. properties=properties,
  348. body=body,
  349. ))
  350. try:
  351. self._channel.basic_consume(
  352. queue=queue,
  353. on_message_callback=on_message_callback,
  354. auto_ack=auto_ack,
  355. exclusive=exclusive,
  356. consumer_tag=consumer_tag,
  357. arguments=arguments,
  358. callback=on_consume_ok,
  359. )
  360. except Exception: # pylint: disable=W0703
  361. return defer.fail()
  362. return d
  363. def basic_get(self, queue, auto_ack=False):
  364. """Get a single message from the AMQP broker.
  365. Will return If the queue is empty, it will return None.
  366. If you want to
  367. be notified of Basic.GetEmpty, use the Channel.add_callback method
  368. adding your Basic.GetEmpty callback which should expect only one
  369. parameter, frame. Due to implementation details, this cannot be called
  370. a second time until the callback is executed. For more information on
  371. basic_get and its parameters, see:
  372. http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get
  373. This method wraps :meth:`Channel.basic_get
  374. <pika.channel.Channel.basic_get>`.
  375. :param str queue: The queue from which to get a message. Use the empty
  376. string to specify the most recent server-named queue
  377. for this channel.
  378. :param bool auto_ack: Tell the broker to not expect a reply
  379. :returns: Deferred that fires with a namedtuple whose attributes are:
  380. channel: this TwistedChannel
  381. method: pika.spec.Basic.GetOk
  382. properties: pika.spec.BasicProperties
  383. body: bytes
  384. If the queue is empty, None will be returned.
  385. :rtype: Deferred
  386. :raises pika.exceptions.DuplicateGetOkCallback:
  387. """
  388. if self._basic_get_deferred is not None:
  389. raise exceptions.DuplicateGetOkCallback()
  390. def create_namedtuple(result):
  391. if result is None:
  392. return None
  393. _channel, method, properties, body = result
  394. return ReceivedMessage(
  395. channel=self,
  396. method=method,
  397. properties=properties,
  398. body=body,
  399. )
  400. def cleanup_attribute(result):
  401. self._basic_get_deferred = None
  402. return result
  403. d = self._wrap_channel_method("basic_get")(
  404. queue=queue, auto_ack=auto_ack)
  405. d.addCallback(create_namedtuple)
  406. d.addBoth(cleanup_attribute)
  407. self._basic_get_deferred = d
  408. return d
  409. def basic_nack(self, delivery_tag=None, multiple=False, requeue=True):
  410. """This method allows a client to reject one or more incoming messages.
  411. It can be used to interrupt and cancel large incoming messages, or
  412. return untreatable messages to their original queue.
  413. :param integer delivery-tag: int/long The server-assigned delivery tag
  414. :param bool multiple: If set to True, the delivery tag is treated as
  415. "up to and including", so that multiple messages
  416. can be acknowledged with a single method. If set
  417. to False, the delivery tag refers to a single
  418. message. If the multiple field is 1, and the
  419. delivery tag is zero, this indicates
  420. acknowledgement of all outstanding messages.
  421. :param bool requeue: If requeue is true, the server will attempt to
  422. requeue the message. If requeue is false or the
  423. requeue attempt fails the messages are discarded
  424. or dead-lettered.
  425. """
  426. return self._channel.basic_nack(
  427. delivery_tag=delivery_tag,
  428. multiple=multiple,
  429. requeue=requeue,
  430. )
  431. def basic_publish(self,
  432. exchange,
  433. routing_key,
  434. body,
  435. properties=None,
  436. mandatory=False):
  437. """Publish to the channel with the given exchange, routing key and body.
  438. This method wraps :meth:`Channel.basic_publish
  439. <pika.channel.Channel.basic_publish>`, but makes sure the channel is
  440. not closed before publishing.
  441. For more information on basic_publish and what the parameters do, see:
  442. http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish
  443. :param str exchange: The exchange to publish to
  444. :param str routing_key: The routing key to bind on
  445. :param bytes body: The message body
  446. :param pika.spec.BasicProperties properties: Basic.properties
  447. :param bool mandatory: The mandatory flag
  448. :returns: A Deferred that fires with the result of the channel's
  449. basic_publish.
  450. :rtype: Deferred
  451. :raises UnroutableError: raised when a message published in
  452. publisher-acknowledgments mode (see
  453. `BlockingChannel.confirm_delivery`) is returned via `Basic.Return`
  454. followed by `Basic.Ack`.
  455. :raises NackError: raised when a message published in
  456. publisher-acknowledgements mode is Nack'ed by the broker. See
  457. `BlockingChannel.confirm_delivery`.
  458. """
  459. if self._closed:
  460. return defer.fail(self._closed)
  461. result = self._channel.basic_publish(
  462. exchange=exchange,
  463. routing_key=routing_key,
  464. body=body,
  465. properties=properties,
  466. mandatory=mandatory)
  467. if not self._delivery_confirmation:
  468. return defer.succeed(result)
  469. else:
  470. # See http://www.rabbitmq.com/confirms.html#publisher-confirms
  471. self._delivery_message_id += 1
  472. self._deliveries[self._delivery_message_id] = defer.Deferred()
  473. return self._deliveries[self._delivery_message_id]
  474. def basic_qos(self, prefetch_size=0, prefetch_count=0, global_qos=False):
  475. """Specify quality of service. This method requests a specific quality
  476. of service. The QoS can be specified for the current channel or for all
  477. channels on the connection. The client can request that messages be
  478. sent in advance so that when the client finishes processing a message,
  479. the following message is already held locally, rather than needing to
  480. be sent down the channel. Prefetching gives a performance improvement.
  481. :param int prefetch_size: This field specifies the prefetch window
  482. size. The server will send a message in
  483. advance if it is equal to or smaller in size
  484. than the available prefetch size (and also
  485. falls into other prefetch limits). May be
  486. set to zero, meaning "no specific limit",
  487. although other prefetch limits may still
  488. apply. The prefetch-size is ignored by
  489. consumers who have enabled the no-ack
  490. option.
  491. :param int prefetch_count: Specifies a prefetch window in terms of
  492. whole messages. This field may be used in
  493. combination with the prefetch-size field; a
  494. message will only be sent in advance if both
  495. prefetch windows (and those at the channel
  496. and connection level) allow it. The
  497. prefetch-count is ignored by consumers who
  498. have enabled the no-ack option.
  499. :param bool global_qos: Should the QoS apply to all consumers on the
  500. Channel
  501. :returns: Deferred that fires on the Basic.QosOk response
  502. :rtype: Deferred
  503. """
  504. return self._wrap_channel_method("basic_qos")(
  505. prefetch_size=prefetch_size,
  506. prefetch_count=prefetch_count,
  507. global_qos=global_qos,
  508. )
  509. def basic_reject(self, delivery_tag, requeue=True):
  510. """Reject an incoming message. This method allows a client to reject a
  511. message. It can be used to interrupt and cancel large incoming
  512. messages, or return untreatable messages to their original queue.
  513. :param integer delivery_tag: int/long The server-assigned delivery tag
  514. :param bool requeue: If requeue is true, the server will attempt to
  515. requeue the message. If requeue is false or the
  516. requeue attempt fails the messages are discarded
  517. or dead-lettered.
  518. :raises: TypeError
  519. """
  520. return self._channel.basic_reject(
  521. delivery_tag=delivery_tag, requeue=requeue)
  522. def basic_recover(self, requeue=False):
  523. """This method asks the server to redeliver all unacknowledged messages
  524. on a specified channel. Zero or more messages may be redelivered. This
  525. method replaces the asynchronous Recover.
  526. :param bool requeue: If False, the message will be redelivered to the
  527. original recipient. If True, the server will
  528. attempt to requeue the message, potentially then
  529. delivering it to an alternative subscriber.
  530. :returns: Deferred that fires on the Basic.RecoverOk response
  531. :rtype: Deferred
  532. """
  533. return self._wrap_channel_method("basic_recover")(requeue=requeue)
  534. def close(self, reply_code=0, reply_text="Normal shutdown"):
  535. """Invoke a graceful shutdown of the channel with the AMQP Broker.
  536. If channel is OPENING, transition to CLOSING and suppress the incoming
  537. Channel.OpenOk, if any.
  538. :param int reply_code: The reason code to send to broker
  539. :param str reply_text: The reason text to send to broker
  540. :raises ChannelWrongStateError: if channel is closed or closing
  541. """
  542. return self._channel.close(reply_code=reply_code, reply_text=reply_text)
  543. def confirm_delivery(self):
  544. """Turn on Confirm mode in the channel. Pass in a callback to be
  545. notified by the Broker when a message has been confirmed as received or
  546. rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.
  547. For more information see:
  548. http://www.rabbitmq.com/confirms.html#publisher-confirms
  549. :returns: Deferred that fires on the Confirm.SelectOk response
  550. :rtype: Deferred
  551. """
  552. if self._delivery_confirmation:
  553. LOGGER.error('confirm_delivery: confirmation was already enabled.')
  554. return defer.succeed(None)
  555. wrapped = self._wrap_channel_method('confirm_delivery')
  556. d = wrapped(ack_nack_callback=self._on_delivery_confirmation)
  557. def set_delivery_confirmation(result):
  558. self._delivery_confirmation = True
  559. self._delivery_message_id = 0
  560. LOGGER.debug("Delivery confirmation enabled.")
  561. return result
  562. d.addCallback(set_delivery_confirmation)
  563. # Unroutable messages returned after this point will be in the context
  564. # of publisher acknowledgments
  565. self._channel.add_on_return_callback(self._on_puback_message_returned)
  566. return d
  567. def _on_delivery_confirmation(self, method_frame):
  568. """Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
  569. command, passing in either a Basic.Ack or Basic.Nack frame with
  570. the delivery tag of the message that was published. The delivery tag
  571. is an integer counter indicating the message number that was sent
  572. on the channel via Basic.Publish. Here we're just doing house keeping
  573. to keep track of stats and remove message numbers that we expect
  574. a delivery confirmation of from the list used to keep track of messages
  575. that are pending confirmation.
  576. :param pika.frame.Method method_frame: Basic.Ack or Basic.Nack frame
  577. """
  578. delivery_tag = method_frame.method.delivery_tag
  579. if delivery_tag not in self._deliveries:
  580. LOGGER.error("Delivery tag %s not found in the pending deliveries",
  581. delivery_tag)
  582. return
  583. if method_frame.method.multiple:
  584. tags = [tag for tag in self._deliveries if tag <= delivery_tag]
  585. tags.sort()
  586. else:
  587. tags = [delivery_tag]
  588. for tag in tags:
  589. d = self._deliveries[tag]
  590. del self._deliveries[tag]
  591. if isinstance(method_frame.method, pika.spec.Basic.Nack):
  592. # Broker was unable to process the message due to internal
  593. # error
  594. LOGGER.warning(
  595. "Message was Nack'ed by broker: nack=%r; channel=%s;",
  596. method_frame.method, self.channel_number)
  597. if self._puback_return is not None:
  598. returned_messages = [self._puback_return]
  599. self._puback_return = None
  600. else:
  601. returned_messages = []
  602. d.errback(exceptions.NackError(returned_messages))
  603. else:
  604. assert isinstance(method_frame.method, pika.spec.Basic.Ack)
  605. if self._puback_return is not None:
  606. # Unroutable message was returned
  607. returned_messages = [self._puback_return]
  608. self._puback_return = None
  609. d.errback(exceptions.UnroutableError(returned_messages))
  610. else:
  611. d.callback(method_frame.method)
  612. def _on_puback_message_returned(self, message):
  613. """Called as the result of Basic.Return from broker in
  614. publisher-acknowledgements mode. Saves the info as a ReturnedMessage
  615. instance in self._puback_return.
  616. :param pika.Channel channel: our self._impl channel
  617. :param pika.spec.Basic.Return method:
  618. :param pika.spec.BasicProperties properties: message properties
  619. :param bytes body: returned message body; empty string if no body
  620. """
  621. assert isinstance(message.method, spec.Basic.Return), message.method
  622. assert isinstance(message.properties,
  623. spec.BasicProperties), (message.properties)
  624. LOGGER.warning(
  625. "Published message was returned: _delivery_confirmation=%s; "
  626. "channel=%s; method=%r; properties=%r; body_size=%d; "
  627. "body_prefix=%.255r", self._delivery_confirmation,
  628. message.channel.channel_number, message.method, message.properties,
  629. len(message.body) if message.body is not None else None,
  630. message.body)
  631. self._puback_return = message
  632. def exchange_bind(self, destination, source, routing_key='',
  633. arguments=None):
  634. """Bind an exchange to another exchange.
  635. :param str destination: The destination exchange to bind
  636. :param str source: The source exchange to bind to
  637. :param str routing_key: The routing key to bind on
  638. :param dict arguments: Custom key/value pair arguments for the binding
  639. :raises ValueError:
  640. :returns: Deferred that fires on the Exchange.BindOk response
  641. :rtype: Deferred
  642. """
  643. return self._wrap_channel_method("exchange_bind")(
  644. destination=destination,
  645. source=source,
  646. routing_key=routing_key,
  647. arguments=arguments,
  648. )
  649. def exchange_declare(self,
  650. exchange,
  651. exchange_type='direct',
  652. passive=False,
  653. durable=False,
  654. auto_delete=False,
  655. internal=False,
  656. arguments=None):
  657. """This method creates an exchange if it does not already exist, and if
  658. the exchange exists, verifies that it is of the correct and expected
  659. class.
  660. If passive set, the server will reply with Declare-Ok if the exchange
  661. already exists with the same name, and raise an error if not and if the
  662. exchange does not already exist, the server MUST raise a channel
  663. exception with reply code 404 (not found).
  664. :param str exchange: The exchange name consists of a non-empty sequence
  665. of these characters: letters, digits, hyphen, underscore, period,
  666. or colon
  667. :param str exchange_type: The exchange type to use
  668. :param bool passive: Perform a declare or just check to see if it
  669. exists
  670. :param bool durable: Survive a reboot of RabbitMQ
  671. :param bool auto_delete: Remove when no more queues are bound to it
  672. :param bool internal: Can only be published to by other exchanges
  673. :param dict arguments: Custom key/value pair arguments for the exchange
  674. :returns: Deferred that fires on the Exchange.DeclareOk response
  675. :rtype: Deferred
  676. :raises ValueError:
  677. """
  678. return self._wrap_channel_method("exchange_declare")(
  679. exchange=exchange,
  680. exchange_type=exchange_type,
  681. passive=passive,
  682. durable=durable,
  683. auto_delete=auto_delete,
  684. internal=internal,
  685. arguments=arguments,
  686. )
  687. def exchange_delete(self, exchange=None, if_unused=False):
  688. """Delete the exchange.
  689. :param str exchange: The exchange name
  690. :param bool if_unused: only delete if the exchange is unused
  691. :returns: Deferred that fires on the Exchange.DeleteOk response
  692. :rtype: Deferred
  693. :raises ValueError:
  694. """
  695. return self._wrap_channel_method("exchange_delete")(
  696. exchange=exchange,
  697. if_unused=if_unused,
  698. )
  699. def exchange_unbind(self,
  700. destination=None,
  701. source=None,
  702. routing_key='',
  703. arguments=None):
  704. """Unbind an exchange from another exchange.
  705. :param str destination: The destination exchange to unbind
  706. :param str source: The source exchange to unbind from
  707. :param str routing_key: The routing key to unbind
  708. :param dict arguments: Custom key/value pair arguments for the binding
  709. :returns: Deferred that fires on the Exchange.UnbindOk response
  710. :rtype: Deferred
  711. :raises ValueError:
  712. """
  713. return self._wrap_channel_method("exchange_unbind")(
  714. destination=destination,
  715. source=source,
  716. routing_key=routing_key,
  717. arguments=arguments,
  718. )
  719. def flow(self, active):
  720. """Turn Channel flow control off and on.
  721. Returns a Deferred that will fire with a bool indicating the channel
  722. flow state. For more information, please reference:
  723. http://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow
  724. :param bool active: Turn flow on or off
  725. :returns: Deferred that fires with the channel flow state
  726. :rtype: Deferred
  727. :raises ValueError:
  728. """
  729. return self._wrap_channel_method("flow")(active=active)
  730. def open(self):
  731. """Open the channel"""
  732. return self._channel.open()
  733. def queue_bind(self, queue, exchange, routing_key=None, arguments=None):
  734. """Bind the queue to the specified exchange
  735. :param str queue: The queue to bind to the exchange
  736. :param str exchange: The source exchange to bind to
  737. :param str routing_key: The routing key to bind on
  738. :param dict arguments: Custom key/value pair arguments for the binding
  739. :returns: Deferred that fires on the Queue.BindOk response
  740. :rtype: Deferred
  741. :raises ValueError:
  742. """
  743. return self._wrap_channel_method("queue_bind")(
  744. queue=queue,
  745. exchange=exchange,
  746. routing_key=routing_key,
  747. arguments=arguments,
  748. )
  749. def queue_declare(self,
  750. queue,
  751. passive=False,
  752. durable=False,
  753. exclusive=False,
  754. auto_delete=False,
  755. arguments=None):
  756. """Declare queue, create if needed. This method creates or checks a
  757. queue. When creating a new queue the client can specify various
  758. properties that control the durability of the queue and its contents,
  759. and the level of sharing for the queue.
  760. Use an empty string as the queue name for the broker to auto-generate
  761. one
  762. :param str queue: The queue name; if empty string, the broker will
  763. create a unique queue name
  764. :param bool passive: Only check to see if the queue exists
  765. :param bool durable: Survive reboots of the broker
  766. :param bool exclusive: Only allow access by the current connection
  767. :param bool auto_delete: Delete after consumer cancels or disconnects
  768. :param dict arguments: Custom key/value arguments for the queue
  769. :returns: Deferred that fires on the Queue.DeclareOk response
  770. :rtype: Deferred
  771. :raises ValueError:
  772. """
  773. return self._wrap_channel_method("queue_declare")(
  774. queue=queue,
  775. passive=passive,
  776. durable=durable,
  777. exclusive=exclusive,
  778. auto_delete=auto_delete,
  779. arguments=arguments,
  780. )
  781. def queue_delete(self, queue, if_unused=False, if_empty=False):
  782. """Delete a queue from the broker.
  783. This method wraps :meth:`Channel.queue_delete
  784. <pika.channel.Channel.queue_delete>`, and removes the reference to the
  785. queue object after it gets deleted on the server.
  786. :param str queue: The queue to delete
  787. :param bool if_unused: only delete if it's unused
  788. :param bool if_empty: only delete if the queue is empty
  789. :returns: Deferred that fires on the Queue.DeleteOk response
  790. :rtype: Deferred
  791. :raises ValueError:
  792. """
  793. wrapped = self._wrap_channel_method('queue_delete')
  794. d = wrapped(queue=queue, if_unused=if_unused, if_empty=if_empty)
  795. def _clear_consumer(ret, queue_name):
  796. for consumer_tag in list(
  797. self._queue_name_to_consumer_tags.get(queue_name, set())):
  798. self._consumers[consumer_tag].close(
  799. exceptions.ConsumerCancelled(
  800. "Queue %s was deleted." % queue_name))
  801. del self._consumers[consumer_tag]
  802. self._queue_name_to_consumer_tags[queue_name].remove(
  803. consumer_tag)
  804. return ret
  805. return d.addCallback(_clear_consumer, queue)
  806. def queue_purge(self, queue):
  807. """Purge all of the messages from the specified queue
  808. :param str queue: The queue to purge
  809. :returns: Deferred that fires on the Queue.PurgeOk response
  810. :rtype: Deferred
  811. :raises ValueError:
  812. """
  813. return self._wrap_channel_method("queue_purge")(queue=queue)
  814. def queue_unbind(self,
  815. queue,
  816. exchange=None,
  817. routing_key=None,
  818. arguments=None):
  819. """Unbind a queue from an exchange.
  820. :param str queue: The queue to unbind from the exchange
  821. :param str exchange: The source exchange to bind from
  822. :param str routing_key: The routing key to unbind
  823. :param dict arguments: Custom key/value pair arguments for the binding
  824. :returns: Deferred that fires on the Queue.UnbindOk response
  825. :rtype: Deferred
  826. :raises ValueError:
  827. """
  828. return self._wrap_channel_method("queue_unbind")(
  829. queue=queue,
  830. exchange=exchange,
  831. routing_key=routing_key,
  832. arguments=arguments,
  833. )
  834. def tx_commit(self):
  835. """Commit a transaction.
  836. :returns: Deferred that fires on the Tx.CommitOk response
  837. :rtype: Deferred
  838. :raises ValueError:
  839. """
  840. return self._wrap_channel_method("tx_commit")()
  841. def tx_rollback(self):
  842. """Rollback a transaction.
  843. :returns: Deferred that fires on the Tx.RollbackOk response
  844. :rtype: Deferred
  845. :raises ValueError:
  846. """
  847. return self._wrap_channel_method("tx_rollback")()
  848. def tx_select(self):
  849. """Select standard transaction mode. This method sets the channel to use
  850. standard transactions. The client must use this method at least once on
  851. a channel before using the Commit or Rollback methods.
  852. :returns: Deferred that fires on the Tx.SelectOk response
  853. :rtype: Deferred
  854. :raises ValueError:
  855. """
  856. return self._wrap_channel_method("tx_select")()
  857. class _TwistedConnectionAdapter(pika.connection.Connection):
  858. """A Twisted-specific implementation of a Pika Connection.
  859. NOTE: since `base_connection.BaseConnection`'s primary responsibility is
  860. management of the transport, we use `pika.connection.Connection` directly
  861. as our base class because this adapter uses a different transport
  862. management strategy.
  863. """
  864. def __init__(self, parameters, on_open_callback, on_open_error_callback,
  865. on_close_callback, custom_reactor):
  866. super(_TwistedConnectionAdapter, self).__init__(
  867. parameters=parameters,
  868. on_open_callback=on_open_callback,
  869. on_open_error_callback=on_open_error_callback,
  870. on_close_callback=on_close_callback,
  871. internal_connection_workflow=False)
  872. self._reactor = custom_reactor or reactor
  873. self._transport = None # to be provided by `connection_made()`
  874. def _adapter_call_later(self, delay, callback):
  875. """Implement
  876. :py:meth:`pika.connection.Connection._adapter_call_later()`.
  877. """
  878. check_callback_arg(callback, 'callback')
  879. return _TimerHandle(self._reactor.callLater(delay, callback))
  880. def _adapter_remove_timeout(self, timeout_id):
  881. """Implement
  882. :py:meth:`pika.connection.Connection._adapter_remove_timeout()`.
  883. """
  884. timeout_id.cancel()
  885. def _adapter_add_callback_threadsafe(self, callback):
  886. """Implement
  887. :py:meth:`pika.connection.Connection._adapter_add_callback_threadsafe()`.
  888. """
  889. check_callback_arg(callback, 'callback')
  890. self._reactor.callFromThread(callback)
  891. def _adapter_connect_stream(self):
  892. """Implement pure virtual
  893. :py:ref:meth:`pika.connection.Connection._adapter_connect_stream()`
  894. method.
  895. NOTE: This should not be called due to our initialization of Connection
  896. via `internal_connection_workflow=False`
  897. """
  898. raise NotImplementedError
  899. def _adapter_disconnect_stream(self):
  900. """Implement pure virtual
  901. :py:ref:meth:`pika.connection.Connection._adapter_disconnect_stream()`
  902. method.
  903. """
  904. self._transport.loseConnection()
  905. def _adapter_emit_data(self, data):
  906. """Implement pure virtual
  907. :py:ref:meth:`pika.connection.Connection._adapter_emit_data()` method.
  908. """
  909. self._transport.write(data)
  910. def connection_made(self, transport):
  911. """Introduces transport to protocol after transport is connected.
  912. :param twisted.internet.interfaces.ITransport transport:
  913. :raises Exception: Exception-based exception on error
  914. """
  915. self._transport = transport
  916. # Let connection know that stream is available
  917. self._on_stream_connected()
  918. def connection_lost(self, error):
  919. """Called upon loss or closing of TCP connection.
  920. NOTE: `connection_made()` and `connection_lost()` are each called just
  921. once and in that order. All other callbacks are called between them.
  922. :param Failure: A Twisted Failure instance wrapping an exception.
  923. """
  924. self._transport = None
  925. error = error.value # drop the Failure wrapper
  926. if isinstance(error, twisted_error.ConnectionDone):
  927. self._error = error
  928. error = None
  929. LOGGER.log(logging.DEBUG if error is None else logging.ERROR,
  930. 'connection_lost: %r', error)
  931. self._on_stream_terminated(error)
  932. def data_received(self, data):
  933. """Called to deliver incoming data from the server to the protocol.
  934. :param data: Non-empty data bytes.
  935. :raises Exception: Exception-based exception on error
  936. """
  937. self._on_data_available(data)
  938. class TwistedProtocolConnection(protocol.Protocol):
  939. """A Pika-specific implementation of a Twisted Protocol. Allows using
  940. Twisted's non-blocking connectTCP/connectSSL methods for connecting to the
  941. server.
  942. TwistedProtocolConnection objects have a `ready` instance variable that's a
  943. Deferred which fires when the connection is ready to be used (the initial
  944. AMQP handshaking has been done). You *have* to wait for this Deferred to
  945. fire before requesting a channel.
  946. Once the connection is ready, you will be able to use the `closed` instance
  947. variable: a Deferred which fires when the connection is closed.
  948. Since it's Twisted handling connection establishing it does not accept
  949. connect callbacks, you have to implement that within Twisted. Also remember
  950. that the host, port and ssl values of the connection parameters are ignored
  951. because, yet again, it's Twisted who manages the connection.
  952. """
  953. def __init__(self, parameters=None, custom_reactor=None):
  954. self.ready = defer.Deferred()
  955. self.ready.addCallback(lambda _: self.connectionReady())
  956. self.closed = None
  957. self._impl = _TwistedConnectionAdapter(
  958. parameters=parameters,
  959. on_open_callback=self._on_connection_ready,
  960. on_open_error_callback=self._on_connection_failed,
  961. on_close_callback=self._on_connection_closed,
  962. custom_reactor=custom_reactor,
  963. )
  964. def channel(self, channel_number=None): # pylint: disable=W0221
  965. """Create a new channel with the next available channel number or pass
  966. in a channel number to use. Must be non-zero if you would like to
  967. specify but it is recommended that you let Pika manage the channel
  968. numbers.
  969. :param int channel_number: The channel number to use, defaults to the
  970. next available.
  971. :returns: a Deferred that fires with an instance of a wrapper around
  972. the Pika Channel class.
  973. :rtype: Deferred
  974. """
  975. d = defer.Deferred()
  976. self._impl.channel(channel_number, d.callback)
  977. return d.addCallback(TwistedChannel)
  978. @property
  979. def is_closed(self):
  980. # For compatibility with previous releases.
  981. return self._impl.is_closed
  982. def close(self, reply_code=200, reply_text='Normal shutdown'):
  983. if not self._impl.is_closed:
  984. self._impl.close(reply_code, reply_text)
  985. return self.closed
  986. # IProtocol methods
  987. def dataReceived(self, data):
  988. # Pass the bytes to Pika for parsing
  989. self._impl.data_received(data)
  990. def connectionLost(self, reason=protocol.connectionDone):
  991. self._impl.connection_lost(reason)
  992. # Let the caller know there's been an error
  993. d, self.ready = self.ready, None
  994. if d:
  995. d.errback(reason)
  996. def makeConnection(self, transport):
  997. self._impl.connection_made(transport)
  998. protocol.Protocol.makeConnection(self, transport)
  999. # Our own methods
  1000. def connectionReady(self):
  1001. """This method will be called when the underlying connection is ready.
  1002. """
  1003. def _on_connection_ready(self, _connection):
  1004. d, self.ready = self.ready, None
  1005. if d:
  1006. self.closed = defer.Deferred()
  1007. d.callback(None)
  1008. def _on_connection_failed(self, _connection, _error_message=None):
  1009. d, self.ready = self.ready, None
  1010. if d:
  1011. attempts = self._impl.params.connection_attempts
  1012. exc = exceptions.AMQPConnectionError(attempts)
  1013. d.errback(exc)
  1014. def _on_connection_closed(self, _connection, exception):
  1015. d, self.closed = self.closed, None
  1016. if d:
  1017. if isinstance(exception, Failure):
  1018. # Calling `callback` with a Failure instance will trigger the
  1019. # errback path.
  1020. exception = exception.value
  1021. d.callback(exception)
  1022. class _TimerHandle(nbio_interface.AbstractTimerReference):
  1023. """This module's adaptation of `nbio_interface.AbstractTimerReference`.
  1024. """
  1025. def __init__(self, handle):
  1026. """
  1027. :param twisted.internet.base.DelayedCall handle:
  1028. """
  1029. self._handle = handle
  1030. def cancel(self):
  1031. if self._handle is not None:
  1032. try:
  1033. self._handle.cancel()
  1034. except (twisted_error.AlreadyCalled,
  1035. twisted_error.AlreadyCancelled):
  1036. pass
  1037. self._handle = None