retry_interceptor.go 13 KB

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