File: kioutil.go

package info (click to toggle)
golang-k8s-sigs-kustomize-kyaml 0.20.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,180 kB
  • sloc: makefile: 220; sh: 68
file content (420 lines) | stat: -rw-r--r-- 11,518 bytes parent folder | download | duplicates (2)
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
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package kioutil

import (
	"fmt"
	"path"
	"sort"
	"strconv"
	"strings"

	"sigs.k8s.io/kustomize/kyaml/errors"
	"sigs.k8s.io/kustomize/kyaml/yaml"
)

type AnnotationKey = string

const (
	// internalPrefix is the prefix given to internal annotations that are used
	// internally by the orchestrator
	internalPrefix string = "internal.config.kubernetes.io/"

	// IndexAnnotation records the index of a specific resource in a file or input stream.
	IndexAnnotation AnnotationKey = internalPrefix + "index"

	// PathAnnotation records the path to the file the Resource was read from
	PathAnnotation AnnotationKey = internalPrefix + "path"

	// SeqIndentAnnotation records the sequence nodes indentation of the input resource
	SeqIndentAnnotation AnnotationKey = internalPrefix + "seqindent"

	// IdAnnotation records the id of the resource to map inputs to outputs
	IdAnnotation AnnotationKey = internalPrefix + "id"

	// Deprecated: Use IndexAnnotation instead.
	LegacyIndexAnnotation AnnotationKey = "config.kubernetes.io/index"

	// Deprecated: use PathAnnotation instead.
	LegacyPathAnnotation AnnotationKey = "config.kubernetes.io/path"

	// Deprecated: use IdAnnotation instead.
	LegacyIdAnnotation = "config.k8s.io/id"

	// InternalAnnotationsMigrationResourceIDAnnotation is used to uniquely identify
	// resources during round trip to and from a function execution. We will use it
	// to track the internal annotations and reconcile them if needed.
	InternalAnnotationsMigrationResourceIDAnnotation = internalPrefix + "annotations-migration-resource-id"
)

func GetFileAnnotations(rn *yaml.RNode) (string, string, error) {
	rm, _ := rn.GetMeta()
	annotations := rm.Annotations
	path, found := annotations[PathAnnotation]
	if !found {
		path = annotations[LegacyPathAnnotation]
	}
	index, found := annotations[IndexAnnotation]
	if !found {
		index = annotations[LegacyIndexAnnotation]
	}
	return path, index, nil
}

func GetIdAnnotation(rn *yaml.RNode) string {
	rm, _ := rn.GetMeta()
	annotations := rm.Annotations
	id, found := annotations[IdAnnotation]
	if !found {
		id = annotations[LegacyIdAnnotation]
	}
	return id
}

func CopyLegacyAnnotations(rn *yaml.RNode) error {
	meta, err := rn.GetMeta()
	if err != nil {
		if err == yaml.ErrMissingMetadata {
			// resource has no metadata, this should be a no-op
			return nil
		}
		return err
	}
	if err := copyAnnotations(meta, rn, LegacyPathAnnotation, PathAnnotation); err != nil {
		return err
	}
	if err := copyAnnotations(meta, rn, LegacyIndexAnnotation, IndexAnnotation); err != nil {
		return err
	}
	if err := copyAnnotations(meta, rn, LegacyIdAnnotation, IdAnnotation); err != nil {
		return err
	}
	return nil
}

func copyAnnotations(meta yaml.ResourceMeta, rn *yaml.RNode, legacyKey string, newKey string) error {
	newValue := meta.Annotations[newKey]
	legacyValue := meta.Annotations[legacyKey]
	if newValue != "" {
		if legacyValue == "" {
			if err := rn.PipeE(yaml.SetAnnotation(legacyKey, newValue)); err != nil {
				return err
			}
		}
	} else {
		if legacyValue != "" {
			if err := rn.PipeE(yaml.SetAnnotation(newKey, legacyValue)); err != nil {
				return err
			}
		}
	}
	return nil
}

// ErrorIfMissingAnnotation validates the provided annotations are present on the given resources
func ErrorIfMissingAnnotation(nodes []*yaml.RNode, keys ...AnnotationKey) error {
	for _, key := range keys {
		for _, node := range nodes {
			val, err := node.Pipe(yaml.GetAnnotation(key))
			if err != nil {
				return errors.Wrap(err)
			}
			if val == nil {
				return errors.Errorf("missing annotation %s", key)
			}
		}
	}
	return nil
}

