Takahiro Suzuki | 241c10e | 2020-12-17 20:17:57 +0900 | [diff] [blame] | 1 | /* |
| 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. |
| 21 | package balancer |
| 22 | |
| 23 | import ( |
| 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 | |
| 38 | var ( |
| 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. |
| 52 | func 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. |
| 60 | func unregisterForTesting(name string) { |
| 61 | delete(m, name) |
| 62 | } |
| 63 | |
| 64 | func 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. |
| 71 | func 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. |
| 96 | type 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. |
| 110 | type 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. |
| 126 | type 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. |
| 146 | // |
| 147 | // Deprecated: Use the Target field in the BuildOptions instead. |
| 148 | Target() string |
| 149 | } |
| 150 | |
| 151 | // BuildOptions contains additional information for Build. |
| 152 | type 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 |
| 165 | // 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 |
| 169 | } |
| 170 | |
| 171 | // Builder creates a balancer. |
| 172 | type 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 | |
| 180 | // ConfigParser parses load balancer configs. |
| 181 | type 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 | |
| 188 | // PickOptions contains addition information for the Pick operation. |
| 189 | type PickOptions struct { |
| 190 | // FullMethodName is the method name that NewClientStream() is called |
| 191 | // with. The canonical format is /service/Method. |
| 192 | FullMethodName string |
| 193 | } |
| 194 | |
| 195 | // DoneInfo contains additional information for done. |
| 196 | type 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 |
| 205 | // 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{} |
| 210 | } |
| 211 | |
| 212 | var ( |
| 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(). |
| 226 | type 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; |
| 239 | // - 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. |
| 243 | // |
| 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. |
| 268 | type 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. |
| 275 | // |
| 276 | // Deprecated: if V2Balancer is implemented by the Balancer, |
| 277 | // UpdateSubConnState will be called instead. |
| 278 | 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. |
| 284 | // |
| 285 | // Deprecated: if V2Balancer is implemented by the Balancer, |
| 286 | // UpdateClientConnState will be called instead. |
| 287 | 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 | |
| 293 | // SubConnState describes the state of a SubConn. |
| 294 | type 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. |
| 301 | type 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 | // ErrBadResolverState may be returned by UpdateClientConnState to indicate a |
| 309 | // problem with the provided name resolver data. |
| 310 | var ErrBadResolverState = errors.New("bad resolver state") |
| 311 | |
| 312 | // V2Balancer is defined for documentation purposes. If a Balancer also |
| 313 | // implements V2Balancer, its UpdateClientConnState method will be called |
| 314 | // instead of HandleResolvedAddrs and its UpdateSubConnState will be called |
| 315 | // instead of HandleSubConnStateChange. |
| 316 | type V2Balancer interface { |
| 317 | // UpdateClientConnState is called by gRPC when the state of the ClientConn |
| 318 | // changes. If the error returned is ErrBadResolverState, the ClientConn |
| 319 | // will begin calling ResolveNow on the active name resolver with |
| 320 | // exponential backoff until a subsequent call to UpdateClientConnState |
| 321 | // returns a nil error. Any other errors are currently ignored. |
| 322 | UpdateClientConnState(ClientConnState) error |
| 323 | // ResolverError is called by gRPC when the name resolver reports an error. |
| 324 | ResolverError(error) |
| 325 | // UpdateSubConnState is called by gRPC when the state of a SubConn |
| 326 | // changes. |
| 327 | UpdateSubConnState(SubConn, SubConnState) |
| 328 | // Close closes the balancer. The balancer is not required to call |
| 329 | // ClientConn.RemoveSubConn for its existing SubConns. |
| 330 | Close() |
| 331 | } |
| 332 | |
| 333 | // ConnectivityStateEvaluator takes the connectivity states of multiple SubConns |
| 334 | // and returns one aggregated connectivity state. |
| 335 | // |
| 336 | // It's not thread safe. |
| 337 | type ConnectivityStateEvaluator struct { |
| 338 | numReady uint64 // Number of addrConns in ready state. |
| 339 | numConnecting uint64 // Number of addrConns in connecting state. |
| 340 | numTransientFailure uint64 // Number of addrConns in transientFailure. |
| 341 | } |
| 342 | |
| 343 | // RecordTransition records state change happening in subConn and based on that |
| 344 | // it evaluates what aggregated state should be. |
| 345 | // |
| 346 | // - If at least one SubConn in Ready, the aggregated state is Ready; |
| 347 | // - Else if at least one SubConn in Connecting, the aggregated state is Connecting; |
| 348 | // - Else the aggregated state is TransientFailure. |
| 349 | // |
| 350 | // Idle and Shutdown are not considered. |
| 351 | func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State { |
| 352 | // Update counters. |
| 353 | for idx, state := range []connectivity.State{oldState, newState} { |
| 354 | updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. |
| 355 | switch state { |
| 356 | case connectivity.Ready: |
| 357 | cse.numReady += updateVal |
| 358 | case connectivity.Connecting: |
| 359 | cse.numConnecting += updateVal |
| 360 | case connectivity.TransientFailure: |
| 361 | cse.numTransientFailure += updateVal |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | // Evaluate. |
| 366 | if cse.numReady > 0 { |
| 367 | return connectivity.Ready |
| 368 | } |
| 369 | if cse.numConnecting > 0 { |
| 370 | return connectivity.Connecting |
| 371 | } |
| 372 | return connectivity.TransientFailure |
| 373 | } |