blob: aaa0c3c24ca5c05dcf2531460ed69ca66e900c1e [file] [log] [blame]
khenaidoob9203542018-09-17 22:56:37 -04001#!/usr/bin/env python
2
Zack Williams998f4422018-09-19 10:38:57 -07003# Copyright 2018 the original author or authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
khenaidoo6fdf0ba2018-11-02 14:38:33 -040017import time
18from uuid import uuid4
19
20import structlog
21from afkak.client import KafkaClient
22from afkak.consumer import OFFSET_LATEST, Consumer
khenaidoob9203542018-09-17 22:56:37 -040023from twisted.internet import reactor
24from twisted.internet.defer import inlineCallbacks, returnValue, Deferred, \
25 DeferredQueue, gatherResults
khenaidoo6fdf0ba2018-11-02 14:38:33 -040026from zope.interface import implementer
khenaidoob9203542018-09-17 22:56:37 -040027
khenaidoofdbad6e2018-11-06 22:26:38 -050028from python.common.utils import asleep
29from python.common.utils.registry import IComponent
30from kafka_proxy import KafkaProxy, get_kafka_proxy
31from python.protos.core_adapter_pb2 import MessageType, Argument, \
khenaidoo6fdf0ba2018-11-02 14:38:33 -040032 InterContainerRequestBody, InterContainerMessage, Header, \
33 InterContainerResponseBody
khenaidoob9203542018-09-17 22:56:37 -040034
35log = structlog.get_logger()
36
khenaidoo6fdf0ba2018-11-02 14:38:33 -040037
khenaidoob9203542018-09-17 22:56:37 -040038class KafkaMessagingError(BaseException):
39 def __init__(self, error):
40 self.error = error
41
khenaidoo6fdf0ba2018-11-02 14:38:33 -040042
khenaidoob9203542018-09-17 22:56:37 -040043@implementer(IComponent)
44class IKafkaMessagingProxy(object):
45 _kafka_messaging_instance = None
46
47 def __init__(self,
48 kafka_host_port,
49 kv_store,
50 default_topic,
51 target_cls):
52 """
53 Initialize the kafka proxy. This is a singleton (may change to
54 non-singleton if performance is better)
55 :param kafka_host_port: Kafka host and port
56 :param kv_store: Key-Value store
57 :param default_topic: Default topic to subscribe to
58 :param target_cls: target class - method of that class is invoked
59 when a message is received on the default_topic
60 """
61 # return an exception if the object already exist
62 if IKafkaMessagingProxy._kafka_messaging_instance:
63 raise Exception(
64 'Singleton-exist', cls=IKafkaMessagingProxy)
65
66 log.debug("Initializing-KafkaProxy")
67 self.kafka_host_port = kafka_host_port
68 self.kv_store = kv_store
69 self.default_topic = default_topic
70 self.target_cls = target_cls
71 self.topic_target_cls_map = {}
72 self.topic_consumer_map = {}
73 self.topic_callback_map = {}
74 self.subscribers = {}
75 self.kafka_client = None
76 self.kafka_proxy = None
77 self.transaction_id_deferred_map = {}
78 self.received_msg_queue = DeferredQueue()
79
80 self.init_time = 0
81 self.init_received_time = 0
82
83 self.init_resp_time = 0
84 self.init_received_resp_time = 0
85
86 self.num_messages = 0
87 self.total_time = 0
88 self.num_responses = 0
89 self.total_time_responses = 0
90 log.debug("KafkaProxy-initialized")
91
92 def start(self):
93 try:
94 # Create the kafka client
95 # assert self.kafka_host is not None
96 # assert self.kafka_port is not None
97 # kafka_host_port = ":".join((self.kafka_host, self.kafka_port))
98 self.kafka_client = KafkaClient(self.kafka_host_port)
99
100 # Get the kafka proxy instance. If it does not exist then
101 # create it
102 self.kafka_proxy = get_kafka_proxy()
103 if self.kafka_proxy == None:
104 KafkaProxy(kafka_endpoint=self.kafka_host_port).start()
105 self.kafka_proxy = get_kafka_proxy()
106
107 # Subscribe the default topic and target_cls
108 self.topic_target_cls_map[self.default_topic] = self.target_cls
109
110 # Start the queue to handle incoming messages
111 reactor.callLater(0, self._received_message_processing_loop)
112
113 # Start listening for incoming messages
114 reactor.callLater(0, self.subscribe, self.default_topic,
115 target_cls=self.target_cls)
116
117 # Setup the singleton instance
118 IKafkaMessagingProxy._kafka_messaging_instance = self
119 except Exception as e:
120 log.exception("Failed-to-start-proxy", e=e)
121
khenaidoob9203542018-09-17 22:56:37 -0400122 def stop(self):
123 """
124 Invoked to stop the kafka proxy
125 :return: None on success, Exception on failure
126 """
127 log.debug("Stopping-messaging-proxy ...")
128 try:
129 # Stop all the consumers
130 deferred_list = []
131 for key, values in self.topic_consumer_map.iteritems():
132 deferred_list.extend([c.stop() for c in values])
133
134 if not deferred_list:
135 d = gatherResults(deferred_list)
136 d.addCallback(lambda result: self.kafka_client.close())
137 log.debug("Messaging-proxy-stopped.")
138 except Exception as e:
139 log.exception("Exception-when-stopping-messaging-proxy:", e=e)
140
khenaidoob9203542018-09-17 22:56:37 -0400141 @inlineCallbacks
142 def _wait_until_topic_is_ready(self, client, topic):
143 e = True
144 while e:
145 yield client.load_metadata_for_topics(topic)
146 e = client.metadata_error_for_topic(topic)
147 if e:
148 log.debug("Topic-not-ready-retrying...", topic=topic)
149
150 def _clear_backoff(self):
151 if self.retries:
152 log.info('reconnected-to-consul', after_retries=self.retries)
153 self.retries = 0
154
khenaidoo43c82122018-11-22 18:38:28 -0500155 def get_target_cls(self):
156 return self.target_cls
157
158 def get_default_topic(self):
159 return self.default_topic
160
khenaidoob9203542018-09-17 22:56:37 -0400161 @inlineCallbacks
162 def _subscribe(self, topic, callback=None, target_cls=None):
163 try:
164 yield self._wait_until_topic_is_ready(self.kafka_client, topic)
165 partitions = self.kafka_client.topic_partitions[topic]
166 consumers = []
167
168 # First setup the generic callback - all received messages will
169 # go through that queue
170 if topic not in self.topic_consumer_map:
171 consumers = [Consumer(self.kafka_client, topic, partition,
172 self._enqueue_received_message)
173 for partition in partitions]
174 self.topic_consumer_map[topic] = consumers
175
khenaidoo6fdf0ba2018-11-02 14:38:33 -0400176 log.debug("_subscribe", topic=topic,
177 consumermap=self.topic_consumer_map)
khenaidoob9203542018-09-17 22:56:37 -0400178
179 if target_cls is not None and callback is None:
180 # Scenario #1
181 if topic not in self.topic_target_cls_map:
182 self.topic_target_cls_map[topic] = target_cls
183 elif target_cls is None and callback is not None:
184 # Scenario #2
185 log.debug("custom-callback", topic=topic,
186 callback_map=self.topic_callback_map)
187 if topic not in self.topic_callback_map:
188 self.topic_callback_map[topic] = [callback]
189 else:
190 self.topic_callback_map[topic].extend([callback])
191 else:
192 log.warn("invalid-parameters")
193
194 def cb_closed(result):
195 """
196 Called when a consumer cleanly stops.
197 """
198 log.debug("Consumers-cleanly-stopped")
199
200 def eb_failed(failure):
201 """
202 Called when a consumer fails due to an uncaught exception in the
203 processing callback or a network error on shutdown. In this case we
204 simply log the error.
205 """
206 log.warn("Consumers-failed", failure=failure)
207
208 for c in consumers:
209 c.start(OFFSET_LATEST).addCallbacks(cb_closed, eb_failed)
210
211 returnValue(True)
212 except Exception as e:
213 log.exception("Exception-during-subscription", e=e)
214 returnValue(False)
215
216 def subscribe(self, topic, callback=None, target_cls=None,
217 max_retry=3):
218 """
219 Scenario 1: invoked to subscribe to a specific topic with a
220 target_cls to invoke when a message is received on that topic. This
221 handles the case of request/response where this library performs the
222 heavy lifting. In this case the m_callback must to be None
223
224 Scenario 2: invoked to subscribe to a specific topic with a
225 specific callback to invoke when a message is received on that topic.
226 This handles the case where the caller wants to process the message
227 received itself. In this case the target_cls must to be None
228
229 :param topic: topic to subscribe to
230 :param callback: Callback to invoke when a message is received on
231 the topic. Either one of callback or target_cls needs can be none
232 :param target_cls: Target class to use when a message is
233 received on the topic. There can only be 1 target_cls per topic.
234 Either one of callback or target_cls needs can be none
235 :param max_retry: the number of retries before reporting failure
236 to subscribe. This caters for scenario where the kafka topic is not
237 ready.
238 :return: True on success, False on failure
239 """
240 RETRY_BACKOFF = [0.05, 0.1, 0.2, 0.5, 1, 2, 5]
241
242 def _backoff(msg, retries):
243 wait_time = RETRY_BACKOFF[min(retries,
244 len(RETRY_BACKOFF) - 1)]
245 log.info(msg, retry_in=wait_time)
246 return asleep(wait_time)
247
248 retry = 0
249 while not self._subscribe(topic, callback=callback,
250 target_cls=target_cls):
251 if retry > max_retry:
252 return False
253 else:
254 _backoff("subscription-not-complete", retry)
255 retry += 1
256 return True
257
258 def unsubscribe(self, topic):
259 """
260 Invoked when unsubscribing to a topic
261 :param topic: topic to unsubscibe from
262 :return: None on success or Exception on failure
263 """
264 log.debug("Unsubscribing-to-topic", topic=topic)
265
266 def remove_topic(topic):
267 if topic in self.topic_consumer_map:
268 del self.topic_consumer_map[topic]
269
270 try:
271 if topic in self.topic_consumer_map:
272 consumers = self.topic_consumer_map[topic]
273 d = gatherResults([c.stop() for c in consumers])
274 d.addCallback(remove_topic, topic)
275 log.debug("Unsubscribed-to-topic.", topic=topic)
276 else:
277 log.debug("Topic-does-not-exist.", topic=topic)
278 except Exception as e:
279 log.exception("Exception-when-stopping-messaging-proxy:", e=e)
280
281 @inlineCallbacks
282 def _enqueue_received_message(self, reactor, message_list):
283 """
284 Internal method to continuously queue all received messaged
285 irrespective of topic
286 :param reactor: A requirement by the Twisted Python kafka library
287 :param message_list: Received list of messages
288 :return: None on success, Exception on failure
289 """
290 try:
291 for m in message_list:
292 log.debug("received-msg", msg=m)
293 yield self.received_msg_queue.put(m)
294 except Exception as e:
295 log.exception("Failed-enqueueing-received-message", e=e)
296
297 @inlineCallbacks
298 def _received_message_processing_loop(self):
299 """
300 Internal method to continuously process all received messages one
301 at a time
302 :return: None on success, Exception on failure
303 """
304 while True:
305 try:
306 message = yield self.received_msg_queue.get()
307 yield self._process_message(message)
308 except Exception as e:
309 log.exception("Failed-dequeueing-received-message", e=e)
310
311 def _to_string(self, unicode_str):
312 if unicode_str is not None:
313 if type(unicode_str) == unicode:
314 return unicode_str.encode('ascii', 'ignore')
315 else:
316 return unicode_str
317 else:
318 return None
319
320 def _format_request(self,
321 rpc,
322 to_topic,
323 reply_topic,
324 **kwargs):
325 """
326 Format a request to send over kafka
327 :param rpc: Requested remote API
328 :param to_topic: Topic to send the request
329 :param reply_topic: Topic to receive the resulting response, if any
330 :param kwargs: Dictionary of key-value pairs to pass as arguments to
331 the remote rpc API.
332 :return: A InterContainerMessage message type on success or None on
333 failure
334 """
335 try:
336 transaction_id = uuid4().hex
337 request = InterContainerMessage()
338 request_body = InterContainerRequestBody()
339 request.header.id = transaction_id
340 request.header.type = MessageType.Value("REQUEST")
khenaidoo43c82122018-11-22 18:38:28 -0500341 request.header.from_topic = reply_topic
khenaidoob9203542018-09-17 22:56:37 -0400342 request.header.to_topic = to_topic
343
344 response_required = False
345 if reply_topic:
346 request_body.reply_to_topic = reply_topic
khenaidoo43c82122018-11-22 18:38:28 -0500347 request_body.response_required = True
khenaidoob9203542018-09-17 22:56:37 -0400348 response_required = True
349
350 request.header.timestamp = int(round(time.time() * 1000))
351 request_body.rpc = rpc
352 for a, b in kwargs.iteritems():
353 arg = Argument()
354 arg.key = a
355 try:
356 arg.value.Pack(b)
357 request_body.args.extend([arg])
358 except Exception as e:
359 log.exception("Failed-parsing-value", e=e)
khenaidoob9203542018-09-17 22:56:37 -0400360 request.body.Pack(request_body)
361 return request, transaction_id, response_required
362 except Exception as e:
363 log.exception("formatting-request-failed",
364 rpc=rpc,
365 to_topic=to_topic,
366 reply_topic=reply_topic,
367 args=kwargs)
368 return None, None, None
369
370 def _format_response(self, msg_header, msg_body, status):
371 """
372 Format a response
373 :param msg_header: The header portion of a received request
374 :param msg_body: The response body
375 :param status: True is this represents a successful response
376 :return: a InterContainerMessage message type
377 """
378 try:
379 assert isinstance(msg_header, Header)
380 response = InterContainerMessage()
381 response_body = InterContainerResponseBody()
382 response.header.id = msg_header.id
383 response.header.timestamp = int(
384 round(time.time() * 1000))
385 response.header.type = MessageType.Value("RESPONSE")
386 response.header.from_topic = msg_header.to_topic
387 response.header.to_topic = msg_header.from_topic
388 if msg_body is not None:
389 response_body.result.Pack(msg_body)
390 response_body.success = status
391 response.body.Pack(response_body)
392 return response
393 except Exception as e:
394 log.exception("formatting-response-failed", header=msg_header,
395 body=msg_body, status=status, e=e)
396 return None
397
398 def _parse_response(self, msg):
399 try:
400 message = InterContainerMessage()
401 message.ParseFromString(msg)
402 resp = InterContainerResponseBody()
403 if message.body.Is(InterContainerResponseBody.DESCRIPTOR):
404 message.body.Unpack(resp)
405 else:
406 log.debug("unsupported-msg", msg_type=type(message.body))
407 return None
408 log.debug("parsed-response", input=message, output=resp)
409 return resp
410 except Exception as e:
411 log.exception("parsing-response-failed", msg=msg, e=e)
412 return None
413
414 @inlineCallbacks
415 def _process_message(self, m):
416 """
417 Default internal method invoked for every batch of messages received
418 from Kafka.
419 """
khenaidoo6fdf0ba2018-11-02 14:38:33 -0400420
khenaidoob9203542018-09-17 22:56:37 -0400421 def _toDict(args):
422 """
423 Convert a repeatable Argument type into a python dictionary
424 :param args: Repeatable core_adapter.Argument type
425 :return: a python dictionary
426 """
427 if args is None:
428 return None
429 result = {}
430 for arg in args:
431 assert isinstance(arg, Argument)
432 result[arg.key] = arg.value
433 return result
434
435 current_time = int(round(time.time() * 1000))
436 # log.debug("Got Message", message=m)
437 try:
438 val = m.message.value
439 # print m.topic
440
441 # Go over customized callbacks first
442 if m.topic in self.topic_callback_map:
443 for c in self.topic_callback_map[m.topic]:
444 yield c(val)
445
446 # Check whether we need to process request/response scenario
447 if m.topic not in self.topic_target_cls_map:
448 return
449
450 # Process request/response scenario
451 message = InterContainerMessage()
452 message.ParseFromString(val)
453
454 if message.header.type == MessageType.Value("REQUEST"):
khenaidoob9203542018-09-17 22:56:37 -0400455 # Get the target class for that specific topic
456 targetted_topic = self._to_string(message.header.to_topic)
457 msg_body = InterContainerRequestBody()
458 if message.body.Is(InterContainerRequestBody.DESCRIPTOR):
459 message.body.Unpack(msg_body)
460 else:
461 log.debug("unsupported-msg", msg_type=type(message.body))
462 return
463 if targetted_topic in self.topic_target_cls_map:
464 if msg_body.args:
465 log.debug("message-body-args-present", body=msg_body)
466 (status, res) = yield getattr(
467 self.topic_target_cls_map[targetted_topic],
468 self._to_string(msg_body.rpc))(
469 **_toDict(msg_body.args))
470 else:
471 log.debug("message-body-args-absent", body=msg_body,
472 rpc=msg_body.rpc)
473 (status, res) = yield getattr(
474 self.topic_target_cls_map[targetted_topic],
475 self._to_string(msg_body.rpc))()
476 if msg_body.response_required:
477 response = self._format_response(
478 msg_header=message.header,
479 msg_body=res,
480 status=status,
481 )
482 if response is not None:
483 res_topic = self._to_string(
484 response.header.to_topic)
485 self._send_kafka_message(res_topic, response)
486
khenaidoo43c82122018-11-22 18:38:28 -0500487 log.debug("Response-sent", response=response.body, to_topic=res_topic)
khenaidoob9203542018-09-17 22:56:37 -0400488 elif message.header.type == MessageType.Value("RESPONSE"):
489 trns_id = self._to_string(message.header.id)
490 if trns_id in self.transaction_id_deferred_map:
khenaidoob9203542018-09-17 22:56:37 -0400491 resp = self._parse_response(val)
492
493 self.transaction_id_deferred_map[trns_id].callback(resp)
494 else:
495 log.error("!!INVALID-TRANSACTION-TYPE!!")
496
497 except Exception as e:
498 log.exception("Failed-to-process-message", message=m, e=e)
499
500 @inlineCallbacks
501 def _send_kafka_message(self, topic, msg):
502 try:
503 yield self.kafka_proxy.send_message(topic, msg.SerializeToString())
504 except Exception, e:
505 log.exception("Failed-sending-message", message=msg, e=e)
506
507 @inlineCallbacks
508 def send_request(self,
509 rpc,
510 to_topic,
511 reply_topic=None,
512 callback=None,
513 **kwargs):
514 """
515 Invoked to send a message to a remote container and receive a
516 response if required.
517 :param rpc: The remote API to invoke
518 :param to_topic: Send the message to this kafka topic
519 :param reply_topic: If not None then a response is expected on this
520 topic. If set to None then no response is required.
521 :param callback: Callback to invoke when a response is received.
522 :param kwargs: Key-value pairs representing arguments to pass to the
523 rpc remote API.
524 :return: Either no response is required, or a response is returned
525 via the callback or the response is a tuple of (status, return_cls)
526 """
527 try:
528 # Ensure all strings are not unicode encoded
529 rpc = self._to_string(rpc)
530 to_topic = self._to_string(to_topic)
531 reply_topic = self._to_string(reply_topic)
532
533 request, transaction_id, response_required = \
534 self._format_request(
535 rpc=rpc,
536 to_topic=to_topic,
537 reply_topic=reply_topic,
538 **kwargs)
539
540 if request is None:
541 return
542
543 # Add the transaction to the transaction map before sending the
544 # request. This will guarantee the eventual response will be
545 # processed.
546 wait_for_result = None
547 if response_required:
548 wait_for_result = Deferred()
549 self.transaction_id_deferred_map[
550 self._to_string(request.header.id)] = wait_for_result
551
khenaidoob9203542018-09-17 22:56:37 -0400552 yield self._send_kafka_message(to_topic, request)
khenaidoo6fdf0ba2018-11-02 14:38:33 -0400553 log.debug("message-sent", to_topic=to_topic,
554 from_topic=reply_topic)
khenaidoob9203542018-09-17 22:56:37 -0400555
556 if response_required:
557 res = yield wait_for_result
558
559 if res is None or not res.success:
560 raise KafkaMessagingError(error="Failed-response:{"
561 "}".format(res))
562
563 # Remove the transaction from the transaction map
564 del self.transaction_id_deferred_map[transaction_id]
565
566 log.debug("send-message-response", rpc=rpc, result=res)
567
568 if callback:
569 callback((res.success, res.result))
570 else:
571 returnValue((res.success, res.result))
572 except Exception as e:
573 log.exception("Exception-sending-request", e=e)
574 raise KafkaMessagingError(error=e)
575
576
577# Common method to get the singleton instance of the kafka proxy class
578def get_messaging_proxy():
579 return IKafkaMessagingProxy._kafka_messaging_instance