event_bus_utils.py 11.4 KB
Newer Older
1 2
import os
import pika
3
import logging
4
import threading
5
import traceback
6 7 8 9 10 11 12

# for using it as library and as a __main__
try:
    from messages import *
except:
    from .messages import *

13
VERSION = '0.0.10'
14
AMQP_EXCHANGE = 'amq.topic'
Federico Sismondi's avatar
Federico Sismondi committed
15
MAX_LOG_LINE_LENGTH = 120
16

17
logger = logging.getLogger(__name__)
18 19 20 21

class AmqpSynchCallTimeoutError(Exception):
    pass

22

23
class AmqpListener(threading.Thread):
24
    DEFAULT_TOPIC_SUSBCRIPTIONS = ['#']
25
    DEFAULT_EXCHAGE = 'amq.topic'
26
    DEFAULT_AMQP_URL = 'amqp://guest:guest@locahost/'
27

Matteo Filipponi's avatar
Matteo Filipponi committed
28
    def __init__(self, amqp_url, amqp_exchange, callback, topics=None, use_message_typing=True, pre_declared_queue=None):
29

30 31
        self.COMPONENT_ID = 'amqp_listener_%s' % str(uuid.uuid4())[:8]

32
        self.stopping = False
33 34
        self.connection = None
        self.channel = None
Matteo Filipponi's avatar
Matteo Filipponi committed
35 36
        if pre_declared_queue:
            self.services_queue_name = pre_declared_queue
37
            self.queue_is_declared = True
Matteo Filipponi's avatar
Matteo Filipponi committed
38 39 40
        else:
            self.services_queue_name = 'services_queue@%s' % self.COMPONENT_ID
            self.queue_is_declared = False
41
        self.use_message_typing = use_message_typing
42

43 44 45
        threading.Thread.__init__(self)

        if callback is None:
46
            self.message_dispatcher = AmqpListener.default_message_handler
47
        else:
48
            self.message_dispatcher = callback
49

50 51 52 53
        if topics:  # subscribe only to passed list
            self.topics = topics
        else:
            self.topics = self.DEFAULT_TOPIC_SUSBCRIPTIONS
54 55 56 57 58 59

        if amqp_exchange:
            self.exchange = amqp_exchange
        else:
            self.exchange = self.DEFAULT_EXCHAGE

60 61 62 63 64 65 66
        if amqp_url:
            self.amqp_url = amqp_url
        else:
            self.amqp_url = self.DEFAULT_AMQP_URL

        self.amqp_connect()

67
    @classmethod
68
    def default_message_handler(cls, message_as_dict):
69
        clean_dict = dict((k, v) for k, v in message_as_dict.items() if v)
Federico Sismondi's avatar
Federico Sismondi committed
70 71
        print('-' * 120)
        print('%s : %s' % ('routing_key', clean_dict.pop('routing_key')))
Federico Sismondi's avatar
Federico Sismondi committed
72 73
        print('-' * 120)
        print(json.dumps(clean_dict, indent=4, sort_keys=True))
74

75 76 77 78
    def amqp_connect(self):
        self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))
        self.channel = self.connection.channel()

79 80 81 82 83 84 85 86 87
        # Declare queue if necessary
        if not self.queue_is_declared:
            self.channel.queue_declare(queue=self.services_queue_name,
                                       auto_delete=True,
                                       arguments={'x-max-length': 200})
            for t in self.topics:
                self.channel.queue_bind(exchange=self.exchange,
                                        queue=self.services_queue_name,
                                        routing_key=t)
88 89 90 91 92 93 94
        # Hello world message
        m = MsgTestingToolComponentReady(
            component=self.COMPONENT_ID,
            description="%s is READY" % self.COMPONENT_ID

        )

95
        # Send hello world message
96 97 98 99 100 101 102 103 104
        self.channel.basic_publish(
            body=m.to_json(),
            routing_key=m.routing_key,
            exchange=self.exchange,
            properties=pika.BasicProperties(
                content_type='application/json',
            )
        )

105
        # Start consuming
106 107 108 109
        self.channel.basic_qos(prefetch_count=1)
        self.channel.basic_consume(self.on_request, queue=self.services_queue_name)

    def stop(self):
