picker_wrapper.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. "fmt"
  22. "io"
  23. "sync"
  24. "google.golang.org/grpc/balancer"
  25. "google.golang.org/grpc/codes"
  26. "google.golang.org/grpc/grpclog"
  27. "google.golang.org/grpc/internal/channelz"
  28. "google.golang.org/grpc/internal/transport"
  29. "google.golang.org/grpc/status"
  30. )
  31. // v2PickerWrapper wraps a balancer.Picker while providing the
  32. // balancer.V2Picker API. It requires a pickerWrapper to generate errors
  33. // including the latest connectionError. To be deleted when balancer.Picker is
  34. // updated to the balancer.V2Picker API.
  35. type v2PickerWrapper struct {
  36. picker balancer.Picker
  37. connErr *connErr
  38. }
  39. func (v *v2PickerWrapper) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
  40. sc, done, err := v.picker.Pick(info.Ctx, info)
  41. if err != nil {
  42. if err == balancer.ErrTransientFailure {
  43. return balancer.PickResult{}, balancer.TransientFailureError(fmt.Errorf("%v, latest connection error: %v", err, v.connErr.connectionError()))
  44. }
  45. return balancer.PickResult{}, err
  46. }
  47. return balancer.PickResult{SubConn: sc, Done: done}, nil
  48. }
  49. // pickerWrapper is a wrapper of balancer.Picker. It blocks on certain pick
  50. // actions and unblock when there's a picker update.
  51. type pickerWrapper struct {
  52. mu sync.Mutex
  53. done bool
  54. blockingCh chan struct{}
  55. picker balancer.V2Picker
  56. // The latest connection error. TODO: remove when V1 picker is deprecated;
  57. // balancer should be responsible for providing the error.
  58. *connErr
  59. }
  60. type connErr struct {
  61. mu sync.Mutex
  62. err error
  63. }
  64. func (c *connErr) updateConnectionError(err error) {
  65. c.mu.Lock()
  66. c.err = err
  67. c.mu.Unlock()
  68. }
  69. func (c *connErr) connectionError() error {
  70. c.mu.Lock()
  71. err := c.err
  72. c.mu.Unlock()
  73. return err
  74. }
  75. func newPickerWrapper() *pickerWrapper {
  76. return &pickerWrapper{blockingCh: make(chan struct{}), connErr: &connErr{}}
  77. }
  78. // updatePicker is called by UpdateBalancerState. It unblocks all blocked pick.
  79. func (pw *pickerWrapper) updatePicker(p balancer.Picker) {
  80. pw.updatePickerV2(&v2PickerWrapper{picker: p, connErr: pw.connErr})
  81. }
  82. // updatePicker is called by UpdateBalancerState. It unblocks all blocked pick.
  83. func (pw *pickerWrapper) updatePickerV2(p balancer.V2Picker) {
  84. pw.mu.Lock()
  85. if pw.done {
  86. pw.mu.Unlock()
  87. return
  88. }
  89. pw.picker = p
  90. // pw.blockingCh should never be nil.
  91. close(pw.blockingCh)
  92. pw.blockingCh = make(chan struct{})
  93. pw.mu.Unlock()
  94. }
  95. func doneChannelzWrapper(acw *acBalancerWrapper, done func(balancer.DoneInfo)) func(balancer.DoneInfo) {
  96. acw.mu.Lock()
  97. ac := acw.ac
  98. acw.mu.Unlock()
  99. ac.incrCallsStarted()
  100. return func(b balancer.DoneInfo) {
  101. if b.Err != nil && b.Err != io.EOF {
  102. ac.incrCallsFailed()
  103. } else {
  104. ac.incrCallsSucceeded()
  105. }
  106. if done != nil {
  107. done(b)
  108. }
  109. }
  110. }
  111. // pick returns the transport that will be used for the RPC.
  112. // It may block in the following cases:
  113. // - there's no picker
  114. // - the current picker returns ErrNoSubConnAvailable
  115. // - the current picker returns other errors and failfast is false.
  116. // - the subConn returned by the current picker is not READY
  117. // When one of these situations happens, pick blocks until the picker gets updated.
  118. func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer.PickInfo) (transport.ClientTransport, func(balancer.DoneInfo), error) {
  119. var ch chan struct{}
  120. var lastPickErr error
  121. for {
  122. pw.mu.Lock()
  123. if pw.done {
  124. pw.mu.Unlock()
  125. return nil, nil, ErrClientConnClosing
  126. }
  127. if pw.picker == nil {
  128. ch = pw.blockingCh
  129. }
  130. if ch == pw.blockingCh {
  131. // This could happen when either:
  132. // - pw.picker is nil (the previous if condition), or
  133. // - has called pick on the current picker.
  134. pw.mu.Unlock()
  135. select {
  136. case <-ctx.Done():
  137. var errStr string
  138. if lastPickErr != nil {
  139. errStr = "latest balancer error: " + lastPickErr.Error()
  140. } else if connectionErr := pw.connectionError(); connectionErr != nil {
  141. errStr = "latest connection error: " + connectionErr.Error()
  142. } else {
  143. errStr = ctx.Err().Error()
  144. }
  145. switch ctx.Err() {
  146. case context.DeadlineExceeded:
  147. return nil, nil, status.Error(codes.DeadlineExceeded, errStr)
  148. case context.Canceled:
  149. return nil, nil, status.Error(codes.Canceled, errStr)
  150. }
  151. case <-ch:
  152. }
  153. continue
  154. }
  155. ch = pw.blockingCh
  156. p := pw.picker
  157. pw.mu.Unlock()
  158. pickResult, err := p.Pick(info)
  159. if err != nil {
  160. if err == balancer.ErrNoSubConnAvailable {
  161. continue
  162. }
  163. if tfe, ok := err.(interface{ IsTransientFailure() bool }); ok && tfe.IsTransientFailure() {
  164. if !failfast {
  165. lastPickErr = err
  166. continue
  167. }
  168. return nil, nil, status.Error(codes.Unavailable, err.Error())
  169. }
  170. if _, ok := status.FromError(err); ok {
  171. return nil, nil, err
  172. }
  173. // err is some other error.
  174. return nil, nil, status.Error(codes.Unknown, err.Error())
  175. }
  176. acw, ok := pickResult.SubConn.(*acBalancerWrapper)
  177. if !ok {
  178. grpclog.Error("subconn returned from pick is not *acBalancerWrapper")
  179. continue
  180. }
  181. if t, ok := acw.getAddrConn().getReadyTransport(); ok {
  182. if channelz.IsOn() {
  183. return t, doneChannelzWrapper(acw, pickResult.Done), nil
  184. }
  185. return t, pickResult.Done, nil
  186. }
  187. if pickResult.Done != nil {
  188. // Calling done with nil error, no bytes sent and no bytes received.
  189. // DoneInfo with default value works.
  190. pickResult.Done(balancer.DoneInfo{})
  191. }
  192. grpclog.Infof("blockingPicker: the picked transport is not ready, loop back to repick")
  193. // If ok == false, ac.state is not READY.
  194. // A valid picker always returns READY subConn. This means the state of ac
  195. // just changed, and picker will be updated shortly.
  196. // continue back to the beginning of the for loop to repick.
  197. }
  198. }
  199. func (pw *pickerWrapper) close() {
  200. pw.mu.Lock()
  201. defer pw.mu.Unlock()
  202. if pw.done {
  203. return
  204. }
  205. pw.done = true
  206. close(pw.blockingCh)
  207. }