// CreatePathAnnotationValue creates a default path annotation value for a Resource.
// The path prefix will be dir.
func CreatePathAnnotationValue(dir string, m yaml.ResourceMeta) string {
	filename := fmt.Sprintf("%s_%s.yaml", strings.ToLower(m.Kind), m.Name)
	return path.Join(dir, m.Namespace, filename)
}

// DefaultPathAndIndexAnnotation sets a default path or index value on any nodes missing the
// annotation
func DefaultPathAndIndexAnnotation(dir string, nodes []*yaml.RNode) error {
	counts := map[string]int{}

	// check each node for the path annotation
	for i := range nodes {
		if err := CopyLegacyAnnotations(nodes[i]); err != nil {
			return err
		}
		m, err := nodes[i].GetMeta()
		if err != nil {
			return err
		}

		// calculate the max index in each file in case we are appending
		if p, found := m.Annotations[PathAnnotation]; found {
			// record the max indexes into each file
			if i, found := m.Annotations[IndexAnnotation]; found {
				index, _ := strconv.Atoi(i)
				if index > counts[p] {
					counts[p] = index
				}
			}

			// has the path annotation already -- do nothing
			continue
		}

		// set a path annotation on the Resource
		path := CreatePathAnnotationValue(dir, m)
		if err := nodes[i].PipeE(yaml.SetAnnotation(PathAnnotation, path)); err != nil {
			return err
		}
		if err := nodes[i].PipeE(yaml.SetAnnotation(LegacyPathAnnotation, path)); err != nil {
			return err
		}
	}

	// set the index annotations
	for i := range nodes {
		m, err := nodes[i].GetMeta()
		if err != nil {
			return err
		}

		if _, found := m.Annotations[IndexAnnotation]; found {
			continue
		}

		p := m.Annotations[PathAnnotation]

		// set an index annotation on the Resource
		c := counts[p]
		counts[p] = c + 1
		if err := nodes[i].PipeE(
			yaml.SetAnnotation(IndexAnnotation, fmt.Sprintf("%d", c))); err != nil {
			return err
		}
		if err := nodes[i].PipeE(
			yaml.SetAnnotation(LegacyIndexAnnotation, fmt.Sprintf("%d", c))); err != nil {
			return err
		}
	}
	return nil
}

// DefaultPathAnnotation sets a default path annotation on any Reources
// missing it.
func DefaultPathAnnotation(dir string, nodes []*yaml.RNode) error {
	// check each node for the path annotation
	for i := range nodes {
		if err := CopyLegacyAnnotations(nodes[i]); err != nil {
			return err
		}
		m, err := nodes[i].GetMeta()
		if err != nil {
			return err
		}

		if _, found := m.Annotations[PathAnnotation]; found {
			// has the path annotation already -- do nothing
			continue
		}

		// set a path annotation on the Resource
		path := CreatePathAnnotationValue(dir, m)
		if err := nodes[i].PipeE(yaml.SetAnnotation(PathAnnotation, path)); err != nil {
			return err
		}
		if err := nodes[i].PipeE(yaml.SetAnnotation(LegacyPathAnnotation, path)); err != nil {
			return err
		}
	}
	return nil
}

// Map invokes fn for each element in nodes.
func Map(nodes []*yaml.RNode, fn func(*yaml.RNode) (*yaml.RNode, error)) ([]*yaml.RNode, error) {
	var returnNodes []*yaml.RNode
	for i := range nodes {
		n, err := fn(nodes[i])
		if err != nil {
			return nil, errors.Wrap(err)
		}
		if n != nil {
			returnNodes = append(returnNodes, n)
		}
	}
	return returnNodes, nil
}

func MapMeta(nodes []*yaml.RNode, fn func(*yaml.RNode, yaml.ResourceMeta) (*yaml.RNode, error)) (
	[]*yaml.RNode, error) {
	var returnNodes []*yaml.RNode
	for i := range nodes {
		meta, err := nodes[i].GetMeta()
		if err != nil {
			return nil, errors.Wrap(err)
		}
		n, err := fn(nodes[i], meta)
		if err != nil {
			return nil, errors.Wrap(err)
		}
		if n != nil {
			returnNodes = append(returnNodes, n)
		}
	}
	return returnNodes, nil
}

