blob: bd1a5d25e8b86652446072b038183df82aef36ec [file] [log] [blame]
divyadesai81bb7ba2020-03-11 11:45:23 +00001// Copyright 2018 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package picker
16
17import (
18 "fmt"
19
20 "go.uber.org/zap"
21 "google.golang.org/grpc/balancer"
22 "google.golang.org/grpc/resolver"
23)
24
25// Picker defines balancer Picker methods.
26type Picker interface {
27 balancer.Picker
28 String() string
29}
30
31// Config defines picker configuration.
32type Config struct {
33 // Policy specifies etcd clientv3's built in balancer policy.
34 Policy Policy
35
36 // Logger defines picker logging object.
37 Logger *zap.Logger
38
39 // SubConnToResolverAddress maps each gRPC sub-connection to an address.
40 // Basically, it is a list of addresses that the Picker can pick from.
41 SubConnToResolverAddress map[balancer.SubConn]resolver.Address
42}
43
44// Policy defines balancer picker policy.
45type Policy uint8
46
47const (
48 // Error is error picker policy.
49 Error Policy = iota
50
51 // RoundrobinBalanced balances loads over multiple endpoints
52 // and implements failover in roundrobin fashion.
53 RoundrobinBalanced
54
55 // Custom defines custom balancer picker.
56 // TODO: custom picker is not supported yet.
57 Custom
58)
59
60func (p Policy) String() string {
61 switch p {
62 case Error:
63 return "picker-error"
64
65 case RoundrobinBalanced:
66 return "picker-roundrobin-balanced"
67
68 case Custom:
69 panic("'custom' picker policy is not supported yet")
70
71 default:
72 panic(fmt.Errorf("invalid balancer picker policy (%d)", p))
73 }
74}
75
76// New creates a new Picker.
77func New(cfg Config) Picker {
78 switch cfg.Policy {
79 case Error:
80 panic("'error' picker policy is not supported here; use 'picker.NewErr'")
81
82 case RoundrobinBalanced:
83 return newRoundrobinBalanced(cfg)
84
85 case Custom:
86 panic("'custom' picker policy is not supported yet")
87
88 default:
89 panic(fmt.Errorf("invalid balancer picker policy (%d)", cfg.Policy))
90 }
91}