/
pull.go
99 lines (96 loc) · 2.4 KB
/
pull.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
package docker
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"io/ioutil"
"log"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/loqutus/artifactory-replication/pkg/credentials"
)
func pullImage(image ImageToReplicate, creds credentials.Creds) error {
sourceImage := image.SourceRegistry + "/" + image.SourceImage + ":" + image.SourceTag
log.Println("Pulling " + sourceImage)
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return err
}
defer cli.Close()
cli.NegotiateAPIVersion(ctx)
if creds.SourceUser != "" || creds.SourcePassword != "" {
authConfig := types.AuthConfig{
Username: creds.SourceUser,
Password: creds.SourcePassword,
}
encodedJSON, err := json.Marshal(authConfig)
if err != nil {
return err
}
authStr := base64.URLEncoding.EncodeToString(encodedJSON)
var failed bool
backOffTime := backOffStart
var out io.ReadCloser
for i := 1; i <= backOffSteps; i++ {
out, err = cli.ImagePull(ctx, sourceImage, types.ImagePullOptions{RegistryAuth: authStr})
if err != nil {
failed = true
log.Print("error pulling image", sourceImage, "retry", string(i))
if i != backOffSteps {
time.Sleep(time.Duration(backOffTime) * time.Millisecond)
}
backOffTime *= i
} else {
defer out.Close()
failed = false
break
}
}
if failed == true {
return err
}
buf := new(bytes.Buffer)
buf.ReadFrom(out)
newStr := buf.String()
if strings.Contains(newStr, "error") || strings.Contains(newStr, "Error") {
return errors.New(newStr)
}
io.Copy(ioutil.Discard, out)
} else {
var failed bool
backOffTime := backOffStart
var out io.ReadCloser
for i := 1; i <= backOffSteps; i++ {
out, err = cli.ImagePull(ctx, sourceImage, types.ImagePullOptions{})
if err != nil {
failed = true
log.Print("error pulling image", sourceImage, "retry", string(i))
if i != backOffSteps {
time.Sleep(time.Duration(backOffTime) * time.Millisecond)
}
backOffTime *= i
} else {
failed = false
break
}
}
if failed == true {
return err
}
defer out.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(out)
newStr := buf.String()
if strings.Contains(newStr, "error") || strings.Contains(newStr, "Error") {
return errors.New(newStr)
}
io.Copy(ioutil.Discard, out)
}
return nil
}