-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathstack_processor_utils.go
More file actions
2915 lines (2607 loc) · 115 KB
/
Copy pathstack_processor_utils.go
File metadata and controls
2915 lines (2607 loc) · 115 KB
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 exec
import (
stderrors "errors"
"fmt"
"hash/fnv"
"os"
"path/filepath"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"sync"
"github.com/go-viper/mapstructure/v2"
"github.com/pkg/errors"
"github.com/santhosh-tekuri/jsonschema/v5"
"gopkg.in/yaml.v3"
errUtils "github.com/cloudposse/atmos/errors"
cfg "github.com/cloudposse/atmos/pkg/config"
log "github.com/cloudposse/atmos/pkg/logger"
m "github.com/cloudposse/atmos/pkg/merge"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/schema"
stackimports "github.com/cloudposse/atmos/pkg/stack/imports"
atmostmpl "github.com/cloudposse/atmos/pkg/template"
u "github.com/cloudposse/atmos/pkg/utils"
"github.com/cloudposse/atmos/pkg/version/manager"
)
// Mutex to serialize writes to importsConfig maps during parallel import processing.
var importsConfigLock = &sync.Mutex{}
// extractLocalsResult holds the results of parsing raw YAML and extracting locals.
type extractLocalsResult struct {
locals map[string]any // Resolved locals.
settings map[string]any // Settings section (for template context).
vars map[string]any // Vars section (for template context).
env map[string]any // Env section (for template context).
versionTrack string // Stack-asserted version track.
hasLocals bool // Whether any locals section exists in the file (including empty locals).
}
// localsExtractionCache memoizes extractLocalsFromRawYAML results keyed by a
// composite of the file path and a content fingerprint. Within a single command
// execution against a real filesystem, file content is immutable (and is itself
// cached via getFileContentSyncMap), so the parse + locals resolution is fully
// deterministic and may be served from cache on repeat imports of the same file.
//
// On the customer workload, extractLocalsFromRawYAML was called 22,181 times for
// ~836 unique files (~26 calls per file via transitive imports), accumulating 13s
// of cumulative CPU time. ~7s of that was UnmarshalYAMLFromFile re-parsing the
// same YAML content for the same file path. This cache eliminates the repeat work.
//
// The cache key includes a 64-bit FNV-1a hash of the YAML content so that test
// callers reusing the same logical file path with different content (a common
// pattern in stack_processor_utils_test.go) do not see stale results, and so that
// a future caller doing dynamic content generation cannot trip on a stale parse.
// FNV-1a was chosen for speed and stdlib availability; collisions on map-key
// strings are not a security concern here because the cache only feeds back to
// the same function under the same atmosConfig.
//
// Cached entries are deep-copied on retrieval (the result struct contains four
// maps: locals/settings/vars/env, all of which downstream consumers store into
// shared template contexts; mutating them would corrupt the cache). Deep-copy
// cost is dominated by map allocation and is typically <50µs per call — well
// below the 533µs avg of the un-cached path.
var localsExtractionCache sync.Map // map[string]*extractLocalsResult (immutable post-insert).
// hexBase is the base argument passed to strconv.FormatUint when building the
// hex-encoded portion of localsCacheKey.
const hexBase = 16
// localsCacheKey builds a stable cache key from the absolute file path and a
// content fingerprint. The fingerprint is a 64-bit FNV-1a hash of yamlContent
// so that the same file path used with two different contents (mostly a test
// pattern) yields two distinct cache entries.
func localsCacheKey(filePath, yamlContent string) string {
h := fnv.New64a()
_, _ = h.Write([]byte(yamlContent))
return filePath + "@" + strconv.FormatUint(h.Sum64(), hexBase)
}
// cloneExtractLocalsResult deep-copies an extractLocalsResult so the cache value
// remains immutable across concurrent retrievals. Returns the same nil hint when
// the source is nil.
func cloneExtractLocalsResult(src *extractLocalsResult) *extractLocalsResult {
if src == nil {
return nil
}
dst := &extractLocalsResult{
hasLocals: src.hasLocals,
versionTrack: src.versionTrack,
}
if src.locals != nil {
if cloned, err := m.DeepCopyMap(src.locals); err == nil {
dst.locals = cloned
}
}
if src.settings != nil {
if cloned, err := m.DeepCopyMap(src.settings); err == nil {
dst.settings = cloned
}
}
if src.vars != nil {
if cloned, err := m.DeepCopyMap(src.vars); err == nil {
dst.vars = cloned
}
}
if src.env != nil {
if cloned, err := m.DeepCopyMap(src.env); err == nil {
dst.env = cloned
}
}
return dst
}
// ClearLocalsExtractionCache clears the locals extraction cache.
// This should be called between independent operations (like tests) to ensure
// fresh processing of files whose on-disk content may have changed.
func ClearLocalsExtractionCache() {
defer perf.Track(nil, "exec.ClearLocalsExtractionCache")()
localsExtractionCache.Range(func(key, _ any) bool {
localsExtractionCache.Delete(key)
return true
})
}
// extractLocalsFromRawYAML parses raw YAML content and extracts/resolves file-scoped locals.
// This function is called BEFORE template processing to make locals available during template execution.
// The raw YAML may contain unresolved templates like {{ .locals.X }}, which YAML treats as strings.
// The locals resolver handles resolving self-references between locals.
// Returns the resolved locals and other sections (settings, vars, env) that should be available during template processing.
//
// Locals are extracted and merged in order of specificity:
// 1. Global locals (root level)
// 2. Section-specific locals (terraform, helmfile, packer sections)
//
// Section-specific locals inherit from and can override global locals.
// All resolved locals are flattened into a single map for template processing.
//
// Results are memoized in localsExtractionCache keyed by filePath. See the cache
// declaration for rationale and the deep-copy contract.
func extractLocalsFromRawYAML(atmosConfig *schema.AtmosConfiguration, yamlContent string, filePath string) (*extractLocalsResult, error) {
defer perf.Track(atmosConfig, "exec.extractLocalsFromRawYAML")()
// Fast path: result is cached for this (file path, content fingerprint)
// pair. Deep-copy on retrieval to keep the cache value immutable across
// concurrent callers.
cacheKey := localsCacheKey(filePath, yamlContent)
if raw, found := localsExtractionCache.Load(cacheKey); found {
if cached, ok := raw.(*extractLocalsResult); ok {
return cloneExtractLocalsResult(cached), nil
}
}
// Parse raw YAML to extract the structure.
// YAML treats template expressions like {{ .locals.X }} as plain strings,
// so parsing succeeds even with unresolved templates.
// Use Atmos's YAML unmarshaling which properly handles custom tags like !terraform.state
// by converting them to strings (e.g., "!terraform.state component .output").
// Create a default config if nil (UnmarshalYAMLFromFile requires non-nil config).
configToUse := atmosConfig
if configToUse == nil {
configToUse = &schema.AtmosConfiguration{}
}
rawConfig, err := u.UnmarshalYAMLFromFile[map[string]any](configToUse, yamlContent, filePath)
if err != nil {
// Provide a helpful hint if the file might contain Go template directives
// that aren't valid YAML. Files with .yaml.tmpl extension are processed
// as templates first, which allows non-YAML-valid Go template syntax.
hint := ""
if !strings.HasSuffix(filePath, u.TemplateExtension) {
hint = " (hint: if this file contains Go template directives, rename it to .yaml.tmpl)"
}
return nil, fmt.Errorf("%w: failed to parse YAML for locals extraction%s: %w", errUtils.ErrInvalidStackManifest, hint, err)
}
if rawConfig == nil {
empty := &extractLocalsResult{}
localsExtractionCache.Store(cacheKey, empty)
return cloneExtractLocalsResult(empty), nil
}
// Derive the stack name from the file path so that YAML functions like
// !terraform.state (2-arg form) can resolve their implicit stack reference.
// Previously, an empty string was passed here, which caused !terraform.state
// to fail with "stack is required" (see GitHub issue #2080).
currentStack := deriveStackNameForLocals(atmosConfig, rawConfig, filePath)
localsCtx, err := ProcessStackLocals(atmosConfig, rawConfig, filePath, currentStack)
if err != nil {
return nil, fmt.Errorf("%w: failed to process stack locals: %w", errUtils.ErrInvalidStackManifest, err)
}
result := buildLocalsResult(rawConfig, localsCtx)
// Cache the canonical result and return a deep copy so the cache remains
// the single immutable source of truth. Concurrent goroutines that race
// on the first cache miss for a given file path will both run the parse
// (cheap given the cache hit on subsequent calls), and the later Store
// silently wins — both results are identical for the same input.
localsExtractionCache.Store(cacheKey, result)
return cloneExtractLocalsResult(result), nil
}
// deriveStackNameForLocals derives the stack name from the file path and raw config
// so that YAML functions in locals (like !terraform.state) can use stack context.
// This uses the same logic as describe_locals.go (deriveStackName) to compute the
// stack name from the file path, vars section, and atmos config.
// Returns empty string if the stack name cannot be determined.
func deriveStackNameForLocals(atmosConfig *schema.AtmosConfiguration, rawConfig map[string]any, filePath string) string {
if atmosConfig == nil {
return ""
}
// Extract vars section for stack name derivation.
var varsSection map[string]any
if vs, ok := rawConfig[cfg.VarsSectionName].(map[string]any); ok {
varsSection = vs
}
// Compute relative stack file name from file path.
stackFileName := computeStackFileName(atmosConfig, filePath)
if stackFileName == "" {
return ""
}
return deriveStackName(atmosConfig, stackFileName, varsSection, rawConfig)
}
// computeStackFileName computes the relative stack file name from an absolute file path
// by stripping the stacks base path prefix and the file extension.
// This produces a name like "deploy/dev" or "orgs/acme/plat/dev/us-east-1".
func computeStackFileName(atmosConfig *schema.AtmosConfiguration, filePath string) string {
if atmosConfig == nil {
return ""
}
// Get the absolute stacks base path.
stacksBasePath := filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath)
absStacksBasePath, err := filepath.Abs(stacksBasePath)
if err != nil {
return ""
}
absFilePath, err := filepath.Abs(filePath)
if err != nil {
return ""
}
// Strip the base path prefix.
rel, err := filepath.Rel(absStacksBasePath, absFilePath)
if err != nil {
return ""
}
// Remove known stack/template suffixes (longest first to handle .yaml.tmpl correctly).
for _, suffix := range []string{
u.YamlTemplateExtension, // .yaml.tmpl
u.YmlTemplateExtension, // .yml.tmpl
u.YamlFileExtension, // .yaml
u.YmlFileExtension, // .yml
} {
if strings.HasSuffix(rel, suffix) {
rel = strings.TrimSuffix(rel, suffix)
break
}
}
return rel
}
// buildLocalsResult builds an extractLocalsResult from raw config and resolved locals context.
func buildLocalsResult(rawConfig map[string]any, localsCtx *LocalsContext) *extractLocalsResult {
result := &extractLocalsResult{
locals: localsCtx.MergeForTemplateContext(),
}
// Detect locals section presence (including empty locals).
// This allows empty locals: {} to still enable template context.
if _, ok := rawConfig[cfg.LocalsSectionName]; ok {
result.hasLocals = true
}
if localsCtx.HasTerraformLocals || localsCtx.HasHelmfileLocals || localsCtx.HasPackerLocals {
result.hasLocals = true
}
// Ensure locals map is never nil when hasLocals is true.
if result.hasLocals && result.locals == nil {
result.locals = make(map[string]any)
}
// Extract settings, vars, env sections for template context.
if settings, ok := rawConfig[cfg.SettingsSectionName].(map[string]any); ok {
result.settings = settings
}
if vars, ok := rawConfig[cfg.VarsSectionName].(map[string]any); ok {
result.vars = vars
}
if env, ok := rawConfig[cfg.EnvSectionName].(map[string]any); ok {
result.env = env
}
if versionSection, ok := rawConfig["version"].(map[string]any); ok {
if track, ok := versionSection["track"].(string); ok {
result.versionTrack = track
}
}
return result
}
// processTemplatesInSection processes Go templates in a section (settings, vars, or env) using the provided context.
// This allows sections to reference resolved locals and other processed sections.
// Returns the processed section or an error if template processing fails.
// IMPORTANT: Uses ignoreMissingTemplateValues=false so that templates referencing values not in the
// current context (like {{ .atmos_component }}) will fail, and the caller can fall back to raw values.
// This preserves those templates for later processing when the full context is available.
func processTemplatesInSection(atmosConfig *schema.AtmosConfiguration, section map[string]any, context map[string]any, filePath string) (map[string]any, error) {
defer perf.Track(atmosConfig, "exec.processTemplatesInSection")()
if len(section) == 0 {
return section, nil
}
section = processStructuredTemplateRefs(section, context).(map[string]any)
// Convert section to YAML for template processing.
yamlStr, err := u.ConvertToYAML(section)
if err != nil {
return nil, stderrors.Join(errUtils.ErrInvalidStackManifest, fmt.Errorf("failed to convert section to YAML: %w", err))
}
// Quick check: if no template markers, return as-is.
if !strings.Contains(yamlStr, "{{") {
return section, nil
}
// Process templates in the YAML string.
// Use ignoreMissingTemplateValues=false so templates with missing values fail
// (e.g., {{ .atmos_component }} when component context isn't available yet).
// The caller will fall back to raw values, preserving templates for later processing.
processed, err := ProcessTmpl(atmosConfig, filePath, yamlStr, context, false)
if err != nil {
return nil, stderrors.Join(errUtils.ErrInvalidStackManifest, fmt.Errorf("failed to process templates in section: %w", err))
}
// Parse the processed YAML back to a map.
var result map[string]any
if err := yaml.Unmarshal([]byte(processed), &result); err != nil {
return nil, stderrors.Join(errUtils.ErrInvalidStackManifest, fmt.Errorf("failed to parse processed section YAML: %w", err))
}
return result, nil
}
func processStructuredTemplateRefs(value any, context map[string]any) any {
switch typed := value.(type) {
case map[string]any:
result := make(map[string]any, len(typed))
for k, v := range typed {
result[k] = processStructuredTemplateRefs(v, context)
}
return result
case []any:
result := make([]any, len(typed))
for i, v := range typed {
result[i] = processStructuredTemplateRefs(v, context)
}
return result
case string:
ref, ok, err := atmostmpl.ExtractPlainFieldRef(typed)
if err != nil || !ok {
return typed
}
if resolved, found := atmostmpl.LookupFieldPath(context, ref.Path); found {
return resolved
}
return typed
default:
return value
}
}
// extractAndAddLocalsToContext extracts locals from YAML and adds them to the template context.
// Returns the updated context and any error encountered during locals extraction.
// Note: The "locals" key in context is reserved for file-scoped locals and will override
// any user-provided "locals" key in the import context.
// Settings, vars, and env sections are also added to the context so templates can reference them.
// For template files (.tmpl), YAML parse errors are logged and the function continues
// without locals, since template files may contain Go template syntax that isn't valid YAML
// until after template processing.
func extractAndAddLocalsToContext(
atmosConfig *schema.AtmosConfiguration,
yamlContent string,
filePath string,
relativeFilePath string,
context map[string]any,
) (map[string]any, error) {
defer perf.Track(atmosConfig, "exec.extractAndAddLocalsToContext")()
// Clone the input context so concurrent goroutines processing sibling imports
// (in processYAMLConfigFileWithContextInternal, which fans out to one goroutine
// per import while sharing mergedContext) cannot race on the file-scoped
// delete + assign below. Without the clone, the parent context was mutated
// directly, producing a data race surfaced by `go test -race` on
// TestHierarchicalImports_*. Cloning is a shallow copy: the values are shared
// references but the map header is per-goroutine, which is the only mutation
// surface inside this function.
clonedContext := make(map[string]any, len(context))
for k, v := range context {
if k == cfg.LocalsSectionName {
// Enforce file-scoped locals: drop inherited locals during the
// clone. This replaces the previous in-place delete on the shared
// parent context.
continue
}
clonedContext[k] = v
}
context = clonedContext
extractResult, localsErr := extractLocalsFromRawYAML(atmosConfig, yamlContent, filePath)
if localsErr != nil {
// For template files (.tmpl), YAML parse errors are expected since the raw content
// may contain Go template syntax that isn't valid YAML until after processing.
// Log the error and continue without locals - template processing will happen next.
if strings.HasSuffix(filePath, u.TemplateExtension) {
log.Trace("Skipping locals extraction for template file with invalid YAML", "file", relativeFilePath, "error", localsErr)
return context, nil
}
// Circular dependencies in locals are a stack misconfiguration error.
// Return a helpful error with hints on how to fix it.
if stderrors.Is(localsErr, errUtils.ErrLocalsCircularDep) {
return context, errUtils.Build(errUtils.ErrLocalsCircularDep).
WithCause(localsErr).
WithContext("file", relativeFilePath).
WithHintf("Fix the circular dependency in '%s'", relativeFilePath).
WithHint("Ensure locals don't reference each other in a cycle").
WithHintf("Use 'atmos describe locals --stack %s' to inspect locals", relativeFilePath).
WithExitCode(1).
Err()
}
return context, localsErr
}
// Only modify context if a locals section exists in the file.
// This preserves the original behavior where files without locals don't trigger
// template processing (see the len(context) > 0 check in ProcessBaseStackConfig).
// We check hasLocals instead of len(locals) to support empty locals: {} sections,
// which should still enable template context.
if !extractResult.hasLocals {
return manager.AddTemplateContext(atmosConfig, yamlContent, context, extractResult.versionTrack)
}
// context is never nil here: the clone above always allocates a fresh map
// (make returns a non-nil empty map when len(input)==0). The historical
// `if context == nil { context = make(...) }` initializer is now dead.
// Add resolved locals to the template context first.
// This allows settings/vars/env templates to reference locals.
context[cfg.LocalsSectionName] = extractResult.locals
var versionContextErr error
context, versionContextErr = manager.AddTemplateContext(atmosConfig, yamlContent, context, extractResult.versionTrack)
if versionContextErr != nil {
return context, versionContextErr
}
log.Trace("Extracted and resolved locals", "file", relativeFilePath, "count", len(extractResult.locals))
// Process templates in settings, vars, env sections using the resolved locals.
// This enables bidirectional references between locals and settings:
// locals:
// stage: dev
// settings:
// context:
// stage_from_local: '{{ .locals.stage }}' # Now resolves to "dev"
// vars:
// setting_value: '{{ .settings.context.stage_from_local }}' # Now resolves to "dev"
//
// Note: We need to process these sections AFTER locals are resolved so they can reference .locals,
// but BEFORE adding them to the context so vars can reference the resolved settings values.
// Seed section context with any external import context so that settings/vars/env
// templates referencing import-provided values can resolve during section processing.
// Locals are always overridden to ensure file-scoped locality.
localsOnlyContext := map[string]any{}
for k, v := range context {
localsOnlyContext[k] = v
}
localsOnlyContext[cfg.LocalsSectionName] = extractResult.locals
// Process templates in settings if it contains template expressions.
if extractResult.settings != nil {
processedSettings, err := processTemplatesInSection(atmosConfig, extractResult.settings, localsOnlyContext, relativeFilePath)
if err != nil {
log.Debug("Failed to process templates in settings section", "file", relativeFilePath, "error", err)
// Fall back to raw settings on error.
context[cfg.SettingsSectionName] = extractResult.settings
} else {
context[cfg.SettingsSectionName] = processedSettings
}
}
if extractResult.vars != nil {
// For vars, we need locals, external context, and processed settings available.
varsContext := map[string]any{}
for k, v := range localsOnlyContext {
varsContext[k] = v
}
if processedSettings, ok := context[cfg.SettingsSectionName].(map[string]any); ok {
varsContext[cfg.SettingsSectionName] = processedSettings
}
processedVars, err := processTemplatesInSection(atmosConfig, extractResult.vars, varsContext, relativeFilePath)
if err != nil {
log.Debug("Failed to process templates in vars section", "file", relativeFilePath, "error", err)
// Fall back to raw vars on error.
context[cfg.VarsSectionName] = extractResult.vars
} else {
context[cfg.VarsSectionName] = processedVars
}
}
if extractResult.env != nil {
// For env, we need locals, external context, processed settings, and processed vars.
envContext := map[string]any{}
for k, v := range localsOnlyContext {
envContext[k] = v
}
if processedSettings, ok := context[cfg.SettingsSectionName].(map[string]any); ok {
envContext[cfg.SettingsSectionName] = processedSettings
}
if processedVars, ok := context[cfg.VarsSectionName].(map[string]any); ok {
envContext[cfg.VarsSectionName] = processedVars
}
processedEnv, err := processTemplatesInSection(atmosConfig, extractResult.env, envContext, relativeFilePath)
if err != nil {
log.Debug("Failed to process templates in env section", "file", relativeFilePath, "error", err)
// Fall back to raw env on error.
context[cfg.EnvSectionName] = extractResult.env
} else {
context[cfg.EnvSectionName] = processedEnv
}
}
return context, nil
}
// stackProcessResult holds the result of processing a single stack in parallel.
type stackProcessResult struct {
index int
stackFileName string
yamlConfig string
finalConfig map[string]any
stackConfig map[string]any
importsConfig map[string]map[string]any
uniqueImports []string
mergeContext *m.MergeContext
err error
}
// ProcessYAMLConfigFiles takes a list of paths to stack manifests, processes and deep-merges all imports, and returns a list of stack configs.
func ProcessYAMLConfigFiles(
atmosConfig *schema.AtmosConfiguration,
stacksBasePath string,
terraformComponentsBasePath string,
helmfileComponentsBasePath string,
packerComponentsBasePath string,
ansibleComponentsBasePath string,
filePaths []string,
processStackDeps bool,
processComponentDeps bool,
ignoreMissingFiles bool,
) (
[]string,
map[string]any,
map[string]map[string]any,
error,
) {
defer perf.Track(atmosConfig, "exec.ProcessYAMLConfigFiles")()
count := len(filePaths)
listResult := make([]string, count)
mapResult := make(map[string]any, count)
rawStackConfigs := make(map[string]map[string]any, count)
// Create channel for results - no locks needed with channels.
results := make(chan stackProcessResult, count)
var wg sync.WaitGroup
wg.Add(count)
for i, filePath := range filePaths {
go func(i int, p string) {
defer wg.Done()
stackBasePath := stacksBasePath
if len(stackBasePath) < 1 {
stackBasePath = filepath.Dir(p)
}
stackFileName := strings.TrimSuffix(
strings.TrimSuffix(
u.TrimBasePathFromPath(stackBasePath+"/", p),
u.DefaultStackConfigFileExtension,
),
".yml",
)
// Each goroutine gets its own merge context to avoid data races.
// For single-file operations (like describe component), use the
// SetLastMergeContext/GetLastMergeContext mechanism instead.
mergeContext := m.NewMergeContext()
if atmosConfig != nil && atmosConfig.TrackProvenance {
mergeContext.EnableProvenance()
}
processingResult, mergeContext, err := ProcessYAMLConfigFileWithContext(
atmosConfig,
stackBasePath,
p,
map[string]map[string]any{},
nil,
ignoreMissingFiles,
false,
atmosConfig != nil && atmosConfig.Templates.Settings.IgnoreMissingTemplateValues,
false,
map[string]any{},
map[string]any{},
map[string]any{},
map[string]any{},
"",
mergeContext,
)
if err != nil {
results <- stackProcessResult{index: i, err: err}
return
}
if mergeContext != nil {
if len(mergeContext.ImportChain) > 0 {
log.Trace("After processing file, merge context has import chain", "file", stackFileName, "import_chain_length", len(mergeContext.ImportChain), "import_chain", mergeContext.ImportChain)
} else {
log.Trace("After processing file, merge context has empty import chain", "file", stackFileName)
}
}
var imports []string
for k := range processingResult.ImportsConfig {
imports = append(imports, k)
}
uniqueImports := u.UniqueStrings(imports)
sort.Strings(uniqueImports)
componentStackMap := map[string]map[string][]string{}
finalConfig, err := ProcessStackConfig(
atmosConfig,
stackBasePath,
terraformComponentsBasePath,
helmfileComponentsBasePath,
packerComponentsBasePath,
ansibleComponentsBasePath,
p,
processingResult.DeepMergedConfig,
processStackDeps,
processComponentDeps,
"",
componentStackMap,
processingResult.ImportsConfig,
true,
)
if err != nil {
results <- stackProcessResult{index: i, err: err}
return
}
finalConfig["imports"] = uniqueImports
yamlConfig, err := u.ConvertToYAML(finalConfig)
if err != nil {
results <- stackProcessResult{index: i, err: err}
return
}
// Send result via channel (lock-free).
results <- stackProcessResult{
index: i,
stackFileName: stackFileName,
yamlConfig: yamlConfig,
finalConfig: finalConfig,
stackConfig: processingResult.StackConfig,
importsConfig: processingResult.ImportsConfig,
uniqueImports: uniqueImports,
mergeContext: mergeContext,
err: nil,
}
}(i, filePath)
}
// Close results channel when all goroutines complete.
go func() {
wg.Wait()
close(results)
}()
// Collect all results from channel (no lock contention).
for result := range results {
if result.err != nil {
return nil, nil, nil, result.err
}
// Store merge context for this stack file if provenance tracking is enabled.
if atmosConfig != nil && atmosConfig.TrackProvenance && result.mergeContext != nil && result.mergeContext.IsProvenanceEnabled() {
SetMergeContextForStack(result.stackFileName, result.mergeContext)
// Also set as last merge context for backward compatibility (note: may be overwritten by other results)
SetLastMergeContext(result.mergeContext)
}
listResult[result.index] = result.yamlConfig
mapResult[result.stackFileName] = result.finalConfig
rawStackConfigs[result.stackFileName] = map[string]any{
"stack": result.stackConfig,
"imports": result.importsConfig,
"import_files": result.uniqueImports,
}
}
return listResult, mapResult, rawStackConfigs, nil
}
// ProcessYAMLConfigFile takes a path to a YAML stack manifest,
// recursively processes and deep-merges all the imports,
// and returns the final stack config.
func ProcessYAMLConfigFile(
atmosConfig *schema.AtmosConfiguration,
basePath string,
filePath string,
importsConfig map[string]map[string]any,
context map[string]any,
ignoreMissingFiles bool,
skipTemplatesProcessingInImports bool,
ignoreMissingTemplateValues bool,
skipIfMissing bool,
parentTerraformOverridesInline map[string]any,
parentTerraformOverridesImports map[string]any,
parentHelmfileOverridesInline map[string]any,
parentHelmfileOverridesImports map[string]any,
atmosManifestJsonSchemaFilePath string,
) (*schema.StackManifestProcessingResult, error) {
defer perf.Track(atmosConfig, "exec.ProcessYAMLConfigFile")()
// Create merge context for single-file operations
var mergeContext *m.MergeContext
if atmosConfig != nil && atmosConfig.TrackProvenance {
mergeContext = m.NewMergeContext()
mergeContext.EnableProvenance()
}
// Call the context-aware version
result, mergeContext, err := ProcessYAMLConfigFileWithContext(
atmosConfig,
basePath,
filePath,
importsConfig,
context,
ignoreMissingFiles,
skipTemplatesProcessingInImports,
ignoreMissingTemplateValues,
skipIfMissing,
parentTerraformOverridesInline,
parentTerraformOverridesImports,
parentHelmfileOverridesInline,
parentHelmfileOverridesImports,
atmosManifestJsonSchemaFilePath,
mergeContext,
)
// Store merge context if provenance tracking is enabled (for single-file operations like describe component)
if atmosConfig != nil && atmosConfig.TrackProvenance && mergeContext != nil && mergeContext.IsProvenanceEnabled() {
SetLastMergeContext(mergeContext)
}
return result, err
}
// ProcessYAMLConfigFileWithContext takes a path to a YAML stack manifest,
// recursively processes and deep-merges all the imports with context tracking,
// and returns the final stack config.
func ProcessYAMLConfigFileWithContext(
atmosConfig *schema.AtmosConfiguration,
basePath string,
filePath string,
importsConfig map[string]map[string]any,
context map[string]any,
ignoreMissingFiles bool,
skipTemplatesProcessingInImports bool,
ignoreMissingTemplateValues bool,
skipIfMissing bool,
parentTerraformOverridesInline map[string]any,
parentTerraformOverridesImports map[string]any,
parentHelmfileOverridesInline map[string]any,
parentHelmfileOverridesImports map[string]any,
atmosManifestJsonSchemaFilePath string,
mergeContext *m.MergeContext,
) (*schema.StackManifestProcessingResult, *m.MergeContext, error) {
defer perf.Track(atmosConfig, "exec.ProcessYAMLConfigFileWithContext")()
return processYAMLConfigFileWithContextInternal(
atmosConfig,
basePath,
filePath,
basePath,
schema.StackImportNestedImportsLocal,
importsConfig,
context,
// Top-level call: no accumulated import-path context yet. It is built up
// from earlier imports as the manifest's import list is processed.
nil,
ignoreMissingFiles,
skipTemplatesProcessingInImports,
ignoreMissingTemplateValues,
skipIfMissing,
parentTerraformOverridesInline,
parentTerraformOverridesImports,
parentHelmfileOverridesInline,
parentHelmfileOverridesImports,
atmosManifestJsonSchemaFilePath,
mergeContext,
)
}
// importFileResult holds the result of processing a single import file in parallel.
type importFileResult struct {
index int
importFile string
yamlConfig map[string]any
yamlConfigRaw map[string]any
terraformOverridesInline map[string]any
terraformOverridesImports map[string]any
helmfileOverridesInline map[string]any
helmfileOverridesImports map[string]any
importRelativePathWithoutExt string
mergeContext *m.MergeContext
err error
}
// jsonPointerToPositionKey converts a JSON Pointer (RFC 6901, e.g.
// "/components/terraform/0/vars") as returned by
// jsonschema.BasicError.InstanceLocation into the dot/bracket path format
// u.PositionMap keys use (built via u.AppendJSONPathKey/AppendJSONPathIndex),
// so a position lookup by path succeeds.
func jsonPointerToPositionKey(pointer string) string {
if pointer == "" {
return ""
}
segments := strings.Split(strings.TrimPrefix(pointer, "/"), "/")
path := ""
for _, seg := range segments {
seg = strings.ReplaceAll(seg, "~1", "/")
seg = strings.ReplaceAll(seg, "~0", "~")
if idx, err := strconv.Atoi(seg); err == nil {
path = u.AppendJSONPathIndex(path, idx)
continue
}
path = u.AppendJSONPathKey(path, seg)
}
return path
}
// isSchemaBranchWrapperMessage reports whether a jsonschema.BasicError.Error
// is a structural "one of these sub-schemas should have matched" wrapper
// (from oneOf/anyOf/$ref indirection) rather than an actionable leaf
// violation: oneOf/anyOf constructs report every failed candidate branch, so
// a single mistake (e.g. a wrong type) can otherwise produce many redundant
// lines at the same location; dropping wrapper messages keeps only the
// specific ones (e.g. "expected object, but got string").
func isSchemaBranchWrapperMessage(msg string) bool {
return strings.HasPrefix(msg, "doesn't validate with") ||
msg == "oneOf failed" ||
msg == "anyOf failed"
}
// formatManifestSchemaValidationErrors renders a jsonschema.ValidationError as
// a Markdown list of GCC-style diagnostic lines ("file:line:col: error:
// path: message" per item), matching the convention `atmos validate
// editorconfig --format=gcc` already uses, instead of a raw BasicOutput JSON
// dump. BasicOutput's first entry is always a generic "doesn't validate with
// <schema>" wrapper around the whole document (empty KeywordLocation);
// wrapper entries throughout (including nested oneOf/anyOf branch failures)
// are dropped in favor of the specific leaf violations.
//
// Markdown list syntax (not plain lines) is deliberate: the CLI's error box
// renders this as CommonMark, which treats a lone "\n" between plain
// paragraph text as a soft break (collapsed to a space) rather than a line
// break -- only list items reliably keep one diagnostic per rendered line.
// The leading "\n" pushes every item, including the first, onto its own
// line rather than running into the box's own "Error:" label inline.
func formatManifestSchemaValidationErrors(relativeFilePath string, e *jsonschema.ValidationError, positions u.PositionMap) string {
items := collectManifestSchemaErrorItems(e, positions)
if len(items) == 0 {
return fmt.Sprintf("\n- %s: error: %s", relativeFilePath, e.Error())
}
rendered := renderManifestSchemaErrorItems(relativeFilePath, items)
return "\n" + strings.Join(rendered, "\n")
}
// manifestSchemaTypeAlternatives coalesces the distinct expected types that
// failed a shared oneOf/anyOf branch for the same instance location and
// actual value, so they render as one "expected X or Y, but got Z" finding
// instead of one line per failed branch.
type manifestSchemaTypeAlternatives struct {
path string
position u.Position
got string
expected []string
expectedSet map[string]struct{}
}
// manifestSchemaErrorItem is one candidate finding collected from a
// jsonschema.ValidationError's BasicOutput -- either a concrete leaf message,
// or a coalesced type-alternatives entry.
type manifestSchemaErrorItem struct {
path string
position u.Position
message string
types *manifestSchemaTypeAlternatives
}
// collectManifestSchemaErrorItems walks a jsonschema.ValidationError's
// BasicOutput and builds one item per actionable leaf finding, coalescing
// oneOf/anyOf type-mismatch branches for the same instance location and
// actual value into a single manifestSchemaTypeAlternatives entry.
func collectManifestSchemaErrorItems(e *jsonschema.ValidationError, positions u.PositionMap) []manifestSchemaErrorItem {
items := make([]manifestSchemaErrorItem, 0)
alternatives := make(map[string]*manifestSchemaTypeAlternatives)
for _, basicErr := range e.BasicOutput().Errors {
if basicErr.KeywordLocation == "" || isSchemaBranchWrapperMessage(basicErr.Error) {
continue
}
path := jsonPointerToPositionKey(basicErr.InstanceLocation)
if path == "" {
path = "(root)"
}
pos := u.GetYAMLPosition(positions, jsonPointerToPositionKey(basicErr.InstanceLocation))
if expected, got, ok := schemaTypeAlternative(basicErr.Error); ok {
key := path + "\x00" + got
alternative := alternatives[key]
if alternative == nil {
alternative = &manifestSchemaTypeAlternatives{
path: path, position: pos, got: got,
expectedSet: make(map[string]struct{}),
}
alternatives[key] = alternative
items = append(items, manifestSchemaErrorItem{types: alternative})
}
if _, seen := alternative.expectedSet[expected]; !seen {
alternative.expectedSet[expected] = struct{}{}
alternative.expected = append(alternative.expected, expected)
}
continue
}
items = append(items, manifestSchemaErrorItem{path: path, position: pos, message: manifestSchemaErrorMessage(basicErr.Error)})
}
return items
}
// manifestSchemaItemHasDescendant reports whether some other item's path is a
// nested child of path (a JSON object/array descendant), which makes path's
// own type-mismatch finding a redundant cascade rather than the actionable
// error.
func manifestSchemaItemHasDescendant(items []manifestSchemaErrorItem, current int, path string) bool {
for index, candidate := range items {
if index == current {
continue
}
candidatePath := candidate.path
if candidate.types != nil {
candidatePath = candidate.types.path
}
if strings.HasPrefix(candidatePath, path+".") || strings.HasPrefix(candidatePath, path+"[") {
return true
}
}
return false
}
// manifestSchemaItemHasSpecificFinding reports whether some other item names
// exactly path with a specific (non-type-alternative) finding, which makes
// path's own type-mismatch finding a redundant cascade.
func manifestSchemaItemHasSpecificFinding(items []manifestSchemaErrorItem, current int, path string) bool {
for index, candidate := range items {
if index != current && candidate.types == nil && candidate.path == path {
return true
}
}
return false
}
// renderManifestSchemaErrorItems renders each collected item as a GCC-style
// diagnostic line, dropping type-mismatch items that are cascades of a more
// specific sibling finding.