blob: 7a94f7b4d26088624dd07a7512051db6d4d7dd2f [file] [log] [blame]
sslobodr392ebd52019-01-18 12:41:49 -05001/*
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 */
sslobodr392ebd52019-01-18 12:41:49 -050016
17package afrouter
18
19import (
sslobodr392ebd52019-01-18 12:41:49 -050020 "errors"
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040021 "fmt"
22 "github.com/golang/protobuf/proto"
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040023 "github.com/opencord/voltha-go/common/log"
24 "google.golang.org/grpc"
sslobodr1d1e50b2019-03-14 09:17:40 -040025 "regexp"
sslobodr392ebd52019-01-18 12:41:49 -050026 "strconv"
sslobodr392ebd52019-01-18 12:41:49 -050027)
28
Scott Baker112b0d42019-08-22 08:32:26 -070029// TODO: Used in multiple routers, should move to common file
sslobodr1d1e50b2019-03-14 09:17:40 -040030const (
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040031 PKG_MTHD_PKG int = 1
sslobodr1d1e50b2019-03-14 09:17:40 -040032 PKG_MTHD_MTHD int = 2
33)
34
sslobodr392ebd52019-01-18 12:41:49 -050035type AffinityRouter struct {
Kent Hagerman1e9061e2019-05-21 16:01:21 -040036 name string
37 association associationType
38 routingField string
39 grpcService string
Kent Hagerman1e9061e2019-05-21 16:01:21 -040040 methodMap map[string]byte
41 nbBindingMethodMap map[string]byte
42 cluster *cluster
43 affinity map[string]*backend
44 currentBackend **backend
sslobodr392ebd52019-01-18 12:41:49 -050045}
46
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040047func newAffinityRouter(rconf *RouterConfig, config *RouteConfig) (Router, error) {
sslobodr392ebd52019-01-18 12:41:49 -050048 var err error = nil
Kent Hagerman1e9061e2019-05-21 16:01:21 -040049 var rtrn_err = false
50 var pkg_re = regexp.MustCompile(`^(\.[^.]+\.)(.+)$`)
sslobodr392ebd52019-01-18 12:41:49 -050051 // Validate the configuration
52
53 // A name must exist
54 if config.Name == "" {
55 log.Error("A router 'name' must be specified")
56 rtrn_err = true
57 }
58
59 if rconf.ProtoPackage == "" {
60 log.Error("A 'package' must be specified")
61 rtrn_err = true
62 }
63
64 if rconf.ProtoService == "" {
65 log.Error("A 'service' must be specified")
66 rtrn_err = true
67 }
68
69 //if config.RouteField == "" {
70 // log.Error("A 'routing_field' must be specified")
71 // rtrn_err = true
72 //}
73
74 // TODO The overrieds section is currently not being used
75 // so the router will route all methods based on the
76 // routing_field. This needs to be added so that methods
77 // can have different routing fields.
78 var bptr *backend
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040079 bptr = nil
sslobodr392ebd52019-01-18 12:41:49 -050080 dr := AffinityRouter{
Kent Hagerman1e9061e2019-05-21 16:01:21 -040081 name: config.Name,
82 grpcService: rconf.ProtoService,
83 affinity: make(map[string]*backend),
84 methodMap: make(map[string]byte),
85 nbBindingMethodMap: make(map[string]byte),
86 currentBackend: &bptr,
sslobodr392ebd52019-01-18 12:41:49 -050087 }
88 // An association must exist
Kent Hagerman1e9061e2019-05-21 16:01:21 -040089 dr.association = config.Association
90 if dr.association == AssociationUndefined {
91 log.Error("An association must be specified")
sslobodr392ebd52019-01-18 12:41:49 -050092 rtrn_err = true
93 }
94
sslobodr392ebd52019-01-18 12:41:49 -050095 // Build the routing structure based on the loaded protobuf
96 // descriptor file and the config information.
97 type key struct {
Kent Hagerman1e9061e2019-05-21 16:01:21 -040098 method string
99 field string
sslobodr392ebd52019-01-18 12:41:49 -0500100 }
Kent Hagerman03b58992019-08-29 17:21:03 -0400101 var fieldNumberLookup = make(map[key]byte)
102 for _, f := range rconf.protoDescriptor.File {
sslobodr392ebd52019-01-18 12:41:49 -0500103 // Build a temporary map of message types by name.
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400104 for _, m := range f.MessageType {
105 for _, fld := range m.Field {
sslobodr392ebd52019-01-18 12:41:49 -0500106 log.Debugf("Processing message '%s', field '%s'", *m.Name, *fld.Name)
Kent Hagerman03b58992019-08-29 17:21:03 -0400107 fieldNumberLookup[key{*m.Name, *fld.Name}] = byte(*fld.Number)
sslobodr392ebd52019-01-18 12:41:49 -0500108 }
109 }
110 }
Kent Hagerman03b58992019-08-29 17:21:03 -0400111 for _, f := range rconf.protoDescriptor.File {
sslobodr392ebd52019-01-18 12:41:49 -0500112 if *f.Package == rconf.ProtoPackage {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400113 for _, s := range f.Service {
sslobodr392ebd52019-01-18 12:41:49 -0500114 if *s.Name == rconf.ProtoService {
115 log.Debugf("Loading package data '%s' for service '%s' for router '%s'", *f.Package, *s.Name, dr.name)
116 // Now create a map keyed by method name with the value being the
117 // field number of the route selector.
118 var ok bool
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400119 for _, m := range s.Method {
sslobodr392ebd52019-01-18 12:41:49 -0500120 // Find the input type in the messages and extract the
121 // field number and save it for future reference.
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400122 log.Debugf("Processing method '%s'", *m.Name)
sslobodr392ebd52019-01-18 12:41:49 -0500123 // Determine if this is a method we're supposed to be processing.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400124 if needMethod(*m.Name, config) {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400125 log.Debugf("Enabling method '%s'", *m.Name)
sslobodr1d1e50b2019-03-14 09:17:40 -0400126 pkg_methd := pkg_re.FindStringSubmatch(*m.InputType)
127 if pkg_methd == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400128 log.Errorf("Regular expression didn't match input type '%s'", *m.InputType)
sslobodr1d1e50b2019-03-14 09:17:40 -0400129 rtrn_err = true
130 }
sslobodr392ebd52019-01-18 12:41:49 -0500131 // The input type has the package name prepended to it. Remove it.
sslobodr1d1e50b2019-03-14 09:17:40 -0400132 //in := (*m.InputType)[len(rconf.ProtoPackage)+2:]
133 in := pkg_methd[PKG_MTHD_MTHD]
Kent Hagerman03b58992019-08-29 17:21:03 -0400134 dr.methodMap[*m.Name], ok = fieldNumberLookup[key{in, config.RouteField}]
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400135 if !ok {
sslobodr392ebd52019-01-18 12:41:49 -0500136 log.Errorf("Method '%s' has no field named '%s' in it's parameter message '%s'",
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400137 *m.Name, config.RouteField, in)
sslobodr392ebd52019-01-18 12:41:49 -0500138 rtrn_err = true
139 }
140 }
141 // The sb method is always included in the methods so we can check it here too.
Kent Hagerman03b58992019-08-29 17:21:03 -0400142 if needNbBindingMethod(*m.Name, config) {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400143 log.Debugf("Enabling southbound method '%s'", *m.Name)
sslobodr392ebd52019-01-18 12:41:49 -0500144 // The output type has the package name prepended to it. Remove it.
145 out := (*m.OutputType)[len(rconf.ProtoPackage)+2:]
Kent Hagerman03b58992019-08-29 17:21:03 -0400146 dr.nbBindingMethodMap[*m.Name], ok = fieldNumberLookup[key{out, config.RouteField}]
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400147 if !ok {
sslobodr392ebd52019-01-18 12:41:49 -0500148 log.Errorf("Method '%s' has no field named '%s' in it's parameter message '%s'",
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400149 *m.Name, config.RouteField, out)
sslobodr392ebd52019-01-18 12:41:49 -0500150 rtrn_err = true
151 }
152 }
153 }
154 }
155 }
156 }
157 }
158
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400159 // Create the backend cluster or link to an existing one
sslobodr392ebd52019-01-18 12:41:49 -0500160 ok := true
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400161 if dr.cluster, ok = clusters[config.backendCluster.Name]; !ok {
162 if dr.cluster, err = newBackendCluster(config.backendCluster); err != nil {
sslobodr392ebd52019-01-18 12:41:49 -0500163 log.Errorf("Could not create a backend for router %s", config.Name)
164 rtrn_err = true
165 }
166 }
167
168 if rtrn_err {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400169 return dr, errors.New(fmt.Sprintf("Failed to create a new router '%s'", dr.name))
sslobodr392ebd52019-01-18 12:41:49 -0500170 }
171
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400172 return dr, nil
sslobodr392ebd52019-01-18 12:41:49 -0500173}
174
Kent Hagerman03b58992019-08-29 17:21:03 -0400175func needNbBindingMethod(mthd string, conf *RouteConfig) bool {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400176 for _, m := range conf.NbBindingMethods {
sslobodr392ebd52019-01-18 12:41:49 -0500177 if mthd == m {
178 return true
179 }
180 }
181 return false
182}
183
Scott Baker112b0d42019-08-22 08:32:26 -0700184// TODO: Used in multiple routers, should move to common file
sslobodr392ebd52019-01-18 12:41:49 -0500185func needMethod(mthd string, conf *RouteConfig) bool {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400186 for _, m := range conf.Methods {
sslobodr392ebd52019-01-18 12:41:49 -0500187 if mthd == m {
188 return true
189 }
190 }
191 return false
192}
193
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400194func (ar AffinityRouter) Service() string {
195 return ar.grpcService
sslobodr392ebd52019-01-18 12:41:49 -0500196}
197
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400198func (ar AffinityRouter) Name() string {
199 return ar.name
sslobodr392ebd52019-01-18 12:41:49 -0500200}
201
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400202func (ar AffinityRouter) skipField(data *[]byte, idx *int) error {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400203 switch (*data)[*idx] & 3 {
204 case 0: // Varint
Scott Bakeracacd472019-09-20 17:46:35 -0700205 // skip the field number/type
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400206 *idx++
Scott Bakeracacd472019-09-20 17:46:35 -0700207 // if the msb is set, then more bytes to follow
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400208 for (*data)[*idx] >= 128 {
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400209 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400210 }
Scott Bakeracacd472019-09-20 17:46:35 -0700211 // the last byte doesn't have the msb set
212 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400213 case 1: // 64 bit
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400214 *idx += 9
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400215 case 2: // Length delimited
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400216 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400217 b := proto.NewBuffer((*data)[*idx:])
218 t, _ := b.DecodeVarint()
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400219 *idx += int(t) + 1
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400220 case 3: // Deprecated
221 case 4: // Deprecated
222 case 5: // 32 bit
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400223 *idx += 5
sslobodr392ebd52019-01-18 12:41:49 -0500224 }
225 return nil
226}
227
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400228func (ar AffinityRouter) decodeProtoField(payload []byte, fieldId byte) (string, error) {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400229 idx := 0
sslobodr392ebd52019-01-18 12:41:49 -0500230 b := proto.NewBuffer([]byte{})
sslobodr1d1e50b2019-03-14 09:17:40 -0400231 //b.DebugPrint("The Buffer", payload)
sslobodr392ebd52019-01-18 12:41:49 -0500232 for { // Find the route selector field
233 log.Debugf("Decoding afinity value attributeNumber: %d from %v at index %d", fieldId, payload, idx)
234 log.Debugf("Attempting match with payload: %d, methodTable: %d", payload[idx], fieldId)
235 if payload[idx]>>3 == fieldId {
236 log.Debugf("Method match with payload: %d, methodTable: %d", payload[idx], fieldId)
237 // TODO: Consider supporting other selector types.... Way, way in the future
238 // ok, the future is now, support strings as well... ugh.
239 var selector string
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400240 switch payload[idx] & 3 {
241 case 0: // Integer
242 b.SetBuf(payload[idx+1:])
243 v, e := b.DecodeVarint()
244 if e == nil {
245 log.Debugf("Decoded the ing field: %v", v)
246 selector = strconv.Itoa(int(v))
247 } else {
248 log.Errorf("Failed to decode varint %v", e)
249 return "", e
250 }
251 case 2: // Length delimited AKA string
252 b.SetBuf(payload[idx+1:])
253 v, e := b.DecodeStringBytes()
254 if e == nil {
255 log.Debugf("Decoded the string field: %v", v)
256 selector = v
257 } else {
258 log.Errorf("Failed to decode string %v", e)
259 return "", e
260 }
261 default:
262 err := errors.New(fmt.Sprintf("Only integer and string route selectors are permitted"))
263 log.Error(err)
264 return "", err
sslobodr392ebd52019-01-18 12:41:49 -0500265 }
266 return selector, nil
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400267 } else if err := ar.skipField(&payload, &idx); err != nil {
sslobodr392ebd52019-01-18 12:41:49 -0500268 log.Errorf("Parsing message failed %v", err)
269 return "", err
270 }
271 }
272}
273
Scott Baker112b0d42019-08-22 08:32:26 -0700274func (ar AffinityRouter) Route(sel interface{}) (*backend, *connection) {
sslobodr392ebd52019-01-18 12:41:49 -0500275 switch sl := sel.(type) {
Kent Hagerman03b58992019-08-29 17:21:03 -0400276 case *requestFrame:
277 log.Debugf("Route called for requestFrame with method %s", sl.methodInfo.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400278 // Check if this method should be affinity bound from the
279 // reply rather than the request.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400280 if _, ok := ar.nbBindingMethodMap[sl.methodInfo.method]; ok {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400281 var err error
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400282 log.Debugf("Method '%s' affinity binds on reply", sl.methodInfo.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400283 // Just round robin route the southbound request
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400284 if *ar.currentBackend, err = ar.cluster.nextBackend(*ar.currentBackend, BackendSequenceRoundRobin); err == nil {
Scott Baker112b0d42019-08-22 08:32:26 -0700285 return *ar.currentBackend, nil
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400286 } else {
287 sl.err = err
Scott Baker112b0d42019-08-22 08:32:26 -0700288 return nil, nil
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400289 }
290 }
291 // Not a south affinity binding method, proceed with north affinity binding.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400292 if selector, err := ar.decodeProtoField(sl.payload, ar.methodMap[sl.methodInfo.method]); err == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400293 log.Debugf("Establishing affinity for selector: %s", selector)
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400294 if rtrn, ok := ar.affinity[selector]; ok {
Scott Baker112b0d42019-08-22 08:32:26 -0700295 return rtrn, nil
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400296 } else {
297 // The selector isn't in the map, create a new affinity mapping
298 log.Debugf("MUST CREATE A NEW AFFINITY MAP ENTRY!!")
sslobodr392ebd52019-01-18 12:41:49 -0500299 var err error
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400300 if *ar.currentBackend, err = ar.cluster.nextBackend(*ar.currentBackend, BackendSequenceRoundRobin); err == nil {
301 ar.setAffinity(selector, *ar.currentBackend)
302 //ar.affinity[selector] = *ar.currentBackend
303 //log.Debugf("New affinity set to backend %s",(*ar.currentBackend).name)
Scott Baker112b0d42019-08-22 08:32:26 -0700304 return *ar.currentBackend, nil
sslobodr392ebd52019-01-18 12:41:49 -0500305 } else {
306 sl.err = err
Scott Baker112b0d42019-08-22 08:32:26 -0700307 return nil, nil
sslobodr392ebd52019-01-18 12:41:49 -0500308 }
309 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400310 }
311 default:
312 log.Errorf("Internal: invalid data type in Route call %v", sel)
Scott Baker112b0d42019-08-22 08:32:26 -0700313 return nil, nil
sslobodr392ebd52019-01-18 12:41:49 -0500314 }
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400315 log.Errorf("Bad lookup in affinity map %v", ar.affinity)
Scott Baker112b0d42019-08-22 08:32:26 -0700316 return nil, nil
sslobodr392ebd52019-01-18 12:41:49 -0500317}
318
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400319func (ar AffinityRouter) GetMetaKeyVal(serverStream grpc.ServerStream) (string, string, error) {
320 return "", "", nil
sslobodr392ebd52019-01-18 12:41:49 -0500321}
322
Kent Hagerman03b58992019-08-29 17:21:03 -0400323func (ar AffinityRouter) IsStreaming(_ string) (bool, bool) {
324 panic("not implemented")
325}
326
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400327func (ar AffinityRouter) BackendCluster(mthd string, metaKey string) (*cluster, error) {
328 return ar.cluster, nil
sslobodr392ebd52019-01-18 12:41:49 -0500329}
330
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400331func (ar AffinityRouter) FindBackendCluster(beName string) *cluster {
332 if beName == ar.cluster.name {
333 return ar.cluster
sslobodr392ebd52019-01-18 12:41:49 -0500334 }
335 return nil
336}
337
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400338func (ar AffinityRouter) ReplyHandler(sel interface{}) error {
sslobodr392ebd52019-01-18 12:41:49 -0500339 switch sl := sel.(type) {
Kent Hagerman03b58992019-08-29 17:21:03 -0400340 case *responseFrame:
341 log.Debugf("Reply handler called for responseFrame with method %s", sl.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400342 // Determine if reply action is required.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400343 if fld, ok := ar.nbBindingMethodMap[sl.method]; ok && len(sl.payload) > 0 {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400344 // Extract the field value from the frame and
345 // and set affinity accordingly
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400346 if selector, err := ar.decodeProtoField(sl.payload, fld); err == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400347 log.Debug("Settign affinity on reply")
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400348 if ar.setAffinity(selector, sl.backend) != nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400349 log.Error("Setting affinity on reply failed")
sslobodr392ebd52019-01-18 12:41:49 -0500350 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400351 return nil
352 } else {
353 err := errors.New(fmt.Sprintf("Failed to decode reply field %d for method %s", fld, sl.method))
354 log.Error(err)
355 return err
sslobodr392ebd52019-01-18 12:41:49 -0500356 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400357 }
358 return nil
359 default:
360 err := errors.New(fmt.Sprintf("Internal: invalid data type in ReplyHander call %v", sl))
361 log.Error(err)
362 return err
sslobodr392ebd52019-01-18 12:41:49 -0500363 }
364}
365
366func (ar AffinityRouter) setAffinity(key string, be *backend) error {
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400367 if be2, ok := ar.affinity[key]; !ok {
sslobodr392ebd52019-01-18 12:41:49 -0500368 ar.affinity[key] = be
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400369 log.Debugf("New affinity set to backend %s for key %s", be.name, key)
sslobodr392ebd52019-01-18 12:41:49 -0500370 } else if be2 != be {
371 err := errors.New(fmt.Sprintf("Attempting multiple sets of affinity for key %s to backend %s from %s on router %s",
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400372 key, be.name, ar.affinity[key].name, ar.name))
sslobodr392ebd52019-01-18 12:41:49 -0500373 log.Error(err)
374 return err
375 }
376 return nil
377}