-
Notifications
You must be signed in to change notification settings - Fork 202
/
dependencies.go
369 lines (301 loc) · 11.5 KB
/
dependencies.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
package stage
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/werf/logboek"
"github.com/werf/werf/pkg/config"
"github.com/werf/werf/pkg/container_runtime"
"github.com/werf/werf/pkg/docker"
imagePkg "github.com/werf/werf/pkg/image"
"github.com/werf/werf/pkg/stapel"
"github.com/werf/werf/pkg/storage"
"github.com/werf/werf/pkg/util"
)
type getImportsOptions struct {
Before StageName
After StageName
}
func getImports(imageBaseConfig *config.StapelImageBase, options *getImportsOptions) []*config.Import {
var imports []*config.Import
for _, elm := range imageBaseConfig.Import {
if options.Before != "" && elm.Before != "" && elm.Before == string(options.Before) {
imports = append(imports, elm)
} else if options.After != "" && elm.After != "" && elm.After == string(options.After) {
imports = append(imports, elm)
}
}
return imports
}
func getDependencies(imageBaseConfig *config.StapelImageBase, options *getImportsOptions) []*config.Dependency {
return nil // TODO(images-dependencies)
}
func newDependenciesStage(imports []*config.Import, dependencies []*config.Dependency, name StageName, baseStageOptions *NewBaseStageOptions) *DependenciesStage {
s := &DependenciesStage{}
s.imports = imports
s.dependencies = dependencies
s.BaseStage = newBaseStage(name, baseStageOptions)
return s
}
type DependenciesStage struct {
*BaseStage
imports []*config.Import
dependencies []*config.Dependency
}
func (s *DependenciesStage) GetDependencies(ctx context.Context, c Conveyor, _, _ container_runtime.LegacyImageInterface) (string, error) {
var args []string
for ind, elm := range s.imports {
var sourceChecksum string
var err error
if err := logboek.Context(ctx).Info().LogProcess("Getting import %d source checksum ...", ind).DoError(func() error {
sourceChecksum, err = s.getImportSourceChecksum(ctx, c, elm)
return err
}); err != nil {
return "", fmt.Errorf("unable to get import %d source checksum: %s", ind, err)
}
args = append(args, sourceChecksum)
args = append(args, elm.To)
args = append(args, elm.Group, elm.Owner)
}
for _, dep := range s.dependencies {
args = append(args, "Dependency", c.GetImageNameForLastImageStage(dep.ImageName))
for _, imp := range dep.Imports {
args = append(args, "DependencyImport", getDependencyImportID(imp))
}
}
return util.Sha256Hash(args...), nil
}
func (s *DependenciesStage) PrepareImage(ctx context.Context, c Conveyor, _, img container_runtime.LegacyImageInterface) error {
for _, elm := range s.imports {
sourceImageName := getSourceImageName(elm)
srv, err := c.GetImportServer(ctx, sourceImageName, elm.Stage)
if err != nil {
return fmt.Errorf("unable to get import server for image %q: %s", sourceImageName, err)
}
command := srv.GetCopyCommand(ctx, elm)
img.Container().AddServiceRunCommands(command)
imageServiceCommitChangeOptions := img.Container().ServiceCommitChangeOptions()
labelKey := imagePkg.WerfImportChecksumLabelPrefix + getImportID(elm)
importSourceID := getImportSourceID(c, elm)
importMetadata, err := c.GetImportMetadata(ctx, s.projectName, importSourceID)
if err != nil {
return fmt.Errorf("unable to get import source checksum: %s", err)
} else if importMetadata == nil {
panic(fmt.Sprintf("import metadata %s not found", importSourceID))
}
labelValue := importMetadata.Checksum
imageServiceCommitChangeOptions.AddLabel(map[string]string{labelKey: labelValue})
}
for _, dep := range s.dependencies {
depImageServiceOptions := img.Container().ServiceCommitChangeOptions()
depImageName := c.GetImageNameForLastImageStage(dep.ImageName)
depImageID := c.GetImageIDForLastImageStage(dep.ImageName)
depImageRepo, depImageTag := imagePkg.ParseRepositoryAndTag(depImageName)
for _, img := range dep.Imports {
switch img.Type {
case config.ImageRepoImport:
depImageServiceOptions.AddEnv(map[string]string{
img.TargetEnv: depImageRepo,
})
case config.ImageTagImport:
depImageServiceOptions.AddEnv(map[string]string{
img.TargetEnv: depImageTag,
})
case config.ImageNameImport:
depImageServiceOptions.AddEnv(map[string]string{
img.TargetEnv: depImageName,
})
case config.ImageIDImport:
depImageServiceOptions.AddEnv(map[string]string{
img.TargetEnv: depImageID,
})
default:
panic("unexpected configuration")
}
}
}
return nil
}
func (s *DependenciesStage) getImportSourceChecksum(ctx context.Context, c Conveyor, importElm *config.Import) (string, error) {
importSourceID := getImportSourceID(c, importElm)
importMetadata, err := c.GetImportMetadata(ctx, s.projectName, importSourceID)
if err != nil {
return "", fmt.Errorf("unable to get import metadata: %s", err)
}
if importMetadata == nil {
checksum, err := s.generateImportChecksum(ctx, c, importElm)
if err != nil {
return "", fmt.Errorf("unable to generate import source checksum: %s", err)
}
sourceImageID := getSourceImageID(c, importElm)
importMetadata = &storage.ImportMetadata{
ImportSourceID: importSourceID,
SourceImageID: sourceImageID,
Checksum: checksum,
}
if err := c.PutImportMetadata(ctx, s.projectName, importMetadata); err != nil {
return "", fmt.Errorf("unable to put import metadata: %s", err)
}
}
return importMetadata.Checksum, nil
}
func (s *DependenciesStage) generateImportChecksum(ctx context.Context, c Conveyor, importElm *config.Import) (string, error) {
sourceImageDockerImageName := getSourceImageDockerImageName(c, importElm)
importSourceID := getImportSourceID(c, importElm)
stapelContainerName, err := stapel.GetOrCreateContainer(ctx)
if err != nil {
return "", err
}
importHostTmpDir := filepath.Join(s.imageTmpDir, string(s.Name()), "imports", importSourceID)
importContainerDir := s.containerWerfDir
importScriptHostTmpPath := filepath.Join(importHostTmpDir, "script.sh")
resultChecksumHostTmpPath := filepath.Join(importHostTmpDir, "checksum")
importScriptContainerPath := path.Join(importContainerDir, "script.sh")
resultChecksumContainerPath := path.Join(importContainerDir, "checksum")
command := generateChecksumCommand(importElm.Add, importElm.IncludePaths, importElm.ExcludePaths, resultChecksumContainerPath)
if err := stapel.CreateScript(importScriptHostTmpPath, []string{command}); err != nil {
return "", fmt.Errorf("unable to create script: %s", err)
}
runArgs := []string{
"--rm",
"--user=0:0",
"--workdir=/",
fmt.Sprintf("--volumes-from=%s", stapelContainerName),
fmt.Sprintf("--volume=%s:%s", importHostTmpDir, importContainerDir),
fmt.Sprintf("--entrypoint=%s", stapel.BashBinPath()),
sourceImageDockerImageName,
importScriptContainerPath,
}
if debugImportSourceChecksum() {
fmt.Println(runArgs)
}
if output, err := docker.CliRun_RecordedOutput(ctx, runArgs...); err != nil {
logboek.Context(ctx).Error().LogF("%s", output)
return "", err
}
data, err := ioutil.ReadFile(resultChecksumHostTmpPath)
if err != nil {
return "", fmt.Errorf("unable to read file with import source checksum: %s", err)
}
checksum := strings.TrimSpace(string(data))
return checksum, nil
}
func generateChecksumCommand(from string, includePaths, excludePaths []string, resultChecksumPath string) string {
findCommandParts := append([]string{}, stapel.FindBinPath(), from, "-type", "f")
var nameIncludeArgs []string
for _, includePath := range includePaths {
formattedPath := formatIncludeAndExcludePath(includePath)
nameIncludeArgs = append(
nameIncludeArgs,
fmt.Sprintf("-wholename \"%s\"", path.Join(from, formattedPath)),
fmt.Sprintf("-wholename \"%s\"", path.Join(from, formattedPath, "**")),
)
}
if len(nameIncludeArgs) != 0 {
findCommandParts = append(findCommandParts, fmt.Sprintf("\\( %s \\)", strings.Join(nameIncludeArgs, " -or ")))
}
var nameExcludeArgs []string
for _, excludePath := range excludePaths {
formattedPath := formatIncludeAndExcludePath(excludePath)
nameExcludeArgs = append(
nameExcludeArgs,
fmt.Sprintf("! -wholename \"%s\"", path.Join(from, formattedPath)),
fmt.Sprintf("! -wholename \"%s\"", path.Join(from, formattedPath, "**")),
)
}
if len(nameExcludeArgs) != 0 {
if len(nameIncludeArgs) != 0 {
findCommandParts = append(findCommandParts, fmt.Sprintf("-and"))
}
findCommandParts = append(findCommandParts, fmt.Sprintf("\\( %s \\)", strings.Join(nameExcludeArgs, " -and ")))
}
findCommand := strings.Join(findCommandParts, " ")
sortCommandParts := append([]string{}, stapel.SortBinPath(), "-n")
sortCommand := strings.Join(sortCommandParts, " ")
xargsCommandParts := append([]string{}, stapel.XargsBinPath(), stapel.Md5sumBinPath())
xargsCommand := strings.Join(xargsCommandParts, " ")
md5SumCommand := stapel.Md5sumBinPath()
cutCommandParts := append([]string{}, stapel.CutBinPath(), "-d", "' '", "-f", "1")
cutCommand := strings.Join(cutCommandParts, " ")
commands := append([]string{}, findCommand, sortCommand, xargsCommand, md5SumCommand, cutCommand)
command := fmt.Sprintf("%s > %s", strings.Join(commands, " | "), resultChecksumPath)
return command
}
func formatIncludeAndExcludePath(path string) string {
return strings.TrimRight(path, "*/")
}
func getDependencyImportID(dependencyImport *config.DependencyImport) string {
return util.Sha256Hash(
"Type", string(dependencyImport.Type),
"TargetEnv", dependencyImport.TargetEnv,
)
}
func getImportID(importElm *config.Import) string {
return util.Sha256Hash(
"ImageName", importElm.ImageName,
"ArtifactName", importElm.ArtifactName,
"Stage", importElm.Stage,
"After", importElm.After,
"Before", importElm.Before,
"Add", importElm.Add,
"To", importElm.To,
"Group", importElm.Group,
"Owner", importElm.Owner,
"IncludePaths", strings.Join(importElm.IncludePaths, "///"),
"ExcludePaths", strings.Join(importElm.ExcludePaths, "///"),
)
}
func getImportSourceID(c Conveyor, importElm *config.Import) string {
return util.Sha256Hash(
"SourceImageContentDigest", getSourceImageContentDigest(c, importElm),
"Add", importElm.Add,
"IncludePaths", strings.Join(importElm.IncludePaths, "///"),
"ExcludePaths", strings.Join(importElm.ExcludePaths, "///"),
)
}
func getSourceImageDockerImageName(c Conveyor, importElm *config.Import) string {
sourceImageName := getSourceImageName(importElm)
var sourceImageDockerImageName string
if importElm.Stage == "" {
sourceImageDockerImageName = c.GetImageNameForLastImageStage(sourceImageName)
} else {
sourceImageDockerImageName = c.GetImageNameForImageStage(sourceImageName, importElm.Stage)
}
return sourceImageDockerImageName
}
func getSourceImageID(c Conveyor, importElm *config.Import) string {
sourceImageName := getSourceImageName(importElm)
var sourceImageID string
if importElm.Stage == "" {
sourceImageID = c.GetImageIDForLastImageStage(sourceImageName)
} else {
sourceImageID = c.GetImageIDForImageStage(sourceImageName, importElm.Stage)
}
return sourceImageID
}
func getSourceImageContentDigest(c Conveyor, importElm *config.Import) string {
sourceImageName := getSourceImageName(importElm)
var sourceImageContentDigest string
if importElm.Stage == "" {
sourceImageContentDigest = c.GetImageContentDigest(sourceImageName)
} else {
sourceImageContentDigest = c.GetImageStageContentDigest(sourceImageName, importElm.Stage)
}
return sourceImageContentDigest
}
func getSourceImageName(importElm *config.Import) string {
var sourceImageName string
if importElm.ImageName != "" {
sourceImageName = importElm.ImageName
} else {
sourceImageName = importElm.ArtifactName
}
return sourceImageName
}
func debugImportSourceChecksum() bool {
return os.Getenv("WERF_DEBUG_IMPORT_SOURCE_CHECKSUM") == "1"
}