retry_interceptor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Based on github.com/grpc-ecosystem/go-grpc-middleware/retry, but modified to support the more
  15. // fine grained error checking required by write-at-most-once retry semantics of etcd.
  16. package clientv3
  17. import (
  18. "context"
  19. "io"
  20. "sync"
  21. "time"
  22. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  23. "go.uber.org/zap"
  24. "google.golang.org/grpc"
  25. "google.golang.org/grpc/codes"
  26. "google.golang.org/grpc/metadata"
  27. )
  28. // unaryClientInterceptor returns a new retrying unary client interceptor.
  29. //
  30. // The default configuration of the interceptor is to not retry *at all*. This behaviour can be
  31. // changed through options (e.g. WithMax) on creation of the interceptor or on call (through grpc.CallOptions).
  32. func (c *Client) unaryClientInterceptor(logger *zap.Logger, optFuncs ...retryOption) grpc.UnaryClientInterceptor {
  33. intOpts := reuseOrNewWithCallOptions(defaultOptions, optFuncs)
  34. return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  35. grpcOpts, retryOpts := filterCallOptions(opts)
  36. callOpts := reuseOrNewWithCallOptions(intOpts, retryOpts)
  37. // short circuit for simplicity, and avoiding allocations.
  38. if callOpts.max == 0 {
  39. return invoker(ctx, method, req, reply, cc, grpcOpts...)
  40. }
  41. var lastErr error
  42. for attempt := uint(0); attempt < callOpts.max; attempt++ {
  43. if err := waitRetryBackoff(ctx, attempt, callOpts); err != nil {
  44. return err
  45. }
  46. lastErr = invoker(ctx, method, req, reply, cc, grpcOpts...)
  47. logger.Info("retry unary intercept", zap.Uint("attempt", attempt), zap.Error(lastErr))
  48. if lastErr == nil {
  49. return nil
  50. }
  51. if isContextError(lastErr) {
  52. if ctx.Err() != nil {
  53. // its the context deadline or cancellation.
  54. return lastErr
  55. }
  56. // its the callCtx deadline or cancellation, in which case try again.
  57. continue
  58. }
  59. if callOpts.retryAuth && rpctypes.Error(lastErr) == rpctypes.ErrInvalidAuthToken {
  60. gterr := c.getToken(ctx)
  61. if gterr != nil {
  62. logger.Info("retry failed to fetch new auth token", zap.Error(gterr))
  63. return lastErr // return the original error for simplicity
  64. }
  65. continue
  66. }
  67. if !isSafeRetry(c.lg, lastErr, callOpts) {
  68. return lastErr
  69. }
  70. }
  71. return lastErr
  72. }
  73. }
  74. // streamClientInterceptor returns a new retrying stream client interceptor for server side streaming calls.
  75. //
  76. // The default configuration of the interceptor is to not retry *at all*. This behaviour can be
  77. // changed through options (e.g. WithMax) on creation of the interceptor or on call (through grpc.CallOptions).
  78. //
  79. // Retry logic is available *only for ServerStreams*, i.e. 1:n streams, as the internal logic needs
  80. // to buffer the messages sent by the client. If retry is enabled on any other streams (ClientStreams,
  81. // BidiStreams), the retry interceptor will fail the call.
  82. func (c *Client) streamClientInterceptor(logger *zap.Logger, optFuncs ...retryOption) grpc.StreamClientInterceptor {
  83. intOpts := reuseOrNewWithCallOptions(defaultOptions, optFuncs)
  84. return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
  85. grpcOpts, retryOpts := filterCallOptions(opts)
  86. callOpts := reuseOrNewWithCallOptions(intOpts, retryOpts)
  87. // short circuit for simplicity, and avoiding allocations.
  88. if callOpts.max == 0 {
  89. return streamer(ctx, desc, cc, method, grpcOpts...)
  90. }
  91. if desc.ClientStreams {
  92. return nil, grpc.Errorf(codes.Unimplemented, "clientv3/retry_interceptor: cannot retry on ClientStreams, set Disable()")
  93. }
  94. newStreamer, err := streamer(ctx, desc, cc, method, grpcOpts...)
  95. logger.Info("retry stream intercept", zap.Error(err))
  96. if err != nil {
  97. // TODO(mwitkow): Maybe dial and transport errors should be retriable?
  98. return nil, err
  99. }
  100. retryingStreamer := &serverStreamingRetryingStream{
  101. client: c,
  102. ClientStream: newStreamer,
  103. callOpts: callOpts,
  104. ctx: ctx,
  105. streamerCall: func(ctx context.Context) (grpc.ClientStream, error) {
  106. return streamer(ctx, desc, cc, method, grpcOpts...)
  107. },
  108. }
  109. return retryingStreamer, nil
  110. }
  111. }
  112. // type serverStreamingRetryingStream is the implementation of grpc.ClientStream that acts as a
  113. // proxy to the underlying call. If any of the RecvMsg() calls fail, it will try to reestablish
  114. // a new ClientStream according to the retry policy.
  115. type serverStreamingRetryingStream struct {
  116. grpc.ClientStream
  117. client *Client
  118. bufferedSends []interface{} // single message that the client can sen
  119. receivedGood bool // indicates whether any prior receives were successful
  120. wasClosedSend bool // indicates that CloseSend was closed
  121. ctx context.Context
  122. callOpts *options
  123. streamerCall func(ctx context.Context) (grpc.ClientStream, error)
  124. mu sync.RWMutex
  125. }
  126. func (s *serverStreamingRetryingStream) setStream(clientStream grpc.ClientStream) {
  127. s.mu.Lock()
  128. s.ClientStream = clientStream
  129. s.mu.Unlock()
  130. }
  131. func (s *serverStreamingRetryingStream) getStream() grpc.ClientStream {
  132. s.mu.RLock()
  133. defer s.mu.RUnlock()
  134. return s.ClientStream
  135. }
  136. func (s *serverStreamingRetryingStream) SendMsg(m interface{}) error {
  137. s.mu.Lock()
  138. s.bufferedSends = append(s.bufferedSends, m)
  139. s.mu.Unlock()
  140. return s.getStream().SendMsg(m)
  141. }
  142. func (s *serverStreamingRetryingStream) CloseSend() error {
  143. s.mu.Lock()
  144. s.wasClosedSend = true
  145. s.mu.Unlock()
  146. return s.getStream().CloseSend()
  147. }
  148. func (s *serverStreamingRetryingStream) Header() (metadata.MD, error) {
  149. return s.getStream().Header()
  150. }
  151. func (s *serverStreamingRetryingStream) Trailer() metadata.MD {
  152. return s.getStream().Trailer()
  153. }
  154. func (s *serverStreamingRetryingStream) RecvMsg(m interface{}) error {
  155. attemptRetry, lastErr := s.receiveMsgAndIndicateRetry(m)
  156. if !attemptRetry {
  157. return lastErr // success or hard failure
  158. }
  159. // We start off from attempt 1, because zeroth was already made on normal SendMsg().
  160. for attempt := uint(1); attempt < s.callOpts.max; attempt++ {
  161. if err := waitRetryBackoff(s.ctx, attempt, s.callOpts); err != nil {
  162. return err
  163. }
  164. newStream, err := s.reestablishStreamAndResendBuffer(s.ctx)
  165. if err != nil {
  166. // TODO(mwitkow): Maybe dial and transport errors should be retriable?
  167. return err
  168. }
  169. s.setStream(newStream)
  170. attemptRetry, lastErr = s.receiveMsgAndIndicateRetry(m)
  171. //fmt.Printf("Received message and indicate: %v %v\n", attemptRetry, lastErr)
  172. if !attemptRetry {
  173. return lastErr
  174. }
  175. }
  176. return lastErr
  177. }
  178. func (s *serverStreamingRetryingStream) receiveMsgAndIndicateRetry(m interface{}) (bool, error) {
  179. s.mu.RLock()
  180. wasGood := s.receivedGood
  181. s.mu.RUnlock()
  182. err := s.getStream().RecvMsg(m)
  183. if err == nil || err == io.EOF {
  184. s.mu.Lock()
  185. s.receivedGood = true
  186. s.mu.Unlock()
  187. return false, err
  188. } else if wasGood {
  189. // previous RecvMsg in the stream succeeded, no retry logic should interfere
  190. return false, err
  191. }
  192. if isContextError(err) {
  193. if s.ctx.Err() != nil {
  194. return false, err
  195. }
  196. // its the callCtx deadline or cancellation, in which case try again.
  197. return true, err
  198. }
  199. if s.callOpts.retryAuth && rpctypes.Error(err) == rpctypes.ErrInvalidAuthToken {
  200. gterr := s.client.getToken(s.ctx)
  201. if gterr != nil {
  202. s.client.lg.Info("retry failed to fetch new auth token", zap.Error(gterr))
  203. return false, err // return the original error for simplicity
  204. }
  205. return true, err
  206. }
  207. return isSafeRetry(s.client.lg, err, s.callOpts), err
  208. }
  209. func (s *serverStreamingRetryingStream) reestablishStreamAndResendBuffer(callCtx context.Context) (grpc.ClientStream, error) {
  210. s.mu.RLock()
  211. bufferedSends := s.bufferedSends
  212. s.mu.RUnlock()
  213. newStream, err := s.streamerCall(callCtx)
  214. if err != nil {
  215. return nil, err
  216. }
  217. for _, msg := range bufferedSends {
  218. if err := newStream.SendMsg(msg); err != nil {
  219. return nil, err
  220. }
  221. }
  222. if err := newStream.CloseSend(); err != nil {
  223. return nil, err
  224. }
  225. return newStream, nil
  226. }
  227. func waitRetryBackoff(ctx context.Context, attempt uint, callOpts *options) error {
  228. waitTime := time.Duration(0)
  229. if attempt > 0 {
  230. waitTime = callOpts.backoffFunc(attempt)
  231. }
  232. if waitTime > 0 {
  233. timer := time.NewTimer(waitTime)
  234. select {
  235. case <-ctx.Done():
  236. timer.Stop()
  237. return contextErrToGrpcErr(ctx.Err())
  238. case <-timer.C:
  239. }
  240. }
  241. return nil
  242. }
  243. // isSafeRetry returns "true", if request is safe for retry with the given error.
  244. func isSafeRetry(lg *zap.Logger, err error, callOpts *options) bool {
  245. if isContextError(err) {
  246. return false
  247. }
  248. switch callOpts.retryPolicy {
  249. case repeatable:
  250. return isSafeRetryImmutableRPC(err)
  251. case nonRepeatable:
  252. return isSafeRetryMutableRPC(err)
  253. default:
  254. lg.Warn("unrecognized retry policy", zap.String("retryPolicy", callOpts.retryPolicy.String()))
  255. return false
  256. }
  257. }
  258. func isContextError(err error) bool {
  259. return grpc.Code(err) == codes.DeadlineExceeded || grpc.Code(err) == codes.Canceled
  260. }
  261. func contextErrToGrpcErr(err error) error {
  262. switch err {
  263. case context.DeadlineExceeded:
  264. return grpc.Errorf(codes.DeadlineExceeded, err.Error())
  265. case context.Canceled:
  266. return grpc.Errorf(codes.Canceled, err.Error())
  267. default:
  268. return grpc.Errorf(codes.Unknown, err.Error())
  269. }
  270. }
  271. var (
  272. defaultOptions = &options{
  273. retryPolicy: nonRepeatable,
  274. max: 0, // disable
  275. backoffFunc: backoffLinearWithJitter(50*time.Millisecond /*jitter*/, 0.10),
  276. retryAuth: true,
  277. }
  278. )
  279. // backoffFunc denotes a family of functions that control the backoff duration between call retries.
  280. //
  281. // They are called with an identifier of the attempt, and should return a time the system client should
  282. // hold off for. If the time returned is longer than the `context.Context.Deadline` of the request
  283. // the deadline of the request takes precedence and the wait will be interrupted before proceeding
  284. // with the next iteration.
  285. type backoffFunc func(attempt uint) time.Duration
  286. // withRetryPolicy sets the retry policy of this call.
  287. func withRetryPolicy(rp retryPolicy) retryOption {
  288. return retryOption{applyFunc: func(o *options) {
  289. o.retryPolicy = rp
  290. }}
  291. }
  292. // withAuthRetry sets enables authentication retries.
  293. func withAuthRetry(retryAuth bool) retryOption {
  294. return retryOption{applyFunc: func(o *options) {
  295. o.retryAuth = retryAuth
  296. }}
  297. }
  298. // withMax sets the maximum number of retries on this call, or this interceptor.
  299. func withMax(maxRetries uint) retryOption {
  300. return retryOption{applyFunc: func(o *options) {
  301. o.max = maxRetries
  302. }}
  303. }
  304. // WithBackoff sets the `BackoffFunc `used to control time between retries.
  305. func withBackoff(bf backoffFunc) retryOption {
  306. return retryOption{applyFunc: func(o *options) {
  307. o.backoffFunc = bf
  308. }}
  309. }
  310. type options struct {
  311. retryPolicy retryPolicy
  312. max uint
  313. backoffFunc backoffFunc
  314. retryAuth bool
  315. }
  316. // retryOption is a grpc.CallOption that is local to clientv3's retry interceptor.
  317. type retryOption struct {
  318. grpc.EmptyCallOption // make sure we implement private after() and before() fields so we don't panic.
  319. applyFunc func(opt *options)
  320. }
  321. func reuseOrNewWithCallOptions(opt *options, retryOptions []retryOption) *options {
  322. if len(retryOptions) == 0 {
  323. return opt
  324. }
  325. optCopy := &options{}
  326. *optCopy = *opt
  327. for _, f := range retryOptions {
  328. f.applyFunc(optCopy)
  329. }
  330. return optCopy
  331. }
  332. func filterCallOptions(callOptions []grpc.CallOption) (grpcOptions []grpc.CallOption, retryOptions []retryOption) {
  333. for _, opt := range callOptions {
  334. if co, ok := opt.(retryOption); ok {
  335. retryOptions = append(retryOptions, co)
  336. } else {
  337. grpcOptions = append(grpcOptions, opt)
  338. }
  339. }
  340. return grpcOptions, retryOptions
  341. }
  342. // BackoffLinearWithJitter waits a set period of time, allowing for jitter (fractional adjustment).
  343. //
  344. // For example waitBetween=1s and jitter=0.10 can generate waits between 900ms and 1100ms.
  345. func backoffLinearWithJitter(waitBetween time.Duration, jitterFraction float64) backoffFunc {
  346. return func(attempt uint) time.Duration {
  347. return jitterUp(waitBetween, jitterFraction)
  348. }
  349. }