-
Notifications
You must be signed in to change notification settings - Fork 303
/
tiltfile_state.go
1459 lines (1247 loc) · 43.4 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"
"github.com/docker/distribution/reference"
"github.com/looplab/tarjan"
"github.com/pkg/errors"
"go.starlark.net/starlark"
"go.starlark.net/syntax"
links "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/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/tiltextension"
"github.com/tilt-dev/tilt/internal/tiltfile/updatesettings"
"github.com/tilt-dev/tilt/internal/tiltfile/version"
"github.com/tilt-dev/tilt/internal/tiltfile/watch"
"github.com/tilt-dev/tilt/pkg/logger"
"github.com/tilt-dev/tilt/pkg/model"
)
var unmatchedImageNoConfigsWarning = "No Kubernetes or Docker Compose configs found.\n" +
"Skipping all image builds until we have a place 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"
type resourceSet struct {
dc dcResourceSet // currently only support one d-c.yml
k8s []*k8sResource
}
type tiltfileState struct {
// set at creation
ctx context.Context
dcCli dockercompose.DockerComposeClient
webHost model.WebHost
k8sContextExt k8scontext.Extension
versionExt version.Extension
configExt *config.Extension
localRegistry container.Registry
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 dcResourceSet // currently only support one d-c.yml
k8sResourceOptions map[string]k8sResourceOptions
localResources []localResource
// ensure that any images are pushed to/pulled from this registry, rewriting names if needed
defaultReg container.Registry
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
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
}
func newTiltfileState(
ctx context.Context,
dcCli dockercompose.DockerComposeClient,
webHost model.WebHost,
k8sContextExt k8scontext.Extension,
versionExt version.Extension,
configExt *config.Extension,
localRegistry container.Registry,
features feature.FeatureSet) *tiltfileState {
return &tiltfileState{
ctx: ctx,
dcCli: dcCli,
webHost: webHost,
k8sContextExt: k8sContextExt,
versionExt: versionExt,
configExt: configExt,
localRegistry: localRegistry,
buildIndex: newBuildIndex(),
k8sObjectIndex: tiltfile_k8s.NewState(),
k8sByName: make(map[string]*k8sResource),
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),
k8sResourceOptions: make(map[string]k8sResourceOptions),
localResources: []localResource{},
triggerMode: TriggerModeAuto,
features: features,
secretSettings: model.DefaultSecretSettings(),
k8sKinds: make(map[k8s.ObjectSelector]*tiltfile_k8s.KindInfo),
}
}
// 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(absFilename string, userConfigState model.UserConfigState) ([]model.Manifest, starkit.Model, error) {
s.logger.Infof("Beginning Tiltfile execution")
s.configExt.UserConfigState = userConfigState
dlr, err := tiltextension.NewTempDirDownloader()
if err != nil {
return nil, starkit.Model{}, err
}
fetcher := tiltextension.NewGithubFetcher(dlr)
result, err := starkit.ExecFile(absFilename,
s,
include.IncludeFn{},
git.NewExtension(),
os.NewExtension(),
sys.NewExtension(),
io.NewExtension(),
s.k8sContextExt,
dockerprune.NewExtension(),
analytics.NewExtension(),
s.versionExt,
s.configExt,
starlarkstruct.NewExtension(),
telemetry.NewExtension(),
metrics.NewExtension(),
updatesettings.NewExtension(),
secretsettings.NewExtension(),
encoding.NewExtension(),
shlex.NewExtension(),
watch.NewExtension(),
loaddynamic.NewExtension(),
tiltextension.NewExtension(fetcher, tiltextension.NewLocalStore(filepath.Dir(absFilename))),
links.NewExtension(),
print.NewExtension(),
probe.NewExtension(),
)
if err != nil {
return nil, result, starkit.UnpackBacktrace(err)
}
resources, unresourced, err := s.assemble()
if err != nil {
return nil, result, err
}
var manifests []model.Manifest
k8sContextState, err := k8scontext.GetState(result)
if err != nil {
return nil, result, err
}
if len(resources.k8s) > 0 || len(unresourced) > 0 {
manifests, err = s.translateK8s(resources.k8s)
if err != nil {
return nil, result, err
}
isAllowed := k8sContextState.IsAllowed()
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)
}
} else {
manifests, err = s.translateDC(resources.dc)
if err != nil {
return nil, result, err
}
}
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...)
configSettings, _ := config.GetState(result)
manifests, err = configSettings.EnabledResources(manifests)
if err != nil {
return nil, starkit.Model{}, err
}
if len(unresourced) > 0 {
yamlManifest, err := k8s.NewK8sOnlyManifest(model.UnresourcedYAMLManifestName, unresourced, s.k8sImageLocatorsList())
if err != nil {
return nil, starkit.Model{}, err
}
manifests = append(manifests, yamlManifest)
}
err = validateResourceDependencies(manifests)
if err != nil {
return nil, starkit.Model{}, err
}
for _, m := range manifests {
err := m.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"
// local resource functions
localResourceN = "local_resource"
testN = "test" // test is just a 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) 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) {
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()
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 extensions
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},
{localResourceN, s.localResource},
{testN, s.localResource}, // test is just a fork of local resource, w/ some switches based on fn.Name()
{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
}
// Returns the current orchestrator.
//
// Note that assemble() will eventually error out if this has
// both DC and K8s resources.
func (s *tiltfileState) orchestrator() model.Orchestrator {
if !s.dc.Empty() {
return model.OrchestratorDC
}
return model.OrchestratorK8s
}
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
}
if !s.dc.Empty() && (len(s.k8s) > 0 || len(s.k8sUnresourced) > 0) {
return resourceSet{}, nil, fmt.Errorf("can't declare both k8s " +
"resources/entities and docker-compose resources")
}
err = s.assertAllImagesMatched()
if err != nil {
s.logger.Warnf("%s", err.Error())
}
return resourceSet{
dc: s.dc,
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() error {
unmatchedImages := s.buildIndex.unmatchedImages()
if len(unmatchedImages) == 0 {
return nil
}
if len(s.dc.services) == 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 len(s.dc.services) > 0 {
configType = "Docker Compose"
}
return s.buildIndex.unmatchedImageWarning(unmatchedImages[0], configType)
}
func (s *tiltfileState) assembleImages() error {
for _, imageBuilder := range s.buildIndex.images {
var err error
var depImages []reference.Named
if imageBuilder.dbDockerfile != "" {
depImages, err = imageBuilder.dbDockerfile.FindImages()
}
if err != nil {
return err
}
for _, depImage := range depImages {
depBuilder := s.buildIndex.findBuilderForConsumedImage(depImage)
if depBuilder != nil {
imageBuilder.dependencyIDs = append(imageBuilder.dependencyIDs, depBuilder.ID())
}
}
}
return nil
}
func (s *tiltfileState) assembleDC() error {
if len(s.dc.services) > 0 && !s.defaultReg.Empty() {
return errors.New("default_registry is not supported with docker compose")
}
for _, svc := range s.dc.services {
if svc.ImageRef() != nil {
builder := s.buildIndex.findBuilderForConsumedImage(svc.ImageRef())
if builder != nil {
svc.DependencyIDs = append(svc.DependencyIDs, builder.ID())
}
// TODO(maia): throw warning if
// a. there is an img ref from config, and img ref from user doesn't match
// b. there is no img ref from config, and img ref from user is not of form .*_<svc_name>
}
}
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 workload, 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[workload]; ok {
r.extraPodSelectors = opts.extraPodSelectors
r.podReadinessMode = opts.podReadinessMode
r.portForwards = opts.portForwards
r.triggerMode = opts.triggerMode
r.autoInit = opts.autoInit
r.resourceDeps = opts.resourceDeps
r.links = opts.links
if opts.newName != "" && opts.newName != r.name {
if _, ok := s.k8sByName[opts.newName]; ok {
return fmt.Errorf("k8s_resource at %s specified to rename %q to %q, but there already exists a resource with that name", opts.tiltfilePosition.String(), r.name, opts.newName)
}
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("k8s_resource at %s specified unknown resource %q. known resources: %s\n\nNote: Tilt's resource naming has recently changed. See https://docs.tilt.dev/resource_assembly_migration.html for more info", opts.tiltfilePosition.String(), 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
}
}
// assembleK8sUnresourced makes k8sResources for all k8s entities that:
// a. are not already attached to a Tilt resource, and
// b. will result in pods,
// and stores the resulting resource(s) on the tiltfileState.
// (We smartly grouping pod-creating entities with some kinds of
// corresponding entities, e.g. services),
func (s *tiltfileState) assembleK8sUnresourced() error {
withPodSpec, allRest, err := k8s.FilterByHasPodTemplateSpec(s.k8sUnresourced)
if err != nil {
return nil
}
for _, e := range withPodSpec {
target, err := s.k8sResourceForName(e.Name())
if err != nil {
return err
}
target.entities = append(target.entities, e)
match, rest, err := k8s.FilterByMatchesPodTemplateSpec(e, allRest)
if err != nil {
return err
}
target.entities = append(target.entities, match...)
allRest = rest
}
s.k8sUnresourced = allRest
return nil
}
func (s *tiltfileState) validateK8s(r *k8sResource) error {
if len(r.entities) == 0 {
return fmt.Errorf("resource %q: could not associate any k8s YAML with this resource", r.name)
}
for _, ref := range r.imageRefs {
builder := s.buildIndex.findBuilderForConsumedImage(ref)
if builder != nil {
r.dependencyIDs = append(r.dependencyIDs, builder.ID())
}
}
return nil
}
// k8sResourceForName returns the k8sResource with which this name is associated
// (either an existing resource or a new one).
func (s *tiltfileState) k8sResourceForName(name string) (*k8sResource, error) {
if r, ok := s.k8sByName[name]; ok {
return r, nil
}
// otherwise, create a new resource
return s.makeK8sResource(name)
}
// decideRegistry returns the image registry we should use; if detected, a pre-configured
// local registry; otherwise, the registry specified by the user via default_registry.
// Otherwise, we'll return the zero value of `s.defaultReg`, which is an empty registry.
// It has side-effects (a log line) and so should only be called once.
func (s *tiltfileState) decideRegistry() container.Registry {
if s.orchestrator() == model.OrchestratorK8s && !s.localRegistry.Empty() {
// If we've found a local registry in the cluster at run-time, use that
// instead of the default_registry (if any) declared in the Tiltfile
s.logger.Infof("Auto-detected local registry from environment: %s", s.localRegistry)
return s.localRegistry
}
return s.defaultReg
}
// Auto-infer the readiness mode
//
// CONVO:
// jazzdan: This still feels overloaded to me
// nicks: i think whenever we define a new CRD, we need to know:
// how to find the images in it
// how to find any pods it deploys (if they can't be found by owner references)
// if it should not expect pods at all (e.g., PostgresVersion)
// if it should wait for the pods to be ready before building the next resource (e.g., servers)
// if it should wait for the pods to be complete before building the next resource (e.g., jobs)
// and it's complicated a bit by the fact that there are both normal CRDs where the image shows up in the same place each time, and more meta CRDs (like HelmRelease) where it might appear in different places
//
// feels like wer're still doing this very ad-hoc rather than holistically
func (s *tiltfileState) inferPodReadinessMode(r *k8sResource) model.PodReadinessMode {
// The mode set directly on the resource has highest priority.
if r.podReadinessMode != model.PodReadinessNone {
return r.podReadinessMode
}
// Next, check if any of the k8s kinds have a mode.
hasWaitMode := false
hasIgnoreMode := false
for _, e := range r.entities {
for sel, info := range s.k8sKinds {
if sel.Matches(e) {
if info.PodReadinessMode == model.PodReadinessWait {
hasWaitMode = true
}
if info.PodReadinessMode == model.PodReadinessIgnore {
hasIgnoreMode = true
}
}
}
}
if hasWaitMode {
return model.PodReadinessWait
}
if hasIgnoreMode {
return model.PodReadinessIgnore
}
// Auto-infer based on context
//
// If the resource was
// 1) manually grouped (i.e., we didn't find any images in it)
// 2) doesn't have pod selectors, and
// 3) doesn't depend on images
// assume that it will never create pods.