Debian Codegraph @

api/internal/plugins/loader/loader.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package loader
5
6 import (
7 "fmt"
8 "os"
9 "path/filepath"
10 "strings"
11
12 "sigs.k8s.io/kustomize/api/ifc"
13 "sigs.k8s.io/kustomize/api/internal/plugins/builtinhelpers"
14 "sigs.k8s.io/kustomize/api/internal/plugins/execplugin"
15 "sigs.k8s.io/kustomize/api/internal/plugins/fnplugin"
16 "sigs.k8s.io/kustomize/api/konfig"
17 "sigs.k8s.io/kustomize/api/resmap"
18 "sigs.k8s.io/kustomize/api/resource"
19 "sigs.k8s.io/kustomize/api/types"
20 "sigs.k8s.io/kustomize/kyaml/errors"
21 "sigs.k8s.io/kustomize/kyaml/filesys"
22 "sigs.k8s.io/kustomize/kyaml/resid"
23 )
24
25 // Loader loads plugins using a file loader (a different loader).
26 type Loader struct {
27 pc *types.PluginConfig
28 rf *resmap.Factory
29 fs filesys.FileSystem
30
31 // absolutePluginHome caches the location of a valid plugin root directory.
32 // It should only be set once the directory's existence has been confirmed.
33 absolutePluginHome string
34 }
35
36 func NewLoader(
37 pc *types.PluginConfig, rf *resmap.Factory, fs filesys.FileSystem,
38 ) *Loader {
39 return &Loader{pc: pc, rf: rf, fs: fs}
40 }
41
42 // LoaderWithWorkingDir returns loader after setting its working directory.
43 // NOTE: This is not really a new loader since some of the Loader struct fields are pointers.
44 func (l *Loader) LoaderWithWorkingDir(wd string) *Loader {
45 lpc := &types.PluginConfig{
46 PluginRestrictions: l.pc.PluginRestrictions,
47 BpLoadingOptions: l.pc.BpLoadingOptions,
48 FnpLoadingOptions: l.pc.FnpLoadingOptions,
49 HelmConfig: l.pc.HelmConfig,
50 }
51 lpc.FnpLoadingOptions.WorkingDir = wd
52 return &Loader{pc: lpc, rf: l.rf, fs: l.fs}
53 }
54
55 // Config provides the global (not plugin specific) PluginConfig data.
56 func (l *Loader) Config() *types.PluginConfig {
57 return l.pc
58 }
59
60 func (l *Loader) LoadGenerators(
61 ldr ifc.Loader, v ifc.Validator, rm resmap.ResMap) (
62 result []*resmap.GeneratorWithProperties, err error,
63 ) {
64 for _, res := range rm.Resources() {
65 g, err := l.LoadGenerator(ldr, v, res)
66 if err != nil {
67 return nil, fmt.Errorf("failed to load generator: %w", err)
68 }
69 generatorOrigin, err := resource.OriginFromCustomPlugin(res)
70 if err != nil {
71 return nil, fmt.Errorf("failed to get origin from CustomPlugin: %w", err)
72 }
73 result = append(result, &resmap.GeneratorWithProperties{Generator: g, Origin: generatorOrigin})
74 }
75 return result, nil
76 }
77
78 func (l *Loader) LoadGenerator(
79 ldr ifc.Loader, v ifc.Validator, res *resource.Resource,
80 ) (resmap.Generator, error) {
81 c, err := l.loadAndConfigurePlugin(ldr, v, res)
82 if err != nil {
83 return nil, err
84 }
85 g, ok := c.(resmap.Generator)
86 if !ok {
87 return nil, fmt.Errorf("plugin %s not a generator", res.OrgId())
88 }
89 return g, nil
90 }
91
92 func (l *Loader) LoadTransformers(
93 ldr ifc.Loader, v ifc.Validator, rm resmap.ResMap,
94 ) ([]*resmap.TransformerWithProperties, error) {
95 var result []*resmap.TransformerWithProperties
96 for _, res := range rm.Resources() {
97 t, err := l.LoadTransformer(ldr, v, res)
98 if err != nil {
99 return nil, err
100 }
101 transformerOrigin, err := resource.OriginFromCustomPlugin(res)
102 if err != nil {
103 return nil, err
104 }
105 result = append(result, &resmap.TransformerWithProperties{Transformer: t, Origin: transformerOrigin})
106 }
107 return result, nil
108 }
109
110 func (l *Loader) LoadTransformer(
111 ldr ifc.Loader, v ifc.Validator, res *resource.Resource,
112 ) (*resmap.TransformerWithProperties, error) {
113 c, err := l.loadAndConfigurePlugin(ldr, v, res)
114 if err != nil {
115 return nil, err
116 }
117 t, ok := c.(resmap.Transformer)
118 if !ok {
119 return nil, fmt.Errorf("plugin %s not a transformer", res.OrgId())
120 }
121 return &resmap.TransformerWithProperties{Transformer: t}, nil
122 }
123
124 func relativePluginPath(id resid.ResId) string {
125 return filepath.Join(
126 id.Group,
127 id.Version,
128 strings.ToLower(id.Kind))
129 }
130
131 func (l *Loader) AbsolutePluginPath(id resid.ResId) (string, error) {
132 pluginHome, err := l.absPluginHome()
133 if err != nil {
134 return "", err
135 }
136 return filepath.Join(pluginHome, relativePluginPath(id), id.Kind), nil
137 }
138
139 // absPluginHome is the home of kustomize Exec and Go plugins.
140 // Kustomize plugin configuration files are k8s-style objects
141 // containing the fields 'apiVersion' and 'kind', e.g.
142 //
143 // apiVersion: apps/v1
144 // kind: Deployment
145 //
146 // kustomize reads plugin configuration data from a file path
147 // specified in the 'generators:' or 'transformers:' field of a
148 // kustomization file. For Exec and Go plugins, kustomize
149 // uses this data to both locate the plugin and configure it.
150 // Each Exec or Go plugin (its code, its tests, its supporting data
151 // files, etc.) must be housed in its own directory at
152 //
153 // ${absPluginHome}/${pluginApiVersion}/LOWERCASE(${pluginKind})
154 //
155 // where
156 // - ${absPluginHome} is an absolute path, defined below.
157 // - ${pluginApiVersion} is taken from the plugin config file.
158 // - ${pluginKind} is taken from the plugin config file.
159 func (l *Loader) absPluginHome() (string, error) {
160 // External plugins are disabled--return the dummy plugin root.
161 if l.pc.PluginRestrictions != types.PluginRestrictionsNone {
162 return konfig.NoPluginHomeSentinal, nil
163 }
164 // We've already determined plugin home--use the cached value.
165 if l.absolutePluginHome != "" {
166 return l.absolutePluginHome, nil
167 }
168
169 // Check default locations for a valid plugin root, and cache it if found.
170 dir, err := konfig.DefaultAbsPluginHome(l.fs)
171 if err != nil {
172 return "", err
173 }
174 l.absolutePluginHome = dir
175 return l.absolutePluginHome, nil
176 }
177
178 func isBuiltinPlugin(res *resource.Resource) bool {
179 // TODO: the special string should appear in Group, not Version.
180 return res.GetGvk().Group == "" &&
181 res.GetGvk().Version == konfig.BuiltinPluginApiVersion
182 }
183
184 func (l *Loader) loadAndConfigurePlugin(
185 ldr ifc.Loader,
186 v ifc.Validator,
187 res *resource.Resource,
188 ) (c resmap.Configurable, err error) {
189 if isBuiltinPlugin(res) {
190 switch l.pc.BpLoadingOptions {
191 case types.BploLoadFromFileSys:
192 c, err = l.loadPlugin(res)
193 case types.BploUseStaticallyLinked:
194 // Instead of looking for and loading a .so file,
195 // instantiate the plugin from a generated factory
196 // function (see "pluginator"). Being able to do this
197 // is what makes a plugin "builtin".
198 c, err = l.makeBuiltinPlugin(res.GetGvk())
199 default:
200 err = fmt.Errorf(
201 "unknown plugin loader behavior specified: %s %v", res.GetGvk().String(),
202 l.pc.BpLoadingOptions)
203 }
204 } else {
205 switch l.pc.PluginRestrictions {
206 case types.PluginRestrictionsNone:
207 c, err = l.loadPlugin(res)
208 case types.PluginRestrictionsBuiltinsOnly:
209 err = types.NewErrOnlyBuiltinPluginsAllowed(res.OrgId().Kind)
210 default:
211 err = fmt.Errorf(
212 "unknown plugin restriction specified: %v",
213 l.pc.PluginRestrictions)
214 }
215 }
216 if err != nil {
217 return nil, err
218 }
219 yaml, err := res.AsYAML()
220 if err != nil {
221 return nil, errors.WrapPrefixf(err, "marshalling yaml from res %s", res.OrgId())
222 }
223 err = c.Config(resmap.NewPluginHelpers(ldr, v, l.rf, l.pc), yaml)
224 if err != nil {
225 return nil, errors.WrapPrefixf(
226 err, "plugin %s fails configuration", res.OrgId())
227 }
228 return c, nil
229 }
230
231 func (l *Loader) makeBuiltinPlugin(r resid.Gvk) (resmap.Configurable, error) {
232 bpt := builtinhelpers.GetBuiltinPluginType(r.Kind)
233 if f, ok := builtinhelpers.GeneratorFactories[bpt]; ok {
234 return f(), nil
235 }
236 if f, ok := builtinhelpers.TransformerFactories[bpt]; ok {
237 return f(), nil
238 }
239 return nil, errors.Errorf("unable to load builtin %s", r)
240 }
241
242 func (l *Loader) loadPlugin(res *resource.Resource) (resmap.Configurable, error) {
243 spec, err := fnplugin.GetFunctionSpec(res)
244 if err != nil {
245 return nil, fmt.Errorf("loader: %w", err)
246 }
247 if spec != nil {
248 // validation check that function mounts are under the current kustomization directory
249 for _, mount := range spec.Container.StorageMounts {
250 if filepath.IsAbs(mount.Src) {
251 return nil, errors.Errorf("plugin %s with mount path '%s' is not permitted; "+
252 "mount paths must be relative to the current kustomization directory", res.OrgId(), mount.Src)
253 }
254 if strings.HasPrefix(filepath.Clean(mount.Src), "..") {
255 return nil, errors.Errorf("plugin %s with mount path '%s' is not permitted; "+
256 "mount paths must be under the current kustomization directory", res.OrgId(), mount.Src)
257 }
258 }
259 return fnplugin.NewFnPlugin(&l.pc.FnpLoadingOptions), nil
260 }
261 return l.loadExecOrGoPlugin(res.OrgId())
262 }
263
264 func (l *Loader) loadExecOrGoPlugin(resId resid.ResId) (resmap.Configurable, error) {
265 absPluginPath, err := l.AbsolutePluginPath(resId)
266 if err != nil {
267 return nil, err
268 }
269 // First try to load the plugin as an executable.
270 p := execplugin.NewExecPlugin(absPluginPath)
271 if err = p.ErrIfNotExecutable(); err == nil {
272 return p, nil
273 }
274 if !os.IsNotExist(err) {
275 // The file exists, but something else is wrong,
276 // likely it's not executable.
277 // Assume the user forgot to set the exec bit,
278 // and return an error, rather than adding ".so"
279 // to the name and attempting to load it as a Go
280 // plugin, which will likely fail and result
281 // in an obscure message.
282 return nil, err
283 }
284 // Failing the above, try loading it as a Go plugin.
285 c, err := l.loadGoPlugin(resId, absPluginPath+".so")
286 if err != nil {
287 return nil, err
288 }
289 return c, nil
290 }