Debian Codegraph @

cmd/config/internal/commands/run-fns.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package commands
5
6 import (
7 "fmt"
8 "io"
9 "os"
10 "strings"
11
12 "github.com/spf13/cobra"
13 "sigs.k8s.io/kustomize/cmd/config/runner"
14
15 "sigs.k8s.io/kustomize/kyaml/errors"
16 "sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil"
17 "sigs.k8s.io/kustomize/kyaml/runfn"
18 "sigs.k8s.io/kustomize/kyaml/yaml"
19
20 "sigs.k8s.io/kustomize/cmd/config/internal/generateddocs/commands"
21 )
22
23 // GetRunFnRunner returns a RunFnRunner.
24 func GetRunFnRunner(name string) *RunFnRunner {
25 r := &RunFnRunner{}
26 c := &cobra.Command{
27 Use: "run [DIR]",
28 Short: commands.RunFnsShort,
29 Long: commands.RunFnsLong,
30 Example: commands.RunFnsExamples,
31 RunE: r.runE,
32 PreRunE: r.preRunE,
33 }
34 runner.FixDocs(name, c)
35 c.Flags().BoolVar(&r.IncludeSubpackages, "include-subpackages", true,
36 "also print resources from subpackages.")
37 r.Command = c
38 r.Command.Flags().BoolVar(
39 &r.DryRun, "dry-run", false, "print results to stdout")
40 r.Command.Flags().BoolVar(
41 &r.GlobalScope, "global-scope", false, "set global scope for functions.")
42 r.Command.Flags().StringSliceVar(
43 &r.FnPaths, "fn-path", []string{},
44 "read functions from these directories instead of the configuration directory.")
45 r.Command.Flags().StringVar(
46 &r.Image, "image", "",
47 "run this image as a function instead of discovering them.")
48 // NOTE: exec plugins execute arbitrary code -- never change the default value of this flag!!!
49 r.Command.Flags().BoolVar(
50 &r.EnableExec, "enable-exec", false, /*do not change!*/
51 "enable support for exec functions -- note: exec functions run arbitrary code -- do not use for untrusted configs!!! (Alpha)")
52 r.Command.Flags().StringVar(
53 &r.ExecPath, "exec-path", "", "run an executable as a function. (Alpha)")
54
55 r.Command.Flags().StringVar(
56 &r.ResultsDir, "results-dir", "", "write function results to this dir")
57
58 r.Command.Flags().BoolVar(
59 &r.Network, "network", false, "enable network access for functions that declare it")
60 r.Command.Flags().StringArrayVar(
61 &r.Mounts, "mount", []string{},
62 "a list of storage options read from the filesystem")
63 r.Command.Flags().BoolVar(
64 &r.LogSteps, "log-steps", false, "log steps to stderr")
65 r.Command.Flags().StringArrayVarP(
66 &r.Env, "env", "e", []string{},
67 "a list of environment variables to be used by functions")
68 r.Command.Flags().BoolVar(
69 &r.AsCurrentUser, "as-current-user", false, "use the uid and gid of the command executor to run the function in the container")
70
71 return r
72 }
73
74 func RunCommand(name string) *cobra.Command {
75 return GetRunFnRunner(name).Command
76 }
77
78 // RunFnRunner contains the run function
79 type RunFnRunner struct {
80 IncludeSubpackages bool
81 Command *cobra.Command
82 DryRun bool
83 GlobalScope bool
84 FnPaths []string
85 Image string
86 StarPath string
87 StarURL string
88 StarName string
89 EnableExec bool
90 ExecPath string
91 RunFns runfn.RunFns
92 ResultsDir string
93 Network bool
94 Mounts []string
95 LogSteps bool
96 Env []string
97 AsCurrentUser bool
98 }
99
100 func (r *RunFnRunner) runE(c *cobra.Command, args []string) error {
101 return runner.HandleError(c, r.RunFns.Execute())
102 }
103
104 // getContainerFunctions parses the commandline flags and arguments into explicit
105 // Functions to run.
106 func (r *RunFnRunner) getContainerFunctions(dataItems []string) (
107 []*yaml.RNode, error) {
108 if r.Image == "" && r.StarPath == "" && r.ExecPath == "" && r.StarURL == "" {
109 return nil, nil
110 }
111
112 res, err := buildFnConfigResource(dataItems)
113 if err != nil {
114 return nil, err
115 }
116
117 // create the function spec to set as an annotation
118 var fnAnnotation *yaml.RNode
119 switch {
120 case r.Image != "":
121 fnAnnotation, err = fnAnnotationForImage(r.Image, r.Network)
122 case r.EnableExec && r.ExecPath != "":
123 fnAnnotation, err = fnAnnotationForExec(r.ExecPath)
124 }
125 if err != nil {
126 return nil, err
127 }
128
129 // set the function annotation on the function config, so that it is parsed by RunFns
130 value, err := fnAnnotation.String()
131 if err != nil {
132 return nil, errors.Wrap(err)
133 }
134 err = res.PipeE(
135 yaml.LookupCreate(yaml.MappingNode, "metadata", "annotations"),
136 yaml.SetField(runtimeutil.FunctionAnnotationKey, yaml.NewScalarRNode(value)))
137 if err != nil {
138 return nil, errors.Wrap(err)
139 }
140
141 return []*yaml.RNode{res}, nil
142 }
143
144 func buildFnConfigResource(dataItems []string) (*yaml.RNode, error) {
145 // create the function config
146 rc, err := yaml.Parse(`
147 metadata:
148 name: function-input
149 data: {}
150 `)
151 if err != nil {
152 return nil, err
153 }
154
155 // default the function config kind to ConfigMap, this may be overridden
156 var kind = "ConfigMap"
157 var version = "v1"
158
159 // populate the function config with data. this is a convention for functions
160 // to be more commandline friendly
161 if len(dataItems) > 0 {
162 dataField, err := rc.Pipe(yaml.Lookup("data"))
163 if err != nil {
164 return nil, err
165 }
166 for i, s := range dataItems {
167 kv := strings.SplitN(s, "=", 2)
168 if i == 0 && len(kv) == 1 {
169 // first argument may be the kind
170 kind = s
171 continue
172 }
173 if len(kv) != 2 {
174 return nil, fmt.Errorf("args must have keys and values separated by =")
175 }
176 // do not set style since function should determine tag and style
177 err := dataField.PipeE(
178 yaml.FieldSetter{Name: kv[0], Value: yaml.NewScalarRNode(kv[1]), OverrideStyle: true})
179 if err != nil {
180 return nil, err
181 }
182 }
183 }
184 err = rc.PipeE(yaml.SetField("kind", yaml.NewScalarRNode(kind)))
185 if err != nil {
186 return nil, err
187 }
188 err = rc.PipeE(yaml.SetField("apiVersion", yaml.NewScalarRNode(version)))
189 if err != nil {
190 return nil, err
191 }
192 return rc, nil
193 }
194
195 func fnAnnotationForExec(path string) (*yaml.RNode, error) {
196 fn, err := yaml.Parse(`exec: {}`)
197 if err != nil {
198 return nil, errors.Wrap(err)
199 }
200
201 err = fn.PipeE(
202 yaml.Lookup("exec"),
203 yaml.SetField("path", yaml.NewScalarRNode(path)))
204 if err != nil {
205 return nil, errors.Wrap(err)
206 }
207 return fn, nil
208 }
209
210 func fnAnnotationForImage(image string, enableNetwork bool) (*yaml.RNode, error) {
211 fn, err := yaml.Parse(`container: {}`)
212 if err != nil {
213 return nil, errors.Wrap(err)
214 }
215 // TODO: add support network, volumes, etc based on flag values
216 err = fn.PipeE(
217 yaml.Lookup("container"),
218 yaml.SetField("image", yaml.NewScalarRNode(image)))
219 if err != nil {
220 return nil, errors.Wrap(err)
221 }
222 if enableNetwork {
223 n := &yaml.Node{
224 Kind: yaml.ScalarNode,
225 Value: "true",
226 Tag: yaml.NodeTagBool,
227 }
228 err = fn.PipeE(
229 yaml.Lookup("container"),
230 yaml.SetField("network", yaml.NewRNode(n)))
231 if err != nil {
232 return nil, errors.Wrap(err)
233 }
234 }
235 return fn, nil
236 }
237
238 func toStorageMounts(mounts []string) []runtimeutil.StorageMount {
239 var sms []runtimeutil.StorageMount
240 for _, mount := range mounts {
241 sms = append(sms, runtimeutil.StringToStorageMount(mount))
242 }
243 return sms
244 }
245
246 func (r *RunFnRunner) preRunE(c *cobra.Command, args []string) error {
247 if !r.EnableExec && r.ExecPath != "" {
248 return errors.Errorf("must specify --enable-exec with --exec-path")
249 }
250
251 if c.ArgsLenAtDash() >= 0 && r.Image == "" && !(r.EnableExec && r.ExecPath != "") {
252 return errors.Errorf("must specify --image")
253 }
254
255 var dataItems []string
256 if c.ArgsLenAtDash() >= 0 {
257 dataItems = args[c.ArgsLenAtDash():]
258 args = args[:c.ArgsLenAtDash()]
259 }
260 if len(args) > 1 {
261 return errors.Errorf("0 or 1 arguments supported, function arguments go after '--'")
262 }
263
264 fns, err := r.getContainerFunctions(dataItems)
265 if err != nil {
266 return err
267 }
268
269 // set the output to stdout if in dry-run mode or no arguments are specified
270 var output io.Writer
271 var input io.Reader
272 if len(args) == 0 {
273 output = c.OutOrStdout()
274 input = c.InOrStdin()
275 } else if r.DryRun {
276 output = c.OutOrStdout()
277 }
278
279 // set the path if specified as an argument
280 var path string
281 if len(args) == 1 {
282 // argument is the directory
283 path = args[0]
284 }
285
286 // parse mounts to set storageMounts
287 storageMounts := toStorageMounts(r.Mounts)
288
289 wd, err := os.Getwd()
290 if err != nil {
291 return err
292 }
293
294 r.RunFns = runfn.RunFns{
295 FunctionPaths: r.FnPaths,
296 GlobalScope: r.GlobalScope,
297 Functions: fns,
298 Output: output,
299 Input: input,
300 Path: path,
301 Network: r.Network,
302 EnableExec: r.EnableExec,
303 StorageMounts: storageMounts,
304 ResultsDir: r.ResultsDir,
305 LogSteps: r.LogSteps,
306 Env: r.Env,
307 AsCurrentUser: r.AsCurrentUser,
308 WorkingDir: wd,
309 }
310
311 // don't consider args for the function
312 return nil
313 }