balancer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. //
  105. // Deprecated: Use the Attributes field in resolver.Address to pass
  106. // arbitrary data to the credential handshaker.
  107. CredsBundle credentials.Bundle
  108. // HealthCheckEnabled indicates whether health check service should be
  109. // enabled on this SubConn
  110. HealthCheckEnabled bool
  111. }
  112. // State contains the balancer's state relevant to the gRPC ClientConn.
  113. type State struct {
  114. // State contains the connectivity state of the balancer, which is used to
  115. // determine the state of the ClientConn.
  116. ConnectivityState connectivity.State
  117. // Picker is used to choose connections (SubConns) for RPCs.
  118. Picker Picker
  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. // UpdateState notifies gRPC that the balancer's internal state has
  135. // changed.
  136. //
  137. // gRPC will update the connectivity state of the ClientConn, and will call
  138. // Pick on the new Picker to pick new SubConns.
  139. UpdateState(State)
  140. // ResolveNow is called by balancer to notify gRPC to do a name resolving.
  141. ResolveNow(resolver.ResolveNowOptions)
  142. // Target returns the dial target for this ClientConn.
  143. //
  144. // Deprecated: Use the Target field in the BuildOptions instead.
  145. Target() string
  146. }
  147. // BuildOptions contains additional information for Build.
  148. type BuildOptions struct {
  149. // DialCreds is the transport credential the Balancer implementation can
  150. // use to dial to a remote load balancer server. The Balancer implementations
  151. // can ignore this if it does not need to talk to another party securely.
  152. DialCreds credentials.TransportCredentials
  153. // CredsBundle is the credentials bundle that the Balancer can use.
  154. CredsBundle credentials.Bundle
  155. // Dialer is the custom dialer the Balancer implementation can use to dial
  156. // to a remote load balancer server. The Balancer implementations
  157. // can ignore this if it doesn't need to talk to remote balancer.
  158. Dialer func(context.Context, string) (net.Conn, error)
  159. // ChannelzParentID is the entity parent's channelz unique identification number.
  160. ChannelzParentID int64
  161. // Target contains the parsed address info of the dial target. It is the same resolver.Target as
  162. // passed to the resolver.
  163. // See the documentation for the resolver.Target type for details about what it contains.
  164. Target resolver.Target
  165. }
  166. // Builder creates a balancer.
  167. type Builder interface {
  168. // Build creates a new balancer with the ClientConn.
  169. Build(cc ClientConn, opts BuildOptions) Balancer
  170. // Name returns the name of balancers built by this builder.
  171. // It will be used to pick balancers (for example in service config).
  172. Name() string
  173. }
  174. // ConfigParser parses load balancer configs.
  175. type ConfigParser interface {
  176. // ParseConfig parses the JSON load balancer config provided into an
  177. // internal form or returns an error if the config is invalid. For future
  178. // compatibility reasons, unknown fields in the config should be ignored.
  179. ParseConfig(LoadBalancingConfigJSON json.RawMessage) (serviceconfig.LoadBalancingConfig, error)
  180. }
  181. // PickInfo contains additional information for the Pick operation.
  182. type PickInfo struct {
  183. // FullMethodName is the method name that NewClientStream() is called
  184. // with. The canonical format is /service/Method.
  185. FullMethodName string
  186. // Ctx is the RPC's context, and may contain relevant RPC-level information
  187. // like the outgoing header metadata.
  188. Ctx context.Context
  189. }
  190. // DoneInfo contains additional information for done.
  191. type DoneInfo struct {
  192. // Err is the rpc error the RPC finished with. It could be nil.
  193. Err error
  194. // Trailer contains the metadata from the RPC's trailer, if present.
  195. Trailer metadata.MD
  196. // BytesSent indicates if any bytes have been sent to the server.
  197. BytesSent bool
  198. // BytesReceived indicates if any byte has been received from the server.
  199. BytesReceived bool
  200. // ServerLoad is the load received from server. It's usually sent as part of
  201. // trailing metadata.
  202. //
  203. // The only supported type now is *orca_v1.LoadReport.
  204. ServerLoad interface{}
  205. }
  206. var (
  207. // ErrNoSubConnAvailable indicates no SubConn is available for pick().
  208. // gRPC will block the RPC until a new picker is available via UpdateState().
  209. ErrNoSubConnAvailable = errors.New("no SubConn is available")
  210. // ErrTransientFailure indicates all SubConns are in TransientFailure.
  211. // WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
  212. //
  213. // Deprecated: return an appropriate error based on the last resolution or
  214. // connection attempt instead. The behavior is the same for any non-gRPC
  215. // status error.
  216. ErrTransientFailure = errors.New("all SubConns are in TransientFailure")
  217. )
  218. // PickResult contains information related to a connection chosen for an RPC.
  219. type PickResult struct {
  220. // SubConn is the connection to use for this pick, if its state is Ready.
  221. // If the state is not Ready, gRPC will block the RPC until a new Picker is
  222. // provided by the balancer (using ClientConn.UpdateState). The SubConn
  223. // must be one returned by ClientConn.NewSubConn.
  224. SubConn SubConn
  225. // Done is called when the RPC is completed. If the SubConn is not ready,
  226. // this will be called with a nil parameter. If the SubConn is not a valid
  227. // type, Done may not be called. May be nil if the balancer does not wish
  228. // to be notified when the RPC completes.
  229. Done func(DoneInfo)
  230. }
  231. // TransientFailureError returns e. It exists for backward compatibility and
  232. // will be deleted soon.
  233. //
  234. // Deprecated: no longer necessary, picker errors are treated this way by
  235. // default.
  236. func TransientFailureError(e error) error { return e }
  237. // Picker is used by gRPC to pick a SubConn to send an RPC.
  238. // Balancer is expected to generate a new picker from its snapshot every time its
  239. // internal state has changed.
  240. //
  241. // The pickers used by gRPC can be updated by ClientConn.UpdateState().
  242. type Picker interface {
  243. // Pick returns the connection to use for this RPC and related information.
  244. //
  245. // Pick should not block. If the balancer needs to do I/O or any blocking
  246. // or time-consuming work to service this call, it should return
  247. // ErrNoSubConnAvailable, and the Pick call will be repeated by gRPC when
  248. // the Picker is updated (using ClientConn.UpdateState).
  249. //
  250. // If an error is returned:
  251. //
  252. // - If the error is ErrNoSubConnAvailable, gRPC will block until a new
  253. // Picker is provided by the balancer (using ClientConn.UpdateState).
  254. //
  255. // - If the error is a status error (implemented by the grpc/status
  256. // package), gRPC will terminate the RPC with the code and message
  257. // provided.
  258. //
  259. // - For all other errors, wait for ready RPCs will wait, but non-wait for
  260. // ready RPCs will be terminated with this error's Error() string and
  261. // status code Unavailable.
  262. Pick(info PickInfo) (PickResult, error)
  263. }
  264. // Balancer takes input from gRPC, manages SubConns, and collects and aggregates
  265. // the connectivity states.
  266. //
  267. // It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
  268. //
  269. // UpdateClientConnState, ResolverError, UpdateSubConnState, and Close are
  270. // guaranteed to be called synchronously from the same goroutine. There's no
  271. // guarantee on picker.Pick, it may be called anytime.
  272. type Balancer interface {
  273. // UpdateClientConnState is called by gRPC when the state of the ClientConn
  274. // changes. If the error returned is ErrBadResolverState, the ClientConn
  275. // will begin calling ResolveNow on the active name resolver with
  276. // exponential backoff until a subsequent call to UpdateClientConnState
  277. // returns a nil error. Any other errors are currently ignored.
  278. UpdateClientConnState(ClientConnState) error
  279. // ResolverError is called by gRPC when the name resolver reports an error.
  280. ResolverError(error)
  281. // UpdateSubConnState is called by gRPC when the state of a SubConn
  282. // changes.
  283. UpdateSubConnState(SubConn, SubConnState)
  284. // Close closes the balancer. The balancer is not required to call
  285. // ClientConn.RemoveSubConn for its existing SubConns.
  286. Close()
  287. }
  288. // SubConnState describes the state of a SubConn.
  289. type SubConnState struct {
  290. // ConnectivityState is the connectivity state of the SubConn.
  291. ConnectivityState connectivity.State
  292. // ConnectionError is set if the ConnectivityState is TransientFailure,
  293. // describing the reason the SubConn failed. Otherwise, it is nil.
  294. ConnectionError error
  295. }
  296. // ClientConnState describes the state of a ClientConn relevant to the
  297. // balancer.
  298. type ClientConnState struct {
  299. ResolverState resolver.State
  300. // The parsed load balancing configuration returned by the builder's
  301. // ParseConfig method, if implemented.
  302. BalancerConfig serviceconfig.LoadBalancingConfig
  303. }
  304. // ErrBadResolverState may be returned by UpdateClientConnState to indicate a
  305. // problem with the provided name resolver data.
  306. var ErrBadResolverState = errors.New("bad resolver state")
  307. // ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
  308. // and returns one aggregated connectivity state.
  309. //
  310. // It's not thread safe.
  311. type ConnectivityStateEvaluator struct {
  312. numReady uint64 // Number of addrConns in ready state.
  313. numConnecting uint64 // Number of addrConns in connecting state.
  314. }
  315. // RecordTransition records state change happening in subConn and based on that
  316. // it evaluates what aggregated state should be.
  317. //
  318. // - If at least one SubConn in Ready, the aggregated state is Ready;
  319. // - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
  320. // - Else the aggregated state is TransientFailure.
  321. //
  322. // Idle and Shutdown are not considered.
  323. func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
  324. // Update counters.
  325. for idx, state := range []connectivity.State{oldState, newState} {
  326. updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
  327. switch state {
  328. case connectivity.Ready:
  329. cse.numReady += updateVal
  330. case connectivity.Connecting:
  331. cse.numConnecting += updateVal
  332. }
  333. }
  334. // Evaluate.
  335. if cse.numReady > 0 {
  336. return connectivity.Ready
  337. }
  338. if cse.numConnecting > 0 {
  339. return connectivity.Connecting
  340. }
  341. return connectivity.TransientFailure
  342. }