retry_interceptor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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/api/v3/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(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. c.GetLogger().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. c.GetLogger().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 c.shouldRefreshToken(lastErr, callOpts) {
  72. gterr := c.refreshToken(ctx)
  73. if gterr != nil {
  74. c.GetLogger().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(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. c.GetLogger().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. c.GetLogger().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. // shouldRefreshToken checks whether there's a need to refresh the token based on the error and callOptions,
  139. // and returns a boolean value.
  140. func (c *Client) shouldRefreshToken(err error, callOpts *options) bool {
  141. if rpctypes.Error(err) == rpctypes.ErrUserEmpty {
  142. // refresh the token when username, password is present but the server returns ErrUserEmpty
  143. // which is possible when the client token is cleared somehow
  144. return c.authTokenBundle != nil // equal to c.Username != "" && c.Password != ""
  145. }
  146. return callOpts.retryAuth &&
  147. (rpctypes.Error(err) == rpctypes.ErrInvalidAuthToken || rpctypes.Error(err) == rpctypes.ErrAuthOldRevision)
  148. }
  149. func (c *Client) refreshToken(ctx context.Context) error {
  150. if c.authTokenBundle == nil {
  151. // c.authTokenBundle will be initialized only when
  152. // c.Username != "" && c.Password != "".
  153. //
  154. // When users use the TLS CommonName based authentication, the
  155. // authTokenBundle is always nil. But it's possible for the clients
  156. // to get `rpctypes.ErrAuthOldRevision` response when the clients
  157. // concurrently modify auth data (e.g, addUser, deleteUser etc.).
  158. // In this case, there is no need to refresh the token; instead the
  159. // clients just need to retry the operations (e.g. Put, Delete etc).
  160. return nil
  161. }
  162. // clear auth token before refreshing it.
  163. c.authTokenBundle.UpdateAuthToken("")
  164. return c.getToken(ctx)
  165. }
  166. // type serverStreamingRetryingStream is the implementation of grpc.ClientStream that acts as a
  167. // proxy to the underlying call. If any of the RecvMsg() calls fail, it will try to reestablish
  168. // a new ClientStream according to the retry policy.
  169. type serverStreamingRetryingStream struct {
  170. grpc.ClientStream
  171. client *Client
  172. bufferedSends []interface{} // single message that the client can sen
  173. receivedGood bool // indicates whether any prior receives were successful
  174. wasClosedSend bool // indicates that CloseSend was closed
  175. ctx context.Context
  176. callOpts *options
  177. streamerCall func(ctx context.Context) (grpc.ClientStream, error)
  178. mu sync.RWMutex
  179. }
  180. func (s *serverStreamingRetryingStream) setStream(clientStream grpc.ClientStream) {
  181. s.mu.Lock()
  182. s.ClientStream = clientStream
  183. s.mu.Unlock()
  184. }
  185. func (s *serverStreamingRetryingStream) getStream() grpc.ClientStream {
  186. s.mu.RLock()
  187. defer s.mu.RUnlock()
  188. return s.ClientStream
  189. }
  190. func (s *serverStreamingRetryingStream) SendMsg(m interface{}) error {
  191. s.mu.Lock()
  192. s.bufferedSends = append(s.bufferedSends, m)
  193. s.mu.Unlock()
  194. return s.getStream().SendMsg(m)
  195. }
  196. func (s *serverStreamingRetryingStream) CloseSend() error {
  197. s.mu.Lock()
  198. s.wasClosedSend = true
  199. s.mu.Unlock()
  200. return s.getStream().CloseSend()
  201. }
  202. func (s *serverStreamingRetryingStream) Header() (metadata.MD, error) {
  203. return s.getStream().Header()
  204. }
  205. func (s *serverStreamingRetryingStream) Trailer() metadata.MD {
  206. return s.getStream().Trailer()
  207. }
  208. func (s *serverStreamingRetryingStream) RecvMsg(m interface{}) error {
  209. attemptRetry, lastErr := s.receiveMsgAndIndicateRetry(m)
  210. if !attemptRetry {
  211. return lastErr // success or hard failure
  212. }
  213. // We start off from attempt 1, because zeroth was already made on normal SendMsg().
  214. for attempt := uint(1); attempt < s.callOpts.max; attempt++ {
  215. if err := waitRetryBackoff(s.ctx, attempt, s.callOpts); err != nil {
  216. return err
  217. }
  218. newStream, err := s.reestablishStreamAndResendBuffer(s.ctx)
  219. if err != nil {
  220. s.client.lg.Error("failed reestablishStreamAndResendBuffer", zap.Error(err))
  221. return err // TODO(mwitkow): Maybe dial and transport errors should be retriable?
  222. }
  223. s.setStream(newStream)
  224. s.client.lg.Warn("retrying RecvMsg", zap.Error(lastErr))
  225. attemptRetry, lastErr = s.receiveMsgAndIndicateRetry(m)
  226. if !attemptRetry {
  227. return lastErr
  228. }
  229. }
  230. return lastErr
  231. }
  232. func (s *serverStreamingRetryingStream) receiveMsgAndIndicateRetry(m interface{}) (bool, error) {
  233. s.mu.RLock()
  234. wasGood := s.receivedGood
  235. s.mu.RUnlock()
  236. err := s.getStream().RecvMsg(m)
  237. if err == nil || err == io.EOF {
  238. s.mu.Lock()
  239. s.receivedGood = true
  240. s.mu.Unlock()
  241. return false, err
  242. } else if wasGood {
  243. // previous RecvMsg in the stream succeeded, no retry logic should interfere
  244. return false, err
  245. }
  246. if isContextError(err) {
  247. if s.ctx.Err() != nil {
  248. return false, err
  249. }
  250. // its the callCtx deadline or cancellation, in which case try again.
  251. return true, err
  252. }
  253. if s.client.shouldRefreshToken(err, s.callOpts) {
  254. gterr := s.client.refreshToken(s.ctx)
  255. if gterr != nil {
  256. s.client.lg.Warn("retry failed to fetch new auth token", zap.Error(gterr))
  257. return false, err // return the original error for simplicity
  258. }
  259. return true, err
  260. }
  261. return isSafeRetry(s.client.lg, err, s.callOpts), err
  262. }
  263. func (s *serverStreamingRetryingStream) reestablishStreamAndResendBuffer(callCtx context.Context) (grpc.ClientStream, error) {
  264. s.mu.RLock()
  265. bufferedSends := s.bufferedSends
  266. s.mu.RUnlock()
  267. newStream, err := s.streamerCall(callCtx)
  268. if err != nil {
  269. return nil, err
  270. }
  271. for _, msg := range bufferedSends {
  272. if err := newStream.SendMsg(msg); err != nil {
  273. return nil, err
  274. }
  275. }
  276. if err := newStream.CloseSend(); err != nil {
  277. return nil, err
  278. }
  279. return newStream, nil
  280. }
  281. func waitRetryBackoff(ctx context.Context, attempt uint, callOpts *options) error {
  282. waitTime := time.Duration(0)
  283. if attempt > 0 {
  284. waitTime = callOpts.backoffFunc(attempt)
  285. }
  286. if waitTime > 0 {
  287. timer := time.NewTimer(waitTime)
  288. select {
  289. case <-ctx.Done():
  290. timer.Stop()
  291. return contextErrToGrpcErr(ctx.Err())
  292. case <-timer.C:
  293. }
  294. }
  295. return nil
  296. }
  297. // isSafeRetry returns "true", if request is safe for retry with the given error.
  298. func isSafeRetry(lg *zap.Logger, err error, callOpts *options) bool {
  299. if isContextError(err) {
  300. return false
  301. }
  302. switch callOpts.retryPolicy {
  303. case repeatable:
  304. return isSafeRetryImmutableRPC(err)
  305. case nonRepeatable:
  306. return isSafeRetryMutableRPC(err)
  307. default:
  308. lg.Warn("unrecognized retry policy", zap.String("retryPolicy", callOpts.retryPolicy.String()))
  309. return false
  310. }
  311. }
  312. func isContextError(err error) bool {
  313. return status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Canceled
  314. }
  315. func contextErrToGrpcErr(err error) error {
  316. switch err {
  317. case context.DeadlineExceeded:
  318. return status.Errorf(codes.DeadlineExceeded, err.Error())
  319. case context.Canceled:
  320. return status.Errorf(codes.Canceled, err.Error())
  321. default:
  322. return status.Errorf(codes.Unknown, err.Error())
  323. }
  324. }
  325. var (
  326. defaultOptions = &options{
  327. retryPolicy: nonRepeatable,
  328. max: 0, // disable
  329. backoffFunc: backoffLinearWithJitter(50*time.Millisecond /*jitter*/, 0.10),
  330. retryAuth: true,
  331. }
  332. )
  333. // backoffFunc denotes a family of functions that control the backoff duration between call retries.
  334. //
  335. // They are called with an identifier of the attempt, and should return a time the system client should
  336. // hold off for. If the time returned is longer than the `context.Context.Deadline` of the request
  337. // the deadline of the request takes precedence and the wait will be interrupted before proceeding
  338. // with the next iteration.
  339. type backoffFunc func(attempt uint) time.Duration
  340. // withRetryPolicy sets the retry policy of this call.
  341. func withRetryPolicy(rp retryPolicy) retryOption {
  342. return retryOption{applyFunc: func(o *options) {
  343. o.retryPolicy = rp
  344. }}
  345. }
  346. // withMax sets the maximum number of retries on this call, or this interceptor.
  347. func withMax(maxRetries uint) retryOption {
  348. return retryOption{applyFunc: func(o *options) {
  349. o.max = maxRetries
  350. }}
  351. }
  352. // WithBackoff sets the `BackoffFunc `used to control time between retries.
  353. func withBackoff(bf backoffFunc) retryOption {
  354. return retryOption{applyFunc: func(o *options) {
  355. o.backoffFunc = bf
  356. }}
  357. }
  358. type options struct {
  359. retryPolicy retryPolicy
  360. max uint
  361. backoffFunc backoffFunc
  362. retryAuth bool
  363. }
  364. // retryOption is a grpc.CallOption that is local to clientv3's retry interceptor.
  365. type retryOption struct {
  366. grpc.EmptyCallOption // make sure we implement private after() and before() fields so we don't panic.
  367. applyFunc func(opt *options)
  368. }
  369. func reuseOrNewWithCallOptions(opt *options, retryOptions []retryOption) *options {
  370. if len(retryOptions) == 0 {
  371. return opt
  372. }
  373. optCopy := &options{}
  374. *optCopy = *opt
  375. for _, f := range retryOptions {
  376. f.applyFunc(optCopy)
  377. }
  378. return optCopy
  379. }
  380. func filterCallOptions(callOptions []grpc.CallOption) (grpcOptions []grpc.CallOption, retryOptions []retryOption) {
  381. for _, opt := range callOptions {
  382. if co, ok := opt.(retryOption); ok {
  383. retryOptions = append(retryOptions, co)
  384. } else {
  385. grpcOptions = append(grpcOptions, opt)
  386. }
  387. }
  388. return grpcOptions, retryOptions
  389. }
  390. // BackoffLinearWithJitter waits a set period of time, allowing for jitter (fractional adjustment).
  391. //
  392. // For example waitBetween=1s and jitter=0.10 can generate waits between 900ms and 1100ms.
  393. func backoffLinearWithJitter(waitBetween time.Duration, jitterFraction float64) backoffFunc {
  394. return func(attempt uint) time.Duration {
  395. return jitterUp(waitBetween, jitterFraction)
  396. }
  397. }