// SortNodes sorts nodes in place:
// - by PathAnnotation annotation
// - by IndexAnnotation annotation
func SortNodes(nodes []*yaml.RNode) error {
	var err error
	// use stable sort to keep ordering of equal elements
	sort.SliceStable(nodes, func(i, j int) bool {
		if err != nil {
			return false
		}
		if err := CopyLegacyAnnotations(nodes[i]); err != nil {
			return false
		}
		if err := CopyLegacyAnnotations(nodes[j]); err != nil {
			return false
		}
		var iMeta, jMeta yaml.ResourceMeta
		if iMeta, _ = nodes[i].GetMeta(); err != nil {
			return false
		}
		if jMeta, _ = nodes[j].GetMeta(); err != nil {
			return false
		}

		iValue := iMeta.Annotations[PathAnnotation]
		jValue := jMeta.Annotations[PathAnnotation]
		if iValue != jValue {
			return iValue < jValue
		}

		iValue = iMeta.Annotations[IndexAnnotation]
		jValue = jMeta.Annotations[IndexAnnotation]

		// put resource config without an index first
		if iValue == jValue {
			return false
		}
		if iValue == "" {
			return true
		}
		if jValue == "" {
			return false
		}

		// sort by index
		var iIndex, jIndex int
		iIndex, err = strconv.Atoi(iValue)
		if err != nil {
			err = fmt.Errorf("unable to parse config.kubernetes.io/index %s :%v", iValue, err)
			return false
		}
		jIndex, err = strconv.Atoi(jValue)
		if err != nil {
			err = fmt.Errorf("unable to parse config.kubernetes.io/index %s :%v", jValue, err)
			return false
		}
		if iIndex != jIndex {
			return iIndex < jIndex
		}

		// elements are equal
		return false
	})
	return errors.Wrap(err)
}

// CopyInternalAnnotations copies the annotations that begin with the prefix
// `internal.config.kubernetes.io` from the source RNode to the destination RNode.
// It takes a parameter exclusions, which is a list of annotation keys to ignore.
func CopyInternalAnnotations(src *yaml.RNode, dst *yaml.RNode, exclusions ...AnnotationKey) error {
	srcAnnotations := GetInternalAnnotations(src)
	for k, v := range srcAnnotations {
		if stringSliceContains(exclusions, k) {
			continue
		}
		if err := dst.PipeE(yaml.SetAnnotation(k, v)); err != nil {
			return err
		}
	}
	return nil
}

// ConfirmInternalAnnotationUnchanged compares the annotations of the RNodes that begin with the prefix
// `internal.config.kubernetes.io`, throwing an error if they differ. It takes a parameter exclusions,
// which is a list of annotation keys to ignore.
func ConfirmInternalAnnotationUnchanged(r1 *yaml.RNode, r2 *yaml.RNode, exclusions ...AnnotationKey) error {
	r1Annotations := GetInternalAnnotations(r1)
	r2Annotations := GetInternalAnnotations(r2)

	// this is a map to prevent duplicates
	diffAnnos := make(map[string]bool)

	for k, v1 := range r1Annotations {
		if stringSliceContains(exclusions, k) {
			continue
		}
		if v2, ok := r2Annotations[k]; !ok || v1 != v2 {
			diffAnnos[k] = true
		}
	}

	for k, v2 := range r2Annotations {
		if stringSliceContains(exclusions, k) {
			continue
		}
		if v1, ok := r1Annotations[k]; !ok || v2 != v1 {
			diffAnnos[k] = true
		}
	}

	if len(diffAnnos) > 0 {
		keys := make([]string, 0, len(diffAnnos))
		for k := range diffAnnos {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		errorString := "internal annotations differ: "
		for _, key := range keys {
			errorString = errorString + key + ", "
		}
		return errors.Errorf(errorString[0 : len(errorString)-2])
	}

	return nil
}

// GetInternalAnnotations returns a map of all the annotations of the provided
// RNode that satisfies one of the following: 1) begin with the prefix
// `internal.config.kubernetes.io` 2) is one of `config.kubernetes.io/path`,
// `config.kubernetes.io/index` and `config.k8s.io/id`.
func GetInternalAnnotations(rn *yaml.RNode) map[string]string {
	meta, _ := rn.GetMeta()
	annotations := meta.Annotations
	result := make(map[string]string)
	for k, v := range annotations {
		if strings.HasPrefix(k, internalPrefix) || k == LegacyPathAnnotation || k == LegacyIndexAnnotation || k == LegacyIdAnnotation {
			result[k] = v
		}
	}
	return result
}

// stringSliceContains returns true if the slice has the string.
func stringSliceContains(slice []string, str string) bool {
	for _, s := range slice {
		if s == str {
			return true
		}
	}
	return false
}