/
image.go
543 lines (511 loc) · 15.3 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Copyright (C) 2014-2018 Goodrain Co., Ltd.
// RAINBOND, Application Management Platform
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Rainbond,
// one or multiple Commercial Licenses authorized by Goodrain Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package sources
import (
"bufio"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/goodrain/rainbond/builder/model"
"github.com/goodrain/rainbond/event"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
//ErrorNoAuth error no auth
var ErrorNoAuth = fmt.Errorf("pull image require docker login")
//ErrorNoImage error no image
var ErrorNoImage = fmt.Errorf("image not exist")
//ImagePull pull docker image
//timeout minutes of the unit
func ImagePull(dockerCli *client.Client, image string, username, password string, logger event.Logger, timeout int) (*types.ImageInspect, error) {
if logger != nil {
logger.Info(fmt.Sprintf("start get image:%s", image), map[string]string{"step": "pullimage"})
}
var pullipo types.ImagePullOptions
if username != "" && password != "" {
auth, err := EncodeAuthToBase64(types.AuthConfig{Username: username, Password: password})
if err != nil {
logrus.Errorf("make auth base63 push image error: %s", err.Error())
logger.Error(fmt.Sprintf("Failed to generate a Token to get the image"), map[string]string{"step": "builder-exector", "status": "failure"})
return nil, err
}
pullipo = types.ImagePullOptions{
RegistryAuth: auth,
}
} else {
pullipo = types.ImagePullOptions{}
}
rf, err := reference.ParseAnyReference(image)
if err != nil {
logrus.Errorf("reference image error: %s", err.Error())
return nil, err
}
//最少一分钟
if timeout < 1 {
timeout = 1
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*time.Duration(timeout))
defer cancel()
//TODO: 使用1.12版本api的bug “repository name must be canonical”,使用rf.String()完整的镜像地址
readcloser, err := dockerCli.ImagePull(ctx, rf.String(), pullipo)
if err != nil {
logrus.Debugf("image name: %s readcloser error: %v", image, err.Error())
if strings.HasSuffix(err.Error(), "does not exist or no pull access") {
if logger != nil {
logger.Error(fmt.Sprintf("image: %s does not exist or is not available", image), map[string]string{"step": "pullimage", "status": "failure"})
}
return nil, fmt.Errorf("Image(%s) does not exist or no pull access", image)
}
return nil, err
}
defer readcloser.Close()
dec := json.NewDecoder(readcloser)
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
var jm JSONMessage
if err := dec.Decode(&jm); err != nil {
if err == io.EOF {
break
}
logrus.Debugf("error decoding jm(JSONMessage): %v", err)
return nil, err
}
if jm.Error != nil {
logrus.Debugf("error pulling image: %v", jm.Error)
return nil, jm.Error
}
if logger != nil {
logger.Debug(fmt.Sprintf(jm.JSONString()), map[string]string{"step": "progress"})
} else {
logrus.Debug(jm.JSONString())
}
}
logger.Debug("Get the image information and its raw representation", map[string]string{"step": "progress"})
ins, _, err := dockerCli.ImageInspectWithRaw(ctx, image)
if err != nil {
logger.Debug("Fail to get the image information and its raw representation", map[string]string{"step": "progress"})
return nil, err
}
logger.Info(fmt.Sprintf("Success Pull Image:%s", image), map[string]string{"step": "pullimage"})
return &ins, nil
}
//ImageTag change docker image tag
func ImageTag(dockerCli *client.Client, source, target string, logger event.Logger, timeout int) error {
if logger != nil {
logger.Info(fmt.Sprintf("change image tag:%s -> %s", source, target), map[string]string{"step": "changetag"})
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*time.Duration(timeout))
defer cancel()
err := dockerCli.ImageTag(ctx, source, target)
if err != nil {
logrus.Debugf("image tag err: %s", err.Error())
return err
}
logger.Info("change image tag success", map[string]string{"step": "changetag"})
return nil
}
//ImageNameHandle 解析imagename
func ImageNameHandle(imageName string) *model.ImageName {
var i model.ImageName
if strings.Contains(imageName, "/") {
mm := strings.Split(imageName, "/")
i.Host = mm[0]
names := strings.Join(mm[1:], "/")
if strings.Contains(names, ":") {
nn := strings.Split(names, ":")
i.Name = nn[0]
i.Tag = nn[1]
} else {
i.Name = names
i.Tag = "latest"
}
} else {
if strings.Contains(imageName, ":") {
nn := strings.Split(imageName, ":")
i.Name = nn[0]
i.Tag = nn[1]
} else {
i.Name = imageName
i.Tag = "latest"
}
}
return &i
}
//ImageNameWithNamespaceHandle if have namespace,will parse namespace
func ImageNameWithNamespaceHandle(imageName string) *model.ImageName {
var i model.ImageName
if strings.Contains(imageName, "/") {
mm := strings.Split(imageName, "/")
i.Host = mm[0]
names := strings.Join(mm[1:], "/")
if len(mm) >= 3 {
i.Namespace = mm[1]
names = strings.Join(mm[2:], "/")
}
if strings.Contains(names, ":") {
nn := strings.Split(names, ":")
i.Name = nn[0]
i.Tag = nn[1]
} else {
i.Name = names
i.Tag = "latest"
}
} else {
if strings.Contains(imageName, ":") {
nn := strings.Split(imageName, ":")
i.Name = nn[0]
i.Tag = nn[1]
} else {
i.Name = imageName
i.Tag = "latest"
}
}
return &i
}
// GenSaveImageName generates the final name of the image, which is the name of
// the image in the exported tar package.
func GenSaveImageName(name string) string {
imageName := ImageNameWithNamespaceHandle(name)
return fmt.Sprintf("%s:%s", imageName.Name, imageName.Tag)
}
//ImagePush push image to registry
//timeout minutes of the unit
func ImagePush(dockerCli *client.Client, image, user, pass string, logger event.Logger, timeout int) error {
if logger != nil {
logger.Info(fmt.Sprintf("start push image:%s", image), map[string]string{"step": "pushimage"})
}
if timeout < 1 {
timeout = 1
}
if user == "" {
user = os.Getenv("LOCAL_HUB_USER")
}
if pass == "" {
pass = os.Getenv("LOCAL_HUB_PASS")
}
ref, err := reference.ParseNormalizedNamed(image)
if err != nil {
return err
}
var opts types.ImagePushOptions
pushauth, err := EncodeAuthToBase64(types.AuthConfig{
Username: user,
Password: pass,
ServerAddress: reference.Domain(ref),
})
if err != nil {
logrus.Errorf("make auth base63 push image error: %s", err.Error())
if logger != nil {
logger.Error(fmt.Sprintf("Failed to generate a token to get the image"), map[string]string{"step": "builder-exector", "status": "failure"})
}
return err
}
opts.RegistryAuth = pushauth
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*time.Duration(timeout))
defer cancel()
readcloser, err := dockerCli.ImagePush(ctx, image, opts)
if err != nil {
if strings.Contains(err.Error(), "does not exist") {
if logger != nil {
logger.Error(fmt.Sprintf("image %s does not exist, cannot be pushed", image), map[string]string{"step": "pushimage", "status": "failure"})
}
return fmt.Errorf("Image(%s) does not exist", image)
}
return err
}
if readcloser != nil {
defer readcloser.Close()
dec := json.NewDecoder(readcloser)
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
var jm JSONMessage
if err := dec.Decode(&jm); err != nil {
if err == io.EOF {
break
}
return err
}
if jm.Error != nil {
return jm.Error
}
logger.Debug(jm.JSONString(), map[string]string{"step": "progress"})
}
}
logger.Info(fmt.Sprintf("success push image:%s", image), map[string]string{"step": "pushimage"})
return nil
}
//TrustedImagePush push image to trusted registry
func TrustedImagePush(dockerCli *client.Client, image, user, pass string, logger event.Logger, timeout int) error {
if err := CheckTrustedRepositories(image, user, pass); err != nil {
return err
}
return ImagePush(dockerCli, image, user, pass, logger, timeout)
}
//CheckTrustedRepositories check Repositories is exist ,if not create it.
func CheckTrustedRepositories(image, user, pass string) error {
ref, err := reference.ParseNormalizedNamed(image)
if err != nil {
return err
}
var server string
if reference.IsNameOnly(ref) {
server = "docker.io"
} else {
server = reference.Domain(ref)
}
cli, err := createTrustedRegistryClient(server, user, pass)
if err != nil {
return err
}
var namespace, repName string
infos := strings.Split(reference.TrimNamed(ref).String(), "/")
if len(infos) == 3 && infos[0] == server {
namespace = infos[1]
repName = infos[2]
}
if len(infos) == 2 {
namespace = infos[0]
repName = infos[1]
}
_, err = cli.GetRepository(namespace, repName)
if err != nil {
if err.Error() == "resource does not exist" {
rep := Repostory{
Name: repName,
ShortDescription: image, // The maximum length is 140
LongDescription: fmt.Sprintf("push image for %s", image),
Visibility: "private",
}
if len(rep.ShortDescription) > 140 {
rep.ShortDescription = rep.ShortDescription[0:140]
}
err := cli.CreateRepository(namespace, &rep)
if err != nil {
return fmt.Errorf("create repostory error,%s", err.Error())
}
return nil
}
return fmt.Errorf("get repostory error,%s", err.Error())
}
return err
}
// EncodeAuthToBase64 serializes the auth configuration as JSON base64 payload
func EncodeAuthToBase64(authConfig types.AuthConfig) (string, error) {
buf, err := json.Marshal(authConfig)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(buf), nil
}
//ImageBuild ImageBuild
func ImageBuild(dockerCli *client.Client, contextDir string, options types.ImageBuildOptions, logger event.Logger, timeout int) (string, error) {
var ctx context.Context
if timeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), time.Minute*time.Duration(timeout))
defer cancel()
} else {
ctx = context.Background()
}
buildCtx, err := archive.TarWithOptions(contextDir, &archive.TarOptions{
Compression: archive.Uncompressed,
ExcludePatterns: []string{""},
IncludeFiles: []string{"."},
})
if err != nil {
return "", err
}
rc, err := dockerCli.ImageBuild(ctx, buildCtx, options)
if err != nil {
return "", err
}
var out io.Writer
if logger != nil {
out = logger.GetWriter("build-progress", "info")
} else {
out, _ = os.OpenFile("/tmp/build.log", os.O_RDWR|os.O_CREATE, 0755)
}
var imageID string
err = jsonmessage.DisplayJSONMessagesStream(rc.Body, out, 0, true, func(msg jsonmessage.JSONMessage) {
var r types.BuildResult
imageID = r.ID
})
if err != nil {
logrus.Errorf("read build log failure %s", err.Error())
return "", err
}
return imageID, nil
}
//ImageInspectWithRaw get image inspect
func ImageInspectWithRaw(dockerCli *client.Client, image string) (*types.ImageInspect, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ins, _, err := dockerCli.ImageInspectWithRaw(ctx, image)
if err != nil {
return nil, err
}
return &ins, nil
}
//ImageSave save image to tar file
// destination destination file name eg. /tmp/xxx.tar
func ImageSave(dockerCli *client.Client, image, destination string, logger event.Logger) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
rc, err := dockerCli.ImageSave(ctx, []string{image})
if err != nil {
return err
}
defer rc.Close()
return CopyToFile(destination, rc)
}
//MultiImageSave save multi image to tar file
// destination destination file name eg. /tmp/xxx.tar
func MultiImageSave(ctx context.Context, dockerCli *client.Client, destination string, logger event.Logger, images ...string) error {
rc, err := dockerCli.ImageSave(ctx, images)
if err != nil {
return err
}
defer rc.Close()
return CopyToFile(destination, rc)
}
//ImageLoad load image from tar file
// destination destination file name eg. /tmp/xxx.tar
func ImageLoad(dockerCli *client.Client, tarFile string, logger event.Logger) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
reader, err := os.OpenFile(tarFile, os.O_RDONLY, 0644)
if err != nil {
return err
}
defer reader.Close()
rc, err := dockerCli.ImageLoad(ctx, reader, false)
if err != nil {
return err
}
if rc.Body != nil {
defer rc.Body.Close()
dec := json.NewDecoder(rc.Body)
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
var jm JSONMessage
if err := dec.Decode(&jm); err != nil {
if err == io.EOF {
break
}
return err
}
if jm.Error != nil {
return jm.Error
}
logger.Info(jm.JSONString(), map[string]string{"step": "build-progress"})
}
}
return nil
}
//ImageImport save image to tar file
// source source file name eg. /tmp/xxx.tar
func ImageImport(dockerCli *client.Client, image, source string, logger event.Logger) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
file, err := os.Open(source)
if err != nil {
return err
}
defer file.Close()
isource := types.ImageImportSource{
Source: file,
SourceName: "-",
}
options := types.ImageImportOptions{}
readcloser, err := dockerCli.ImageImport(ctx, isource, image, options)
if err != nil {
return err
}
if readcloser != nil {
defer readcloser.Close()
r := bufio.NewReader(readcloser)
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if line, _, err := r.ReadLine(); err == nil {
if logger != nil {
logger.Debug(string(line), map[string]string{"step": "progress"})
} else {
fmt.Println(string(line))
}
} else {
if err.Error() == "EOF" {
return nil
}
return err
}
}
}
return nil
}
// CopyToFile writes the content of the reader to the specified file
func CopyToFile(outfile string, r io.Reader) error {
// We use sequential file access here to avoid depleting the standby list
// on Windows. On Linux, this is a call directly to ioutil.TempFile
tmpFile, err := os.OpenFile(path.Join(filepath.Dir(outfile), ".docker_temp_"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer tmpFile.Close()
tmpPath := tmpFile.Name()
_, err = io.Copy(tmpFile, r)
if err != nil {
os.Remove(tmpPath)
return err
}
if err = os.Rename(tmpPath, outfile); err != nil {
os.Remove(tmpPath)
return err
}
return nil
}
//ImageRemove remove image
func ImageRemove(dockerCli *client.Client, image string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
_, err := dockerCli.ImageRemove(ctx, image, types.ImageRemoveOptions{Force: true})
return err
}