balancer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. // Package balancer defines APIs for load balancing in gRPC.
  19. // All APIs in this package are experimental.
  20. package balancer
  21. import (
  22. "context"
  23. "encoding/json"
  24. "errors"
  25. "net"
  26. "strings"
  27. "google.golang.org/grpc/connectivity"
  28. "google.golang.org/grpc/credentials"
  29. "google.golang.org/grpc/internal"
  30. "google.golang.org/grpc/metadata"
  31. "google.golang.org/grpc/resolver"
  32. "google.golang.org/grpc/serviceconfig"
  33. )
  34. var (
  35. // m is a map from name to balancer builder.
  36. m = make(map[string]Builder)
  37. )
  38. // Register registers the balancer builder to the balancer map. b.Name
  39. // (lowercased) will be used as the name registered with this builder. If the
  40. // Builder implements ConfigParser, ParseConfig will be called when new service
  41. // configs are received by the resolver, and the result will be provided to the
  42. // Balancer in UpdateClientConnState.
  43. //
  44. // NOTE: this function must only be called during initialization time (i.e. in
  45. // an init() function), and is not thread-safe. If multiple Balancers are
  46. // registered with the same name, the one registered last will take effect.
  47. func Register(b Builder) {
  48. m[strings.ToLower(b.Name())] = b
  49. }
  50. // unregisterForTesting deletes the balancer with the given name from the
  51. // balancer map.
  52. //
  53. // This function is not thread-safe.
  54. func unregisterForTesting(name string) {
  55. delete(m, name)
  56. }
  57. func init() {
  58. internal.BalancerUnregister = unregisterForTesting
  59. }
  60. // Get returns the resolver builder registered with the given name.
  61. // Note that the compare is done in a case-insensitive fashion.
  62. // If no builder is register with the name, nil will be returned.
  63. func Get(name string) Builder {
  64. if b, ok := m[strings.ToLower(name)]; ok {
  65. return b
  66. }
  67. return nil
  68. }
  69. // SubConn represents a gRPC sub connection.
  70. // Each sub connection contains a list of addresses. gRPC will
  71. // try to connect to them (in sequence), and stop trying the
  72. // remainder once one connection is successful.
  73. //
  74. // The reconnect backoff will be applied on the list, not a single address.
  75. // For example, try_on_all_addresses -> backoff -> try_on_all_addresses.
  76. //
  77. // All SubConns start in IDLE, and will not try to connect. To trigger
  78. // the connecting, Balancers must call Connect.
  79. // When the connection encounters an error, it will reconnect immediately.
  80. // When the connection becomes IDLE, it will not reconnect unless Connect is
  81. // called.
  82. //
  83. // This interface is to be implemented by gRPC. Users should not need a
  84. // brand new implementation of this interface. For the situations like
  85. // testing, the new implementation should embed this interface. This allows
  86. // gRPC to add new methods to this interface.
  87. type SubConn interface {
  88. // UpdateAddresses updates the addresses used in this SubConn.
  89. // gRPC checks if currently-connected address is still in the new list.
  90. // If it's in the list, the connection will be kept.
  91. // If it's not in the list, the connection will gracefully closed, and
  92. // a new connection will be created.
  93. //
  94. // This will trigger a state transition for the SubConn.
  95. UpdateAddresses([]resolver.Address)
  96. // Connect starts the connecting for this SubConn.
  97. Connect()
  98. }
  99. // NewSubConnOptions contains options to create new SubConn.
  100. type NewSubConnOptions struct {
  101. // CredsBundle is the credentials bundle that will be used in the created
  102. // SubConn. If it's nil, the original creds from grpc DialOptions will be
  103. // used.
  104. CredsBundle credentials.Bundle
  105. // HealthCheckEnabled indicates whether health check service should be
  106. // enabled on this SubConn
  107. HealthCheckEnabled bool
  108. }
  109. // State contains the balancer's state relevant to the gRPC ClientConn.
  110. type State struct {
  111. // State contains the connectivity state of the balancer, which is used to
  112. // determine the state of the ClientConn.
  113. ConnectivityState connectivity.State
  114. // Picker is used to choose connections (SubConns) for RPCs.
  115. Picker V2Picker
  116. }
  117. // ClientConn represents a gRPC ClientConn.
  118. //
  119. // This interface is to be implemented by gRPC. Users should not need a
  120. // brand new implementation of this interface. For the situations like
  121. // testing, the new implementation should embed this interface. This allows
  122. // gRPC to add new methods to this interface.
  123. type ClientConn interface {
  124. // NewSubConn is called by balancer to create a new SubConn.
  125. // It doesn't block and wait for the connections to be established.
  126. // Behaviors of the SubConn can be controlled by options.
  127. NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error)
  128. // RemoveSubConn removes the SubConn from ClientConn.
  129. // The SubConn will be shutdown.
  130. RemoveSubConn(SubConn)
  131. // UpdateBalancerState is called by balancer to notify gRPC that some internal
  132. // state in balancer has changed.
  133. //
  134. // gRPC will update the connectivity state of the ClientConn, and will call pick
  135. // on the new picker to pick new SubConn.
  136. //
  137. // Deprecated: use UpdateState instead
  138. UpdateBalancerState(s connectivity.State, p Picker)
  139. // UpdateState notifies gRPC that the balancer's internal state has
  140. // changed.
  141. //
  142. // gRPC will update the connectivity state of the ClientConn, and will call pick
  143. // on the new picker to pick new SubConns.
  144. UpdateState(State)
  145. // ResolveNow is called by balancer to notify gRPC to do a name resolving.
  146. ResolveNow(resolver.ResolveNowOptions)
  147. // Target returns the dial target for this ClientConn.
  148. //
  149. // Deprecated: Use the Target field in the BuildOptions instead.
  150. Target() string
  151. }
  152. // BuildOptions contains additional information for Build.
  153. type BuildOptions struct {
  154. // DialCreds is the transport credential the Balancer implementation can
  155. // use to dial to a remote load balancer server. The Balancer implementations
  156. // can ignore this if it does not need to talk to another party securely.
  157. DialCreds credentials.TransportCredentials
  158. // CredsBundle is the credentials bundle that the Balancer can use.
  159. CredsBundle credentials.Bundle
  160. // Dialer is the custom dialer the Balancer implementation can use to dial
  161. // to a remote load balancer server. The Balancer implementations
  162. // can ignore this if it doesn't need to talk to remote balancer.
  163. Dialer func(context.Context, string) (net.Conn, error)
  164. // ChannelzParentID is the entity parent's channelz unique identification number.
  165. ChannelzParentID int64
  166. // Target contains the parsed address info of the dial target. It is the same resolver.Target as
  167. // passed to the resolver.
  168. // See the documentation for the resolver.Target type for details about what it contains.
  169. Target resolver.Target
  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. // ConfigParser parses load balancer configs.
  180. type ConfigParser interface {
  181. // ParseConfig parses the JSON load balancer config provided into an
  182. // internal form or returns an error if the config is invalid. For future
  183. // compatibility reasons, unknown fields in the config should be ignored.
  184. ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error)
  185. }
  186. // PickInfo contains additional information for the Pick operation.
  187. type PickInfo struct {
  188. // FullMethodName is the method name that NewClientStream() is called
  189. // with. The canonical format is /service/Method.
  190. FullMethodName string
  191. // Ctx is the RPC's context, and may contain relevant RPC-level information
  192. // like the outgoing header metadata.
  193. Ctx context.Context
  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. var (
  212. // ErrNoSubConnAvailable indicates no SubConn is available for pick().
  213. // gRPC will block the RPC until a new picker is available via UpdateBalancerState().
  214. ErrNoSubConnAvailable = errors.New("no SubConn is available")
  215. // ErrTransientFailure indicates all SubConns are in TransientFailure.
  216. // WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
  217. ErrTransientFailure = TransientFailureError(errors.New("all SubConns are in TransientFailure"))
  218. )
  219. // Picker is used by gRPC to pick a SubConn to send an RPC.
  220. // Balancer is expected to generate a new picker from its snapshot every time its
  221. // internal state has changed.
  222. //
  223. // The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
  224. //
  225. // Deprecated: use V2Picker instead
  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 or implements IsTransientFailure()
  247. // bool, returning true:
  248. // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState()
  249. // is called to pick again;
  250. // - Otherwise, RPC will fail with unavailable error.
  251. // - Else (error is other non-nil error):
  252. // - The RPC will fail with the error's status code, or Unknown if it is
  253. // not a status error.
  254. //
  255. // The returned done() function will be called once the rpc has finished,
  256. // with the final status of that RPC. If the SubConn returned is not a
  257. // valid SubConn type, done may not be called. done may be nil if balancer
  258. // doesn't care about the RPC status.
  259. Pick(ctx context.Context, info PickInfo) (conn SubConn, done func(DoneInfo), err error)
  260. }
  261. // PickResult contains information related to a connection chosen for an RPC.
  262. type PickResult struct {
  263. // SubConn is the connection to use for this pick, if its state is Ready.
  264. // If the state is not Ready, gRPC will block the RPC until a new Picker is
  265. // provided by the balancer (using ClientConn.UpdateState). The SubConn
  266. // must be one returned by ClientConn.NewSubConn.
  267. SubConn SubConn
  268. // Done is called when the RPC is completed. If the SubConn is not ready,
  269. // this will be called with a nil parameter. If the SubConn is not a valid
  270. // type, Done may not be called. May be nil if the balancer does not wish
  271. // to be notified when the RPC completes.
  272. Done func(DoneInfo)
  273. }
  274. type transientFailureError struct {
  275. error
  276. }
  277. func (e *transientFailureError) IsTransientFailure() bool { return true }
  278. // TransientFailureError wraps err in an error implementing
  279. // IsTransientFailure() bool, returning true.
  280. func TransientFailureError(err error) error {
  281. return &transientFailureError{error: err}
  282. }
  283. // V2Picker is used by gRPC to pick a SubConn to send an RPC.
  284. // Balancer is expected to generate a new picker from its snapshot every time its
  285. // internal state has changed.
  286. //
  287. // The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
  288. type V2Picker interface {
  289. // Pick returns the connection to use for this RPC and related information.
  290. //
  291. // Pick should not block. If the balancer needs to do I/O or any blocking
  292. // or time-consuming work to service this call, it should return
  293. // ErrNoSubConnAvailable, and the Pick call will be repeated by gRPC when
  294. // the Picker is updated (using ClientConn.UpdateState).
  295. //
  296. // If an error is returned:
  297. //
  298. // - If the error is ErrNoSubConnAvailable, gRPC will block until a new
  299. // Picker is provided by the balancer (using ClientConn.UpdateState).
  300. //
  301. // - If the error implements IsTransientFailure() bool, returning true,
  302. // wait for ready RPCs will wait, but non-wait for ready RPCs will be
  303. // terminated with this error's Error() string and status code
  304. // Unavailable.
  305. //
  306. // - Any other errors terminate all RPCs with the code and message
  307. // provided. If the error is not a status error, it will be converted by
  308. // gRPC to a status error with code Unknown.
  309. Pick(info PickInfo) (PickResult, error)
  310. }
  311. // Balancer takes input from gRPC, manages SubConns, and collects and aggregates
  312. // the connectivity states.
  313. //
  314. // It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
  315. //
  316. // HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed
  317. // to be called synchronously from the same goroutine.
  318. // There's no guarantee on picker.Pick, it may be called anytime.
  319. type Balancer interface {
  320. // HandleSubConnStateChange is called by gRPC when the connectivity state
  321. // of sc has changed.
  322. // Balancer is expected to aggregate all the state of SubConn and report
  323. // that back to gRPC.
  324. // Balancer should also generate and update Pickers when its internal state has
  325. // been changed by the new state.
  326. //
  327. // Deprecated: if V2Balancer is implemented by the Balancer,
  328. // UpdateSubConnState will be called instead.
  329. HandleSubConnStateChange(sc SubConn, state connectivity.State)
  330. // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to
  331. // balancers.
  332. // Balancer can create new SubConn or remove SubConn with the addresses.
  333. // An empty address slice and a non-nil error will be passed if the resolver returns
  334. // non-nil error to gRPC.
  335. //
  336. // Deprecated: if V2Balancer is implemented by the Balancer,
  337. // UpdateClientConnState will be called instead.
  338. HandleResolvedAddrs([]resolver.Address, error)
  339. // Close closes the balancer. The balancer is not required to call
  340. // ClientConn.RemoveSubConn for its existing SubConns.
  341. Close()
  342. }
  343. // SubConnState describes the state of a SubConn.
  344. type SubConnState struct {
  345. // ConnectivityState is the connectivity state of the SubConn.
  346. ConnectivityState connectivity.State
  347. // ConnectionError is set if the ConnectivityState is TransientFailure,
  348. // describing the reason the SubConn failed. Otherwise, it is nil.
  349. ConnectionError error
  350. }
  351. // ClientConnState describes the state of a ClientConn relevant to the
  352. // balancer.
  353. type ClientConnState struct {
  354. ResolverState resolver.State
  355. // The parsed load balancing configuration returned by the builder's
  356. // ParseConfig method, if implemented.
  357. BalancerConfig serviceconfig.LoadBalancingConfig
  358. }
  359. // ErrBadResolverState may be returned by UpdateClientConnState to indicate a
  360. // problem with the provided name resolver data.
  361. var ErrBadResolverState = errors.New("bad resolver state")
  362. // V2Balancer is defined for documentation purposes. If a Balancer also
  363. // implements V2Balancer, its UpdateClientConnState method will be called
  364. // instead of HandleResolvedAddrs and its UpdateSubConnState will be called
  365. // instead of HandleSubConnStateChange.
  366. type V2Balancer interface {
  367. // UpdateClientConnState is called by gRPC when the state of the ClientConn
  368. // changes. If the error returned is ErrBadResolverState, the ClientConn
  369. // will begin calling ResolveNow on the active name resolver with
  370. // exponential backoff until a subsequent call to UpdateClientConnState
  371. // returns a nil error. Any other errors are currently ignored.
  372. UpdateClientConnState(ClientConnState) error
  373. // ResolverError is called by gRPC when the name resolver reports an error.
  374. ResolverError(error)
  375. // UpdateSubConnState is called by gRPC when the state of a SubConn
  376. // changes.
  377. UpdateSubConnState(SubConn, SubConnState)
  378. // Close closes the balancer. The balancer is not required to call
  379. // ClientConn.RemoveSubConn for its existing SubConns.
  380. Close()
  381. }
  382. // ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
  383. // and returns one aggregated connectivity state.
  384. //
  385. // It's not thread safe.
  386. type ConnectivityStateEvaluator struct {
  387. numReady uint64 // Number of addrConns in ready state.
  388. numConnecting uint64 // Number of addrConns in connecting state.
  389. }
  390. // RecordTransition records state change happening in subConn and based on that
  391. // it evaluates what aggregated state should be.
  392. //
  393. // - If at least one SubConn in Ready, the aggregated state is Ready;
  394. // - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
  395. // - Else the aggregated state is TransientFailure.
  396. //
  397. // Idle and Shutdown are not considered.
  398. func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
  399. // Update counters.
  400. for idx, state := range []connectivity.State{oldState, newState} {
  401. updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
  402. switch state {
  403. case connectivity.Ready:
  404. cse.numReady += updateVal
  405. case connectivity.Connecting:
  406. cse.numConnecting += updateVal
  407. }
  408. }
  409. // Evaluate.
  410. if cse.numReady > 0 {
  411. return connectivity.Ready
  412. }
  413. if cse.numConnecting > 0 {
  414. return connectivity.Connecting
  415. }
  416. return connectivity.TransientFailure
  417. }