X-Git-Url: https://osm.etsi.org/gitweb/?a=blobdiff_plain;f=osm_common%2Fmsgkafka.py;h=5487093b3478c6afc4507de6060436715a68aadc;hb=654c377eb49aff6b6c11340f91b69ee45da7fbc3;hp=91775f2d5062e79a2923191e23c8e413aac62345;hpb=562435aafccc3d73341e60332c8a33aa6b82aa79;p=osm%2Fcommon.git diff --git a/osm_common/msgkafka.py b/osm_common/msgkafka.py index 91775f2..5487093 100644 --- a/osm_common/msgkafka.py +++ b/osm_common/msgkafka.py @@ -13,20 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. -import logging import asyncio -import yaml +import logging + from aiokafka import AIOKafkaConsumer from aiokafka import AIOKafkaProducer from aiokafka.errors import KafkaError from osm_common.msgbase import MsgBase, MsgException +import yaml -__author__ = "Alfonso Tierno , " \ - "Guillermo Calvino " +__author__ = ( + "Alfonso Tierno , " + "Guillermo Calvino " +) class MsgKafka(MsgBase): - def __init__(self, logger_name='msg', lock=False): + def __init__(self, logger_name="msg", lock=False): super().__init__(logger_name, lock) self.host = None self.port = None @@ -64,15 +67,19 @@ class MsgKafka(MsgBase): :param msg: message content, can be string or dictionary :return: None or raises MsgException on failing """ - retry = 2 # Try two times + retry = 2 # Try two times while retry: try: - self.loop.run_until_complete(self.aiowrite(topic=topic, key=key, msg=msg)) + self.loop.run_until_complete( + self.aiowrite(topic=topic, key=key, msg=msg) + ) break except Exception as e: retry -= 1 if retry == 0: - raise MsgException("Error writing {} topic: {}".format(topic, str(e))) + raise MsgException( + "Error writing {} topic: {}".format(topic, str(e)) + ) def read(self, topic): """ @@ -100,16 +107,33 @@ class MsgKafka(MsgBase): if not loop: loop = self.loop try: - self.producer = AIOKafkaProducer(loop=loop, key_serializer=str.encode, value_serializer=str.encode, - bootstrap_servers=self.broker) + self.producer = AIOKafkaProducer( + loop=loop, + key_serializer=str.encode, + value_serializer=str.encode, + bootstrap_servers=self.broker, + ) await self.producer.start() - await self.producer.send(topic=topic, key=key, value=yaml.safe_dump(msg, default_flow_style=True)) + await self.producer.send( + topic=topic, key=key, value=yaml.safe_dump(msg, default_flow_style=True) + ) except Exception as e: - raise MsgException("Error publishing topic '{}', key '{}': {}".format(topic, key, e)) + raise MsgException( + "Error publishing topic '{}', key '{}': {}".format(topic, key, e) + ) finally: await self.producer.stop() - async def aioread(self, topic, loop=None, callback=None, aiocallback=None, group_id=None, **kwargs): + async def aioread( + self, + topic, + loop=None, + callback=None, + aiocallback=None, + group_id=None, + from_beginning=None, + **kwargs + ): """ Asyncio read from one or several topics. :param topic: can be str: single topic; or str list: several topics @@ -118,6 +142,9 @@ class MsgKafka(MsgBase): :param aiocallback: async callback function that will handle the message in kafka bus :param group_id: kafka group_id to use. Can be False (set group_id to None), None (use general group_id provided at connect inside config), or a group_id string + :param from_beginning: if True, messages will be obtained from beginning instead of only new ones. + If group_id is supplied, only the not processed messages by other worker are obtained. + If group_id is None, all messages stored at kafka are obtained. :param kwargs: optional keyword arguments for callback function :return: If no callback defined, it returns (topic, key, message) """ @@ -133,19 +160,36 @@ class MsgKafka(MsgBase): topic_list = topic else: topic_list = (topic,) - - self.consumer = AIOKafkaConsumer(loop=loop, bootstrap_servers=self.broker, group_id=group_id) + self.consumer = AIOKafkaConsumer( + loop=loop, + bootstrap_servers=self.broker, + group_id=group_id, + auto_offset_reset="earliest" if from_beginning else "latest", + ) await self.consumer.start() self.consumer.subscribe(topic_list) async for message in self.consumer: if callback: - callback(message.topic, yaml.safe_load(message.key), yaml.safe_load(message.value), **kwargs) + callback( + message.topic, + yaml.safe_load(message.key), + yaml.safe_load(message.value), + **kwargs + ) elif aiocallback: - await aiocallback(message.topic, yaml.safe_load(message.key), yaml.safe_load(message.value), - **kwargs) + await aiocallback( + message.topic, + yaml.safe_load(message.key), + yaml.safe_load(message.value), + **kwargs + ) else: - return message.topic, yaml.safe_load(message.key), yaml.safe_load(message.value) + return ( + message.topic, + yaml.safe_load(message.key), + yaml.safe_load(message.value), + ) except KafkaError as e: raise MsgException(str(e)) finally: