/
manifest.go
394 lines (318 loc) · 10.3 KB
/
manifest.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
package manifest
import (
"bufio"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/plexsystems/sinker/internal/docker"
"gopkg.in/yaml.v2"
)
// Manifest contains all of the sources to push to a target registry.
type Manifest struct {
Target Target `yaml:"target"`
Sources []Source `yaml:"sources,omitempty"`
}
// Get returns the manifest found at the specified path.
func Get(path string) (Manifest, error) {
manifestLocation := getManifestLocation(path)
manifestContents, err := ioutil.ReadFile(manifestLocation)
if err != nil {
return Manifest{}, fmt.Errorf("reading manifest: %w", err)
}
var manifest Manifest
if err := yaml.Unmarshal(manifestContents, &manifest); err != nil {
return Manifest{}, fmt.Errorf("unmarshal manifest: %w", err)
}
// When a source in the manifest does not define its own target the default target
// should be the target defined in the manifest.
for s := range manifest.Sources {
if manifest.Sources[s].Target.Host == "" {
manifest.Sources[s].Target = manifest.Target
}
}
return manifest, nil
}
// Write writes the contents of the manifest to disk at the specified path.
func (m Manifest) Write(path string) error {
imageManifestContents, err := yaml.Marshal(&m)
if err != nil {
return fmt.Errorf("marshal image manifest: %w", err)
}
manifestLocation := getManifestLocation(path)
if err := ioutil.WriteFile(manifestLocation, imageManifestContents, os.ModePerm); err != nil {
return fmt.Errorf("creating file: %w", err)
}
return nil
}
func (m Manifest) Update(images []string) Manifest {
var updatedSources []Source
for _, updatedImage := range images {
updatedRegistryPath := docker.RegistryPath(updatedImage)
updatedSource := Source{
Tag: updatedRegistryPath.Tag(),
Digest: updatedRegistryPath.Digest(),
}
foundSource, exists := m.findSourceInManifest(updatedImage)
if !exists {
// When the source host and the target host are the same, this means that the
// images that were retrieved are target images. Therefore, we must attempt to
// find the source host from the repository of the image.
//
// When the source host and target host are different, we can safely use the
// host found in the image manifest as the source.
updatedSource.Host = updatedRegistryPath.Host()
if updatedRegistryPath.Host() == m.Target.Host {
updatedSource.Host = getSourceHostFromRepository(updatedRegistryPath.Repository())
}
updatedRepository := updatedRegistryPath.Repository()
updatedRepository = strings.Replace(updatedRepository, m.Target.Repository, "", 1)
updatedRepository = strings.TrimLeft(updatedRepository, "/")
updatedSource.Repository = updatedRepository
updatedSources = append(updatedSources, updatedSource)
continue
}
updatedSource.Repository = foundSource.Repository
updatedSource.Host = foundSource.Host
updatedSource.Auth = foundSource.Auth
// If the target host (or repository) of the source does not match the manifest
// target host (or repository), it has been modified by the user.
//
// To preserve the current settings, set the manifest host and repository values
// to the ones present in the current manifest.
if foundSource.Target.Host != m.Target.Host ||
foundSource.Target.Repository != m.Target.Repository {
updatedSource.Target = foundSource.Target
}
updatedSources = append(updatedSources, updatedSource)
}
updatedManifest := Manifest{
Target: m.Target,
Sources: updatedSources,
}
return updatedManifest
}
// Auth is a username and password to authenticate to a registry.
type Auth struct {
Username string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
}
// Target is the target registry where the images defined in
// the manifest will be pushed to.
type Target struct {
Host string `yaml:"host,omitempty"`
Repository string `yaml:"repository,omitempty"`
Auth Auth `yaml:"auth,omitempty"`
}
// EncodedAuth returns the Base64 encoded auth for the target registry.
func (t Target) EncodedAuth() (string, error) {
if t.Auth.Password != "" {
auth, err := getEncodedBasicAuth(os.Getenv(t.Auth.Username), os.Getenv(t.Auth.Password))
if err != nil {
return "", fmt.Errorf("get encoded auth: %w", err)
}
return auth, nil
}
auth, err := docker.GetEncodedAuthForHost(t.Host)
if err != nil {
return "", fmt.Errorf("get encoded auth for host: %w", err)
}
return auth, nil
}
// Source is a container image in the manifest.
type Source struct {
Repository string `yaml:"repository"`
Host string `yaml:"host,omitempty"`
Target Target `yaml:"target,omitempty"`
Tag string `yaml:"tag,omitempty"`
Digest string `yaml:"digest,omitempty"`
Auth Auth `yaml:"auth,omitempty"`
}
// Image returns the source image including its tag or digest.
func (s Source) Image() string {
var source string
if s.Tag != "" {
source = ":" + s.Tag
} else if s.Digest != "" {
source = "@" + s.Digest
}
if s.Repository != "" {
source = "/" + s.Repository + source
}
if s.Host != "" {
source = "/" + s.Host + source
}
source = strings.TrimLeft(source, "/")
return source
}
// TargetImage returns the target image including its tag or digest.
func (s Source) TargetImage() string {
var target string
if s.Tag != "" {
target = ":" + s.Tag
} else if s.Digest != "" {
target = strings.ReplaceAll(s.Digest, "sha256:", "")
target = ":" + target
}
if s.Repository != "" {
if hostSupportsNestedRepositories(s.Target.Host) {
target = "/" + s.Repository + target
} else {
target = "/" + filepath.Base(s.Repository) + target
}
}
if s.Target.Repository != "" {
target = "/" + s.Target.Repository + target
}
if s.Target.Host != "" {
target = "/" + s.Target.Host + target
}
target = strings.TrimLeft(target, "/")
return target
}
// EncodedAuth returns the Base64 encoded auth for the source registry.
func (s Source) EncodedAuth() (string, error) {
if s.Auth.Password != "" {
auth, err := getEncodedBasicAuth(os.Getenv(s.Auth.Username), os.Getenv(s.Auth.Password))
if err != nil {
return "", fmt.Errorf("get encoded auth: %w", err)
}
return auth, nil
}
auth, err := docker.GetEncodedAuthForHost(s.Host)
if err != nil {
return "", fmt.Errorf("get encoded auth for host: %w", err)
}
return auth, nil
}
// GetSourcesFromImages returns the given images as sources with the specified target.
func GetSourcesFromImages(images []string, target string) []Source {
images = dedupeImages(images)
targetRegistryPath := docker.RegistryPath(target)
sourceTarget := Target{
Host: targetRegistryPath.Host(),
Repository: targetRegistryPath.Repository(),
}
var sources []Source
for _, image := range images {
registryPath := docker.RegistryPath(image)
source := Source{
Host: registryPath.Host(),
Target: sourceTarget,
Repository: registryPath.Repository(),
Tag: registryPath.Tag(),
Digest: registryPath.Digest(),
}
sources = append(sources, source)
}
return sources
}
// GetImagesFromStandardInput gets a list of images passed in by standard input.
func GetImagesFromStandardInput() ([]string, error) {
standardInReader := ioutil.NopCloser(bufio.NewReader(os.Stdin))
byteContents, err := ioutil.ReadAll(standardInReader)
if err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
contents := string(byteContents)
if strings.Contains(contents, "---") {
images, err := GetImagesFromKubernetesResources([]string{contents})
if err != nil {
return nil, fmt.Errorf("get images from resources: %w", err)
}
return images, nil
}
var images []string
if strings.Contains(contents, " ") {
images = strings.Split(contents, " ")
} else if strings.Contains(contents, "\n") {
images = strings.Split(contents, "\n")
}
images = dedupeImages(images)
return images, nil
}
func getSourceHostFromRepository(repository string) string {
repositoryMappings := map[string]string{
"kubernetes-ingress-controller": "quay.io",
"coreos": "quay.io",
"open-policy-agent": "quay.io",
"twistlock": "registry.twistlock.com",
"etcd": "k8s.gcr.io",
"kube-apiserver": "k8s.gcr.io",
"coredns": "k8s.gcr.io",
"kube-proxy": "k8s.gcr.io",
"kube-scheduler": "k8s.gcr.io",
"kube-controller-manager": "k8s.gcr.io",
}
for repositorySegment, host := range repositoryMappings {
if strings.Contains(repository, repositorySegment) {
return host
}
}
// An empty host refers to an image that is on Docker Hub.
return ""
}
func (m Manifest) findSourceInManifest(image string) (Source, bool) {
for _, currentSource := range m.Sources {
imagePath := docker.RegistryPath(image)
sourceImagePath := docker.RegistryPath(currentSource.Image())
targetImagePath := docker.RegistryPath(currentSource.TargetImage())
if imagePath.Host() == sourceImagePath.Host() && imagePath.Repository() == sourceImagePath.Repository() {
return currentSource, true
}
if imagePath.Host() == targetImagePath.Host() && imagePath.Repository() == targetImagePath.Repository() {
return currentSource, true
}
}
return Source{}, false
}
func getManifestLocation(path string) string {
const defaultManifestFileName = ".images.yaml"
location := path
if !strings.Contains(location, ".yaml") && !strings.Contains(location, ".yml") {
location = filepath.Join(path, defaultManifestFileName)
}
return location
}
func getEncodedBasicAuth(username string, password string) (string, error) {
authConfig := Auth{
Username: username,
Password: password,
}
jsonAuth, err := json.Marshal(authConfig)
if err != nil {
return "", fmt.Errorf("marshal auth: %w", err)
}
return base64.URLEncoding.EncodeToString(jsonAuth), nil
}
func hostSupportsNestedRepositories(host string) bool {
// Quay.io
if strings.Contains(host, "quay.io") {
return false
}
// GHCR.io
if strings.Contains(host, "ghcr.io") {
return false
}
// Docker Registry (Docker Hub)
// An empty host is assumed to be Docker Hub.
if strings.Contains(host, "docker.io") || host == "" {
return false
}
return true
}
func dedupeImages(images []string) []string {
var dedupedImages []string
for _, image := range images {
if image == "" {
continue
}
if !contains(dedupedImages, image) {
dedupedImages = append(dedupedImages, image)
}
}
return dedupedImages
}