This repository has been archived by the owner on Oct 29, 2023. It is now read-only.
/
main.go
307 lines (286 loc) · 8.22 KB
/
main.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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/csmith/envflag"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/crane"
"github.com/google/go-containerregistry/pkg/name"
"github.com/greboid/golog"
"golang.org/x/time/rate"
"gopkg.in/yaml.v2"
)
var (
configLocation = flag.String("config", "/config.yml", "Specifies the location of the config file")
duration = flag.Duration("duration", 0, "Number of seconds between executions")
limit = flag.String("rate-limit", "", "The rate at which we mirror images")
log = logger.MustCreateLogger(false)
)
func main() {
envflag.Parse()
config, err := parseConfig(*configLocation)
if err != nil {
log.Fatalf("unable to load the config file: %s", err.Error())
}
parsedLimit, err := parseRate(*limit)
if err != nil {
log.Fatalf("Unable to parse rate limit %s", err.Error())
}
m := &DockerMirror{
Images: config.Images,
Registries: config.Registries,
Mirrors: config.Mirrors,
Limiter: rate.NewLimiter(parsedLimit, 1),
}
m.Limiter.Limit()
authn.DefaultKeychain = m
reposToMirror, err := m.getMirrorRegistries(m.Mirrors)
if err != nil {
log.Errorf("Unable to get repos from registries to mirror")
}
m.Images = append(m.Images, reposToMirror...)
if len(m.Images) == 0 {
log.Fatalf("No images to mirror, exiting.")
}
if *duration < time.Minute && len(*limit) == 0 {
m.mirrorRepos(m.Images)
return
}
for {
m.mirrorRepos(m.Images)
time.Sleep(*duration)
}
}
func parseRate(rateDescription string) (rate.Limit, error) {
if len(rateDescription) == 0 {
return rate.Inf, nil
}
parts := strings.Split(rateDescription, "/")
if len(parts) != 2 {
return -1, fmt.Errorf("unable to parse rate")
}
num, err := strconv.Atoi(parts[0])
if err != nil {
return -1, err
}
duration, err := time.ParseDuration(parts[1])
if err != nil {
return -1, err
}
limit := rate.Limit(float64(num) / duration.Seconds())
return limit, nil
}
func (m *DockerMirror) getMirrorRegistries(registries []Mirror) ([]Image, error) {
repos := make([]Image, 0)
for index := range registries {
newRepos, err := m.getMirrorRegistry(registries[index].From, registries[index].To, registries[index].Namespace)
if err == nil {
repos = append(repos, newRepos...)
}
}
return repos, nil
}
func (m *DockerMirror) getMirrorRegistry(source string, dest string, namespace string) ([]Image, error) {
mirrors := make([]Image, 0)
repos, err := m.getRepos(source)
if err != nil {
log.Fatalf("Error parsing mirror registry '%s': %s", source, err.Error())
}
for repoIndex := range repos {
sourceRegistry := repos[repoIndex].Context().RegistryStr()
repoName := strings.TrimPrefix(repos[repoIndex].Context().Name(), repos[repoIndex].Context().RegistryStr()+"/")
tag := repos[repoIndex].Identifier()
destRepo := repoName
if namespace != "" {
destRepo = fmt.Sprintf("%s/%s", namespace, repoName)
}
mirrors = append(mirrors, Image{
From: fmt.Sprintf("%s/%s:%s", sourceRegistry, repoName, tag),
To: fmt.Sprintf("%s/%s:%s", dest, destRepo, tag),
})
}
return mirrors, nil
}
func (m *DockerMirror) getRepos(registry string) ([]name.Reference, error) {
parts := strings.SplitN(registry, "/", 2)
if registry == "hub.docker.com" && len(m.Registries["hub.docker.com"].Username) > 0 && len(parts) == 1 {
return m.getDockerHubRepos(m.Registries["hub.docker.com"].Username)
} else if strings.HasPrefix(registry, "hub.docker.com") && len(parts) == 2 {
return m.getDockerHubRepos(parts[1])
} else if !strings.HasPrefix(registry, "hub.docker.com") {
return m.getRegistryRepos(registry)
}
return nil, errors.New("invalid format")
}
func (m *DockerMirror) getRegistryRepos(registry string) ([]name.Reference, error) {
repos, err := crane.Catalog(registry)
if err != nil {
return nil, err
}
refs := make([]name.Reference, 0)
for index := range repos {
image, err := name.ParseReference(fmt.Sprintf("%s/%s", registry, repos[index]))
if err != nil {
continue
}
refs = append(refs, image)
}
return refs, nil
}
func (m *DockerMirror) getDockerHubRepos(namespace string) ([]name.Reference, error) {
username, password := m.ResolveString("hub.docker.com")
resp, err := http.Post("https://hub.docker.com/v2/users/login/", "application/json",
strings.NewReader(fmt.Sprintf("{\"username\": \"%s\", \"password\": \"%s\"}", username, password)))
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
hubLoginResponse := &HubLoginResponse{}
err = json.Unmarshal(body, hubLoginResponse)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", fmt.Sprintf("https://hub.docker.com/v2/repositories/%s/?page_size=1000", namespace), nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("JWT %s", hubLoginResponse.Token))
client := http.Client{}
resp, err = client.Do(req)
if err != nil {
return nil, err
}
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
repos := &HubRepositoriesResponse{}
err = json.Unmarshal(body, repos)
if err != nil {
return nil, err
}
images := make([]string, 0)
for index := range repos.Images {
images = append(images, fmt.Sprintf("%s/%s", repos.Images[index].Namespace, repos.Images[index].Name))
}
refs := make([]name.Reference, 0)
for index := range images {
image, err := name.ParseReference(images[index])
if err != nil {
continue
}
refs = append(refs, image)
}
return refs, nil
}
type HubLoginResponse struct {
Token string `json:"token"`
Message string `json:"message"`
}
type HubRepositoriesResponse struct {
Count int `json:"count"`
Images []struct {
User string `json:"user"`
Name string `json:"name"`
Namespace string `json:"namespace"`
} `json:"results"`
}
type DockerMirror struct {
Images []Image
Registries map[string]Registry
Mirrors []Mirror
Limiter *rate.Limiter
}
func (m *DockerMirror) mirrorRepos(images []Image) {
total := len(images)
log.Infof("Starting to mirror %d images", total)
failed := 0
success := 0
for repo := range images {
err := m.Limiter.Wait(context.Background())
if err != nil {
log.Fatalf("Rate limiter error: %s", err.Error())
}
err = crane.Copy(images[repo].From, images[repo].To)
if err != nil {
failed++
log.Errorf("Failed to mirror %s to %s: %s", images[repo].From, images[repo].To, err.Error())
} else {
success++
log.Infof("Succeeded to mirror %s to %s", images[repo].From, images[repo].To)
}
}
log.Infof("Finished mirroring, %d succeeded, %d failed", success, failed)
}
func (m *DockerMirror) Resolve(resource authn.Resource) (authn.Authenticator, error) {
username, password := m.ResolveString(resource.RegistryStr())
return authn.FromConfig(authn.AuthConfig{
Username: username,
Password: password,
}), nil
}
func (m *DockerMirror) ResolveString(resource string) (string, string) {
var value Registry
var ok bool
if resource == name.DefaultRegistry {
value, ok = m.Registries["hub.docker.com"]
} else {
value, ok = m.Registries[resource]
}
if !ok {
return "", ""
}
return value.Username, value.Password
}
type Config struct {
Images []Image `yaml:"images"`
Registries map[string]Registry `yaml:"registries"`
Mirrors []Mirror `yaml:"mirrors"`
}
type Registry struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
}
type Image struct {
From string `yaml:"from"`
To string `yaml:"to"`
}
type Mirror struct {
From string `yaml:"from"`
To string `yaml:"to"`
Namespace string `yaml:"namespace"`
}
func parseConfig(configPath string) (*Config, error) {
s, err := os.Stat(configPath)
if err != nil {
return nil, fmt.Errorf("'%s' does not exist", configPath)
}
if s.IsDir() {
return nil, fmt.Errorf("'%s' is not a file", configPath)
}
config := &Config{}
file, err := os.Open(configPath)
if err != nil {
return nil, fmt.Errorf("unable to open '%s'", configPath)
}
defer func() {
_ = file.Close()
}()
if err := yaml.NewDecoder(file).Decode(config); err != nil {
return nil, fmt.Errorf("parse error: %s", err.Error())
}
return config, nil
}