blob: 042e1213c1165683f26048cb8f7156a20955633d [file] [log] [blame]
khenaidoobf6e7bb2018-08-14 22:27:29 -04001/*
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 */
khenaidooabad44c2018-08-03 16:58:35 -040016package kafka
17
18import (
19 "context"
20 "errors"
21 "fmt"
khenaidooabad44c2018-08-03 16:58:35 -040022 "reflect"
khenaidoo19374072018-12-11 11:05:15 -050023 "strings"
khenaidooabad44c2018-08-03 16:58:35 -040024 "sync"
25 "time"
khenaidooabad44c2018-08-03 16:58:35 -040026
serkant.uluderya2ae470f2020-01-21 11:13:09 -080027 "github.com/golang/protobuf/proto"
28 "github.com/golang/protobuf/ptypes"
29 "github.com/golang/protobuf/ptypes/any"
30 "github.com/google/uuid"
31 "github.com/opencord/voltha-lib-go/v3/pkg/log"
32 ic "github.com/opencord/voltha-protos/v3/go/inter_container"
33)
khenaidooabad44c2018-08-03 16:58:35 -040034
35const (
khenaidoo43c82122018-11-22 18:38:28 -050036 DefaultMaxRetries = 3
khenaidoo6d055132019-02-12 16:51:19 -050037 DefaultRequestTimeout = 10000 // 10000 milliseconds - to handle a wider latency range
khenaidooabad44c2018-08-03 16:58:35 -040038)
39
khenaidoo297cd252019-02-07 22:10:23 -050040const (
41 TransactionKey = "transactionID"
khenaidoo54e0ddf2019-02-27 16:21:33 -050042 FromTopic = "fromTopic"
khenaidoo297cd252019-02-07 22:10:23 -050043)
44
khenaidoo09771ef2019-10-11 14:25:02 -040045var ErrorTransactionNotAcquired = errors.New("transaction-not-acquired")
46var ErrorTransactionInvalidId = errors.New("transaction-invalid-id")
47
khenaidoo43c82122018-11-22 18:38:28 -050048// requestHandlerChannel represents an interface associated with a channel. Whenever, an event is
49// obtained from that channel, this interface is invoked. This is used to handle
50// async requests into the Core via the kafka messaging bus
51type requestHandlerChannel struct {
52 requesthandlerInterface interface{}
khenaidoo79232702018-12-04 11:00:41 -050053 ch <-chan *ic.InterContainerMessage
khenaidooabad44c2018-08-03 16:58:35 -040054}
55
khenaidoo43c82122018-11-22 18:38:28 -050056// transactionChannel represents a combination of a topic and a channel onto which a response received
57// on the kafka bus will be sent to
58type transactionChannel struct {
59 topic *Topic
khenaidoo79232702018-12-04 11:00:41 -050060 ch chan *ic.InterContainerMessage
khenaidoo43c82122018-11-22 18:38:28 -050061}
62
63// InterContainerProxy represents the messaging proxy
64type InterContainerProxy struct {
65 kafkaHost string
66 kafkaPort int
67 DefaultTopic *Topic
68 defaultRequestHandlerInterface interface{}
khenaidoo79232702018-12-04 11:00:41 -050069 deviceDiscoveryTopic *Topic
khenaidoo43c82122018-11-22 18:38:28 -050070 kafkaClient Client
71 doneCh chan int
72
73 // This map is used to map a topic to an interface and channel. When a request is received
74 // on that channel (registered to the topic) then that interface is invoked.
75 topicToRequestHandlerChannelMap map[string]*requestHandlerChannel
76 lockTopicRequestHandlerChannelMap sync.RWMutex
77
78 // This map is used to map a channel to a response topic. This channel handles all responses on that
khenaidoo4c1a5bf2018-11-29 15:53:42 -050079 // channel for that topic and forward them to the appropriate consumers channel, using the
khenaidoo43c82122018-11-22 18:38:28 -050080 // transactionIdToChannelMap.
khenaidoo79232702018-12-04 11:00:41 -050081 topicToResponseChannelMap map[string]<-chan *ic.InterContainerMessage
khenaidoo43c82122018-11-22 18:38:28 -050082 lockTopicResponseChannelMap sync.RWMutex
83
khenaidoo4c1a5bf2018-11-29 15:53:42 -050084 // This map is used to map a transaction to a consumers channel. This is used whenever a request has been
khenaidoo43c82122018-11-22 18:38:28 -050085 // sent out and we are waiting for a response.
86 transactionIdToChannelMap map[string]*transactionChannel
khenaidooabad44c2018-08-03 16:58:35 -040087 lockTransactionIdToChannelMap sync.RWMutex
88}
89
khenaidoo43c82122018-11-22 18:38:28 -050090type InterContainerProxyOption func(*InterContainerProxy)
khenaidooabad44c2018-08-03 16:58:35 -040091
khenaidoo43c82122018-11-22 18:38:28 -050092func InterContainerHost(host string) InterContainerProxyOption {
93 return func(args *InterContainerProxy) {
94 args.kafkaHost = host
khenaidooabad44c2018-08-03 16:58:35 -040095 }
96}
97
khenaidoo43c82122018-11-22 18:38:28 -050098func InterContainerPort(port int) InterContainerProxyOption {
99 return func(args *InterContainerProxy) {
100 args.kafkaPort = port
khenaidooabad44c2018-08-03 16:58:35 -0400101 }
102}
103
khenaidoo43c82122018-11-22 18:38:28 -0500104func DefaultTopic(topic *Topic) InterContainerProxyOption {
105 return func(args *InterContainerProxy) {
khenaidooabad44c2018-08-03 16:58:35 -0400106 args.DefaultTopic = topic
107 }
108}
109
khenaidoo79232702018-12-04 11:00:41 -0500110func DeviceDiscoveryTopic(topic *Topic) InterContainerProxyOption {
111 return func(args *InterContainerProxy) {
112 args.deviceDiscoveryTopic = topic
113 }
114}
115
khenaidoo43c82122018-11-22 18:38:28 -0500116func RequestHandlerInterface(handler interface{}) InterContainerProxyOption {
117 return func(args *InterContainerProxy) {
118 args.defaultRequestHandlerInterface = handler
khenaidooabad44c2018-08-03 16:58:35 -0400119 }
120}
121
khenaidoo43c82122018-11-22 18:38:28 -0500122func MsgClient(client Client) InterContainerProxyOption {
123 return func(args *InterContainerProxy) {
124 args.kafkaClient = client
125 }
126}
127
128func NewInterContainerProxy(opts ...InterContainerProxyOption) (*InterContainerProxy, error) {
129 proxy := &InterContainerProxy{
130 kafkaHost: DefaultKafkaHost,
131 kafkaPort: DefaultKafkaPort,
khenaidooabad44c2018-08-03 16:58:35 -0400132 }
133
134 for _, option := range opts {
135 option(proxy)
136 }
137
138 // Create the locks for all the maps
khenaidoo43c82122018-11-22 18:38:28 -0500139 proxy.lockTopicRequestHandlerChannelMap = sync.RWMutex{}
khenaidooabad44c2018-08-03 16:58:35 -0400140 proxy.lockTransactionIdToChannelMap = sync.RWMutex{}
khenaidoo43c82122018-11-22 18:38:28 -0500141 proxy.lockTopicResponseChannelMap = sync.RWMutex{}
khenaidooabad44c2018-08-03 16:58:35 -0400142
143 return proxy, nil
144}
145
khenaidoo43c82122018-11-22 18:38:28 -0500146func (kp *InterContainerProxy) Start() error {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800147 logger.Info("Starting-Proxy")
khenaidooabad44c2018-08-03 16:58:35 -0400148
khenaidoo43c82122018-11-22 18:38:28 -0500149 // Kafka MsgClient should already have been created. If not, output fatal error
150 if kp.kafkaClient == nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800151 logger.Fatal("kafka-client-not-set")
khenaidoo43c82122018-11-22 18:38:28 -0500152 }
153
khenaidooabad44c2018-08-03 16:58:35 -0400154 // Create the Done channel
155 kp.doneCh = make(chan int, 1)
156
khenaidoo43c82122018-11-22 18:38:28 -0500157 // Start the kafka client
khenaidoo4c1a5bf2018-11-29 15:53:42 -0500158 if err := kp.kafkaClient.Start(); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800159 logger.Errorw("Cannot-create-kafka-proxy", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400160 return err
161 }
162
khenaidoo43c82122018-11-22 18:38:28 -0500163 // Create the topic to response channel map
khenaidoo79232702018-12-04 11:00:41 -0500164 kp.topicToResponseChannelMap = make(map[string]<-chan *ic.InterContainerMessage)
khenaidoo43c82122018-11-22 18:38:28 -0500165 //
khenaidooabad44c2018-08-03 16:58:35 -0400166 // Create the transactionId to Channel Map
khenaidoo43c82122018-11-22 18:38:28 -0500167 kp.transactionIdToChannelMap = make(map[string]*transactionChannel)
168
169 // Create the topic to request channel map
170 kp.topicToRequestHandlerChannelMap = make(map[string]*requestHandlerChannel)
khenaidooabad44c2018-08-03 16:58:35 -0400171
172 return nil
173}
174
khenaidoo43c82122018-11-22 18:38:28 -0500175func (kp *InterContainerProxy) Stop() {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800176 logger.Info("stopping-intercontainer-proxy")
khenaidoo43c82122018-11-22 18:38:28 -0500177 kp.doneCh <- 1
178 // TODO : Perform cleanup
khenaidooca301322019-01-09 23:06:32 -0500179 kp.kafkaClient.Stop()
khenaidoo43c82122018-11-22 18:38:28 -0500180 //kp.deleteAllTopicRequestHandlerChannelMap()
181 //kp.deleteAllTopicResponseChannelMap()
182 //kp.deleteAllTransactionIdToChannelMap()
khenaidooabad44c2018-08-03 16:58:35 -0400183}
184
khenaidoo79232702018-12-04 11:00:41 -0500185// DeviceDiscovered publish the discovered device onto the kafka messaging bus
khenaidoo19374072018-12-11 11:05:15 -0500186func (kp *InterContainerProxy) DeviceDiscovered(deviceId string, deviceType string, parentId string, publisher string) error {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800187 logger.Debugw("sending-device-discovery-msg", log.Fields{"deviceId": deviceId})
khenaidoo79232702018-12-04 11:00:41 -0500188 // Simple validation
189 if deviceId == "" || deviceType == "" {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800190 logger.Errorw("invalid-parameters", log.Fields{"id": deviceId, "type": deviceType})
khenaidoo79232702018-12-04 11:00:41 -0500191 return errors.New("invalid-parameters")
192 }
193 // Create the device discovery message
194 header := &ic.Header{
195 Id: uuid.New().String(),
196 Type: ic.MessageType_DEVICE_DISCOVERED,
197 FromTopic: kp.DefaultTopic.Name,
198 ToTopic: kp.deviceDiscoveryTopic.Name,
199 Timestamp: time.Now().UnixNano(),
200 }
201 body := &ic.DeviceDiscovered{
202 Id: deviceId,
203 DeviceType: deviceType,
204 ParentId: parentId,
khenaidood2b6df92018-12-13 16:37:20 -0500205 Publisher: publisher,
khenaidoo79232702018-12-04 11:00:41 -0500206 }
207
208 var marshalledData *any.Any
209 var err error
210 if marshalledData, err = ptypes.MarshalAny(body); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800211 logger.Errorw("cannot-marshal-request", log.Fields{"error": err})
khenaidoo79232702018-12-04 11:00:41 -0500212 return err
213 }
214 msg := &ic.InterContainerMessage{
215 Header: header,
216 Body: marshalledData,
217 }
218
219 // Send the message
220 if err := kp.kafkaClient.Send(msg, kp.deviceDiscoveryTopic); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800221 logger.Errorw("cannot-send-device-discovery-message", log.Fields{"error": err})
khenaidoo79232702018-12-04 11:00:41 -0500222 return err
223 }
224 return nil
225}
226
khenaidoo43c82122018-11-22 18:38:28 -0500227// InvokeRPC is used to send a request to a given topic
228func (kp *InterContainerProxy) InvokeRPC(ctx context.Context, rpc string, toTopic *Topic, replyToTopic *Topic,
khenaidoobdcb8e02019-03-06 16:28:56 -0500229 waitForResponse bool, key string, kvArgs ...*KVArg) (bool, *any.Any) {
khenaidoo43c82122018-11-22 18:38:28 -0500230
231 // If a replyToTopic is provided then we use it, otherwise just use the default toTopic. The replyToTopic is
232 // typically the device ID.
233 responseTopic := replyToTopic
234 if responseTopic == nil {
235 responseTopic = kp.DefaultTopic
236 }
237
khenaidooabad44c2018-08-03 16:58:35 -0400238 // Encode the request
khenaidoobdcb8e02019-03-06 16:28:56 -0500239 protoRequest, err := encodeRequest(rpc, toTopic, responseTopic, key, kvArgs...)
khenaidooabad44c2018-08-03 16:58:35 -0400240 if err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800241 logger.Warnw("cannot-format-request", log.Fields{"rpc": rpc, "error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400242 return false, nil
243 }
244
245 // Subscribe for response, if needed, before sending request
khenaidoo79232702018-12-04 11:00:41 -0500246 var ch <-chan *ic.InterContainerMessage
khenaidooabad44c2018-08-03 16:58:35 -0400247 if waitForResponse {
248 var err error
khenaidoo43c82122018-11-22 18:38:28 -0500249 if ch, err = kp.subscribeForResponse(*responseTopic, protoRequest.Header.Id); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800250 logger.Errorw("failed-to-subscribe-for-response", log.Fields{"error": err, "toTopic": toTopic.Name})
khenaidooabad44c2018-08-03 16:58:35 -0400251 }
252 }
253
khenaidoo43c82122018-11-22 18:38:28 -0500254 // Send request - if the topic is formatted with a device Id then we will send the request using a
255 // specific key, hence ensuring a single partition is used to publish the request. This ensures that the
256 // subscriber on that topic will receive the request in the order it was sent. The key used is the deviceId.
khenaidoobdcb8e02019-03-06 16:28:56 -0500257 //key := GetDeviceIdFromTopic(*toTopic)
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800258 logger.Debugw("sending-msg", log.Fields{"rpc": rpc, "toTopic": toTopic, "replyTopic": responseTopic, "key": key, "xId": protoRequest.Header.Id})
khenaidoo8f474192019-04-03 17:20:44 -0400259 go kp.kafkaClient.Send(protoRequest, toTopic, key)
khenaidooabad44c2018-08-03 16:58:35 -0400260
261 if waitForResponse {
khenaidoob9203542018-09-17 22:56:37 -0400262 // Create a child context based on the parent context, if any
khenaidooabad44c2018-08-03 16:58:35 -0400263 var cancel context.CancelFunc
khenaidoob9203542018-09-17 22:56:37 -0400264 childCtx := context.Background()
khenaidooabad44c2018-08-03 16:58:35 -0400265 if ctx == nil {
266 ctx, cancel = context.WithTimeout(context.Background(), DefaultRequestTimeout*time.Millisecond)
khenaidoob9203542018-09-17 22:56:37 -0400267 } else {
268 childCtx, cancel = context.WithTimeout(ctx, DefaultRequestTimeout*time.Millisecond)
khenaidooabad44c2018-08-03 16:58:35 -0400269 }
khenaidoob9203542018-09-17 22:56:37 -0400270 defer cancel()
khenaidooabad44c2018-08-03 16:58:35 -0400271
272 // Wait for response as well as timeout or cancellation
273 // Remove the subscription for a response on return
274 defer kp.unSubscribeForResponse(protoRequest.Header.Id)
275 select {
khenaidoo3dfc8bc2019-01-10 16:48:25 -0500276 case msg, ok := <-ch:
277 if !ok {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800278 logger.Warnw("channel-closed", log.Fields{"rpc": rpc, "replyTopic": replyToTopic.Name})
khenaidoo3dfc8bc2019-01-10 16:48:25 -0500279 protoError := &ic.Error{Reason: "channel-closed"}
280 var marshalledArg *any.Any
281 if marshalledArg, err = ptypes.MarshalAny(protoError); err != nil {
282 return false, nil // Should never happen
283 }
284 return false, marshalledArg
285 }
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800286 logger.Debugw("received-response", log.Fields{"rpc": rpc, "msgHeader": msg.Header})
khenaidoo79232702018-12-04 11:00:41 -0500287 var responseBody *ic.InterContainerResponseBody
khenaidooabad44c2018-08-03 16:58:35 -0400288 var err error
289 if responseBody, err = decodeResponse(msg); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800290 logger.Errorw("decode-response-error", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400291 }
292 return responseBody.Success, responseBody.Result
293 case <-ctx.Done():
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800294 logger.Debugw("context-cancelled", log.Fields{"rpc": rpc, "ctx": ctx.Err()})
khenaidooabad44c2018-08-03 16:58:35 -0400295 // pack the error as proto any type
khenaidoo79232702018-12-04 11:00:41 -0500296 protoError := &ic.Error{Reason: ctx.Err().Error()}
khenaidooabad44c2018-08-03 16:58:35 -0400297 var marshalledArg *any.Any
298 if marshalledArg, err = ptypes.MarshalAny(protoError); err != nil {
299 return false, nil // Should never happen
300 }
301 return false, marshalledArg
khenaidoob9203542018-09-17 22:56:37 -0400302 case <-childCtx.Done():
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800303 logger.Debugw("context-cancelled", log.Fields{"rpc": rpc, "ctx": childCtx.Err()})
khenaidoob9203542018-09-17 22:56:37 -0400304 // pack the error as proto any type
khenaidoo79232702018-12-04 11:00:41 -0500305 protoError := &ic.Error{Reason: childCtx.Err().Error()}
khenaidoob9203542018-09-17 22:56:37 -0400306 var marshalledArg *any.Any
307 if marshalledArg, err = ptypes.MarshalAny(protoError); err != nil {
308 return false, nil // Should never happen
309 }
310 return false, marshalledArg
khenaidooabad44c2018-08-03 16:58:35 -0400311 case <-kp.doneCh:
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800312 logger.Infow("received-exit-signal", log.Fields{"toTopic": toTopic.Name, "rpc": rpc})
khenaidooabad44c2018-08-03 16:58:35 -0400313 return true, nil
314 }
315 }
316 return true, nil
317}
318
khenaidoo43c82122018-11-22 18:38:28 -0500319// SubscribeWithRequestHandlerInterface allows a caller to assign a target object to be invoked automatically
khenaidooabad44c2018-08-03 16:58:35 -0400320// when a message is received on a given topic
khenaidoo43c82122018-11-22 18:38:28 -0500321func (kp *InterContainerProxy) SubscribeWithRequestHandlerInterface(topic Topic, handler interface{}) error {
khenaidooabad44c2018-08-03 16:58:35 -0400322
323 // Subscribe to receive messages for that topic
khenaidoo79232702018-12-04 11:00:41 -0500324 var ch <-chan *ic.InterContainerMessage
khenaidooabad44c2018-08-03 16:58:35 -0400325 var err error
khenaidoo4c1a5bf2018-11-29 15:53:42 -0500326 if ch, err = kp.kafkaClient.Subscribe(&topic); err != nil {
khenaidoo43c82122018-11-22 18:38:28 -0500327 //if ch, err = kp.Subscribe(topic); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800328 logger.Errorw("failed-to-subscribe", log.Fields{"error": err, "topic": topic.Name})
Abhilash S.L90cd9552019-07-18 17:30:29 +0530329 return err
khenaidooabad44c2018-08-03 16:58:35 -0400330 }
khenaidoo43c82122018-11-22 18:38:28 -0500331
332 kp.defaultRequestHandlerInterface = handler
333 kp.addToTopicRequestHandlerChannelMap(topic.Name, &requestHandlerChannel{requesthandlerInterface: handler, ch: ch})
khenaidooabad44c2018-08-03 16:58:35 -0400334 // Launch a go routine to receive and process kafka messages
khenaidoo54e0ddf2019-02-27 16:21:33 -0500335 go kp.waitForMessages(ch, topic, handler)
khenaidooabad44c2018-08-03 16:58:35 -0400336
337 return nil
338}
339
khenaidoo43c82122018-11-22 18:38:28 -0500340// SubscribeWithDefaultRequestHandler allows a caller to add a topic to an existing target object to be invoked automatically
341// when a message is received on a given topic. So far there is only 1 target registered per microservice
khenaidoo731697e2019-01-29 16:03:29 -0500342func (kp *InterContainerProxy) SubscribeWithDefaultRequestHandler(topic Topic, initialOffset int64) error {
khenaidoo43c82122018-11-22 18:38:28 -0500343 // Subscribe to receive messages for that topic
khenaidoo79232702018-12-04 11:00:41 -0500344 var ch <-chan *ic.InterContainerMessage
khenaidoo43c82122018-11-22 18:38:28 -0500345 var err error
khenaidoo54e0ddf2019-02-27 16:21:33 -0500346 if ch, err = kp.kafkaClient.Subscribe(&topic, &KVArg{Key: Offset, Value: initialOffset}); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800347 logger.Errorw("failed-to-subscribe", log.Fields{"error": err, "topic": topic.Name})
khenaidooca301322019-01-09 23:06:32 -0500348 return err
khenaidoo43c82122018-11-22 18:38:28 -0500349 }
350 kp.addToTopicRequestHandlerChannelMap(topic.Name, &requestHandlerChannel{requesthandlerInterface: kp.defaultRequestHandlerInterface, ch: ch})
351
352 // Launch a go routine to receive and process kafka messages
khenaidoo54e0ddf2019-02-27 16:21:33 -0500353 go kp.waitForMessages(ch, topic, kp.defaultRequestHandlerInterface)
khenaidoo43c82122018-11-22 18:38:28 -0500354
khenaidooabad44c2018-08-03 16:58:35 -0400355 return nil
356}
357
khenaidoo43c82122018-11-22 18:38:28 -0500358func (kp *InterContainerProxy) UnSubscribeFromRequestHandler(topic Topic) error {
359 return kp.deleteFromTopicRequestHandlerChannelMap(topic.Name)
360}
361
khenaidoo4c1a5bf2018-11-29 15:53:42 -0500362// setupTopicResponseChannelMap sets up single consumers channel that will act as a broadcast channel for all
khenaidoo43c82122018-11-22 18:38:28 -0500363// responses from that topic.
khenaidoo79232702018-12-04 11:00:41 -0500364func (kp *InterContainerProxy) setupTopicResponseChannelMap(topic string, arg <-chan *ic.InterContainerMessage) {
khenaidoo43c82122018-11-22 18:38:28 -0500365 kp.lockTopicResponseChannelMap.Lock()
366 defer kp.lockTopicResponseChannelMap.Unlock()
367 if _, exist := kp.topicToResponseChannelMap[topic]; !exist {
368 kp.topicToResponseChannelMap[topic] = arg
khenaidooabad44c2018-08-03 16:58:35 -0400369 }
370}
371
khenaidoo43c82122018-11-22 18:38:28 -0500372func (kp *InterContainerProxy) isTopicSubscribedForResponse(topic string) bool {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400373 kp.lockTopicResponseChannelMap.RLock()
374 defer kp.lockTopicResponseChannelMap.RUnlock()
khenaidoo43c82122018-11-22 18:38:28 -0500375 _, exist := kp.topicToResponseChannelMap[topic]
376 return exist
377}
378
379func (kp *InterContainerProxy) deleteFromTopicResponseChannelMap(topic string) error {
380 kp.lockTopicResponseChannelMap.Lock()
381 defer kp.lockTopicResponseChannelMap.Unlock()
382 if _, exist := kp.topicToResponseChannelMap[topic]; exist {
383 // Unsubscribe to this topic first - this will close the subscribed channel
384 var err error
385 if err = kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToResponseChannelMap[topic]); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800386 logger.Errorw("unsubscribing-error", log.Fields{"topic": topic})
khenaidoo43c82122018-11-22 18:38:28 -0500387 }
388 delete(kp.topicToResponseChannelMap, topic)
389 return err
390 } else {
391 return errors.New(fmt.Sprintf("%s-Topic-not-found", topic))
khenaidooabad44c2018-08-03 16:58:35 -0400392 }
393}
394
khenaidoo43c82122018-11-22 18:38:28 -0500395func (kp *InterContainerProxy) deleteAllTopicResponseChannelMap() error {
396 kp.lockTopicResponseChannelMap.Lock()
397 defer kp.lockTopicResponseChannelMap.Unlock()
398 var err error
399 for topic, _ := range kp.topicToResponseChannelMap {
400 // Unsubscribe to this topic first - this will close the subscribed channel
401 if err = kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToResponseChannelMap[topic]); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800402 logger.Errorw("unsubscribing-error", log.Fields{"topic": topic, "error": err})
khenaidoo43c82122018-11-22 18:38:28 -0500403 }
404 delete(kp.topicToResponseChannelMap, topic)
khenaidooabad44c2018-08-03 16:58:35 -0400405 }
khenaidoo43c82122018-11-22 18:38:28 -0500406 return err
khenaidooabad44c2018-08-03 16:58:35 -0400407}
408
khenaidoo43c82122018-11-22 18:38:28 -0500409func (kp *InterContainerProxy) addToTopicRequestHandlerChannelMap(topic string, arg *requestHandlerChannel) {
410 kp.lockTopicRequestHandlerChannelMap.Lock()
411 defer kp.lockTopicRequestHandlerChannelMap.Unlock()
412 if _, exist := kp.topicToRequestHandlerChannelMap[topic]; !exist {
413 kp.topicToRequestHandlerChannelMap[topic] = arg
khenaidooabad44c2018-08-03 16:58:35 -0400414 }
khenaidooabad44c2018-08-03 16:58:35 -0400415}
416
khenaidoo43c82122018-11-22 18:38:28 -0500417func (kp *InterContainerProxy) deleteFromTopicRequestHandlerChannelMap(topic string) error {
418 kp.lockTopicRequestHandlerChannelMap.Lock()
419 defer kp.lockTopicRequestHandlerChannelMap.Unlock()
420 if _, exist := kp.topicToRequestHandlerChannelMap[topic]; exist {
421 // Close the kafka client client first by unsubscribing to this topic
422 kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToRequestHandlerChannelMap[topic].ch)
423 delete(kp.topicToRequestHandlerChannelMap, topic)
khenaidooabad44c2018-08-03 16:58:35 -0400424 return nil
khenaidoo43c82122018-11-22 18:38:28 -0500425 } else {
426 return errors.New(fmt.Sprintf("%s-Topic-not-found", topic))
khenaidooabad44c2018-08-03 16:58:35 -0400427 }
khenaidooabad44c2018-08-03 16:58:35 -0400428}
429
khenaidoo43c82122018-11-22 18:38:28 -0500430func (kp *InterContainerProxy) deleteAllTopicRequestHandlerChannelMap() error {
431 kp.lockTopicRequestHandlerChannelMap.Lock()
432 defer kp.lockTopicRequestHandlerChannelMap.Unlock()
433 var err error
434 for topic, _ := range kp.topicToRequestHandlerChannelMap {
435 // Close the kafka client client first by unsubscribing to this topic
436 if err = kp.kafkaClient.UnSubscribe(&Topic{Name: topic}, kp.topicToRequestHandlerChannelMap[topic].ch); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800437 logger.Errorw("unsubscribing-error", log.Fields{"topic": topic, "error": err})
khenaidoo43c82122018-11-22 18:38:28 -0500438 }
439 delete(kp.topicToRequestHandlerChannelMap, topic)
440 }
441 return err
442}
443
khenaidoo79232702018-12-04 11:00:41 -0500444func (kp *InterContainerProxy) addToTransactionIdToChannelMap(id string, topic *Topic, arg chan *ic.InterContainerMessage) {
khenaidooabad44c2018-08-03 16:58:35 -0400445 kp.lockTransactionIdToChannelMap.Lock()
446 defer kp.lockTransactionIdToChannelMap.Unlock()
447 if _, exist := kp.transactionIdToChannelMap[id]; !exist {
khenaidoo43c82122018-11-22 18:38:28 -0500448 kp.transactionIdToChannelMap[id] = &transactionChannel{topic: topic, ch: arg}
khenaidooabad44c2018-08-03 16:58:35 -0400449 }
450}
451
khenaidoo43c82122018-11-22 18:38:28 -0500452func (kp *InterContainerProxy) deleteFromTransactionIdToChannelMap(id string) {
khenaidooabad44c2018-08-03 16:58:35 -0400453 kp.lockTransactionIdToChannelMap.Lock()
454 defer kp.lockTransactionIdToChannelMap.Unlock()
khenaidoo43c82122018-11-22 18:38:28 -0500455 if transChannel, exist := kp.transactionIdToChannelMap[id]; exist {
456 // Close the channel first
457 close(transChannel.ch)
khenaidooabad44c2018-08-03 16:58:35 -0400458 delete(kp.transactionIdToChannelMap, id)
459 }
460}
461
khenaidoo43c82122018-11-22 18:38:28 -0500462func (kp *InterContainerProxy) deleteTopicTransactionIdToChannelMap(id string) {
463 kp.lockTransactionIdToChannelMap.Lock()
464 defer kp.lockTransactionIdToChannelMap.Unlock()
465 for key, value := range kp.transactionIdToChannelMap {
466 if value.topic.Name == id {
467 close(value.ch)
468 delete(kp.transactionIdToChannelMap, key)
khenaidooabad44c2018-08-03 16:58:35 -0400469 }
470 }
khenaidooabad44c2018-08-03 16:58:35 -0400471}
472
khenaidoo43c82122018-11-22 18:38:28 -0500473func (kp *InterContainerProxy) deleteAllTransactionIdToChannelMap() {
474 kp.lockTransactionIdToChannelMap.Lock()
475 defer kp.lockTransactionIdToChannelMap.Unlock()
476 for key, value := range kp.transactionIdToChannelMap {
477 close(value.ch)
478 delete(kp.transactionIdToChannelMap, key)
khenaidooabad44c2018-08-03 16:58:35 -0400479 }
khenaidooabad44c2018-08-03 16:58:35 -0400480}
481
khenaidoo43c82122018-11-22 18:38:28 -0500482func (kp *InterContainerProxy) DeleteTopic(topic Topic) error {
483 // If we have any consumers on that topic we need to close them
khenaidoo3dfc8bc2019-01-10 16:48:25 -0500484 if err := kp.deleteFromTopicResponseChannelMap(topic.Name); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800485 logger.Errorw("delete-from-topic-responsechannelmap-failed", log.Fields{"error": err})
khenaidoo3dfc8bc2019-01-10 16:48:25 -0500486 }
487 if err := kp.deleteFromTopicRequestHandlerChannelMap(topic.Name); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800488 logger.Errorw("delete-from-topic-requesthandlerchannelmap-failed", log.Fields{"error": err})
khenaidoo3dfc8bc2019-01-10 16:48:25 -0500489 }
khenaidoo43c82122018-11-22 18:38:28 -0500490 kp.deleteTopicTransactionIdToChannelMap(topic.Name)
khenaidoo3dfc8bc2019-01-10 16:48:25 -0500491
khenaidoo43c82122018-11-22 18:38:28 -0500492 return kp.kafkaClient.DeleteTopic(&topic)
493}
494
495func encodeReturnedValue(returnedVal interface{}) (*any.Any, error) {
khenaidooabad44c2018-08-03 16:58:35 -0400496 // Encode the response argument - needs to be a proto message
497 if returnedVal == nil {
498 return nil, nil
499 }
500 protoValue, ok := returnedVal.(proto.Message)
501 if !ok {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800502 logger.Warnw("response-value-not-proto-message", log.Fields{"error": ok, "returnVal": returnedVal})
khenaidooabad44c2018-08-03 16:58:35 -0400503 err := errors.New("response-value-not-proto-message")
504 return nil, err
505 }
506
507 // Marshal the returned value, if any
508 var marshalledReturnedVal *any.Any
509 var err error
510 if marshalledReturnedVal, err = ptypes.MarshalAny(protoValue); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800511 logger.Warnw("cannot-marshal-returned-val", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400512 return nil, err
513 }
514 return marshalledReturnedVal, nil
515}
516
khenaidoo79232702018-12-04 11:00:41 -0500517func encodeDefaultFailedResponse(request *ic.InterContainerMessage) *ic.InterContainerMessage {
518 responseHeader := &ic.Header{
khenaidooabad44c2018-08-03 16:58:35 -0400519 Id: request.Header.Id,
khenaidoo79232702018-12-04 11:00:41 -0500520 Type: ic.MessageType_RESPONSE,
khenaidooabad44c2018-08-03 16:58:35 -0400521 FromTopic: request.Header.ToTopic,
522 ToTopic: request.Header.FromTopic,
523 Timestamp: time.Now().Unix(),
524 }
khenaidoo79232702018-12-04 11:00:41 -0500525 responseBody := &ic.InterContainerResponseBody{
khenaidooabad44c2018-08-03 16:58:35 -0400526 Success: false,
527 Result: nil,
528 }
529 var marshalledResponseBody *any.Any
530 var err error
531 // Error should never happen here
532 if marshalledResponseBody, err = ptypes.MarshalAny(responseBody); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800533 logger.Warnw("cannot-marshal-failed-response-body", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400534 }
535
khenaidoo79232702018-12-04 11:00:41 -0500536 return &ic.InterContainerMessage{
khenaidooabad44c2018-08-03 16:58:35 -0400537 Header: responseHeader,
538 Body: marshalledResponseBody,
539 }
540
541}
542
543//formatRequest formats a request to send over kafka and returns an InterContainerMessage message on success
544//or an error on failure
khenaidoo79232702018-12-04 11:00:41 -0500545func encodeResponse(request *ic.InterContainerMessage, success bool, returnedValues ...interface{}) (*ic.InterContainerMessage, error) {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800546 //logger.Debugw("encodeResponse", log.Fields{"success": success, "returnedValues": returnedValues})
khenaidoo79232702018-12-04 11:00:41 -0500547 responseHeader := &ic.Header{
khenaidooabad44c2018-08-03 16:58:35 -0400548 Id: request.Header.Id,
khenaidoo79232702018-12-04 11:00:41 -0500549 Type: ic.MessageType_RESPONSE,
khenaidooabad44c2018-08-03 16:58:35 -0400550 FromTopic: request.Header.ToTopic,
551 ToTopic: request.Header.FromTopic,
khenaidoo2c6a0992019-04-29 13:46:56 -0400552 KeyTopic: request.Header.KeyTopic,
khenaidoo8f474192019-04-03 17:20:44 -0400553 Timestamp: time.Now().UnixNano(),
khenaidooabad44c2018-08-03 16:58:35 -0400554 }
555
556 // Go over all returned values
557 var marshalledReturnedVal *any.Any
558 var err error
559 for _, returnVal := range returnedValues {
khenaidoo43c82122018-11-22 18:38:28 -0500560 if marshalledReturnedVal, err = encodeReturnedValue(returnVal); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800561 logger.Warnw("cannot-marshal-response-body", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400562 }
563 break // for now we support only 1 returned value - (excluding the error)
564 }
565
khenaidoo79232702018-12-04 11:00:41 -0500566 responseBody := &ic.InterContainerResponseBody{
khenaidooabad44c2018-08-03 16:58:35 -0400567 Success: success,
568 Result: marshalledReturnedVal,
569 }
570
571 // Marshal the response body
572 var marshalledResponseBody *any.Any
573 if marshalledResponseBody, err = ptypes.MarshalAny(responseBody); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800574 logger.Warnw("cannot-marshal-response-body", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400575 return nil, err
576 }
577
khenaidoo79232702018-12-04 11:00:41 -0500578 return &ic.InterContainerMessage{
khenaidooabad44c2018-08-03 16:58:35 -0400579 Header: responseHeader,
580 Body: marshalledResponseBody,
581 }, nil
582}
583
584func CallFuncByName(myClass interface{}, funcName string, params ...interface{}) (out []reflect.Value, err error) {
585 myClassValue := reflect.ValueOf(myClass)
khenaidoo19374072018-12-11 11:05:15 -0500586 // Capitalize the first letter in the funcName to workaround the first capital letters required to
587 // invoke a function from a different package
588 funcName = strings.Title(funcName)
khenaidooabad44c2018-08-03 16:58:35 -0400589 m := myClassValue.MethodByName(funcName)
590 if !m.IsValid() {
khenaidoo43c82122018-11-22 18:38:28 -0500591 return make([]reflect.Value, 0), fmt.Errorf("method-not-found \"%s\"", funcName)
khenaidooabad44c2018-08-03 16:58:35 -0400592 }
593 in := make([]reflect.Value, len(params))
594 for i, param := range params {
595 in[i] = reflect.ValueOf(param)
596 }
597 out = m.Call(in)
598 return
599}
600
khenaidoo297cd252019-02-07 22:10:23 -0500601func (kp *InterContainerProxy) addTransactionId(transactionId string, currentArgs []*ic.Argument) []*ic.Argument {
602 arg := &KVArg{
603 Key: TransactionKey,
604 Value: &ic.StrType{Val: transactionId},
605 }
606
607 var marshalledArg *any.Any
608 var err error
609 if marshalledArg, err = ptypes.MarshalAny(&ic.StrType{Val: transactionId}); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800610 logger.Warnw("cannot-add-transactionId", log.Fields{"error": err})
khenaidoo297cd252019-02-07 22:10:23 -0500611 return currentArgs
612 }
613 protoArg := &ic.Argument{
614 Key: arg.Key,
615 Value: marshalledArg,
616 }
617 return append(currentArgs, protoArg)
618}
619
khenaidoo54e0ddf2019-02-27 16:21:33 -0500620func (kp *InterContainerProxy) addFromTopic(fromTopic string, currentArgs []*ic.Argument) []*ic.Argument {
621 var marshalledArg *any.Any
622 var err error
623 if marshalledArg, err = ptypes.MarshalAny(&ic.StrType{Val: fromTopic}); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800624 logger.Warnw("cannot-add-transactionId", log.Fields{"error": err})
khenaidoo54e0ddf2019-02-27 16:21:33 -0500625 return currentArgs
626 }
627 protoArg := &ic.Argument{
628 Key: FromTopic,
629 Value: marshalledArg,
630 }
631 return append(currentArgs, protoArg)
632}
633
634func (kp *InterContainerProxy) handleMessage(msg *ic.InterContainerMessage, targetInterface interface{}) {
khenaidooabad44c2018-08-03 16:58:35 -0400635
khenaidoo43c82122018-11-22 18:38:28 -0500636 // First extract the header to know whether this is a request - responses are handled by a different handler
khenaidoo79232702018-12-04 11:00:41 -0500637 if msg.Header.Type == ic.MessageType_REQUEST {
khenaidooabad44c2018-08-03 16:58:35 -0400638 var out []reflect.Value
639 var err error
640
641 // Get the request body
khenaidoo79232702018-12-04 11:00:41 -0500642 requestBody := &ic.InterContainerRequestBody{}
khenaidooabad44c2018-08-03 16:58:35 -0400643 if err = ptypes.UnmarshalAny(msg.Body, requestBody); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800644 logger.Warnw("cannot-unmarshal-request", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400645 } else {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800646 logger.Debugw("received-request", log.Fields{"rpc": requestBody.Rpc, "header": msg.Header})
khenaidooabad44c2018-08-03 16:58:35 -0400647 // let the callee unpack the arguments as its the only one that knows the real proto type
khenaidoo297cd252019-02-07 22:10:23 -0500648 // Augment the requestBody with the message Id as it will be used in scenarios where cores
649 // are set in pairs and competing
650 requestBody.Args = kp.addTransactionId(msg.Header.Id, requestBody.Args)
khenaidoo54e0ddf2019-02-27 16:21:33 -0500651
652 // Augment the requestBody with the From topic name as it will be used in scenarios where a container
653 // needs to send an unsollicited message to the currently requested container
654 requestBody.Args = kp.addFromTopic(msg.Header.FromTopic, requestBody.Args)
655
khenaidooabad44c2018-08-03 16:58:35 -0400656 out, err = CallFuncByName(targetInterface, requestBody.Rpc, requestBody.Args)
657 if err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800658 logger.Warn(err)
khenaidooabad44c2018-08-03 16:58:35 -0400659 }
660 }
661 // Response required?
662 if requestBody.ResponseRequired {
663 // If we already have an error before then just return that
khenaidoo79232702018-12-04 11:00:41 -0500664 var returnError *ic.Error
khenaidooabad44c2018-08-03 16:58:35 -0400665 var returnedValues []interface{}
666 var success bool
667 if err != nil {
khenaidoo79232702018-12-04 11:00:41 -0500668 returnError = &ic.Error{Reason: err.Error()}
khenaidooabad44c2018-08-03 16:58:35 -0400669 returnedValues = make([]interface{}, 1)
670 returnedValues[0] = returnError
671 } else {
khenaidoob9203542018-09-17 22:56:37 -0400672 returnedValues = make([]interface{}, 0)
673 // Check for errors first
674 lastIndex := len(out) - 1
675 if out[lastIndex].Interface() != nil { // Error
khenaidoo09771ef2019-10-11 14:25:02 -0400676 if retError, ok := out[lastIndex].Interface().(error); ok {
677 if retError.Error() == ErrorTransactionNotAcquired.Error() {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800678 logger.Debugw("Ignoring request", log.Fields{"error": retError, "txId": msg.Header.Id})
khenaidoo09771ef2019-10-11 14:25:02 -0400679 return // Ignore - process is in competing mode and ignored transaction
680 }
681 returnError = &ic.Error{Reason: retError.Error()}
khenaidoob9203542018-09-17 22:56:37 -0400682 returnedValues = append(returnedValues, returnError)
683 } else { // Should never happen
khenaidoo79232702018-12-04 11:00:41 -0500684 returnError = &ic.Error{Reason: "incorrect-error-returns"}
khenaidoob9203542018-09-17 22:56:37 -0400685 returnedValues = append(returnedValues, returnError)
686 }
khenaidoo54e0ddf2019-02-27 16:21:33 -0500687 } else if len(out) == 2 && reflect.ValueOf(out[0].Interface()).IsValid() && reflect.ValueOf(out[0].Interface()).IsNil() {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800688 logger.Warnw("Unexpected response of (nil,nil)", log.Fields{"txId": msg.Header.Id})
khenaidoo09771ef2019-10-11 14:25:02 -0400689 return // Ignore - should not happen
khenaidoob9203542018-09-17 22:56:37 -0400690 } else { // Non-error case
691 success = true
692 for idx, val := range out {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800693 //logger.Debugw("returned-api-response-loop", log.Fields{"idx": idx, "val": val.Interface()})
khenaidoob9203542018-09-17 22:56:37 -0400694 if idx != lastIndex {
695 returnedValues = append(returnedValues, val.Interface())
khenaidooabad44c2018-08-03 16:58:35 -0400696 }
khenaidooabad44c2018-08-03 16:58:35 -0400697 }
698 }
699 }
700
khenaidoo79232702018-12-04 11:00:41 -0500701 var icm *ic.InterContainerMessage
khenaidooabad44c2018-08-03 16:58:35 -0400702 if icm, err = encodeResponse(msg, success, returnedValues...); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800703 logger.Warnw("error-encoding-response-returning-failure-result", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400704 icm = encodeDefaultFailedResponse(msg)
705 }
khenaidoo43c82122018-11-22 18:38:28 -0500706 // To preserve ordering of messages, all messages to a given topic are sent to the same partition
707 // by providing a message key. The key is encoded in the topic name. If the deviceId is not
708 // present then the key will be empty, hence all messages for a given topic will be sent to all
709 // partitions.
710 replyTopic := &Topic{Name: msg.Header.FromTopic}
khenaidoobdcb8e02019-03-06 16:28:56 -0500711 key := msg.Header.KeyTopic
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800712 logger.Debugw("sending-response-to-kafka", log.Fields{"rpc": requestBody.Rpc, "header": icm.Header, "key": key})
khenaidoo43c82122018-11-22 18:38:28 -0500713 // TODO: handle error response.
khenaidoo2c6a0992019-04-29 13:46:56 -0400714 go kp.kafkaClient.Send(icm, replyTopic, key)
khenaidooabad44c2018-08-03 16:58:35 -0400715 }
khenaidoo54e0ddf2019-02-27 16:21:33 -0500716 } else if msg.Header.Type == ic.MessageType_RESPONSE {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800717 logger.Debugw("response-received", log.Fields{"msg-header": msg.Header})
khenaidoo54e0ddf2019-02-27 16:21:33 -0500718 go kp.dispatchResponse(msg)
719 } else {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800720 logger.Warnw("unsupported-message-received", log.Fields{"msg-header": msg.Header})
khenaidooabad44c2018-08-03 16:58:35 -0400721 }
722}
723
khenaidoo54e0ddf2019-02-27 16:21:33 -0500724func (kp *InterContainerProxy) waitForMessages(ch <-chan *ic.InterContainerMessage, topic Topic, targetInterface interface{}) {
khenaidooabad44c2018-08-03 16:58:35 -0400725 // Wait for messages
726 for msg := range ch {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800727 //logger.Debugw("request-received", log.Fields{"msg": msg, "topic": topic.Name, "target": targetInterface})
khenaidoo54e0ddf2019-02-27 16:21:33 -0500728 go kp.handleMessage(msg, targetInterface)
khenaidooabad44c2018-08-03 16:58:35 -0400729 }
730}
731
khenaidoo79232702018-12-04 11:00:41 -0500732func (kp *InterContainerProxy) dispatchResponse(msg *ic.InterContainerMessage) {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400733 kp.lockTransactionIdToChannelMap.RLock()
734 defer kp.lockTransactionIdToChannelMap.RUnlock()
khenaidooabad44c2018-08-03 16:58:35 -0400735 if _, exist := kp.transactionIdToChannelMap[msg.Header.Id]; !exist {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800736 logger.Debugw("no-waiting-channel", log.Fields{"transaction": msg.Header.Id})
khenaidooabad44c2018-08-03 16:58:35 -0400737 return
738 }
khenaidoo43c82122018-11-22 18:38:28 -0500739 kp.transactionIdToChannelMap[msg.Header.Id].ch <- msg
khenaidooabad44c2018-08-03 16:58:35 -0400740}
741
khenaidooabad44c2018-08-03 16:58:35 -0400742// subscribeForResponse allows a caller to subscribe to a given topic when waiting for a response.
743// This method is built to prevent all subscribers to receive all messages as is the case of the Subscribe
744// API. There is one response channel waiting for kafka messages before dispatching the message to the
745// corresponding waiting channel
khenaidoo79232702018-12-04 11:00:41 -0500746func (kp *InterContainerProxy) subscribeForResponse(topic Topic, trnsId string) (chan *ic.InterContainerMessage, error) {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800747 logger.Debugw("subscribeForResponse", log.Fields{"topic": topic.Name, "trnsid": trnsId})
khenaidooabad44c2018-08-03 16:58:35 -0400748
khenaidoo4c1a5bf2018-11-29 15:53:42 -0500749 // Create a specific channel for this consumers. We cannot use the channel from the kafkaclient as it will
khenaidoo43c82122018-11-22 18:38:28 -0500750 // broadcast any message for this topic to all channels waiting on it.
khenaidoo79232702018-12-04 11:00:41 -0500751 ch := make(chan *ic.InterContainerMessage)
khenaidoo43c82122018-11-22 18:38:28 -0500752 kp.addToTransactionIdToChannelMap(trnsId, &topic, ch)
khenaidooabad44c2018-08-03 16:58:35 -0400753
754 return ch, nil
755}
756
khenaidoo43c82122018-11-22 18:38:28 -0500757func (kp *InterContainerProxy) unSubscribeForResponse(trnsId string) error {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800758 logger.Debugw("unsubscribe-for-response", log.Fields{"trnsId": trnsId})
khenaidoo7ff26c72019-01-16 14:55:48 -0500759 kp.deleteFromTransactionIdToChannelMap(trnsId)
khenaidooabad44c2018-08-03 16:58:35 -0400760 return nil
761}
762
Scott Bakeree6a0872019-10-29 15:59:52 -0700763func (kp *InterContainerProxy) EnableLivenessChannel(enable bool) chan bool {
764 return kp.kafkaClient.EnableLivenessChannel(enable)
765}
766
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800767func (kp *InterContainerProxy) EnableHealthinessChannel(enable bool) chan bool {
768 return kp.kafkaClient.EnableHealthinessChannel(enable)
769}
770
Scott Bakeree6a0872019-10-29 15:59:52 -0700771func (kp *InterContainerProxy) SendLiveness() error {
772 return kp.kafkaClient.SendLiveness()
773}
774
khenaidooabad44c2018-08-03 16:58:35 -0400775//formatRequest formats a request to send over kafka and returns an InterContainerMessage message on success
776//or an error on failure
khenaidoobdcb8e02019-03-06 16:28:56 -0500777func encodeRequest(rpc string, toTopic *Topic, replyTopic *Topic, key string, kvArgs ...*KVArg) (*ic.InterContainerMessage, error) {
khenaidoo79232702018-12-04 11:00:41 -0500778 requestHeader := &ic.Header{
khenaidooabad44c2018-08-03 16:58:35 -0400779 Id: uuid.New().String(),
khenaidoo79232702018-12-04 11:00:41 -0500780 Type: ic.MessageType_REQUEST,
khenaidooabad44c2018-08-03 16:58:35 -0400781 FromTopic: replyTopic.Name,
782 ToTopic: toTopic.Name,
khenaidoo2c6a0992019-04-29 13:46:56 -0400783 KeyTopic: key,
khenaidoo8f474192019-04-03 17:20:44 -0400784 Timestamp: time.Now().UnixNano(),
khenaidooabad44c2018-08-03 16:58:35 -0400785 }
khenaidoo79232702018-12-04 11:00:41 -0500786 requestBody := &ic.InterContainerRequestBody{
khenaidooabad44c2018-08-03 16:58:35 -0400787 Rpc: rpc,
788 ResponseRequired: true,
789 ReplyToTopic: replyTopic.Name,
790 }
791
792 for _, arg := range kvArgs {
khenaidoo2c6f1672018-09-20 23:14:41 -0400793 if arg == nil {
794 // In case the caller sends an array with empty args
795 continue
796 }
khenaidooabad44c2018-08-03 16:58:35 -0400797 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 {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800802 logger.Warnw("argument-value-not-proto-message", log.Fields{"error": ok, "Value": arg.Value})
khenaidooabad44c2018-08-03 16:58:35 -0400803 err := errors.New("argument-value-not-proto-message")
804 return nil, err
805 }
806 if marshalledArg, err = ptypes.MarshalAny(protoValue); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800807 logger.Warnw("cannot-marshal-request", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400808 return nil, err
809 }
khenaidoo79232702018-12-04 11:00:41 -0500810 protoArg := &ic.Argument{
khenaidooabad44c2018-08-03 16:58:35 -0400811 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 {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800820 logger.Warnw("cannot-marshal-request", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400821 return nil, err
822 }
khenaidoo79232702018-12-04 11:00:41 -0500823 request := &ic.InterContainerMessage{
khenaidooabad44c2018-08-03 16:58:35 -0400824 Header: requestHeader,
825 Body: marshalledData,
826 }
827 return request, nil
828}
829
khenaidoo79232702018-12-04 11:00:41 -0500830func decodeResponse(response *ic.InterContainerMessage) (*ic.InterContainerResponseBody, error) {
khenaidooabad44c2018-08-03 16:58:35 -0400831 // Extract the message body
khenaidoo79232702018-12-04 11:00:41 -0500832 responseBody := ic.InterContainerResponseBody{}
khenaidooabad44c2018-08-03 16:58:35 -0400833 if err := ptypes.UnmarshalAny(response.Body, &responseBody); err != nil {
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800834 logger.Warnw("cannot-unmarshal-response", log.Fields{"error": err})
khenaidooabad44c2018-08-03 16:58:35 -0400835 return nil, err
836 }
serkant.uluderya2ae470f2020-01-21 11:13:09 -0800837 //logger.Debugw("response-decoded-successfully", log.Fields{"response-status": &responseBody.Success})
khenaidooabad44c2018-08-03 16:58:35 -0400838
839 return &responseBody, nil
840
841}