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