-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
retry.go
421 lines (333 loc) · 12.1 KB
/
retry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package tfresource
import (
"context"
"errors"
"fmt"
"math/rand"
"sync"
"time"
"github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
tfawserr_sdkv2 "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-provider-aws/internal/errs"
)
// Retryable is a function that is used to decide if a function's error is retryable or not.
// The error argument can be `nil`.
// If the error is retryable, returns a bool value of `true` and an error (not necessarily the error passed as the argument).
// If the error is not retryable, returns a bool value of `false` and either no error (success state) or an error (not necessarily the error passed as the argument).
type Retryable func(error) (bool, error)
// RetryWhen retries the function `f` when the error it returns satisfies `retryable`.
// `f` is retried until `timeout` expires.
func RetryWhen(ctx context.Context, timeout time.Duration, f func() (interface{}, error), retryable Retryable) (interface{}, error) {
var output interface{}
err := Retry(ctx, timeout, func() *retry.RetryError {
var err error
var again bool
output, err = f()
again, err = retryable(err)
if again {
return retry.RetryableError(err)
}
if err != nil {
return retry.NonRetryableError(err)
}
return nil
})
if TimedOut(err) {
output, err = f()
}
if err != nil {
return nil, err
}
return output, nil
}
// RetryGWhen is the generic version of RetryWhen which obviates the need for a type
// assertion after the call. It retries the function `f` when the error it returns
// satisfies `retryable`. `f` is retried until `timeout` expires.
func RetryGWhen[T any](ctx context.Context, timeout time.Duration, f func() (T, error), retryable Retryable) (T, error) {
var output T
err := Retry(ctx, timeout, func() *retry.RetryError {
var err error
var again bool
output, err = f()
again, err = retryable(err)
if again {
return retry.RetryableError(err)
}
if err != nil {
return retry.NonRetryableError(err)
}
return nil
})
if TimedOut(err) {
output, err = f()
}
if err != nil {
var zero T
return zero, err
}
return output, nil
}
// RetryWhenAWSErrCodeEquals retries the specified function when it returns one of the specified AWS error codes.
func RetryWhenAWSErrCodeEquals(ctx context.Context, timeout time.Duration, f func() (interface{}, error), codes ...string) (interface{}, error) { // nosemgrep:ci.aws-in-func-name
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if tfawserr.ErrCodeEquals(err, codes...) || tfawserr_sdkv2.ErrCodeEquals(err, codes...) {
return true, err
}
return false, err
})
}
// RetryWhenAWSErrCodeContains retries the specified function when it returns an AWS error containing the specified code.
func RetryWhenAWSErrCodeContains(ctx context.Context, timeout time.Duration, f func() (interface{}, error), code string) (interface{}, error) { // nosemgrep:ci.aws-in-func-name
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if tfawserr.ErrCodeContains(err, code) || tfawserr_sdkv2.ErrCodeContains(err, code) {
return true, err
}
return false, err
})
}
// RetryWhenAWSErrMessageContains retries the specified function when it returns an AWS error containing the specified message.
func RetryWhenAWSErrMessageContains(ctx context.Context, timeout time.Duration, f func() (interface{}, error), code, message string) (interface{}, error) { // nosemgrep:ci.aws-in-func-name
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if tfawserr.ErrMessageContains(err, code, message) || tfawserr_sdkv2.ErrMessageContains(err, code, message) {
return true, err
}
return false, err
})
}
// RetryWhenMessageContains retries the specified function when it returns an error containing any of the specified messages.
func RetryWhenMessageContains(ctx context.Context, timeout time.Duration, f func() (interface{}, error), codes []string, messages []string) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
for i, message := range messages {
if tfawserr.ErrMessageContains(err, codes[i], message) || tfawserr_sdkv2.ErrMessageContains(err, codes[i], message) {
return true, err
}
}
return false, err
})
}
// RetryGWhenMessageContains retries the specified function when it returns an error containing any of the specified messages.
func RetryGWhenMessageContains[T any](ctx context.Context, timeout time.Duration, f func() (T, error), codes []string, messages []string) (T, error) {
return RetryGWhen(ctx, timeout, f, func(err error) (bool, error) {
for i, message := range messages {
if tfawserr.ErrMessageContains(err, codes[i], message) || tfawserr_sdkv2.ErrMessageContains(err, codes[i], message) {
return true, err
}
}
return false, err
})
}
func RetryWhenIsA[T error](ctx context.Context, timeout time.Duration, f func() (interface{}, error)) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if errs.IsA[T](err) {
return true, err
}
return false, err
})
}
func RetryWhenIsOneOf2[T1, T2 error](ctx context.Context, timeout time.Duration, f func() (interface{}, error)) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if errs.IsA[T1](err) || errs.IsA[T2](err) {
return true, err
}
return false, err
})
}
func RetryWhenIsOneOf3[T1, T2, T3 error](ctx context.Context, timeout time.Duration, f func() (interface{}, error)) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if errs.IsA[T1](err) || errs.IsA[T2](err) || errs.IsA[T3](err) {
return true, err
}
return false, err
})
}
func RetryWhenIsAErrorMessageContains[T errs.ErrorWithErrorMessage](ctx context.Context, timeout time.Duration, f func() (interface{}, error), needle string) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if errs.IsAErrorMessageContains[T](err, needle) {
return true, err
}
return false, err
})
}
// RetryUntilEqual retries the specified function until it returns a value equal to `t`.
func RetryUntilEqual[T comparable](ctx context.Context, timeout time.Duration, t T, f func() (T, error)) (T, error) {
var output T
err := Retry(ctx, timeout, func() *retry.RetryError {
var err error
output, err = f()
if err != nil {
return retry.NonRetryableError(err)
}
if output != t {
return retry.RetryableError(fmt.Errorf("output = %v, want %v", output, t))
}
return nil
})
if TimedOut(err) {
output, err = f()
if err == nil && output != t {
err = fmt.Errorf("output = %v, want %v", output, t)
}
}
if err != nil {
var zero T
return zero, err
}
return output, nil
}
// RetryWhenHTTPStatusCodeEquals retries the specified function when it returns one of the specified HTTP status codes.
func RetryWhenHTTPStatusCodeEquals(ctx context.Context, timeout time.Duration, f func() (interface{}, error), statusCodes ...int) (interface{}, error) { // nosemgrep:ci.aws-in-func-name
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if tfawserr_sdkv2.ErrHTTPStatusCodeEquals(err, statusCodes...) {
return true, err
}
return false, err
})
}
var ErrFoundResource = errors.New(`found resource`)
// RetryUntilNotFound retries the specified function until it returns a retry.NotFoundError.
func RetryUntilNotFound(ctx context.Context, timeout time.Duration, f func() (interface{}, error)) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if NotFound(err) {
return false, nil
}
if err != nil {
return false, err
}
return true, ErrFoundResource
})
}
// RetryWhenNotFound retries the specified function when it returns a retry.NotFoundError.
func RetryWhenNotFound(ctx context.Context, timeout time.Duration, f func() (interface{}, error)) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if NotFound(err) {
return true, err
}
return false, err
})
}
// RetryWhenNewResourceNotFound retries the specified function when it returns a retry.NotFoundError and `isNewResource` is true.
func RetryWhenNewResourceNotFound(ctx context.Context, timeout time.Duration, f func() (interface{}, error), isNewResource bool) (interface{}, error) {
return RetryWhen(ctx, timeout, f, func(err error) (bool, error) {
if isNewResource && NotFound(err) {
return true, err
}
return false, err
})
}
type Options struct {
Delay time.Duration // Wait this time before starting checks
MinPollInterval time.Duration // Smallest time to wait before refreshes (MinTimeout in retry.StateChangeConf)
PollInterval time.Duration // Override MinPollInterval/backoff and only poll this often
NotFoundChecks int // Number of times to allow not found (nil result from Refresh)
ContinuousTargetOccurence int // Number of times the Target state has to occur continuously
}
func (o Options) Apply(c *retry.StateChangeConf) {
if o.Delay > 0 {
c.Delay = o.Delay
}
if o.MinPollInterval > 0 {
c.MinTimeout = o.MinPollInterval
}
if o.PollInterval > 0 {
c.PollInterval = o.PollInterval
}
if o.NotFoundChecks > 0 {
c.NotFoundChecks = o.NotFoundChecks
}
if o.ContinuousTargetOccurence > 0 {
c.ContinuousTargetOccurence = o.ContinuousTargetOccurence
}
}
type OptionsFunc func(*Options)
func WithDelay(delay time.Duration) OptionsFunc {
return func(o *Options) {
o.Delay = delay
}
}
// WithDelayRand sets the delay to a value between 0s and the passed duration
func WithDelayRand(delayRand time.Duration) OptionsFunc {
return func(o *Options) {
o.Delay = time.Duration(rand.Int63n(delayRand.Milliseconds())) * time.Millisecond
}
}
func WithMinPollInterval(minPollInterval time.Duration) OptionsFunc {
return func(o *Options) {
o.MinPollInterval = minPollInterval
}
}
func WithPollInterval(pollInterval time.Duration) OptionsFunc {
return func(o *Options) {
o.PollInterval = pollInterval
}
}
func WithNotFoundChecks(notFoundChecks int) OptionsFunc {
return func(o *Options) {
o.NotFoundChecks = notFoundChecks
}
}
func WithContinuousTargetOccurence(continuousTargetOccurence int) OptionsFunc {
return func(o *Options) {
o.ContinuousTargetOccurence = continuousTargetOccurence
}
}
// Retry allows configuration of StateChangeConf's various time arguments.
// This is especially useful for AWS services that are prone to throttling, such as Route53, where
// the default durations cause problems.
func Retry(ctx context.Context, timeout time.Duration, f retry.RetryFunc, optFns ...OptionsFunc) error {
// These are used to pull the error out of the function; need a mutex to
// avoid a data race.
var resultErr error
var resultErrMu sync.Mutex
options := Options{}
for _, fn := range optFns {
fn(&options)
}
c := &retry.StateChangeConf{
Pending: []string{"retryableerror"},
Target: []string{"success"},
Timeout: timeout,
MinTimeout: 500 * time.Millisecond,
Refresh: func() (interface{}, string, error) {
rerr := f()
resultErrMu.Lock()
defer resultErrMu.Unlock()
if rerr == nil {
resultErr = nil
return 42, "success", nil
}
resultErr = rerr.Err
if rerr.Retryable {
return 42, "retryableerror", nil
}
return nil, "quit", rerr.Err
},
}
options.Apply(c)
_, waitErr := c.WaitForStateContext(ctx)
// Need to acquire the lock here to be able to avoid race using resultErr as
// the return value
resultErrMu.Lock()
defer resultErrMu.Unlock()
// resultErr may be nil because the wait timed out and resultErr was never
// set; this is still an error
if resultErr == nil {
return waitErr
}
// resultErr takes precedence over waitErr if both are set because it is
// more likely to be useful
return resultErr
}
type deadline time.Time
func NewDeadline(duration time.Duration) deadline {
return deadline(time.Now().Add(duration))
}
func (d deadline) Remaining() time.Duration {
if v := time.Until(time.Time(d)); v < 0 {
return 0
} else {
return v
}
}