blob: 583d0a70873814089a6e25ef380956ed9b356088 [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
sslobodr1d1e50b2019-03-14 09:17:40 -040029const (
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040030 PKG_MTHD_PKG int = 1
sslobodr1d1e50b2019-03-14 09:17:40 -040031 PKG_MTHD_MTHD int = 2
32)
33
sslobodr392ebd52019-01-18 12:41:49 -050034type AffinityRouter struct {
Kent Hagerman1e9061e2019-05-21 16:01:21 -040035 name string
36 association associationType
37 routingField string
38 grpcService string
Kent Hagerman1e9061e2019-05-21 16:01:21 -040039 methodMap map[string]byte
40 nbBindingMethodMap map[string]byte
41 cluster *cluster
42 affinity map[string]*backend
43 currentBackend **backend
sslobodr392ebd52019-01-18 12:41:49 -050044}
45
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040046func newAffinityRouter(rconf *RouterConfig, config *RouteConfig) (Router, error) {
sslobodr392ebd52019-01-18 12:41:49 -050047 var err error = nil
Kent Hagerman1e9061e2019-05-21 16:01:21 -040048 var rtrn_err = false
49 var pkg_re = regexp.MustCompile(`^(\.[^.]+\.)(.+)$`)
sslobodr392ebd52019-01-18 12:41:49 -050050 // Validate the configuration
51
52 // A name must exist
53 if config.Name == "" {
54 log.Error("A router 'name' must be specified")
55 rtrn_err = true
56 }
57
58 if rconf.ProtoPackage == "" {
59 log.Error("A 'package' must be specified")
60 rtrn_err = true
61 }
62
63 if rconf.ProtoService == "" {
64 log.Error("A 'service' must be specified")
65 rtrn_err = true
66 }
67
68 //if config.RouteField == "" {
69 // log.Error("A 'routing_field' must be specified")
70 // rtrn_err = true
71 //}
72
73 // TODO The overrieds section is currently not being used
74 // so the router will route all methods based on the
75 // routing_field. This needs to be added so that methods
76 // can have different routing fields.
77 var bptr *backend
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040078 bptr = nil
sslobodr392ebd52019-01-18 12:41:49 -050079 dr := AffinityRouter{
Kent Hagerman1e9061e2019-05-21 16:01:21 -040080 name: config.Name,
81 grpcService: rconf.ProtoService,
82 affinity: make(map[string]*backend),
83 methodMap: make(map[string]byte),
84 nbBindingMethodMap: make(map[string]byte),
85 currentBackend: &bptr,
sslobodr392ebd52019-01-18 12:41:49 -050086 }
87 // An association must exist
Kent Hagerman1e9061e2019-05-21 16:01:21 -040088 dr.association = config.Association
89 if dr.association == AssociationUndefined {
90 log.Error("An association must be specified")
sslobodr392ebd52019-01-18 12:41:49 -050091 rtrn_err = true
92 }
93
sslobodr392ebd52019-01-18 12:41:49 -050094 // Build the routing structure based on the loaded protobuf
95 // descriptor file and the config information.
96 type key struct {
Kent Hagerman1e9061e2019-05-21 16:01:21 -040097 method string
98 field string
sslobodr392ebd52019-01-18 12:41:49 -050099 }
Kent Hagerman03b58992019-08-29 17:21:03 -0400100 var fieldNumberLookup = make(map[key]byte)
101 for _, f := range rconf.protoDescriptor.File {
sslobodr392ebd52019-01-18 12:41:49 -0500102 // Build a temporary map of message types by name.
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400103 for _, m := range f.MessageType {
104 for _, fld := range m.Field {
sslobodr392ebd52019-01-18 12:41:49 -0500105 log.Debugf("Processing message '%s', field '%s'", *m.Name, *fld.Name)
Kent Hagerman03b58992019-08-29 17:21:03 -0400106 fieldNumberLookup[key{*m.Name, *fld.Name}] = byte(*fld.Number)
sslobodr392ebd52019-01-18 12:41:49 -0500107 }
108 }
109 }
Kent Hagerman03b58992019-08-29 17:21:03 -0400110 for _, f := range rconf.protoDescriptor.File {
sslobodr392ebd52019-01-18 12:41:49 -0500111 if *f.Package == rconf.ProtoPackage {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400112 for _, s := range f.Service {
sslobodr392ebd52019-01-18 12:41:49 -0500113 if *s.Name == rconf.ProtoService {
114 log.Debugf("Loading package data '%s' for service '%s' for router '%s'", *f.Package, *s.Name, dr.name)
115 // Now create a map keyed by method name with the value being the
116 // field number of the route selector.
117 var ok bool
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400118 for _, m := range s.Method {
sslobodr392ebd52019-01-18 12:41:49 -0500119 // Find the input type in the messages and extract the
120 // field number and save it for future reference.
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400121 log.Debugf("Processing method '%s'", *m.Name)
sslobodr392ebd52019-01-18 12:41:49 -0500122 // Determine if this is a method we're supposed to be processing.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400123 if needMethod(*m.Name, config) {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400124 log.Debugf("Enabling method '%s'", *m.Name)
sslobodr1d1e50b2019-03-14 09:17:40 -0400125 pkg_methd := pkg_re.FindStringSubmatch(*m.InputType)
126 if pkg_methd == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400127 log.Errorf("Regular expression didn't match input type '%s'", *m.InputType)
sslobodr1d1e50b2019-03-14 09:17:40 -0400128 rtrn_err = true
129 }
sslobodr392ebd52019-01-18 12:41:49 -0500130 // The input type has the package name prepended to it. Remove it.
sslobodr1d1e50b2019-03-14 09:17:40 -0400131 //in := (*m.InputType)[len(rconf.ProtoPackage)+2:]
132 in := pkg_methd[PKG_MTHD_MTHD]
Kent Hagerman03b58992019-08-29 17:21:03 -0400133 dr.methodMap[*m.Name], ok = fieldNumberLookup[key{in, config.RouteField}]
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400134 if !ok {
sslobodr392ebd52019-01-18 12:41:49 -0500135 log.Errorf("Method '%s' has no field named '%s' in it's parameter message '%s'",
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400136 *m.Name, config.RouteField, in)
sslobodr392ebd52019-01-18 12:41:49 -0500137 rtrn_err = true
138 }
139 }
140 // The sb method is always included in the methods so we can check it here too.
Kent Hagerman03b58992019-08-29 17:21:03 -0400141 if needNbBindingMethod(*m.Name, config) {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400142 log.Debugf("Enabling southbound method '%s'", *m.Name)
sslobodr392ebd52019-01-18 12:41:49 -0500143 // The output type has the package name prepended to it. Remove it.
144 out := (*m.OutputType)[len(rconf.ProtoPackage)+2:]
Kent Hagerman03b58992019-08-29 17:21:03 -0400145 dr.nbBindingMethodMap[*m.Name], ok = fieldNumberLookup[key{out, config.RouteField}]
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400146 if !ok {
sslobodr392ebd52019-01-18 12:41:49 -0500147 log.Errorf("Method '%s' has no field named '%s' in it's parameter message '%s'",
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400148 *m.Name, config.RouteField, out)
sslobodr392ebd52019-01-18 12:41:49 -0500149 rtrn_err = true
150 }
151 }
152 }
153 }
154 }
155 }
156 }
157
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400158 // Create the backend cluster or link to an existing one
sslobodr392ebd52019-01-18 12:41:49 -0500159 ok := true
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400160 if dr.cluster, ok = clusters[config.backendCluster.Name]; !ok {
161 if dr.cluster, err = newBackendCluster(config.backendCluster); err != nil {
sslobodr392ebd52019-01-18 12:41:49 -0500162 log.Errorf("Could not create a backend for router %s", config.Name)
163 rtrn_err = true
164 }
165 }
166
167 if rtrn_err {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400168 return dr, errors.New(fmt.Sprintf("Failed to create a new router '%s'", dr.name))
sslobodr392ebd52019-01-18 12:41:49 -0500169 }
170
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400171 return dr, nil
sslobodr392ebd52019-01-18 12:41:49 -0500172}
173
Kent Hagerman03b58992019-08-29 17:21:03 -0400174func needNbBindingMethod(mthd string, conf *RouteConfig) bool {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400175 for _, m := range conf.NbBindingMethods {
sslobodr392ebd52019-01-18 12:41:49 -0500176 if mthd == m {
177 return true
178 }
179 }
180 return false
181}
182
183func needMethod(mthd string, conf *RouteConfig) bool {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400184 for _, m := range conf.Methods {
sslobodr392ebd52019-01-18 12:41:49 -0500185 if mthd == m {
186 return true
187 }
188 }
189 return false
190}
191
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400192func (ar AffinityRouter) Service() string {
193 return ar.grpcService
sslobodr392ebd52019-01-18 12:41:49 -0500194}
195
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400196func (ar AffinityRouter) Name() string {
197 return ar.name
sslobodr392ebd52019-01-18 12:41:49 -0500198}
199
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400200func (ar AffinityRouter) skipField(data *[]byte, idx *int) error {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400201 switch (*data)[*idx] & 3 {
202 case 0: // Varint
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400203 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400204 for (*data)[*idx] >= 128 {
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400205 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400206 }
207 case 1: // 64 bit
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400208 *idx += 9
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400209 case 2: // Length delimited
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400210 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400211 b := proto.NewBuffer((*data)[*idx:])
212 t, _ := b.DecodeVarint()
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400213 *idx += int(t) + 1
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400214 case 3: // Deprecated
215 case 4: // Deprecated
216 case 5: // 32 bit
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400217 *idx += 5
sslobodr392ebd52019-01-18 12:41:49 -0500218 }
219 return nil
220}
221
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400222func (ar AffinityRouter) decodeProtoField(payload []byte, fieldId byte) (string, error) {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400223 idx := 0
sslobodr392ebd52019-01-18 12:41:49 -0500224 b := proto.NewBuffer([]byte{})
sslobodr1d1e50b2019-03-14 09:17:40 -0400225 //b.DebugPrint("The Buffer", payload)
sslobodr392ebd52019-01-18 12:41:49 -0500226 for { // Find the route selector field
227 log.Debugf("Decoding afinity value attributeNumber: %d from %v at index %d", fieldId, payload, idx)
228 log.Debugf("Attempting match with payload: %d, methodTable: %d", payload[idx], fieldId)
229 if payload[idx]>>3 == fieldId {
230 log.Debugf("Method match with payload: %d, methodTable: %d", payload[idx], fieldId)
231 // TODO: Consider supporting other selector types.... Way, way in the future
232 // ok, the future is now, support strings as well... ugh.
233 var selector string
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400234 switch payload[idx] & 3 {
235 case 0: // Integer
236 b.SetBuf(payload[idx+1:])
237 v, e := b.DecodeVarint()
238 if e == nil {
239 log.Debugf("Decoded the ing field: %v", v)
240 selector = strconv.Itoa(int(v))
241 } else {
242 log.Errorf("Failed to decode varint %v", e)
243 return "", e
244 }
245 case 2: // Length delimited AKA string
246 b.SetBuf(payload[idx+1:])
247 v, e := b.DecodeStringBytes()
248 if e == nil {
249 log.Debugf("Decoded the string field: %v", v)
250 selector = v
251 } else {
252 log.Errorf("Failed to decode string %v", e)
253 return "", e
254 }
255 default:
256 err := errors.New(fmt.Sprintf("Only integer and string route selectors are permitted"))
257 log.Error(err)
258 return "", err
sslobodr392ebd52019-01-18 12:41:49 -0500259 }
260 return selector, nil
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400261 } else if err := ar.skipField(&payload, &idx); err != nil {
sslobodr392ebd52019-01-18 12:41:49 -0500262 log.Errorf("Parsing message failed %v", err)
263 return "", err
264 }
265 }
266}
267
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400268func (ar AffinityRouter) Route(sel interface{}) *backend {
sslobodr392ebd52019-01-18 12:41:49 -0500269 switch sl := sel.(type) {
Kent Hagerman03b58992019-08-29 17:21:03 -0400270 case *requestFrame:
271 log.Debugf("Route called for requestFrame with method %s", sl.methodInfo.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400272 // Check if this method should be affinity bound from the
273 // reply rather than the request.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400274 if _, ok := ar.nbBindingMethodMap[sl.methodInfo.method]; ok {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400275 var err error
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400276 log.Debugf("Method '%s' affinity binds on reply", sl.methodInfo.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400277 // Just round robin route the southbound request
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400278 if *ar.currentBackend, err = ar.cluster.nextBackend(*ar.currentBackend, BackendSequenceRoundRobin); err == nil {
279 return *ar.currentBackend
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400280 } else {
281 sl.err = err
282 return nil
283 }
284 }
285 // Not a south affinity binding method, proceed with north affinity binding.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400286 if selector, err := ar.decodeProtoField(sl.payload, ar.methodMap[sl.methodInfo.method]); err == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400287 log.Debugf("Establishing affinity for selector: %s", selector)
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400288 if rtrn, ok := ar.affinity[selector]; ok {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400289 return rtrn
290 } else {
291 // The selector isn't in the map, create a new affinity mapping
292 log.Debugf("MUST CREATE A NEW AFFINITY MAP ENTRY!!")
sslobodr392ebd52019-01-18 12:41:49 -0500293 var err error
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400294 if *ar.currentBackend, err = ar.cluster.nextBackend(*ar.currentBackend, BackendSequenceRoundRobin); err == nil {
295 ar.setAffinity(selector, *ar.currentBackend)
296 //ar.affinity[selector] = *ar.currentBackend
297 //log.Debugf("New affinity set to backend %s",(*ar.currentBackend).name)
298 return *ar.currentBackend
sslobodr392ebd52019-01-18 12:41:49 -0500299 } else {
300 sl.err = err
301 return nil
302 }
303 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400304 }
305 default:
306 log.Errorf("Internal: invalid data type in Route call %v", sel)
307 return nil
sslobodr392ebd52019-01-18 12:41:49 -0500308 }
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400309 log.Errorf("Bad lookup in affinity map %v", ar.affinity)
sslobodr392ebd52019-01-18 12:41:49 -0500310 return nil
311}
312
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400313func (ar AffinityRouter) GetMetaKeyVal(serverStream grpc.ServerStream) (string, string, error) {
314 return "", "", nil
sslobodr392ebd52019-01-18 12:41:49 -0500315}
316
Kent Hagerman03b58992019-08-29 17:21:03 -0400317func (ar AffinityRouter) IsStreaming(_ string) (bool, bool) {
318 panic("not implemented")
319}
320
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400321func (ar AffinityRouter) BackendCluster(mthd string, metaKey string) (*cluster, error) {
322 return ar.cluster, nil
sslobodr392ebd52019-01-18 12:41:49 -0500323}
324
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400325func (ar AffinityRouter) FindBackendCluster(beName string) *cluster {
326 if beName == ar.cluster.name {
327 return ar.cluster
sslobodr392ebd52019-01-18 12:41:49 -0500328 }
329 return nil
330}
331
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400332func (ar AffinityRouter) ReplyHandler(sel interface{}) error {
sslobodr392ebd52019-01-18 12:41:49 -0500333 switch sl := sel.(type) {
Kent Hagerman03b58992019-08-29 17:21:03 -0400334 case *responseFrame:
335 log.Debugf("Reply handler called for responseFrame with method %s", sl.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400336 // Determine if reply action is required.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400337 if fld, ok := ar.nbBindingMethodMap[sl.method]; ok && len(sl.payload) > 0 {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400338 // Extract the field value from the frame and
339 // and set affinity accordingly
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400340 if selector, err := ar.decodeProtoField(sl.payload, fld); err == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400341 log.Debug("Settign affinity on reply")
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400342 if ar.setAffinity(selector, sl.backend) != nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400343 log.Error("Setting affinity on reply failed")
sslobodr392ebd52019-01-18 12:41:49 -0500344 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400345 return nil
346 } else {
347 err := errors.New(fmt.Sprintf("Failed to decode reply field %d for method %s", fld, sl.method))
348 log.Error(err)
349 return err
sslobodr392ebd52019-01-18 12:41:49 -0500350 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400351 }
352 return nil
353 default:
354 err := errors.New(fmt.Sprintf("Internal: invalid data type in ReplyHander call %v", sl))
355 log.Error(err)
356 return err
sslobodr392ebd52019-01-18 12:41:49 -0500357 }
358}
359
360func (ar AffinityRouter) setAffinity(key string, be *backend) error {
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400361 if be2, ok := ar.affinity[key]; !ok {
sslobodr392ebd52019-01-18 12:41:49 -0500362 ar.affinity[key] = be
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400363 log.Debugf("New affinity set to backend %s for key %s", be.name, key)
sslobodr392ebd52019-01-18 12:41:49 -0500364 } else if be2 != be {
365 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 -0400366 key, be.name, ar.affinity[key].name, ar.name))
sslobodr392ebd52019-01-18 12:41:49 -0500367 log.Error(err)
368 return err
369 }
370 return nil
371}