forked from tilt-dev/tilt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker.go
645 lines (547 loc) · 17.1 KB
/
docker.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package tiltfile
import (
"bytes"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/distribution/reference"
"github.com/moby/buildkit/frontend/dockerfile/dockerignore"
"github.com/pkg/errors"
"go.starlark.net/starlark"
"github.com/tilt-dev/tilt/internal/container"
"github.com/tilt-dev/tilt/internal/dockerfile"
"github.com/tilt-dev/tilt/internal/ospath"
"github.com/tilt-dev/tilt/internal/sliceutils"
"github.com/tilt-dev/tilt/internal/tiltfile/io"
"github.com/tilt-dev/tilt/internal/tiltfile/starkit"
"github.com/tilt-dev/tilt/internal/tiltfile/value"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/tilt/pkg/model"
)
const dockerPlatformEnv = "DOCKER_DEFAULT_PLATFORM"
var cacheObsoleteWarning = "docker_build(cache=...) is obsolete, and currently a no-op.\n" +
"You should switch to live_update to optimize your builds."
type dockerImage struct {
buildType dockerImageBuildType
configurationRef container.RefSelector
matchInEnvVars bool
sshSpecs []string
secretSpecs []string
ignores []string
onlys []string
entrypoint model.Cmd // optional: if specified, we override the image entrypoint/k8s command with this
targetStage string // optional: if specified, we build a particular target in the dockerfile
network string
extraTags []string // Extra tags added at build-time.
cacheFrom []string
pullParent bool
platform string
// Overrides the container args. Used as an escape hatch in case people want the old entrypoint behavior.
// See discussion here:
// https://github.com/tilt-dev/tilt/pull/2933
overrideArgs *v1alpha1.ImageMapOverrideArgs
dbDockerfilePath string
dbDockerfile dockerfile.Dockerfile
// dbBuildPath may be empty if the user is building from a URL
dbBuildPath string
dbBuildArgs []string
customCommand model.Cmd
customDeps []string
customTag string
customImgDeps []reference.Named
// Whether this has been matched up yet to a deploy resource.
matched bool
imageMapDeps []string
// Only applicable to custom_build
disablePush bool
skipsLocalDocker bool
outputsImageRefTo string
liveUpdate v1alpha1.LiveUpdateSpec
// TODO(milas): we should have a better way of passing the Tiltfile path around during resource assembly
tiltfilePath string
dockerComposeService string
dockerComposeLocalVolumePaths []string
extraHosts []string
}
func (d *dockerImage) ID() model.TargetID {
return model.ImageID(d.configurationRef)
}
func (d *dockerImage) ImageMapName() string {
return string(model.ImageID(d.configurationRef).Name)
}
type dockerImageBuildType int
const (
UnknownBuild dockerImageBuildType = iota
DockerBuild
CustomBuild
DockerComposeBuild
)
func (d *dockerImage) Type() dockerImageBuildType {
return d.buildType
}
func (s *tiltfileState) dockerBuild(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var dockerRef, targetStage string
contextVal := value.NewLocalPathUnpacker(thread)
dockerfilePathVal := value.NewLocalPathUnpacker(thread)
var dockerfileContentsVal,
cacheVal,
liveUpdateVal,
ignoreVal,
onlyVal,
entrypoint starlark.Value
var buildArgs value.StringStringMap
var network, platform value.Stringable
var ssh, secret, extraTags, cacheFrom, extraHosts value.StringOrStringList
var matchInEnvVars, pullParent bool
var overrideArgsVal starlark.Sequence
if err := s.unpackArgs(fn.Name(), args, kwargs,
"ref", &dockerRef,
"context", &contextVal,
"build_args?", &buildArgs,
"dockerfile??", &dockerfilePathVal,
"dockerfile_contents?", &dockerfileContentsVal,
"cache?", &cacheVal,
"live_update?", &liveUpdateVal,
"match_in_env_vars?", &matchInEnvVars,
"ignore?", &ignoreVal,
"only?", &onlyVal,
"entrypoint?", &entrypoint,
"container_args?", &overrideArgsVal,
"target?", &targetStage,
"ssh?", &ssh,
"secret?", &secret,
"network?", &network,
"extra_tag?", &extraTags,
"cache_from?", &cacheFrom,
"pull?", &pullParent,
"platform?", &platform,
"extra_hosts?", &extraHosts,
); err != nil {
return nil, err
}
ref, err := container.ParseNamed(dockerRef)
if err != nil {
return nil, fmt.Errorf("Argument 1 (ref): can't parse %q: %v", dockerRef, err)
}
context := contextVal.Value
dockerfilePath := filepath.Join(context, "Dockerfile")
var dockerfileContents string
if dockerfileContentsVal != nil && dockerfilePathVal.IsSet {
return nil, fmt.Errorf("Cannot specify both dockerfile and dockerfile_contents keyword arguments")
}
if dockerfileContentsVal != nil {
switch v := dockerfileContentsVal.(type) {
case io.Blob:
dockerfileContents = v.Text
case starlark.String:
dockerfileContents = v.GoString()
default:
return nil, fmt.Errorf("Argument (dockerfile_contents): must be string or blob.")
}
} else if dockerfilePathVal.IsSet {
dockerfilePath = dockerfilePathVal.Value
bs, err := io.ReadFile(thread, dockerfilePath)
if err != nil {
return nil, errors.Wrap(err, "error reading dockerfile")
}
dockerfileContents = string(bs)
} else {
bs, err := io.ReadFile(thread, dockerfilePath)
if err != nil {
return nil, errors.Wrapf(err, "error reading dockerfile")
}
dockerfileContents = string(bs)
}
if cacheVal != nil {
s.logger.Warnf("%s", cacheObsoleteWarning)
}
liveUpdate, err := s.liveUpdateFromSteps(thread, liveUpdateVal)
if err != nil {
return nil, errors.Wrap(err, "live_update")
}
ignores, err := parseValuesToStrings(ignoreVal, "ignore")
if err != nil {
return nil, err
}
onlys, err := s.parseOnly(onlyVal)
if err != nil {
return nil, err
}
entrypointCmd, err := value.ValueToUnixCmd(thread, entrypoint, nil, nil)
if err != nil {
return nil, err
}
var overrideArgs *v1alpha1.ImageMapOverrideArgs
if overrideArgsVal != nil {
args, err := value.SequenceToStringSlice(overrideArgsVal)
if err != nil {
return nil, fmt.Errorf("Argument 'container_args': %v", err)
}
overrideArgs = &v1alpha1.ImageMapOverrideArgs{Args: args}
}
for _, extraTag := range extraTags.Values {
_, err := container.ParseNamed(extraTag)
if err != nil {
return nil, fmt.Errorf("Argument extra_tag=%q not a valid image reference: %v", extraTag, err)
}
}
if platform.Value == "" {
// for compatibility with Docker CLI, support the env var fallback
// see https://docs.docker.com/engine/reference/commandline/cli/#environment-variables
platform.Value = os.Getenv(dockerPlatformEnv)
}
buildArgsList := []string{}
for k, v := range buildArgs.AsMap() {
if v == "" {
buildArgsList = append(buildArgsList, k)
} else {
buildArgsList = append(buildArgsList, fmt.Sprintf("%s=%s", k, v))
}
}
sort.Strings(buildArgsList)
r := &dockerImage{
buildType: DockerBuild,
dbDockerfilePath: dockerfilePath,
dbDockerfile: dockerfile.Dockerfile(dockerfileContents),
dbBuildPath: context,
configurationRef: container.NewRefSelector(ref),
dbBuildArgs: buildArgsList,
liveUpdate: liveUpdate,
matchInEnvVars: matchInEnvVars,
sshSpecs: ssh.Values,
secretSpecs: secret.Values,
ignores: ignores,
onlys: onlys,
entrypoint: entrypointCmd,
overrideArgs: overrideArgs,
targetStage: targetStage,
network: network.Value,
extraTags: extraTags.Values,
cacheFrom: cacheFrom.Values,
pullParent: pullParent,
platform: platform.Value,
tiltfilePath: starkit.CurrentExecPath(thread),
extraHosts: extraHosts.Values,
}
err = s.buildIndex.addImage(r)
if err != nil {
return nil, err
}
return starlark.None, nil
}
func (s *tiltfileState) parseOnly(val starlark.Value) ([]string, error) {
paths, err := parseValuesToStrings(val, "only")
if err != nil {
return nil, err
}
for _, p := range paths {
// We want to forbid file globs due to these issues:
// https://github.com/tilt-dev/tilt/issues/1982
// https://github.com/moby/moby/issues/30018
if strings.Contains(p, "*") {
return nil, fmt.Errorf("'only' does not support '*' file globs. Must be a real path: %s", p)
}
}
return paths, nil
}
func (s *tiltfileState) customBuild(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var dockerRef string
var commandVal, commandBat, commandBatVal starlark.Value
deps := value.NewLocalPathListUnpacker(thread)
var tag string
var disablePush bool
var liveUpdateVal, ignoreVal starlark.Value
var matchInEnvVars bool
var entrypoint starlark.Value
var overrideArgsVal starlark.Sequence
var skipsLocalDocker bool
var imageDeps value.ImageList
var env value.StringStringMap
var dir starlark.Value
outputsImageRefTo := value.NewLocalPathUnpacker(thread)
err := s.unpackArgs(fn.Name(), args, kwargs,
"ref", &dockerRef,
"command", &commandVal,
"deps", &deps,
"tag?", &tag,
"disable_push?", &disablePush,
"skips_local_docker?", &skipsLocalDocker,
"live_update?", &liveUpdateVal,
"match_in_env_vars?", &matchInEnvVars,
"ignore?", &ignoreVal,
"entrypoint?", &entrypoint,
"container_args?", &overrideArgsVal,
"command_bat_val", &commandBatVal,
"outputs_image_ref_to", &outputsImageRefTo,
// This is a crappy fix for https://github.com/tilt-dev/tilt/issues/4061
// so that we don't break things.
"command_bat", &commandBat,
"image_deps", &imageDeps,
"env?", &env,
"dir?", &dir,
)
if err != nil {
return nil, err
}
ref, err := container.ParseNamed(dockerRef)
if err != nil {
return nil, fmt.Errorf("Argument 1 (ref): can't parse %q: %v", dockerRef, err)
}
liveUpdate, err := s.liveUpdateFromSteps(thread, liveUpdateVal)
if err != nil {
return nil, errors.Wrap(err, "live_update")
}
ignores, err := parseValuesToStrings(ignoreVal, "ignore")
if err != nil {
return nil, err
}
entrypointCmd, err := value.ValueToUnixCmd(thread, entrypoint, nil, nil)
if err != nil {
return nil, err
}
var overrideArgs *v1alpha1.ImageMapOverrideArgs
if overrideArgsVal != nil {
args, err := value.SequenceToStringSlice(overrideArgsVal)
if err != nil {
return nil, fmt.Errorf("Argument 'container_args': %v", err)
}
overrideArgs = &v1alpha1.ImageMapOverrideArgs{Args: args}
}
if commandBat == nil {
commandBat = commandBatVal
}
command, err := value.ValueGroupToCmdHelper(thread, commandVal, commandBat, dir, env)
if err != nil {
return nil, fmt.Errorf("Argument 2 (command): %v", err)
} else if command.Empty() {
return nil, fmt.Errorf("Argument 2 (command) can't be empty")
}
if tag != "" && outputsImageRefTo.Value != "" {
return nil, fmt.Errorf("Cannot specify both tag= and outputs_image_ref_to=")
}
img := &dockerImage{
buildType: CustomBuild,
configurationRef: container.NewRefSelector(ref),
customCommand: command,
customDeps: deps.Value,
customTag: tag,
customImgDeps: []reference.Named(imageDeps),
disablePush: disablePush,
skipsLocalDocker: skipsLocalDocker,
liveUpdate: liveUpdate,
matchInEnvVars: matchInEnvVars,
ignores: ignores,
entrypoint: entrypointCmd,
overrideArgs: overrideArgs,
outputsImageRefTo: outputsImageRefTo.Value,
tiltfilePath: starkit.CurrentExecPath(thread),
}
err = s.buildIndex.addImage(img)
if err != nil {
return nil, err
}
return &customBuild{s: s, img: img}, nil
}
type customBuild struct {
s *tiltfileState
img *dockerImage
}
var _ starlark.Value = &customBuild{}
func (b *customBuild) String() string {
return fmt.Sprintf("custom_build(%q)", b.img.configurationRef.String())
}
func (b *customBuild) Type() string {
return "custom_build"
}
func (b *customBuild) Freeze() {}
func (b *customBuild) Truth() starlark.Bool {
return true
}
func (b *customBuild) Hash() (uint32, error) {
return 0, fmt.Errorf("unhashable type: custom_build")
}
func (b *customBuild) AttrNames() []string {
return []string{}
}
func parseValuesToStrings(value starlark.Value, param string) ([]string, error) {
tempIgnores := starlarkValueOrSequenceToSlice(value)
var ignores []string
for _, v := range tempIgnores {
switch val := v.(type) {
case starlark.String: // for singular string
goString := val.GoString()
if strings.Contains(goString, "\n") {
return nil, fmt.Errorf(param+" cannot contain newlines; found "+param+": %q", goString)
}
ignores = append(ignores, val.GoString())
default:
return nil, fmt.Errorf(param+" must be a string or a sequence of strings; found a %T", val)
}
}
return ignores, nil
}
func isGitRepoBase(path string) bool {
return ospath.IsDir(filepath.Join(path, ".git"))
}
func repoIgnoresForPaths(paths []string) []v1alpha1.IgnoreDef {
var result []v1alpha1.IgnoreDef
repoSet := map[string]bool{}
for _, path := range paths {
isRepoBase := isGitRepoBase(path)
if !isRepoBase || repoSet[path] {
continue
}
repoSet[path] = true
result = append(result, v1alpha1.IgnoreDef{
BasePath: filepath.Join(path, ".git"),
})
}
return result
}
func (s *tiltfileState) repoIgnoresForImage(image *dockerImage) []v1alpha1.IgnoreDef {
var paths []string
paths = append(paths, image.dbDockerfilePath)
if image.dbBuildPath != "" {
paths = append(paths, image.dbBuildPath)
}
paths = append(paths, image.customDeps...)
return repoIgnoresForPaths(paths)
}
func (s *tiltfileState) defaultRegistry(t *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
if !container.IsEmptyRegistry(s.defaultReg) {
return starlark.None, errors.New("default registry already defined")
}
var host, hostFromCluster, singleName string
if err := s.unpackArgs(fn.Name(), args, kwargs,
"host", &host,
"host_from_cluster?", &hostFromCluster,
"single_name?", &singleName); err != nil {
return nil, err
}
reg := &v1alpha1.RegistryHosting{
Host: host,
HostFromContainerRuntime: hostFromCluster,
SingleName: singleName,
}
ctx, err := starkit.ContextFromThread(t)
if err != nil {
return starlark.None, err
}
if err := reg.Validate(ctx); err != nil {
return starlark.None, errors.Wrapf(err.ToAggregate(), "validating defaultRegistry")
}
reg.SingleName = singleName
s.defaultReg = reg
return starlark.None, nil
}
func (s *tiltfileState) dockerignoresFromPathsAndContextFilters(source string, paths []string, ignorePatterns []string, onlys []string, dbDockerfilePath string) ([]model.Dockerignore, error) {
var result []model.Dockerignore
dupeSet := map[string]bool{}
onlyPatterns := onlysToDockerignorePatterns(onlys)
for _, path := range paths {
if path == "" || dupeSet[path] {
continue
}
dupeSet[path] = true
if !ospath.IsDir(path) {
continue
}
if len(ignorePatterns) != 0 {
result = append(result, model.Dockerignore{
LocalPath: path,
Source: source + " ignores=",
Patterns: ignorePatterns,
})
}
if len(onlyPatterns) != 0 {
result = append(result, model.Dockerignore{
LocalPath: path,
Source: source + " only=",
Patterns: onlyPatterns,
})
}
diFile := filepath.Join(path, ".dockerignore")
if dbDockerfilePath != "" {
customDiFile := dbDockerfilePath + ".dockerignore"
_, err := os.Stat(customDiFile)
if !os.IsNotExist(err) {
diFile = customDiFile
}
}
s.postExecReadFiles = sliceutils.AppendWithoutDupes(s.postExecReadFiles, diFile)
contents, err := os.ReadFile(diFile)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
patterns, err := dockerignore.ReadAll(bytes.NewBuffer(contents))
if err != nil {
return nil, err
}
result = append(result, model.Dockerignore{
LocalPath: path,
Source: diFile,
Patterns: patterns,
})
}
return result, nil
}
func onlysToDockerignorePatterns(onlys []string) []string {
if len(onlys) == 0 {
return nil
}
result := []string{"**"}
for _, only := range onlys {
result = append(result, fmt.Sprintf("!%s", only))
}
return result
}
func (s *tiltfileState) dockerignoresForImage(image *dockerImage) ([]model.Dockerignore, error) {
var paths []string
var source string
ref := image.configurationRef.RefFamiliarString()
switch image.Type() {
case DockerBuild:
if image.dbBuildPath != "" {
paths = append(paths, image.dbBuildPath)
}
source = fmt.Sprintf("docker_build(%q)", ref)
case CustomBuild:
paths = append(paths, image.customDeps...)
source = fmt.Sprintf("custom_build(%q)", ref)
case DockerComposeBuild:
if image.dbBuildPath != "" {
paths = append(paths, image.dbBuildPath)
}
source = fmt.Sprintf("docker_compose(%q)", ref)
}
return s.dockerignoresFromPathsAndContextFilters(
source,
paths, image.ignores, image.onlys, image.dbDockerfilePath)
}
// Filter out all images that are suppressed.
func filterUnmatchedImages(us model.UpdateSettings, images []*dockerImage) []*dockerImage {
result := make([]*dockerImage, 0, len(images))
for _, image := range images {
name := container.FamiliarString(image.configurationRef)
ok := true
for _, suppressed := range us.SuppressUnusedImageWarnings {
if suppressed == "*" {
ok = false
break
}
if suppressed == name {
ok = false
break
}
}
if ok {
result = append(result, image)
}
}
return result
}