-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.go
355 lines (298 loc) · 8.99 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package main
import (
"context"
"encoding/json"
"errors"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/archive"
"io/ioutil"
"net/http"
"path"
"strings"
"time"
)
type dockerImage struct {
client *client.Client
}
type imageName struct {
Name string
DockerRegistry string
}
func (n imageName) GetFullImageName() string {
if n.DockerRegistry != "" {
if !strings.HasSuffix(n.DockerRegistry, "/") {
n.DockerRegistry = n.DockerRegistry + "/"
}
}
return n.DockerRegistry + n.Name
}
func NewImageName(name, dockerRegistry string) *imageName {
return &imageName{Name: name, DockerRegistry: dockerRegistry}
}
func NewDockerImage(client *client.Client) *dockerImage {
return &dockerImage{client: client}
}
func (d *dockerImage) ListImages() ([]types.ImageSummary, error) {
imagesSummeries, err := d.client.ImageList(context.Background(), types.ImageListOptions{})
if err != nil {
return imagesSummeries, err
}
for _, summery := range imagesSummeries {
//fmt.Println(summery.ID)
log.Debug(summery.RepoTags)
}
return imagesSummeries, err
}
func (d *dockerImage) BuildImage(dockerfileContent string, enginePath string, dockerName string) error {
err := ioutil.WriteFile(path.Join(enginePath, "Dockerfile"), []byte(dockerfileContent), 0644)
if err != nil {
return err
}
log.Debugf("Docker context dir: %s and engine path: %s", enginePath, enginePath)
compression := archive.Uncompressed
buildCtx, err := archive.TarWithOptions(enginePath, &archive.TarOptions{
Compression: compression,
ExcludePatterns: []string{},
IncludeFiles: []string{},
})
if err != nil {
log.Debugf("Archive build conext error %s", err.Error())
return err
}
log.Debugf("Docker files: %s", "Dockerfile")
buildResponse, err := d.client.ImageBuild(context.Background(), buildCtx, types.ImageBuildOptions{Tags: []string{dockerName}, Dockerfile: "Dockerfile"})
if err != nil {
log.Debugf("Build image error %s", err.Error())
return err
}
log.Debugf("Build os type %s", buildResponse.OSType)
b, err := ioutil.ReadAll(buildResponse.Body)
if err != nil {
log.Debugf("Read build response from read error %s", err.Error())
return err
}
log.Debugf("Build image response %s", string(b))
return nil
}
func (d *dockerImage) TagImage(repositoryName string, ref string) error {
return d.client.ImageTag(context.Background(), repositoryName, ref)
}
func (d *dockerImage) PullImage(repositoryName string) error {
options := types.ImagePullOptions{}
reader, err := d.client.ImagePull(context.Background(), repositoryName, options)
if err != nil {
log.Errorf("Pull images error %s", err.Error())
return err
}
b, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
log.Debugf("pull image response %s", string(b))
defer reader.Close()
return nil
}
func (d *dockerImage) PushImages(repositoryName string) error {
buildResponse, err := d.client.ImagePush(context.Background(), repositoryName, types.ImagePushOptions{RegistryAuth: ""})
if err != nil {
return err
}
b, err := ioutil.ReadAll(buildResponse)
if err != nil {
return err
}
log.Debugf("push image response %s", string(b))
return nil
}
func (d *dockerImage) DelImage(repositoryName string) ([]types.ImageDelete, error) {
client, err := client.NewEnvClient()
dels, err := client.ImageRemove(context.Background(), repositoryName, types.ImageRemoveOptions{Force: true})
log.Debugf("Delete image response %+v", dels)
return dels, err
}
func (d *dockerImage) RunContainer(name imageName, containerName string, conf *container.Config, hostConf *container.HostConfig) (string, error) {
config := container.Config{}
config.Image = name.GetFullImageName()
id, err := d.CreateContainer(containerName, conf, hostConf)
if err != nil {
return id, err
}
log.Debugf("Create container %s done", id)
err = d.StartContainer(id)
if err != nil {
return "", err
}
log.Debugf("Start container %s done", id)
return id, nil
}
func (d *dockerImage) InspectContainer(containerId string) (types.ContainerJSON, error) {
result, err := d.client.ContainerInspect(context.Background(), containerId)
if err != nil {
log.Errorf("Inspect container error: %s", err.Error())
return types.ContainerJSON{}, err
}
log.Debugf("status is: %s ", result.State.Status)
return result, nil
}
func (d *dockerImage) StatusContainer(containerId string) (string, error) {
result, err := d.client.ContainerInspect(context.Background(), containerId)
if err != nil {
log.Errorf("Inspect container error: %s", err.Error())
return "", err
}
log.Debugf("status is: %s ", result.State.Status)
return result.State.Status, nil
}
func (d *dockerImage) WaitContainerDone(containerId string) error {
done := make(chan bool)
cErr := make(chan error)
go func() {
status, err := d.StatusContainer(containerId)
for {
if err != nil {
done <- true
cErr <- err
}
log.Debugf("Container %s status %s", containerId, status)
if strings.EqualFold("done", status) || strings.EqualFold("exited", status) {
done <- true
cErr <- nil
} else {
time.Sleep(1 * time.Second)
status, err = d.StatusContainer(containerId)
}
}
}()
<-done
err := <-cErr
return err
}
func (d *dockerImage) StartContainer(containerId string) error {
startOptions := types.ContainerStartOptions{}
err := d.client.ContainerStart(context.Background(), containerId, startOptions)
if err != nil {
log.Errorf("Start container error: %s", err.Error())
return err
}
return nil
}
func (d *dockerImage) ContainerLog(containerId string) (string, error) {
logOptions := types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true}
reader, err := d.client.ContainerLogs(context.Background(), containerId, logOptions)
if err != nil {
log.Errorf("Start container error: %s", err.Error())
return "", err
}
b, err := ioutil.ReadAll(reader)
if err != nil {
log.Errorf("Read container log from reader error: %s", err.Error())
return "", err
}
log.Debugf(string(b))
return string(b), nil
}
func (d *dockerImage) CreateContainer(containerName string, conf *container.Config, hostConf *container.HostConfig) (string, error) {
res, err := d.client.ContainerCreate(context.Background(), conf, hostConf, nil, containerName)
if err != nil {
log.Errorf("Create container error: %s", err.Error())
if strings.Contains(err.Error(), "No such image") {
//Pull from registry
log.Debugf("Pulling image: %s", conf.Image)
err := d.PullImage(conf.Image)
if err != nil {
return "", err
}
s, err := d.CreateContainer(containerName, conf, hostConf)
if err != nil {
return "", err
}
return s, nil
} else if strings.Contains(err.Error(), "is already in use by container") {
log.Debugf("remove container name %s", containerName)
err := d.RemoveContainer(containerName)
if err != nil {
log.Errorf("Remove container error")
} else {
s, err := d.CreateContainer(containerName, conf, hostConf)
if err != nil {
return "", err
}
return s, nil
}
} else {
return "", err
}
}
return res.ID, nil
}
func (d *dockerImage) RemoveContainer(containerId string) error {
options := types.ContainerRemoveOptions{Force: true}
err := d.client.ContainerRemove(context.Background(), containerId, options)
if err != nil {
log.Errorf("Rmove container %s error: %s", containerId, err.Error())
return err
}
return nil
}
func (d *dockerImage) RemoveContainers(containerIds []string) error {
options := types.ContainerRemoveOptions{Force: true}
for _, v := range containerIds {
err := d.client.ContainerRemove(context.Background(), v, options)
if err != nil {
log.Errorf("Rmove container %s error: %s", v, err.Error())
return err
}
}
return nil
}
func (d *dockerImage) CheckImagesExistInDockerRegistry(name imageName) (bool, error) {
if name.DockerRegistry == "" {
return false, errors.New("Docker registry cannot empty")
}
var url = ""
if strings.HasSuffix(name.DockerRegistry, "/") {
url = "http://" + name.DockerRegistry + "2/" + GetImageName(name.Name) + "/tags/list"
} else {
url = "http://" + name.DockerRegistry + "/2/" + GetImageName(name.Name) + "/tags/list"
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return false, err
}
results := map[string]interface{}{}
err = json.Unmarshal(body, &results)
if err != nil {
return false, err
}
tags := results["tags"].([]string)
for _, tag := range tags {
if strings.EqualFold(tag, GetImageTag(name.Name)) {
return true, nil
}
}
return false, nil
}
func GetImageName(imageName string) string {
if strings.Index(imageName, ":") > 0 {
return strings.Split(imageName, ":")[0]
}
return imageName
}
func GetImageTag(imageName string) string {
if strings.Index(imageName, ":") > 0 {
return strings.Split(imageName, ":")[1]
}
return imageName
}