Scott Baker | e7144bc | 2019-10-01 14:16:47 -0700 | [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 | */ |
| 16 | |
| 17 | package afrouter |
| 18 | |
| 19 | import ( |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "google.golang.org/grpc" |
| 23 | ) |
| 24 | |
| 25 | var allRouters = make(map[string]Router) |
| 26 | |
| 27 | // The router interface |
| 28 | type Router interface { |
| 29 | Name() string |
| 30 | |
| 31 | // Route() returns a backend and a connection. The connection is optional and if unspecified, then any |
| 32 | // connection on the backend may be used. |
| 33 | Route(interface{}) (*backend, *connection) |
| 34 | |
| 35 | Service() string |
| 36 | IsStreaming(string) (bool, bool) |
| 37 | BackendCluster(string, string) (*cluster, error) |
| 38 | FindBackendCluster(string) *cluster |
| 39 | ReplyHandler(interface{}) error |
| 40 | GetMetaKeyVal(serverStream grpc.ServerStream) (string, string, error) |
| 41 | } |
| 42 | |
| 43 | func newRouter(config *RouterConfig) (Router, error) { |
| 44 | r, err := newMethodRouter(config) |
| 45 | if err == nil { |
| 46 | allRouters[r.Name()] = r |
| 47 | } |
| 48 | return r, err |
| 49 | } |
| 50 | |
| 51 | func newSubRouter(rconf *RouterConfig, config *RouteConfig) (Router, error) { |
| 52 | switch config.Type { |
| 53 | case RouteTypeRpcAffinityMessage: |
| 54 | r, err := newAffinityRouter(rconf, config) |
| 55 | if err == nil { |
| 56 | allRouters[rconf.Name+config.Name] = r |
| 57 | } |
| 58 | return r, err |
| 59 | case RouteTypeBinding: |
| 60 | r, err := newBindingRouter(rconf, config) |
| 61 | if err == nil { |
| 62 | allRouters[rconf.Name+config.Name] = r |
| 63 | } |
| 64 | return r, err |
| 65 | case RouteTypeRoundRobin: |
| 66 | r, err := newRoundRobinRouter(rconf, config) |
| 67 | if err == nil { |
| 68 | allRouters[rconf.Name+config.Name] = r |
| 69 | } |
| 70 | return r, err |
| 71 | case RouteTypeSource: |
| 72 | r, err := newSourceRouter(rconf, config) |
| 73 | if err == nil { |
| 74 | allRouters[rconf.Name+config.Name] = r |
| 75 | } |
| 76 | return r, err |
| 77 | default: |
| 78 | return nil, errors.New(fmt.Sprintf("Internal error, undefined router type: %s", config.Type)) |
| 79 | } |
| 80 | } |