retry_interceptor.go 13 KB

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