File: runtimeutil.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 (281 lines) | stat: -rw-r--r-- 7,722 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
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package runtimeutil

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"path"
	"strings"

	"sigs.k8s.io/kustomize/kyaml/comments"
	"sigs.k8s.io/kustomize/kyaml/errors"
	"sigs.k8s.io/kustomize/kyaml/kio"
	"sigs.k8s.io/kustomize/kyaml/kio/kioutil"
	"sigs.k8s.io/kustomize/kyaml/order"

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

// FunctionFilter wraps another filter to be invoked in the context of a function.
// FunctionFilter manages scoping the function, deferring failures, and saving results
// to files.
type FunctionFilter struct {
	// Run implements the function.
	Run func(reader io.Reader, writer io.Writer) error

	// FunctionConfig is passed to the function through ResourceList.functionConfig.
	FunctionConfig *yaml.RNode `yaml:"functionConfig,omitempty"`

	// GlobalScope explicitly scopes the function to all input resources rather than only those
	// resources scoped to it by path.
	GlobalScope bool

	// ResultsFile is the file to write function ResourceList.results to.
	// If unset, results will not be written.
	ResultsFile string

	// DeferFailure will cause the Filter to return a nil error even if Run returns an error.
	// The Run error will be available through GetExit().
	DeferFailure bool

	// results saves the results emitted from Run
	Results *yaml.RNode

	// exit saves the error returned from Run
	exit error

	ids map[string]*yaml.RNode
}

// GetExit returns the error from Run
func (c FunctionFilter) GetExit() error {
	return c.exit
}

// functionsDirectoryName is keyword directory name for functions scoped 1 directory higher
const functionsDirectoryName = "functions"

// getFunctionScope returns the path of the directory containing the function config,
// or its parent directory if the base directory is named "functions"
func (c *FunctionFilter) getFunctionScope() (string, error) {
	m, err := c.FunctionConfig.GetMeta()
	if err != nil {
		return "", errors.Wrap(err)
	}
	var p string
	var found bool
	p, found = m.Annotations[kioutil.PathAnnotation]
	if !found {
		p, found = m.Annotations[kioutil.LegacyPathAnnotation]
		if !found {
			return "", nil
		}
	}

	functionDir := path.Clean(path.Dir(p))

	if path.Base(functionDir) == functionsDirectoryName {
		// the scope of functions in a directory called "functions" is 1 level higher
		// this is similar to how the golang "internal" directory scoping works
		functionDir = path.Dir(functionDir)
	}
	return functionDir, nil
}

// scope partitions the input nodes into 2 slices.  The first slice contains only Resources
// which are scoped under dir, and the second slice contains the Resources which are not.
func (c *FunctionFilter) scope(dir string, nodes []*yaml.RNode) ([]*yaml.RNode, []*yaml.RNode, error) {
	// scope container filtered Resources to Resources under that directory
	var input, saved []*yaml.RNode
	if c.GlobalScope {
		return nodes, nil, nil
	}

	// global function
	if dir == "" || dir == "." {
		return nodes, nil, nil
	}

	// identify Resources read from directories under the function configuration
	for i := range nodes {
		m, err := nodes[i].GetMeta()
		if err != nil {
			return nil, nil, err
		}
		var p string
		var found bool
		p, found = m.Annotations[kioutil.PathAnnotation]
		if !found {
			p, found = m.Annotations[kioutil.LegacyPathAnnotation]
			if !found {
				// this Resource isn't scoped under the function -- don't know where it came from
				// consider it out of scope
				saved = append(saved, nodes[i])
				continue
			}
		}

		resourceDir := path.Clean(path.Dir(p))
		if path.Base(resourceDir) == functionsDirectoryName {
			// Functions in the `functions` directory are scoped to
			// themselves, and should see themselves as input
			resourceDir = path.Dir(resourceDir)
		}
		if !strings.HasPrefix(resourceDir, dir) {
			// this Resource doesn't fall under the function scope if it
			// isn't in a subdirectory of where the function lives
			saved = append(saved, nodes[i])
			continue
		}

		// this input is scoped under the function
		input = append(input, nodes[i])
	}

	return input, saved, nil
}

