Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 110 lines (81 sloc) 3.8 KB
import json
import pickle
import pika
from pika.credentials import PlainCredentials
import eventlet
from st2reactor.sensor.base import Sensor
'json': json.loads,
'pickle': pickle.loads
class RabbitMQQueueSensor(Sensor):
"""Sensor which monitors a RabbitMQ queue for new messages
This is a RabbitMQ Queue sensor i.e. it works on the simplest RabbitMQ
messaging model as described in
It is capable of simultaneously consuming from multiple queues. Each message is
dispatched to stackstorm as a `rabbitmq.new_message` TriggerInstance.
def __init__(self, sensor_service, config=None):
super(RabbitMQQueueSensor, self).__init__(sensor_service=sensor_service, config=config)
self._logger = self._sensor_service.get_logger(name=self.__class__.__name__) = self._config['sensor_config']['host']
self.username = self._config['sensor_config']['username']
self.password = self._config['sensor_config']['password']
queue_sensor_config = self._config['sensor_config']['rabbitmq_queue_sensor']
self.queues = queue_sensor_config['queues']
if not isinstance(self.queues, list):
self.queues = [self.queues]
self.deserialization_method = queue_sensor_config['deserialization_method']
supported_methods = DESERIALIZATION_FUNCTIONS.keys()
if self.deserialization_method and self.deserialization_method not in supported_methods:
raise ValueError('Invalid deserialization method specified: %s' %
self.conn = None = None
def run(self):'Starting to consume messages from RabbitMQ for %s', self.queues)
# run in an eventlet in-order to yield correctly
gt = eventlet.spawn(
# wait else the sensor will quit
def cleanup(self):
if self.conn:
def setup(self):
if self.username and self.password:
credentials = PlainCredentials(username=self.username, password=self.password)
connection_params = pika.ConnectionParameters(, credentials=credentials)
connection_params = pika.ConnectionParameters(
self.conn = pika.BlockingConnection(connection_params) =
# Setup Qs for listening
for queue in self.queues:, durable=True)
def callback(ch, method, properties, body, queue_copy=queue):
self._dispatch_trigger(ch, method, properties, body, queue_copy), queue=queue)
def _dispatch_trigger(self, ch, method, properties, body, queue):
body = self._deserialize_body(body=body)
self._logger.debug('Received message for queue %s with body %s', queue, body)
payload = {"queue": queue, "body": body}
self._sensor_service.dispatch(trigger="rabbitmq.new_message", payload=payload)
def update_trigger(self, trigger):
def add_trigger(self, trigger):
def remove_trigger(self, trigger):
def _deserialize_body(self, body):
if not self.deserialization_method:
return body
deserialization_func = DESERIALIZATION_FUNCTIONS[self.deserialization_method]
body = deserialization_func(body)
except Exception:
return body