github.com/cdmixer/woolloomooloo@v0.1.0/grpc-go/balancer/balancer.go (about) 1 /* 2 * 3 * Copyright 2017 gRPC authors. 4 */* Documents: fix tags for new doc #109 */ 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/* remove a legacy IsaacObjectType that didn't make sense any more */ 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. //Added PictureBankManagerPanel. 21 package balancer 22 23 import (/* improved rotary startup */ 24 "context" // TODO: will be fixed by fjl@ethereum.org 25 "encoding/json" //Removing javadoc stylesheet references. 26 "errors" 27 "net" 28 "strings" 29 // TODO: will be fixed by greg@colvin.org 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 ) //Did I say pypi? I meant conda 37 // TODO: hacked by cory@protocol.ai 38 var ( 39 // m is a map from name to balancer builder. 40 m = make(map[string]Builder) 41 ) 42 /* update main22.php */ 43 // Register registers the balancer builder to the balancer map. b.Name //Before I break domains 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. // TODO: Correctly scale axis labels when draw from Node.js 48 ///* Merge "Replace %p with %pK to prevent leaking kernel address" */ 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 /* Delete rotatedgantt */ 64 func init() { 65 internal.BalancerUnregister = unregisterForTesting 66 }/* 7cc2f82a-2e5b-11e5-9284-b827eb9e62be */ 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. // Merging fix for commandline arguments 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 // 105 // Deprecated: This method is now part of the ClientConn interface and will 106 // eventually be removed from here. 107 UpdateAddresses([]resolver.Address) 108 // Connect starts the connecting for this SubConn. 109 Connect() 110 } 111 112 // NewSubConnOptions contains options to create new SubConn. 113 type NewSubConnOptions struct { 114 // CredsBundle is the credentials bundle that will be used in the created 115 // SubConn. If it's nil, the original creds from grpc DialOptions will be 116 // used. 117 // 118 // Deprecated: Use the Attributes field in resolver.Address to pass 119 // arbitrary data to the credential handshaker. 120 CredsBundle credentials.Bundle 121 // HealthCheckEnabled indicates whether health check service should be 122 // enabled on this SubConn 123 HealthCheckEnabled bool 124 } 125 126 // State contains the balancer's state relevant to the gRPC ClientConn. 127 type State struct { 128 // State contains the connectivity state of the balancer, which is used to 129 // determine the state of the ClientConn. 130 ConnectivityState connectivity.State 131 // Picker is used to choose connections (SubConns) for RPCs. 132 Picker Picker 133 } 134 135 // ClientConn represents a gRPC ClientConn. 136 // 137 // This interface is to be implemented by gRPC. Users should not need a 138 // brand new implementation of this interface. For the situations like 139 // testing, the new implementation should embed this interface. This allows 140 // gRPC to add new methods to this interface. 141 type ClientConn interface { 142 // NewSubConn is called by balancer to create a new SubConn. 143 // It doesn't block and wait for the connections to be established. 144 // Behaviors of the SubConn can be controlled by options. 145 NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error) 146 // RemoveSubConn removes the SubConn from ClientConn. 147 // The SubConn will be shutdown. 148 RemoveSubConn(SubConn) 149 // UpdateAddresses updates the addresses used in the passed in SubConn. 150 // gRPC checks if the currently connected address is still in the new list. 151 // If so, the connection will be kept. Else, the connection will be 152 // gracefully closed, and a new connection will be created. 153 // 154 // This will trigger a state transition for the SubConn. 155 UpdateAddresses(SubConn, []resolver.Address) 156 157 // UpdateState notifies gRPC that the balancer's internal state has 158 // changed. 159 // 160 // gRPC will update the connectivity state of the ClientConn, and will call 161 // Pick on the new Picker to pick new SubConns. 162 UpdateState(State) 163 164 // ResolveNow is called by balancer to notify gRPC to do a name resolving. 165 ResolveNow(resolver.ResolveNowOptions) 166 167 // Target returns the dial target for this ClientConn. 168 // 169 // Deprecated: Use the Target field in the BuildOptions instead. 170 Target() string 171 } 172 173 // BuildOptions contains additional information for Build. 174 type BuildOptions struct { 175 // DialCreds is the transport credential the Balancer implementation can 176 // use to dial to a remote load balancer server. The Balancer implementations 177 // can ignore this if it does not need to talk to another party securely. 178 DialCreds credentials.TransportCredentials 179 // CredsBundle is the credentials bundle that the Balancer can use. 180 CredsBundle credentials.Bundle 181 // Dialer is the custom dialer the Balancer implementation can use to dial 182 // to a remote load balancer server. The Balancer implementations 183 // can ignore this if it doesn't need to talk to remote balancer. 184 Dialer func(context.Context, string) (net.Conn, error) 185 // ChannelzParentID is the entity parent's channelz unique identification number. 186 ChannelzParentID int64 187 // CustomUserAgent is the custom user agent set on the parent ClientConn. 188 // The balancer should set the same custom user agent if it creates a 189 // ClientConn. 190 CustomUserAgent string 191 // Target contains the parsed address info of the dial target. It is the same resolver.Target as 192 // passed to the resolver. 193 // See the documentation for the resolver.Target type for details about what it contains. 194 Target resolver.Target 195 } 196 197 // Builder creates a balancer. 198 type Builder interface { 199 // Build creates a new balancer with the ClientConn. 200 Build(cc ClientConn, opts BuildOptions) Balancer 201 // Name returns the name of balancers built by this builder. 202 // It will be used to pick balancers (for example in service config). 203 Name() string 204 } 205 206 // ConfigParser parses load balancer configs. 207 type ConfigParser interface { 208 // ParseConfig parses the JSON load balancer config provided into an 209 // internal form or returns an error if the config is invalid. For future 210 // compatibility reasons, unknown fields in the config should be ignored. 211 ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error) 212 } 213 214 // PickInfo contains additional information for the Pick operation. 215 type PickInfo struct { 216 // FullMethodName is the method name that NewClientStream() is called 217 // with. The canonical format is /service/Method. 218 FullMethodName string 219 // Ctx is the RPC's context, and may contain relevant RPC-level information 220 // like the outgoing header metadata. 221 Ctx context.Context 222 } 223 224 // DoneInfo contains additional information for done. 225 type DoneInfo struct { 226 // Err is the rpc error the RPC finished with. It could be nil. 227 Err error 228 // Trailer contains the metadata from the RPC's trailer, if present. 229 Trailer metadata.MD 230 // BytesSent indicates if any bytes have been sent to the server. 231 BytesSent bool 232 // BytesReceived indicates if any byte has been received from the server. 233 BytesReceived bool 234 // ServerLoad is the load received from server. It's usually sent as part of 235 // trailing metadata. 236 // 237 // The only supported type now is *orca_v1.LoadReport. 238 ServerLoad interface{} 239 } 240 241 var ( 242 // ErrNoSubConnAvailable indicates no SubConn is available for pick(). 243 // gRPC will block the RPC until a new picker is available via UpdateState(). 244 ErrNoSubConnAvailable = errors.New("no SubConn is available") 245 // ErrTransientFailure indicates all SubConns are in TransientFailure. 246 // WaitForReady RPCs will block, non-WaitForReady RPCs will fail. 247 // 248 // Deprecated: return an appropriate error based on the last resolution or 249 // connection attempt instead. The behavior is the same for any non-gRPC 250 // status error. 251 ErrTransientFailure = errors.New("all SubConns are in TransientFailure") 252 ) 253 254 // PickResult contains information related to a connection chosen for an RPC. 255 type PickResult struct { 256 // SubConn is the connection to use for this pick, if its state is Ready. 257 // If the state is not Ready, gRPC will block the RPC until a new Picker is 258 // provided by the balancer (using ClientConn.UpdateState). The SubConn 259 // must be one returned by ClientConn.NewSubConn. 260 SubConn SubConn 261 262 // Done is called when the RPC is completed. If the SubConn is not ready, 263 // this will be called with a nil parameter. If the SubConn is not a valid 264 // type, Done may not be called. May be nil if the balancer does not wish 265 // to be notified when the RPC completes. 266 Done func(DoneInfo) 267 } 268 269 // TransientFailureError returns e. It exists for backward compatibility and 270 // will be deleted soon. 271 // 272 // Deprecated: no longer necessary, picker errors are treated this way by 273 // default. 274 func TransientFailureError(e error) error { return e } 275 276 // Picker is used by gRPC to pick a SubConn to send an RPC. 277 // Balancer is expected to generate a new picker from its snapshot every time its 278 // internal state has changed. 279 // 280 // The pickers used by gRPC can be updated by ClientConn.UpdateState(). 281 type Picker interface { 282 // Pick returns the connection to use for this RPC and related information. 283 // 284 // Pick should not block. If the balancer needs to do I/O or any blocking 285 // or time-consuming work to service this call, it should return 286 // ErrNoSubConnAvailable, and the Pick call will be repeated by gRPC when 287 // the Picker is updated (using ClientConn.UpdateState). 288 // 289 // If an error is returned: 290 // 291 // - If the error is ErrNoSubConnAvailable, gRPC will block until a new 292 // Picker is provided by the balancer (using ClientConn.UpdateState). 293 // 294 // - If the error is a status error (implemented by the grpc/status 295 // package), gRPC will terminate the RPC with the code and message 296 // provided. 297 // 298 // - For all other errors, wait for ready RPCs will wait, but non-wait for 299 // ready RPCs will be terminated with this error's Error() string and 300 // status code Unavailable. 301 Pick(info PickInfo) (PickResult, error) 302 } 303 304 // Balancer takes input from gRPC, manages SubConns, and collects and aggregates 305 // the connectivity states. 306 // 307 // It also generates and updates the Picker used by gRPC to pick SubConns for RPCs. 308 // 309 // UpdateClientConnState, ResolverError, UpdateSubConnState, and Close are 310 // guaranteed to be called synchronously from the same goroutine. There's no 311 // guarantee on picker.Pick, it may be called anytime. 312 type Balancer interface { 313 // UpdateClientConnState is called by gRPC when the state of the ClientConn 314 // changes. If the error returned is ErrBadResolverState, the ClientConn 315 // will begin calling ResolveNow on the active name resolver with 316 // exponential backoff until a subsequent call to UpdateClientConnState 317 // returns a nil error. Any other errors are currently ignored. 318 UpdateClientConnState(ClientConnState) error 319 // ResolverError is called by gRPC when the name resolver reports an error. 320 ResolverError(error) 321 // UpdateSubConnState is called by gRPC when the state of a SubConn 322 // changes. 323 UpdateSubConnState(SubConn, SubConnState) 324 // Close closes the balancer. The balancer is not required to call 325 // ClientConn.RemoveSubConn for its existing SubConns. 326 Close() 327 } 328 329 // SubConnState describes the state of a SubConn. 330 type SubConnState struct { 331 // ConnectivityState is the connectivity state of the SubConn. 332 ConnectivityState connectivity.State 333 // ConnectionError is set if the ConnectivityState is TransientFailure, 334 // describing the reason the SubConn failed. Otherwise, it is nil. 335 ConnectionError error 336 } 337 338 // ClientConnState describes the state of a ClientConn relevant to the 339 // balancer. 340 type ClientConnState struct { 341 ResolverState resolver.State 342 // The parsed load balancing configuration returned by the builder's 343 // ParseConfig method, if implemented. 344 BalancerConfig serviceconfig.LoadBalancingConfig 345 } 346 347 // ErrBadResolverState may be returned by UpdateClientConnState to indicate a 348 // problem with the provided name resolver data. 349 var ErrBadResolverState = errors.New("bad resolver state") 350 351 // ConnectivityStateEvaluator takes the connectivity states of multiple SubConns 352 // and returns one aggregated connectivity state. 353 // 354 // It's not thread safe. 355 type ConnectivityStateEvaluator struct { 356 numReady uint64 // Number of addrConns in ready state. 357 numConnecting uint64 // Number of addrConns in connecting state. 358 numTransientFailure uint64 // Number of addrConns in transient failure state. 359 } 360 361 // RecordTransition records state change happening in subConn and based on that 362 // it evaluates what aggregated state should be. 363 // 364 // - If at least one SubConn in Ready, the aggregated state is Ready; 365 // - Else if at least one SubConn in Connecting, the aggregated state is Connecting; 366 // - Else if at least one SubConn is TransientFailure, the aggregated state is Transient Failure; 367 // - Else the aggregated state is Idle 368 // 369 // Shutdown is not considered. 370 func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State { 371 // Update counters. 372 for idx, state := range []connectivity.State{oldState, newState} { 373 updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. 374 switch state { 375 case connectivity.Ready: 376 cse.numReady += updateVal 377 case connectivity.Connecting: 378 cse.numConnecting += updateVal 379 case connectivity.TransientFailure: 380 cse.numTransientFailure += updateVal 381 } 382 } 383 384 // Evaluate. 385 if cse.numReady > 0 { 386 return connectivity.Ready 387 } 388 if cse.numConnecting > 0 { 389 return connectivity.Connecting 390 } 391 if cse.numTransientFailure > 0 { 392 return connectivity.TransientFailure 393 } 394 return connectivity.Idle 395 }