-
Notifications
You must be signed in to change notification settings - Fork 203
/
publish_images_phase.go
381 lines (314 loc) · 13 KB
/
publish_images_phase.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
package build
import (
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"github.com/werf/logboek"
"github.com/werf/werf/pkg/build/stage"
"github.com/werf/werf/pkg/container_runtime"
"github.com/werf/werf/pkg/image"
"github.com/werf/werf/pkg/storage"
"github.com/werf/werf/pkg/tag_strategy"
"github.com/werf/werf/pkg/util"
)
func NewPublishImagesPhase(c *Conveyor, imagesRepo storage.ImagesRepo, opts PublishImagesOptions) *PublishImagesPhase {
tagsByScheme := map[tag_strategy.TagStrategy][]string{
tag_strategy.Custom: opts.CustomTags,
tag_strategy.GitBranch: opts.TagsByGitBranch,
tag_strategy.GitTag: opts.TagsByGitTag,
tag_strategy.GitCommit: opts.TagsByGitCommit,
}
return &PublishImagesPhase{
BasePhase: BasePhase{c},
ImagesToPublish: opts.ImagesToPublish,
TagsByScheme: tagsByScheme,
TagByStagesSignature: opts.TagByStagesSignature,
ImagesRepo: imagesRepo,
PublishReport: &PublishReport{Images: make(map[string]PublishReportImageRecord)},
PublishReportPath: opts.PublishReportPath,
PublishReportFormat: opts.PublishReportFormat,
}
}
type PublishImagesPhase struct {
BasePhase
ImagesToPublish []string
TagsByScheme map[tag_strategy.TagStrategy][]string
TagByStagesSignature bool
ImagesRepo storage.ImagesRepo
PublishReport *PublishReport
PublishReportPath string
PublishReportFormat PublishReportFormat
}
type PublishReportFormat string
const (
PublishReportJSON PublishReportFormat = "json"
)
type PublishReport struct {
Images map[string]PublishReportImageRecord
}
type PublishReportImageRecord struct {
WerfImageName string
DockerRepo string
DockerTag string
DockerImageID string
}
func (phase *PublishImagesPhase) Name() string {
return "publish"
}
func (phase *PublishImagesPhase) BeforeImages() error {
return nil
}
func (phase *PublishImagesPhase) AfterImages() error {
if data, err := json.Marshal(phase.PublishReport); err != nil {
return fmt.Errorf("unable to prepare publish report: %s", err)
} else {
logboek.Debug.LogF("Publish report:\n%s\n", data)
if phase.PublishReportPath != "" && phase.PublishReportFormat == PublishReportJSON {
if err := ioutil.WriteFile(phase.PublishReportPath, append(data, []byte("\n")...), 0644); err != nil {
return fmt.Errorf("unable to write publish report to %s: %s", phase.PublishReportPath, err)
}
}
}
return nil
}
func (phase *PublishImagesPhase) BeforeImageStages(img *Image) error {
return nil
}
func (phase *PublishImagesPhase) OnImageStage(img *Image, stg stage.Interface) error {
return nil
}
func (phase *PublishImagesPhase) AfterImageStages(img *Image) error {
if img.isArtifact {
return nil
}
if len(phase.ImagesToPublish) == 0 {
return phase.publishImage(img)
}
for _, name := range phase.ImagesToPublish {
if name == img.GetName() {
return phase.publishImage(img)
}
}
return nil
}
func (phase *PublishImagesPhase) ImageProcessingShouldBeStopped(img *Image) bool {
return false
}
func (phase *PublishImagesPhase) publishImage(img *Image) error {
var nonEmptySchemeInOrder []tag_strategy.TagStrategy
for strategy, tags := range phase.TagsByScheme {
if len(tags) == 0 {
continue
}
nonEmptySchemeInOrder = append(nonEmptySchemeInOrder, strategy)
}
if phase.Conveyor.localGitRepo != nil {
if err := logboek.Info.LogProcess(fmt.Sprintf("publishing image %s git metadata", img.GetName()), logboek.LevelLogProcessOptions{}, func() error {
headCommit, err := phase.Conveyor.localGitRepo.HeadCommit()
if err != nil {
return err
}
// FIXME: Virtual merge commit?
if metadata, err := phase.Conveyor.StagesManager.StagesStorage.GetImageMetadataByCommit(phase.Conveyor.projectName(), img.GetName(), headCommit); err != nil {
return fmt.Errorf("unable to get image %s metadata by commit %s: %s", img.GetName(), headCommit, err)
} else if metadata != nil {
if metadata.ContentSignature != img.GetContentSignature() {
// TODO: Check image existance and automatically allow republish if no images found by this commit. What if multiple images are published by multiple tagging strategies (including custom)?
// TODO: allowInconsistentPublish: true option for werf.yaml
return fmt.Errorf("inconsistent build: found already published image with stages-signature %s by commit %s, cannot publish a new image with stages-signature %s by the same commit", metadata.ContentSignature, headCommit, img.GetContentSignature())
}
return nil
} else {
return phase.Conveyor.StagesManager.StagesStorage.PutImageCommit(phase.Conveyor.projectName(), img.GetName(), headCommit, &storage.ImageMetadata{ContentSignature: img.GetContentSignature()})
}
}); err != nil {
return err
}
}
var existingTags []string
if tags, err := phase.fetchExistingTags(img.GetName()); err != nil {
return err
} else {
existingTags = tags
}
for _, strategy := range nonEmptySchemeInOrder {
imageMetaTags := phase.TagsByScheme[strategy]
if err := logboek.Info.LogProcess(
fmt.Sprintf("%s tagging strategy", string(strategy)),
logboek.LevelLogProcessOptions{Style: logboek.HighlightStyle()},
func() error {
for _, imageMetaTag := range imageMetaTags {
if err := phase.publishImageByTag(img, imageMetaTag, strategy, publishImageByTagOptions{ExistingTagsList: existingTags, CheckAlreadyExistingTagByContentSignatureLabel: true}); err != nil {
return fmt.Errorf("error publishing image %s by tag %s: %s", img.LogName(), imageMetaTag, err)
}
}
return nil
},
); err != nil {
return err
}
}
if phase.TagByStagesSignature {
if err := logboek.Info.LogProcess(
fmt.Sprintf("%s tagging strategy", tag_strategy.StagesSignature),
logboek.LevelLogProcessOptions{Style: logboek.HighlightStyle()},
func() error {
if err := phase.publishImageByTag(img, img.GetContentSignature(), tag_strategy.StagesSignature, publishImageByTagOptions{ExistingTagsList: existingTags}); err != nil {
return fmt.Errorf("error publishing image %s by image signature %s: %s", img.GetName(), img.GetContentSignature(), err)
}
return nil
},
); err != nil {
return err
}
}
return nil
}
func (phase *PublishImagesPhase) fetchExistingTags(imageName string) (existingTags []string, err error) {
logProcessMsg := fmt.Sprintf("Fetching existing repo tags")
_ = logboek.Info.LogProcessInline(logProcessMsg, logboek.LevelLogProcessInlineOptions{}, func() error {
existingTags, err = phase.ImagesRepo.GetAllImageRepoTags(imageName)
return nil
})
logboek.Info.LogOptionalLn()
if err != nil {
return existingTags, fmt.Errorf("error fetching existing tags from image repository %s: %s", phase.ImagesRepo.String(), err)
}
return existingTags, nil
}
type publishImageByTagOptions struct {
CheckAlreadyExistingTagByContentSignatureLabel bool
ExistingTagsList []string
}
func (phase *PublishImagesPhase) publishImageByTag(img *Image, imageMetaTag string, tagStrategy tag_strategy.TagStrategy, opts publishImageByTagOptions) error {
imageRepository := phase.ImagesRepo.ImageRepositoryName(img.GetName())
imageName := phase.ImagesRepo.ImageRepositoryNameWithTag(img.GetName(), imageMetaTag)
imageActualTag := phase.ImagesRepo.ImageRepositoryTag(img.GetName(), imageMetaTag)
alreadyExists, alreadyExistingDockerImageID, err := phase.checkImageAlreadyExists(opts.ExistingTagsList, img.GetName(), imageMetaTag, img.GetContentSignature(), opts.CheckAlreadyExistingTagByContentSignatureLabel)
if err != nil {
return fmt.Errorf("error checking image %s already exists in the images repo: %s", img.LogName(), err)
}
if alreadyExists {
logboek.Default.LogFHighlight("%s tag %s is up-to-date\n", strings.Title(string(tagStrategy)), imageActualTag)
_ = logboek.WithIndent(func() error {
logboek.Default.LogFDetails("images-repo: %s\n", imageRepository)
logboek.Default.LogFDetails(" image: %s\n", imageName)
return nil
})
logboek.LogOptionalLn()
phase.PublishReport.Images[img.GetName()] = PublishReportImageRecord{
WerfImageName: img.GetName(),
DockerRepo: imageRepository,
DockerTag: imageActualTag,
DockerImageID: alreadyExistingDockerImageID,
}
return nil
}
publishImage := container_runtime.NewWerfImage(phase.Conveyor.GetStageImage(img.GetLastNonEmptyStage().GetImage().Name()), imageName, phase.Conveyor.ContainerRuntime.(*container_runtime.LocalDockerServerRuntime))
publishImage.Container().ServiceCommitChangeOptions().AddLabel(map[string]string{
image.WerfDockerImageName: imageName,
image.WerfTagStrategyLabel: string(tagStrategy),
image.WerfImageLabel: "true",
image.WerfImageNameLabel: img.GetName(),
image.WerfImageTagLabel: imageMetaTag,
image.WerfContentSignatureLabel: img.GetContentSignature(),
image.WerfImageVersionLabel: image.WerfImageVersion,
})
successInfoSectionFunc := func() {
_ = logboek.WithIndent(func() error {
logboek.Default.LogFDetails("images-repo: %s\n", imageRepository)
logboek.Default.LogFDetails(" image: %s\n", imageName)
return nil
})
}
publishingFunc := func() error {
if err := phase.Conveyor.StagesManager.FetchStage(img.GetLastNonEmptyStage()); err != nil {
return err
}
if err := logboek.Info.LogProcess("Building final image with meta information", logboek.LevelLogProcessOptions{}, func() error {
if err := publishImage.Build(container_runtime.BuildOptions{}); err != nil {
return fmt.Errorf("error building %s with tagging strategy '%s': %s", imageName, tagStrategy, err)
}
return nil
}); err != nil {
return err
}
if lock, err := phase.Conveyor.StorageLockManager.LockImage(phase.Conveyor.projectName(), imageName); err != nil {
return fmt.Errorf("error locking image %s: %s", imageName, err)
} else {
defer phase.Conveyor.StorageLockManager.Unlock(lock)
}
existingTags, err := phase.fetchExistingTags(img.GetName())
if err != nil {
return err
}
alreadyExists, alreadyExistingImageID, err := phase.checkImageAlreadyExists(existingTags, img.GetName(), imageMetaTag, img.GetContentSignature(), opts.CheckAlreadyExistingTagByContentSignatureLabel)
if err != nil {
return fmt.Errorf("error checking image %s already exists in the images repo: %s", img.LogName(), err)
}
if alreadyExists {
logboek.Default.LogFHighlight("%s tag %s is up-to-date\n", strings.Title(string(tagStrategy)), imageActualTag)
_ = logboek.WithIndent(func() error {
logboek.Info.LogFDetails("discarding newly built image %s\n", publishImage.MustGetBuiltId())
logboek.Default.LogFDetails("images-repo: %s\n", imageRepository)
logboek.Default.LogFDetails(" image: %s\n", imageName)
return nil
})
logboek.LogOptionalLn()
phase.PublishReport.Images[img.GetName()] = PublishReportImageRecord{
WerfImageName: img.GetName(),
DockerRepo: imageRepository,
DockerTag: imageActualTag,
DockerImageID: alreadyExistingImageID,
}
return nil
}
if err := phase.ImagesRepo.PublishImage(publishImage); err != nil {
return err
}
phase.PublishReport.Images[img.GetName()] = PublishReportImageRecord{
WerfImageName: img.GetName(),
DockerRepo: imageRepository,
DockerTag: imageActualTag,
DockerImageID: publishImage.MustGetBuiltId(),
}
return nil
}
return logboek.Default.LogProcess(
fmt.Sprintf("Publishing image %s by %s tag %s", img.LogName(), tagStrategy, imageMetaTag),
logboek.LevelLogProcessOptions{
SuccessInfoSectionFunc: successInfoSectionFunc,
Style: logboek.HighlightStyle(),
},
publishingFunc)
}
func (phase *PublishImagesPhase) checkImageAlreadyExists(existingTags []string, werfImageName, imageMetaTag, imageContentSignature string, checkAlreadyExistingTagByContentSignatureFromLabels bool) (bool, string, error) {
imageActualTag := phase.ImagesRepo.ImageRepositoryTag(werfImageName, imageMetaTag)
if !util.IsStringsContainValue(existingTags, imageActualTag) {
return false, "", nil
} else if !checkAlreadyExistingTagByContentSignatureFromLabels {
return true, "", nil
}
var repoImageContentSignature string
var repoDockerImageID string
var err error
getImageContentSignature := func() error {
repoImage, err := phase.ImagesRepo.GetRepoImage(werfImageName, imageMetaTag)
if err != nil {
return err
}
repoImageContentSignature = repoImage.Labels[image.WerfContentSignatureLabel]
repoDockerImageID = repoImage.ID
return nil
}
logProcessMsg := fmt.Sprintf("Getting existing tag %s manifest", imageActualTag)
err = logboek.Info.LogProcessInline(logProcessMsg, logboek.LevelLogProcessInlineOptions{}, getImageContentSignature)
if err != nil {
return false, "", fmt.Errorf("unable to get image %s parent id: %s", werfImageName, err)
}
logboek.Debug.LogF("Current image content signature: %s\n", imageContentSignature)
logboek.Debug.LogF("Already published image content signature: %s\n", repoImageContentSignature)
logboek.Debug.LogF("Already published image docker ID: %s\n", repoDockerImageID)
return imageContentSignature == repoImageContentSignature, repoDockerImageID, nil
}