110
        self.stopping = True
111 112 113 114 115 116
        self.channel.queue_delete(self.services_queue_name)
        self.channel.stop_consuming()
        self.connection.close()

    def on_request(self, ch, method, props, body):

117 118
        if self.use_message_typing:
            try:
119
                m = Message.load_from_pika(method, props, body)
120
                if m is None:
121
                    raise Exception("Couldnt build message from json %s, rkey: %s " % (body, method.routing_key))
122
                m.routing_key = method.routing_key
123
                logger.debug('Message in bus: %s' % repr(m)[:MAX_LOG_LINE_LENGTH])
124 125 126
                self.message_dispatcher(m)

            except NonCompliantMessageFormatError as e:
127
                logger.error('%s got a non compliant message error %s' % (self.__class__.__name__, e))
128 129

            except Exception as e:
130 131
                logger.error(e)
                logger.error('message received:\n\tr_key: %s\n\t%s' % (method.routing_key, body))
132 133 134 135 136
                raise e

            finally:
                ch.basic_ack(delivery_tag=method.delivery_tag)
        else:
137 138 139 140 141 142 143 144 145 146 147 148

            props_dict = {
                'content_type': props.content_type,
                'delivery_mode': props.delivery_mode,
                'correlation_id': props.correlation_id,
                'reply_to': props.reply_to,
                'message_id': props.message_id,
                'timestamp': props.timestamp,
                'user_id': props.user_id,
                'app_id': props.app_id,
            }

149
            body_dict = json.loads(body.decode('utf-8'), object_pairs_hook=OrderedDict)
150
            ch.basic_ack(delivery_tag=method.delivery_tag)
151
            text_based_message_representation = OrderedDict()
152
            text_based_message_representation.update({'routing_key': method.routing_key})
153 154 155
            text_based_message_representation.update(props_dict)
            text_based_message_representation.update(body_dict)
            self.message_dispatcher(text_based_message_representation)
156 157

    def run(self):
158
        logger.info("Starting thread listening on the event bus on topics %s" % self.topics)
159

160 161 162
        for i in range(1, 4):
            try:
                self.channel.start_consuming()
163 164 165 166

            except (pika.exceptions.ConnectionClosed,
                    pika.exceptions.ChannelError,
                    pika.exceptions.ChannelClosed) as err:
167 168 169 170
                if not self.stopping:
                    logger.error('[AmqpListener] Unexpected connection closed, reconnecting %s/%s' % (i, 4))
                    logger.error(traceback.format_exc())
                    self.amqp_connect()
171

172
        logger.info('%s says Bye byes!' % self.COMPONENT_ID)
173 174 175 176 177 178 179 180 181


def publish_message(connection, message):
    """
    Publishes message into the correct topic (uses Message object metadata)
    Creates temporary channel on it's own
    Connection must be a pika.BlockingConnection
    """

182 183 184 185 186 187 188 189
    channel = connection.channel()
    properties = pika.BasicProperties(**message.get_properties())
    channel.basic_publish(
        exchange=AMQP_EXCHANGE,
        routing_key=message.routing_key,
        properties=properties,
        body=message.to_json(),
    )
190

191 192
    if channel and channel.is_open:
        channel.close()
193 194


195
def amqp_request(connection, request_message, component_id, retries=10, time_between_retries=0.5, use_message_typing=False):
196 197 198 199 200 201 202 203 204 205 206
    """
    Publishes message into the correct topic (uses Message object metadata)
    Returns reply message.
    Uses reply_to and corr id amqp's properties for matching the reply
    Creates temporary channel, and queues on it's own
    Connection must be a pika.BlockingConnection
    """

    # check first that sender didnt forget about reply to and corr id
    assert request_message.reply_to
    assert request_message.correlation_id
207 208
    assert retries > 0

209
    channel = None
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    response = None

    reply_queue_name = 'amqp_rpc_%s@%s' % (str(uuid.uuid4())[:8], component_id)

    channel = connection.channel()
    result = channel.queue_declare(queue=reply_queue_name, auto_delete=True)
    callback_queue = result.method.queue

    # bind and listen to reply_to topic
    channel.queue_bind(
        exchange=AMQP_EXCHANGE,
        queue=callback_queue,
        routing_key=request_message.reply_to
    )

    channel.basic_publish(
        exchange=AMQP_EXCHANGE,
        routing_key=request_message.routing_key,
        properties=pika.BasicProperties(**request_message.get_properties()),
        body=request_message.to_json(),
    )

    time.sleep(0.2)
    retries_left = retries

    while retries_left > 0:
