-
Notifications
You must be signed in to change notification settings - Fork 82
/
retryable.go
671 lines (611 loc) · 15.9 KB
/
retryable.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//go:build !nolegacy
// +build !nolegacy
// Package retryable is a legacy package, functionality has been moved to reghttp
package retryable
import (
"bytes"
"context"
"os"
"sync"
// crypto libraries included for go-digest
_ "crypto/sha256"
_ "crypto/sha512"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net/http"
"net/url"
"time"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
)
// Retryable is used to create requests with built in retry capabilities
type Retryable interface {
DoRequest(ctx context.Context, method string, u []url.URL, opts ...OptsReq) (Response, error)
BackoffClear()
BackoffUntil() time.Time
}
// Response is used to handle the result of a request
type Response interface {
io.ReadCloser
HTTPResponse() *http.Response
HTTPResponses() ([]*http.Response, error)
}
// Auth is used to process Www-Authenticate header and update request with Authorization header
type Auth interface {
AddScope(host, scope string) error
HandleResponse(*http.Response) error
UpdateRequest(*http.Request) error
}
// Opts injects options into NewRetryable
type Opts func(*retryable)
// OptsReq injects options into NewRequest
type OptsReq func(*request)
type retryable struct {
httpClient *http.Client
auth Auth
rootCAPool [][]byte
limit int
delayInit time.Duration
delayMax time.Duration
backoffNeeded bool
backoffCur int
backoffUntil time.Time
log *logrus.Logger
useragent string
mu sync.Mutex
}
var defaultDelayInit, _ = time.ParseDuration("1s")
var defaultDelayMax, _ = time.ParseDuration("30s")
var defaultLimit = 3
// NewRetryable returns a retryable interface
func NewRetryable(opts ...Opts) Retryable {
r := &retryable{
httpClient: &http.Client{},
limit: defaultLimit,
delayInit: defaultDelayInit,
delayMax: defaultDelayMax,
log: &logrus.Logger{Out: io.Discard},
rootCAPool: [][]byte{},
}
for _, opt := range opts {
opt(r)
}
// inject certificates from user
if len(r.rootCAPool) > 0 {
var tlsc *tls.Config
if r.httpClient.Transport == nil {
r.httpClient.Transport = &http.Transport{}
}
t, ok := r.httpClient.Transport.(*http.Transport)
if ok {
if t.TLSClientConfig != nil {
tlsc = t.TLSClientConfig.Clone()
} else {
//#nosec G402 the default TLS 1.2 minimum version is allowed to support older registries
tlsc = &tls.Config{}
}
if tlsc.RootCAs == nil {
rootPool, err := x509.SystemCertPool()
if err != nil {
r.log.WithFields(logrus.Fields{
"err": err,
}).Warn("Failed to load system cert pool")
}
tlsc.RootCAs = rootPool
}
for _, ca := range r.rootCAPool {
if ok := tlsc.RootCAs.AppendCertsFromPEM(ca); !ok {
r.log.WithFields(logrus.Fields{
"cert": string(ca),
}).Warn("Failed to load root certificate")
}
}
t.TLSClientConfig = tlsc
r.httpClient.Transport = t
}
}
return r
}
// WithAuth adds authentication to retryable methods
func WithAuth(auth Auth) Opts {
return func(r *retryable) {
r.auth = auth
}
}
// WithCerts adds certificates
func WithCerts(certs [][]byte) Opts {
return func(r *retryable) {
r.rootCAPool = append(r.rootCAPool, certs...)
}
}
// WithCertFiles adds certificates by filename
func WithCertFiles(files []string) Opts {
return func(r *retryable) {
for _, f := range files {
//#nosec G304 command is run by a user accessing their own files
c, err := os.ReadFile(f)
if err != nil {
r.log.WithFields(logrus.Fields{
"err": err,
"file": f,
}).Warn("Failed to read certificate")
} else {
r.rootCAPool = append(r.rootCAPool, c)
}
}
}
}
// WithDelay initial time to wait between retries (increased with exponential backoff)
func WithDelay(delayInit time.Duration, delayMax time.Duration) Opts {
return func(r *retryable) {
if delayInit > 0 {
r.delayInit = delayInit
}
// delayMax must be at least delayInit, if 0 initialize to 30x delayInit
if delayMax > r.delayInit {
r.delayMax = delayMax
} else if delayMax > 0 {
r.delayMax = r.delayInit
} else {
r.delayMax = r.delayInit * 30
}
}
}
// WithHTTPClient uses a specific http client with retryable requests
func WithHTTPClient(h *http.Client) Opts {
return func(r *retryable) {
r.httpClient = h
}
}
// WithLimit restricts the number of retries (defaults to 5)
func WithLimit(l int) Opts {
return func(r *retryable) {
if l > 0 {
r.limit = l
}
}
}
// WithLog injects a logrus Logger configuration
func WithLog(log *logrus.Logger) Opts {
return func(r *retryable) {
r.log = log
}
}
// WithTransport uses a specific http transport with retryable requests
func WithTransport(t *http.Transport) Opts {
return func(r *retryable) {
r.httpClient = &http.Client{Transport: t}
}
}
// WithUserAgent sets a user agent header
func WithUserAgent(ua string) Opts {
return func(r *retryable) {
r.useragent = ua
}
}
func (r *retryable) BackoffClear() {
if r.backoffCur > r.limit {
r.backoffCur = r.limit
}
if r.backoffCur > 0 {
r.backoffCur--
if r.backoffCur == 0 {
r.backoffUntil = time.Time{}
}
}
r.backoffNeeded = false
}
func (r *retryable) backoffSet(lastResp *http.Response) error {
r.backoffCur++
// sleep for backoff time
sleepTime := r.delayInit << r.backoffCur
// limit to max delay
if sleepTime > r.delayMax {
sleepTime = r.delayMax
}
// check rate limit header
if lastResp != nil && lastResp.Header.Get("Retry-After") != "" {
ras := lastResp.Header.Get("Retry-After")
ra, _ := time.ParseDuration(ras + "s")
if ra > r.delayMax {
sleepTime = r.delayMax
} else if ra > sleepTime {
sleepTime = ra
}
}
r.backoffUntil = time.Now().Add(sleepTime)
r.backoffNeeded = true
if r.backoffCur == r.limit {
return fmt.Errorf("%w: backoffs %d", ErrBackoffLimit, r.backoffCur)
}
return nil
}
// BackoffUntil returns the time until the next backoff would complete
func (r *retryable) BackoffUntil() time.Time {
return r.backoffUntil
}
type request struct {
r *retryable
context context.Context
method string
urls []url.URL
curURL int
header http.Header
getBody func() (io.ReadCloser, error)
contentLen int64
chunking bool
offset int64
curRead int64
done bool
digest digest.Digest
digester digest.Digester
progressCB func(int64, error)
responses []*http.Response
reader io.Reader
log *logrus.Logger
}
func (r *retryable) DoRequest(ctx context.Context, method string, u []url.URL, opts ...OptsReq) (Response, error) {
req := &request{
r: r,
context: ctx,
method: method,
urls: u,
curURL: 0,
header: http.Header{},
getBody: nil,
contentLen: -1,
chunking: false,
offset: 0,
curRead: 0,
done: false,
digest: "",
digester: nil,
progressCB: nil,
responses: []*http.Response{},
reader: nil,
log: r.log,
}
// apply opts
for _, opt := range opts {
opt(req)
}
// run the request until successful or non-recoverable error
err := req.retryLoop()
return req, err
}
// WithBodyBytes converts a bytes slice into a body func and content length
func WithBodyBytes(body []byte) OptsReq {
return func(req *request) {
req.contentLen = int64(len(body))
req.getBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(body)), nil
}
}
}
// WithBodyFunc includes body content in a request
func WithBodyFunc(getbody func() (io.ReadCloser, error)) OptsReq {
return func(req *request) {
req.getBody = getbody
}
}
// WithChunking allows content to be divided into multiple smaller chunks
func WithChunking() OptsReq {
return func(req *request) {
req.chunking = true
}
}
// WithContentLen sets the content length
func WithContentLen(l int64) OptsReq {
return func(req *request) {
req.contentLen = l
}
}
// WithDigest verifies the returned content digest matches.
// Note that the digest is only calculated upon EOF from the downloaded
// content, so the reader may receive an error rather than EOF from a
// digest mismatch. The content itself must still be read.
func WithDigest(d digest.Digest) OptsReq {
return func(req *request) {
req.digest = d
req.digester = digest.Canonical.Digester()
}
}
// WithHeader sets a header
func WithHeader(key string, values []string) OptsReq {
return func(req *request) {
for _, v := range values {
req.header.Add(key, v)
}
}
}
// WithHeaders includes a header object
func WithHeaders(headers http.Header) OptsReq {
return func(req *request) {
for key := range headers {
for _, val := range headers.Values(key) {
req.header.Add(key, val)
}
}
}
}
// WithProgressCB calls the CB function as data is received
func WithProgressCB(cb func(int64, error)) OptsReq {
return func(req *request) {
req.progressCB = cb
}
}
func WithScope(repo string, push bool) OptsReq {
scope := "repository:" + repo + ":pull"
if push {
scope = scope + ",push"
}
return func(req *request) {
for _, url := range req.urls {
_ = req.r.auth.AddScope(url.Host, scope)
}
}
}
func (req *request) retryLoop() error {
req.r.mu.Lock()
defer req.r.mu.Unlock()
curRetry := 0
var httpErr error
for {
// handle backoffs and errors
if len(req.urls) == 0 {
if httpErr != nil {
return httpErr
}
return ErrAllRequestsFailed
}
curRetry++
if curRetry > req.r.limit {
return ErrAllRequestsFailed
}
if !req.r.backoffUntil.IsZero() && req.r.backoffUntil.After(time.Now()) {
sleepTime := time.Until(req.r.backoffUntil)
req.log.WithFields(logrus.Fields{
"Host": req.urls[req.curURL].Host,
"Seconds": sleepTime.Seconds(),
}).Warn("Sleeping for backoff")
select {
case <-req.context.Done():
return ErrCanceled
case <-time.After(sleepTime):
}
}
// close any previous responses before making a new request
if len(req.responses) > 0 {
errC := req.responses[len(req.responses)-1].Body.Close()
if errC != nil {
return fmt.Errorf("failed to close connection: %w", errC)
}
}
// send the new request
httpErr = req.httpDo()
if httpErr != nil {
_ = req.r.backoffSet(nil)
req.nextURL(true)
continue
}
// check the response
lastURL := req.urls[req.curURL]
lastResp := req.responses[len(req.responses)-1]
statusCode := lastResp.StatusCode
removeURL := false
runBackoff := false
switch {
case 200 <= statusCode && statusCode < 300:
// all 200 status codes are successful
req.r.BackoffClear()
return nil
case statusCode == http.StatusUnauthorized:
err := req.handleAuth()
if err != nil {
req.log.WithFields(logrus.Fields{
"URL": lastURL.String(),
"Err": err,
}).Warn("Failed to handle auth request")
runBackoff = true
removeURL = true
}
case statusCode == http.StatusForbidden:
req.log.WithFields(logrus.Fields{
"URL": lastURL.String(),
"Status": lastResp.Status,
}).Debug("Forbidden")
runBackoff = true
removeURL = true
case statusCode == http.StatusNotFound:
req.log.WithFields(logrus.Fields{
"URL": lastURL.String(),
"Status": lastResp.Status,
}).Debug("Not found")
removeURL = true
case statusCode == http.StatusTooManyRequests:
req.log.WithFields(logrus.Fields{
"URL": lastURL.String(),
"Status": lastResp.Status,
}).Debug("Rate limit exceeded")
runBackoff = true
case statusCode == http.StatusRequestTimeout:
req.log.WithFields(logrus.Fields{
"URL": lastURL.String(),
"Status": lastResp.Status,
}).Debug("Timeout")
runBackoff = true
case statusCode == http.StatusGatewayTimeout:
req.log.WithFields(logrus.Fields{
"URL": lastURL.String(),
"Status": lastResp.Status,
}).Debug("Gateway timeout")
runBackoff = true
default:
body, _ := io.ReadAll(lastResp.Body)
req.log.WithFields(logrus.Fields{
"URL": lastURL.String(),
"Status": lastResp.Status,
"Body": string(body),
}).Debug("Unexpected status")
runBackoff = true
removeURL = true
}
// remove url and trigger backoff if needed
if removeURL {
req.nextURL(removeURL)
}
if runBackoff {
_ = req.r.backoffSet(lastResp) // ignore error indicating backoff limit reached
}
}
}
func (req *request) handleAuth() error {
curURL := req.urls[req.curURL]
lastResp := req.responses[len(req.responses)-1]
// for unauthorized requests, try to setup auth and retry without backoff
if req.r.auth == nil {
return ErrUnauthorized
}
err := req.r.auth.HandleResponse(lastResp)
if err != nil {
req.log.WithFields(logrus.Fields{
"URL": curURL.String(),
"Err": err,
}).Warn("Failed to handle auth request")
return err
}
return nil
}
func (req *request) httpDo() error {
// build the http reqest for the current mirror url
httpReq, err := http.NewRequestWithContext(req.context, req.method, req.urls[req.curURL].String(), nil)
if err != nil {
return err
}
if req.getBody != nil {
httpReq.Body, err = req.getBody()
if err != nil {
return err
}
httpReq.GetBody = req.getBody
httpReq.ContentLength = req.contentLen
}
if len(req.header) > 0 {
httpReq.Header = req.header
}
if req.r.useragent != "" && httpReq.Header.Get("User-Agent") == "" {
httpReq.Header.Add("User-Agent", req.r.useragent)
}
if req.offset > 0 {
// TODO: implement range requests
return ErrNotImplemented
}
// include auth header
if req.r.auth != nil {
err = req.r.auth.UpdateRequest(httpReq)
if err != nil {
return err
}
}
req.log.WithFields(logrus.Fields{
"method": req.method,
"url": req.urls[req.curURL].String(),
"withAuth": (len(httpReq.Header.Values("Authorization")) > 0),
}).Debug("Sending request")
resp, err := req.r.httpClient.Do(httpReq)
if err != nil {
return err
}
req.responses = append(req.responses, resp)
// update reader
if req.digester == nil {
req.reader = resp.Body
} else {
req.reader = io.TeeReader(resp.Body, req.digester.Hash())
}
return nil
}
func (req *request) nextURL(removeLast bool) {
// next mirror based on whether remove flag is set
if removeLast {
req.urls = append(req.urls[:req.curURL], req.urls[req.curURL+1:]...)
if req.curURL >= len(req.urls) {
req.curURL = 0
}
} else {
if len(req.urls) > 0 {
req.curURL = (req.curURL + 1) % len(req.urls)
} else {
req.curURL = 0
}
}
}
func (req *request) Read(b []byte) (int, error) {
// if done, return eof
if req.done {
return 0, io.EOF
}
// if no responses, error
if len(req.responses) == 0 {
return 0, ErrNotFound
}
// fetch block
lastResp := req.responses[len(req.responses)-1]
i, err := req.reader.Read(b)
req.curRead += int64(i)
if err == io.EOF && lastResp.ContentLength > 0 {
if lastResp.Request.Method == "HEAD" {
// no body on a head request
req.done = true
} else if req.curRead < lastResp.ContentLength {
// TODO: handle early EOF or other failed connection with a retry
// req.offset += req.curRead
// err = req.retryLoop()
// if err != nil {
// return i, err
// }
req.log.WithFields(logrus.Fields{
"curRead": req.curRead,
"contentLen": lastResp.ContentLength,
}).Debug("EOF before reading all content, retrying")
return i, err
} else if req.curRead >= lastResp.ContentLength {
req.done = true
}
}
// if eof, verify digest, set error on mismatch
if req.digester != nil && err == io.EOF && req.digest != req.digester.Digest() {
req.log.WithFields(logrus.Fields{
"expected": req.digest,
"computed": req.digester.Digest(),
}).Warn("Digest mismatch")
req.done = true
return i, ErrDigestMismatch
}
// pass through read on the last response
return i, err
}
func (req *request) Close() error {
// if no responses, error
if req.reader == nil || len(req.responses) == 0 {
return ErrNotFound
}
// pass through close to last request, mark as done
lastResp := req.responses[len(req.responses)-1]
req.done = true
return lastResp.Body.Close()
}
func (req *request) HTTPResponse() *http.Response {
if len(req.responses) > 0 {
return req.responses[len(req.responses)-1]
}
return nil
}
func (req *request) HTTPResponses() ([]*http.Response, error) {
if len(req.responses) > 0 {
return req.responses, nil
}
return nil, ErrNotFound
}