blob: 33261912e2da3c950e6dcb0f3774b42c758ed186 [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package kafka
17
18import (
19 "context"
20 "errors"
21 "fmt"
22 "github.com/golang/protobuf/proto"
23 "github.com/golang/protobuf/ptypes"
24 "github.com/golang/protobuf/ptypes/any"
25 "github.com/google/uuid"
Scott Bakerce767002019-10-23 13:30:24 -070026 "github.com/opencord/voltha-lib-go/v2/pkg/log"
Scott Bakerf1b096c2019-11-01 12:36:30 -070027 ic "github.com/opencord/voltha-protos/v2/go/inter_container"
Scott Baker2c1c4822019-10-16 11:02:41 -070028 "reflect"
29 "strings"
30 "sync"
31 "time"
32)
33
34// Initialize the logger - gets the default until the main function setup the logger
35func init() {
36 log.AddPackage(log.JSON, log.DebugLevel, nil)
37}
38
39const (
40 DefaultMaxRetries = 3
41 DefaultRequestTimeout = 10000 // 10000 milliseconds - to handle a wider latency range
42)
43
44const (
45 TransactionKey = "transactionID"
46 FromTopic = "fromTopic"
47)
48
49var ErrorTransactionNotAcquired = errors.New("transaction-not-acquired")
50var ErrorTransactionInvalidId = errors.New("transaction-invalid-id")
51
52// requestHandlerChannel represents an interface associated with a channel. Whenever, an event is
53// obtained from that channel, this interface is invoked. This is used to handle
54// async requests into the Core via the kafka messaging bus
55type requestHandlerChannel struct {
56 requesthandlerInterface interface{}
57 ch <-chan *ic.InterContainerMessage
58}
59
60// transactionChannel represents a combination of a topic and a channel onto which a response received
61// on the kafka bus will be sent to
62type transactionChannel struct {
63 topic *Topic
64 ch chan *ic.InterContainerMessage
65}
66
67// InterContainerProxy represents the messaging proxy
68type InterContainerProxy struct {
69 kafkaHost string
70 kafkaPort int
71 DefaultTopic *Topic
72 defaultRequestHandlerInterface interface{}
73 deviceDiscoveryTopic *Topic
74 kafkaClient Client
75 doneCh chan int
76
77 // This map is used to map a topic to an interface and channel. When a request is received
78 // on that channel (registered to the topic) then that interface is invoked.
79 topicToRequestHandlerChannelMap map[string]*requestHandlerChannel
80 lockTopicRequestHandlerChannelMap sync.RWMutex
81
82 // This map is used to map a channel to a response topic. This channel handles all responses on that
83 // channel for that topic and forward them to the appropriate consumers channel, using the
84 // transactionIdToChannelMap.
85 topicToResponseChannelMap map[string]<-chan *ic.InterContainerMessage
86 lockTopicResponseChannelMap sync.RWMutex
87
88 // This map is used to map a transaction to a consumers channel. This is used whenever a request has been
89 // sent out and we are waiting for a response.
90 transactionIdToChannelMap map[string]*transactionChannel
91 lockTransactionIdToChannelMap sync.RWMutex
92}
93
94type InterContainerProxyOption func(*InterContainerProxy)
95
96func InterContainerHost(host string) InterContainerProxyOption {
97 return func(args *InterContainerProxy) {
98 args.kafkaHost = host
99 }
100}
101
102func InterContainerPort(port int) InterContainerProxyOption {
103 return func(args *InterContainerProxy) {
104 args.kafkaPort = port
105 }
106}
107
108func DefaultTopic(topic *Topic) InterContainerProxyOption {
109 return func(args *InterContainerProxy) {
110 args.DefaultTopic = topic
111 }
112}
113
114func DeviceDiscoveryTopic(topic *Topic) InterContainerProxyOption {
115 return func(args *InterContainerProxy) {
116 args.deviceDiscoveryTopic = topic
117 }
118}
119
120func RequestHandlerInterface(handler interface{}) InterContainerProxyOption {
121 return func(args *InterContainerProxy) {
122 args.defaultRequestHandlerInterface = handler
123 }
124}
125
126func MsgClient(client Client) InterContainerProxyOption {
127 return func(args *InterContainerProxy) {
128 args.kafkaClient = client
129 }
130}
131
132func NewInterContainerProxy(opts ...InterContainerProxyOption) (*InterContainerProxy, error) {
133 proxy := &InterContainerProxy{
134 kafkaHost: DefaultKafkaHost,
135 kafkaPort: DefaultKafkaPort,
136 }
137
138 for _, option := range opts {
139 option(proxy)
140 }
141
142 // Create the locks for all the maps
143 proxy.lockTopicRequestHandlerChannelMap = sync.RWMutex{}
144 proxy.lockTransactionIdToChannelMap = sync.RWMutex{}
145 proxy.lockTopicResponseChannelMap = sync.RWMutex{}
146
147 return proxy, nil
148}
149
150func (kp *InterContainerProxy) Start() error {
151 log.Info("Starting-Proxy")
152
153 // Kafka MsgClient should already have been created. If not, output fatal error
154 if kp.kafkaClient == nil {
155 log.Fatal("kafka-client-not-set")
156 }
157
158 // Create the Done channel
159 kp.doneCh = make(chan int, 1)
160
161 // Start the kafka client
162 if err := kp.kafkaClient.Start(); err != nil {
163 log.Errorw("Cannot-create-kafka-proxy", log.Fields{"error": err})
164 return err
165 }
166
167 // Create the topic to response channel map
168 kp.topicToResponseChannelMap = make(map[string]<-chan *ic.InterContainerMessage)
169 //
170 // Create the transactionId to Channel Map
171 kp.transactionIdToChannelMap = make(map[string]*transactionChannel)
172
173 // Create the topic to request channel map
174 kp.topicToRequestHandlerChannelMap = make(map[string]*requestHandlerChannel)
175
176 return nil
177}
178
179func (kp *InterContainerProxy) Stop() {
180 log.Info("stopping-intercontainer-proxy")
181 kp.doneCh <- 1
182 // TODO : Perform cleanup
183 kp.kafkaClient.Stop()
184 //kp.deleteAllTopicRequestHandlerChannelMap()
185 //kp.deleteAllTopicResponseChannelMap()
186 //kp.deleteAllTransactionIdToChannelMap()
187}
188
189// DeviceDiscovered publish the discovered device onto the kafka messaging bus
190func (kp *InterContainerProxy) DeviceDiscovered(deviceId string, deviceType string, parentId string, publisher string) error {
191 log.Debugw("sending-device-discovery-msg", log.Fields{"deviceId": deviceId})
192 // Simple validation
193 if deviceId == "" || deviceType == "" {
194 log.Errorw("invalid-parameters", log.Fields{"id": deviceId, "type": deviceType})
195 return errors.New("invalid-parameters")
196 }
197 // Create the device discovery message
198 header := &ic.Header{
199 Id: uuid.New().String(),
200 Type: ic.MessageType_DEVICE_DISCOVERED,
201 FromTopic: kp.DefaultTopic.Name,
202 ToTopic: kp.deviceDiscoveryTopic.Name,
203 Timestamp: time.Now().UnixNano(),
204 }
205 body := &ic.DeviceDiscovered{
206 Id: deviceId,
207 DeviceType: deviceType,
208 ParentId: parentId,
209 Publisher: publisher,
210 }
211
212 var marshalledData *any.Any
213 var err error
214 if marshalledData, err = ptypes.MarshalAny(body); err != nil {
215 log.Errorw("cannot-marshal-request", log.Fields{"error": err})
216 return err
217 }
218 msg := &ic.InterContainerMessage{
219 Header: header,
220 Body: marshalledData,
221 }
222
223 // Send the message
224 if err := kp.kafkaClient.Send(msg, kp.deviceDiscoveryTopic); err != nil {
225 log.Errorw("cannot-send-device-discovery-message", log.Fields{"error": err})
226 return err
227 }
228 return nil
229}
230
231// InvokeRPC is used to send a request to a given topic
232func (kp *InterContainerProxy) InvokeRPC(ctx context.Context, rpc string, toTopic *Topic, replyToTopic *Topic,
233 waitForResponse bool, key string, kvArgs ...*KVArg) (bool, *any.Any) {
234
235 // If a replyToTopic is provided then we use it, otherwise just use the default toTopic. The replyToTopic is
236 // typically the device ID.
237 responseTopic := replyToTopic
238 if responseTopic == nil {
239 responseTopic = kp.DefaultTopic
240 }
241
242 // Encode the request
243 protoRequest, err := encodeRequest(rpc, toTopic, responseTopic, key, kvArgs...)
244 if err != nil {
245 log.Warnw("cannot-format-request", log.Fields{"rpc": rpc, "error": err})
246 return false, nil
247 }
248
249 // Subscribe for response, if needed, before sending request
250 var ch <-chan *ic.InterContainerMessage
251 if waitForResponse {
252 var err error
253 if ch, err = kp.subscribeForResponse(*responseTopic, protoRequest.Header.Id); err != nil {
254 log.Errorw("failed-to-subscribe-for-response", log.Fields{"error": err, "toTopic": toTopic.Name})
255 }
256 }
257
258 // Send request - if the topic is formatted with a device Id then we will send the request using a
259 // specific key, hence ensuring a single partition is used to publish the request. This ensures that the
260 // subscriber on that topic will receive the request in the order it was sent. The key used is the deviceId.
261 //key := GetDeviceIdFromTopic(*toTopic)
262 log.Debugw("sending-msg", log.Fields{"rpc": rpc, "toTopic": toTopic, "replyTopic": responseTopic, "key": key, "xId": protoRequest.Header.Id})
263 go kp.kafkaClient.Send(protoRequest, toTopic, key)
264
265 if waitForResponse {
266 // Create a child context based on the parent context, if any
267 var cancel context.CancelFunc
268 childCtx := context.Background()
269 if ctx == nil {
270 ctx, cancel = context.WithTimeout(context.Background(), DefaultRequestTimeout*time.Millisecond)
271 } else {
272 childCtx, cancel = context.WithTimeout(ctx, DefaultRequestTimeout*time.Millisecond)
273 }
274 defer cancel()
275
276 // Wait for response as well as timeout or cancellation
277 // Remove the subscription for a response on return
278 defer kp.unSubscribeForResponse(protoRequest.Header.Id)
279 select {
280 case msg, ok := <-ch:
281 if !ok {
282 log.Warnw("channel-closed", log.Fields{"rpc": rpc, "replyTopic": replyToTopic.Name})
283 protoError := &ic.Error{Reason: "channel-closed"}
284 var marshalledArg *any.Any
285 if marshalledArg, err = ptypes.MarshalAny(protoError); err != nil {
286 return false, nil // Should never happen
287 }
288 return false, marshalledArg
289 }
290 log.Debugw("received-response", log.Fields{"rpc": rpc, "msgHeader": msg.Header})
291 var responseBody *ic.InterContainerResponseBody
292 var err error
293 if responseBody, err = decodeResponse(msg); err != nil {
294 log.Errorw("decode-response-error", log.Fields{"error": err})
295 }
296 return responseBody.Success, responseBody.Result
297 case <-ctx.Done():
298 log.Debugw("context-cancelled", log.Fields{"rpc": rpc, "ctx": ctx.Err()})
299 // pack the error as proto any type
300 protoError := &ic.Error{Reason: ctx.Err().Error()}
301 var marshalledArg *any.Any
302 if marshalledArg, err = ptypes.MarshalAny(protoError); err != nil {
303 return false, nil // Should never happen
304 }
305 return false, marshalledArg
306 case <-childCtx.Done():
307 log.Debugw("context-cancelled", log.Fields{"rpc": rpc, "ctx": childCtx.Err()})
308 // pack the error as proto any type
309 protoError := &ic.Error{Reason: childCtx.Err().Error()}
310 var marshalledArg *any.Any
311 if marshalledArg, err = ptypes.MarshalAny(protoError); err != nil {
312 return false, nil // Should never happen
313 }
314 return false, marshalledArg
315 case <-kp.doneCh:
316 log.Infow("received-exit-signal", log.Fields{"toTopic": toTopic.Name, "rpc": rpc})
317 return true, nil
318 }
319 }
320 return true, nil
321}
322
323// SubscribeWithRequestHandlerInterface allows a caller to assign a target object to be invoked automatically
324// when a message is received on a given topic
325func (kp *InterContainerProxy) SubscribeWithRequestHandlerInterface(topic Topic, handler interface{}) error {
326
327 // Subscribe to receive messages for that topic
328 var ch <-chan *ic.InterContainerMessage
329 var err error
330 if ch, err = kp.kafkaClient.Subscribe(&topic); err != nil {
331 //if ch, err = kp.Subscribe(topic); err != nil {
332 log.Errorw("failed-to-subscribe", log.Fields{"error": err, "topic": topic.Name})
333 return err
334 }
335
336 kp.defaultRequestHandlerInterface = handler
337 kp.addToTopicRequestHandlerChannelMap(topic.Name, &requestHandlerChannel{requesthandlerInterface: handler, ch: ch})
338 // Launch a go routine to receive and process kafka messages
339 go kp.waitForMessages(ch, topic, handler)
340
341 return nil
342}
343
344// SubscribeWithDefaultRequestHandler allows a caller to add a topic to an existing target object to be invoked automatically
345// when a message is received on a given topic. So far there is only 1 target registered per microservice
346func (kp *InterContainerProxy) SubscribeWithDefaultRequestHandler(topic Topic, initialOffset int64) error {
347 // Subscribe to receive messages for that topic
348 var ch <-chan *ic.InterContainerMessage
349 var err error
350 if ch, err = kp.kafkaClient.Subscribe(&topic, &KVArg{Key: Offset, Value: initialOffset}); err != nil {
351 log.Errorw("failed-to-subscribe", log.Fields{"error": err, "topic": topic.Name})
352 return err
353 }
354 kp.addToTopicRequestHandlerChannelMap(topic.Name, &requestHandlerChannel{requesthandlerInterface: kp.defaultRequestHandlerInterface, ch: ch})
355
356 // Launch a go routine to receive and process kafka messages
357 go kp.waitForMessages(ch, topic, kp.defaultRequestHandlerInterface)
358
359 return nil
360}
361
362func (kp *InterContainerProxy) UnSubscribeFromRequestHandler(topic Topic) error {
363 return kp.deleteFromTopicRequestHandlerChannelMap(topic.Name)
364}
365
366// setupTopicResponseChannelMap sets up single consumers channel that will act as a broadcast channel for all
367// responses from that topic.
368func (kp *InterContainerProxy) setupTopicResponseChannelMap(topic string, arg <-chan *ic.InterContainerMessage) {
369 kp.lockTopicResponseChannelMap.Lock()
370 defer kp.lockTopicResponseChannelMap.Unlock()
371 if _, exist := kp.topicToResponseChannelMap[topic]; !exist {
372 kp.topicToResponseChannelMap[topic] = arg
373 }
374}
375
376func (kp *InterContainerProxy) isTopicSubscribedForResponse(topic string) bool {
377 kp.lockTopicResponseChannelMap.RLock()
378 defer kp.lockTopicResponseChannelMap.RUnlock()
379 _, exist := kp.topicToResponseChannelMap[topic]
380 return exist
381}
382
383func (kp *InterContainerProxy) deleteFromTopicResponseChannelMap(topic string) error {
384 kp.lockTopicResponseChannelMap.Lock()
385 defer kp.lockTopicResponseChannelMap.Unlock()
386 if _, exist := kp.topicToResponseChannelMap[topic]; exist {
387 // Unsubscribe to this topic first - this will close the subscribed channel
388 var err error
389 if err = kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToResponseChannelMap[topic]); err != nil {
390 log.Errorw("unsubscribing-error", log.Fields{"topic": topic})
391 }
392 delete(kp.topicToResponseChannelMap, topic)
393 return err
394 } else {
395 return errors.New(fmt.Sprintf("%s-Topic-not-found", topic))
396 }
397}
398
399func (kp *InterContainerProxy) deleteAllTopicResponseChannelMap() error {
400 kp.lockTopicResponseChannelMap.Lock()
401 defer kp.lockTopicResponseChannelMap.Unlock()
402 var err error
403 for topic, _ := range kp.topicToResponseChannelMap {
404 // Unsubscribe to this topic first - this will close the subscribed channel
405 if err = kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToResponseChannelMap[topic]); err != nil {
406 log.Errorw("unsubscribing-error", log.Fields{"topic": topic, "error": err})
407 }
408 delete(kp.topicToResponseChannelMap, topic)
409 }
410 return err
411}
412
413func (kp *InterContainerProxy) addToTopicRequestHandlerChannelMap(topic string, arg *requestHandlerChannel) {
414 kp.lockTopicRequestHandlerChannelMap.Lock()
415 defer kp.lockTopicRequestHandlerChannelMap.Unlock()
416 if _, exist := kp.topicToRequestHandlerChannelMap[topic]; !exist {
417 kp.topicToRequestHandlerChannelMap[topic] = arg
418 }
419}
420
421func (kp *InterContainerProxy) deleteFromTopicRequestHandlerChannelMap(topic string) error {
422 kp.lockTopicRequestHandlerChannelMap.Lock()
423 defer kp.lockTopicRequestHandlerChannelMap.Unlock()
424 if _, exist := kp.topicToRequestHandlerChannelMap[topic]; exist {
425 // Close the kafka client client first by unsubscribing to this topic
426 kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToRequestHandlerChannelMap[topic].ch)
427 delete(kp.topicToRequestHandlerChannelMap, topic)
428 return nil
429 } else {
430 return errors.New(fmt.Sprintf("%s-Topic-not-found", topic))
431 }
432}
433
434func (kp *InterContainerProxy) deleteAllTopicRequestHandlerChannelMap() error {
435 kp.lockTopicRequestHandlerChannelMap.Lock()
436 defer kp.lockTopicRequestHandlerChannelMap.Unlock()
437 var err error
438 for topic, _ := range kp.topicToRequestHandlerChannelMap {
439 // Close the kafka client client first by unsubscribing to this topic
440 if err = kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToRequestHandlerChannelMap[topic].ch); err != nil {
441 log.Errorw("unsubscribing-error", log.Fields{"topic": topic, "error": err})
442 }
443 delete(kp.topicToRequestHandlerChannelMap, topic)
444 }
445 return err
446}
447
448func (kp *InterContainerProxy) addToTransactionIdToChannelMap(id string, topic *Topic, arg chan *ic.InterContainerMessage) {
449 kp.lockTransactionIdToChannelMap.Lock()
450 defer kp.lockTransactionIdToChannelMap.Unlock()
451 if _, exist := kp.transactionIdToChannelMap[id]; !exist {
452 kp.transactionIdToChannelMap[id] = &transactionChannel{topic: topic, ch: arg}
453 }
454}
455
456func (kp *InterContainerProxy) deleteFromTransactionIdToChannelMap(id string) {
457 kp.lockTransactionIdToChannelMap.Lock()
458 defer kp.lockTransactionIdToChannelMap.Unlock()
459 if transChannel, exist := kp.transactionIdToChannelMap[id]; exist {
460 // Close the channel first
461 close(transChannel.ch)
462 delete(kp.transactionIdToChannelMap, id)
463 }
464}
465
466func (kp *InterContainerProxy) deleteTopicTransactionIdToChannelMap(id string) {
467 kp.lockTransactionIdToChannelMap.Lock()
468 defer kp.lockTransactionIdToChannelMap.Unlock()
469 for key, value := range kp.transactionIdToChannelMap {
470 if value.topic.Name == id {
471 close(value.ch)
472 delete(kp.transactionIdToChannelMap, key)
473 }
474 }
475}
476
477func (kp *InterContainerProxy) deleteAllTransactionIdToChannelMap() {
478 kp.lockTransactionIdToChannelMap.Lock()
479 defer kp.lockTransactionIdToChannelMap.Unlock()
480 for key, value := range kp.transactionIdToChannelMap {
481 close(value.ch)
482 delete(kp.transactionIdToChannelMap, key)
483 }
484}
485
486func (kp *InterContainerProxy) DeleteTopic(topic Topic) error {
487 // If we have any consumers on that topic we need to close them
488 if err := kp.deleteFromTopicResponseChannelMap(topic.Name); err != nil {
489 log.Errorw("delete-from-topic-responsechannelmap-failed", log.Fields{"error": err})
490 }
491 if err := kp.deleteFromTopicRequestHandlerChannelMap(topic.Name); err != nil {
492 log.Errorw("delete-from-topic-requesthandlerchannelmap-failed", log.Fields{"error": err})
493 }
494 kp.deleteTopicTransactionIdToChannelMap(topic.Name)
495
496 return kp.kafkaClient.DeleteTopic(&topic)
497}
498
499func encodeReturnedValue(returnedVal interface{}) (*any.Any, error) {
500 // Encode the response argument - needs to be a proto message
501 if returnedVal == nil {
502 return nil, nil
503 }
504 protoValue, ok := returnedVal.(proto.Message)
505 if !ok {
506 log.Warnw("response-value-not-proto-message", log.Fields{"error": ok, "returnVal": returnedVal})
507 err := errors.New("response-value-not-proto-message")
508 return nil, err
509 }
510
511 // Marshal the returned value, if any
512 var marshalledReturnedVal *any.Any
513 var err error
514 if marshalledReturnedVal, err = ptypes.MarshalAny(protoValue); err != nil {
515 log.Warnw("cannot-marshal-returned-val", log.Fields{"error": err})
516 return nil, err
517 }
518 return marshalledReturnedVal, nil
519}
520
521func encodeDefaultFailedResponse(request *ic.InterContainerMessage) *ic.InterContainerMessage {
522 responseHeader := &ic.Header{
523 Id: request.Header.Id,
524 Type: ic.MessageType_RESPONSE,
525 FromTopic: request.Header.ToTopic,
526 ToTopic: request.Header.FromTopic,
527 Timestamp: time.Now().Unix(),
528 }
529 responseBody := &ic.InterContainerResponseBody{
530 Success: false,
531 Result: nil,
532 }
533 var marshalledResponseBody *any.Any
534 var err error
535 // Error should never happen here
536 if marshalledResponseBody, err = ptypes.MarshalAny(responseBody); err != nil {
537 log.Warnw("cannot-marshal-failed-response-body", log.Fields{"error": err})
538 }
539
540 return &ic.InterContainerMessage{
541 Header: responseHeader,
542 Body: marshalledResponseBody,
543 }
544
545}
546
547//formatRequest formats a request to send over kafka and returns an InterContainerMessage message on success
548//or an error on failure
549func encodeResponse(request *ic.InterContainerMessage, success bool, returnedValues ...interface{}) (*ic.InterContainerMessage, error) {
550 //log.Debugw("encodeResponse", log.Fields{"success": success, "returnedValues": returnedValues})
551 responseHeader := &ic.Header{
552 Id: request.Header.Id,
553 Type: ic.MessageType_RESPONSE,
554 FromTopic: request.Header.ToTopic,
555 ToTopic: request.Header.FromTopic,
556 KeyTopic: request.Header.KeyTopic,
557 Timestamp: time.Now().UnixNano(),
558 }
559
560 // Go over all returned values
561 var marshalledReturnedVal *any.Any
562 var err error
563 for _, returnVal := range returnedValues {
564 if marshalledReturnedVal, err = encodeReturnedValue(returnVal); err != nil {
565 log.Warnw("cannot-marshal-response-body", log.Fields{"error": err})
566 }
567 break // for now we support only 1 returned value - (excluding the error)
568 }
569
570 responseBody := &ic.InterContainerResponseBody{
571 Success: success,
572 Result: marshalledReturnedVal,
573 }
574
575 // Marshal the response body
576 var marshalledResponseBody *any.Any
577 if marshalledResponseBody, err = ptypes.MarshalAny(responseBody); err != nil {
578 log.Warnw("cannot-marshal-response-body", log.Fields{"error": err})
579 return nil, err
580 }
581
582 return &ic.InterContainerMessage{
583 Header: responseHeader,
584 Body: marshalledResponseBody,
585 }, nil
586}
587
588func CallFuncByName(myClass interface{}, funcName string, params ...interface{}) (out []reflect.Value, err error) {
589 myClassValue := reflect.ValueOf(myClass)
590 // Capitalize the first letter in the funcName to workaround the first capital letters required to
591 // invoke a function from a different package
592 funcName = strings.Title(funcName)
593 m := myClassValue.MethodByName(funcName)
594 if !m.IsValid() {
595 return make([]reflect.Value, 0), fmt.Errorf("method-not-found \"%s\"", funcName)
596 }
597 in := make([]reflect.Value, len(params))
598 for i, param := range params {
599 in[i] = reflect.ValueOf(param)
600 }
601 out = m.Call(in)
602 return
603}
604
605func (kp *InterContainerProxy) addTransactionId(transactionId string, currentArgs []*ic.Argument) []*ic.Argument {
606 arg := &KVArg{
607 Key: TransactionKey,
608 Value: &ic.StrType{Val: transactionId},
609 }
610
611 var marshalledArg *any.Any
612 var err error
613 if marshalledArg, err = ptypes.MarshalAny(&ic.StrType{Val: transactionId}); err != nil {
614 log.Warnw("cannot-add-transactionId", log.Fields{"error": err})
615 return currentArgs
616 }
617 protoArg := &ic.Argument{
618 Key: arg.Key,
619 Value: marshalledArg,
620 }
621 return append(currentArgs, protoArg)
622}
623
624func (kp *InterContainerProxy) addFromTopic(fromTopic string, currentArgs []*ic.Argument) []*ic.Argument {
625 var marshalledArg *any.Any
626 var err error
627 if marshalledArg, err = ptypes.MarshalAny(&ic.StrType{Val: fromTopic}); err != nil {
628 log.Warnw("cannot-add-transactionId", log.Fields{"error": err})
629 return currentArgs
630 }
631 protoArg := &ic.Argument{
632 Key: FromTopic,
633 Value: marshalledArg,
634 }
635 return append(currentArgs, protoArg)
636}
637
638func (kp *InterContainerProxy) handleMessage(msg *ic.InterContainerMessage, targetInterface interface{}) {
639
640 // First extract the header to know whether this is a request - responses are handled by a different handler
641 if msg.Header.Type == ic.MessageType_REQUEST {
642 var out []reflect.Value
643 var err error
644
645 // Get the request body
646 requestBody := &ic.InterContainerRequestBody{}
647 if err = ptypes.UnmarshalAny(msg.Body, requestBody); err != nil {
648 log.Warnw("cannot-unmarshal-request", log.Fields{"error": err})
649 } else {
650 log.Debugw("received-request", log.Fields{"rpc": requestBody.Rpc, "header": msg.Header})
651 // let the callee unpack the arguments as its the only one that knows the real proto type
652 // Augment the requestBody with the message Id as it will be used in scenarios where cores
653 // are set in pairs and competing
654 requestBody.Args = kp.addTransactionId(msg.Header.Id, requestBody.Args)
655
656 // Augment the requestBody with the From topic name as it will be used in scenarios where a container
657 // needs to send an unsollicited message to the currently requested container
658 requestBody.Args = kp.addFromTopic(msg.Header.FromTopic, requestBody.Args)
659
660 out, err = CallFuncByName(targetInterface, requestBody.Rpc, requestBody.Args)
661 if err != nil {
662 log.Warn(err)
663 }
664 }
665 // Response required?
666 if requestBody.ResponseRequired {
667 // If we already have an error before then just return that
668 var returnError *ic.Error
669 var returnedValues []interface{}
670 var success bool
671 if err != nil {
672 returnError = &ic.Error{Reason: err.Error()}
673 returnedValues = make([]interface{}, 1)
674 returnedValues[0] = returnError
675 } else {
676 returnedValues = make([]interface{}, 0)
677 // Check for errors first
678 lastIndex := len(out) - 1
679 if out[lastIndex].Interface() != nil { // Error
680 if retError, ok := out[lastIndex].Interface().(error); ok {
681 if retError.Error() == ErrorTransactionNotAcquired.Error() {
682 log.Debugw("Ignoring request", log.Fields{"error": retError, "txId": msg.Header.Id})
683 return // Ignore - process is in competing mode and ignored transaction
684 }
685 returnError = &ic.Error{Reason: retError.Error()}
686 returnedValues = append(returnedValues, returnError)
687 } else { // Should never happen
688 returnError = &ic.Error{Reason: "incorrect-error-returns"}
689 returnedValues = append(returnedValues, returnError)
690 }
691 } else if len(out) == 2 && reflect.ValueOf(out[0].Interface()).IsValid() && reflect.ValueOf(out[0].Interface()).IsNil() {
692 log.Warnw("Unexpected response of (nil,nil)", log.Fields{"txId": msg.Header.Id})
693 return // Ignore - should not happen
694 } else { // Non-error case
695 success = true
696 for idx, val := range out {
697 //log.Debugw("returned-api-response-loop", log.Fields{"idx": idx, "val": val.Interface()})
698 if idx != lastIndex {
699 returnedValues = append(returnedValues, val.Interface())
700 }
701 }
702 }
703 }
704
705 var icm *ic.InterContainerMessage
706 if icm, err = encodeResponse(msg, success, returnedValues...); err != nil {
707 log.Warnw("error-encoding-response-returning-failure-result", log.Fields{"error": err})
708 icm = encodeDefaultFailedResponse(msg)
709 }
710 // To preserve ordering of messages, all messages to a given topic are sent to the same partition
711 // by providing a message key. The key is encoded in the topic name. If the deviceId is not
712 // present then the key will be empty, hence all messages for a given topic will be sent to all
713 // partitions.
714 replyTopic := &Topic{Name: msg.Header.FromTopic}
715 key := msg.Header.KeyTopic
716 log.Debugw("sending-response-to-kafka", log.Fields{"rpc": requestBody.Rpc, "header": icm.Header, "key": key})
717 // TODO: handle error response.
718 go kp.kafkaClient.Send(icm, replyTopic, key)
719 }
720 } else if msg.Header.Type == ic.MessageType_RESPONSE {
721 log.Debugw("response-received", log.Fields{"msg-header": msg.Header})
722 go kp.dispatchResponse(msg)
723 } else {
724 log.Warnw("unsupported-message-received", log.Fields{"msg-header": msg.Header})
725 }
726}
727
728func (kp *InterContainerProxy) waitForMessages(ch <-chan *ic.InterContainerMessage, topic Topic, targetInterface interface{}) {
729 // Wait for messages
730 for msg := range ch {
731 //log.Debugw("request-received", log.Fields{"msg": msg, "topic": topic.Name, "target": targetInterface})
732 go kp.handleMessage(msg, targetInterface)
733 }
734}
735
736func (kp *InterContainerProxy) dispatchResponse(msg *ic.InterContainerMessage) {
737 kp.lockTransactionIdToChannelMap.RLock()
738 defer kp.lockTransactionIdToChannelMap.RUnlock()
739 if _, exist := kp.transactionIdToChannelMap[msg.Header.Id]; !exist {
740 log.Debugw("no-waiting-channel", log.Fields{"transaction": msg.Header.Id})
741 return
742 }
743 kp.transactionIdToChannelMap[msg.Header.Id].ch <- msg
744}
745
746// subscribeForResponse allows a caller to subscribe to a given topic when waiting for a response.
747// This method is built to prevent all subscribers to receive all messages as is the case of the Subscribe
748// API. There is one response channel waiting for kafka messages before dispatching the message to the
749// corresponding waiting channel
750func (kp *InterContainerProxy) subscribeForResponse(topic Topic, trnsId string) (chan *ic.InterContainerMessage, error) {
751 log.Debugw("subscribeForResponse", log.Fields{"topic": topic.Name, "trnsid": trnsId})
752
753 // Create a specific channel for this consumers. We cannot use the channel from the kafkaclient as it will
754 // broadcast any message for this topic to all channels waiting on it.
755 ch := make(chan *ic.InterContainerMessage)
756 kp.addToTransactionIdToChannelMap(trnsId, &topic, ch)
757
758 return ch, nil
759}
760
761func (kp *InterContainerProxy) unSubscribeForResponse(trnsId string) error {
762 log.Debugw("unsubscribe-for-response", log.Fields{"trnsId": trnsId})
763 kp.deleteFromTransactionIdToChannelMap(trnsId)
764 return nil
765}
766
Scott Baker104b67d2019-10-29 15:56:27 -0700767func (kp *InterContainerProxy) EnableLivenessChannel(enable bool) chan bool {
768 return kp.kafkaClient.EnableLivenessChannel(enable)
769}
770
771func (kp *InterContainerProxy) SendLiveness() error {
772 return kp.kafkaClient.SendLiveness()
773}
774
Scott Baker2c1c4822019-10-16 11:02:41 -0700775//formatRequest formats a request to send over kafka and returns an InterContainerMessage message on success
776//or an error on failure
777func encodeRequest(rpc string, toTopic *Topic, replyTopic *Topic, key string, kvArgs ...*KVArg) (*ic.InterContainerMessage, error) {
778 requestHeader := &ic.Header{
779 Id: uuid.New().String(),
780 Type: ic.MessageType_REQUEST,
781 FromTopic: replyTopic.Name,
782 ToTopic: toTopic.Name,
783 KeyTopic: key,
784 Timestamp: time.Now().UnixNano(),
785 }
786 requestBody := &ic.InterContainerRequestBody{
787 Rpc: rpc,
788 ResponseRequired: true,
789 ReplyToTopic: replyTopic.Name,
790 }
791
792 for _, arg := range kvArgs {
793 if arg == nil {
794 // In case the caller sends an array with empty args
795 continue
796 }
797 var marshalledArg *any.Any
798 var err error
799 // ascertain the value interface type is a proto.Message
800 protoValue, ok := arg.Value.(proto.Message)
801 if !ok {
802 log.Warnw("argument-value-not-proto-message", log.Fields{"error": ok, "Value": arg.Value})
803 err := errors.New("argument-value-not-proto-message")
804 return nil, err
805 }
806 if marshalledArg, err = ptypes.MarshalAny(protoValue); err != nil {
807 log.Warnw("cannot-marshal-request", log.Fields{"error": err})
808 return nil, err
809 }
810 protoArg := &ic.Argument{
811 Key: arg.Key,
812 Value: marshalledArg,
813 }
814 requestBody.Args = append(requestBody.Args, protoArg)
815 }
816
817 var marshalledData *any.Any
818 var err error
819 if marshalledData, err = ptypes.MarshalAny(requestBody); err != nil {
820 log.Warnw("cannot-marshal-request", log.Fields{"error": err})
821 return nil, err
822 }
823 request := &ic.InterContainerMessage{
824 Header: requestHeader,
825 Body: marshalledData,
826 }
827 return request, nil
828}
829
830func decodeResponse(response *ic.InterContainerMessage) (*ic.InterContainerResponseBody, error) {
831 // Extract the message body
832 responseBody := ic.InterContainerResponseBody{}
833 if err := ptypes.UnmarshalAny(response.Body, &responseBody); err != nil {
834 log.Warnw("cannot-unmarshal-response", log.Fields{"error": err})
835 return nil, err
836 }
837 //log.Debugw("response-decoded-successfully", log.Fields{"response-status": &responseBody.Success})
838
839 return &responseBody, nil
840
841}