Debian Codegraph @

api/internal/plugins/execplugin/execplugin.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package execplugin
5
6 import (
7 "bytes"
8 "fmt"
9 "log"
10 "os"
11 "os/exec"
12 "runtime"
13 "strings"
14
15 "sigs.k8s.io/kustomize/api/internal/plugins/utils"
16 "sigs.k8s.io/kustomize/api/resmap"
17 "sigs.k8s.io/kustomize/kyaml/errors"
18 "sigs.k8s.io/yaml"
19 )
20
21 const (
22 tmpConfigFilePrefix = "kust-plugin-config-"
23 maxArgStringLength = 131071
24 )
25
26 // ExecPlugin record the name and args of an executable
27 // It triggers the executable generator and transformer
28 type ExecPlugin struct {
29 // absolute path of the executable
30 path string
31
32 // Optional command line arguments to the executable
33 // pulled from specially named fields in cfg.
34 // This is for executables that don't want to parse YAML.
35 args []string
36
37 // Plugin configuration data.
38 cfg []byte
39
40 // PluginHelpers
41 h *resmap.PluginHelpers
42 }
43
44 func NewExecPlugin(p string) *ExecPlugin {
45 return &ExecPlugin{path: p}
46 }
47
48 func (p *ExecPlugin) ErrIfNotExecutable() error {
49 f, err := os.Stat(p.path)
50 if err != nil {
51 return err
52 }
53 // In Windows, it is not possible to determine whether a
54 // file is executable through file mode.
55 // TODO: provide for setting the executable FileMode bit on Windows
56 // The (fs *fileStat) Mode() (m FileMode) {} function in
57 // https://golang.org/src/os/types_windows.go
58 // lacks the ability to set the FileMode executable bit in response
59 // to file data on Windows.
60 if f.Mode()&0111 == 0000 && runtime.GOOS != "windows" {
61 return fmt.Errorf("unexecutable plugin at: %s", p.path)
62 }
63 return nil
64 }
65
66 func (p *ExecPlugin) Path() string {
67 return p.path
68 }
69
70 func (p *ExecPlugin) Args() []string {
71 return p.args
72 }
73
74 func (p *ExecPlugin) Cfg() []byte {
75 return p.cfg
76 }
77
78 func (p *ExecPlugin) Config(h *resmap.PluginHelpers, config []byte) error {
79 p.h = h
80 p.cfg = config
81 return p.processOptionalArgsFields()
82 }
83
84 type argsConfig struct {
85 ArgsOneLiner string `json:"argsOneLiner,omitempty" yaml:"argsOneLiner,omitempty"`
86 ArgsFromFile string `json:"argsFromFile,omitempty" yaml:"argsFromFile,omitempty"`
87 }
88
89 func (p *ExecPlugin) processOptionalArgsFields() error {
90 var c argsConfig
91 err := yaml.Unmarshal(p.cfg, &c)
92 if err != nil {
93 return err
94 }
95 if c.ArgsOneLiner != "" {
96 argsTolenSlice, err := ShlexSplit(c.ArgsOneLiner)
97 if err != nil {
98 return fmt.Errorf("failed to parse argsOneLiner: %w", err)
99 }
100 p.args = argsTolenSlice
101 }
102 if c.ArgsFromFile != "" {
103 content, err := p.h.Loader().Load(c.ArgsFromFile)
104 if err != nil {
105 return err
106 }
107 for _, x := range strings.Split(string(content), "\n") {
108 x := strings.TrimLeft(x, " ")
109 if x != "" {
110 p.args = append(p.args, x)
111 }
112 }
113 }
114 return nil
115 }
116
117 func (p *ExecPlugin) Generate() (resmap.ResMap, error) {
118 output, err := p.invokePlugin(nil)
119 if err != nil {
120 return nil, err
121 }
122 rm, err := p.h.ResmapFactory().NewResMapFromBytes(output)
123 if err != nil {
124 return nil, err
125 }
126 return utils.UpdateResourceOptions(rm)
127 }
128
129 func (p *ExecPlugin) Transform(rm resmap.ResMap) error {
130 // add ResIds as annotations to all objects so that we can add them back
131 inputRM, err := utils.GetResMapWithIDAnnotation(rm)
132 if err != nil {
133 return err
134 }
135
136 // encode the ResMap so it can be fed to the plugin
137 resources, err := inputRM.AsYaml()
138 if err != nil {
139 return err
140 }
141
142 // invoke the plugin with resources as the input
143 output, err := p.invokePlugin(resources)
144 if err != nil {
145 return fmt.Errorf("%v %s", err, string(output))
146 }
147
148 // update the original ResMap based on the output
149 return utils.UpdateResMapValues(p.path, p.h, output, rm)
150 }
151
152 // invokePlugin writes plugin config to a temp file, then
153 // passes the full temp file path as the first arg to a process
154 // running the plugin binary. Process output is returned.
155 func (p *ExecPlugin) invokePlugin(input []byte) ([]byte, error) {
156 f, err := os.CreateTemp("", tmpConfigFilePrefix)
157 if err != nil {
158 return nil, errors.WrapPrefixf(
159 err, "creating tmp plugin config file")
160 }
161 _, err = f.Write(p.cfg)
162 if err != nil {
163 return nil, errors.WrapPrefixf(
164 err, "writing plugin config to %s", f.Name())
165 }
166 err = f.Close()
167 if err != nil {
168 return nil, errors.WrapPrefixf(
169 err, "closing plugin config file %s", f.Name())
170 }
171 cmd := exec.Command(
172 p.path, append([]string{f.Name()}, p.args...)...)
173 cmd.Env = p.getEnv()
174 cmd.Stdin = bytes.NewReader(input)
175 var stdErr bytes.Buffer
176 cmd.Stderr = &stdErr
177 if _, err := os.Stat(p.h.Loader().Root()); err == nil {
178 cmd.Dir = p.h.Loader().Root()
179 }
180 result, err := cmd.Output()
181 if err != nil {
182 return nil, errors.WrapPrefixf(
183 fmt.Errorf("failure in plugin configured via %s; %w", f.Name(), err),
184 "%s", stdErr.String())
185 }
186 return result, os.Remove(f.Name())
187 }
188
189 func (p *ExecPlugin) getEnv() []string {
190 env := os.Environ()
191 pluginConfigString := "KUSTOMIZE_PLUGIN_CONFIG_STRING=" + string(p.cfg)
192 if len(pluginConfigString) <= maxArgStringLength {
193 env = append(env, pluginConfigString)
194 } else {
195 log.Printf("KUSTOMIZE_PLUGIN_CONFIG_STRING exceeds hard limit of %d characters, the environment variable "+
196 "will be omitted", maxArgStringLength)
197 }
198 pluginConfigRoot := "KUSTOMIZE_PLUGIN_CONFIG_ROOT=" + p.h.Loader().Root()
199 if len(pluginConfigRoot) <= maxArgStringLength {
200 env = append(env, pluginConfigRoot)
201 } else {
202 log.Printf("KUSTOMIZE_PLUGIN_CONFIG_ROOT exceeds hard limit of %d characters, the environment variable "+
203 "will be omitted", maxArgStringLength)
204 }
205 return env
206 }