| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 1 | import logging |
| 2 | import asyncio |
| 3 | import yaml |
| 4 | from aiokafka import AIOKafkaConsumer |
| 5 | from aiokafka import AIOKafkaProducer |
| 6 | from aiokafka.errors import KafkaError |
| tierno | 3054f78 | 2018-04-25 16:59:53 +0200 | [diff] [blame] | 7 | from osm_common.msgbase import MsgBase, MsgException |
| 8 | # import json |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 9 | |
| 10 | __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>, " \ |
| 11 | "Guillermo Calvino <guillermo.calvinosanchez@altran.com>" |
| tierno | 3054f78 | 2018-04-25 16:59:53 +0200 | [diff] [blame] | 12 | |
| 13 | |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 14 | class MsgKafka(MsgBase): |
| 15 | def __init__(self, logger_name='msg'): |
| 16 | self.logger = logging.getLogger(logger_name) |
| 17 | self.host = None |
| 18 | self.port = None |
| 19 | self.consumer = None |
| 20 | self.producer = None |
| 21 | self.loop = None |
| 22 | self.broker = None |
| 23 | |
| 24 | def connect(self, config): |
| 25 | try: |
| 26 | if "logger_name" in config: |
| 27 | self.logger = logging.getLogger(config["logger_name"]) |
| 28 | self.host = config["host"] |
| 29 | self.port = config["port"] |
| 30 | self.loop = asyncio.get_event_loop() |
| 31 | self.broker = str(self.host) + ":" + str(self.port) |
| 32 | |
| 33 | except Exception as e: # TODO refine |
| 34 | raise MsgException(str(e)) |
| 35 | |
| 36 | def disconnect(self): |
| 37 | try: |
| tierno | ebbf353 | 2018-05-03 17:49:37 +0200 | [diff] [blame] | 38 | pass |
| 39 | # self.loop.close() |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 40 | except Exception as e: # TODO refine |
| 41 | raise MsgException(str(e)) |
| 42 | |
| 43 | def write(self, topic, key, msg): |
| tierno | 8657799 | 2018-05-10 16:51:17 +0200 | [diff] [blame] | 44 | """ |
| 45 | Write a message at kafka bus |
| 46 | :param topic: message topic, must be string |
| 47 | :param key: message key, must be string |
| 48 | :param msg: message content, can be string or dictionary |
| 49 | :return: None or raises MsgException on failing |
| 50 | """ |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 51 | try: |
| tierno | 8657799 | 2018-05-10 16:51:17 +0200 | [diff] [blame] | 52 | self.loop.run_until_complete(self.aiowrite(topic=topic, key=key, msg=msg)) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 53 | |
| 54 | except Exception as e: |
| 55 | raise MsgException("Error writing {} topic: {}".format(topic, str(e))) |
| 56 | |
| 57 | def read(self, topic): |
| 58 | """ |
| tierno | 8657799 | 2018-05-10 16:51:17 +0200 | [diff] [blame] | 59 | Read from one or several topics. |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 60 | :param topic: can be str: single topic; or str list: several topics |
| 61 | :return: topic, key, message; or None |
| 62 | """ |
| 63 | try: |
| 64 | return self.loop.run_until_complete(self.aioread(topic, self.loop)) |
| 65 | except MsgException: |
| 66 | raise |
| 67 | except Exception as e: |
| 68 | raise MsgException("Error reading {} topic: {}".format(topic, str(e))) |
| 69 | |
| 70 | async def aiowrite(self, topic, key, msg, loop=None): |
| 71 | |
| 72 | if not loop: |
| 73 | loop = self.loop |
| 74 | try: |
| 75 | self.producer = AIOKafkaProducer(loop=loop, key_serializer=str.encode, value_serializer=str.encode, |
| 76 | bootstrap_servers=self.broker) |
| 77 | await self.producer.start() |
| tierno | 3054f78 | 2018-04-25 16:59:53 +0200 | [diff] [blame] | 78 | await self.producer.send(topic=topic, key=key, value=yaml.safe_dump(msg, default_flow_style=True)) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 79 | except Exception as e: |
| tierno | 3054f78 | 2018-04-25 16:59:53 +0200 | [diff] [blame] | 80 | raise MsgException("Error publishing topic '{}', key '{}': {}".format(topic, key, e)) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 81 | finally: |
| 82 | await self.producer.stop() |
| 83 | |
| 84 | async def aioread(self, topic, loop=None, callback=None, *args): |
| 85 | """ |
| 86 | Asyncio read from one or several topics. It blocks |
| 87 | :param topic: can be str: single topic; or str list: several topics |
| 88 | :param loop: asyncio loop |
| 89 | :callback: callback function that will handle the message in kafka bus |
| 90 | :*args: optional arguments for callback function |
| 91 | :return: topic, key, message |
| 92 | """ |
| 93 | |
| 94 | if not loop: |
| 95 | loop = self.loop |
| 96 | try: |
| 97 | if isinstance(topic, (list, tuple)): |
| 98 | topic_list = topic |
| 99 | else: |
| 100 | topic_list = (topic,) |
| 101 | |
| 102 | self.consumer = AIOKafkaConsumer(loop=loop, bootstrap_servers=self.broker) |
| 103 | await self.consumer.start() |
| 104 | self.consumer.subscribe(topic_list) |
| 105 | |
| 106 | async for message in self.consumer: |
| 107 | if callback: |
| 108 | callback(message.topic, yaml.load(message.key), yaml.load(message.value), *args) |
| 109 | else: |
| 110 | return message.topic, yaml.load(message.key), yaml.load(message.value) |
| 111 | except KafkaError as e: |
| 112 | raise MsgException(str(e)) |
| 113 | finally: |
| 114 | await self.consumer.stop() |