-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimage.go
181 lines (156 loc) · 4.19 KB
/
image.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
package containers
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
)
// Image initializes the given image, and attempts to pull the container from docker hub.
// If the Build() Option is provided then the given DockerFile tarball is built and returned.
func (c *Client) Image(ctx context.Context, name string, options ...ImageOption) (image *Image, err error) {
image = &Image{
client: c,
image: name,
}
for _, opt := range options {
if err := opt(image); err != nil {
return nil, errorImageOptions(name, err)
}
}
imageExists := image.checkImageExists(ctx)
if image.buildTarball != nil && (ForceRebuild || !imageExists) {
if err := image.buildImage(ctx); err != nil {
return nil, errorImageBuild(name, err)
}
} else {
if image, err = image.Pull(ctx); err != nil {
err = errorImagePull(name, err)
if !imageExists {
image = nil
}
return image, err
}
}
return
}
// checkImage checks the docker host client if the image is known.
func (i *Image) checkImageExists(ctx context.Context) bool {
res, err := i.client.ImageList(ctx, types.ImageListOptions{
Filters: NewFilter("reference", i.image),
})
return err == nil && len(res) > 0
}
// buildImage builds a DockerFile tarball as a docker image.
func (i *Image) buildImage(ctx context.Context) error {
imageBuildResponse, err := i.client.ImageBuild(
ctx,
i.buildTarball,
types.ImageBuildOptions{
Context: i.buildTarball,
Dockerfile: "Dockerfile",
Tags: []string{i.image},
Remove: true,
},
)
if err != nil {
return errorImageBuildDockerFile(err)
}
defer imageBuildResponse.Body.Close()
if _, err = io.Copy(os.Stdout, imageBuildResponse.Body); err != nil {
return errorImageBuildResCopy(err)
}
return nil
}
// Pull retrieves latest changes to the image from docker hub.
func (i *Image) Pull(ctx context.Context) (*Image, error) {
reader, err := i.client.ImagePull(ctx, i.image, types.ImagePullOptions{})
if err != nil {
return i, errorClientPull(err)
}
defer reader.Close()
fileScanner := bufio.NewScanner(reader)
fileScanner.Split(bufio.ScanLines)
for fileScanner.Scan() {
var line = fileScanner.Bytes()
var status struct {
Status string
ProgressDetail struct {
Current int
Total int
}
Id string
}
if err = json.Unmarshal(line, &status); err != nil {
return i, errorImagePullStatus(err)
}
}
return i, nil
}
// Instantiate sets given options and creates the container from the docker image.
func (i *Image) Instantiate(ctx context.Context, options ...ContainerOption) (*Container, error) {
c := &Container{
image: i,
}
for _, opt := range options {
err := opt(c)
if err != nil {
return nil, errorContainerOptions(i.image, err)
}
}
mounts := make([]mount.Mount, len(c.volumes))
for idx, volume := range c.volumes {
mounts[idx] = mount.Mount{
Type: mount.TypeBind,
Source: volume.source,
Target: volume.target,
}
}
config := &container.Config{
Image: i.image,
Cmd: c.cmd,
Shell: c.shell,
Tty: false,
Env: c.env,
}
if len(c.workDir) > 0 {
config.WorkingDir = c.workDir
}
resp, err := c.image.client.ContainerCreate(ctx, config, &container.HostConfig{Mounts: mounts}, nil, nil, "")
if err != nil {
return nil, errorContainerCreate(c.image.Name(), err)
}
c.id = resp.ID
return c, nil
}
// Clean removes all docker images that match the given filter, and max age.
func (c *Client) Clean(ctx context.Context, age time.Duration, filter filters.Args) error {
images, _ := c.ImageList(ctx, types.ImageListOptions{Filters: filter})
timeNow := time.Now()
var err error
for _, image := range images {
if time.Unix(image.Created, 0).Add(age).Before(timeNow) {
if _, _err := c.ImageRemove(ctx, image.ID, types.ImageRemoveOptions{
Force: true,
PruneChildren: true,
}); _err != nil {
if err != nil {
err = fmt.Errorf("%s:%w", err, _err)
} else {
err = _err
}
}
}
}
return err
}
// Name returns the name of the image
func (i *Image) Name() string {
return i.image
}