Debian Codegraph @

api/internal/target/kusttarget.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package target
5
6 import (
7 "encoding/json"
8 "fmt"
9 "os"
10 "strings"
11
12 "sigs.k8s.io/kustomize/api/ifc"
13 "sigs.k8s.io/kustomize/api/internal/accumulator"
14 "sigs.k8s.io/kustomize/api/internal/builtins"
15 "sigs.k8s.io/kustomize/api/internal/kusterr"
16 load "sigs.k8s.io/kustomize/api/internal/loader"
17 "sigs.k8s.io/kustomize/api/internal/plugins/builtinconfig"
18 "sigs.k8s.io/kustomize/api/internal/plugins/builtinhelpers"
19 "sigs.k8s.io/kustomize/api/internal/plugins/loader"
20 "sigs.k8s.io/kustomize/api/internal/utils"
21 "sigs.k8s.io/kustomize/api/konfig"
22 "sigs.k8s.io/kustomize/api/resmap"
23 "sigs.k8s.io/kustomize/api/resource"
24 "sigs.k8s.io/kustomize/api/types"
25 "sigs.k8s.io/kustomize/kyaml/errors"
26 "sigs.k8s.io/kustomize/kyaml/openapi"
27 "sigs.k8s.io/yaml"
28 )
29
30 // KustTarget encapsulates the entirety of a kustomization build.
31 type KustTarget struct {
32 kustomization *types.Kustomization
33 kustFileName string
34 ldr ifc.Loader
35 validator ifc.Validator
36 rFactory *resmap.Factory
37 pLdr *loader.Loader
38 origin *resource.Origin
39 helmRootNamespace string // namespace inherited from parent kustomization for HelmCharts
40 }
41
42 // NewKustTarget returns a new instance of KustTarget.
43 func NewKustTarget(
44 ldr ifc.Loader,
45 validator ifc.Validator,
46 rFactory *resmap.Factory,
47 pLdr *loader.Loader) *KustTarget {
48 return &KustTarget{
49 ldr: ldr,
50 validator: validator,
51 rFactory: rFactory,
52 pLdr: pLdr.LoaderWithWorkingDir(ldr.Root()),
53 }
54 }
55
56 // Load attempts to load the target's kustomization file.
57 func (kt *KustTarget) Load() error {
58 content, kustFileName, err := LoadKustFile(kt.ldr)
59 if err != nil {
60 return err
61 }
62
63 var k types.Kustomization
64 if err := k.Unmarshal(content); err != nil {
65 return err
66 }
67
68 // show warning message when using deprecated fields.
69 if warningMessages := k.CheckDeprecatedFields(); warningMessages != nil {
70 for _, msg := range *warningMessages {
71 fmt.Fprintf(os.Stderr, "%v\n", msg)
72 }
73 }
74
75 k.FixKustomization()
76
77 // check that Kustomization is empty
78 if err := k.CheckEmpty(); err != nil {
79 return err
80 }
81
82 errs := k.EnforceFields()
83 if len(errs) > 0 {
84 return fmt.Errorf(
85 "Failed to read kustomization file under %s:\n"+
86 strings.Join(errs, "\n"), kt.ldr.Root())
87 }
88 kt.kustomization = &k
89 kt.kustFileName = kustFileName
90 return nil
91 }
92
93 // Kustomization returns a copy of the immutable, internal kustomization object.
94 func (kt *KustTarget) Kustomization() types.Kustomization {
95 var result types.Kustomization
96 b, _ := json.Marshal(*kt.kustomization)
97 json.Unmarshal(b, &result)
98 return result
99 }
100
101 func LoadKustFile(ldr ifc.Loader) ([]byte, string, error) {
102 var content []byte
103 match := 0
104 var kustFileName string
105 for _, kf := range konfig.RecognizedKustomizationFileNames() {
106 c, err := ldr.Load(kf)
107 if err == nil {
108 match += 1
109 content = c
110 kustFileName = kf
111 }
112 }
113 switch match {
114 case 0:
115 return nil, "", NewErrMissingKustomization(ldr.Root())
116 case 1:
117 return content, kustFileName, nil
118 default:
119 return nil, "", fmt.Errorf(
120 "Found multiple kustomization files under: %s\n", ldr.Root())
121 }
122 }
123
124 // MakeCustomizedResMap creates a fully customized ResMap
125 // per the instructions contained in its kustomization instance.
126 func (kt *KustTarget) MakeCustomizedResMap() (resmap.ResMap, error) {
127 return kt.makeCustomizedResMap()
128 }
129
130 func (kt *KustTarget) makeCustomizedResMap() (resmap.ResMap, error) {
131 var origin *resource.Origin
132 if len(kt.kustomization.BuildMetadata) != 0 {
133 origin = &resource.Origin{}
134 }
135 kt.origin = origin
136 ra, err := kt.AccumulateTarget()
137 if err != nil {
138 return nil, err
139 }
140
141 // The following steps must be done last, not as part of
142 // the recursion implicit in AccumulateTarget.
143
144 err = kt.addHashesToNames(ra)
145 if err != nil {
146 return nil, err
147 }
148
149 // Given that names have changed (prefixs/suffixes added),
150 // fix all the back references to those names.
151 err = ra.FixBackReferences()
152 if err != nil {
153 return nil, err
154 }
155
156 // With all the back references fixed, it's OK to resolve Vars.
157 err = ra.ResolveVars()
158 if err != nil {
159 return nil, err
160 }
161
162 err = kt.IgnoreLocal(ra)
163 if err != nil {
164 return nil, err
165 }
166
167 return ra.ResMap(), nil
168 }
169
170 func (kt *KustTarget) addHashesToNames(
171 ra *accumulator.ResAccumulator) error {
172 p := builtins.NewHashTransformerPlugin()
173 err := kt.configureBuiltinPlugin(p, nil, builtinhelpers.HashTransformer)
174 if err != nil {
175 return err
176 }
177 return ra.Transform(p)
178 }
179
180 // AccumulateTarget returns a new ResAccumulator,
181 // holding customized resources and the data/rules used
182 // to do so. The name back references and vars are
183 // not yet fixed.
184 // The origin parameter is used through the recursive calls
185 // to annotate each resource with information about where
186 // the resource came from, e.g. the file and/or the repository
187 // it originated from.
188 // As an entrypoint, one can pass an empty resource.Origin object to
189 // AccumulateTarget. As AccumulateTarget moves recursively
190 // through kustomization directories, it updates `origin.path`
191 // accordingly. When a remote base is found, it updates `origin.repo`
192 // and `origin.ref` accordingly.
193 func (kt *KustTarget) AccumulateTarget() (
194 ra *accumulator.ResAccumulator, err error) {
195 return kt.accumulateTarget(accumulator.MakeEmptyAccumulator())
196 }
197
198 // ra should be empty when this KustTarget is a Kustomization, or the ra of the parent if this KustTarget is a Component
199 // (or empty if the Component does not have a parent).
200 func (kt *KustTarget) accumulateTarget(ra *accumulator.ResAccumulator) (
201 resRa *accumulator.ResAccumulator, err error) {
202 ra, err = kt.accumulateResources(ra, kt.kustomization.Resources)
203 if err != nil {
204 return nil, errors.WrapPrefixf(err, "accumulating resources")
205 }
206 tConfig, err := builtinconfig.MakeTransformerConfig(
207 kt.ldr, kt.kustomization.Configurations)
208 if err != nil {
209 return nil, err
210 }
211 err = ra.MergeConfig(tConfig)
212 if err != nil {
213 return nil, errors.WrapPrefixf(
214 err, "merging config %v", tConfig)
215 }
216 crdTc, err := accumulator.LoadConfigFromCRDs(kt.ldr, kt.kustomization.Crds)
217 if err != nil {
218 return nil, errors.WrapPrefixf(
219 err, "loading CRDs %v", kt.kustomization.Crds)
220 }
221 err = ra.MergeConfig(crdTc)
222 if err != nil {
223 return nil, errors.WrapPrefixf(
224 err, "merging CRDs %v", crdTc)
225 }
226 err = kt.runGenerators(ra)
227 if err != nil {
228 return nil, err
229 }
230
231 // components are expected to execute after reading resources and adding generators ,before applying transformers and validation.
232 // https://github.com/kubernetes-sigs/kustomize/pull/5170#discussion_r1212101287
233 ra, err = kt.accumulateComponents(ra, kt.kustomization.Components)
234 if err != nil {
235 return nil, errors.WrapPrefixf(err, "accumulating components")
236 }
237
238 err = kt.runTransformers(ra)
239 if err != nil {
240 return nil, err
241 }
242 err = kt.runValidators(ra)
243 if err != nil {
244 return nil, err
245 }
246 err = ra.MergeVars(kt.kustomization.Vars)
247 if err != nil {
248 return nil, errors.WrapPrefixf(
249 err, "merging vars %v", kt.kustomization.Vars)
250 }
251 return ra, nil
252 }
253
254 // IgnoreLocal drops the local resource by checking the annotation "config.kubernetes.io/local-config".
255 func (kt *KustTarget) IgnoreLocal(ra *accumulator.ResAccumulator) error {
256 rf := kt.rFactory.RF()
257 if rf.IncludeLocalConfigs {
258 return nil
259 }
260 remainRes, err := rf.DropLocalNodes(ra.ResMap().ToRNodeSlice())
261 if err != nil {
262 return err
263 }
264 return ra.Intersection(kt.rFactory.FromResourceSlice(remainRes))
265 }
266
267 func (kt *KustTarget) runGenerators(
268 ra *accumulator.ResAccumulator) error {
269 var generators []*resmap.GeneratorWithProperties
270 gs, err := kt.configureBuiltinGenerators()
271 if err != nil {
272 return err
273 }
274 generators = append(generators, gs...)
275
276 gs, err = kt.configureExternalGenerators()
277 if err != nil {
278 return errors.WrapPrefixf(err, "loading generator plugins")
279 }
280 generators = append(generators, gs...)
281 for i, g := range generators {
282 resMap, err := g.Generate()
283 if err != nil {
284 return err
285 }
286 if resMap != nil {
287 err = resMap.AddOriginAnnotation(generators[i].Origin)
288 if err != nil {
289 return errors.WrapPrefixf(err, "adding origin annotations for generator %v", g)
290 }
291 }
292 err = ra.AbsorbAll(resMap)
293 if err != nil {
294 return errors.WrapPrefixf(err, "merging from generator %v", g)
295 }
296 }
297 return nil
298 }
299
300 func (kt *KustTarget) configureExternalGenerators() (
301 []*resmap.GeneratorWithProperties, error) {
302 ra := accumulator.MakeEmptyAccumulator()
303 var generatorPaths []string
304 for _, p := range kt.kustomization.Generators {
305 // handle inline generators
306 rm, err := kt.rFactory.NewResMapFromBytes([]byte(p))
307 if err != nil {
308 // not an inline config
309 generatorPaths = append(generatorPaths, p)
310 continue
311 }
312 // inline config, track the origin
313 if kt.origin != nil {
314 resources := rm.Resources()
315 for _, r := range resources {
316 r.SetOrigin(kt.origin.Append(kt.kustFileName))
317 rm.Replace(r)
318 }
319 }
320 if err = ra.AppendAll(rm); err != nil {
321 return nil, errors.WrapPrefixf(err, "configuring external generator")
322 }
323 }
324 ra, err := kt.accumulateResources(ra, generatorPaths)
325 if err != nil {
326 return nil, err
327 }
328 return kt.pLdr.LoadGenerators(kt.ldr, kt.validator, ra.ResMap())
329 }
330
331 func (kt *KustTarget) runTransformers(ra *accumulator.ResAccumulator) error {
332 var r []*resmap.TransformerWithProperties
333 tConfig := ra.GetTransformerConfig()
334 lts, err := kt.configureBuiltinTransformers(tConfig)
335 if err != nil {
336 return err
337 }
338 r = append(r, lts...)
339 lts, err = kt.configureExternalTransformers(kt.kustomization.Transformers)
340 if err != nil {
341 return err
342 }
343 r = append(r, lts...)
344 return ra.Transform(newMultiTransformer(r))
345 }
346
347 func (kt *KustTarget) configureExternalTransformers(transformers []string) ([]*resmap.TransformerWithProperties, error) {
348 ra := accumulator.MakeEmptyAccumulator()
349 var transformerPaths []string
350 for _, p := range transformers {
351 // handle inline transformers
352 rm, err := kt.rFactory.NewResMapFromBytes([]byte(p))
353 if err != nil {
354 // not an inline config
355 transformerPaths = append(transformerPaths, p)
356 continue
357 }
358 // inline config, track the origin
359 if kt.origin != nil {
360 resources := rm.Resources()
361 for _, r := range resources {
362 r.SetOrigin(kt.origin.Append(kt.kustFileName))
363 rm.Replace(r)
364 }
365 }
366
367 if err = ra.AppendAll(rm); err != nil {
368 return nil, errors.WrapPrefixf(err, "configuring external transformer")
369 }
370 }
371 ra, err := kt.accumulateResources(ra, transformerPaths)
372 if err != nil {
373 return nil, err
374 }
375 return kt.pLdr.LoadTransformers(kt.ldr, kt.validator, ra.ResMap())
376 }
377
378 func (kt *KustTarget) runValidators(ra *accumulator.ResAccumulator) error {
379 validators, err := kt.configureExternalTransformers(kt.kustomization.Validators)
380 if err != nil {
381 return err
382 }
383 for _, v := range validators {
384 // Validators shouldn't modify the resource map
385 orignal := ra.ResMap().DeepCopy()
386 err = v.Transform(ra.ResMap())
387 if err != nil {
388 return err
389 }
390 newMap := ra.ResMap().DeepCopy()
391 if err = kt.removeValidatedByLabel(newMap); err != nil {
392 return err
393 }
394 if err = orignal.ErrorIfNotEqualSets(newMap); err != nil {
395 return fmt.Errorf("validator shouldn't modify the resource map: %v", err)
396 }
397 }
398 return nil
399 }
400
401 func (kt *KustTarget) removeValidatedByLabel(rm resmap.ResMap) error {
402 resources := rm.Resources()
403 for _, r := range resources {
404 labels := r.GetLabels()
405 if _, found := labels[konfig.ValidatedByLabelKey]; !found {
406 continue
407 }
408 delete(labels, konfig.ValidatedByLabelKey)
409 if err := r.SetLabels(labels); err != nil {
410 return err
411 }
412 }
413 return nil
414 }
415
416 // accumulateResources fills the given resourceAccumulator
417 // with resources read from the given list of paths.
418 func (kt *KustTarget) accumulateResources(
419 ra *accumulator.ResAccumulator, paths []string) (*accumulator.ResAccumulator, error) {
420 for _, path := range paths {
421 // try loading resource as file then as base (directory or git repository)
422 if errF := kt.accumulateFile(ra, path); errF != nil {
423 // not much we can do if the error is an HTTP error so we bail out
424 if errors.Is(errF, load.ErrHTTP) {
425 return nil, errF
426 }
427 ldr, err := kt.ldr.New(path)
428 if err != nil {
429 // If accumulateFile found malformed YAML and there was a failure
430 // loading the resource as a base, then the resource is likely a
431 // file. The loader failure message is unnecessary, and could be
432 // confusing. Report only the file load error.
433 //
434 // However, a loader timeout implies there is a git repo at the
435 // path. In that case, both errors could be important.
436 if kusterr.IsMalformedYAMLError(errF) && !utils.IsErrTimeout(err) {
437 return nil, errF
438 }
439 return nil, errors.WrapPrefixf(
440 err, "accumulation err='%s'", errF.Error())
441 }
442 // store the origin, we'll need it later
443 origin := kt.origin.Copy()
444 if kt.origin != nil {
445 kt.origin = kt.origin.Append(path)
446 ra, err = kt.accumulateDirectory(ra, ldr, false)
447 // after we are done recursing through the directory, reset the origin
448 kt.origin = &origin
449 } else {
450 ra, err = kt.accumulateDirectory(ra, ldr, false)
451 }
452 if err != nil {
453 return nil, errors.WrapPrefixf(
454 err, "accumulation err='%s'", errF.Error())
455 }
456 }
457 }
458 return ra, nil
459 }
460
461 // accumulateComponents fills the given resourceAccumulator
462 // with resources read from the given list of paths.
463 func (kt *KustTarget) accumulateComponents(
464 ra *accumulator.ResAccumulator, paths []string) (*accumulator.ResAccumulator, error) {
465 for _, path := range paths {
466 // Components always refer to directories
467 ldr, errL := kt.ldr.New(path)
468 if errL != nil {
469 return nil, fmt.Errorf("loader.New %q", errL)
470 }
471 var errD error
472 // store the origin, we'll need it later
473 origin := kt.origin.Copy()
474 if kt.origin != nil {
475 kt.origin = kt.origin.Append(path)
476 ra, errD = kt.accumulateDirectory(ra, ldr, true)
477 // after we are done recursing through the directory, reset the origin
478 kt.origin = &origin
479 } else {
480 ra, errD = kt.accumulateDirectory(ra, ldr, true)
481 }
482 if errD != nil {
483 return nil, fmt.Errorf("accumulateDirectory: %q", errD)
484 }
485 }
486 return ra, nil
487 }
488
489 func (kt *KustTarget) accumulateDirectory(
490 ra *accumulator.ResAccumulator, ldr ifc.Loader, isComponent bool) (*accumulator.ResAccumulator, error) {
491 defer ldr.Cleanup()
492 subKt := NewKustTarget(ldr, kt.validator, kt.rFactory, kt.pLdr)
493 err := subKt.Load()
494 if err != nil {
495 return nil, errors.WrapPrefixf(
496 err, "couldn't make target for path '%s'", ldr.Root())
497 }
498 subKt.kustomization.BuildMetadata = kt.kustomization.BuildMetadata
499 subKt.origin = kt.origin
500 // Propagate namespace to child kustomization's helmRootNamespace for HelmCharts
501 // This ensures Helm charts in base kustomizations inherit namespace from overlays
502 // without affecting other transformers like patches
503 // Fixes https://github.com/kubernetes-sigs/kustomize/issues/6031
504 // Fixes https://github.com/kubernetes-sigs/kustomize/issues/6027
505 if kt.kustomization.Namespace != "" {
506 subKt.helmRootNamespace = kt.kustomization.Namespace
507 } else if kt.helmRootNamespace != "" {
508 subKt.helmRootNamespace = kt.helmRootNamespace
509 }
510 var bytes []byte
511 if openApiPath, exists := subKt.Kustomization().OpenAPI["path"]; exists {
512 bytes, err = ldr.Load(openApiPath)
513 if err != nil {
514 return nil, err
515 }
516 }
517 err = openapi.SetSchema(subKt.Kustomization().OpenAPI, bytes, false)
518 if err != nil {
519 return nil, err
520 }
521 if isComponent && subKt.kustomization.Kind != types.ComponentKind {
522 return nil, fmt.Errorf(
523 "expected kind '%s' for path '%s' but got '%s'", types.ComponentKind, ldr.Root(), subKt.kustomization.Kind)
524 } else if !isComponent && subKt.kustomization.Kind == types.ComponentKind {
525 return nil, fmt.Errorf(
526 "expected kind != '%s' for path '%s'", types.ComponentKind, ldr.Root())
527 }
528
529 var subRa *accumulator.ResAccumulator
530 if isComponent {
531 // Components don't create a new accumulator: the kustomization directives are added to the current accumulator
532 subRa, err = subKt.accumulateTarget(ra)
533 ra = accumulator.MakeEmptyAccumulator()
534 } else {
535 // Child Kustomizations create a new accumulator which resolves their kustomization directives, which will later
536 // be merged into the current accumulator.
537 subRa, err = subKt.AccumulateTarget()
538 }
539 if err != nil {
540 return nil, errors.WrapPrefixf(
541 err, "recursed accumulation of path '%s'", ldr.Root())
542 }
543 err = ra.MergeAccumulator(subRa)
544 if err != nil {
545 return nil, errors.WrapPrefixf(
546 err, "recursed merging from path '%s'", ldr.Root())
547 }
548 return ra, nil
549 }
550
551 func (kt *KustTarget) accumulateFile(
552 ra *accumulator.ResAccumulator, path string) error {
553 resources, err := kt.rFactory.FromFile(kt.ldr, path)
554 if err != nil {
555 return errors.WrapPrefixf(err, "accumulating resources from '%s'", path)
556 }
557 if kt.origin != nil {
558 originAnno, err := kt.origin.Append(path).String()
559 if err != nil {
560 return errors.WrapPrefixf(err, "cannot add path annotation for '%s'", path)
561 }
562 err = resources.AnnotateAll(utils.OriginAnnotationKey, originAnno)
563 if err != nil || originAnno == "" {
564 return errors.WrapPrefixf(err, "cannot add path annotation for '%s'", path)
565 }
566 }
567 err = ra.AppendAll(resources)
568 if err != nil {
569 return errors.WrapPrefixf(err, "merging resources from '%s'", path)
570 }
571 return nil
572 }
573
574 func (kt *KustTarget) configureBuiltinPlugin(
575 p resmap.Configurable, c interface{}, bpt builtinhelpers.BuiltinPluginType) (err error) {
576 var y []byte
577 if c != nil {
578 y, err = yaml.Marshal(c)
579 if err != nil {
580 return errors.WrapPrefixf(
581 err, "builtin %s marshal", bpt)
582 }
583 }
584 err = p.Config(
585 resmap.NewPluginHelpers(
586 kt.ldr, kt.validator, kt.rFactory, kt.pLdr.Config()),
587 y)
588 if err != nil {
589 return errors.WrapPrefixf(
590 err, "trouble configuring builtin %s with config: `\n%s`", bpt, string(y))
591 }
592 return nil
593 }