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