Support for mongodb replicaset connection (HA).
[osm/common.git] / osm_common / msgkafka.py
index 1e22c9f..4d02024 100644 (file)
@@ -64,11 +64,15 @@ class MsgKafka(MsgBase):
         :param msg: message content, can be string or dictionary
         :return: None or raises MsgException on failing
         """
-        try:
-            self.loop.run_until_complete(self.aiowrite(topic=topic, key=key, msg=msg))
-
-        except Exception as e:
-            raise MsgException("Error writing {} topic: {}".format(topic, str(e)))
+        retry = 2   # Try two times
+        while retry:
+            try:
+                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)))
 
     def read(self, topic):
         """
@@ -105,7 +109,8 @@ class MsgKafka(MsgBase):
         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
@@ -114,6 +119,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)
         """
@@ -129,8 +137,8 @@ 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)