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