1 # Copyright 2019 AT&T Intellectual Property. All rights reserved.
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 implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from pykafka import KafkaClient
15 from pykafka.common import OffsetType
16 from robot.api.deco import keyword
17 from robot import utils
20 class KafkaKeywords(object):
21 """ Utilities useful for Kafka consuming and producing """
24 super(KafkaKeywords, self).__init__()
25 self._cache = utils.ConnectionCache('No Kafka Environments created')
28 def connect(self, alias, kafka_host, kafka_version="1.0.0"):
29 """connect to the specified kafka server"""
30 client = KafkaClient(hosts=kafka_host, broker_version=kafka_version)
31 self._cache.register(client, alias=alias)
34 def produce(self, alias, topic, key, value):
38 producer = self._get_producer(alias, topic)
39 return producer.produce(value, key)
41 def _get_producer(self, alias, topic_name):
42 topic = self._cache.switch(alias).topics[topic_name]
43 prod = topic.get_sync_producer()
47 def consume(self, alias, topic_name, consumer_group=None):
50 consumer = self._get_consumer(alias, topic_name, consumer_group)
51 msg = consumer.consume()
57 def _get_consumer(self, alias, topic_name, consumer_group=None, set_offset_to_earliest=False):
60 # default to the topic as group name
66 topic = self._cache.switch(alias).topics[topic_name]
68 offset_type = OffsetType.LATEST
69 if set_offset_to_earliest:
70 offset_type = OffsetType.EARLIEST
72 c = topic.get_simple_consumer(
73 consumer_group=cgn, auto_offset_reset=offset_type, auto_commit_enable=True,
74 reset_offset_on_start=True, consumer_timeout_ms=5000)