func (c *FunctionFilter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
	in := &bytes.Buffer{}
	out := &bytes.Buffer{}

	// only process Resources scoped to this function, save the others
	functionDir, err := c.getFunctionScope()
	if err != nil {
		return nil, err
	}
	input, saved, err := c.scope(functionDir, nodes)
	if err != nil {
		return nil, err
	}

	// set ids on each input so it is possible to copy comments from inputs back to outputs
	if err := c.setIds(input); err != nil {
		return nil, err
	}

	// write the input
	err = kio.ByteWriter{
		WrappingAPIVersion:    kio.ResourceListAPIVersion,
		WrappingKind:          kio.ResourceListKind,
		Writer:                in,
		KeepReaderAnnotations: true,
		FunctionConfig:        c.FunctionConfig}.Write(input)
	if err != nil {
		return nil, err
	}

	// capture the command stdout for the return value
	r := &kio.ByteReader{Reader: out}

	// don't exit immediately if the function fails -- write out the validation
	c.exit = c.Run(in, out)

	output, err := r.Read()
	if err != nil {
		return nil, err
	}

	// copy the comments and sync the order of fields from the inputs to the outputs
	if err := c.copyCommentsAndSyncOrder(output); err != nil {
		return nil, err
	}

	if err := c.doResults(r); err != nil {
		return nil, err
	}

	if c.exit != nil && !c.DeferFailure {
		return append(output, saved...), c.exit
	}

	// annotate any generated Resources with a path and index if they don't already have one
	if err := kioutil.DefaultPathAnnotation(functionDir, output); err != nil {
		return nil, err
	}

	// emit both the Resources output from the function, and the out-of-scope Resources
	// which were not provided to the function
	return append(output, saved...), nil
}

func (c *FunctionFilter) setIds(nodes []*yaml.RNode) error {
	// set the id on each node to map inputs to outputs
	var id int
	c.ids = map[string]*yaml.RNode{}
	for i := range nodes {
		id++
		idStr := fmt.Sprintf("%v", id)
		err := nodes[i].PipeE(yaml.SetAnnotation(kioutil.IdAnnotation, idStr))
		if err != nil {
			return errors.Wrap(err)
		}
		err = nodes[i].PipeE(yaml.SetAnnotation(kioutil.LegacyIdAnnotation, idStr))
		if err != nil {
			return errors.Wrap(err)
		}
		c.ids[idStr] = nodes[i]
	}
	return nil
}

func (c *FunctionFilter) copyCommentsAndSyncOrder(nodes []*yaml.RNode) error {
	for i := range nodes {
		node := nodes[i]
		anID, err := node.Pipe(yaml.GetAnnotation(kioutil.IdAnnotation))
		if err != nil {
			return errors.Wrap(err)
		}
		if anID == nil {
			anID, err = node.Pipe(yaml.GetAnnotation(kioutil.LegacyIdAnnotation))
			if err != nil {
				return errors.Wrap(err)
			}
			if anID == nil {
				continue
			}
		}

		var in *yaml.RNode
		var found bool
		if in, found = c.ids[anID.YNode().Value]; !found {
			continue
		}
		if err := comments.CopyComments(in, node); err != nil {
			return errors.Wrap(err)
		}
		if err := order.SyncOrder(in, node); err != nil {
			return errors.Wrap(err)
		}
		if err := node.PipeE(yaml.ClearAnnotation(kioutil.IdAnnotation)); err != nil {
			return errors.Wrap(err)
		}
		if err := node.PipeE(yaml.ClearAnnotation(kioutil.LegacyIdAnnotation)); err != nil {
			return errors.Wrap(err)
		}
	}
	return nil
}

func (c *FunctionFilter) doResults(r *kio.ByteReader) error {
	// Write the results to a file if configured to do so
	if c.ResultsFile != "" && r.Results != nil {
		results, err := r.Results.String()
		if err != nil {
			return err
		}
		err = os.WriteFile(c.ResultsFile, []byte(results), 0600)
		if err != nil {
			return err
		}
	}

	if r.Results != nil {
		c.Results = r.Results
	}
	return nil
}