-
Notifications
You must be signed in to change notification settings - Fork 2
/
kafka_interface.py
220 lines (188 loc) · 8.12 KB
/
kafka_interface.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import sys, os, logging
import requests
import json
from confluent_kafka import SerializingProducer, DeserializingConsumer
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroSerializer, AvroDeserializer
from confluent_kafka.error import ValueDeserializationError, KeyDeserializationError
import avro.schema
LOGGER = logging.getLogger(__name__)
# Environment variables
BOOTSTRAP_SERVERS = os.getenv("BOOTSTRAP_SERVERS", "broker:29092")
SCHEMA_REGISTRY_URL = os.getenv("SCHEMA_REGISTRY_URL", "http://schema-registry:8081")
AVRO_SCHEMAS_ROOT = os.getenv("AVRO_SCHEMAS_ROOT", "/avro_schemas")
class kafka_producer(object):
"""
A kafka producer configured for a given topic
"""
def __init__(self, topic, value_schema_file=False, key_schema_file=False):
LOGGER.info("Initializing Producer")
self.topic = topic
schema_reg_config = {'url': SCHEMA_REGISTRY_URL}
schema_registry_client = SchemaRegistryClient(schema_reg_config)
# load value schema from file if specified, use default file name if not specified
# last check registry for latest version
if key_schema_file:
self.key_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
key_schema_file,
)
else:
self.key_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
"%s-key.avsc" % topic,
)
LOGGER.info("Reading key schema file: %s", self.key_schema_file)
if os.path.exists(self.key_schema_file):
with open(self.key_schema_file, "rb") as f:
self.key_schema_str = str(avro.schema.parse(f.read()))
else:
LOGGER.info("No local key schema file, checking registry")
key_schema_url = (
SCHEMA_REGISTRY_URL + '/subjects/' + self.topic + '-key/versions/latest'
)
r = requests.get(key_schema_url)
r.raise_for_status()
self.key_schema_str = json.dumps(r.json()['schema'])
self.key_avro_serializer = AvroSerializer(
schema_registry_client, self.key_schema_str
)
# load value schema from file if specified, use default file name if not specified
# last check registry for latest version
if value_schema_file:
self.value_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
value_schema_file,
)
else:
self.value_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
"%s-value.avsc" % topic,
)
LOGGER.info("Reading value schema file: %s", self.value_schema_file)
if os.path.exists(self.value_schema_file):
with open(self.value_schema_file, "rb") as f:
self.value_schema_str = str(avro.schema.parse(f.read()))
else:
LOGGER.info("No local value schema file, checking registry")
value_schema_url = (
SCHEMA_REGISTRY_URL + '/subjects/' + self.topic + '-value/versions/latest'
)
r = requests.get(value_schema_url)
r.raise_for_status()
self.value_schema_str = json.dumps(r.json()['schema'])
self.value_avro_serializer = AvroSerializer(
schema_registry_client, self.value_schema_str
)
producer_config = {
'bootstrap.servers': BOOTSTRAP_SERVERS,
'key.serializer': self.key_avro_serializer,
'value.serializer': self.value_avro_serializer,
'linger.ms': 5,
'enable.idempotence': True,
}
self.producer = SerializingProducer(producer_config)
def produce(self, key, message):
self.producer.produce(self.topic, key, message)
def flush(self):
self.producer.flush()
def produce_and_flush(self, key, message):
self.producer.produce(self.topic, key, message)
self.producer.flush()
class kafka_consumer(object):
"""
A kafka consumer configured for a given topic.
"""
def __init__(self, topic, value_schema_file=False, key_schema_file=False, consumer_group=False):
self.topic = topic
schema_reg_config = {'url': SCHEMA_REGISTRY_URL}
schema_registry_client = SchemaRegistryClient(schema_reg_config)
# load key schema from file if specified, use default file name if not specified
# last check registry for latest version
if key_schema_file:
self.key_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
key_schema_file,
)
else:
self.key_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
"%s-key.avsc" % topic,
)
LOGGER.info("Reading key schema file: %s", self.key_schema_file)
if os.path.exists(self.key_schema_file):
with open(self.key_schema_file, "rb") as f:
self.key_schema_str = str(avro.schema.parse(f.read()))
else:
LOGGER.info("No local key schema file, checking registry")
key_schema_url = (
SCHEMA_REGISTRY_URL + '/subjects/' + self.topic + '-key/versions/latest'
)
r = requests.get(key_schema_url)
r.raise_for_status()
self.key_schema_str = r.json()['schema']
self.key_avro_deserializer = AvroDeserializer(
schema_registry_client, self.key_schema_str
)
# load value schema from file if specified, use default file name if not specified
# last check registry for latest version
if value_schema_file:
self.value_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
value_schema_file,
)
else:
self.value_schema_file = os.path.join(
AVRO_SCHEMAS_ROOT,
"%s-value.avsc" % topic,
)
LOGGER.info("Reading value schema file: %s", self.value_schema_file)
if os.path.exists(self.value_schema_file):
with open(self.value_schema_file, "rb") as f:
self.value_schema_str = str(avro.schema.parse(f.read()))
else:
LOGGER.info("No local value schema file, checking registry")
value_schema_url = (
SCHEMA_REGISTRY_URL + '/subjects/' + self.topic + '-value/versions/latest'
)
r = requests.get(value_schema_url)
r.raise_for_status()
self.value_schema_str = r.json()['schema']
self.value_avro_deserializer = AvroDeserializer(
schema_registry_client, self.value_schema_str
)
# use consumer group name if given, otherwise default to using topic name
if consumer_group:
self.consumer_group = consumer_group
else:
self.consumer_group = self.topic
consumer_config = {
'bootstrap.servers': BOOTSTRAP_SERVERS,
'key.deserializer': self.key_avro_deserializer,
'group.id': self.consumer_group,
'value.deserializer': self.value_avro_deserializer,
'session.timeout.ms': 6000,
'heartbeat.interval.ms': 2000,
'auto.offset.reset': 'earliest',
}
self.consumer = DeserializingConsumer(consumer_config)
self.consumer.subscribe([self.topic])
LOGGER.info("Consumer subscribed to topic: %s", self.topic)
LOGGER.info("Consumer group id: %s", self.consumer_group)
def consume(self):
while True:
try:
# poll for 1 second at a time
poll = self.consumer.poll(1)
if poll:
return {"offset": poll.offset(), "key": poll.key(), "value": poll.value()}
except KeyDeserializationError:
LOGGER.error('KeyDeserializationError')
continue
except ValueDeserializationError:
LOGGER.error('ValueDeserializationError')
continue
except KeyboardInterrupt:
LOGGER.error('Stopping via keyboardInterrupt')
# sys.exit()
raise