|
| 1 | +package docker |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + "path" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/Sirupsen/logrus" |
| 11 | + "github.com/containerd/containerd/images" |
| 12 | + "github.com/containerd/containerd/log" |
| 13 | + ocispec "github.com/opencontainers/image-spec/specs-go/v1" |
| 14 | + "github.com/pkg/errors" |
| 15 | +) |
| 16 | + |
| 17 | +type dockerFetcher struct { |
| 18 | + *dockerBase |
| 19 | +} |
| 20 | + |
| 21 | +func (r dockerFetcher) Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) { |
| 22 | + ctx = log.WithLogger(ctx, log.G(ctx).WithFields( |
| 23 | + logrus.Fields{ |
| 24 | + "base": r.base.String(), |
| 25 | + "digest": desc.Digest, |
| 26 | + }, |
| 27 | + )) |
| 28 | + |
| 29 | + paths, err := getV2URLPaths(desc) |
| 30 | + if err != nil { |
| 31 | + return nil, err |
| 32 | + } |
| 33 | + |
| 34 | + for _, path := range paths { |
| 35 | + u := r.url(path) |
| 36 | + |
| 37 | + req, err := http.NewRequest(http.MethodGet, u, nil) |
| 38 | + if err != nil { |
| 39 | + return nil, err |
| 40 | + } |
| 41 | + |
| 42 | + req.Header.Set("Accept", strings.Join([]string{desc.MediaType, `*`}, ", ")) |
| 43 | + resp, err := r.doRequestWithRetries(ctx, req, nil) |
| 44 | + if err != nil { |
| 45 | + return nil, err |
| 46 | + } |
| 47 | + |
| 48 | + if resp.StatusCode > 299 { |
| 49 | + if resp.StatusCode == http.StatusNotFound { |
| 50 | + continue // try one of the other urls. |
| 51 | + } |
| 52 | + resp.Body.Close() |
| 53 | + return nil, errors.Errorf("unexpected status code %v: %v", u, resp.Status) |
| 54 | + } |
| 55 | + |
| 56 | + return resp.Body, nil |
| 57 | + } |
| 58 | + |
| 59 | + return nil, errors.New("not found") |
| 60 | +} |
| 61 | + |
| 62 | +// getV2URLPaths generates the candidate urls paths for the object based on the |
| 63 | +// set of hints and the provided object id. URLs are returned in the order of |
| 64 | +// most to least likely succeed. |
| 65 | +func getV2URLPaths(desc ocispec.Descriptor) ([]string, error) { |
| 66 | + var urls []string |
| 67 | + |
| 68 | + switch desc.MediaType { |
| 69 | + case images.MediaTypeDockerSchema2Manifest, images.MediaTypeDockerSchema2ManifestList, |
| 70 | + ocispec.MediaTypeImageManifest, ocispec.MediaTypeImageIndex: |
| 71 | + urls = append(urls, path.Join("manifests", desc.Digest.String())) |
| 72 | + } |
| 73 | + |
| 74 | + // always fallback to attempting to get the object out of the blobs store. |
| 75 | + urls = append(urls, path.Join("blobs", desc.Digest.String())) |
| 76 | + |
| 77 | + return urls, nil |
| 78 | +} |
0 commit comments