retry_interceptor.go 12 KB

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