Debian Codegraph @

kyaml/runfn/runfn.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package runfn
5
6 import (
7 "fmt"
8 "io"
9 "os"
10 "os/user"
11 "path"
12 "path/filepath"
13 "sort"
14 "strconv"
15 "strings"
16 "sync/atomic"
17
18 "sigs.k8s.io/kustomize/kyaml/errors"
19 "sigs.k8s.io/kustomize/kyaml/fn/runtime/container"
20 "sigs.k8s.io/kustomize/kyaml/fn/runtime/exec"
21 "sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil"
22 "sigs.k8s.io/kustomize/kyaml/kio"
23 "sigs.k8s.io/kustomize/kyaml/kio/kioutil"
24 "sigs.k8s.io/kustomize/kyaml/yaml"
25 )
26
27 // RunFns runs the set of configuration functions in a local directory against
28 // the Resources in that directory
29 type RunFns struct {
30 StorageMounts []runtimeutil.StorageMount
31
32 // Path is the path to the directory containing functions
33 Path string
34
35 // FunctionPaths Paths allows functions to be specified outside the configuration
36 // directory.
37 // Functions provided on FunctionPaths are globally scoped.
38 // If FunctionPaths length is > 0, then NoFunctionsFromInput defaults to true
39 FunctionPaths []string
40
41 // Functions is an explicit list of functions to run against the input.
42 // Functions provided on Functions are globally scoped.
43 // If Functions length is > 0, then NoFunctionsFromInput defaults to true
44 Functions []*yaml.RNode
45
46 // GlobalScope if true, functions read from input will be scoped globally rather
47 // than only to Resources under their subdirs.
48 GlobalScope bool
49
50 // Input can be set to read the Resources from Input rather than from a directory
51 Input io.Reader
52
53 // Network enables network access for functions that declare it
54 Network bool
55
56 // Output can be set to write the result to Output rather than back to the directory
57 Output io.Writer
58
59 // NoFunctionsFromInput if set to true will not read any functions from the input,
60 // and only use explicit sources
61 NoFunctionsFromInput *bool
62
63 // EnableExec will enable exec functions
64 EnableExec bool
65
66 // DisableContainers will disable functions run as containers
67 DisableContainers bool
68
69 // ResultsDir is where to write each functions results
70 ResultsDir string
71
72 // LogSteps enables logging the function that is running.
73 LogSteps bool
74
75 // LogWriter can be set to write the logs to LogWriter rather than stderr if LogSteps is enabled.
76 LogWriter io.Writer
77
78 // resultsCount is used to generate the results filename for each container
79 resultsCount uint32
80
81 // functionFilterProvider provides a filter to perform the function.
82 // this is a variable so it can be mocked in tests
83 functionFilterProvider func(
84 filter runtimeutil.FunctionSpec, api *yaml.RNode, currentUser currentUserFunc) (kio.Filter, error)
85
86 // AsCurrentUser is a boolean to indicate whether docker container should use
87 // the uid and gid that run the command
88 AsCurrentUser bool
89
90 // Env contains environment variables that will be exported to container
91 Env []string
92
93 // ContinueOnEmptyResult configures what happens when the underlying pipeline
94 // returns an empty result.
95 // If it is false (default), subsequent functions will be skipped and the
96 // result will be returned immediately.
97 // If it is true, the empty result will be provided as input to the next
98 // function in the list.
99 ContinueOnEmptyResult bool
100
101 // WorkingDir specifies which working directory an exec function should run in.
102 WorkingDir string
103 }
104
105 // Execute runs the command
106 func (r RunFns) Execute() error {
107 // make the path absolute so it works on mac
108 var err error
109 r.Path, err = filepath.Abs(r.Path)
110 if err != nil {
111 return errors.Wrap(err)
112 }
113
114 // default the containerFilterProvider if it hasn't been override. Split out for testing.
115 (&r).init()
116 nodes, fltrs, output, err := r.getNodesAndFilters()
117 if err != nil {
118 return err
119 }
120 return r.runFunctions(nodes, output, fltrs)
121 }
122
123 func (r RunFns) getNodesAndFilters() (
124 *kio.PackageBuffer, []kio.Filter, *kio.LocalPackageReadWriter, error) {
125 // Read Resources from Directory or Input
126 buff := &kio.PackageBuffer{}
127 p := kio.Pipeline{Outputs: []kio.Writer{buff}}
128 // save the output dir because we will need it to write back
129 // the same one for reading must be used for writing if deleting Resources
130 var outputPkg *kio.LocalPackageReadWriter
131 if r.Path != "" {
132 outputPkg = &kio.LocalPackageReadWriter{PackagePath: r.Path, MatchFilesGlob: kio.MatchAll}
133 }
134
135 if r.Input == nil {
136 p.Inputs = []kio.Reader{outputPkg}
137 } else {
138 p.Inputs = []kio.Reader{&kio.ByteReader{Reader: r.Input}}
139 }
140 if err := p.Execute(); err != nil {
141 return nil, nil, outputPkg, err
142 }
143
144 fltrs, err := r.getFilters(buff.Nodes)
145 if err != nil {
146 return nil, nil, outputPkg, err
147 }
148 return buff, fltrs, outputPkg, nil
149 }
150
151 func (r RunFns) getFilters(nodes []*yaml.RNode) ([]kio.Filter, error) {
152 var fltrs []kio.Filter
153
154 // fns from annotations on the input resources
155 f, err := r.getFunctionsFromInput(nodes)
156 if err != nil {
157 return nil, err
158 }
159 fltrs = append(fltrs, f...)
160
161 // fns from directories specified on the struct
162 f, err = r.getFunctionsFromFunctionPaths()
163 if err != nil {
164 return nil, err
165 }
166 fltrs = append(fltrs, f...)
167
168 // explicit fns specified on the struct
169 f, err = r.getFunctionsFromFunctions()
170 if err != nil {
171 return nil, err
172 }
173 fltrs = append(fltrs, f...)
174
175 return fltrs, nil
176 }
177
178 // runFunctions runs the fltrs against the input and writes to either r.Output or output
179 func (r RunFns) runFunctions(
180 input kio.Reader, output kio.Writer, fltrs []kio.Filter) error {
181 // use the previously read Resources as input
182 var outputs []kio.Writer
183 if r.Output == nil {
184 // write back to the package
185 outputs = append(outputs, output)
186 } else {
187 // write to the output instead of the directory if r.Output is specified or
188 // the output is nil (reading from Input)
189 outputs = append(outputs, kio.ByteWriter{Writer: r.Output})
190 }
191
192 var err error
193 pipeline := kio.Pipeline{
194 Inputs: []kio.Reader{input},
195 Filters: fltrs,
196 Outputs: outputs,
197 ContinueOnEmptyResult: r.ContinueOnEmptyResult,
198 }
199 if r.LogSteps {
200 err = pipeline.ExecuteWithCallback(func(op kio.Filter) {
201 var identifier string
202
203 switch filter := op.(type) {
204 case *container.Filter:
205 identifier = filter.Image
206 case *exec.Filter:
207 identifier = filter.Path
208 default:
209 identifier = "unknown-type function"
210 }
211
212 _, _ = fmt.Fprintf(r.LogWriter, "Running %s\n", identifier)
213 })
214 } else {
215 err = pipeline.Execute()
216 }
217 if err != nil {
218 return err
219 }
220
221 // check for deferred function errors
222 var errs []string
223 for i := range fltrs {
224 cf, ok := fltrs[i].(runtimeutil.DeferFailureFunction)
225 if !ok {
226 continue
227 }
228 if cf.GetExit() != nil {
229 errs = append(errs, cf.GetExit().Error())
230 }
231 }
232 if len(errs) > 0 {
233 return fmt.Errorf("%s", strings.Join(errs, "\n---\n"))
234 }
235 return nil
236 }
237
238 // getFunctionsFromInput scans the input for functions and runs them
239 func (r RunFns) getFunctionsFromInput(nodes []*yaml.RNode) ([]kio.Filter, error) {
240 if *r.NoFunctionsFromInput {
241 return nil, nil
242 }
243
244 buff := &kio.PackageBuffer{}
245 err := kio.Pipeline{
246 Inputs: []kio.Reader{&kio.PackageBuffer{Nodes: nodes}},
247 Filters: []kio.Filter{&runtimeutil.IsReconcilerFilter{}},
248 Outputs: []kio.Writer{buff},
249 }.Execute()
250 if err != nil {
251 return nil, err
252 }
253 err = sortFns(buff)
254 if err != nil {
255 return nil, err
256 }
257 return r.getFunctionFilters(false, buff.Nodes...)
258 }
259
260 // getFunctionsFromFunctionPaths returns the set of functions read from r.FunctionPaths
261 // as a slice of Filters
262 func (r RunFns) getFunctionsFromFunctionPaths() ([]kio.Filter, error) {
263 buff := &kio.PackageBuffer{}
264 for i := range r.FunctionPaths {
265 err := kio.Pipeline{
266 Inputs: []kio.Reader{
267 kio.LocalPackageReader{PackagePath: r.FunctionPaths[i]},
268 },
269 Outputs: []kio.Writer{buff},
270 }.Execute()
271 if err != nil {
272 return nil, err
273 }
274 }
275 return r.getFunctionFilters(true, buff.Nodes...)
276 }
277
278 // getFunctionsFromFunctions returns the set of explicitly provided functions as
279 // Filters
280 func (r RunFns) getFunctionsFromFunctions() ([]kio.Filter, error) {
281 return r.getFunctionFilters(true, r.Functions...)
282 }
283
284 // mergeContainerEnv is container-specific and will merge the envs specified by command line (imperative)
285 // and config file (declarative). If they have same key, the imperative value will be respected.
286 func (r RunFns) mergeContainerEnv(envs []string) []string {
287 imperative := runtimeutil.NewContainerEnvFromStringSlice(r.Env)
288 declarative := runtimeutil.NewContainerEnvFromStringSlice(envs)
289 for key, value := range imperative.EnvVars {
290 declarative.AddKeyValue(key, value)
291 }
292
293 for _, key := range imperative.VarsToExport {
294 declarative.AddKey(key)
295 }
296
297 return declarative.Raw()
298 }
299
300 // mergeExecEnv will merge the envs specified by command line (imperative) and config
301 // file (declarative). If they have same key, the imperative value will be respected.
302 func (r RunFns) mergeExecEnv(envs []string) []string {
303 envMap := map[string]string{}
304
305 for _, env := range append(envs, r.Env...) {
306 res := strings.Split(env, "=")
307 //nolint:gomnd
308 if len(res) == 2 {
309 envMap[res[0]] = res[1]
310 }
311 }
312
313 mergedEnv := []string{}
314 for key, value := range envMap {
315 mergedEnv = append(mergedEnv, fmt.Sprintf("%s=%s", key, value))
316 }
317 // Sort the envs to make the output deterministic
318 sort.Strings(mergedEnv)
319 return mergedEnv
320 }
321
322 func (r RunFns) getFunctionFilters(global bool, fns ...*yaml.RNode) (
323 []kio.Filter, error) {
324 var fltrs []kio.Filter
325 for i := range fns {
326 api := fns[i]
327 spec, err := runtimeutil.GetFunctionSpec(api)
328 if err != nil {
329 return nil, fmt.Errorf("failed to get FunctionSpec: %w", err)
330 }
331 if spec == nil {
332 // resource doesn't have function spec
333 continue
334 }
335 if spec.Container.Network && !r.Network {
336 // TODO(eddiezane): Provide error info about which function needs the network
337 return fltrs, errors.Errorf("network required but not enabled with --network")
338 }
339 // merge envs from imperative and declarative
340 spec.Container.Env = r.mergeContainerEnv(spec.Container.Env)
341
342 c, err := r.functionFilterProvider(*spec, api, user.Current)
343 if err != nil {
344 return nil, err
345 }
346
347 if c == nil {
348 continue
349 }
350 cf, ok := c.(*container.Filter)
351 if ok {
352 if global {
353 cf.Exec.GlobalScope = true
354 }
355 cf.Exec.WorkingDir = r.WorkingDir
356 }
357 fltrs = append(fltrs, c)
358 }
359 return fltrs, nil
360 }
361
362 // sortFns sorts functions so that functions with the longest paths come first
363 func sortFns(buff *kio.PackageBuffer) error {
364 var outerErr error
365 // sort the nodes so that we traverse them depth first
366 // functions deeper in the file system tree should be run first
367 sort.Slice(buff.Nodes, func(i, j int) bool {
368 if err := kioutil.CopyLegacyAnnotations(buff.Nodes[i]); err != nil {
369 return false
370 }
371 if err := kioutil.CopyLegacyAnnotations(buff.Nodes[j]); err != nil {
372 return false
373 }
374 mi, _ := buff.Nodes[i].GetMeta()
375 pi := filepath.ToSlash(mi.Annotations[kioutil.PathAnnotation])
376
377 mj, _ := buff.Nodes[j].GetMeta()
378 pj := filepath.ToSlash(mj.Annotations[kioutil.PathAnnotation])
379
380 // If the path is the same, we decide the ordering based on the
381 // index annotation.
382 if pi == pj {
383 iIndex, err := strconv.Atoi(mi.Annotations[kioutil.IndexAnnotation])
384 if err != nil {
385 outerErr = err
386 return false
387 }
388 jIndex, err := strconv.Atoi(mj.Annotations[kioutil.IndexAnnotation])
389 if err != nil {
390 outerErr = err
391 return false
392 }
393 return iIndex < jIndex
394 }
395
396 if filepath.Base(path.Dir(pi)) == "functions" {
397 // don't count the functions dir, the functions are scoped 1 level above
398 pi = filepath.Dir(path.Dir(pi))
399 } else {
400 pi = filepath.Dir(pi)
401 }
402
403 if filepath.Base(path.Dir(pj)) == "functions" {
404 // don't count the functions dir, the functions are scoped 1 level above
405 pj = filepath.Dir(path.Dir(pj))
406 } else {
407 pj = filepath.Dir(pj)
408 }
409
410 // i is "less" than j (comes earlier) if its depth is greater -- e.g. run
411 // i before j if it is deeper in the directory structure
412 li := len(strings.Split(pi, "/"))
413 if pi == "." {
414 // local dir should have 0 path elements instead of 1
415 li = 0
416 }
417 lj := len(strings.Split(pj, "/"))
418 if pj == "." {
419 // local dir should have 0 path elements instead of 1
420 lj = 0
421 }
422 if li != lj {
423 // use greater-than because we want to sort with the longest
424 // paths FIRST rather than last
425 return li > lj
426 }
427
428 // sort by path names if depths are equal
429 return pi < pj
430 })
431 return outerErr
432 }
433
434 // init initializes the RunFns with a containerFilterProvider.
435 func (r *RunFns) init() {
436 if r.NoFunctionsFromInput == nil {
437 // default no functions from input if any function sources are explicitly provided
438 nfn := len(r.FunctionPaths) > 0 || len(r.Functions) > 0
439 r.NoFunctionsFromInput = &nfn
440 }
441
442 // if no path is specified, default reading from stdin and writing to stdout
443 if r.Path == "" {
444 if r.Output == nil {
445 r.Output = os.Stdout
446 }
447 if r.Input == nil {
448 r.Input = os.Stdin
449 }
450 }
451
452 // functionFilterProvider set the filter provider
453 if r.functionFilterProvider == nil {
454 r.functionFilterProvider = r.ffp
455 }
456
457 // if LogSteps is enabled and LogWriter is not specified, use stderr
458 if r.LogSteps && r.LogWriter == nil {
459 r.LogWriter = os.Stderr
460 }
461 }
462
463 type currentUserFunc func() (*user.User, error)
464
465 // getUIDGID will return "nobody" if asCurrentUser is false. Otherwise
466 // return "uid:gid" according to the return from currentUser function.
467 func getUIDGID(asCurrentUser bool, currentUser currentUserFunc) (string, error) {
468 if !asCurrentUser {
469 return "nobody", nil
470 }
471
472 u, err := currentUser()
473 if err != nil {
474 return "", err
475 }
476 return fmt.Sprintf("%s:%s", u.Uid, u.Gid), nil
477 }
478
479 // ffp provides function filters
480 func (r *RunFns) ffp(spec runtimeutil.FunctionSpec, api *yaml.RNode, currentUser currentUserFunc) (kio.Filter, error) {
481 var resultsFile string
482 if r.ResultsDir != "" {
483 resultsFile = filepath.Join(r.ResultsDir, fmt.Sprintf(
484 "results-%v.yaml", r.resultsCount))
485 atomic.AddUint32(&r.resultsCount, 1)
486 }
487 if !r.DisableContainers && spec.Container.Image != "" {
488 // TODO: Add a test for this behavior
489 uidgid, err := getUIDGID(r.AsCurrentUser, currentUser)
490 if err != nil {
491 return nil, err
492 }
493
494 // Storage mounts can either come from kustomize fn run --mounts,
495 // or from the declarative function mounts field.
496 storageMounts := spec.Container.StorageMounts
497 storageMounts = append(storageMounts, r.StorageMounts...)
498
499 c := container.NewContainer(
500 runtimeutil.ContainerSpec{
501 Image: spec.Container.Image,
502 Network: spec.Container.Network,
503 StorageMounts: storageMounts,
504 Env: spec.Container.Env,
505 },
506 uidgid,
507 )
508 cf := &c
509 cf.Exec.FunctionConfig = api
510 cf.Exec.GlobalScope = r.GlobalScope
511 cf.Exec.ResultsFile = resultsFile
512 cf.Exec.DeferFailure = spec.DeferFailure
513 return cf, nil
514 }
515
516 if r.EnableExec && spec.Exec.Path != "" {
517 ef := &exec.Filter{
518 Path: spec.Exec.Path,
519 Args: spec.Exec.Args,
520 Env: r.mergeExecEnv(spec.Exec.Env),
521 WorkingDir: r.WorkingDir,
522 }
523
524 ef.FunctionConfig = api
525 ef.GlobalScope = r.GlobalScope
526 ef.ResultsFile = resultsFile
527 ef.DeferFailure = spec.DeferFailure
528 return ef, nil
529 }
530
531 return nil, nil
532 }