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