blob: 531a174a839926bf056acda1c50099de3237868e [file] [log] [blame]
onkarkundargi72cfd362020-02-27 12:34:37 +05301/*
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"
25 "encoding/json"
26 "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"
35 "google.golang.org/grpc/serviceconfig"
36)
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
44// (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.
48//
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// State contains the balancer's state relevant to the gRPC ClientConn.
121type State struct {
122 // State contains the connectivity state of the balancer, which is used to
123 // determine the state of the ClientConn.
124 ConnectivityState connectivity.State
125 // Picker is used to choose connections (SubConns) for RPCs.
126 Picker V2Picker
127}
128
129// ClientConn represents a gRPC ClientConn.
130//
131// This interface is to be implemented by gRPC. Users should not need a
132// brand new implementation of this interface. For the situations like
133// testing, the new implementation should embed this interface. This allows
134// gRPC to add new methods to this interface.
135type ClientConn interface {
136 // NewSubConn is called by balancer to create a new SubConn.
137 // It doesn't block and wait for the connections to be established.
138 // Behaviors of the SubConn can be controlled by options.
139 NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error)
140 // RemoveSubConn removes the SubConn from ClientConn.
141 // The SubConn will be shutdown.
142 RemoveSubConn(SubConn)
143
144 // UpdateBalancerState is called by balancer to notify gRPC that some internal
145 // state in balancer has changed.
146 //
147 // gRPC will update the connectivity state of the ClientConn, and will call pick
148 // on the new picker to pick new SubConn.
149 //
150 // Deprecated: use UpdateState instead
151 UpdateBalancerState(s connectivity.State, p Picker)
152
153 // UpdateState notifies gRPC that the balancer's internal state has
154 // changed.
155 //
156 // gRPC will update the connectivity state of the ClientConn, and will call pick
157 // on the new picker to pick new SubConns.
158 UpdateState(State)
159
160 // ResolveNow is called by balancer to notify gRPC to do a name resolving.
161 ResolveNow(resolver.ResolveNowOptions)
162
163 // Target returns the dial target for this ClientConn.
164 //
165 // Deprecated: Use the Target field in the BuildOptions instead.
166 Target() string
167}
168
169// BuildOptions contains additional information for Build.
170type BuildOptions struct {
171 // DialCreds is the transport credential the Balancer implementation can
172 // use to dial to a remote load balancer server. The Balancer implementations
173 // can ignore this if it does not need to talk to another party securely.
174 DialCreds credentials.TransportCredentials
175 // CredsBundle is the credentials bundle that the Balancer can use.
176 CredsBundle credentials.Bundle
177 // Dialer is the custom dialer the Balancer implementation can use to dial
178 // to a remote load balancer server. The Balancer implementations
179 // can ignore this if it doesn't need to talk to remote balancer.
180 Dialer func(context.Context, string) (net.Conn, error)
181 // ChannelzParentID is the entity parent's channelz unique identification number.
182 ChannelzParentID int64
183 // Target contains the parsed address info of the dial target. It is the same resolver.Target as
184 // passed to the resolver.
185 // See the documentation for the resolver.Target type for details about what it contains.
186 Target resolver.Target
187}
188
189// Builder creates a balancer.
190type Builder interface {
191 // Build creates a new balancer with the ClientConn.
192 Build(cc ClientConn, opts BuildOptions) Balancer
193 // Name returns the name of balancers built by this builder.
194 // It will be used to pick balancers (for example in service config).
195 Name() string
196}
197
198// ConfigParser parses load balancer configs.
199type ConfigParser interface {
200 // ParseConfig parses the JSON load balancer config provided into an
201 // internal form or returns an error if the config is invalid. For future
202 // compatibility reasons, unknown fields in the config should be ignored.
203 ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error)
204}
205
206// PickOptions is a type alias of PickInfo for legacy reasons.
207//
208// Deprecated: use PickInfo instead.
209type PickOptions = PickInfo
210
211// PickInfo contains additional information for the Pick operation.
212type PickInfo struct {
213 // FullMethodName is the method name that NewClientStream() is called
214 // with. The canonical format is /service/Method.
215 FullMethodName string
216 // Ctx is the RPC's context, and may contain relevant RPC-level information
217 // like the outgoing header metadata.
218 Ctx context.Context
219}
220
221// DoneInfo contains additional information for done.
222type DoneInfo struct {
223 // Err is the rpc error the RPC finished with. It could be nil.
224 Err error
225 // Trailer contains the metadata from the RPC's trailer, if present.
226 Trailer metadata.MD
227 // BytesSent indicates if any bytes have been sent to the server.
228 BytesSent bool
229 // BytesReceived indicates if any byte has been received from the server.
230 BytesReceived bool
231 // ServerLoad is the load received from server. It's usually sent as part of
232 // trailing metadata.
233 //
234 // The only supported type now is *orca_v1.LoadReport.
235 ServerLoad interface{}
236}
237
238var (
239 // ErrNoSubConnAvailable indicates no SubConn is available for pick().
240 // gRPC will block the RPC until a new picker is available via UpdateBalancerState().
241 ErrNoSubConnAvailable = errors.New("no SubConn is available")
242 // ErrTransientFailure indicates all SubConns are in TransientFailure.
243 // WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
244 ErrTransientFailure = TransientFailureError(errors.New("all SubConns are in TransientFailure"))
245)
246
247// Picker is used by gRPC to pick a SubConn to send an RPC.
248// Balancer is expected to generate a new picker from its snapshot every time its
249// internal state has changed.
250//
251// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
252//
253// Deprecated: use V2Picker instead
254type Picker interface {
255 // Pick returns the SubConn to be used to send the RPC.
256 // The returned SubConn must be one returned by NewSubConn().
257 //
258 // This functions is expected to return:
259 // - a SubConn that is known to be READY;
260 // - ErrNoSubConnAvailable if no SubConn is available, but progress is being
261 // made (for example, some SubConn is in CONNECTING mode);
262 // - other errors if no active connecting is happening (for example, all SubConn
263 // are in TRANSIENT_FAILURE mode).
264 //
265 // If a SubConn is returned:
266 // - If it is READY, gRPC will send the RPC on it;
267 // - If it is not ready, or becomes not ready after it's returned, gRPC will
268 // block until UpdateBalancerState() is called and will call pick on the
269 // new picker. The done function returned from Pick(), if not nil, will be
270 // called with nil error, no bytes sent and no bytes received.
271 //
272 // If the returned error is not nil:
273 // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState()
274 // - If the error is ErrTransientFailure or implements IsTransientFailure()
275 // bool, returning true:
276 // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState()
277 // is called to pick again;
278 // - Otherwise, RPC will fail with unavailable error.
279 // - Else (error is other non-nil error):
280 // - The RPC will fail with the error's status code, or Unknown if it is
281 // not a status error.
282 //
283 // The returned done() function will be called once the rpc has finished,
284 // with the final status of that RPC. If the SubConn returned is not a
285 // valid SubConn type, done may not be called. done may be nil if balancer
286 // doesn't care about the RPC status.
287 Pick(ctx context.Context, info PickInfo) (conn SubConn, done func(DoneInfo), err error)
288}
289
290// PickResult contains information related to a connection chosen for an RPC.
291type PickResult struct {
292 // SubConn is the connection to use for this pick, if its state is Ready.
293 // If the state is not Ready, gRPC will block the RPC until a new Picker is
294 // provided by the balancer (using ClientConn.UpdateState). The SubConn
295 // must be one returned by ClientConn.NewSubConn.
296 SubConn SubConn
297
298 // Done is called when the RPC is completed. If the SubConn is not ready,
299 // this will be called with a nil parameter. If the SubConn is not a valid
300 // type, Done may not be called. May be nil if the balancer does not wish
301 // to be notified when the RPC completes.
302 Done func(DoneInfo)
303}
304
305type transientFailureError struct {
306 error
307}
308
309func (e *transientFailureError) IsTransientFailure() bool { return true }
310
311// TransientFailureError wraps err in an error implementing
312// IsTransientFailure() bool, returning true.
313func TransientFailureError(err error) error {
314 return &transientFailureError{error: err}
315}
316
317// V2Picker is used by gRPC to pick a SubConn to send an RPC.
318// Balancer is expected to generate a new picker from its snapshot every time its
319// internal state has changed.
320//
321// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
322type V2Picker interface {
323 // Pick returns the connection to use for this RPC and related information.
324 //
325 // Pick should not block. If the balancer needs to do I/O or any blocking
326 // or time-consuming work to service this call, it should return
327 // ErrNoSubConnAvailable, and the Pick call will be repeated by gRPC when
328 // the Picker is updated (using ClientConn.UpdateState).
329 //
330 // If an error is returned:
331 //
332 // - If the error is ErrNoSubConnAvailable, gRPC will block until a new
333 // Picker is provided by the balancer (using ClientConn.UpdateState).
334 //
335 // - If the error implements IsTransientFailure() bool, returning true,
336 // wait for ready RPCs will wait, but non-wait for ready RPCs will be
337 // terminated with this error's Error() string and status code
338 // Unavailable.
339 //
340 // - Any other errors terminate all RPCs with the code and message
341 // provided. If the error is not a status error, it will be converted by
342 // gRPC to a status error with code Unknown.
343 Pick(info PickInfo) (PickResult, error)
344}
345
346// Balancer takes input from gRPC, manages SubConns, and collects and aggregates
347// the connectivity states.
348//
349// It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
350//
351// HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed
352// to be called synchronously from the same goroutine.
353// There's no guarantee on picker.Pick, it may be called anytime.
354type Balancer interface {
355 // HandleSubConnStateChange is called by gRPC when the connectivity state
356 // of sc has changed.
357 // Balancer is expected to aggregate all the state of SubConn and report
358 // that back to gRPC.
359 // Balancer should also generate and update Pickers when its internal state has
360 // been changed by the new state.
361 //
362 // Deprecated: if V2Balancer is implemented by the Balancer,
363 // UpdateSubConnState will be called instead.
364 HandleSubConnStateChange(sc SubConn, state connectivity.State)
365 // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to
366 // balancers.
367 // Balancer can create new SubConn or remove SubConn with the addresses.
368 // An empty address slice and a non-nil error will be passed if the resolver returns
369 // non-nil error to gRPC.
370 //
371 // Deprecated: if V2Balancer is implemented by the Balancer,
372 // UpdateClientConnState will be called instead.
373 HandleResolvedAddrs([]resolver.Address, error)
374 // Close closes the balancer. The balancer is not required to call
375 // ClientConn.RemoveSubConn for its existing SubConns.
376 Close()
377}
378
379// SubConnState describes the state of a SubConn.
380type SubConnState struct {
381 // ConnectivityState is the connectivity state of the SubConn.
382 ConnectivityState connectivity.State
383 // ConnectionError is set if the ConnectivityState is TransientFailure,
384 // describing the reason the SubConn failed. Otherwise, it is nil.
385 ConnectionError error
386}
387
388// ClientConnState describes the state of a ClientConn relevant to the
389// balancer.
390type ClientConnState struct {
391 ResolverState resolver.State
392 // The parsed load balancing configuration returned by the builder's
393 // ParseConfig method, if implemented.
394 BalancerConfig serviceconfig.LoadBalancingConfig
395}
396
397// ErrBadResolverState may be returned by UpdateClientConnState to indicate a
398// problem with the provided name resolver data.
399var ErrBadResolverState = errors.New("bad resolver state")
400
401// V2Balancer is defined for documentation purposes. If a Balancer also
402// implements V2Balancer, its UpdateClientConnState method will be called
403// instead of HandleResolvedAddrs and its UpdateSubConnState will be called
404// instead of HandleSubConnStateChange.
405type V2Balancer interface {
406 // UpdateClientConnState is called by gRPC when the state of the ClientConn
407 // changes. If the error returned is ErrBadResolverState, the ClientConn
408 // will begin calling ResolveNow on the active name resolver with
409 // exponential backoff until a subsequent call to UpdateClientConnState
410 // returns a nil error. Any other errors are currently ignored.
411 UpdateClientConnState(ClientConnState) error
412 // ResolverError is called by gRPC when the name resolver reports an error.
413 ResolverError(error)
414 // UpdateSubConnState is called by gRPC when the state of a SubConn
415 // changes.
416 UpdateSubConnState(SubConn, SubConnState)
417 // Close closes the balancer. The balancer is not required to call
418 // ClientConn.RemoveSubConn for its existing SubConns.
419 Close()
420}
421
422// ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
423// and returns one aggregated connectivity state.
424//
425// It's not thread safe.
426type ConnectivityStateEvaluator struct {
427 numReady uint64 // Number of addrConns in ready state.
428 numConnecting uint64 // Number of addrConns in connecting state.
429}
430
431// RecordTransition records state change happening in subConn and based on that
432// it evaluates what aggregated state should be.
433//
434// - If at least one SubConn in Ready, the aggregated state is Ready;
435// - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
436// - Else the aggregated state is TransientFailure.
437//
438// Idle and Shutdown are not considered.
439func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
440 // Update counters.
441 for idx, state := range []connectivity.State{oldState, newState} {
442 updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
443 switch state {
444 case connectivity.Ready:
445 cse.numReady += updateVal
446 case connectivity.Connecting:
447 cse.numConnecting += updateVal
448 }
449 }
450
451 // Evaluate.
452 if cse.numReady > 0 {
453 return connectivity.Ready
454 }
455 if cse.numConnecting > 0 {
456 return connectivity.Connecting
457 }
458 return connectivity.TransientFailure
459}