blob: c266f4ec102c76b48dbfe7fa6d95b32f98babb11 [file] [log] [blame]
Scott Bakereee8dd82019-09-24 12:52:34 -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
19// Package balancer defines APIs for load balancing in gRPC.
20// All APIs in this package are experimental.
21package balancer
22
23import (
24 "context"
Scott Baker611f6bd2019-10-18 13:45:19 -070025 "encoding/json"
Scott Bakereee8dd82019-09-24 12:52:34 -070026 "errors"
27 "net"
28 "strings"
29
30 "google.golang.org/grpc/connectivity"
31 "google.golang.org/grpc/credentials"
32 "google.golang.org/grpc/internal"
33 "google.golang.org/grpc/metadata"
34 "google.golang.org/grpc/resolver"
Scott Baker611f6bd2019-10-18 13:45:19 -070035 "google.golang.org/grpc/serviceconfig"
Scott Bakereee8dd82019-09-24 12:52:34 -070036)
37
38var (
39 // m is a map from name to balancer builder.
40 m = make(map[string]Builder)
41)
42
43// Register registers the balancer builder to the balancer map. b.Name
Scott Baker611f6bd2019-10-18 13:45:19 -070044// (lowercased) will be used as the name registered with this builder. If the
45// Builder implements ConfigParser, ParseConfig will be called when new service
46// configs are received by the resolver, and the result will be provided to the
47// Balancer in UpdateClientConnState.
Scott Bakereee8dd82019-09-24 12:52:34 -070048//
49// NOTE: this function must only be called during initialization time (i.e. in
50// an init() function), and is not thread-safe. If multiple Balancers are
51// registered with the same name, the one registered last will take effect.
52func Register(b Builder) {
53 m[strings.ToLower(b.Name())] = b
54}
55
56// unregisterForTesting deletes the balancer with the given name from the
57// balancer map.
58//
59// This function is not thread-safe.
60func unregisterForTesting(name string) {
61 delete(m, name)
62}
63
64func init() {
65 internal.BalancerUnregister = unregisterForTesting
66}
67
68// Get returns the resolver builder registered with the given name.
69// Note that the compare is done in a case-insensitive fashion.
70// If no builder is register with the name, nil will be returned.
71func Get(name string) Builder {
72 if b, ok := m[strings.ToLower(name)]; ok {
73 return b
74 }
75 return nil
76}
77
78// SubConn represents a gRPC sub connection.
79// Each sub connection contains a list of addresses. gRPC will
80// try to connect to them (in sequence), and stop trying the
81// remainder once one connection is successful.
82//
83// The reconnect backoff will be applied on the list, not a single address.
84// For example, try_on_all_addresses -> backoff -> try_on_all_addresses.
85//
86// All SubConns start in IDLE, and will not try to connect. To trigger
87// the connecting, Balancers must call Connect.
88// When the connection encounters an error, it will reconnect immediately.
89// When the connection becomes IDLE, it will not reconnect unless Connect is
90// called.
91//
92// This interface is to be implemented by gRPC. Users should not need a
93// brand new implementation of this interface. For the situations like
94// testing, the new implementation should embed this interface. This allows
95// gRPC to add new methods to this interface.
96type SubConn interface {
97 // UpdateAddresses updates the addresses used in this SubConn.
98 // gRPC checks if currently-connected address is still in the new list.
99 // If it's in the list, the connection will be kept.
100 // If it's not in the list, the connection will gracefully closed, and
101 // a new connection will be created.
102 //
103 // This will trigger a state transition for the SubConn.
104 UpdateAddresses([]resolver.Address)
105 // Connect starts the connecting for this SubConn.
106 Connect()
107}
108
109// NewSubConnOptions contains options to create new SubConn.
110type NewSubConnOptions struct {
111 // CredsBundle is the credentials bundle that will be used in the created
112 // SubConn. If it's nil, the original creds from grpc DialOptions will be
113 // used.
114 CredsBundle credentials.Bundle
115 // HealthCheckEnabled indicates whether health check service should be
116 // enabled on this SubConn
117 HealthCheckEnabled bool
118}
119
120// ClientConn represents a gRPC ClientConn.
121//
122// This interface is to be implemented by gRPC. Users should not need a
123// brand new implementation of this interface. For the situations like
124// testing, the new implementation should embed this interface. This allows
125// gRPC to add new methods to this interface.
126type ClientConn interface {
127 // NewSubConn is called by balancer to create a new SubConn.
128 // It doesn't block and wait for the connections to be established.
129 // Behaviors of the SubConn can be controlled by options.
130 NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error)
131 // RemoveSubConn removes the SubConn from ClientConn.
132 // The SubConn will be shutdown.
133 RemoveSubConn(SubConn)
134
135 // UpdateBalancerState is called by balancer to notify gRPC that some internal
136 // state in balancer has changed.
137 //
138 // gRPC will update the connectivity state of the ClientConn, and will call pick
139 // on the new picker to pick new SubConn.
140 UpdateBalancerState(s connectivity.State, p Picker)
141
142 // ResolveNow is called by balancer to notify gRPC to do a name resolving.
143 ResolveNow(resolver.ResolveNowOption)
144
145 // Target returns the dial target for this ClientConn.
Scott Baker611f6bd2019-10-18 13:45:19 -0700146 //
147 // Deprecated: Use the Target field in the BuildOptions instead.
Scott Bakereee8dd82019-09-24 12:52:34 -0700148 Target() string
149}
150
151// BuildOptions contains additional information for Build.
152type BuildOptions struct {
153 // DialCreds is the transport credential the Balancer implementation can
154 // use to dial to a remote load balancer server. The Balancer implementations
155 // can ignore this if it does not need to talk to another party securely.
156 DialCreds credentials.TransportCredentials
157 // CredsBundle is the credentials bundle that the Balancer can use.
158 CredsBundle credentials.Bundle
159 // Dialer is the custom dialer the Balancer implementation can use to dial
160 // to a remote load balancer server. The Balancer implementations
161 // can ignore this if it doesn't need to talk to remote balancer.
162 Dialer func(context.Context, string) (net.Conn, error)
163 // ChannelzParentID is the entity parent's channelz unique identification number.
164 ChannelzParentID int64
Scott Baker611f6bd2019-10-18 13:45:19 -0700165 // Target contains the parsed address info of the dial target. It is the same resolver.Target as
166 // passed to the resolver.
167 // See the documentation for the resolver.Target type for details about what it contains.
168 Target resolver.Target
Scott Bakereee8dd82019-09-24 12:52:34 -0700169}
170
171// Builder creates a balancer.
172type Builder interface {
173 // Build creates a new balancer with the ClientConn.
174 Build(cc ClientConn, opts BuildOptions) Balancer
175 // Name returns the name of balancers built by this builder.
176 // It will be used to pick balancers (for example in service config).
177 Name() string
178}
179
Scott Baker611f6bd2019-10-18 13:45:19 -0700180// ConfigParser parses load balancer configs.
181type ConfigParser interface {
182 // ParseConfig parses the JSON load balancer config provided into an
183 // internal form or returns an error if the config is invalid. For future
184 // compatibility reasons, unknown fields in the config should be ignored.
185 ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error)
186}
187
Scott Bakereee8dd82019-09-24 12:52:34 -0700188// PickOptions contains addition information for the Pick operation.
189type PickOptions struct {
190 // FullMethodName is the method name that NewClientStream() is called
191 // with. The canonical format is /service/Method.
192 FullMethodName string
Scott Bakereee8dd82019-09-24 12:52:34 -0700193}
194
195// DoneInfo contains additional information for done.
196type DoneInfo struct {
197 // Err is the rpc error the RPC finished with. It could be nil.
198 Err error
199 // Trailer contains the metadata from the RPC's trailer, if present.
200 Trailer metadata.MD
201 // BytesSent indicates if any bytes have been sent to the server.
202 BytesSent bool
203 // BytesReceived indicates if any byte has been received from the server.
204 BytesReceived bool
Scott Baker611f6bd2019-10-18 13:45:19 -0700205 // ServerLoad is the load received from server. It's usually sent as part of
206 // trailing metadata.
207 //
208 // The only supported type now is *orca_v1.LoadReport.
209 ServerLoad interface{}
Scott Bakereee8dd82019-09-24 12:52:34 -0700210}
211
212var (
213 // ErrNoSubConnAvailable indicates no SubConn is available for pick().
214 // gRPC will block the RPC until a new picker is available via UpdateBalancerState().
215 ErrNoSubConnAvailable = errors.New("no SubConn is available")
216 // ErrTransientFailure indicates all SubConns are in TransientFailure.
217 // WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
218 ErrTransientFailure = errors.New("all SubConns are in TransientFailure")
219)
220
221// Picker is used by gRPC to pick a SubConn to send an RPC.
222// Balancer is expected to generate a new picker from its snapshot every time its
223// internal state has changed.
224//
225// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
226type Picker interface {
227 // Pick returns the SubConn to be used to send the RPC.
228 // The returned SubConn must be one returned by NewSubConn().
229 //
230 // This functions is expected to return:
231 // - a SubConn that is known to be READY;
232 // - ErrNoSubConnAvailable if no SubConn is available, but progress is being
233 // made (for example, some SubConn is in CONNECTING mode);
234 // - other errors if no active connecting is happening (for example, all SubConn
235 // are in TRANSIENT_FAILURE mode).
236 //
237 // If a SubConn is returned:
238 // - If it is READY, gRPC will send the RPC on it;
Scott Baker611f6bd2019-10-18 13:45:19 -0700239 // - If it is not ready, or becomes not ready after it's returned, gRPC will
240 // block until UpdateBalancerState() is called and will call pick on the
241 // new picker. The done function returned from Pick(), if not nil, will be
242 // called with nil error, no bytes sent and no bytes received.
Scott Bakereee8dd82019-09-24 12:52:34 -0700243 //
244 // If the returned error is not nil:
245 // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState()
246 // - If the error is ErrTransientFailure:
247 // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState()
248 // is called to pick again;
249 // - Otherwise, RPC will fail with unavailable error.
250 // - Else (error is other non-nil error):
251 // - The RPC will fail with unavailable error.
252 //
253 // The returned done() function will be called once the rpc has finished,
254 // with the final status of that RPC. If the SubConn returned is not a
255 // valid SubConn type, done may not be called. done may be nil if balancer
256 // doesn't care about the RPC status.
257 Pick(ctx context.Context, opts PickOptions) (conn SubConn, done func(DoneInfo), err error)
258}
259
260// Balancer takes input from gRPC, manages SubConns, and collects and aggregates
261// the connectivity states.
262//
263// It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
264//
265// HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed
266// to be called synchronously from the same goroutine.
267// There's no guarantee on picker.Pick, it may be called anytime.
268type Balancer interface {
269 // HandleSubConnStateChange is called by gRPC when the connectivity state
270 // of sc has changed.
271 // Balancer is expected to aggregate all the state of SubConn and report
272 // that back to gRPC.
273 // Balancer should also generate and update Pickers when its internal state has
274 // been changed by the new state.
Scott Baker611f6bd2019-10-18 13:45:19 -0700275 //
276 // Deprecated: if V2Balancer is implemented by the Balancer,
277 // UpdateSubConnState will be called instead.
Scott Bakereee8dd82019-09-24 12:52:34 -0700278 HandleSubConnStateChange(sc SubConn, state connectivity.State)
279 // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to
280 // balancers.
281 // Balancer can create new SubConn or remove SubConn with the addresses.
282 // An empty address slice and a non-nil error will be passed if the resolver returns
283 // non-nil error to gRPC.
Scott Baker611f6bd2019-10-18 13:45:19 -0700284 //
285 // Deprecated: if V2Balancer is implemented by the Balancer,
286 // UpdateClientConnState will be called instead.
Scott Bakereee8dd82019-09-24 12:52:34 -0700287 HandleResolvedAddrs([]resolver.Address, error)
288 // Close closes the balancer. The balancer is not required to call
289 // ClientConn.RemoveSubConn for its existing SubConns.
290 Close()
291}
292
Scott Baker611f6bd2019-10-18 13:45:19 -0700293// SubConnState describes the state of a SubConn.
294type SubConnState struct {
295 ConnectivityState connectivity.State
296 // TODO: add last connection error
297}
298
299// ClientConnState describes the state of a ClientConn relevant to the
300// balancer.
301type ClientConnState struct {
302 ResolverState resolver.State
303 // The parsed load balancing configuration returned by the builder's
304 // ParseConfig method, if implemented.
305 BalancerConfig serviceconfig.LoadBalancingConfig
306}
307
308// V2Balancer is defined for documentation purposes. If a Balancer also
309// implements V2Balancer, its UpdateClientConnState method will be called
310// instead of HandleResolvedAddrs and its UpdateSubConnState will be called
311// instead of HandleSubConnStateChange.
312type V2Balancer interface {
313 // UpdateClientConnState is called by gRPC when the state of the ClientConn
314 // changes.
315 UpdateClientConnState(ClientConnState)
316 // UpdateSubConnState is called by gRPC when the state of a SubConn
317 // changes.
318 UpdateSubConnState(SubConn, SubConnState)
319 // Close closes the balancer. The balancer is not required to call
320 // ClientConn.RemoveSubConn for its existing SubConns.
321 Close()
322}
323
Scott Bakereee8dd82019-09-24 12:52:34 -0700324// ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
325// and returns one aggregated connectivity state.
326//
327// It's not thread safe.
328type ConnectivityStateEvaluator struct {
329 numReady uint64 // Number of addrConns in ready state.
330 numConnecting uint64 // Number of addrConns in connecting state.
331 numTransientFailure uint64 // Number of addrConns in transientFailure.
332}
333
334// RecordTransition records state change happening in subConn and based on that
335// it evaluates what aggregated state should be.
336//
337// - If at least one SubConn in Ready, the aggregated state is Ready;
338// - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
339// - Else the aggregated state is TransientFailure.
340//
341// Idle and Shutdown are not considered.
342func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
343 // Update counters.
344 for idx, state := range []connectivity.State{oldState, newState} {
345 updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
346 switch state {
347 case connectivity.Ready:
348 cse.numReady += updateVal
349 case connectivity.Connecting:
350 cse.numConnecting += updateVal
351 case connectivity.TransientFailure:
352 cse.numTransientFailure += updateVal
353 }
354 }
355
356 // Evaluate.
357 if cse.numReady > 0 {
358 return connectivity.Ready
359 }
360 if cse.numConnecting > 0 {
361 return connectivity.Connecting
362 }
363 return connectivity.TransientFailure
364}