Debian Codegraph @

util/testutil/ensurehello.go

raw
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 package testutil
18
19 import (
20 "compress/gzip"
21 "context"
22 "fmt"
23 "io"
24 "net/http"
25 "os"
26
27 "github.com/containerd/containerd/content"
28 "github.com/containerd/containerd/content/local"
29 "github.com/containerd/containerd/images/archive"
30 "github.com/opencontainers/go-digest"
31 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
32 )
33
34 const (
35 // HelloArchiveURL points to an OCI archive of `hello-world`.
36 // Exported from `docker.io/library/hello-world@sha256:1a523af650137b8accdaed439c17d684df61ee4d74feac151b5b337bd29e7eec` .
37 // See https://github.com/AkihiroSuda/test-oci-archives/releases/tag/v20210101
38 HelloArchiveURL = "https://github.com/AkihiroSuda/test-oci-archives/releases/download/v20210101/hello-world.tar.gz"
39 // HelloArchiveDigest is the digest of the archive.
40 HelloArchiveDigest = "sha256:5aa022621c4de0e941ab2a30d4569c403e156b4ba2de2ec32e382ae8679f40e1"
41 )
42
43 // EnsureHello creates a temp content store and ensures `hello-world` image from HelloArchiveURL into the store.
44 func EnsureHello(ctx context.Context) (*ocispec.Descriptor, content.Store, error) {
45 // Pulling an image without the daemon is a mess, so we use OCI archive here.
46 resp, err := http.Get(HelloArchiveURL)
47 if err != nil {
48 return nil, nil, err
49 }
50 defer resp.Body.Close()
51
52 sha256Digester := digest.SHA256.Digester()
53 sha256Hasher := sha256Digester.Hash()
54 tr := io.TeeReader(resp.Body, sha256Hasher)
55 gzReader, err := gzip.NewReader(tr)
56 if err != nil {
57 return nil, nil, err
58 }
59
60 tempDir, err := os.MkdirTemp("", "test-estargz")
61 if err != nil {
62 return nil, nil, err
63 }
64
65 cs, err := local.NewStore(tempDir)
66 if err != nil {
67 return nil, nil, err
68 }
69
70 desc, err := archive.ImportIndex(ctx, cs, gzReader)
71 if err != nil {
72 return nil, nil, err
73 }
74 resp.Body.Close()
75 if d := sha256Digester.Digest().String(); d != HelloArchiveDigest {
76 err = fmt.Errorf("expected digest of %q to be %q, got %q", HelloArchiveURL, HelloArchiveDigest, d)
77 return nil, nil, err
78 }
79 return &desc, cs, nil
80 }