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