blob: ee1703f034ecc1e02a9635e31e0232258b7531a4 [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001/*
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 "errors"
25 "net"
26 "strings"
27
28 "golang.org/x/net/context"
29 "google.golang.org/grpc/connectivity"
30 "google.golang.org/grpc/credentials"
31 "google.golang.org/grpc/metadata"
32 "google.golang.org/grpc/resolver"
33)
34
35var (
36 // m is a map from name to balancer builder.
37 m = make(map[string]Builder)
38)
39
40// Register registers the balancer builder to the balancer map. b.Name
41// (lowercased) will be used as the name registered with this builder.
42//
43// NOTE: this function must only be called during initialization time (i.e. in
44// an init() function), and is not thread-safe. If multiple Balancers are
45// registered with the same name, the one registered last will take effect.
46func Register(b Builder) {
47 m[strings.ToLower(b.Name())] = b
48}
49
50// Get returns the resolver builder registered with the given name.
51// Note that the compare is done in a case-insenstive fashion.
52// If no builder is register with the name, nil will be returned.
53func Get(name string) Builder {
54 if b, ok := m[strings.ToLower(name)]; ok {
55 return b
56 }
57 return nil
58}
59
60// SubConn represents a gRPC sub connection.
61// Each sub connection contains a list of addresses. gRPC will
62// try to connect to them (in sequence), and stop trying the
63// remainder once one connection is successful.
64//
65// The reconnect backoff will be applied on the list, not a single address.
66// For example, try_on_all_addresses -> backoff -> try_on_all_addresses.
67//
68// All SubConns start in IDLE, and will not try to connect. To trigger
69// the connecting, Balancers must call Connect.
70// When the connection encounters an error, it will reconnect immediately.
71// When the connection becomes IDLE, it will not reconnect unless Connect is
72// called.
73//
74// This interface is to be implemented by gRPC. Users should not need a
75// brand new implementation of this interface. For the situations like
76// testing, the new implementation should embed this interface. This allows
77// gRPC to add new methods to this interface.
78type SubConn interface {
79 // UpdateAddresses updates the addresses used in this SubConn.
80 // gRPC checks if currently-connected address is still in the new list.
81 // If it's in the list, the connection will be kept.
82 // If it's not in the list, the connection will gracefully closed, and
83 // a new connection will be created.
84 //
85 // This will trigger a state transition for the SubConn.
86 UpdateAddresses([]resolver.Address)
87 // Connect starts the connecting for this SubConn.
88 Connect()
89}
90
91// NewSubConnOptions contains options to create new SubConn.
92type NewSubConnOptions struct {
93 // CredsBundle is the credentials bundle that will be used in the created
94 // SubConn. If it's nil, the original creds from grpc DialOptions will be
95 // used.
96 CredsBundle credentials.Bundle
97}
98
99// ClientConn represents a gRPC ClientConn.
100//
101// This interface is to be implemented by gRPC. Users should not need a
102// brand new implementation of this interface. For the situations like
103// testing, the new implementation should embed this interface. This allows
104// gRPC to add new methods to this interface.
105type ClientConn interface {
106 // NewSubConn is called by balancer to create a new SubConn.
107 // It doesn't block and wait for the connections to be established.
108 // Behaviors of the SubConn can be controlled by options.
109 NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error)
110 // RemoveSubConn removes the SubConn from ClientConn.
111 // The SubConn will be shutdown.
112 RemoveSubConn(SubConn)
113
114 // UpdateBalancerState is called by balancer to nofity gRPC that some internal
115 // state in balancer has changed.
116 //
117 // gRPC will update the connectivity state of the ClientConn, and will call pick
118 // on the new picker to pick new SubConn.
119 UpdateBalancerState(s connectivity.State, p Picker)
120
121 // ResolveNow is called by balancer to notify gRPC to do a name resolving.
122 ResolveNow(resolver.ResolveNowOption)
123
124 // Target returns the dial target for this ClientConn.
125 Target() string
126}
127
128// BuildOptions contains additional information for Build.
129type BuildOptions struct {
130 // DialCreds is the transport credential the Balancer implementation can
131 // use to dial to a remote load balancer server. The Balancer implementations
132 // can ignore this if it does not need to talk to another party securely.
133 DialCreds credentials.TransportCredentials
134 // CredsBundle is the credentials bundle that the Balancer can use.
135 CredsBundle credentials.Bundle
136 // Dialer is the custom dialer the Balancer implementation can use to dial
137 // to a remote load balancer server. The Balancer implementations
138 // can ignore this if it doesn't need to talk to remote balancer.
139 Dialer func(context.Context, string) (net.Conn, error)
140 // ChannelzParentID is the entity parent's channelz unique identification number.
141 ChannelzParentID int64
142}
143
144// Builder creates a balancer.
145type Builder interface {
146 // Build creates a new balancer with the ClientConn.
147 Build(cc ClientConn, opts BuildOptions) Balancer
148 // Name returns the name of balancers built by this builder.
149 // It will be used to pick balancers (for example in service config).
150 Name() string
151}
152
153// PickOptions contains addition information for the Pick operation.
154type PickOptions struct {
155 // FullMethodName is the method name that NewClientStream() is called
156 // with. The canonical format is /service/Method.
157 FullMethodName string
158 // Header contains the metadata from the RPC's client header. The metadata
159 // should not be modified; make a copy first if needed.
160 Header metadata.MD
161}
162
163// DoneInfo contains additional information for done.
164type DoneInfo struct {
165 // Err is the rpc error the RPC finished with. It could be nil.
166 Err error
167 // Trailer contains the metadata from the RPC's trailer, if present.
168 Trailer metadata.MD
169 // BytesSent indicates if any bytes have been sent to the server.
170 BytesSent bool
171 // BytesReceived indicates if any byte has been received from the server.
172 BytesReceived bool
173}
174
175var (
176 // ErrNoSubConnAvailable indicates no SubConn is available for pick().
177 // gRPC will block the RPC until a new picker is available via UpdateBalancerState().
178 ErrNoSubConnAvailable = errors.New("no SubConn is available")
179 // ErrTransientFailure indicates all SubConns are in TransientFailure.
180 // WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
181 ErrTransientFailure = errors.New("all SubConns are in TransientFailure")
182)
183
184// Picker is used by gRPC to pick a SubConn to send an RPC.
185// Balancer is expected to generate a new picker from its snapshot every time its
186// internal state has changed.
187//
188// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
189type Picker interface {
190 // Pick returns the SubConn to be used to send the RPC.
191 // The returned SubConn must be one returned by NewSubConn().
192 //
193 // This functions is expected to return:
194 // - a SubConn that is known to be READY;
195 // - ErrNoSubConnAvailable if no SubConn is available, but progress is being
196 // made (for example, some SubConn is in CONNECTING mode);
197 // - other errors if no active connecting is happening (for example, all SubConn
198 // are in TRANSIENT_FAILURE mode).
199 //
200 // If a SubConn is returned:
201 // - If it is READY, gRPC will send the RPC on it;
202 // - If it is not ready, or becomes not ready after it's returned, gRPC will block
203 // until UpdateBalancerState() is called and will call pick on the new picker.
204 //
205 // If the returned error is not nil:
206 // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState()
207 // - If the error is ErrTransientFailure:
208 // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState()
209 // is called to pick again;
210 // - Otherwise, RPC will fail with unavailable error.
211 // - Else (error is other non-nil error):
212 // - The RPC will fail with unavailable error.
213 //
214 // The returned done() function will be called once the rpc has finished, with the
215 // final status of that RPC.
216 // done may be nil if balancer doesn't care about the RPC status.
217 Pick(ctx context.Context, opts PickOptions) (conn SubConn, done func(DoneInfo), err error)
218}
219
220// Balancer takes input from gRPC, manages SubConns, and collects and aggregates
221// the connectivity states.
222//
223// It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
224//
225// HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed
226// to be called synchronously from the same goroutine.
227// There's no guarantee on picker.Pick, it may be called anytime.
228type Balancer interface {
229 // HandleSubConnStateChange is called by gRPC when the connectivity state
230 // of sc has changed.
231 // Balancer is expected to aggregate all the state of SubConn and report
232 // that back to gRPC.
233 // Balancer should also generate and update Pickers when its internal state has
234 // been changed by the new state.
235 HandleSubConnStateChange(sc SubConn, state connectivity.State)
236 // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to
237 // balancers.
238 // Balancer can create new SubConn or remove SubConn with the addresses.
239 // An empty address slice and a non-nil error will be passed if the resolver returns
240 // non-nil error to gRPC.
241 HandleResolvedAddrs([]resolver.Address, error)
242 // Close closes the balancer. The balancer is not required to call
243 // ClientConn.RemoveSubConn for its existing SubConns.
244 Close()
245}
246
247// ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
248// and returns one aggregated connectivity state.
249//
250// It's not thread safe.
251type ConnectivityStateEvaluator struct {
252 numReady uint64 // Number of addrConns in ready state.
253 numConnecting uint64 // Number of addrConns in connecting state.
254 numTransientFailure uint64 // Number of addrConns in transientFailure.
255}
256
257// RecordTransition records state change happening in subConn and based on that
258// it evaluates what aggregated state should be.
259//
260// - If at least one SubConn in Ready, the aggregated state is Ready;
261// - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
262// - Else the aggregated state is TransientFailure.
263//
264// Idle and Shutdown are not considered.
265func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
266 // Update counters.
267 for idx, state := range []connectivity.State{oldState, newState} {
268 updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
269 switch state {
270 case connectivity.Ready:
271 cse.numReady += updateVal
272 case connectivity.Connecting:
273 cse.numConnecting += updateVal
274 case connectivity.TransientFailure:
275 cse.numTransientFailure += updateVal
276 }
277 }
278
279 // Evaluate.
280 if cse.numReady > 0 {
281 return connectivity.Ready
282 }
283 if cse.numConnecting > 0 {
284 return connectivity.Connecting
285 }
286 return connectivity.TransientFailure
287}