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