236
        time.sleep(time_between_retries)
237 238 239 240 241 242 243 244
        method, props, body = channel.basic_get(reply_queue_name)
        if method:
            channel.basic_ack(method.delivery_tag)
            if hasattr(props, 'correlation_id') and props.correlation_id == request_message.correlation_id:
                break
        retries_left -= 1

    if retries_left > 0:
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

        if use_message_typing:
            try:
                response = Message.load_from_pika(method, props, body)
                if response is None:
                    raise Exception("Couldnt build message from json %s, rkey: %s " % (body, method.routing_key))

            except NonCompliantMessageFormatError as e:
                logger.error('amqp_request got a non compliant message error %s' %  e)

            except Exception as e:
                logger.error(e)
                logger.error('message received:\n\tr_key: %s\n\t%s' % (method.routing_key, body))
                raise e

        else:

            body_dict = json.loads(body.decode('utf-8'), object_pairs_hook=OrderedDict)
            response = MsgReply(request_message, **body_dict)
264 265 266 267 268 269 270 271
    else:
        # clean up
        channel.queue_delete(reply_queue_name)
        channel.close()
        raise AmqpSynchCallTimeoutError(
            "Response timeout! rkey: %s , request type: %s" % (
                request_message.routing_key,
                type(request_message)
272
            )
273
        )
274

275 276 277 278
    if channel and channel.is_open:
        # clean up
        channel.queue_delete(reply_queue_name)
        channel.close()
279

280
    return response
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

if __name__ == '__main__':

    try:
        AMQP_EXCHANGE = str(os.environ['AMQP_EXCHANGE'])
    except KeyError as e:
        AMQP_EXCHANGE = "amq.topic"

    try:
        AMQP_URL = str(os.environ['AMQP_URL'])
        print('Env vars for AMQP connection succesfully imported')

    except KeyError as e:
        AMQP_URL = "amqp://guest:guest@localhost/"

    def callback_function(message_received):
        print("Callback function received: \n\t" + repr(message_received))

299

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    # EXAMPLE ON AMQP LISTENER

    # # amqp listener example:
    # amqp_listener_thread = AmqpListener(
    #     amqp_url=AMQP_URL,
    #     amqp_exchange=AMQP_EXCHANGE,
    #     callback=callback_function,
    #     topics='#'
    # )
    #
    # try:
    #     amqp_listener_thread.start()
    # except Exception as e:
    #     print(e)
    #
    # # publish message example
    # retries_left = 3
    # while retries_left > 0:
    #     try:
    #         connection = pika.BlockingConnection(pika.URLParameters(AMQP_URL))
    #         m = MsgTest()
    #         publish_message(connection, m)
    #         break
    #     except pika.exceptions.ConnectionClosed:
    #         retries_left -= 1
    #         print('retrying..')
    #         time.sleep(0.2)
    #
    # # example of a request sent into the bus
    # m = MsgTestSuiteGetTestCases()
    # try:
    #     r = amqp_request(connection, m, 'someImaginaryComponent')
    #     print("This is the response I got:\n\t" + repr(r))
    #
    # except AmqpSynchCallTimeoutError as e:
    #     print("Nobody answered to our request :'(")


    # EXAMPLE ON REQUEST REPLY FOR UI BUTTONS:
    con = pika.BlockingConnection(pika.URLParameters(AMQP_URL))
    channel = con.channel()

Federico Sismondi's avatar
Federico Sismondi committed
342 343 344 345 346 347 348 349 350
    # ui_request = MsgUiRequestConfirmationButton()
    # print("publishing .. %s" % repr(ui_request))
    # ui_reply = amqp_request(con, ui_request, 'dummy_component')
    # print(repr(ui_reply))


    req = MsgUiRequestSessionConfiguration()
    ui_reply = amqp_request(con, req,'dummy_component')
    print(ui_reply.users)