google.golang.org/grpc@v1.62.1/balancer/balancer.go (about) 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/channelz" 31 "google.golang.org/grpc/connectivity" 32 "google.golang.org/grpc/credentials" 33 "google.golang.org/grpc/grpclog" 34 "google.golang.org/grpc/internal" 35 "google.golang.org/grpc/metadata" 36 "google.golang.org/grpc/resolver" 37 "google.golang.org/grpc/serviceconfig" 38 ) 39 40 var ( 41 // m is a map from name to balancer builder. 42 m = make(map[string]Builder) 43 44 logger = grpclog.Component("balancer") 45 ) 46 47 // Register registers the balancer builder to the balancer map. b.Name 48 // (lowercased) will be used as the name registered with this builder. If the 49 // Builder implements ConfigParser, ParseConfig will be called when new service 50 // configs are received by the resolver, and the result will be provided to the 51 // Balancer in UpdateClientConnState. 52 // 53 // NOTE: this function must only be called during initialization time (i.e. in 54 // an init() function), and is not thread-safe. If multiple Balancers are 55 // registered with the same name, the one registered last will take effect. 56 func Register(b Builder) { 57 if strings.ToLower(b.Name()) != b.Name() { 58 // TODO: Skip the use of strings.ToLower() to index the map after v1.59 59 // is released to switch to case sensitive balancer registry. Also, 60 // remove this warning and update the docstrings for Register and Get. 61 logger.Warningf("Balancer registered with name %q. grpc-go will be switching to case sensitive balancer registries soon", b.Name()) 62 } 63 m[strings.ToLower(b.Name())] = b 64 } 65 66 // unregisterForTesting deletes the balancer with the given name from the 67 // balancer map. 68 // 69 // This function is not thread-safe. 70 func unregisterForTesting(name string) { 71 delete(m, name) 72 } 73 74 func init() { 75 internal.BalancerUnregister = unregisterForTesting 76 } 77 78 // Get returns the resolver builder registered with the given name. 79 // Note that the compare is done in a case-insensitive fashion. 80 // If no builder is register with the name, nil will be returned. 81 func Get(name string) Builder { 82 if strings.ToLower(name) != name { 83 // TODO: Skip the use of strings.ToLower() to index the map after v1.59 84 // is released to switch to case sensitive balancer registry. Also, 85 // remove this warning and update the docstrings for Register and Get. 86 logger.Warningf("Balancer retrieved for name %q. grpc-go will be switching to case sensitive balancer registries soon", name) 87 } 88 if b, ok := m[strings.ToLower(name)]; ok { 89 return b 90 } 91 return nil 92 } 93 94 // A SubConn represents a single connection to a gRPC backend service. 95 // 96 // Each SubConn contains a list of addresses. 97 // 98 // All SubConns start in IDLE, and will not try to connect. To trigger the 99 // connecting, Balancers must call Connect. If a connection re-enters IDLE, 100 // Balancers must call Connect again to trigger a new connection attempt. 101 // 102 // gRPC will try to connect to the addresses in sequence, and stop trying the 103 // remainder once the first connection is successful. If an attempt to connect 104 // to all addresses encounters an error, the SubConn will enter 105 // TRANSIENT_FAILURE for a backoff period, and then transition to IDLE. 106 // 107 // Once established, if a connection is lost, the SubConn will transition 108 // directly to IDLE. 109 // 110 // This interface is to be implemented by gRPC. Users should not need their own 111 // implementation of this interface. For situations like testing, any 112 // implementations should embed this interface. This allows gRPC to add new 113 // methods to this interface. 114 type SubConn interface { 115 // UpdateAddresses updates the addresses used in this SubConn. 116 // gRPC checks if currently-connected address is still in the new list. 117 // If it's in the list, the connection will be kept. 118 // If it's not in the list, the connection will gracefully closed, and 119 // a new connection will be created. 120 // 121 // This will trigger a state transition for the SubConn. 122 // 123 // Deprecated: this method will be removed. Create new SubConns for new 124 // addresses instead. 125 UpdateAddresses([]resolver.Address) 126 // Connect starts the connecting for this SubConn. 127 Connect() 128 // GetOrBuildProducer returns a reference to the existing Producer for this 129 // ProducerBuilder in this SubConn, or, if one does not currently exist, 130 // creates a new one and returns it. Returns a close function which must 131 // be called when the Producer is no longer needed. 132 GetOrBuildProducer(ProducerBuilder) (p Producer, close func()) 133 // Shutdown shuts down the SubConn gracefully. Any started RPCs will be 134 // allowed to complete. No future calls should be made on the SubConn. 135 // One final state update will be delivered to the StateListener (or 136 // UpdateSubConnState; deprecated) with ConnectivityState of Shutdown to 137 // indicate the shutdown operation. This may be delivered before 138 // in-progress RPCs are complete and the actual connection is closed. 139 Shutdown() 140 } 141 142 // NewSubConnOptions contains options to create new SubConn. 143 type NewSubConnOptions struct { 144 // CredsBundle is the credentials bundle that will be used in the created 145 // SubConn. If it's nil, the original creds from grpc DialOptions will be 146 // used. 147 // 148 // Deprecated: Use the Attributes field in resolver.Address to pass 149 // arbitrary data to the credential handshaker. 150 CredsBundle credentials.Bundle 151 // HealthCheckEnabled indicates whether health check service should be 152 // enabled on this SubConn 153 HealthCheckEnabled bool 154 // StateListener is called when the state of the subconn changes. If nil, 155 // Balancer.UpdateSubConnState will be called instead. Will never be 156 // invoked until after Connect() is called on the SubConn created with 157 // these options. 158 StateListener func(SubConnState) 159 } 160 161 // State contains the balancer's state relevant to the gRPC ClientConn. 162 type State struct { 163 // State contains the connectivity state of the balancer, which is used to 164 // determine the state of the ClientConn. 165 ConnectivityState connectivity.State 166 // Picker is used to choose connections (SubConns) for RPCs. 167 Picker Picker 168 } 169 170 // ClientConn represents a gRPC ClientConn. 171 // 172 // This interface is to be implemented by gRPC. Users should not need a 173 // brand new implementation of this interface. For the situations like 174 // testing, the new implementation should embed this interface. This allows 175 // gRPC to add new methods to this interface. 176 type ClientConn interface { 177 // NewSubConn is called by balancer to create a new SubConn. 178 // It doesn't block and wait for the connections to be established. 179 // Behaviors of the SubConn can be controlled by options. 180 // 181 // Deprecated: please be aware that in a future version, SubConns will only 182 // support one address per SubConn. 183 NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error) 184 // RemoveSubConn removes the SubConn from ClientConn. 185 // The SubConn will be shutdown. 186 // 187 // Deprecated: use SubConn.Shutdown instead. 188 RemoveSubConn(SubConn) 189 // UpdateAddresses updates the addresses used in the passed in SubConn. 190 // gRPC checks if the currently connected address is still in the new list. 191 // If so, the connection will be kept. Else, the connection will be 192 // gracefully closed, and a new connection will be created. 193 // 194 // This may trigger a state transition for the SubConn. 195 // 196 // Deprecated: this method will be removed. Create new SubConns for new 197 // addresses instead. 198 UpdateAddresses(SubConn, []resolver.Address) 199 200 // UpdateState notifies gRPC that the balancer's internal state has 201 // changed. 202 // 203 // gRPC will update the connectivity state of the ClientConn, and will call 204 // Pick on the new Picker to pick new SubConns. 205 UpdateState(State) 206 207 // ResolveNow is called by balancer to notify gRPC to do a name resolving. 208 ResolveNow(resolver.ResolveNowOptions) 209 210 // Target returns the dial target for this ClientConn. 211 // 212 // Deprecated: Use the Target field in the BuildOptions instead. 213 Target() string 214 } 215 216 // BuildOptions contains additional information for Build. 217 type BuildOptions struct { 218 // DialCreds is the transport credentials to use when communicating with a 219 // remote load balancer server. Balancer implementations which do not 220 // communicate with a remote load balancer server can ignore this field. 221 DialCreds credentials.TransportCredentials 222 // CredsBundle is the credentials bundle to use when communicating with a 223 // remote load balancer server. Balancer implementations which do not 224 // communicate with a remote load balancer server can ignore this field. 225 CredsBundle credentials.Bundle 226 // Dialer is the custom dialer to use when communicating with a remote load 227 // balancer server. Balancer implementations which do not communicate with a 228 // remote load balancer server can ignore this field. 229 Dialer func(context.Context, string) (net.Conn, error) 230 // Authority is the server name to use as part of the authentication 231 // handshake when communicating with a remote load balancer server. Balancer 232 // implementations which do not communicate with a remote load balancer 233 // server can ignore this field. 234 Authority string 235 // ChannelzParentID is the parent ClientConn's channelz ID. 236 ChannelzParentID *channelz.Identifier 237 // CustomUserAgent is the custom user agent set on the parent ClientConn. 238 // The balancer should set the same custom user agent if it creates a 239 // ClientConn. 240 CustomUserAgent string 241 // Target contains the parsed address info of the dial target. It is the 242 // same resolver.Target as passed to the resolver. See the documentation for 243 // the resolver.Target type for details about what it contains. 244 Target resolver.Target 245 } 246 247 // Builder creates a balancer. 248 type Builder interface { 249 // Build creates a new balancer with the ClientConn. 250 Build(cc ClientConn, opts BuildOptions) Balancer 251 // Name returns the name of balancers built by this builder. 252 // It will be used to pick balancers (for example in service config). 253 Name() string 254 } 255 256 // ConfigParser parses load balancer configs. 257 type ConfigParser interface { 258 // ParseConfig parses the JSON load balancer config provided into an 259 // internal form or returns an error if the config is invalid. For future 260 // compatibility reasons, unknown fields in the config should be ignored. 261 ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error) 262 } 263 264 // PickInfo contains additional information for the Pick operation. 265 type PickInfo struct { 266 // FullMethodName is the method name that NewClientStream() is called 267 // with. The canonical format is /service/Method. 268 FullMethodName string 269 // Ctx is the RPC's context, and may contain relevant RPC-level information 270 // like the outgoing header metadata. 271 Ctx context.Context 272 } 273 274 // DoneInfo contains additional information for done. 275 type DoneInfo struct { 276 // Err is the rpc error the RPC finished with. It could be nil. 277 Err error 278 // Trailer contains the metadata from the RPC's trailer, if present. 279 Trailer metadata.MD 280 // BytesSent indicates if any bytes have been sent to the server. 281 BytesSent bool 282 // BytesReceived indicates if any byte has been received from the server. 283 BytesReceived bool 284 // ServerLoad is the load received from server. It's usually sent as part of 285 // trailing metadata. 286 // 287 // The only supported type now is *orca_v3.LoadReport. 288 ServerLoad any 289 } 290 291 var ( 292 // ErrNoSubConnAvailable indicates no SubConn is available for pick(). 293 // gRPC will block the RPC until a new picker is available via UpdateState(). 294 ErrNoSubConnAvailable = errors.New("no SubConn is available") 295 // ErrTransientFailure indicates all SubConns are in TransientFailure. 296 // WaitForReady RPCs will block, non-WaitForReady RPCs will fail. 297 // 298 // Deprecated: return an appropriate error based on the last resolution or 299 // connection attempt instead. The behavior is the same for any non-gRPC 300 // status error. 301 ErrTransientFailure = errors.New("all SubConns are in TransientFailure") 302 ) 303 304 // PickResult contains information related to a connection chosen for an RPC. 305 type PickResult struct { 306 // SubConn is the connection to use for this pick, if its state is Ready. 307 // If the state is not Ready, gRPC will block the RPC until a new Picker is 308 // provided by the balancer (using ClientConn.UpdateState). The SubConn 309 // must be one returned by ClientConn.NewSubConn. 310 SubConn SubConn 311 312 // Done is called when the RPC is completed. If the SubConn is not ready, 313 // this will be called with a nil parameter. If the SubConn is not a valid 314 // type, Done may not be called. May be nil if the balancer does not wish 315 // to be notified when the RPC completes. 316 Done func(DoneInfo) 317 318 // Metadata provides a way for LB policies to inject arbitrary per-call 319 // metadata. Any metadata returned here will be merged with existing 320 // metadata added by the client application. 321 // 322 // LB policies with child policies are responsible for propagating metadata 323 // injected by their children to the ClientConn, as part of Pick(). 324 Metadata metadata.MD 325 } 326 327 // TransientFailureError returns e. It exists for backward compatibility and 328 // will be deleted soon. 329 // 330 // Deprecated: no longer necessary, picker errors are treated this way by 331 // default. 332 func TransientFailureError(e error) error { return e } 333 334 // Picker is used by gRPC to pick a SubConn to send an RPC. 335 // Balancer is expected to generate a new picker from its snapshot every time its 336 // internal state has changed. 337 // 338 // The pickers used by gRPC can be updated by ClientConn.UpdateState(). 339 type Picker interface { 340 // Pick returns the connection to use for this RPC and related information. 341 // 342 // Pick should not block. If the balancer needs to do I/O or any blocking 343 // or time-consuming work to service this call, it should return 344 // ErrNoSubConnAvailable, and the Pick call will be repeated by gRPC when 345 // the Picker is updated (using ClientConn.UpdateState). 346 // 347 // If an error is returned: 348 // 349 // - If the error is ErrNoSubConnAvailable, gRPC will block until a new 350 // Picker is provided by the balancer (using ClientConn.UpdateState). 351 // 352 // - If the error is a status error (implemented by the grpc/status 353 // package), gRPC will terminate the RPC with the code and message 354 // provided. 355 // 356 // - For all other errors, wait for ready RPCs will wait, but non-wait for 357 // ready RPCs will be terminated with this error's Error() string and 358 // status code Unavailable. 359 Pick(info PickInfo) (PickResult, error) 360 } 361 362 // Balancer takes input from gRPC, manages SubConns, and collects and aggregates 363 // the connectivity states. 364 // 365 // It also generates and updates the Picker used by gRPC to pick SubConns for RPCs. 366 // 367 // UpdateClientConnState, ResolverError, UpdateSubConnState, and Close are 368 // guaranteed to be called synchronously from the same goroutine. There's no 369 // guarantee on picker.Pick, it may be called anytime. 370 type Balancer interface { 371 // UpdateClientConnState is called by gRPC when the state of the ClientConn 372 // changes. If the error returned is ErrBadResolverState, the ClientConn 373 // will begin calling ResolveNow on the active name resolver with 374 // exponential backoff until a subsequent call to UpdateClientConnState 375 // returns a nil error. Any other errors are currently ignored. 376 UpdateClientConnState(ClientConnState) error 377 // ResolverError is called by gRPC when the name resolver reports an error. 378 ResolverError(error) 379 // UpdateSubConnState is called by gRPC when the state of a SubConn 380 // changes. 381 // 382 // Deprecated: Use NewSubConnOptions.StateListener when creating the 383 // SubConn instead. 384 UpdateSubConnState(SubConn, SubConnState) 385 // Close closes the balancer. The balancer is not currently required to 386 // call SubConn.Shutdown for its existing SubConns; however, this will be 387 // required in a future release, so it is recommended. 388 Close() 389 } 390 391 // ExitIdler is an optional interface for balancers to implement. If 392 // implemented, ExitIdle will be called when ClientConn.Connect is called, if 393 // the ClientConn is idle. If unimplemented, ClientConn.Connect will cause 394 // all SubConns to connect. 395 // 396 // Notice: it will be required for all balancers to implement this in a future 397 // release. 398 type ExitIdler interface { 399 // ExitIdle instructs the LB policy to reconnect to backends / exit the 400 // IDLE state, if appropriate and possible. Note that SubConns that enter 401 // the IDLE state will not reconnect until SubConn.Connect is called. 402 ExitIdle() 403 } 404 405 // SubConnState describes the state of a SubConn. 406 type SubConnState struct { 407 // ConnectivityState is the connectivity state of the SubConn. 408 ConnectivityState connectivity.State 409 // ConnectionError is set if the ConnectivityState is TransientFailure, 410 // describing the reason the SubConn failed. Otherwise, it is nil. 411 ConnectionError error 412 } 413 414 // ClientConnState describes the state of a ClientConn relevant to the 415 // balancer. 416 type ClientConnState struct { 417 ResolverState resolver.State 418 // The parsed load balancing configuration returned by the builder's 419 // ParseConfig method, if implemented. 420 BalancerConfig serviceconfig.LoadBalancingConfig 421 } 422 423 // ErrBadResolverState may be returned by UpdateClientConnState to indicate a 424 // problem with the provided name resolver data. 425 var ErrBadResolverState = errors.New("bad resolver state") 426 427 // A ProducerBuilder is a simple constructor for a Producer. It is used by the 428 // SubConn to create producers when needed. 429 type ProducerBuilder interface { 430 // Build creates a Producer. The first parameter is always a 431 // grpc.ClientConnInterface (a type to allow creating RPCs/streams on the 432 // associated SubConn), but is declared as `any` to avoid a dependency 433 // cycle. Should also return a close function that will be called when all 434 // references to the Producer have been given up. 435 Build(grpcClientConnInterface any) (p Producer, close func()) 436 } 437 438 // A Producer is a type shared among potentially many consumers. It is 439 // associated with a SubConn, and an implementation will typically contain 440 // other methods to provide additional functionality, e.g. configuration or 441 // subscription registration. 442 type Producer any