balancer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. "errors"
  24. "net"
  25. "strings"
  26. "google.golang.org/grpc/connectivity"
  27. "google.golang.org/grpc/credentials"
  28. "google.golang.org/grpc/metadata"
  29. "google.golang.org/grpc/resolver"
  30. )
  31. var (
  32. // m is a map from name to balancer builder.
  33. m = make(map[string]Builder)
  34. )
  35. // Register registers the balancer builder to the balancer map. b.Name
  36. // (lowercased) will be used as the name registered with this builder.
  37. //
  38. // NOTE: this function must only be called during initialization time (i.e. in
  39. // an init() function), and is not thread-safe. If multiple Balancers are
  40. // registered with the same name, the one registered last will take effect.
  41. func Register(b Builder) {
  42. m[strings.ToLower(b.Name())] = b
  43. }
  44. // Get returns the resolver builder registered with the given name.
  45. // Note that the compare is done in a case-insenstive fashion.
  46. // If no builder is register with the name, nil will be returned.
  47. func Get(name string) Builder {
  48. if b, ok := m[strings.ToLower(name)]; ok {
  49. return b
  50. }
  51. return nil
  52. }
  53. // SubConn represents a gRPC sub connection.
  54. // Each sub connection contains a list of addresses. gRPC will
  55. // try to connect to them (in sequence), and stop trying the
  56. // remainder once one connection is successful.
  57. //
  58. // The reconnect backoff will be applied on the list, not a single address.
  59. // For example, try_on_all_addresses -> backoff -> try_on_all_addresses.
  60. //
  61. // All SubConns start in IDLE, and will not try to connect. To trigger
  62. // the connecting, Balancers must call Connect.
  63. // When the connection encounters an error, it will reconnect immediately.
  64. // When the connection becomes IDLE, it will not reconnect unless Connect is
  65. // called.
  66. //
  67. // This interface is to be implemented by gRPC. Users should not need a
  68. // brand new implementation of this interface. For the situations like
  69. // testing, the new implementation should embed this interface. This allows
  70. // gRPC to add new methods to this interface.
  71. type SubConn interface {
  72. // UpdateAddresses updates the addresses used in this SubConn.
  73. // gRPC checks if currently-connected address is still in the new list.
  74. // If it's in the list, the connection will be kept.
  75. // If it's not in the list, the connection will gracefully closed, and
  76. // a new connection will be created.
  77. //
  78. // This will trigger a state transition for the SubConn.
  79. UpdateAddresses([]resolver.Address)
  80. // Connect starts the connecting for this SubConn.
  81. Connect()
  82. }
  83. // NewSubConnOptions contains options to create new SubConn.
  84. type NewSubConnOptions struct {
  85. // CredsBundle is the credentials bundle that will be used in the created
  86. // SubConn. If it's nil, the original creds from grpc DialOptions will be
  87. // used.
  88. CredsBundle credentials.Bundle
  89. // HealthCheckEnabled indicates whether health check service should be
  90. // enabled on this SubConn
  91. HealthCheckEnabled bool
  92. }
  93. // ClientConn represents a gRPC ClientConn.
  94. //
  95. // This interface is to be implemented by gRPC. Users should not need a
  96. // brand new implementation of this interface. For the situations like
  97. // testing, the new implementation should embed this interface. This allows
  98. // gRPC to add new methods to this interface.
  99. type ClientConn interface {
  100. // NewSubConn is called by balancer to create a new SubConn.
  101. // It doesn't block and wait for the connections to be established.
  102. // Behaviors of the SubConn can be controlled by options.
  103. NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error)
  104. // RemoveSubConn removes the SubConn from ClientConn.
  105. // The SubConn will be shutdown.
  106. RemoveSubConn(SubConn)
  107. // UpdateBalancerState is called by balancer to nofity gRPC that some internal
  108. // state in balancer has changed.
  109. //
  110. // gRPC will update the connectivity state of the ClientConn, and will call pick
  111. // on the new picker to pick new SubConn.
  112. UpdateBalancerState(s connectivity.State, p Picker)
  113. // ResolveNow is called by balancer to notify gRPC to do a name resolving.
  114. ResolveNow(resolver.ResolveNowOption)
  115. // Target returns the dial target for this ClientConn.
  116. Target() string
  117. }
  118. // BuildOptions contains additional information for Build.
  119. type BuildOptions struct {
  120. // DialCreds is the transport credential the Balancer implementation can
  121. // use to dial to a remote load balancer server. The Balancer implementations
  122. // can ignore this if it does not need to talk to another party securely.
  123. DialCreds credentials.TransportCredentials
  124. // CredsBundle is the credentials bundle that the Balancer can use.
  125. CredsBundle credentials.Bundle
  126. // Dialer is the custom dialer the Balancer implementation can use to dial
  127. // to a remote load balancer server. The Balancer implementations
  128. // can ignore this if it doesn't need to talk to remote balancer.
  129. Dialer func(context.Context, string) (net.Conn, error)
  130. // ChannelzParentID is the entity parent's channelz unique identification number.
  131. ChannelzParentID int64
  132. }
  133. // Builder creates a balancer.
  134. type Builder interface {
  135. // Build creates a new balancer with the ClientConn.
  136. Build(cc ClientConn, opts BuildOptions) Balancer
  137. // Name returns the name of balancers built by this builder.
  138. // It will be used to pick balancers (for example in service config).
  139. Name() string
  140. }
  141. // PickOptions contains addition information for the Pick operation.
  142. type PickOptions struct {
  143. // FullMethodName is the method name that NewClientStream() is called
  144. // with. The canonical format is /service/Method.
  145. FullMethodName string
  146. // Header contains the metadata from the RPC's client header. The metadata
  147. // should not be modified; make a copy first if needed.
  148. Header metadata.MD
  149. }
  150. // DoneInfo contains additional information for done.
  151. type DoneInfo struct {
  152. // Err is the rpc error the RPC finished with. It could be nil.
  153. Err error
  154. // Trailer contains the metadata from the RPC's trailer, if present.
  155. Trailer metadata.MD
  156. // BytesSent indicates if any bytes have been sent to the server.
  157. BytesSent bool
  158. // BytesReceived indicates if any byte has been received from the server.
  159. BytesReceived bool
  160. }
  161. var (
  162. // ErrNoSubConnAvailable indicates no SubConn is available for pick().
  163. // gRPC will block the RPC until a new picker is available via UpdateBalancerState().
  164. ErrNoSubConnAvailable = errors.New("no SubConn is available")
  165. // ErrTransientFailure indicates all SubConns are in TransientFailure.
  166. // WaitForReady RPCs will block, non-WaitForReady RPCs will fail.
  167. ErrTransientFailure = errors.New("all SubConns are in TransientFailure")
  168. )
  169. // Picker is used by gRPC to pick a SubConn to send an RPC.
  170. // Balancer is expected to generate a new picker from its snapshot every time its
  171. // internal state has changed.
  172. //
  173. // The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState().
  174. type Picker interface {
  175. // Pick returns the SubConn to be used to send the RPC.
  176. // The returned SubConn must be one returned by NewSubConn().
  177. //
  178. // This functions is expected to return:
  179. // - a SubConn that is known to be READY;
  180. // - ErrNoSubConnAvailable if no SubConn is available, but progress is being
  181. // made (for example, some SubConn is in CONNECTING mode);
  182. // - other errors if no active connecting is happening (for example, all SubConn
  183. // are in TRANSIENT_FAILURE mode).
  184. //
  185. // If a SubConn is returned:
  186. // - If it is READY, gRPC will send the RPC on it;
  187. // - If it is not ready, or becomes not ready after it's returned, gRPC will block
  188. // until UpdateBalancerState() is called and will call pick on the new picker.
  189. //
  190. // If the returned error is not nil:
  191. // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState()
  192. // - If the error is ErrTransientFailure:
  193. // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState()
  194. // is called to pick again;
  195. // - Otherwise, RPC will fail with unavailable error.
  196. // - Else (error is other non-nil error):
  197. // - The RPC will fail with unavailable error.
  198. //
  199. // The returned done() function will be called once the rpc has finished, with the
  200. // final status of that RPC.
  201. // done may be nil if balancer doesn't care about the RPC status.
  202. Pick(ctx context.Context, opts PickOptions) (conn SubConn, done func(DoneInfo), err error)
  203. }
  204. // Balancer takes input from gRPC, manages SubConns, and collects and aggregates
  205. // the connectivity states.
  206. //
  207. // It also generates and updates the Picker used by gRPC to pick SubConns for RPCs.
  208. //
  209. // HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed
  210. // to be called synchronously from the same goroutine.
  211. // There's no guarantee on picker.Pick, it may be called anytime.
  212. type Balancer interface {
  213. // HandleSubConnStateChange is called by gRPC when the connectivity state
  214. // of sc has changed.
  215. // Balancer is expected to aggregate all the state of SubConn and report
  216. // that back to gRPC.
  217. // Balancer should also generate and update Pickers when its internal state has
  218. // been changed by the new state.
  219. HandleSubConnStateChange(sc SubConn, state connectivity.State)
  220. // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to
  221. // balancers.
  222. // Balancer can create new SubConn or remove SubConn with the addresses.
  223. // An empty address slice and a non-nil error will be passed if the resolver returns
  224. // non-nil error to gRPC.
  225. HandleResolvedAddrs([]resolver.Address, error)
  226. // Close closes the balancer. The balancer is not required to call
  227. // ClientConn.RemoveSubConn for its existing SubConns.
  228. Close()
  229. }
  230. // ConnectivityStateEvaluator takes the connectivity states of multiple SubConns
  231. // and returns one aggregated connectivity state.
  232. //
  233. // It's not thread safe.
  234. type ConnectivityStateEvaluator struct {
  235. numReady uint64 // Number of addrConns in ready state.
  236. numConnecting uint64 // Number of addrConns in connecting state.
  237. numTransientFailure uint64 // Number of addrConns in transientFailure.
  238. }
  239. // RecordTransition records state change happening in subConn and based on that
  240. // it evaluates what aggregated state should be.
  241. //
  242. // - If at least one SubConn in Ready, the aggregated state is Ready;
  243. // - Else if at least one SubConn in Connecting, the aggregated state is Connecting;
  244. // - Else the aggregated state is TransientFailure.
  245. //
  246. // Idle and Shutdown are not considered.
  247. func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State {
  248. // Update counters.
  249. for idx, state := range []connectivity.State{oldState, newState} {
  250. updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
  251. switch state {
  252. case connectivity.Ready:
  253. cse.numReady += updateVal
  254. case connectivity.Connecting:
  255. cse.numConnecting += updateVal
  256. case connectivity.TransientFailure:
  257. cse.numTransientFailure += updateVal
  258. }
  259. }
  260. // Evaluate.
  261. if cse.numReady > 0 {
  262. return connectivity.Ready
  263. }
  264. if cse.numConnecting > 0 {
  265. return connectivity.Connecting
  266. }
  267. return connectivity.TransientFailure
  268. }