retry_interceptor.go 12 KB

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