-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpull.go
88 lines (77 loc) · 1.99 KB
/
dpull.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
package dpull
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"github.com/containerd/containerd/errdefs"
"github.com/fatih/color"
"github.com/pkg/errors"
"io"
"os"
"strings"
"time"
)
type Proxy struct {
Option Option
DockerClient *Client
GitClient *GitClient
}
type PullOption struct {
ForceProxy bool
}
func (p *Proxy) Pull(ctx context.Context, ref string, opt PullOption) error {
// 1. get domain
domain, _ := splitDockerDomain(ref)
if domain == defaultDomain && !opt.ForceProxy {
color.Green("pulling image %s ...", ref)
err := p.DockerClient.Pull(ref, os.Stdout)
if err != nil {
return err
}
color.Green("pulling image %s done", ref)
return nil
}
imgTag := strings.Replace(base64.StdEncoding.EncodeToString([]byte(ref)), "=", "_", -1)
color.Green("pulling from proxy")
color.Green("(1/5) modify dockerfile...")
filename, err := p.GitClient.ModifyDockerfile(ref, imgTag)
if err != nil {
return err
}
color.Green("(2/5) commit changes...")
msg := fmt.Sprintf("modify image %s", ref)
err = p.GitClient.AddAndCommit([]string{filename}, msg)
if err != nil {
return err
}
color.Green("(3/5) push tag to remote...")
tag, err := p.GitClient.TagAndPush(imgTag, msg)
imgWithTag := fmt.Sprintf("%s:%s", p.Option.MirrorOption.ImageBasePath, tag)
color.Green("(4/5) wait remote building...")
now := time.Now()
buf := bytes.NewBuffer(nil)
for {
err := p.DockerClient.Pull(imgWithTag, buf)
if err != nil {
time.Sleep(time.Second)
if errdefs.IsNotFound(err) {
color.Green("(5/5) waiting %s, press ^-C to cancel \r", time.Now().Sub(now).String())
}
continue
}
color.Green("(4/5) pulling...")
io.Copy(os.Stdout, buf)
break
}
err = p.DockerClient.Tag(imgWithTag, ref)
if err != nil {
return errors.Wrap(err, "failed to tag image: "+imgWithTag+" to "+ref)
}
err = p.DockerClient.Remove(imgWithTag)
if err != nil {
return errors.Wrap(err, "failed to remove image: "+imgWithTag)
}
color.Green("download %s success", ref)
return nil
}