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