picker_wrapper.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 grpc
  19. import (
  20. "context"
  21. "io"
  22. "sync"
  23. "google.golang.org/grpc/balancer"
  24. "google.golang.org/grpc/codes"
  25. "google.golang.org/grpc/internal/channelz"
  26. istatus "google.golang.org/grpc/internal/status"
  27. "google.golang.org/grpc/internal/transport"
  28. "google.golang.org/grpc/stats"
  29. "google.golang.org/grpc/status"
  30. )
  31. // pickerWrapper is a wrapper of balancer.Picker. It blocks on certain pick
  32. // actions and unblock when there's a picker update.
  33. type pickerWrapper struct {
  34. mu sync.Mutex
  35. done bool
  36. blockingCh chan struct{}
  37. picker balancer.Picker
  38. statsHandlers []stats.Handler // to record blocking picker calls
  39. }
  40. func newPickerWrapper(statsHandlers []stats.Handler) *pickerWrapper {
  41. return &pickerWrapper{
  42. blockingCh: make(chan struct{}),
  43. statsHandlers: statsHandlers,
  44. }
  45. }
  46. // updatePicker is called by UpdateBalancerState. It unblocks all blocked pick.
  47. func (pw *pickerWrapper) updatePicker(p balancer.Picker) {
  48. pw.mu.Lock()
  49. if pw.done {
  50. pw.mu.Unlock()
  51. return
  52. }
  53. pw.picker = p
  54. // pw.blockingCh should never be nil.
  55. close(pw.blockingCh)
  56. pw.blockingCh = make(chan struct{})
  57. pw.mu.Unlock()
  58. }
  59. // doneChannelzWrapper performs the following:
  60. // - increments the calls started channelz counter
  61. // - wraps the done function in the passed in result to increment the calls
  62. // failed or calls succeeded channelz counter before invoking the actual
  63. // done function.
  64. func doneChannelzWrapper(acbw *acBalancerWrapper, result *balancer.PickResult) {
  65. ac := acbw.ac
  66. ac.incrCallsStarted()
  67. done := result.Done
  68. result.Done = func(b balancer.DoneInfo) {
  69. if b.Err != nil && b.Err != io.EOF {
  70. ac.incrCallsFailed()
  71. } else {
  72. ac.incrCallsSucceeded()
  73. }
  74. if done != nil {
  75. done(b)
  76. }
  77. }
  78. }
  79. // pick returns the transport that will be used for the RPC.
  80. // It may block in the following cases:
  81. // - there's no picker
  82. // - the current picker returns ErrNoSubConnAvailable
  83. // - the current picker returns other errors and failfast is false.
  84. // - the subConn returned by the current picker is not READY
  85. // When one of these situations happens, pick blocks until the picker gets updated.
  86. func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer.PickInfo) (transport.ClientTransport, balancer.PickResult, error) {
  87. var ch chan struct{}
  88. var lastPickErr error
  89. for {
  90. pw.mu.Lock()
  91. if pw.done {
  92. pw.mu.Unlock()
  93. return nil, balancer.PickResult{}, ErrClientConnClosing
  94. }
  95. if pw.picker == nil {
  96. ch = pw.blockingCh
  97. }
  98. if ch == pw.blockingCh {
  99. // This could happen when either:
  100. // - pw.picker is nil (the previous if condition), or
  101. // - has called pick on the current picker.
  102. pw.mu.Unlock()
  103. select {
  104. case <-ctx.Done():
  105. var errStr string
  106. if lastPickErr != nil {
  107. errStr = "latest balancer error: " + lastPickErr.Error()
  108. } else {
  109. errStr = ctx.Err().Error()
  110. }
  111. switch ctx.Err() {
  112. case context.DeadlineExceeded:
  113. return nil, balancer.PickResult{}, status.Error(codes.DeadlineExceeded, errStr)
  114. case context.Canceled:
  115. return nil, balancer.PickResult{}, status.Error(codes.Canceled, errStr)
  116. }
  117. case <-ch:
  118. }
  119. continue
  120. }
  121. // If the channel is set, it means that the pick call had to wait for a
  122. // new picker at some point. Either it's the first iteration and this
  123. // function received the first picker, or a picker errored with
  124. // ErrNoSubConnAvailable or errored with failfast set to false, which
  125. // will trigger a continue to the next iteration. In the first case this
  126. // conditional will hit if this call had to block (the channel is set).
  127. // In the second case, the only way it will get to this conditional is
  128. // if there is a new picker.
  129. if ch != nil {
  130. for _, sh := range pw.statsHandlers {
  131. sh.HandleRPC(ctx, &stats.PickerUpdated{})
  132. }
  133. }
  134. ch = pw.blockingCh
  135. p := pw.picker
  136. pw.mu.Unlock()
  137. pickResult, err := p.Pick(info)
  138. if err != nil {
  139. if err == balancer.ErrNoSubConnAvailable {
  140. continue
  141. }
  142. if st, ok := status.FromError(err); ok {
  143. // Status error: end the RPC unconditionally with this status.
  144. // First restrict the code to the list allowed by gRFC A54.
  145. if istatus.IsRestrictedControlPlaneCode(st) {
  146. err = status.Errorf(codes.Internal, "received picker error with illegal status: %v", err)
  147. }
  148. return nil, balancer.PickResult{}, dropError{error: err}
  149. }
  150. // For all other errors, wait for ready RPCs should block and other
  151. // RPCs should fail with unavailable.
  152. if !failfast {
  153. lastPickErr = err
  154. continue
  155. }
  156. return nil, balancer.PickResult{}, status.Error(codes.Unavailable, err.Error())
  157. }
  158. acbw, ok := pickResult.SubConn.(*acBalancerWrapper)
  159. if !ok {
  160. logger.Errorf("subconn returned from pick is type %T, not *acBalancerWrapper", pickResult.SubConn)
  161. continue
  162. }
  163. if t := acbw.ac.getReadyTransport(); t != nil {
  164. if channelz.IsOn() {
  165. doneChannelzWrapper(acbw, &pickResult)
  166. return t, pickResult, nil
  167. }
  168. return t, pickResult, nil
  169. }
  170. if pickResult.Done != nil {
  171. // Calling done with nil error, no bytes sent and no bytes received.
  172. // DoneInfo with default value works.
  173. pickResult.Done(balancer.DoneInfo{})
  174. }
  175. logger.Infof("blockingPicker: the picked transport is not ready, loop back to repick")
  176. // If ok == false, ac.state is not READY.
  177. // A valid picker always returns READY subConn. This means the state of ac
  178. // just changed, and picker will be updated shortly.
  179. // continue back to the beginning of the for loop to repick.
  180. }
  181. }
  182. func (pw *pickerWrapper) close() {
  183. pw.mu.Lock()
  184. defer pw.mu.Unlock()
  185. if pw.done {
  186. return
  187. }
  188. pw.done = true
  189. close(pw.blockingCh)
  190. }
  191. // reset clears the pickerWrapper and prepares it for being used again when idle
  192. // mode is exited.
  193. func (pw *pickerWrapper) reset() {
  194. pw.mu.Lock()
  195. defer pw.mu.Unlock()
  196. if pw.done {
  197. return
  198. }
  199. pw.blockingCh = make(chan struct{})
  200. }
  201. // dropError is a wrapper error that indicates the LB policy wishes to drop the
  202. // RPC and not retry it.
  203. type dropError struct {
  204. error
  205. }