blob: 6da5b5270e290d4148b09699b58e1f3284e46449 [file] [log] [blame]
DR695H6a3fad82019-06-03 21:32:22 -04001# Copyright 2019 AT&T Intellectual Property. All rights reserved.
2#
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
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
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.
14from pykafka import KafkaClient
15from pykafka.common import OffsetType
16from robot.api.deco import keyword
17from robot import utils
18
19
20class KafkaKeywords(object):
21 """ Utilities useful for Kafka consuming and producing """
22
23 def __init__(self):
24 super(KafkaKeywords, self).__init__()
25 self._cache = utils.ConnectionCache('No Kafka Environments created')
26
27 @keyword
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)
32
33 @keyword
34 def produce(self, alias, topic, key, value):
35 assert topic
36 assert value
37
38 producer = self._get_producer(alias, topic)
39 return producer.produce(value, key)
40
41 def _get_producer(self, alias, topic_name):
42 topic = self._cache.switch(alias).topics[topic_name]
43 prod = topic.get_sync_producer()
44 return prod
45
46 @keyword
47 def consume(self, alias, topic_name, consumer_group=None):
48 assert topic_name
49
50 consumer = self._get_consumer(alias, topic_name, consumer_group)
51 msg = consumer.consume()
52 if msg is None:
53 return None
54 else:
55 return msg.value
56
57 def _get_consumer(self, alias, topic_name, consumer_group=None, set_offset_to_earliest=False):
58 assert topic_name
59
60 # default to the topic as group name
61 if consumer_group:
62 cgn = consumer_group
63 else:
64 cgn = topic_name
65
66 topic = self._cache.switch(alias).topics[topic_name]
67
68 offset_type = OffsetType.LATEST
69 if set_offset_to_earliest:
70 offset_type = OffsetType.EARLIEST
71
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)
75
76 return c