-
Notifications
You must be signed in to change notification settings - Fork 303
/
tiltfile_state.go
1747 lines (1508 loc) · 53.3 KB
/
tiltfile_state.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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tiltfile
import (
"context"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/looplab/tarjan"
"github.com/pkg/errors"
"go.starlark.net/starlark"
"go.starlark.net/syntax"
"golang.org/x/mod/semver"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/tilt-dev/tilt/internal/controllers/apis/cmdimage"
"github.com/tilt-dev/tilt/internal/controllers/apis/dockerimage"
"github.com/tilt-dev/tilt/internal/controllers/apis/liveupdate"
"github.com/tilt-dev/tilt/internal/controllers/apiset"
"github.com/tilt-dev/tilt/internal/localexec"
"github.com/tilt-dev/tilt/internal/tiltfile/cisettings"
"github.com/tilt-dev/tilt/internal/tiltfile/hasher"
"github.com/tilt-dev/tilt/internal/tiltfile/links"
"github.com/tilt-dev/tilt/internal/tiltfile/print"
"github.com/tilt-dev/tilt/internal/tiltfile/probe"
"github.com/tilt-dev/tilt/internal/tiltfile/sys"
"github.com/tilt-dev/tilt/internal/tiltfile/tiltextension"
"github.com/tilt-dev/tilt/pkg/apis"
"github.com/tilt-dev/tilt/internal/container"
"github.com/tilt-dev/tilt/internal/dockercompose"
"github.com/tilt-dev/tilt/internal/feature"
"github.com/tilt-dev/tilt/internal/k8s"
"github.com/tilt-dev/tilt/internal/ospath"
"github.com/tilt-dev/tilt/internal/sliceutils"
"github.com/tilt-dev/tilt/internal/tiltfile/analytics"
"github.com/tilt-dev/tilt/internal/tiltfile/config"
"github.com/tilt-dev/tilt/internal/tiltfile/dockerprune"
"github.com/tilt-dev/tilt/internal/tiltfile/encoding"
"github.com/tilt-dev/tilt/internal/tiltfile/git"
"github.com/tilt-dev/tilt/internal/tiltfile/include"
"github.com/tilt-dev/tilt/internal/tiltfile/io"
tiltfile_k8s "github.com/tilt-dev/tilt/internal/tiltfile/k8s"
"github.com/tilt-dev/tilt/internal/tiltfile/k8scontext"
"github.com/tilt-dev/tilt/internal/tiltfile/loaddynamic"
"github.com/tilt-dev/tilt/internal/tiltfile/metrics"
"github.com/tilt-dev/tilt/internal/tiltfile/os"
"github.com/tilt-dev/tilt/internal/tiltfile/secretsettings"
"github.com/tilt-dev/tilt/internal/tiltfile/shlex"
"github.com/tilt-dev/tilt/internal/tiltfile/starkit"
"github.com/tilt-dev/tilt/internal/tiltfile/starlarkstruct"
"github.com/tilt-dev/tilt/internal/tiltfile/telemetry"
"github.com/tilt-dev/tilt/internal/tiltfile/updatesettings"
tfv1alpha1 "github.com/tilt-dev/tilt/internal/tiltfile/v1alpha1"
"github.com/tilt-dev/tilt/internal/tiltfile/version"
"github.com/tilt-dev/tilt/internal/tiltfile/watch"
fwatch "github.com/tilt-dev/tilt/internal/watch"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/tilt/pkg/logger"
"github.com/tilt-dev/tilt/pkg/model"
)
var unmatchedImageNoConfigsWarning = "We could not find any deployment instructions, e.g. `k8s_yaml` or `docker_compose`.\n" +
"Skipping all image builds until we know how to deploy them."
var unmatchedImageAllUnresourcedWarning = "No Kubernetes configs with images found.\n" +
"If you are using CRDs, add k8s_kind() to tell Tilt how to find images.\n" +
"https://docs.tilt.dev/api.html#api.k8s_kind"
var pkgInitTime = time.Now()
type resourceSet struct {
dc []*dcResourceSet
k8s []*k8sResource
}
type tiltfileState struct {
// set at creation
ctx context.Context
dcCli dockercompose.DockerComposeClient
webHost model.WebHost
execer localexec.Execer
k8sContextPlugin k8scontext.Plugin
versionPlugin version.Plugin
configPlugin *config.Plugin
extensionPlugin *tiltextension.Plugin
ciSettingsPlugin cisettings.Plugin
features feature.FeatureSet
// added to during execution
buildIndex *buildIndex
k8sObjectIndex *tiltfile_k8s.State
// The mutation semantics of these 3 things are a bit fuzzy
// Objects are moved back and forth between them in different
// phases of tiltfile execution and post-execution assembly.
//
// TODO(nick): Move these into a unified k8sObjectIndex that
// maintains consistent internal state. Right now the state
// is duplicated.
k8s []*k8sResource
k8sByName map[string]*k8sResource
k8sUnresourced []k8s.K8sEntity
dc dcResourceMap
k8sResourceOptions []k8sResourceOptions
localResources []*localResource
localByName map[string]*localResource
// ensure that any images are pushed to/pulled from this registry, rewriting names if needed
defaultReg *v1alpha1.RegistryHosting
k8sKinds map[k8s.ObjectSelector]*tiltfile_k8s.KindInfo
workloadToResourceFunction workloadToResourceFunction
// for assembly
usedImages map[string]bool
// count how many times each builtin is called, for analytics
builtinCallCounts map[string]int
// how many times each arg is used on each builtin
builtinArgCounts map[string]map[string]int
// any LiveUpdate steps that have been created but not used by a LiveUpdate will cause an error, to ensure
// that users aren't accidentally using step-creating functions incorrectly
// stored as a map of string(declarationPosition) -> step
// it'd be appealing to store this as a map[liveUpdateStep]bool, but then things get weird if we have two steps
// with the same hashcode (like, all restartcontainer steps)
unconsumedLiveUpdateSteps map[string]liveUpdateStep
// global trigger mode -- will be the default for all manifests (tho user can still explicitly set
// triggerMode for a specific manifest)
triggerMode triggerMode
// for error reporting in case it's called twice
triggerModeCallPosition syntax.Position
teamID string
secretSettings model.SecretSettings
apiObjects apiset.ObjectSet
logger logger.Logger
// postExecReadFiles is generally a mistake -- it means that if tiltfile execution fails,
// these will never be read. Remove these when you can!!!
postExecReadFiles []string
// Temporary directory for storing generated artifacts during the lifetime of the tiltfile context.
// The directory is recursively deleted when the context is done.
scratchDir *fwatch.TempDir
}
func newTiltfileState(
ctx context.Context,
dcCli dockercompose.DockerComposeClient,
webHost model.WebHost,
execer localexec.Execer,
k8sContextPlugin k8scontext.Plugin,
versionPlugin version.Plugin,
configPlugin *config.Plugin,
extensionPlugin *tiltextension.Plugin,
ciSettingsPlugin cisettings.Plugin,
features feature.FeatureSet) *tiltfileState {
return &tiltfileState{
ctx: ctx,
dcCli: dcCli,
webHost: webHost,
execer: execer,
k8sContextPlugin: k8sContextPlugin,
versionPlugin: versionPlugin,
configPlugin: configPlugin,
extensionPlugin: extensionPlugin,
ciSettingsPlugin: ciSettingsPlugin,
buildIndex: newBuildIndex(),
k8sObjectIndex: tiltfile_k8s.NewState(),
k8sByName: make(map[string]*k8sResource),
dc: make(map[string]*dcResourceSet),
localByName: make(map[string]*localResource),
usedImages: make(map[string]bool),
logger: logger.Get(ctx),
builtinCallCounts: make(map[string]int),
builtinArgCounts: make(map[string]map[string]int),
unconsumedLiveUpdateSteps: make(map[string]liveUpdateStep),
localResources: []*localResource{},
triggerMode: TriggerModeAuto,
features: features,
secretSettings: model.DefaultSecretSettings(),
apiObjects: apiset.ObjectSet{},
k8sKinds: tiltfile_k8s.InitialKinds(),
}
}
// print() for fulfilling the starlark thread callback
func (s *tiltfileState) print(_ *starlark.Thread, msg string) {
s.logger.Infof("%s", msg)
}
// Load loads the Tiltfile in `filename`, and returns the manifests matching `matching`.
//
// This often returns a starkit.Model even on error, because the starkit.Model
// has a record of what happened during the execution (what files were read, etc).
//
// TODO(nick): Eventually this will just return a starkit.Model, which will contain
// all the mutable state collected by execution.
func (s *tiltfileState) loadManifests(tf *v1alpha1.Tiltfile) ([]model.Manifest, starkit.Model, error) {
s.logger.Infof("Loading Tiltfile at: %s", tf.Spec.Path)
result, err := starkit.ExecFile(tf,
s,
include.IncludeFn{},
git.NewPlugin(),
os.NewPlugin(),
sys.NewPlugin(),
io.NewPlugin(),
s.k8sContextPlugin,
dockerprune.NewPlugin(),
analytics.NewPlugin(),
s.versionPlugin,
s.configPlugin,
starlarkstruct.NewPlugin(),
telemetry.NewPlugin(),
metrics.NewPlugin(),
updatesettings.NewPlugin(),
s.ciSettingsPlugin,
secretsettings.NewPlugin(),
encoding.NewPlugin(),
shlex.NewPlugin(),
watch.NewPlugin(),
loaddynamic.NewPlugin(),
s.extensionPlugin,
links.NewPlugin(),
print.NewPlugin(),
probe.NewPlugin(),
tfv1alpha1.NewPlugin(),
hasher.NewPlugin(),
)
if err != nil {
return nil, result, starkit.UnpackBacktrace(err)
}
resources, unresourced, err := s.assemble()
if err != nil {
return nil, result, err
}
us, err := updatesettings.GetState(result)
if err != nil {
return nil, result, err
}
err = s.assertAllImagesMatched(us)
if err != nil {
s.logger.Warnf("%s", err.Error())
}
manifests := []model.Manifest{}
k8sContextState, err := k8scontext.GetState(result)
if err != nil {
return nil, result, err
}
if len(resources.k8s) > 0 || len(unresourced) > 0 {
ms, err := s.translateK8s(resources.k8s, us)
if err != nil {
return nil, result, err
}
manifests = append(manifests, ms...)
isAllowed := k8sContextState.IsAllowed(tf)
if !isAllowed {
kubeContext := k8sContextState.KubeContext()
return nil, result, fmt.Errorf(`Stop! %s might be production.
If you're sure you want to deploy there, add:
allow_k8s_contexts('%s')
to your Tiltfile. Otherwise, switch k8s contexts and restart Tilt.`, kubeContext, kubeContext)
}
}
if len(resources.dc) > 0 {
if err := s.validateDockerComposeVersion(); err != nil {
return nil, result, err
}
for _, dc := range resources.dc {
ms, err := s.translateDC(dc)
if err != nil {
return nil, result, err
}
manifests = append(manifests, ms...)
}
}
err = s.validateLiveUpdatesForManifests(manifests)
if err != nil {
return nil, result, err
}
err = s.checkForUnconsumedLiveUpdateSteps()
if err != nil {
return nil, result, err
}
localManifests, err := s.translateLocal()
if err != nil {
return nil, result, err
}
manifests = append(manifests, localManifests...)
if len(unresourced) > 0 {
mn := model.UnresourcedYAMLManifestName
r := &k8sResource{
name: mn.String(),
entities: unresourced,
podReadinessMode: model.PodReadinessIgnore,
}
kt, err := s.k8sDeployTarget(mn.TargetName(), r, nil, us)
if err != nil {
return nil, starkit.Model{}, err
}
yamlManifest := model.Manifest{Name: mn}.WithDeployTarget(kt)
manifests = append(manifests, yamlManifest)
}
err = s.sanitizeDependencies(manifests)
if err != nil {
return nil, starkit.Model{}, err
}
for i := range manifests {
// ensure all manifests have a label indicating they're owned
// by the Tiltfile - some reconcilers have special handling
l := manifests[i].Labels
if l == nil {
l = make(map[string]string)
}
manifests[i] = manifests[i].WithLabels(l)
err := manifests[i].Validate()
if err != nil {
// Even on manifest validation errors, we may be able
// to use other kinds of models (e.g., watched files)
return manifests, result, err
}
}
return manifests, result, nil
}
// Builtin functions
const (
// build functions
dockerBuildN = "docker_build"
customBuildN = "custom_build"
defaultRegistryN = "default_registry"
// docker compose functions
dockerComposeN = "docker_compose"
dcResourceN = "dc_resource"
// k8s functions
k8sYamlN = "k8s_yaml"
filterYamlN = "filter_yaml"
k8sResourceN = "k8s_resource"
portForwardN = "port_forward"
k8sKindN = "k8s_kind"
k8sImageJSONPathN = "k8s_image_json_path"
workloadToResourceFunctionN = "workload_to_resource_function"
k8sCustomDeployN = "k8s_custom_deploy"
// local resource functions
localResourceN = "local_resource"
testN = "test" // a deprecated fork of local resource
// file functions
localN = "local"
kustomizeN = "kustomize"
helmN = "helm"
// live update functions
fallBackOnN = "fall_back_on"
syncN = "sync"
runN = "run"
restartContainerN = "restart_container"
// trigger mode
triggerModeN = "trigger_mode"
triggerModeAutoN = "TRIGGER_MODE_AUTO"
triggerModeManualN = "TRIGGER_MODE_MANUAL"
// feature flags
enableFeatureN = "enable_feature"
disableFeatureN = "disable_feature"
disableSnapshotsN = "disable_snapshots"
// other functions
setTeamN = "set_team"
)
type triggerMode int
func (m triggerMode) String() string {
switch m {
case TriggerModeAuto:
return triggerModeAutoN
case TriggerModeManual:
return triggerModeManualN
default:
return fmt.Sprintf("unknown trigger mode with value %d", m)
}
}
func (t triggerMode) Type() string {
return "TriggerMode"
}
func (t triggerMode) Freeze() {
// noop
}
func (t triggerMode) Truth() starlark.Bool {
return starlark.MakeInt(int(t)).Truth()
}
func (t triggerMode) Hash() (uint32, error) {
return starlark.MakeInt(int(t)).Hash()
}
var _ starlark.Value = triggerMode(0)
const (
TriggerModeUnset triggerMode = iota
TriggerModeAuto triggerMode = iota
TriggerModeManual triggerMode = iota
)
func (s *tiltfileState) triggerModeForResource(resourceTriggerMode triggerMode) triggerMode {
if resourceTriggerMode != TriggerModeUnset {
return resourceTriggerMode
} else {
return s.triggerMode
}
}
func starlarkTriggerModeToModel(triggerMode triggerMode, autoInit bool) (model.TriggerMode, error) {
switch triggerMode {
case TriggerModeAuto:
if !autoInit {
return model.TriggerModeAutoWithManualInit, nil
}
return model.TriggerModeAuto, nil
case TriggerModeManual:
if autoInit {
return model.TriggerModeManualWithAutoInit, nil
} else {
return model.TriggerModeManual, nil
}
default:
return 0, fmt.Errorf("unknown triggerMode %v", triggerMode)
}
}
// count how many times each Builtin is called, for analytics
func (s *tiltfileState) OnBuiltinCall(name string, fn *starlark.Builtin) {
s.builtinCallCounts[name]++
}
func (s *tiltfileState) OnExec(t *starlark.Thread, tiltfilePath string, contents []byte) error {
return nil
}
// wrap a builtin such that it's only allowed to run when we have a known safe k8s context
// (none (e.g., docker-compose), local, or specified by `allow_k8s_contexts`)
func (s *tiltfileState) potentiallyK8sUnsafeBuiltin(f starkit.Function) starkit.Function {
return func(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
tf, err := starkit.StartTiltfileFromThread(thread)
if err != nil {
return nil, err
}
model, err := starkit.ModelFromThread(thread)
if err != nil {
return nil, err
}
k8sContextState, err := k8scontext.GetState(model)
if err != nil {
return nil, err
}
isAllowed := k8sContextState.IsAllowed(tf)
if !isAllowed {
kubeContext := k8sContextState.KubeContext()
return nil, fmt.Errorf(`Refusing to run '%s' because %s might be a production kube context.
If you're sure you want to continue add:
allow_k8s_contexts('%s')
before this function call in your Tiltfile. Otherwise, switch k8s contexts and restart Tilt.`, fn.Name(), kubeContext, kubeContext)
}
return f(thread, fn, args, kwargs)
}
}
func (s *tiltfileState) unpackArgs(fnname string, args starlark.Tuple, kwargs []starlark.Tuple, pairs ...interface{}) error {
err := starlark.UnpackArgs(fnname, args, kwargs, pairs...)
if err == nil {
var paramNames []string
for i, o := range pairs {
if i%2 == 0 {
name := strings.TrimSuffix(o.(string), "?")
paramNames = append(paramNames, name)
}
}
usedParamNames := paramNames[:args.Len()]
for _, p := range kwargs {
name := strings.TrimSuffix(string(p[0].(starlark.String)), "?")
usedParamNames = append(usedParamNames, name)
}
_, ok := s.builtinArgCounts[fnname]
if !ok {
s.builtinArgCounts[fnname] = make(map[string]int)
}
for _, paramName := range usedParamNames {
s.builtinArgCounts[fnname][paramName]++
}
}
return err
}
// TODO(nick): Split these into separate plugins
func (s *tiltfileState) OnStart(e *starkit.Environment) error {
e.SetArgUnpacker(s.unpackArgs)
e.SetPrint(s.print)
e.SetContext(s.ctx)
for _, b := range []struct {
name string
builtin starkit.Function
}{
{localN, s.potentiallyK8sUnsafeBuiltin(s.local)},
{dockerBuildN, s.dockerBuild},
{customBuildN, s.customBuild},
{defaultRegistryN, s.defaultRegistry},
{dockerComposeN, s.dockerCompose},
{dcResourceN, s.dcResource},
{k8sYamlN, s.k8sYaml},
{filterYamlN, s.filterYaml},
{k8sResourceN, s.k8sResource},
{k8sCustomDeployN, s.k8sCustomDeploy},
{localResourceN, s.localResource},
{testN, s.localResource},
{portForwardN, s.portForward},
{k8sKindN, s.k8sKind},
{k8sImageJSONPathN, s.k8sImageJsonPath},
{workloadToResourceFunctionN, s.workloadToResourceFunctionFn},
{kustomizeN, s.kustomize},
{helmN, s.helm},
{triggerModeN, s.triggerModeFn},
{fallBackOnN, s.liveUpdateFallBackOn},
{syncN, s.liveUpdateSync},
{runN, s.liveUpdateRun},
{restartContainerN, s.liveUpdateRestartContainer},
{enableFeatureN, s.enableFeature},
{disableFeatureN, s.disableFeature},
{disableSnapshotsN, s.disableSnapshots},
{setTeamN, s.setTeam},
} {
err := e.AddBuiltin(b.name, b.builtin)
if err != nil {
return err
}
}
for _, v := range []struct {
name string
value starlark.Value
}{
{triggerModeAutoN, TriggerModeAuto},
{triggerModeManualN, TriggerModeManual},
} {
err := e.AddValue(v.name, v.value)
if err != nil {
return err
}
}
return nil
}
func (s *tiltfileState) assemble() (resourceSet, []k8s.K8sEntity, error) {
err := s.assembleImages()
if err != nil {
return resourceSet{}, nil, err
}
err = s.assembleK8s()
if err != nil {
return resourceSet{}, nil, err
}
err = s.assembleDC()
if err != nil {
return resourceSet{}, nil, err
}
dcRes := []*dcResourceSet{}
for _, resSet := range s.dc {
dcRes = append(dcRes, resSet)
}
return resourceSet{
dc: dcRes,
k8s: s.k8s,
}, s.k8sUnresourced, nil
}
// Emit an error if there are unmatches images.
//
// There are 4 mistakes people commonly make if they
// have unmatched images:
// 1. They didn't include any Kubernetes or Docker Compose configs at all.
// 2. They included Kubernetes configs, but they're custom resources
// and Tilt can't infer the image.
// 3. They typo'd the image name, and need help finding the right name.
// 4. The tooling they're using to generating the k8s resources
// isn't generating what they expect.
//
// This function intends to help with cases (1)-(3).
// Long-term, we want to have better tooling to help with (4),
// like being able to see k8s resources as they move thru
// the build system.
func (s *tiltfileState) assertAllImagesMatched(us model.UpdateSettings) error {
unmatchedImages := s.buildIndex.unmatchedImages()
unmatchedImages = filterUnmatchedImages(us, unmatchedImages)
if len(unmatchedImages) == 0 {
return nil
}
dcSvcCount := s.dc.ServiceCount()
if dcSvcCount == 0 && len(s.k8s) == 0 && len(s.k8sUnresourced) == 0 {
return fmt.Errorf(unmatchedImageNoConfigsWarning)
}
if len(s.k8s) == 0 && len(s.k8sUnresourced) != 0 {
return fmt.Errorf(unmatchedImageAllUnresourcedWarning)
}
configType := "Kubernetes"
if dcSvcCount > 0 {
configType = "Docker Compose"
}
return s.buildIndex.unmatchedImageWarning(unmatchedImages[0], configType)
}
func (s *tiltfileState) assembleImages() error {
for _, imageBuilder := range s.buildIndex.images {
if imageBuilder.dbDockerfile != "" {
depImages, err := imageBuilder.dbDockerfile.FindImages(imageBuilder.dbBuildArgs)
if err != nil {
return err
}
for _, depImage := range depImages {
depBuilder := s.buildIndex.findBuilderForConsumedImage(depImage)
if depBuilder == nil {
// Images in the Dockerfile that don't have docker_build
// instructions are OK. We'll pull them as prebuilt images.
continue
}
imageBuilder.imageMapDeps = append(imageBuilder.imageMapDeps, depBuilder.ImageMapName())
}
}
for _, depImage := range imageBuilder.customImgDeps {
depBuilder := s.buildIndex.findBuilderForConsumedImage(depImage)
if depBuilder == nil {
// If the user specifically said to depend on this image, there
// must be a build instruction for it.
return fmt.Errorf("image %q: image dep %q not found",
imageBuilder.configurationRef.RefFamiliarString(), container.FamiliarString(depImage))
}
imageBuilder.imageMapDeps = append(imageBuilder.imageMapDeps, depBuilder.ImageMapName())
}
}
return nil
}
func (s *tiltfileState) assembleDC() error {
if s.dc.ServiceCount() > 0 && !container.IsEmptyRegistry(s.defaultReg) {
return errors.New("default_registry is not supported with docker compose")
}
for _, resSet := range s.dc {
for _, svcName := range resSet.serviceNames {
svc := resSet.services[svcName]
builder := s.buildIndex.findBuilderForConsumedImage(svc.ImageRef())
if builder != nil {
// there's a Tilt-managed builder (e.g. docker_build or custom_build) for this image reference, so use that
svc.ImageMapDeps = append(svc.ImageMapDeps, builder.ImageMapName())
} else {
// create a DockerComposeBuild image target and consume it if this service has a build section in YAML
err := s.maybeAddDockerComposeImageBuilder(svc)
if err != nil {
return err
}
}
}
}
return nil
}
func (s *tiltfileState) maybeAddDockerComposeImageBuilder(svc *dcService) error {
build := svc.ServiceConfig.Build
if build == nil || build.Context == "" {
// this Docker Compose service has no build info - it relies purely on
// a pre-existing image (e.g. from a registry)
return nil
}
buildContext := build.Context
dfPath := build.Dockerfile
if dfPath == "" {
// Per Compose spec, the default is "Dockerfile" (in the context dir)
dfPath = "Dockerfile"
}
// Only populate dbBuildPath if it's an absolute path, not if it's a git url.
dbBuildPath := ""
if filepath.IsAbs(buildContext) {
dbBuildPath = buildContext
}
if !filepath.IsAbs(dfPath) && dbBuildPath != "" {
dfPath = filepath.Join(dbBuildPath, dfPath)
}
imageRef := svc.ImageRef()
err := s.buildIndex.addImage(
&dockerImage{
buildType: DockerComposeBuild,
configurationRef: container.NewRefSelector(imageRef),
dockerComposeService: svc.ServiceName,
dockerComposeLocalVolumePaths: svc.MountedLocalDirs,
dbBuildPath: dbBuildPath,
dbDockerfilePath: dfPath,
})
if err != nil {
return err
}
b := s.buildIndex.findBuilderForConsumedImage(imageRef)
svc.ImageMapDeps = append(svc.ImageMapDeps, b.ImageMapName())
return nil
}
func (s *tiltfileState) assembleK8s() error {
err := s.assembleK8sByWorkload()
if err != nil {
return err
}
err = s.assembleK8sUnresourced()
if err != nil {
return err
}
resourcedEntities := []k8s.K8sEntity{}
for _, r := range s.k8sByName {
resourcedEntities = append(resourcedEntities, r.entities...)
}
allEntities := append(resourcedEntities, s.k8sUnresourced...)
fragmentsToEntities := k8s.FragmentsToEntities(allEntities)
fullNames := make([]string, len(allEntities))
for i, e := range allEntities {
fullNames[i] = fullNameFromK8sEntity(e)
}
for _, opts := range s.k8sResourceOptions {
if opts.manuallyGrouped {
r, err := s.makeK8sResource(opts.newName)
if err != nil {
return err
}
r.manuallyGrouped = true
s.k8sByName[opts.newName] = r
}
if r, ok := s.k8sByName[opts.workload]; ok {
// Options are added, so aggregate options from previous resource calls.
r.extraPodSelectors = append(r.extraPodSelectors, opts.extraPodSelectors...)
if opts.podReadinessMode != model.PodReadinessNone {
r.podReadinessMode = opts.podReadinessMode
}
if opts.discoveryStrategy != "" {
r.discoveryStrategy = opts.discoveryStrategy
}
r.portForwards = append(r.portForwards, opts.portForwards...)
if opts.triggerMode != TriggerModeUnset {
r.triggerMode = opts.triggerMode
}
if opts.autoInit.IsSet {
r.autoInit = bool(opts.autoInit.Value)
}
r.resourceDeps = append(r.resourceDeps, opts.resourceDeps...)
r.links = append(r.links, opts.links...)
for k, v := range opts.labels {
r.labels[k] = v
}
if opts.newName != "" && opts.newName != r.name {
err := s.checkResourceConflict(opts.newName)
if err != nil {
return fmt.Errorf("%s: k8s_resource specified to rename %q to %q: %v",
opts.tiltfilePosition.String(), r.name, opts.newName, err)
}
delete(s.k8sByName, r.name)
r.name = opts.newName
s.k8sByName[r.name] = r
}
selectors := make([]k8s.ObjectSelector, len(opts.objects))
for i, o := range opts.objects {
s, err := k8s.SelectorFromString(o)
if err != nil {
return errors.Wrapf(err, "Error making selector from string %q", o)
}
selectors[i] = s
}
for i, o := range opts.objects {
entities, ok := fragmentsToEntities[strings.ToLower(o)]
if !ok || len(entities) == 0 {
return fmt.Errorf("No object identified by the fragment %q could be found. Possible objects are: %s", o, sliceutils.QuotedStringList(fullNames))
}
if len(entities) > 1 {
matchingObjects := make([]string, len(entities))
for i, e := range entities {
matchingObjects[i] = fullNameFromK8sEntity(e)
}
return fmt.Errorf("%q is not a unique fragment. Objects that match %q are %s", o, o, sliceutils.QuotedStringList(matchingObjects))
}
entitiesToRemove := filterEntitiesBySelector(s.k8sUnresourced, selectors[i])
if len(entitiesToRemove) == 0 {
// we've already taken these entities out of unresourced
remainingUnresourced := make([]string, len(s.k8sUnresourced))
for i, entity := range s.k8sUnresourced {
remainingUnresourced[i] = fullNameFromK8sEntity(entity)
}
return fmt.Errorf("No object identified by the fragment %q could be found in remaining YAML. Valid remaining fragments are: %s", o, sliceutils.QuotedStringList(remainingUnresourced))
}
if len(entitiesToRemove) > 1 {
panic(fmt.Sprintf("Fragment %q matches %d resources. Each object fragment must match exactly 1 resource. This should NOT be possible at this point in the code, we should have already checked that this fragment was unique", o, len(entitiesToRemove)))
}
s.addEntityToResourceAndRemoveFromUnresourced(entitiesToRemove[0], r)
}
} else {
var knownResources []string
for name := range s.k8sByName {
knownResources = append(knownResources, name)
}
return fmt.Errorf("%s: k8s_resource specified unknown resource %q. known k8s resources: %s",
opts.tiltfilePosition.String(), opts.workload, strings.Join(knownResources, ", "))
}
}
for _, r := range s.k8s {
if err := s.validateK8s(r); err != nil {
return err
}
}
return nil
}
// NOTE(dmiller): This isn't _technically_ a fullname since it is missing "group" (core, apps, data, etc)
// A true full name would look like "foo:secret:mynamespace:core"
// However because we
// a) couldn't think of a concrete case where you would need to specify group
// b) being able to do so would make things more complicated, like in the case where you want to specify the group of
//
// a cluster scoped object but are unable to specify the namespace (e.g. foo:clusterrole::rbac.authorization.k8s.io)
//
// we decided to leave it off for now. When we encounter a concrete use case for specifying group it shouldn't be too
// hard to add it here and in the docs.
func fullNameFromK8sEntity(e k8s.K8sEntity) string {
return k8s.SelectorStringFromParts([]string{e.Name(), e.GVK().Kind, e.Namespace().String()})
}
func filterEntitiesBySelector(entities []k8s.K8sEntity, sel k8s.ObjectSelector) []k8s.K8sEntity {
ret := []k8s.K8sEntity{}
for _, e := range entities {
if sel.Matches(e) {
ret = append(ret, e)
}
}
return ret
}
func (s *tiltfileState) addEntityToResourceAndRemoveFromUnresourced(e k8s.K8sEntity, r *k8sResource) {
r.entities = append(r.entities, e)
for i, ur := range s.k8sUnresourced {
if ur == e {
// delete from unresourced
s.k8sUnresourced = append(s.k8sUnresourced[:i], s.k8sUnresourced[i+1:]...)
return
}
}
panic("Unable to find entity in unresourced YAML after checking that it was there. This should never happen")
}
func (s *tiltfileState) assembleK8sByWorkload() error {
locators := s.k8sImageLocatorsList()
var workloads, rest []k8s.K8sEntity
for _, e := range s.k8sUnresourced {
isWorkload, err := s.isWorkload(e, locators)
if err != nil {
return err
}
if isWorkload {
workloads = append(workloads, e)
} else {
rest = append(rest, e)
}
}
s.k8sUnresourced = rest
resourceNames, err := s.calculateResourceNames(workloads)
if err != nil {
return err
}
for i, resourceName := range resourceNames {
workload := workloads[i]
res, err := s.makeK8sResource(resourceName)
if err != nil {
return errors.Wrapf(err, "error making resource for workload %s", newK8sObjectID(workload))
}
err = res.addEntities([]k8s.K8sEntity{workload}, locators, s.envVarImages())
if err != nil {
return err
}
// find any other entities that match the workload's labels (e.g., services),
// and move them from unresourced to this resource
match, rest, err := k8s.FilterByMatchesPodTemplateSpec(workload, s.k8sUnresourced)
if err != nil {
return err
}
err = res.addEntities(match, locators, s.envVarImages())
if err != nil {
return err
}
s.k8sUnresourced = rest
}
return nil
}
func (s *tiltfileState) envVarImages() []container.RefSelector {
var r []container.RefSelector
// explicitly don't care about order
for _, img := range s.buildIndex.images {
if !img.matchInEnvVars {
continue
}
r = append(r, img.configurationRef)
}
return r
}
func (s *tiltfileState) isWorkload(e k8s.K8sEntity, locators []k8s.ImageLocator) (bool, error) {
for sel := range s.k8sKinds {
if sel.Matches(e) {
return true, nil
}
}
images, err := e.FindImages(locators, s.envVarImages())
if err != nil {
return false, errors.Wrapf(err, "finding images in %s", e.Name())
} else {
return len(images) > 0, nil