| 1 |
/* |
| 2 |
Copyright The containerd Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
/* |
| 18 |
Copyright 2019 The Go Authors. All rights reserved. |
| 19 |
Use of this source code is governed by a BSD-style |
| 20 |
license that can be found in the NOTICE.md file. |
| 21 |
*/ |
| 22 |
|
| 23 |
package remote |
| 24 |
|
| 25 |
import ( |
| 26 |
"context" |
| 27 |
"crypto/sha256" |
| 28 |
"fmt" |
| 29 |
"io" |
| 30 |
"math/rand" |
| 31 |
"mime" |
| 32 |
"mime/multipart" |
| 33 |
"net/http" |
| 34 |
"path" |
| 35 |
"strconv" |
| 36 |
"strings" |
| 37 |
"sync" |
| 38 |
"time" |
| 39 |
|
| 40 |
"github.com/containerd/containerd/errdefs" |
| 41 |
"github.com/containerd/containerd/log" |
| 42 |
"github.com/containerd/containerd/reference" |
| 43 |
"github.com/containerd/containerd/remotes/docker" |
| 44 |
"github.com/containerd/stargz-snapshotter/cache" |
| 45 |
"github.com/containerd/stargz-snapshotter/fs/config" |
| 46 |
commonmetrics "github.com/containerd/stargz-snapshotter/fs/metrics/common" |
| 47 |
"github.com/containerd/stargz-snapshotter/fs/source" |
| 48 |
"github.com/hashicorp/go-multierror" |
| 49 |
rhttp "github.com/hashicorp/go-retryablehttp" |
| 50 |
digest "github.com/opencontainers/go-digest" |
| 51 |
ocispec "github.com/opencontainers/image-spec/specs-go/v1" |
| 52 |
) |
| 53 |
|
| 54 |
const ( |
| 55 |
defaultChunkSize = 50000 |
| 56 |
defaultValidIntervalSec = 60 |
| 57 |
defaultFetchTimeoutSec = 300 |
| 58 |
|
| 59 |
defaultMaxRetries = 5 |
| 60 |
defaultMinWaitMSec = 30 |
| 61 |
defaultMaxWaitMSec = 300000 |
| 62 |
) |
| 63 |
|
| 64 |
func NewResolver(cfg config.BlobConfig, handlers map[string]Handler) *Resolver { |
| 65 |
if cfg.ChunkSize == 0 { // zero means "use default chunk size" |
| 66 |
cfg.ChunkSize = defaultChunkSize |
| 67 |
} |
| 68 |
if cfg.ValidInterval == 0 { // zero means "use default interval" |
| 69 |
cfg.ValidInterval = defaultValidIntervalSec |
| 70 |
} |
| 71 |
if cfg.CheckAlways { |
| 72 |
cfg.ValidInterval = 0 |
| 73 |
} |
| 74 |
if cfg.FetchTimeoutSec == 0 { |
| 75 |
cfg.FetchTimeoutSec = defaultFetchTimeoutSec |
| 76 |
} |
| 77 |
if cfg.MaxRetries == 0 { |
| 78 |
cfg.MaxRetries = defaultMaxRetries |
| 79 |
} |
| 80 |
if cfg.MinWaitMSec == 0 { |
| 81 |
cfg.MinWaitMSec = defaultMinWaitMSec |
| 82 |
} |
| 83 |
if cfg.MaxWaitMSec == 0 { |
| 84 |
cfg.MaxWaitMSec = defaultMaxWaitMSec |
| 85 |
} |
| 86 |
|
| 87 |
return &Resolver{ |
| 88 |
blobConfig: cfg, |
| 89 |
handlers: handlers, |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
type Resolver struct { |
| 94 |
blobConfig config.BlobConfig |
| 95 |
handlers map[string]Handler |
| 96 |
} |
| 97 |
|
| 98 |
type fetcher interface { |
| 99 |
fetch(ctx context.Context, rs []region, retry bool) (multipartReadCloser, error) |
| 100 |
check() error |
| 101 |
genID(reg region) string |
| 102 |
} |
| 103 |
|
| 104 |
func (r *Resolver) Resolve(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor, blobCache cache.BlobCache) (Blob, error) { |
| 105 |
f, size, err := r.resolveFetcher(ctx, hosts, refspec, desc) |
| 106 |
if err != nil { |
| 107 |
return nil, err |
| 108 |
} |
| 109 |
blobConfig := &r.blobConfig |
| 110 |
return makeBlob(f, |
| 111 |
size, |
| 112 |
blobConfig.ChunkSize, |
| 113 |
blobConfig.PrefetchChunkSize, |
| 114 |
blobCache, |
| 115 |
time.Now(), |
| 116 |
time.Duration(blobConfig.ValidInterval)*time.Second, |
| 117 |
r, |
| 118 |
time.Duration(blobConfig.FetchTimeoutSec)*time.Second), nil |
| 119 |
} |
| 120 |
|
| 121 |
func (r *Resolver) resolveFetcher(ctx context.Context, hosts source.RegistryHosts, refspec reference.Spec, desc ocispec.Descriptor) (f fetcher, size int64, err error) { |
| 122 |
blobConfig := &r.blobConfig |
| 123 |
fc := &fetcherConfig{ |
| 124 |
hosts: hosts, |
| 125 |
refspec: refspec, |
| 126 |
desc: desc, |
| 127 |
maxRetries: blobConfig.MaxRetries, |
| 128 |
minWaitMSec: time.Duration(blobConfig.MinWaitMSec) * time.Millisecond, |
| 129 |
maxWaitMSec: time.Duration(blobConfig.MaxWaitMSec) * time.Millisecond, |
| 130 |
} |
| 131 |
var handlersErr error |
| 132 |
for name, p := range r.handlers { |
| 133 |
// TODO: allow to configure the selection of readers based on the hostname in refspec |
| 134 |
r, size, err := p.Handle(ctx, desc) |
| 135 |
if err != nil { |
| 136 |
handlersErr = multierror.Append(handlersErr, err) |
| 137 |
continue |
| 138 |
} |
| 139 |
log.G(ctx).WithField("handler name", name).WithField("ref", refspec.String()).WithField("digest", desc.Digest). |
| 140 |
Debugf("contents is provided by a handler") |
| 141 |
return &remoteFetcher{r}, size, nil |
| 142 |
} |
| 143 |
|
| 144 |
log.G(ctx).WithError(handlersErr).WithField("ref", refspec.String()).WithField("digest", desc.Digest).Debugf("using default handler") |
| 145 |
hf, size, err := newHTTPFetcher(ctx, fc) |
| 146 |
if err != nil { |
| 147 |
return nil, 0, err |
| 148 |
} |
| 149 |
if blobConfig.ForceSingleRangeMode { |
| 150 |
hf.singleRangeMode() |
| 151 |
} |
| 152 |
return hf, size, err |
| 153 |
} |
| 154 |
|
| 155 |
type fetcherConfig struct { |
| 156 |
hosts source.RegistryHosts |
| 157 |
refspec reference.Spec |
| 158 |
desc ocispec.Descriptor |
| 159 |
maxRetries int |
| 160 |
minWaitMSec time.Duration |
| 161 |
maxWaitMSec time.Duration |
| 162 |
} |
| 163 |
|
| 164 |
func jitter(duration time.Duration) time.Duration { |
| 165 |
if duration <= 0 { |
| 166 |
return duration |
| 167 |
} |
| 168 |
return time.Duration(rand.Int63n(int64(duration)) + int64(duration)) |
| 169 |
} |
| 170 |
|
| 171 |
// backoffStrategy extends retryablehttp's DefaultBackoff to add a random jitter to avoid overwhelming the repository |
| 172 |
// when it comes back online |
| 173 |
// DefaultBackoff either tries to parse the 'Retry-After' header of the response; or, it uses an exponential backoff |
| 174 |
// 2 ^ numAttempts, limited by max |
| 175 |
func backoffStrategy(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { |
| 176 |
delayTime := rhttp.DefaultBackoff(min, max, attemptNum, resp) |
| 177 |
return jitter(delayTime) |
| 178 |
} |
| 179 |
|
| 180 |
// retryStrategy extends retryablehttp's DefaultRetryPolicy to debug log the error when retrying |
| 181 |
// DefaultRetryPolicy retries whenever err is non-nil (except for some url errors) or if returned |
| 182 |
// status code is 429 or 5xx (except 501) |
| 183 |
func retryStrategy(ctx context.Context, resp *http.Response, err error) (bool, error) { |
| 184 |
retry, err2 := rhttp.DefaultRetryPolicy(ctx, resp, err) |
| 185 |
if retry { |
| 186 |
log.G(ctx).WithError(err).Debugf("Retrying request") |
| 187 |
} |
| 188 |
return retry, err2 |
| 189 |
} |
| 190 |
|
| 191 |
func newHTTPFetcher(ctx context.Context, fc *fetcherConfig) (*httpFetcher, int64, error) { |
| 192 |
reghosts, err := fc.hosts(fc.refspec) |
| 193 |
if err != nil { |
| 194 |
return nil, 0, err |
| 195 |
} |
| 196 |
desc := fc.desc |
| 197 |
if desc.Digest.String() == "" { |
| 198 |
return nil, 0, fmt.Errorf("Digest is mandatory in layer descriptor") |
| 199 |
} |
| 200 |
digest := desc.Digest |
| 201 |
pullScope, err := docker.RepositoryScope(fc.refspec, false) |
| 202 |
if err != nil { |
| 203 |
return nil, 0, err |
| 204 |
} |
| 205 |
|
| 206 |
// Try to create fetcher until succeeded |
| 207 |
rErr := fmt.Errorf("failed to resolve") |
| 208 |
for _, host := range reghosts { |
| 209 |
if host.Host == "" || strings.Contains(host.Host, "/") { |
| 210 |
rErr = fmt.Errorf("invalid destination (host %q, ref:%q, digest:%q): %w", host.Host, fc.refspec, digest, rErr) |
| 211 |
continue // Try another |
| 212 |
|
| 213 |
} |
| 214 |
|
| 215 |
// Prepare transport with authorization functionality |
| 216 |
tr := host.Client.Transport |
| 217 |
|
| 218 |
if rt, ok := tr.(*rhttp.RoundTripper); ok { |
| 219 |
rt.Client.RetryMax = fc.maxRetries |
| 220 |
rt.Client.RetryWaitMin = fc.minWaitMSec |
| 221 |
rt.Client.RetryWaitMax = fc.maxWaitMSec |
| 222 |
rt.Client.Backoff = backoffStrategy |
| 223 |
rt.Client.CheckRetry = retryStrategy |
| 224 |
} |
| 225 |
|
| 226 |
timeout := host.Client.Timeout |
| 227 |
if host.Authorizer != nil { |
| 228 |
tr = &transport{ |
| 229 |
inner: tr, |
| 230 |
auth: host.Authorizer, |
| 231 |
scope: pullScope, |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
// Resolve redirection and get blob URL |
| 236 |
blobURL := fmt.Sprintf("%s://%s/%s/blobs/%s", |
| 237 |
host.Scheme, |
| 238 |
path.Join(host.Host, host.Path), |
| 239 |
strings.TrimPrefix(fc.refspec.Locator, fc.refspec.Hostname()+"/"), |
| 240 |
digest) |
| 241 |
url, header, err := redirect(ctx, blobURL, tr, timeout, host.Header) |
| 242 |
if err != nil { |
| 243 |
rErr = fmt.Errorf("failed to redirect (host %q, ref:%q, digest:%q): %v: %w", host.Host, fc.refspec, digest, err, rErr) |
| 244 |
continue // Try another |
| 245 |
} |
| 246 |
|
| 247 |
// Get size information |
| 248 |
// TODO: we should try to use the Size field in the descriptor here. |
| 249 |
start := time.Now() // start time before getting layer header |
| 250 |
size, err := getSize(ctx, url, tr, timeout, header) |
| 251 |
commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.StargzHeaderGet, digest, start) // time to get layer header |
| 252 |
if err != nil { |
| 253 |
rErr = fmt.Errorf("failed to get size (host %q, ref:%q, digest:%q): %v: %w", host.Host, fc.refspec, digest, err, rErr) |
| 254 |
continue // Try another |
| 255 |
} |
| 256 |
|
| 257 |
// Hit one destination |
| 258 |
return &httpFetcher{ |
| 259 |
url: url, |
| 260 |
tr: tr, |
| 261 |
blobURL: blobURL, |
| 262 |
digest: digest, |
| 263 |
timeout: timeout, |
| 264 |
header: header, |
| 265 |
orgHeader: host.Header, |
| 266 |
}, size, nil |
| 267 |
} |
| 268 |
|
| 269 |
return nil, 0, fmt.Errorf("cannot resolve layer: %w", rErr) |
| 270 |
} |
| 271 |
|
| 272 |
type transport struct { |
| 273 |
inner http.RoundTripper |
| 274 |
auth docker.Authorizer |
| 275 |
scope string |
| 276 |
} |
| 277 |
|
| 278 |
func (tr *transport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 279 |
ctx := docker.WithScope(req.Context(), tr.scope) |
| 280 |
roundTrip := func(req *http.Request) (*http.Response, error) { |
| 281 |
// authorize the request using docker.Authorizer |
| 282 |
if err := tr.auth.Authorize(ctx, req); err != nil { |
| 283 |
return nil, err |
| 284 |
} |
| 285 |
|
| 286 |
// send the request |
| 287 |
return tr.inner.RoundTrip(req) |
| 288 |
} |
| 289 |
|
| 290 |
resp, err := roundTrip(req) |
| 291 |
if err != nil { |
| 292 |
return nil, err |
| 293 |
} |
| 294 |
|
| 295 |
// TODO: support more status codes and retries |
| 296 |
if resp.StatusCode == http.StatusUnauthorized { |
| 297 |
log.G(ctx).Infof("Received status code: %v. Refreshing creds...", resp.Status) |
| 298 |
|
| 299 |
// prepare authorization for the target host using docker.Authorizer |
| 300 |
if err := tr.auth.AddResponses(ctx, []*http.Response{resp}); err != nil { |
| 301 |
if errdefs.IsNotImplemented(err) { |
| 302 |
return resp, nil |
| 303 |
} |
| 304 |
return nil, err |
| 305 |
} |
| 306 |
|
| 307 |
// re-authorize and send the request |
| 308 |
return roundTrip(req.Clone(ctx)) |
| 309 |
} |
| 310 |
|
| 311 |
return resp, nil |
| 312 |
} |
| 313 |
|
| 314 |
func redirect(ctx context.Context, blobURL string, tr http.RoundTripper, timeout time.Duration, header http.Header) (url string, withHeader http.Header, err error) { |
| 315 |
if timeout > 0 { |
| 316 |
var cancel context.CancelFunc |
| 317 |
ctx, cancel = context.WithTimeout(ctx, timeout) |
| 318 |
defer cancel() |
| 319 |
} |
| 320 |
// We use GET request for redirect. |
| 321 |
// gcr.io returns 200 on HEAD without Location header (2020). |
| 322 |
// ghcr.io returns 200 on HEAD without Location header (2020). |
| 323 |
req, err := http.NewRequestWithContext(ctx, "GET", blobURL, nil) |
| 324 |
if err != nil { |
| 325 |
return "", nil, fmt.Errorf("failed to make request to the registry: %w", err) |
| 326 |
} |
| 327 |
req.Header = http.Header{} |
| 328 |
for k, v := range header { |
| 329 |
req.Header[k] = v |
| 330 |
} |
| 331 |
req.Close = false |
| 332 |
req.Header.Set("Range", "bytes=0-1") |
| 333 |
res, err := tr.RoundTrip(req) |
| 334 |
if err != nil { |
| 335 |
return "", nil, fmt.Errorf("failed to request: %w", err) |
| 336 |
} |
| 337 |
defer func() { |
| 338 |
io.Copy(io.Discard, res.Body) |
| 339 |
res.Body.Close() |
| 340 |
}() |
| 341 |
|
| 342 |
if res.StatusCode/100 == 2 { |
| 343 |
url = blobURL |
| 344 |
withHeader = header |
| 345 |
} else if redir := res.Header.Get("Location"); redir != "" && res.StatusCode/100 == 3 { |
| 346 |
// TODO: Support nested redirection |
| 347 |
url = redir |
| 348 |
// Do not pass headers to the redirected location. |
| 349 |
} else { |
| 350 |
return "", nil, fmt.Errorf("failed to access to the registry with code %v", res.StatusCode) |
| 351 |
} |
| 352 |
|
| 353 |
return |
| 354 |
} |
| 355 |
|
| 356 |
func getSize(ctx context.Context, url string, tr http.RoundTripper, timeout time.Duration, header http.Header) (int64, error) { |
| 357 |
if timeout > 0 { |
| 358 |
var cancel context.CancelFunc |
| 359 |
ctx, cancel = context.WithTimeout(ctx, timeout) |
| 360 |
defer cancel() |
| 361 |
} |
| 362 |
req, err := http.NewRequestWithContext(ctx, "HEAD", url, nil) |
| 363 |
if err != nil { |
| 364 |
return 0, err |
| 365 |
} |
| 366 |
req.Header = http.Header{} |
| 367 |
for k, v := range header { |
| 368 |
req.Header[k] = v |
| 369 |
} |
| 370 |
req.Close = false |
| 371 |
res, err := tr.RoundTrip(req) |
| 372 |
if err != nil { |
| 373 |
return 0, err |
| 374 |
} |
| 375 |
defer res.Body.Close() |
| 376 |
if res.StatusCode == http.StatusOK { |
| 377 |
return strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64) |
| 378 |
} |
| 379 |
headStatusCode := res.StatusCode |
| 380 |
|
| 381 |
// Failed to do HEAD request. Fall back to GET. |
| 382 |
// ghcr.io (https://github-production-container-registry.s3.amazonaws.com) doesn't allow |
| 383 |
// HEAD request (2020). |
| 384 |
req, err = http.NewRequestWithContext(ctx, "GET", url, nil) |
| 385 |
if err != nil { |
| 386 |
return 0, fmt.Errorf("failed to make request to the registry: %w", err) |
| 387 |
} |
| 388 |
req.Header = http.Header{} |
| 389 |
for k, v := range header { |
| 390 |
req.Header[k] = v |
| 391 |
} |
| 392 |
req.Close = false |
| 393 |
req.Header.Set("Range", "bytes=0-1") |
| 394 |
res, err = tr.RoundTrip(req) |
| 395 |
if err != nil { |
| 396 |
return 0, fmt.Errorf("failed to request: %w", err) |
| 397 |
} |
| 398 |
defer func() { |
| 399 |
io.Copy(io.Discard, res.Body) |
| 400 |
res.Body.Close() |
| 401 |
}() |
| 402 |
|
| 403 |
if res.StatusCode == http.StatusOK { |
| 404 |
return strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64) |
| 405 |
} else if res.StatusCode == http.StatusPartialContent { |
| 406 |
_, size, err := parseRange(res.Header.Get("Content-Range")) |
| 407 |
return size, err |
| 408 |
} |
| 409 |
|
| 410 |
return 0, fmt.Errorf("failed to get size with code (HEAD=%v, GET=%v)", |
| 411 |
headStatusCode, res.StatusCode) |
| 412 |
} |
| 413 |
|
| 414 |
type httpFetcher struct { |
| 415 |
url string |
| 416 |
urlMu sync.Mutex |
| 417 |
tr http.RoundTripper |
| 418 |
blobURL string |
| 419 |
digest digest.Digest |
| 420 |
singleRange bool |
| 421 |
singleRangeMu sync.Mutex |
| 422 |
timeout time.Duration |
| 423 |
header http.Header |
| 424 |
orgHeader http.Header |
| 425 |
} |
| 426 |
|
| 427 |
type multipartReadCloser interface { |
| 428 |
Next() (region, io.Reader, error) |
| 429 |
Close() error |
| 430 |
} |
| 431 |
|
| 432 |
func (f *httpFetcher) fetch(ctx context.Context, rs []region, retry bool) (multipartReadCloser, error) { |
| 433 |
if len(rs) == 0 { |
| 434 |
return nil, fmt.Errorf("no request queried") |
| 435 |
} |
| 436 |
|
| 437 |
var ( |
| 438 |
tr = f.tr |
| 439 |
singleRangeMode = f.isSingleRangeMode() |
| 440 |
) |
| 441 |
|
| 442 |
// squash requesting chunks for reducing the total size of request header |
| 443 |
// (servers generally have limits for the size of headers) |
| 444 |
// TODO: when our request has too many ranges, we need to divide it into |
| 445 |
// multiple requests to avoid huge header. |
| 446 |
var s regionSet |
| 447 |
for _, reg := range rs { |
| 448 |
s.add(reg) |
| 449 |
} |
| 450 |
requests := s.rs |
| 451 |
if singleRangeMode { |
| 452 |
// Squash requests if the layer doesn't support multi range. |
| 453 |
requests = []region{superRegion(requests)} |
| 454 |
} |
| 455 |
|
| 456 |
// Request to the registry |
| 457 |
f.urlMu.Lock() |
| 458 |
url := f.url |
| 459 |
f.urlMu.Unlock() |
| 460 |
req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 461 |
if err != nil { |
| 462 |
return nil, err |
| 463 |
} |
| 464 |
req.Header = http.Header{} |
| 465 |
for k, v := range f.header { |
| 466 |
req.Header[k] = v |
| 467 |
} |
| 468 |
var ranges string |
| 469 |
for _, reg := range requests { |
| 470 |
ranges += fmt.Sprintf("%d-%d,", reg.b, reg.e) |
| 471 |
} |
| 472 |
req.Header.Add("Range", fmt.Sprintf("bytes=%s", ranges[:len(ranges)-1])) |
| 473 |
req.Header.Add("Accept-Encoding", "identity") |
| 474 |
req.Close = false |
| 475 |
|
| 476 |
// Recording the roundtrip latency for remote registry GET operation. |
| 477 |
start := time.Now() |
| 478 |
res, err := tr.RoundTrip(req) // NOT DefaultClient; don't want redirects |
| 479 |
commonmetrics.MeasureLatencyInMilliseconds(commonmetrics.RemoteRegistryGet, f.digest, start) |
| 480 |
if err != nil { |
| 481 |
return nil, err |
| 482 |
} |
| 483 |
if res.StatusCode == http.StatusOK { |
| 484 |
// We are getting the whole blob in one part (= status 200) |
| 485 |
size, err := strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64) |
| 486 |
if err != nil { |
| 487 |
return nil, fmt.Errorf("failed to parse Content-Length: %w", err) |
| 488 |
} |
| 489 |
return newSinglePartReader(region{0, size - 1}, res.Body), nil |
| 490 |
} else if res.StatusCode == http.StatusPartialContent { |
| 491 |
mediaType, params, err := mime.ParseMediaType(res.Header.Get("Content-Type")) |
| 492 |
if err != nil { |
| 493 |
return nil, fmt.Errorf("invalid media type %q: %w", mediaType, err) |
| 494 |
} |
| 495 |
if strings.HasPrefix(mediaType, "multipart/") { |
| 496 |
// We are getting a set of chunks as a multipart body. |
| 497 |
return newMultiPartReader(res.Body, params["boundary"]), nil |
| 498 |
} |
| 499 |
|
| 500 |
// We are getting single range |
| 501 |
reg, _, err := parseRange(res.Header.Get("Content-Range")) |
| 502 |
if err != nil { |
| 503 |
return nil, fmt.Errorf("failed to parse Content-Range: %w", err) |
| 504 |
} |
| 505 |
return newSinglePartReader(reg, res.Body), nil |
| 506 |
} else if retry && res.StatusCode == http.StatusForbidden { |
| 507 |
log.G(ctx).Infof("Received status code: %v. Refreshing URL and retrying...", res.Status) |
| 508 |
|
| 509 |
// re-redirect and retry this once. |
| 510 |
if err := f.refreshURL(ctx); err != nil { |
| 511 |
return nil, fmt.Errorf("failed to refresh URL on %v: %w", res.Status, err) |
| 512 |
} |
| 513 |
return f.fetch(ctx, rs, false) |
| 514 |
} else if retry && res.StatusCode == http.StatusBadRequest && !singleRangeMode { |
| 515 |
log.G(ctx).Infof("Received status code: %v. Setting single range mode and retrying...", res.Status) |
| 516 |
|
| 517 |
// gcr.io (https://storage.googleapis.com) returns 400 on multi-range request (2020 #81) |
| 518 |
f.singleRangeMode() // fallbacks to singe range request mode |
| 519 |
return f.fetch(ctx, rs, false) // retries with the single range mode |
| 520 |
} |
| 521 |
|
| 522 |
return nil, fmt.Errorf("unexpected status code: %v", res.Status) |
| 523 |
} |
| 524 |
|
| 525 |
func (f *httpFetcher) check() error { |
| 526 |
ctx := context.Background() |
| 527 |
if f.timeout > 0 { |
| 528 |
var cancel context.CancelFunc |
| 529 |
ctx, cancel = context.WithTimeout(ctx, f.timeout) |
| 530 |
defer cancel() |
| 531 |
} |
| 532 |
f.urlMu.Lock() |
| 533 |
url := f.url |
| 534 |
f.urlMu.Unlock() |
| 535 |
req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 536 |
if err != nil { |
| 537 |
return fmt.Errorf("check failed: failed to make request: %w", err) |
| 538 |
} |
| 539 |
req.Header = http.Header{} |
| 540 |
for k, v := range f.header { |
| 541 |
req.Header[k] = v |
| 542 |
} |
| 543 |
req.Close = false |
| 544 |
req.Header.Set("Range", "bytes=0-1") |
| 545 |
res, err := f.tr.RoundTrip(req) |
| 546 |
if err != nil { |
| 547 |
return fmt.Errorf("check failed: failed to request to registry: %w", err) |
| 548 |
} |
| 549 |
defer func() { |
| 550 |
io.Copy(io.Discard, res.Body) |
| 551 |
res.Body.Close() |
| 552 |
}() |
| 553 |
if res.StatusCode == http.StatusOK || res.StatusCode == http.StatusPartialContent { |
| 554 |
return nil |
| 555 |
} else if res.StatusCode == http.StatusForbidden { |
| 556 |
// Try to re-redirect this blob |
| 557 |
rCtx := context.Background() |
| 558 |
if f.timeout > 0 { |
| 559 |
var rCancel context.CancelFunc |
| 560 |
rCtx, rCancel = context.WithTimeout(rCtx, f.timeout) |
| 561 |
defer rCancel() |
| 562 |
} |
| 563 |
if err := f.refreshURL(rCtx); err == nil { |
| 564 |
return nil |
| 565 |
} |
| 566 |
return fmt.Errorf("failed to refresh URL on status %v", res.Status) |
| 567 |
} |
| 568 |
|
| 569 |
return fmt.Errorf("unexpected status code %v", res.StatusCode) |
| 570 |
} |
| 571 |
|
| 572 |
func (f *httpFetcher) refreshURL(ctx context.Context) error { |
| 573 |
newURL, headers, err := redirect(ctx, f.blobURL, f.tr, f.timeout, f.orgHeader) |
| 574 |
if err != nil { |
| 575 |
return err |
| 576 |
} |
| 577 |
f.urlMu.Lock() |
| 578 |
f.url = newURL |
| 579 |
f.header = headers |
| 580 |
f.urlMu.Unlock() |
| 581 |
return nil |
| 582 |
} |
| 583 |
|
| 584 |
func (f *httpFetcher) genID(reg region) string { |
| 585 |
sum := sha256.Sum256([]byte(fmt.Sprintf("%s-%d-%d", f.blobURL, reg.b, reg.e))) |
| 586 |
return fmt.Sprintf("%x", sum) |
| 587 |
} |
| 588 |
|
| 589 |
func (f *httpFetcher) singleRangeMode() { |
| 590 |
f.singleRangeMu.Lock() |
| 591 |
f.singleRange = true |
| 592 |
f.singleRangeMu.Unlock() |
| 593 |
} |
| 594 |
|
| 595 |
func (f *httpFetcher) isSingleRangeMode() bool { |
| 596 |
f.singleRangeMu.Lock() |
| 597 |
r := f.singleRange |
| 598 |
f.singleRangeMu.Unlock() |
| 599 |
return r |
| 600 |
} |
| 601 |
|
| 602 |
func newSinglePartReader(reg region, rc io.ReadCloser) multipartReadCloser { |
| 603 |
return &singlepartReader{ |
| 604 |
r: rc, |
| 605 |
Closer: rc, |
| 606 |
reg: reg, |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
type singlepartReader struct { |
| 611 |
io.Closer |
| 612 |
r io.Reader |
| 613 |
reg region |
| 614 |
called bool |
| 615 |
} |
| 616 |
|
| 617 |
func (sr *singlepartReader) Next() (region, io.Reader, error) { |
| 618 |
if !sr.called { |
| 619 |
sr.called = true |
| 620 |
return sr.reg, sr.r, nil |
| 621 |
} |
| 622 |
return region{}, nil, io.EOF |
| 623 |
} |
| 624 |
|
| 625 |
func newMultiPartReader(rc io.ReadCloser, boundary string) multipartReadCloser { |
| 626 |
return &multipartReader{ |
| 627 |
m: multipart.NewReader(rc, boundary), |
| 628 |
Closer: rc, |
| 629 |
} |
| 630 |
} |
| 631 |
|
| 632 |
type multipartReader struct { |
| 633 |
io.Closer |
| 634 |
m *multipart.Reader |
| 635 |
} |
| 636 |
|
| 637 |
func (sr *multipartReader) Next() (region, io.Reader, error) { |
| 638 |
p, err := sr.m.NextPart() |
| 639 |
if err != nil { |
| 640 |
return region{}, nil, err |
| 641 |
} |
| 642 |
reg, _, err := parseRange(p.Header.Get("Content-Range")) |
| 643 |
if err != nil { |
| 644 |
return region{}, nil, fmt.Errorf("failed to parse Content-Range: %w", err) |
| 645 |
} |
| 646 |
return reg, p, nil |
| 647 |
} |
| 648 |
|
| 649 |
func parseRange(header string) (region, int64, error) { |
| 650 |
submatches := contentRangeRegexp.FindStringSubmatch(header) |
| 651 |
if len(submatches) < 4 { |
| 652 |
return region{}, 0, fmt.Errorf("Content-Range %q doesn't have enough information", header) |
| 653 |
} |
| 654 |
begin, err := strconv.ParseInt(submatches[1], 10, 64) |
| 655 |
if err != nil { |
| 656 |
return region{}, 0, fmt.Errorf("failed to parse beginning offset %q: %w", submatches[1], err) |
| 657 |
} |
| 658 |
end, err := strconv.ParseInt(submatches[2], 10, 64) |
| 659 |
if err != nil { |
| 660 |
return region{}, 0, fmt.Errorf("failed to parse end offset %q: %w", submatches[2], err) |
| 661 |
} |
| 662 |
blobSize, err := strconv.ParseInt(submatches[3], 10, 64) |
| 663 |
if err != nil { |
| 664 |
return region{}, 0, fmt.Errorf("failed to parse blob size %q: %w", submatches[3], err) |
| 665 |
} |
| 666 |
|
| 667 |
return region{begin, end}, blobSize, nil |
| 668 |
} |
| 669 |
|
| 670 |
type Option func(*options) |
| 671 |
|
| 672 |
type options struct { |
| 673 |
ctx context.Context |
| 674 |
cacheOpts []cache.Option |
| 675 |
} |
| 676 |
|
| 677 |
func WithContext(ctx context.Context) Option { |
| 678 |
return func(opts *options) { |
| 679 |
opts.ctx = ctx |
| 680 |
} |
| 681 |
} |
| 682 |
|
| 683 |
func WithCacheOpts(cacheOpts ...cache.Option) Option { |
| 684 |
return func(opts *options) { |
| 685 |
opts.cacheOpts = cacheOpts |
| 686 |
} |
| 687 |
} |
| 688 |
|
| 689 |
type remoteFetcher struct { |
| 690 |
r Fetcher |
| 691 |
} |
| 692 |
|
| 693 |
func (r *remoteFetcher) fetch(ctx context.Context, rs []region, retry bool) (multipartReadCloser, error) { |
| 694 |
var s regionSet |
| 695 |
for _, reg := range rs { |
| 696 |
s.add(reg) |
| 697 |
} |
| 698 |
reg := superRegion(s.rs) |
| 699 |
rc, err := r.r.Fetch(ctx, reg.b, reg.size()) |
| 700 |
if err != nil { |
| 701 |
return nil, err |
| 702 |
} |
| 703 |
return newSinglePartReader(reg, rc), nil |
| 704 |
} |
| 705 |
|
| 706 |
func (r *remoteFetcher) check() error { |
| 707 |
return r.r.Check() |
| 708 |
} |
| 709 |
|
| 710 |
func (r *remoteFetcher) genID(reg region) string { |
| 711 |
return r.r.GenID(reg.b, reg.size()) |
| 712 |
} |
| 713 |
|
| 714 |
type Handler interface { |
| 715 |
Handle(ctx context.Context, desc ocispec.Descriptor) (fetcher Fetcher, size int64, err error) |
| 716 |
} |
| 717 |
|
| 718 |
type Fetcher interface { |
| 719 |
Fetch(ctx context.Context, off int64, size int64) (io.ReadCloser, error) |
| 720 |
Check() error |
| 721 |
GenID(off int64, size int64) string |
| 722 |
} |