-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
docker.go
67 lines (57 loc) · 1.86 KB
/
docker.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
package daemon
import (
"context"
"os"
"github.com/docker/docker/client"
"github.com/google/go-containerregistry/pkg/name"
"golang.org/x/xerrors"
)
// DockerImage implements v1.Image by extending daemon.Image.
// The caller must call cleanup() to remove a temporary file.
func DockerImage(ref name.Reference, host string) (Image, func(), error) {
cleanup := func() {}
opts := []client.Opt{client.FromEnv, client.WithAPIVersionNegotiation()}
if host != "" {
// adding host parameter to the last assuming it will pickup more preference
opts = append(opts, client.WithHost(host))
}
c, err := client.NewClientWithOpts(opts...)
if err != nil {
return nil, cleanup, xerrors.Errorf("failed to initialize a docker client: %w", err)
}
defer func() {
if err != nil {
_ = c.Close()
}
}()
// <image_name>:<tag> pattern like "alpine:3.15"
// or
// <image_name>@<digest> pattern like "alpine@sha256:21a3deaa0d32a8057914f36584b5288d2e5ecc984380bc0118285c70fa8c9300"
imageID := ref.Name()
inspect, _, err := c.ImageInspectWithRaw(context.Background(), imageID)
if err != nil {
imageID = ref.String() // <image_id> pattern like `5ac716b05a9c`
inspect, _, err = c.ImageInspectWithRaw(context.Background(), imageID)
if err != nil {
return nil, cleanup, xerrors.Errorf("unable to inspect the image (%s): %w", imageID, err)
}
}
history, err := c.ImageHistory(context.Background(), imageID)
if err != nil {
return nil, cleanup, xerrors.Errorf("unable to get history (%s): %w", imageID, err)
}
f, err := os.CreateTemp("", "fanal-*")
if err != nil {
return nil, cleanup, xerrors.Errorf("failed to create a temporary file")
}
cleanup = func() {
_ = c.Close()
_ = f.Close()
_ = os.Remove(f.Name())
}
return &image{
opener: imageOpener(context.Background(), imageID, f, c.ImageSave),
inspect: inspect,
history: configHistory(history),
}, cleanup, nil
}