blob: 178de0898aa4a4a76450e313e5647762ad8c48a4 [file] [log] [blame]
khenaidoo5fc5cea2021-08-11 17:39:16 -04001/*
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// A SubConn represents a single connection to a gRPC backend service.
79//
80// Each SubConn contains a list of addresses.
81//
82// All SubConns start in IDLE, and will not try to connect. To trigger the
83// connecting, Balancers must call Connect. If a connection re-enters IDLE,
84// Balancers must call Connect again to trigger a new connection attempt.
85//
86// gRPC will try to connect to the addresses in sequence, and stop trying the
87// remainder once the first connection is successful. If an attempt to connect
88// to all addresses encounters an error, the SubConn will enter
89// TRANSIENT_FAILURE for a backoff period, and then transition to IDLE.
90//
91// Once established, if a connection is lost, the SubConn will transition
92// directly to IDLE.
93//
94// This interface is to be implemented by gRPC. Users should not need their own
95// implementation of this interface. For situations like testing, any
96// implementations should embed this interface. This allows gRPC to add new
97// methods to this interface.
98type SubConn interface {
99 // UpdateAddresses updates the addresses used in this SubConn.
100 // gRPC checks if currently-connected address is still in the new list.
101 // If it's in the list, the connection will be kept.
102 // If it's not in the list, the connection will gracefully closed, and
103 // a new connection will be created.
104 //
105 // This will trigger a state transition for the SubConn.
106 //
107 // Deprecated: This method is now part of the ClientConn interface and will
108 // eventually be removed from here.
109 UpdateAddresses([]resolver.Address)
110 // Connect starts the connecting for this SubConn.
111 Connect()
112}
113
114// NewSubConnOptions contains options to create new SubConn.
115type NewSubConnOptions struct {
116 // CredsBundle is the credentials bundle that will be used in the created
117 // SubConn. If it's nil, the original creds from grpc DialOptions will be
118 // used.
119 //
120 // Deprecated: Use the Attributes field in resolver.Address to pass
121 // arbitrary data to the credential handshaker.
122 CredsBundle credentials.Bundle
123 // HealthCheckEnabled indicates whether health check service should be
124 // enabled on this SubConn
125 HealthCheckEnabled bool
126}
127
128// State contains the balancer's state relevant to the gRPC ClientConn.
129type State struct {
130 // State contains the connectivity state of the balancer, which is used to
131 // determine the state of the ClientConn.
132 ConnectivityState connectivity.State
133 // Picker is used to choose connections (SubConns) for RPCs.
134 Picker Picker
135}
136
137// ClientConn represents a gRPC ClientConn.
138//
139// This interface is to be implemented by gRPC. Users should not need a
140// brand new implementation of this interface. For the situations like
141// testing, the new implementation should embed this interface. This allows
142// gRPC to add new methods to this interface.
143type ClientConn interface {
144 // NewSubConn is called by balancer to create a new SubConn.
145 // It doesn't block and wait for the connections to be established.
146 // Behaviors of the SubConn can be controlled by options.
147 NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error)
148 // RemoveSubConn removes the SubConn from ClientConn.
149 // The SubConn will be shutdown.
150 RemoveSubConn(SubConn)
151 // UpdateAddresses updates the addresses used in the passed in SubConn.
152 // gRPC checks if the currently connected address is still in the new list.
153 // If so, the connection will be kept. Else, the connection will be
154 // gracefully closed, and a new connection will be created.
155 //
156 // This will trigger a state transition for the SubConn.
157 UpdateAddresses(SubConn, []resolver.Address)
158
159 // UpdateState notifies gRPC that the balancer's internal state has
160 // changed.
161 //
162 // gRPC will update the connectivity state of the ClientConn, and will call
163 // Pick on the new Picker to pick new SubConns.
164 UpdateState(State)
165
166 // ResolveNow is called by balancer to notify gRPC to do a name resolving.
167 ResolveNow(resolver.ResolveNowOptions)
168
169 // Target returns the dial target for this ClientConn.
170 //
171 // Deprecated: Use the Target field in the BuildOptions instead.
172 Target() string
173}
174
175// BuildOptions contains additional information for Build.
176type BuildOptions struct {
177 // DialCreds is the transport credential the Balancer implementation can
178 // use to dial to a remote load balancer server. The Balancer implementations
179 // can ignore this if it does not need to talk to another party securely.
180 DialCreds credentials.TransportCredentials
181 // CredsBundle is the credentials bundle that the Balancer can use.
182 CredsBundle credentials.Bundle
183 // Dialer is the custom dialer the Balancer implementation can use to dial
184 // to a remote load balancer server. The Balancer implementations
185 // can ignore this if it doesn't need to talk to remote balancer.
186 Dialer func(context.Context, string) (net.Conn, error)
187 // ChannelzParentID is the entity parent's channelz unique identification number.
188 ChannelzParentID int64
189 // CustomUserAgent is the custom user agent set on the parent ClientConn.
190 // The balancer should set the same custom user agent if it creates a
191 // ClientConn.
192 CustomUserAgent string
193 // Target contains the parsed address info of the dial target. It is the same resolver.Target as
194 // passed to the resolver.
195 // See the documentation for the resolver.Target type for details about what it contains.
196 Target resolver.Target
197}
198
199// Builder creates a balancer.
200type Builder interface {
201 // Build creates a new balancer with the ClientConn.
202 Build(cc ClientConn, opts BuildOptions) Balancer
203 // Name returns the name of balancers built by this builder.
204 // It will be used to pick balancers (for example in service config).
205 Name() string
206}
207
208// ConfigParser parses load balancer configs.
209type ConfigParser interface {
210 // ParseConfig parses the JSON load balancer config provided into an
211 // internal form or returns an error if the config is invalid. For future
212 // compatibility reasons, unknown fields in the config should be ignored.
213 ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error)
214}
215
216// PickInfo contains additional information for the Pick operation.
217type PickInfo struct {
218 // FullMethodName is the method name that NewClientStream() is called
219 // with. The canonical format is /service/Method.
220 FullMethodName string
221 // Ctx is the RPC's context, and may contain relevant RPC-level information
222 // like the outgoing header metadata.
223 Ctx context.Context
224}
225
226// DoneInfo contains additional information for done.
227type DoneInfo struct {
228 // Err is the rpc error the RPC finished with. It could be nil.
229 Err error
230 // Trailer contains the metadata from the RPC's trailer, if present.
231 Trailer metadata.MD
232 // BytesSent indicates if any bytes have been sent to the server.
233 BytesSent bool
234 // BytesReceived indicates if any byte has been received from the server.
235 BytesReceived bool
236 // ServerLoad is the load received from server. It's usually sent as part of
237 // trailing metadata.
238 //
239 // The only supported type now is *orca_v1.LoadReport.
240 ServerLoad interface{}
241}
242
243var (
244 // ErrNoSubConnAvailable indicates no SubConn is available for pick().
245 // gRPC will block the RPC until a new picker is available via UpdateState().
246 ErrNoSubConnAvailable = errors.New("no SubConn is available")
247 // ErrTransientFailure indicates all SubConns are in TransientFailure.
248 // WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
249 //
250 // Deprecated: return an appropriate error based on the last resolution or
251 // connection attempt instead. The behavior is the same for any non-gRPC
252 // status error.
253 ErrTransientFailure = errors.New("all SubConns are in TransientFailure")
254)
255
256// PickResult contains information related to a connection chosen for an RPC.
257type PickResult struct {
258 // SubConn is the connection to use for this pick, if its state is Ready.
259 // If the state is not Ready, gRPC will block the RPC until a new Picker is
260 // provided by the balancer (using ClientConn.UpdateState). The SubConn
261 // must be one returned by ClientConn.NewSubConn.
262 SubConn SubConn
263
264 // Done is called when the RPC is completed. If the SubConn is not ready,
265 // this will be called with a nil parameter. If the SubConn is not a valid
266 // type, Done may not be called. May be nil if the balancer does not wish
267 // to be notified when the RPC completes.
268 Done func(DoneInfo)
269}
270
271// TransientFailureError returns e. It exists for backward compatibility and
272// will be deleted soon.
273//
274// Deprecated: no longer necessary, picker errors are treated this way by
275// default.
276func TransientFailureError(e error) error { return e }
277
278// Picker is used by gRPC to pick a SubConn to send an RPC.
279// Balancer is expected to generate a new picker from its snapshot every time its
280// internal state has changed.
281//
282// The pickers used by gRPC can be updated by ClientConn.UpdateState().
283type Picker interface {
284 // Pick returns the connection to use for this RPC and related information.
285 //
286 // Pick should not block. If the balancer needs to do I/O or any blocking
287 // or time-consuming work to service this call, it should return
288 // ErrNoSubConnAvailable, and the Pick call will be repeated by gRPC when
289 // the Picker is updated (using ClientConn.UpdateState).
290 //
291 // If an error is returned:
292 //
293 // - If the error is ErrNoSubConnAvailable, gRPC will block until a new
294 // Picker is provided by the balancer (using ClientConn.UpdateState).
295 //
296 // - If the error is a status error (implemented by the grpc/status
297 // package), gRPC will terminate the RPC with the code and message
298 // provided.
299 //
300 // - For all other errors, wait for ready RPCs will wait, but non-wait for
301 // ready RPCs will be terminated with this error's Error() string and
302 // status code Unavailable.
303 Pick(info PickInfo) (PickResult, error)
304}
305
306// Balancer takes input from gRPC, manages SubConns, and collects and aggregates
307// the connectivity states.
308//
309// It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
310//
311// UpdateClientConnState, ResolverError, UpdateSubConnState, and Close are
312// guaranteed to be called synchronously from the same goroutine. There's no
313// guarantee on picker.Pick, it may be called anytime.
314type Balancer interface {
315 // UpdateClientConnState is called by gRPC when the state of the ClientConn
316 // changes. If the error returned is ErrBadResolverState, the ClientConn
317 // will begin calling ResolveNow on the active name resolver with
318 // exponential backoff until a subsequent call to UpdateClientConnState
319 // returns a nil error. Any other errors are currently ignored.
320 UpdateClientConnState(ClientConnState) error
321 // ResolverError is called by gRPC when the name resolver reports an error.
322 ResolverError(error)
323 // UpdateSubConnState is called by gRPC when the state of a SubConn
324 // changes.
325 UpdateSubConnState(SubConn, SubConnState)
326 // Close closes the balancer. The balancer is not required to call
327 // ClientConn.RemoveSubConn for its existing SubConns.
328 Close()
329}
330
331// ExitIdler is an optional interface for balancers to implement. If
332// implemented, ExitIdle will be called when ClientConn.Connect is called, if
333// the ClientConn is idle. If unimplemented, ClientConn.Connect will cause
334// all SubConns to connect.
335//
336// Notice: it will be required for all balancers to implement this in a future
337// release.
338type ExitIdler interface {
339 // ExitIdle instructs the LB policy to reconnect to backends / exit the
340 // IDLE state, if appropriate and possible. Note that SubConns that enter
341 // the IDLE state will not reconnect until SubConn.Connect is called.
342 ExitIdle()
343}
344
345// SubConnState describes the state of a SubConn.
346type SubConnState struct {
347 // ConnectivityState is the connectivity state of the SubConn.
348 ConnectivityState connectivity.State
349 // ConnectionError is set if the ConnectivityState is TransientFailure,
350 // describing the reason the SubConn failed. Otherwise, it is nil.
351 ConnectionError error
352}
353
354// ClientConnState describes the state of a ClientConn relevant to the
355// balancer.
356type ClientConnState struct {
357 ResolverState resolver.State
358 // The parsed load balancing configuration returned by the builder's
359 // ParseConfig method, if implemented.
360 BalancerConfig serviceconfig.LoadBalancingConfig
361}
362
363// ErrBadResolverState may be returned by UpdateClientConnState to indicate a
364// problem with the provided name resolver data.
365var ErrBadResolverState = errors.New("bad resolver state")
366
367// ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
368// and returns one aggregated connectivity state.
369//
370// It's not thread safe.
371type ConnectivityStateEvaluator struct {
372 numReady uint64 // Number of addrConns in ready state.
373 numConnecting uint64 // Number of addrConns in connecting state.
374 numTransientFailure uint64 // Number of addrConns in transient failure state.
375 numIdle uint64 // Number of addrConns in idle state.
376}
377
378// RecordTransition records state change happening in subConn and based on that
379// it evaluates what aggregated state should be.
380//
381// - If at least one SubConn in Ready, the aggregated state is Ready;
382// - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
383// - Else if at least one SubConn is TransientFailure, the aggregated state is Transient Failure;
384// - Else if at least one SubConn is Idle, the aggregated state is Idle;
385// - Else there are no subconns and the aggregated state is Transient Failure
386//
387// Shutdown is not considered.
388func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
389 // Update counters.
390 for idx, state := range []connectivity.State{oldState, newState} {
391 updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
392 switch state {
393 case connectivity.Ready:
394 cse.numReady += updateVal
395 case connectivity.Connecting:
396 cse.numConnecting += updateVal
397 case connectivity.TransientFailure:
398 cse.numTransientFailure += updateVal
399 case connectivity.Idle:
400 cse.numIdle += updateVal
401 }
402 }
403
404 // Evaluate.
405 if cse.numReady > 0 {
406 return connectivity.Ready
407 }
408 if cse.numConnecting > 0 {
409 return connectivity.Connecting
410 }
411 if cse.numTransientFailure > 0 {
412 return connectivity.TransientFailure
413 }
414 if cse.numIdle > 0 {
415 return connectivity.Idle
416 }
417 return connectivity.TransientFailure
418}