Skip to content

Instantly share code, notes, and snippets.

@Thann
Last active November 1, 2018 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thann/578205afe77a6c40e4973dd1579a7876 to your computer and use it in GitHub Desktop.
Save Thann/578205afe77a6c40e4973dd1579a7876 to your computer and use it in GitHub Desktop.
RabbitWorker and RealtimePublisher for Tornado (python2)
## Mostly taken from https://github.com/pika/pika/blob/03542ef616a2a849e8bfb0845427f50e741ea0c6/docs/examples/tornado_consumer.rst
# -*- coding: utf-8 -*-
import json
import pika
import uuid
from tornado import gen
from tornado.log import app_log
from tornado.ioloop import IOLoop
from tornado.concurrent import Future
LOGGER = app_log
RABBIT_URL = 'amqp://username:password@hostname'
## Usage:
# rabbit_realtime = RealtimePublisher(RABBIT_URL)
# Consumes tasks and Publishes those results
class RabbitWorker(object):
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, which usually are tied to permission related issues or
socket timeouts.
If the channel is closed, it will indicate a problem with one of the
commands that were issued and that should surface in the output as well.
"""
EXCHANGE = 'message'
EXCHANGE_TYPE = 'topic'
CONSUME_QUEUE = (
'tasks', {
'durable': True,
'exclusive': False,
'auto_delete': False,
'arguments': {'x-max-priority': 10}
}
)
PUBLISH_QUEUE = (
'results', {
'durable': True,
'exclusive': False,
'auto_delete': False,
}
)
def __init__(self, amqp_url):
"""Create a new instance of the consumer class, passing in the AMQP
URL used to connect to RabbitMQ.
:param str amqp_url: The AMQP url to connect with
"""
self._connection = None
self._channel = None
self._closing = False
self._consumer_tag = None
self._url = amqp_url
self._deliveries = []
self._acked = 0
self._nacked = 0
self._message_number = 0
# connect automatically!
IOLoop.instance().spawn_callback(self.connect)
## Overload this or add handlers
def on_consume_message(self, unused_channel, basic_deliver, properties, body):
"""Invoked by pika when a message is delivered from RabbitMQ. The
channel is passed for your convenience. The basic_deliver object that
is passed in carries the exchange, routing key, delivery tag and
a redelivered flag for the message. The properties passed in is an
instance of BasicProperties with the message properties and the body
is the message that was sent.
:param pika.channel.Channel unused_channel: The channel object
:param pika.Spec.Basic.Deliver: basic_deliver method
:param pika.Spec.BasicProperties: properties
:param str|unicode body: The message body
"""
body = json.loads(body)
LOGGER.info('Received message # %s from %s [%s]: %s',
basic_deliver.delivery_tag, properties.app_id, body.get('_id') or body)
# TODO: add handlers!
# TODO: connect to arbitrary queue
self._channel.basic_publish(self.EXCHANGE, self.PUBLISH_QUEUE[0],
json.dumps(body),
properties)
def connect(self):
"""This method connects to RabbitMQ, returning the connection handle.
When the connection is established, the on_connection_open method
will be invoked by pika.
:rtype: pika.SelectConnection
"""
LOGGER.info('Connecting to %s', self._url)
self._connection = pika.adapters.TornadoConnection(pika.URLParameters(self._url),
self.on_connection_open,
self.on_connection_closed)
return self._connection
def close_connection(self):
"""This method closes the connection to RabbitMQ."""
LOGGER.info('Closing connection')
self._connection.close()
def on_connection_closed(self, connection, reason, other=None):
"""This method is invoked by pika when the connection to RabbitMQ is
closed unexpectedly. Since it is unexpected, we will reconnect to
RabbitMQ if it disconnects.
:param pika.connection.Connection connection: The closed connection obj
:param Exception reason: exception representing reason for loss of
connection.
"""
self._channel = None
if self._closing:
self._connection.ioloop.stop()
else:
LOGGER.warning('Connection closed, reopening in 5 seconds: %s',
reason)
self._connection.ioloop.call_later(5, self.reconnect)
def on_connection_open(self, unused_connection):
"""This method is called by pika once the connection to RabbitMQ has
been established. It passes the handle to the connection object in
case we need it, but in this case, we'll just mark it unused.
:type unused_connection: pika.SelectConnection
"""
LOGGER.info('Connection opened')
self._connection.add_on_close_callback(self.on_connection_closed)
self.open_channel()
def reconnect(self):
"""Will be invoked by the IOLoop timer if the connection is
closed. See the on_connection_closed method.
"""
if not self._closing:
# Create a new connection
self._connection = self.connect()
def add_on_channel_close_callback(self):
"""This method tells pika to call the on_channel_closed method if
RabbitMQ unexpectedly closes the channel.
"""
LOGGER.info('Adding channel close callback')
self._channel.add_on_close_callback(self.on_channel_closed)
def on_channel_closed(self, channel, reason, other):
"""Invoked by pika when RabbitMQ unexpectedly closes the channel.
Channels are usually closed if you attempt to do something that
violates the protocol, such as re-declare an exchange or queue with
different parameters. In this case, we'll close the connection
to shutdown the object.
:param pika.channel.Channel: The closed channel
:param Exception reason: why the channel was closed
"""
LOGGER.warning('Channel %i was closed: %s <%s>', channel, reason, other)
self._connection.close()
def on_channel_open(self, channel):
"""This method is invoked by pika when the channel has been opened.
The channel object is passed in so we can make use of it.
Since the channel is now open, we'll declare the exchange to use.
:param pika.channel.Channel channel: The channel object
"""
LOGGER.info('Channel opened')
self._channel = channel
self.add_on_channel_close_callback()
self.setup_exchange(self.EXCHANGE)
def setup_exchange(self, exchange_name):
"""Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare
"""
LOGGER.info('Declaring exchange %s', exchange_name)
self._channel.exchange_declare(self.on_exchange_declareok,
exchange_name,
self.EXCHANGE_TYPE)
def on_exchange_declareok(self, unused_frame):
"""Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
command.
:param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame
"""
LOGGER.info('Exchange declared')
LOGGER.info('Declaring publish queue %s', self.PUBLISH_QUEUE[0])
self._channel.queue_declare(self.on_publisher_queue_declareok,
self.PUBLISH_QUEUE[0],
**self.PUBLISH_QUEUE[1])
LOGGER.info('Declaring consume queue %s', self.CONSUME_QUEUE[0])
self._channel.queue_declare(self.on_consumer_queue_declareok,
self.CONSUME_QUEUE[0],
**self.CONSUME_QUEUE[1])
def on_queue_declareok(self, method_frame, callback, routing_key):
"""Method invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is complete, the on_bindok method will
be invoked by pika.
:param pika.frame.Method method_frame: The Queue.DeclareOk frame
"""
LOGGER.info('Binding %s to %s with %s',
# self.EXCHANGE, self.QUEUE, self.ROUTING_KEY)
self.EXCHANGE, method_frame.method.queue, routing_key)
# self._channel.queue_bind(self.on_bindok, self.QUEUE,
# self.EXCHANGE, self.ROUTING_KEY)
self._channel.queue_bind(callback, method_frame.method.queue,
self.EXCHANGE, routing_key)
# self.EXCHANGE, method_frame.method.queue)
def on_publisher_queue_declareok(self, method_frame):
self.on_queue_declareok(method_frame, self.on_publisher_bindok,
self.PUBLISH_QUEUE[0])
def on_consumer_queue_declareok(self, method_frame):
self.on_queue_declareok(method_frame, self.on_consumer_bindok,
self.CONSUME_QUEUE[0])
def on_consumer_cancelled(self, method_frame):
"""Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
receiving messages.
:param pika.frame.Method method_frame: The Basic.Cancel frame
"""
LOGGER.info('Consumer was cancelled remotely, shutting down: %r',
method_frame)
if self._channel:
self._channel.close()
def acknowledge_message(self, delivery_tag):
"""Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame
"""
LOGGER.info('Acknowledging message %s', delivery_tag)
self._channel.basic_ack(delivery_tag)
def on_cancelok(self, unused_frame):
"""This method is invoked by pika when RabbitMQ acknowledges the
cancellation of a consumer. At this point we will close the channel.
This will invoke the on_channel_closed method once the channel has been
closed, which will in-turn close the connection.
:param pika.frame.Method unused_frame: The Basic.CancelOk frame
"""
LOGGER.info('RabbitMQ acknowledged the cancellation of the consumer')
self.close_channel()
def stop_consuming(self):
"""Tell RabbitMQ that you would like to stop consuming by sending the
Basic.Cancel RPC command.
"""
if self._channel:
LOGGER.info('Sending a Basic.Cancel RPC command to RabbitMQ')
self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
def on_consumer_bindok(self, unused_frame):
"""Invoked by pika when the Queue.Bind method has completed. At this
point we will start consuming messages by calling start_consuming
which will invoke the needed RPC commands to start the process.
:param pika.frame.Method unused_frame: The Queue.BindOk response frame
"""
LOGGER.info('Queue bound')
LOGGER.info('Issuing consumer related RPC commands')
self._channel.add_on_cancel_callback(self.on_consumer_cancelled)
LOGGER.info('Consuming on %s', self.CONSUME_QUEUE[0])
self._consumer_tag = self._channel.basic_consume(self.on_consume_message,
self.CONSUME_QUEUE[0])
def on_publisher_bindok(self, unused_frame):
"""Invoked by pika when the Queue.Bind method has completed. At this
point we will start consuming messages by calling start_consuming
which will invoke the needed RPC commands to start the process.
:param pika.frame.Method unused_frame: The Queue.BindOk response frame
"""
LOGGER.info('Queue bound')
# self.start_consuming()
LOGGER.info('Issuing publisher related RPC commands')
# self.add_on_cancel_callback()
self._channel.add_on_cancel_callback(self.on_consumer_cancelled)
"""Send the Confirm.Select RPC method to RabbitMQ to enable delivery
confirmations on the channel. The only way to turn this off is to close
the channel and create a new one.
When the message is confirmed from RabbitMQ, the
on_delivery_confirmation method will be invoked passing in a Basic.Ack
or Basic.Nack method from RabbitMQ that will indicate which messages it
is confirming or rejecting.
"""
self._channel.confirm_delivery(self.on_delivery_confirmation)
def on_delivery_confirmation(self, method_frame):
"""Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
command, passing in either a Basic.Ack or Basic.Nack frame with
the delivery tag of the message that was published. The delivery tag
is an integer counter indicating the message number that was sent
on the channel via Basic.Publish. Here we're just doing house keeping
to keep track of stats and remove message numbers that we expect
a delivery confirmation of from the list used to keep track of messages
that are pending confirmation.
:param pika.frame.Method method_frame: Basic.Ack or Basic.Nack frame
"""
confirmation_type = method_frame.method.NAME.split('.')[1].lower()
LOGGER.info('Received %s for delivery tag: %i',
confirmation_type,
method_frame.method.delivery_tag)
if confirmation_type == 'ack':
self._acked += 1
elif confirmation_type == 'nack':
self._nacked += 1
self._deliveries.remove(method_frame.method.delivery_tag)
LOGGER.info('Published %i messages, %i have yet to be confirmed, '
'%i were acked and %i were nacked',
self._message_number, len(self._deliveries),
self._acked, self._nacked)
def close_channel(self):
"""Call to close the channel with RabbitMQ cleanly by issuing the
Channel.Close RPC command.
"""
LOGGER.info('Closing the channel')
self._channel.close()
def open_channel(self):
"""Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika.
"""
LOGGER.info('Creating a new channel')
self._connection.channel(on_open_callback=self.on_channel_open)
def run(self):
"""Run the example consumer by connecting to RabbitMQ and then
starting the IOLoop to block and allow the SelectConnection to operate.
"""
self._connection = self.connect()
self._connection.ioloop.start()
def stop(self):
"""Cleanly shutdown the connection to RabbitMQ by stopping the consumer
with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok
will be invoked by pika, which will then closing the channel and
connection. The IOLoop is started again because this method is invoked
when CTRL-C is pressed raising a KeyboardInterrupt exception. This
exception stops the IOLoop which needs to be running for pika to
communicate with RabbitMQ. All of the commands issued prior to starting
the IOLoop will be buffered but not processed.
"""
LOGGER.info('Stopping')
self._closing = True
self.stop_consuming()
self._connection.ioloop.start()
LOGGER.info('Stopped')
# Publishes tasks and Consumes those results
class RealtimePublisher(RabbitWorker):
PUBLISH_QUEUE = (
'tasks', {
'durable': True,
'exclusive': False,
'auto_delete': False,
'arguments': {'x-max-priority': 10}
}
)
CONSUME_QUEUE = (
'realtime_results', {
'durable': False,
'exclusive': False,
'auto_delete': True,
}
)
def __init__(self, *args, **kwargs):
self._promises = {}
# Create unique results queue
self.CONSUME_QUEUE = (self.CONSUME_QUEUE[0] + '_'+ str(uuid.uuid4()),
self.CONSUME_QUEUE[1])
super(RealtimePublisher, self).__init__(*args, **kwargs)
def on_consume_message(self, unused_channel, basic_deliver, properties, body):
body = json.loads(body)
LOGGER.info('Received message # %s from %s [%s]: %s',
basic_deliver.delivery_tag, properties.app_id, body.get('_id'), body)
body = json.loads(body)
p = self._promises.get(body.get('_id'))
if p: p.set_result(body)
else: LOGGER.error('Failed to find task [%s] in %s',
body.get('_id'), self._promises.keys())
self.acknowledge_message(basic_deliver.delivery_tag)
def publish_task(self, task_data):
properties = pika.BasicProperties(app_id='tornado-realtime-publisher',
content_type='application/json')
task_data['_id'] = str(uuid.uuid4())
task_data['result_queue'] = self.CONSUME_QUEUE[0]
self._channel.basic_publish(self.EXCHANGE, self.PUBLISH_QUEUE[0],
json.dumps(task_data),
properties)
self._message_number += 1
self._deliveries.append(self._message_number)
LOGGER.info('Published message # %i [%s]',
self._message_number, task_data['_id'])
return
@gen.coroutine
def publish_task_result(self, task_data):
""" This is where the magic happens, publish a task and await the result """
future = Future()
task_id = self.publish_task(task_data)
self._promises[task_id] = future
yield future
raise gen.Return(future.result())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment