1 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
19 from aiokafka
import AIOKafkaConsumer
20 from aiokafka
import AIOKafkaProducer
21 from aiokafka
.errors
import KafkaError
22 from osm_common
.msgbase
import MsgBase
, MsgException
26 "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>, "
27 "Guillermo Calvino <guillermo.calvinosanchez@altran.com>"
31 class MsgKafka(MsgBase
):
32 def __init__(self
, logger_name
="msg", lock
=False):
33 super().__init
__(logger_name
, lock
)
41 def connect(self
, config
):
43 if "logger_name" in config
:
44 self
.logger
= logging
.getLogger(config
["logger_name"])
45 self
.host
= config
["host"]
46 self
.port
= config
["port"]
47 self
.broker
= str(self
.host
) + ":" + str(self
.port
)
48 self
.group_id
= config
.get("group_id")
50 except Exception as e
: # TODO refine
51 raise MsgException(str(e
))
56 except Exception as e
: # TODO refine
57 raise MsgException(str(e
))
59 def write(self
, topic
, key
, msg
):
61 Write a message at kafka bus
62 :param topic: message topic, must be string
63 :param key: message key, must be string
64 :param msg: message content, can be string or dictionary
65 :return: None or raises MsgException on failing
67 retry
= 2 # Try two times
70 asyncio
.run(self
.aiowrite(topic
=topic
, key
=key
, msg
=msg
))
72 except Exception as e
:
76 "Error writing {} topic: {}".format(topic
, str(e
))
79 def read(self
, topic
):
81 Read from one or several topics.
82 :param topic: can be str: single topic; or str list: several topics
83 :return: topic, key, message; or None
86 return asyncio
.run(self
.aioread(topic
))
89 except Exception as e
:
90 raise MsgException("Error reading {} topic: {}".format(topic
, str(e
)))
92 async def aiowrite(self
, topic
, key
, msg
):
95 :param topic: str kafka topic
96 :param key: str kafka key
97 :param msg: str or dictionary kafka message
101 self
.producer
= AIOKafkaProducer(
102 key_serializer
=str.encode
,
103 value_serializer
=str.encode
,
104 bootstrap_servers
=self
.broker
,
106 await self
.producer
.start()
107 await self
.producer
.send(
108 topic
=topic
, key
=key
, value
=yaml
.safe_dump(msg
, default_flow_style
=True)
110 except Exception as e
:
112 "Error publishing topic '{}', key '{}': {}".format(topic
, key
, e
)
115 await self
.producer
.stop()
127 Asyncio read from one or several topics.
128 :param topic: can be str: single topic; or str list: several topics
129 :param callback: synchronous callback function that will handle the message in kafka bus
130 :param aiocallback: async callback function that will handle the message in kafka bus
131 :param group_id: kafka group_id to use. Can be False (set group_id to None), None (use general group_id provided
132 at connect inside config), or a group_id string
133 :param from_beginning: if True, messages will be obtained from beginning instead of only new ones.
134 If group_id is supplied, only the not processed messages by other worker are obtained.
135 If group_id is None, all messages stored at kafka are obtained.
136 :param kwargs: optional keyword arguments for callback function
137 :return: If no callback defined, it returns (topic, key, message)
139 if group_id
is False:
141 elif group_id
is None:
142 group_id
= self
.group_id
144 if isinstance(topic
, (list, tuple)):
147 topic_list
= (topic
,)
148 self
.consumer
= AIOKafkaConsumer(
149 bootstrap_servers
=self
.broker
,
151 auto_offset_reset
="earliest" if from_beginning
else "latest",
153 await self
.consumer
.start()
154 self
.consumer
.subscribe(topic_list
)
156 async for message
in self
.consumer
:
160 yaml
.safe_load(message
.key
),
161 yaml
.safe_load(message
.value
),
167 yaml
.safe_load(message
.key
),
168 yaml
.safe_load(message
.value
),
174 yaml
.safe_load(message
.key
),
175 yaml
.safe_load(message
.value
),
177 except KafkaError
as e
:
178 raise MsgException(str(e
))
180 await self
.consumer
.stop()