blob: 7a3168ee0f832489aeb89d8561938cab4f4ba3f4 [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
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400205 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400206 for (*data)[*idx] >= 128 {
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400207 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400208 }
209 case 1: // 64 bit
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400210 *idx += 9
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400211 case 2: // Length delimited
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400212 *idx++
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400213 b := proto.NewBuffer((*data)[*idx:])
214 t, _ := b.DecodeVarint()
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400215 *idx += int(t) + 1
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400216 case 3: // Deprecated
217 case 4: // Deprecated
218 case 5: // 32 bit
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400219 *idx += 5
sslobodr392ebd52019-01-18 12:41:49 -0500220 }
221 return nil
222}
223
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400224func (ar AffinityRouter) decodeProtoField(payload []byte, fieldId byte) (string, error) {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400225 idx := 0
sslobodr392ebd52019-01-18 12:41:49 -0500226 b := proto.NewBuffer([]byte{})
sslobodr1d1e50b2019-03-14 09:17:40 -0400227 //b.DebugPrint("The Buffer", payload)
sslobodr392ebd52019-01-18 12:41:49 -0500228 for { // Find the route selector field
229 log.Debugf("Decoding afinity value attributeNumber: %d from %v at index %d", fieldId, payload, idx)
230 log.Debugf("Attempting match with payload: %d, methodTable: %d", payload[idx], fieldId)
231 if payload[idx]>>3 == fieldId {
232 log.Debugf("Method match with payload: %d, methodTable: %d", payload[idx], fieldId)
233 // TODO: Consider supporting other selector types.... Way, way in the future
234 // ok, the future is now, support strings as well... ugh.
235 var selector string
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400236 switch payload[idx] & 3 {
237 case 0: // Integer
238 b.SetBuf(payload[idx+1:])
239 v, e := b.DecodeVarint()
240 if e == nil {
241 log.Debugf("Decoded the ing field: %v", v)
242 selector = strconv.Itoa(int(v))
243 } else {
244 log.Errorf("Failed to decode varint %v", e)
245 return "", e
246 }
247 case 2: // Length delimited AKA string
248 b.SetBuf(payload[idx+1:])
249 v, e := b.DecodeStringBytes()
250 if e == nil {
251 log.Debugf("Decoded the string field: %v", v)
252 selector = v
253 } else {
254 log.Errorf("Failed to decode string %v", e)
255 return "", e
256 }
257 default:
258 err := errors.New(fmt.Sprintf("Only integer and string route selectors are permitted"))
259 log.Error(err)
260 return "", err
sslobodr392ebd52019-01-18 12:41:49 -0500261 }
262 return selector, nil
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400263 } else if err := ar.skipField(&payload, &idx); err != nil {
sslobodr392ebd52019-01-18 12:41:49 -0500264 log.Errorf("Parsing message failed %v", err)
265 return "", err
266 }
267 }
268}
269
Scott Baker112b0d42019-08-22 08:32:26 -0700270func (ar AffinityRouter) Route(sel interface{}) (*backend, *connection) {
sslobodr392ebd52019-01-18 12:41:49 -0500271 switch sl := sel.(type) {
Kent Hagerman03b58992019-08-29 17:21:03 -0400272 case *requestFrame:
273 log.Debugf("Route called for requestFrame with method %s", sl.methodInfo.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400274 // Check if this method should be affinity bound from the
275 // reply rather than the request.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400276 if _, ok := ar.nbBindingMethodMap[sl.methodInfo.method]; ok {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400277 var err error
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400278 log.Debugf("Method '%s' affinity binds on reply", sl.methodInfo.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400279 // Just round robin route the southbound request
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400280 if *ar.currentBackend, err = ar.cluster.nextBackend(*ar.currentBackend, BackendSequenceRoundRobin); err == nil {
Scott Baker112b0d42019-08-22 08:32:26 -0700281 return *ar.currentBackend, nil
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400282 } else {
283 sl.err = err
Scott Baker112b0d42019-08-22 08:32:26 -0700284 return nil, nil
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400285 }
286 }
287 // Not a south affinity binding method, proceed with north affinity binding.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400288 if selector, err := ar.decodeProtoField(sl.payload, ar.methodMap[sl.methodInfo.method]); err == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400289 log.Debugf("Establishing affinity for selector: %s", selector)
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400290 if rtrn, ok := ar.affinity[selector]; ok {
Scott Baker112b0d42019-08-22 08:32:26 -0700291 return rtrn, nil
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400292 } else {
293 // The selector isn't in the map, create a new affinity mapping
294 log.Debugf("MUST CREATE A NEW AFFINITY MAP ENTRY!!")
sslobodr392ebd52019-01-18 12:41:49 -0500295 var err error
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400296 if *ar.currentBackend, err = ar.cluster.nextBackend(*ar.currentBackend, BackendSequenceRoundRobin); err == nil {
297 ar.setAffinity(selector, *ar.currentBackend)
298 //ar.affinity[selector] = *ar.currentBackend
299 //log.Debugf("New affinity set to backend %s",(*ar.currentBackend).name)
Scott Baker112b0d42019-08-22 08:32:26 -0700300 return *ar.currentBackend, nil
sslobodr392ebd52019-01-18 12:41:49 -0500301 } else {
302 sl.err = err
Scott Baker112b0d42019-08-22 08:32:26 -0700303 return nil, nil
sslobodr392ebd52019-01-18 12:41:49 -0500304 }
305 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400306 }
307 default:
308 log.Errorf("Internal: invalid data type in Route call %v", sel)
Scott Baker112b0d42019-08-22 08:32:26 -0700309 return nil, nil
sslobodr392ebd52019-01-18 12:41:49 -0500310 }
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400311 log.Errorf("Bad lookup in affinity map %v", ar.affinity)
Scott Baker112b0d42019-08-22 08:32:26 -0700312 return nil, nil
sslobodr392ebd52019-01-18 12:41:49 -0500313}
314
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400315func (ar AffinityRouter) GetMetaKeyVal(serverStream grpc.ServerStream) (string, string, error) {
316 return "", "", nil
sslobodr392ebd52019-01-18 12:41:49 -0500317}
318
Kent Hagerman03b58992019-08-29 17:21:03 -0400319func (ar AffinityRouter) IsStreaming(_ string) (bool, bool) {
320 panic("not implemented")
321}
322
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400323func (ar AffinityRouter) BackendCluster(mthd string, metaKey string) (*cluster, error) {
324 return ar.cluster, nil
sslobodr392ebd52019-01-18 12:41:49 -0500325}
326
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400327func (ar AffinityRouter) FindBackendCluster(beName string) *cluster {
328 if beName == ar.cluster.name {
329 return ar.cluster
sslobodr392ebd52019-01-18 12:41:49 -0500330 }
331 return nil
332}
333
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400334func (ar AffinityRouter) ReplyHandler(sel interface{}) error {
sslobodr392ebd52019-01-18 12:41:49 -0500335 switch sl := sel.(type) {
Kent Hagerman03b58992019-08-29 17:21:03 -0400336 case *responseFrame:
337 log.Debugf("Reply handler called for responseFrame with method %s", sl.method)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400338 // Determine if reply action is required.
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400339 if fld, ok := ar.nbBindingMethodMap[sl.method]; ok && len(sl.payload) > 0 {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400340 // Extract the field value from the frame and
341 // and set affinity accordingly
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400342 if selector, err := ar.decodeProtoField(sl.payload, fld); err == nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400343 log.Debug("Settign affinity on reply")
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400344 if ar.setAffinity(selector, sl.backend) != nil {
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400345 log.Error("Setting affinity on reply failed")
sslobodr392ebd52019-01-18 12:41:49 -0500346 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400347 return nil
348 } else {
349 err := errors.New(fmt.Sprintf("Failed to decode reply field %d for method %s", fld, sl.method))
350 log.Error(err)
351 return err
sslobodr392ebd52019-01-18 12:41:49 -0500352 }
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400353 }
354 return nil
355 default:
356 err := errors.New(fmt.Sprintf("Internal: invalid data type in ReplyHander call %v", sl))
357 log.Error(err)
358 return err
sslobodr392ebd52019-01-18 12:41:49 -0500359 }
360}
361
362func (ar AffinityRouter) setAffinity(key string, be *backend) error {
Kent Hagerman1e9061e2019-05-21 16:01:21 -0400363 if be2, ok := ar.affinity[key]; !ok {
sslobodr392ebd52019-01-18 12:41:49 -0500364 ar.affinity[key] = be
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400365 log.Debugf("New affinity set to backend %s for key %s", be.name, key)
sslobodr392ebd52019-01-18 12:41:49 -0500366 } else if be2 != be {
367 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 -0400368 key, be.name, ar.affinity[key].name, ar.name))
sslobodr392ebd52019-01-18 12:41:49 -0500369 log.Error(err)
370 return err
371 }
372 return nil
373}