/
push.go
362 lines (312 loc) · 10.5 KB
/
push.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
package images
import (
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"os"
"path"
"time"
"github.com/containers/image/v5/pkg/compression/types"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/ulikunitz/xz"
"kubevirt.io/containerdisks/cmd/medius/common"
"kubevirt.io/containerdisks/pkg/api"
"kubevirt.io/containerdisks/pkg/build"
"kubevirt.io/containerdisks/pkg/http"
"kubevirt.io/containerdisks/pkg/repository"
)
type buildAndPublish struct {
Ctx context.Context
Log *logrus.Entry
Options *common.Options
Repo repository.Repository
Getter http.Getter
}
func NewPublishImagesCommand(options *common.Options) *cobra.Command {
options.PublishImagesOptions = common.PublishImageOptions{
SourceRegistry: "quay.io/containerdisks",
}
publishCmd := &cobra.Command{
Use: "push",
Short: "Determine if containerdisks need an update and push an update to the target registry if needed",
Run: func(cmd *cobra.Command, args []string) {
if options.PublishImagesOptions.TargetRegistry == "" {
options.PublishImagesOptions.TargetRegistry = options.PublishImagesOptions.SourceRegistry
}
focusMatched, resultsChan, workerErr := spawnWorkers(cmd.Context(), options, func(e *common.Entry) (*api.ArtifactResult, error) {
errString := ""
artifact := e.Artifacts[0]
b := buildAndPublish{
Ctx: cmd.Context(),
Log: common.Logger(artifact),
Options: options,
Repo: &repository.RepositoryImpl{},
Getter: &http.HTTPGetter{},
}
tags, err := b.Do(e, time.Now())
if err != nil {
errString = err.Error()
}
if tags == nil && err == nil {
return nil, nil
}
return &api.ArtifactResult{
Tags: tags,
Stage: StagePush,
Err: errString,
}, err
})
results := map[string]api.ArtifactResult{}
for result := range resultsChan {
results[result.Key] = result.Value
}
if !focusMatched {
logrus.Fatalf("no artifact was processed, focus '%s' did not match", options.Focus)
}
if !options.DryRun {
if err := writeResultsFile(options.ImagesOptions.ResultsFile, results); err != nil {
logrus.Fatal(err)
}
}
if workerErr != nil {
if options.PublishImagesOptions.NoFail {
logrus.Warn(workerErr)
} else {
logrus.Fatal(workerErr)
}
}
},
}
publishCmd.Flags().BoolVar(&options.PublishImagesOptions.ForceBuild, "force",
options.PublishImagesOptions.ForceBuild, "Force a rebuild and push")
publishCmd.Flags().BoolVar(&options.PublishImagesOptions.NoFail, "no-fail",
options.PublishImagesOptions.NoFail, "Return success even if a worker fails")
publishCmd.Flags().StringVar(&options.PublishImagesOptions.SourceRegistry, "source-registry",
options.PublishImagesOptions.SourceRegistry, "Registry to check if updates are needed")
publishCmd.Flags().StringVar(&options.PublishImagesOptions.TargetRegistry, "target-registry",
options.PublishImagesOptions.TargetRegistry, "Registry to push built containerdisks to")
return publishCmd
}
func (b *buildAndPublish) Do(entry *common.Entry, timestamp time.Time) ([]string, error) {
metadata := entry.Artifacts[0].Metadata()
artifactInfo, err := entry.Artifacts[0].Inspect()
if err != nil {
return nil, fmt.Errorf("error introspecting artifact %q: %v", metadata.Describe(), err)
}
rebuildNeeded, err := b.rebuildNeeded(entry)
if err != nil {
return nil, err
}
if !rebuildNeeded && !b.Options.PublishImagesOptions.ForceBuild {
b.Log.Info("Nothing to do.")
return nil, nil
}
if errors.Is(b.Ctx.Err(), context.Canceled) {
return nil, b.Ctx.Err()
}
images, artifacts, err := b.buildImages(entry)
if err != nil {
return nil, err
}
defer cleanupArtifacts(artifacts)
names := prepareTags(timestamp, b.Options.PublishImagesOptions.TargetRegistry, entry, artifactInfo)
for _, name := range names {
if len(images) > 1 {
containerDiskIndex, err := build.ContainerDiskIndex(images)
if err != nil {
return nil, fmt.Errorf("error creating the containerdisk index : %v", err)
}
if err := b.pushImageIndex(containerDiskIndex, name); err != nil {
return nil, err
}
} else if len(images) == 1 {
if err := b.pushImage(images[0], name); err != nil {
return nil, err
}
}
if errors.Is(b.Ctx.Err(), context.Canceled) {
return nil, b.Ctx.Err()
}
}
return prepareTags(timestamp, "", entry, artifactInfo), nil
}
func (b *buildAndPublish) getImageSha(description, arch string) (imageSha string, err error) {
imageName := path.Join(b.Options.PublishImagesOptions.SourceRegistry, description)
imageInfo, err := b.Repo.ImageMetadata(imageName, arch, b.Options.AllowInsecureRegistry)
if err != nil {
err = b.handleMetadataError(imageName, err)
} else {
b.Log.Infof("Latest containerdisk checksum: %q", imageInfo.Labels[build.LabelShaSum])
imageSha = imageInfo.Labels[build.LabelShaSum]
}
return
}
func (b *buildAndPublish) handleMetadataError(imageName string, err error) error {
switch {
case repository.IsRepositoryUnknownError(err):
b.Log.Info("Repository does not yet exist, it will be created")
case repository.IsManifestUnknownError(err):
b.Log.Info("Tag does not yet exist, it will be created")
case repository.IsTagUnknownError(err):
b.Log.Info("Tag is gone but seems to have existed already, it will be created")
default:
return fmt.Errorf("error introspecting image %q: %v", imageName, err)
}
return nil
}
func (b *buildAndPublish) getArtifact(artifactInfo *api.ArtifactDetails) (string, error) {
artifactReader, err := b.Getter.GetWithChecksumAndContext(b.Ctx, artifactInfo.DownloadURL)
if err != nil {
return "", fmt.Errorf("error opening a connection to the specified download location: %v", err)
}
defer artifactReader.Close()
file, err := b.readArtifact(artifactReader, artifactInfo.Compression)
if err != nil {
return "", err
}
if errors.Is(b.Ctx.Err(), context.Canceled) {
return "", b.Ctx.Err()
}
checksum := artifactReader.Checksum()
if checksum != artifactInfo.SHA256Sum {
return "", fmt.Errorf("expected checksum %q but got %q", artifactInfo.SHA256Sum, checksum)
}
return file, nil
}
func (b *buildAndPublish) readArtifact(artifactReader http.ReadCloserWithChecksum, compression string) (string, error) {
var err error
// Initialize reader with the artifactReader for the case where no compression is used
var reader io.Reader = artifactReader
if compression == types.GzipAlgorithmName {
reader, err = gzip.NewReader(artifactReader)
if err != nil {
return "", fmt.Errorf("error creating a gunzip reader for the specified download location: %v", err)
}
} else if compression == types.XzAlgorithmName {
reader, err = xz.NewReader(artifactReader)
if err != nil {
return "", fmt.Errorf("error creating a lzma reader for the specified download location: %v", err)
}
}
file, err := os.CreateTemp("", "containerdisks")
if err != nil {
return "", err
}
defer file.Close()
// Uncompress disks in chunks up to size defined below
const chunkSize = 1024 * 1024 * 50 // MiB
for {
_, err := io.CopyN(file, reader, chunkSize)
if err != nil {
if err == io.EOF {
break
}
return "", fmt.Errorf("error writing the image to the destination file: %v", err)
}
if errors.Is(b.Ctx.Err(), context.Canceled) {
return "", b.Ctx.Err()
}
}
return file.Name(), nil
}
func (b *buildAndPublish) buildImages(entry *common.Entry) ([]v1.Image, []string, error) {
var images []v1.Image
var artifacts []string
for i := range entry.Artifacts {
metadata := entry.Artifacts[i].Metadata()
artifactInfo, err := entry.Artifacts[i].Inspect()
if err != nil {
return nil, nil, fmt.Errorf("error introspecting artifact %q: %v", metadata.Describe(), err)
}
b.Log.Infof("Rebuild needed, downloading %q ...", artifactInfo.DownloadURL)
file, err := b.getArtifact(artifactInfo)
if err != nil {
return nil, nil, err
}
artifacts = append(artifacts, file)
b.Log.Info("Building containerdisk ...")
image, err := build.ContainerDisk(file,
artifactInfo.ImageArchitecture,
build.ContainerDiskConfig(artifactInfo.SHA256Sum, metadata.EnvVariables))
if err != nil {
return nil, nil, fmt.Errorf("error creating the containerdisk : %v", err)
}
if errors.Is(b.Ctx.Err(), context.Canceled) {
return nil, nil, b.Ctx.Err()
}
images = append(images, image)
}
return images, artifacts, nil
}
func (b *buildAndPublish) rebuildNeeded(entry *common.Entry) (bool, error) {
if len(entry.Artifacts) == 0 {
err := errors.New("entry has no artifacts to check for rebuild")
b.Log.Error(err)
return false, err
}
for i := range entry.Artifacts {
metadata := entry.Artifacts[i].Metadata()
artifactInfo, err := entry.Artifacts[i].Inspect()
if err != nil {
return false, fmt.Errorf("error introspecting artifact %q: %v", metadata.Describe(), err)
}
imageSha, err := b.getImageSha(metadata.Describe(), artifactInfo.ImageArchitecture)
if err != nil {
return false, err
}
if imageSha != artifactInfo.SHA256Sum {
return true, nil
}
}
return false, nil
}
func (b *buildAndPublish) pushImage(containerDisk v1.Image, name string) error {
if !b.Options.DryRun {
b.Log.Infof("Pushing %s", name)
if err := b.Repo.PushImage(b.Ctx, containerDisk, name); err != nil {
b.Log.WithError(err).Error("Failed to push image")
return err
}
} else {
b.Log.Infof("Dry run enabled, not pushing %s", name)
}
return nil
}
func (b *buildAndPublish) pushImageIndex(containerDiskIndex v1.ImageIndex, name string) error {
if !b.Options.DryRun {
b.Log.Infof("Pushing %s image index", name)
if err := b.Repo.PushImageIndex(b.Ctx, containerDiskIndex, name); err != nil {
b.Log.WithError(err).Error("Failed to push image image")
return err
}
} else {
b.Log.Infof("Dry run enabled, not pushing %s image index", name)
}
return nil
}
func prepareTags(timestamp time.Time, registry string, entry *common.Entry, artifactDetails *api.ArtifactDetails) []string {
metadata := entry.Artifacts[0].Metadata()
imageName := path.Join(registry, metadata.Describe())
names := []string{fmt.Sprintf("%s-%s", imageName, timestamp.Format("0601021504"))}
for _, tag := range artifactDetails.AdditionalUniqueTags {
if tag == "" {
continue
}
names = append(names, fmt.Sprintf("%s:%s", path.Join(registry, metadata.Name), tag))
}
// the least specific tag is last
names = append(names, imageName)
if entry.UseForLatest {
names = append(names, fmt.Sprintf("%s:%s", path.Join(registry, metadata.Name), "latest"))
}
return names
}
func cleanupArtifacts(artifacts []string) {
for _, file := range artifacts {
os.Remove(file)
}
}