Debian Codegraph @

api/resource/resource.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package resource
5
6 import (
7 "fmt"
8 "log"
9 "strings"
10
11 "sigs.k8s.io/kustomize/api/filters/patchstrategicmerge"
12 "sigs.k8s.io/kustomize/api/ifc"
13 "sigs.k8s.io/kustomize/api/internal/utils"
14 "sigs.k8s.io/kustomize/api/konfig"
15 "sigs.k8s.io/kustomize/api/types"
16 "sigs.k8s.io/kustomize/kyaml/kio"
17 "sigs.k8s.io/kustomize/kyaml/kio/kioutil"
18 "sigs.k8s.io/kustomize/kyaml/resid"
19 kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
20 "sigs.k8s.io/yaml"
21 )
22
23 // Resource is an RNode, representing a Kubernetes Resource Model object,
24 // paired with metadata used by kustomize.
25 type Resource struct {
26 kyaml.RNode
27 refVarNames []string
28 }
29
30 var BuildAnnotations = []string{
31 utils.BuildAnnotationPreviousKinds,
32 utils.BuildAnnotationPreviousNames,
33 utils.BuildAnnotationPrefixes,
34 utils.BuildAnnotationSuffixes,
35 utils.BuildAnnotationPreviousNamespaces,
36 utils.BuildAnnotationAllowNameChange,
37 utils.BuildAnnotationAllowKindChange,
38 utils.BuildAnnotationsRefBy,
39 utils.BuildAnnotationsGenBehavior,
40 utils.BuildAnnotationsGenAddHashSuffix,
41
42 kioutil.PathAnnotation,
43 kioutil.IndexAnnotation,
44 kioutil.SeqIndentAnnotation,
45 kioutil.IdAnnotation,
46 kioutil.InternalAnnotationsMigrationResourceIDAnnotation,
47
48 kioutil.LegacyPathAnnotation,
49 kioutil.LegacyIndexAnnotation,
50 kioutil.LegacyIdAnnotation,
51
52 konfig.HelmGeneratedAnnotation,
53 }
54
55 func (r *Resource) ResetRNode(incoming *Resource) {
56 r.RNode = *incoming.Copy()
57 }
58
59 func (r *Resource) GetGvk() resid.Gvk {
60 return resid.GvkFromNode(&r.RNode)
61 }
62
63 func (r *Resource) Hash(h ifc.KustHasher) (string, error) {
64 return h.Hash(&r.RNode)
65 }
66
67 func (r *Resource) SetGvk(gvk resid.Gvk) {
68 r.SetKind(gvk.Kind)
69 r.SetApiVersion(gvk.ApiVersion())
70 }
71
72 func (r *Resource) GetOrigin() (*Origin, error) {
73 annotations := r.GetAnnotations()
74 originAnnotations, ok := annotations[utils.OriginAnnotationKey]
75 if !ok {
76 return nil, nil
77 }
78 var origin Origin
79 if err := yaml.Unmarshal([]byte(originAnnotations), &origin); err != nil {
80 return nil, err
81 }
82 return &origin, nil
83 }
84
85 func (r *Resource) SetOrigin(origin *Origin) error {
86 annotations := r.GetAnnotations()
87 if origin == nil {
88 delete(annotations, utils.OriginAnnotationKey)
89 } else {
90 originStr, err := origin.String()
91 if err != nil {
92 return err
93 }
94 annotations[utils.OriginAnnotationKey] = originStr
95 }
96 return r.SetAnnotations(annotations)
97 }
98
99 func (r *Resource) GetTransformations() (Transformations, error) {
100 annotations := r.GetAnnotations()
101 transformerAnnotations, ok := annotations[utils.TransformerAnnotationKey]
102 if !ok {
103 return nil, nil
104 }
105 var transformations Transformations
106 if err := yaml.Unmarshal([]byte(transformerAnnotations), &transformations); err != nil {
107 return nil, err
108 }
109 return transformations, nil
110 }
111
112 func (r *Resource) AddTransformation(origin *Origin) error {
113 annotations := r.GetAnnotations()
114 transformations, err := r.GetTransformations()
115 if err != nil {
116 return err
117 }
118 if transformations == nil {
119 transformations = Transformations{}
120 }
121 transformations = append(transformations, origin)
122 transformationStr, err := transformations.String()
123 if err != nil {
124 return err
125 }
126 annotations[utils.TransformerAnnotationKey] = transformationStr
127 return r.SetAnnotations(annotations)
128 }
129
130 func (r *Resource) ClearTransformations() error {
131 annotations := r.GetAnnotations()
132 delete(annotations, utils.TransformerAnnotationKey)
133 return r.SetAnnotations(annotations)
134 }
135
136 // ResCtx is an interface describing the contextual added
137 // kept kustomize in the context of each Resource object.
138 // Currently mainly the name prefix and name suffix are added.
139 type ResCtx interface {
140 AddNamePrefix(p string)
141 AddNameSuffix(s string)
142 GetNamePrefixes() []string
143 GetNameSuffixes() []string
144 }
145
146 // ResCtxMatcher returns true if two Resources are being
147 // modified in the same kustomize context.
148 type ResCtxMatcher func(ResCtx) bool
149
150 // DeepCopy returns a new copy of resource
151 func (r *Resource) DeepCopy() *Resource {
152 rc := &Resource{
153 RNode: *r.Copy(),
154 }
155 rc.copyKustomizeSpecificFields(r)
156 return rc
157 }
158
159 // CopyMergeMetaDataFieldsFrom copies everything but the non-metadata in
160 // the resource.
161 // TODO: move to RNode, use GetMeta to improve performance.
162 // TODO: make a version of mergeStringMaps that is build-annotation aware
163 // to avoid repeatedly setting refby and genargs annotations
164 // Must remove the kustomize bit at the end.
165 func (r *Resource) CopyMergeMetaDataFieldsFrom(other *Resource) error {
166 if err := r.SetLabels(
167 mergeStringMaps(other.GetLabels(), r.GetLabels())); err != nil {
168 return fmt.Errorf("copyMerge cannot set labels - %w", err)
169 }
170
171 ra := r.GetAnnotations()
172 _, enableNameSuffixHash := ra[utils.BuildAnnotationsGenAddHashSuffix]
173 merged := mergeStringMapsWithBuildAnnotations(other.GetAnnotations(), ra)
174 if !enableNameSuffixHash {
175 delete(merged, utils.BuildAnnotationsGenAddHashSuffix)
176 }
177 if err := r.SetAnnotations(merged); err != nil {
178 return fmt.Errorf("copyMerge cannot set annotations - %w", err)
179 }
180
181 if err := r.SetName(other.GetName()); err != nil {
182 return fmt.Errorf("copyMerge cannot set name - %w", err)
183 }
184 if err := r.SetNamespace(other.GetNamespace()); err != nil {
185 return fmt.Errorf("copyMerge cannot set namespace - %w", err)
186 }
187 r.copyKustomizeSpecificFields(other)
188 return nil
189 }
190
191 func (r *Resource) copyKustomizeSpecificFields(other *Resource) {
192 r.refVarNames = copyStringSlice(other.refVarNames)
193 }
194
195 func (r *Resource) MergeDataMapFrom(o *Resource) {
196 r.SetDataMap(mergeStringMaps(o.GetDataMap(), r.GetDataMap()))
197 }
198
199 func (r *Resource) MergeBinaryDataMapFrom(o *Resource) {
200 r.SetBinaryDataMap(mergeStringMaps(o.GetBinaryDataMap(), r.GetBinaryDataMap()))
201 }
202
203 func (r *Resource) ErrIfNotEquals(o *Resource) error {
204 meYaml, err := r.AsYAML()
205 if err != nil {
206 return err
207 }
208 otherYaml, err := o.AsYAML()
209 if err != nil {
210 return err
211 }
212 if !r.ReferencesEqual(o) {
213 return fmt.Errorf(
214 `unequal references - self:
215 %sreferenced by: %s
216 --- other:
217 %sreferenced by: %s
218 `, meYaml, r.GetRefBy(), otherYaml, o.GetRefBy())
219 }
220 if string(meYaml) != string(otherYaml) {
221 return fmt.Errorf(`--- self:
222 %s
223 --- other:
224 %s
225 `, meYaml, otherYaml)
226 }
227 return nil
228 }
229
230 func (r *Resource) ReferencesEqual(other *Resource) bool {
231 setSelf := make(map[resid.ResId]bool)
232 setOther := make(map[resid.ResId]bool)
233 for _, ref := range other.GetRefBy() {
234 setOther[ref] = true
235 }
236 for _, ref := range r.GetRefBy() {
237 if _, ok := setOther[ref]; !ok {
238 return false
239 }
240 setSelf[ref] = true
241 }
242 return len(setSelf) == len(setOther)
243 }
244
245 func copyStringSlice(s []string) []string {
246 if s == nil {
247 return nil
248 }
249 c := make([]string, len(s))
250 copy(c, s)
251 return c
252 }
253
254 // Implements ResCtx AddNamePrefix
255 func (r *Resource) AddNamePrefix(p string) {
256 r.appendCsvAnnotation(utils.BuildAnnotationPrefixes, p)
257 }
258
259 // Implements ResCtx AddNameSuffix
260 func (r *Resource) AddNameSuffix(s string) {
261 r.appendCsvAnnotation(utils.BuildAnnotationSuffixes, s)
262 }
263
264 func (r *Resource) appendCsvAnnotation(name, value string) {
265 if value == "" {
266 return
267 }
268 currentValue := r.getCsvAnnotation(name)
269 newValue := strings.Join(append(currentValue, value), ",")
270 if err := r.RNode.PipeE(kyaml.SetAnnotation(name, newValue)); err != nil {
271 panic(err)
272 }
273 }
274
275 // Implements ResCtx GetNamePrefixes
276 func (r *Resource) GetNamePrefixes() []string {
277 return r.getCsvAnnotation(utils.BuildAnnotationPrefixes)
278 }
279
280 // Implements ResCtx GetNameSuffixes
281 func (r *Resource) GetNameSuffixes() []string {
282 return r.getCsvAnnotation(utils.BuildAnnotationSuffixes)
283 }
284
285 func (r *Resource) getCsvAnnotation(name string) []string {
286 annotations := r.GetAnnotations()
287 if _, ok := annotations[name]; !ok {
288 return nil
289 }
290 return strings.Split(annotations[name], ",")
291 }
292
293 // PrefixesSuffixesEquals is conceptually doing the same task as
294 // OutermostPrefixSuffix but performs a deeper comparison of the suffix and
295 // prefix slices.
296 // The allowEmpty flag determines whether an empty prefix/suffix
297 // should be considered a match on anything.
298 // This is used when filtering, starting with a coarser pass allowing empty
299 // matches, before requiring exact matches if there are multiple
300 // remaining candidates.
301 func (r *Resource) PrefixesSuffixesEquals(o ResCtx, allowEmpty bool) bool {
302 if allowEmpty {
303 eitherPrefixEmpty := len(r.GetNamePrefixes()) == 0 || len(o.GetNamePrefixes()) == 0
304 eitherSuffixEmpty := len(r.GetNameSuffixes()) == 0 || len(o.GetNameSuffixes()) == 0
305
306 return (eitherPrefixEmpty || utils.SameEndingSubSlice(r.GetNamePrefixes(), o.GetNamePrefixes())) &&
307 (eitherSuffixEmpty || utils.SameEndingSubSlice(r.GetNameSuffixes(), o.GetNameSuffixes()))
308 } else {
309 return utils.SameEndingSubSlice(r.GetNamePrefixes(), o.GetNamePrefixes()) &&
310 utils.SameEndingSubSlice(r.GetNameSuffixes(), o.GetNameSuffixes())
311 }
312 }
313
314 // RemoveBuildAnnotations removes annotations created by the build process.
315 // These are internal-only to kustomize, added to the data pipeline to
316 // track name changes so name references can be fixed.
317 func (r *Resource) RemoveBuildAnnotations() {
318 annotations := r.GetAnnotations()
319 if len(annotations) == 0 {
320 return
321 }
322 for _, a := range BuildAnnotations {
323 delete(annotations, a)
324 }
325 if err := r.SetAnnotations(annotations); err != nil {
326 panic(err)
327 }
328 }
329
330 func (r *Resource) setPreviousId(ns string, n string, k string) *Resource {
331 r.appendCsvAnnotation(utils.BuildAnnotationPreviousNames, n)
332 r.appendCsvAnnotation(utils.BuildAnnotationPreviousNamespaces, ns)
333 r.appendCsvAnnotation(utils.BuildAnnotationPreviousKinds, k)
334 return r
335 }
336
337 // AllowNameChange allows name changes to the resource.
338 func (r *Resource) AllowNameChange() {
339 r.enable(utils.BuildAnnotationAllowNameChange)
340 }
341
342 // NameChangeAllowed checks if a patch resource is allowed to change another resource's name.
343 func (r *Resource) NameChangeAllowed() bool {
344 return r.isEnabled(utils.BuildAnnotationAllowNameChange)
345 }
346
347 // AllowKindChange allows kind changes to the resource.
348 func (r *Resource) AllowKindChange() {
349 r.enable(utils.BuildAnnotationAllowKindChange)
350 }
351
352 // KindChangeAllowed checks if a patch resource is allowed to change another resource's kind.
353 func (r *Resource) KindChangeAllowed() bool {
354 return r.isEnabled(utils.BuildAnnotationAllowKindChange)
355 }
356
357 func (r *Resource) isEnabled(annoKey string) bool {
358 annotations := r.GetAnnotations()
359 v, ok := annotations[annoKey]
360 return ok && v == utils.Enabled
361 }
362
363 func (r *Resource) enable(annoKey string) {
364 annotations := r.GetAnnotations()
365 annotations[annoKey] = utils.Enabled
366 if err := r.SetAnnotations(annotations); err != nil {
367 panic(err)
368 }
369 }
370
371 // String returns resource as JSON.
372 func (r *Resource) String() string {
373 bs, err := r.MarshalJSON()
374 if err != nil {
375 return "<" + err.Error() + ">"
376 }
377 return strings.TrimSpace(string(bs))
378 }
379
380 // AsYAML returns the resource in Yaml form.
381 // Easier to read than JSON.
382 func (r *Resource) AsYAML() ([]byte, error) {
383 json, err := r.MarshalJSON()
384 if err != nil {
385 return nil, err
386 }
387 return yaml.JSONToYAML(json)
388 }
389
390 // MustYaml returns YAML or panics.
391 func (r *Resource) MustYaml() string {
392 yml, err := r.AsYAML()
393 if err != nil {
394 log.Fatal(err)
395 }
396 return string(yml)
397 }
398
399 // Behavior returns the behavior for the resource.
400 func (r *Resource) Behavior() types.GenerationBehavior {
401 annotations := r.GetAnnotations()
402 if v, ok := annotations[utils.BuildAnnotationsGenBehavior]; ok {
403 return types.NewGenerationBehavior(v)
404 }
405 return types.NewGenerationBehavior("")
406 }
407
408 // SetBehavior sets the behavior for the resource.
409 func (r *Resource) SetBehavior(behavior types.GenerationBehavior) {
410 annotations := r.GetAnnotations()
411 annotations[utils.BuildAnnotationsGenBehavior] = behavior.String()
412 if err := r.SetAnnotations(annotations); err != nil {
413 panic(err)
414 }
415 }
416
417 // NeedHashSuffix returns true if a resource content
418 // hash should be appended to the name of the resource.
419 func (r *Resource) NeedHashSuffix() bool {
420 return r.isEnabled(utils.BuildAnnotationsGenAddHashSuffix)
421 }
422
423 // EnableHashSuffix marks the resource as needing a content
424 // hash to be appended to the name of the resource.
425 func (r *Resource) EnableHashSuffix() {
426 r.enable(utils.BuildAnnotationsGenAddHashSuffix)
427 }
428
429 // OrgId returns the original, immutable ResId for the resource.
430 // This doesn't have to be unique in a ResMap.
431 func (r *Resource) OrgId() resid.ResId {
432 ids := r.PrevIds()
433 if len(ids) > 0 {
434 return ids[0]
435 }
436 return r.CurId()
437 }
438
439 // PrevIds returns a list of ResIds that includes every
440 // previous ResId the resource has had through all of its
441 // GVKN transformations, in the order that it had that ID.
442 // I.e. the oldest ID is first.
443 // The returned array does not include the resource's current
444 // ID. If there are no previous IDs, this will return nil.
445 func (r *Resource) PrevIds() []resid.ResId {
446 prevIds, err := utils.PrevIds(&r.RNode)
447 if err != nil {
448 // this should never happen
449 panic(err)
450 }
451 return prevIds
452 }
453
454 // StorePreviousId stores the resource's current ID via build annotations.
455 func (r *Resource) StorePreviousId() {
456 id := r.CurId()
457 r.setPreviousId(id.EffectiveNamespace(), id.Name, id.Kind)
458 }
459
460 // CurId returns a ResId for the resource using the
461 // mutable parts of the resource.
462 // This should be unique in any ResMap.
463 func (r *Resource) CurId() resid.ResId {
464 return resid.NewResIdWithNamespace(
465 r.GetGvk(), r.GetName(), r.GetNamespace())
466 }
467
468 // GetRefBy returns the ResIds that referred to current resource
469 func (r *Resource) GetRefBy() []resid.ResId {
470 var resIds []resid.ResId
471 asStrings := r.getCsvAnnotation(utils.BuildAnnotationsRefBy)
472 for _, s := range asStrings {
473 resIds = append(resIds, resid.FromString(s))
474 }
475 return resIds
476 }
477
478 // AppendRefBy appends a ResId into the refBy list
479 // Using any type except fmt.Stringer here results in a compilation error
480 func (r *Resource) AppendRefBy(id fmt.Stringer) {
481 r.appendCsvAnnotation(utils.BuildAnnotationsRefBy, id.String())
482 }
483
484 // GetRefVarNames returns vars that refer to current resource
485 func (r *Resource) GetRefVarNames() []string {
486 return r.refVarNames
487 }
488
489 // AppendRefVarName appends a name of a var into the refVar list
490 func (r *Resource) AppendRefVarName(variable types.Var) {
491 r.refVarNames = append(r.refVarNames, variable.Name)
492 }
493
494 // ApplySmPatch applies the provided strategic merge patch.
495 func (r *Resource) ApplySmPatch(patch *Resource) error {
496 n, ns, k := r.GetName(), r.GetNamespace(), r.GetKind()
497 if patch.NameChangeAllowed() || patch.KindChangeAllowed() {
498 r.StorePreviousId()
499 }
500 if err := r.ApplyFilter(patchstrategicmerge.Filter{
501 Patch: &patch.RNode,
502 }); err != nil {
503 return err
504 }
505 if r.IsNilOrEmpty() {
506 return nil
507 }
508 if !patch.KindChangeAllowed() {
509 r.SetKind(k)
510 }
511 if !patch.NameChangeAllowed() {
512 r.SetName(n)
513 }
514 r.SetNamespace(ns)
515 return nil
516 }
517
518 func (r *Resource) ApplyFilter(f kio.Filter) error {
519 l, err := f.Filter([]*kyaml.RNode{&r.RNode})
520 if len(l) == 0 {
521 // The node was deleted, which means the entire resource
522 // must be deleted. Signal that via the following:
523 r.SetYNode(nil)
524 }
525 return err
526 }
527
528 func mergeStringMaps(maps ...map[string]string) map[string]string {
529 result := map[string]string{}
530 for _, m := range maps {
531 for key, value := range m {
532 result[key] = value
533 }
534 }
535 return result
536 }
537
538 func mergeStringMapsWithBuildAnnotations(maps ...map[string]string) map[string]string {
539 result := mergeStringMaps(maps...)
540 for i := range BuildAnnotations {
541 if len(maps) > 0 {
542 if v, ok := maps[0][BuildAnnotations[i]]; ok {
543 result[BuildAnnotations[i]] = v
544 continue
545 }
546 }
547 delete(result, BuildAnnotations[i])
548 }
549 return result
550 }