blob: 80559b80ace6148584cea27ebca1515b33c4115b [file] [log] [blame]
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -07001/*
2 *
3 * Copyright 2017 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19package base
20
21import (
22 "context"
Arjun E K57a7fcb2020-01-30 06:44:45 +000023 "errors"
amit.ghosh258d14c2020-10-02 15:13:38 +020024 "fmt"
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070025
26 "google.golang.org/grpc/balancer"
27 "google.golang.org/grpc/connectivity"
28 "google.golang.org/grpc/grpclog"
29 "google.golang.org/grpc/resolver"
30)
31
32type baseBuilder struct {
Arjun E K57a7fcb2020-01-30 06:44:45 +000033 name string
34 pickerBuilder PickerBuilder
35 v2PickerBuilder V2PickerBuilder
36 config Config
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070037}
38
39func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer {
Arjun E K57a7fcb2020-01-30 06:44:45 +000040 bal := &baseBalancer{
41 cc: cc,
42 pickerBuilder: bb.pickerBuilder,
43 v2PickerBuilder: bb.v2PickerBuilder,
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070044
45 subConns: make(map[resolver.Address]balancer.SubConn),
46 scStates: make(map[balancer.SubConn]connectivity.State),
47 csEvltr: &balancer.ConnectivityStateEvaluator{},
Arjun E K57a7fcb2020-01-30 06:44:45 +000048 config: bb.config,
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070049 }
Arjun E K57a7fcb2020-01-30 06:44:45 +000050 // Initialize picker to a picker that always returns
51 // ErrNoSubConnAvailable, because when state of a SubConn changes, we
52 // may call UpdateState with this picker.
53 if bb.pickerBuilder != nil {
54 bal.picker = NewErrPicker(balancer.ErrNoSubConnAvailable)
55 } else {
56 bal.v2Picker = NewErrPickerV2(balancer.ErrNoSubConnAvailable)
57 }
58 return bal
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070059}
60
61func (bb *baseBuilder) Name() string {
62 return bb.name
63}
64
Arjun E K57a7fcb2020-01-30 06:44:45 +000065var _ balancer.V2Balancer = (*baseBalancer)(nil) // Assert that we implement V2Balancer
66
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070067type baseBalancer struct {
Arjun E K57a7fcb2020-01-30 06:44:45 +000068 cc balancer.ClientConn
69 pickerBuilder PickerBuilder
70 v2PickerBuilder V2PickerBuilder
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070071
72 csEvltr *balancer.ConnectivityStateEvaluator
73 state connectivity.State
74
75 subConns map[resolver.Address]balancer.SubConn
76 scStates map[balancer.SubConn]connectivity.State
77 picker balancer.Picker
Arjun E K57a7fcb2020-01-30 06:44:45 +000078 v2Picker balancer.V2Picker
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070079 config Config
amit.ghosh258d14c2020-10-02 15:13:38 +020080
81 resolverErr error // the last error reported by the resolver; cleared on successful resolution
82 connErr error // the last connection error; cleared upon leaving TransientFailure
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070083}
84
85func (b *baseBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) {
86 panic("not implemented")
87}
88
Arjun E K57a7fcb2020-01-30 06:44:45 +000089func (b *baseBalancer) ResolverError(err error) {
amit.ghosh258d14c2020-10-02 15:13:38 +020090 b.resolverErr = err
91 if len(b.subConns) == 0 {
92 b.state = connectivity.TransientFailure
93 }
94 if b.state != connectivity.TransientFailure {
95 // The picker will not change since the balancer does not currently
96 // report an error.
97 return
98 }
99 b.regeneratePicker()
100 if b.picker != nil {
101 b.cc.UpdateBalancerState(b.state, b.picker)
102 } else {
103 b.cc.UpdateState(balancer.State{
104 ConnectivityState: b.state,
105 Picker: b.v2Picker,
106 })
Arjun E K57a7fcb2020-01-30 06:44:45 +0000107 }
108}
109
110func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700111 // TODO: handle s.ResolverState.Err (log if not nil) once implemented.
112 // TODO: handle s.ResolverState.ServiceConfig?
Arjun E K57a7fcb2020-01-30 06:44:45 +0000113 if grpclog.V(2) {
114 grpclog.Infoln("base.baseBalancer: got new ClientConn state: ", s)
115 }
amit.ghosh258d14c2020-10-02 15:13:38 +0200116 // Successful resolution; clear resolver error and ensure we return nil.
117 b.resolverErr = nil
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700118 // addrsSet is the set converted from addrs, it's used for quick lookup of an address.
119 addrsSet := make(map[resolver.Address]struct{})
120 for _, a := range s.ResolverState.Addresses {
121 addrsSet[a] = struct{}{}
122 if _, ok := b.subConns[a]; !ok {
123 // a is a new address (not existing in b.subConns).
124 sc, err := b.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{HealthCheckEnabled: b.config.HealthCheck})
125 if err != nil {
126 grpclog.Warningf("base.baseBalancer: failed to create new SubConn: %v", err)
127 continue
128 }
129 b.subConns[a] = sc
130 b.scStates[sc] = connectivity.Idle
131 sc.Connect()
132 }
133 }
134 for a, sc := range b.subConns {
135 // a was removed by resolver.
136 if _, ok := addrsSet[a]; !ok {
137 b.cc.RemoveSubConn(sc)
138 delete(b.subConns, a)
139 // Keep the state of this sc in b.scStates until sc's state becomes Shutdown.
140 // The entry will be deleted in HandleSubConnStateChange.
141 }
142 }
amit.ghosh258d14c2020-10-02 15:13:38 +0200143 // If resolver state contains no addresses, return an error so ClientConn
144 // will trigger re-resolve. Also records this as an resolver error, so when
145 // the overall state turns transient failure, the error message will have
146 // the zero address information.
147 if len(s.ResolverState.Addresses) == 0 {
148 b.ResolverError(errors.New("produced zero addresses"))
149 return balancer.ErrBadResolverState
150 }
Arjun E K57a7fcb2020-01-30 06:44:45 +0000151 return nil
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700152}
153
amit.ghosh258d14c2020-10-02 15:13:38 +0200154// mergeErrors builds an error from the last connection error and the last
155// resolver error. Must only be called if b.state is TransientFailure.
156func (b *baseBalancer) mergeErrors() error {
157 // connErr must always be non-nil unless there are no SubConns, in which
158 // case resolverErr must be non-nil.
159 if b.connErr == nil {
160 return fmt.Errorf("last resolver error: %v", b.resolverErr)
161 }
162 if b.resolverErr == nil {
163 return fmt.Errorf("last connection error: %v", b.connErr)
164 }
165 return fmt.Errorf("last connection error: %v; last resolver error: %v", b.connErr, b.resolverErr)
166}
167
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700168// regeneratePicker takes a snapshot of the balancer, and generates a picker
169// from it. The picker is
amit.ghosh258d14c2020-10-02 15:13:38 +0200170// - errPicker if the balancer is in TransientFailure,
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700171// - built by the pickerBuilder with all READY SubConns otherwise.
amit.ghosh258d14c2020-10-02 15:13:38 +0200172func (b *baseBalancer) regeneratePicker() {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700173 if b.state == connectivity.TransientFailure {
Arjun E K57a7fcb2020-01-30 06:44:45 +0000174 if b.pickerBuilder != nil {
175 b.picker = NewErrPicker(balancer.ErrTransientFailure)
176 } else {
amit.ghosh258d14c2020-10-02 15:13:38 +0200177 b.v2Picker = NewErrPickerV2(balancer.TransientFailureError(b.mergeErrors()))
Arjun E K57a7fcb2020-01-30 06:44:45 +0000178 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700179 return
180 }
Arjun E K57a7fcb2020-01-30 06:44:45 +0000181 if b.pickerBuilder != nil {
182 readySCs := make(map[resolver.Address]balancer.SubConn)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700183
Arjun E K57a7fcb2020-01-30 06:44:45 +0000184 // Filter out all ready SCs from full subConn map.
185 for addr, sc := range b.subConns {
186 if st, ok := b.scStates[sc]; ok && st == connectivity.Ready {
187 readySCs[addr] = sc
188 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700189 }
Arjun E K57a7fcb2020-01-30 06:44:45 +0000190 b.picker = b.pickerBuilder.Build(readySCs)
191 } else {
192 readySCs := make(map[balancer.SubConn]SubConnInfo)
193
194 // Filter out all ready SCs from full subConn map.
195 for addr, sc := range b.subConns {
196 if st, ok := b.scStates[sc]; ok && st == connectivity.Ready {
197 readySCs[sc] = SubConnInfo{Address: addr}
198 }
199 }
200 b.v2Picker = b.v2PickerBuilder.Build(PickerBuildInfo{ReadySCs: readySCs})
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700201 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700202}
203
204func (b *baseBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
205 panic("not implemented")
206}
207
208func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) {
209 s := state.ConnectivityState
Arjun E K57a7fcb2020-01-30 06:44:45 +0000210 if grpclog.V(2) {
211 grpclog.Infof("base.baseBalancer: handle SubConn state change: %p, %v", sc, s)
212 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700213 oldS, ok := b.scStates[sc]
214 if !ok {
Arjun E K57a7fcb2020-01-30 06:44:45 +0000215 if grpclog.V(2) {
216 grpclog.Infof("base.baseBalancer: got state changes for an unknown SubConn: %p, %v", sc, s)
217 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700218 return
219 }
amit.ghosh258d14c2020-10-02 15:13:38 +0200220 if oldS == connectivity.TransientFailure && s == connectivity.Connecting {
221 // Once a subconn enters TRANSIENT_FAILURE, ignore subsequent
222 // CONNECTING transitions to prevent the aggregated state from being
223 // always CONNECTING when many backends exist but are all down.
224 return
225 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700226 b.scStates[sc] = s
227 switch s {
228 case connectivity.Idle:
229 sc.Connect()
230 case connectivity.Shutdown:
231 // When an address was removed by resolver, b called RemoveSubConn but
232 // kept the sc's state in scStates. Remove state for this sc here.
233 delete(b.scStates, sc)
amit.ghosh258d14c2020-10-02 15:13:38 +0200234 case connectivity.TransientFailure:
235 // Save error to be reported via picker.
236 b.connErr = state.ConnectionError
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700237 }
238
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700239 b.state = b.csEvltr.RecordTransition(oldS, s)
240
241 // Regenerate picker when one of the following happens:
amit.ghosh258d14c2020-10-02 15:13:38 +0200242 // - this sc entered or left ready
243 // - the aggregated state of balancer is TransientFailure
244 // (may need to update error message)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700245 if (s == connectivity.Ready) != (oldS == connectivity.Ready) ||
amit.ghosh258d14c2020-10-02 15:13:38 +0200246 b.state == connectivity.TransientFailure {
247 b.regeneratePicker()
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700248 }
249
Arjun E K57a7fcb2020-01-30 06:44:45 +0000250 if b.picker != nil {
251 b.cc.UpdateBalancerState(b.state, b.picker)
252 } else {
253 b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.v2Picker})
254 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700255}
256
257// Close is a nop because base balancer doesn't have internal state to clean up,
258// and it doesn't need to call RemoveSubConn for the SubConns.
259func (b *baseBalancer) Close() {
260}
261
262// NewErrPicker returns a picker that always returns err on Pick().
263func NewErrPicker(err error) balancer.Picker {
264 return &errPicker{err: err}
265}
266
267type errPicker struct {
268 err error // Pick() always returns this err.
269}
270
Arjun E K57a7fcb2020-01-30 06:44:45 +0000271func (p *errPicker) Pick(context.Context, balancer.PickInfo) (balancer.SubConn, func(balancer.DoneInfo), error) {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700272 return nil, nil, p.err
273}
Arjun E K57a7fcb2020-01-30 06:44:45 +0000274
275// NewErrPickerV2 returns a V2Picker that always returns err on Pick().
276func NewErrPickerV2(err error) balancer.V2Picker {
277 return &errPickerV2{err: err}
278}
279
280type errPickerV2 struct {
281 err error // Pick() always returns this err.
282}
283
284func (p *errPickerV2) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
285 return balancer.PickResult{}, p.err
286}