balancer.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 base
  19. import (
  20. "errors"
  21. "fmt"
  22. "google.golang.org/grpc/balancer"
  23. "google.golang.org/grpc/connectivity"
  24. "google.golang.org/grpc/grpclog"
  25. "google.golang.org/grpc/resolver"
  26. )
  27. var logger = grpclog.Component("balancer")
  28. type baseBuilder struct {
  29. name string
  30. pickerBuilder PickerBuilder
  31. config Config
  32. }
  33. func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer {
  34. bal := &baseBalancer{
  35. cc: cc,
  36. pickerBuilder: bb.pickerBuilder,
  37. subConns: resolver.NewAddressMap(),
  38. scStates: make(map[balancer.SubConn]connectivity.State),
  39. csEvltr: &balancer.ConnectivityStateEvaluator{},
  40. config: bb.config,
  41. state: connectivity.Connecting,
  42. }
  43. // Initialize picker to a picker that always returns
  44. // ErrNoSubConnAvailable, because when state of a SubConn changes, we
  45. // may call UpdateState with this picker.
  46. bal.picker = NewErrPicker(balancer.ErrNoSubConnAvailable)
  47. return bal
  48. }
  49. func (bb *baseBuilder) Name() string {
  50. return bb.name
  51. }
  52. type baseBalancer struct {
  53. cc balancer.ClientConn
  54. pickerBuilder PickerBuilder
  55. csEvltr *balancer.ConnectivityStateEvaluator
  56. state connectivity.State
  57. subConns *resolver.AddressMap
  58. scStates map[balancer.SubConn]connectivity.State
  59. picker balancer.Picker
  60. config Config
  61. resolverErr error // the last error reported by the resolver; cleared on successful resolution
  62. connErr error // the last connection error; cleared upon leaving TransientFailure
  63. }
  64. func (b *baseBalancer) ResolverError(err error) {
  65. b.resolverErr = err
  66. if b.subConns.Len() == 0 {
  67. b.state = connectivity.TransientFailure
  68. }
  69. if b.state != connectivity.TransientFailure {
  70. // The picker will not change since the balancer does not currently
  71. // report an error.
  72. return
  73. }
  74. b.regeneratePicker()
  75. b.cc.UpdateState(balancer.State{
  76. ConnectivityState: b.state,
  77. Picker: b.picker,
  78. })
  79. }
  80. func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error {
  81. // TODO: handle s.ResolverState.ServiceConfig?
  82. if logger.V(2) {
  83. logger.Info("base.baseBalancer: got new ClientConn state: ", s)
  84. }
  85. // Successful resolution; clear resolver error and ensure we return nil.
  86. b.resolverErr = nil
  87. // addrsSet is the set converted from addrs, it's used for quick lookup of an address.
  88. addrsSet := resolver.NewAddressMap()
  89. for _, a := range s.ResolverState.Addresses {
  90. addrsSet.Set(a, nil)
  91. if _, ok := b.subConns.Get(a); !ok {
  92. // a is a new address (not existing in b.subConns).
  93. var sc balancer.SubConn
  94. opts := balancer.NewSubConnOptions{
  95. HealthCheckEnabled: b.config.HealthCheck,
  96. StateListener: func(scs balancer.SubConnState) { b.updateSubConnState(sc, scs) },
  97. }
  98. sc, err := b.cc.NewSubConn([]resolver.Address{a}, opts)
  99. if err != nil {
  100. logger.Warningf("base.baseBalancer: failed to create new SubConn: %v", err)
  101. continue
  102. }
  103. b.subConns.Set(a, sc)
  104. b.scStates[sc] = connectivity.Idle
  105. b.csEvltr.RecordTransition(connectivity.Shutdown, connectivity.Idle)
  106. sc.Connect()
  107. }
  108. }
  109. for _, a := range b.subConns.Keys() {
  110. sci, _ := b.subConns.Get(a)
  111. sc := sci.(balancer.SubConn)
  112. // a was removed by resolver.
  113. if _, ok := addrsSet.Get(a); !ok {
  114. sc.Shutdown()
  115. b.subConns.Delete(a)
  116. // Keep the state of this sc in b.scStates until sc's state becomes Shutdown.
  117. // The entry will be deleted in updateSubConnState.
  118. }
  119. }
  120. // If resolver state contains no addresses, return an error so ClientConn
  121. // will trigger re-resolve. Also records this as an resolver error, so when
  122. // the overall state turns transient failure, the error message will have
  123. // the zero address information.
  124. if len(s.ResolverState.Addresses) == 0 {
  125. b.ResolverError(errors.New("produced zero addresses"))
  126. return balancer.ErrBadResolverState
  127. }
  128. b.regeneratePicker()
  129. b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.picker})
  130. return nil
  131. }
  132. // mergeErrors builds an error from the last connection error and the last
  133. // resolver error. Must only be called if b.state is TransientFailure.
  134. func (b *baseBalancer) mergeErrors() error {
  135. // connErr must always be non-nil unless there are no SubConns, in which
  136. // case resolverErr must be non-nil.
  137. if b.connErr == nil {
  138. return fmt.Errorf("last resolver error: %v", b.resolverErr)
  139. }
  140. if b.resolverErr == nil {
  141. return fmt.Errorf("last connection error: %v", b.connErr)
  142. }
  143. return fmt.Errorf("last connection error: %v; last resolver error: %v", b.connErr, b.resolverErr)
  144. }
  145. // regeneratePicker takes a snapshot of the balancer, and generates a picker
  146. // from it. The picker is
  147. // - errPicker if the balancer is in TransientFailure,
  148. // - built by the pickerBuilder with all READY SubConns otherwise.
  149. func (b *baseBalancer) regeneratePicker() {
  150. if b.state == connectivity.TransientFailure {
  151. b.picker = NewErrPicker(b.mergeErrors())
  152. return
  153. }
  154. readySCs := make(map[balancer.SubConn]SubConnInfo)
  155. // Filter out all ready SCs from full subConn map.
  156. for _, addr := range b.subConns.Keys() {
  157. sci, _ := b.subConns.Get(addr)
  158. sc := sci.(balancer.SubConn)
  159. if st, ok := b.scStates[sc]; ok && st == connectivity.Ready {
  160. readySCs[sc] = SubConnInfo{Address: addr}
  161. }
  162. }
  163. b.picker = b.pickerBuilder.Build(PickerBuildInfo{ReadySCs: readySCs})
  164. }
  165. // UpdateSubConnState is a nop because a StateListener is always set in NewSubConn.
  166. func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) {
  167. logger.Errorf("base.baseBalancer: UpdateSubConnState(%v, %+v) called unexpectedly", sc, state)
  168. }
  169. func (b *baseBalancer) updateSubConnState(sc balancer.SubConn, state balancer.SubConnState) {
  170. s := state.ConnectivityState
  171. if logger.V(2) {
  172. logger.Infof("base.baseBalancer: handle SubConn state change: %p, %v", sc, s)
  173. }
  174. oldS, ok := b.scStates[sc]
  175. if !ok {
  176. if logger.V(2) {
  177. logger.Infof("base.baseBalancer: got state changes for an unknown SubConn: %p, %v", sc, s)
  178. }
  179. return
  180. }
  181. if oldS == connectivity.TransientFailure &&
  182. (s == connectivity.Connecting || s == connectivity.Idle) {
  183. // Once a subconn enters TRANSIENT_FAILURE, ignore subsequent IDLE or
  184. // CONNECTING transitions to prevent the aggregated state from being
  185. // always CONNECTING when many backends exist but are all down.
  186. if s == connectivity.Idle {
  187. sc.Connect()
  188. }
  189. return
  190. }
  191. b.scStates[sc] = s
  192. switch s {
  193. case connectivity.Idle:
  194. sc.Connect()
  195. case connectivity.Shutdown:
  196. // When an address was removed by resolver, b called Shutdown but kept
  197. // the sc's state in scStates. Remove state for this sc here.
  198. delete(b.scStates, sc)
  199. case connectivity.TransientFailure:
  200. // Save error to be reported via picker.
  201. b.connErr = state.ConnectionError
  202. }
  203. b.state = b.csEvltr.RecordTransition(oldS, s)
  204. // Regenerate picker when one of the following happens:
  205. // - this sc entered or left ready
  206. // - the aggregated state of balancer is TransientFailure
  207. // (may need to update error message)
  208. if (s == connectivity.Ready) != (oldS == connectivity.Ready) ||
  209. b.state == connectivity.TransientFailure {
  210. b.regeneratePicker()
  211. }
  212. b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.picker})
  213. }
  214. // Close is a nop because base balancer doesn't have internal state to clean up,
  215. // and it doesn't need to call Shutdown for the SubConns.
  216. func (b *baseBalancer) Close() {
  217. }
  218. // ExitIdle is a nop because the base balancer attempts to stay connected to
  219. // all SubConns at all times.
  220. func (b *baseBalancer) ExitIdle() {
  221. }
  222. // NewErrPicker returns a Picker that always returns err on Pick().
  223. func NewErrPicker(err error) balancer.Picker {
  224. return &errPicker{err: err}
  225. }
  226. // NewErrPickerV2 is temporarily defined for backward compatibility reasons.
  227. //
  228. // Deprecated: use NewErrPicker instead.
  229. var NewErrPickerV2 = NewErrPicker
  230. type errPicker struct {
  231. err error // Pick() always returns this err.
  232. }
  233. func (p *errPicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
  234. return balancer.PickResult{}, p.err
  235. }