Debian Codegraph @

api/internal/plugins/fnplugin/fnplugin.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package fnplugin
5
6 import (
7 "bytes"
8 "fmt"
9
10 "sigs.k8s.io/kustomize/kyaml/errors"
11
12 "sigs.k8s.io/kustomize/api/internal/plugins/utils"
13 "sigs.k8s.io/kustomize/api/resmap"
14 "sigs.k8s.io/kustomize/api/resource"
15 "sigs.k8s.io/kustomize/api/types"
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
21 // FnPlugin is the struct to hold function information
22 type FnPlugin struct {
23 // Function runner
24 runFns runfn.RunFns
25
26 // Plugin configuration data.
27 cfg []byte
28
29 // Plugin name cache for error output
30 pluginName string
31
32 // PluginHelpers
33 h *resmap.PluginHelpers
34 }
35
36 func bytesToRNode(yml []byte) (*yaml.RNode, error) {
37 rnode, err := yaml.Parse(string(yml))
38 if err != nil {
39 return nil, err
40 }
41 return rnode, nil
42 }
43
44 func resourceToRNode(res *resource.Resource) (*yaml.RNode, error) {
45 yml, err := res.AsYAML()
46 if err != nil {
47 return nil, err
48 }
49
50 return bytesToRNode(yml)
51 }
52
53 // GetFunctionSpec return function spec is there is. Otherwise return nil
54 func GetFunctionSpec(res *resource.Resource) (*runtimeutil.FunctionSpec, error) {
55 rnode, err := resourceToRNode(res)
56 if err != nil {
57 return nil, fmt.Errorf("could not convert resource to RNode: %w", err)
58 }
59 functionSpec, err := runtimeutil.GetFunctionSpec(rnode)
60 if err != nil {
61 return nil, fmt.Errorf("failed to get FunctionSpec: %w", err)
62 }
63 return functionSpec, nil
64 }
65
66 func toStorageMounts(mounts []string) []runtimeutil.StorageMount {
67 var sms []runtimeutil.StorageMount
68 for _, mount := range mounts {
69 sms = append(sms, runtimeutil.StringToStorageMount(mount))
70 }
71 return sms
72 }
73
74 // NewFnPlugin creates a FnPlugin struct
75 func NewFnPlugin(o *types.FnPluginLoadingOptions) *FnPlugin {
76 return &FnPlugin{
77 runFns: runfn.RunFns{
78 Functions: []*yaml.RNode{},
79 Network: o.Network,
80 EnableExec: o.EnableExec,
81 StorageMounts: toStorageMounts(o.Mounts),
82 Env: o.Env,
83 AsCurrentUser: o.AsCurrentUser,
84 WorkingDir: o.WorkingDir,
85 },
86 }
87 }
88
89 // Cfg returns function config
90 func (p *FnPlugin) Cfg() []byte {
91 return p.cfg
92 }
93
94 // Config is called by kustomize to pass-in config information
95 func (p *FnPlugin) Config(h *resmap.PluginHelpers, config []byte) error {
96 p.h = h
97 p.cfg = config
98
99 fn, err := bytesToRNode(p.cfg)
100 if err != nil {
101 return err
102 }
103
104 meta, err := fn.GetMeta()
105 if err != nil {
106 return err
107 }
108
109 p.pluginName = fmt.Sprintf("api: %s, kind: %s, name: %s",
110 meta.APIVersion, meta.Kind, meta.Name)
111
112 return nil
113 }
114
115 // Generate is called when run as generator
116 func (p *FnPlugin) Generate() (resmap.ResMap, error) {
117 output, err := p.invokePlugin(nil)
118 if err != nil {
119 return nil, err
120 }
121 rm, err := p.h.ResmapFactory().NewResMapFromBytes(output)
122 if err != nil {
123 return nil, err
124 }
125 return utils.UpdateResourceOptions(rm)
126 }
127
128 // Transform is called when run as transformer
129 func (p *FnPlugin) 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.pluginName, p.h, output, rm)
150 }
151
152 func injectAnnotation(input *yaml.RNode, k, v string) error {
153 err := input.PipeE(yaml.SetAnnotation(k, v))
154 if err != nil {
155 return err
156 }
157 return nil
158 }
159
160 // invokePlugin uses Function runner to run function as plugin
161 func (p *FnPlugin) invokePlugin(input []byte) ([]byte, error) {
162 // get function config rnode
163 functionConfig, err := bytesToRNode(p.cfg)
164 if err != nil {
165 return nil, err
166 }
167
168 // This annotation will let kustomize ingnore this item in output
169 err = injectAnnotation(functionConfig, "config.kubernetes.io/local-config", "true")
170 if err != nil {
171 return nil, err
172 }
173 // we need to add config as input for generators. Some of them don't work with FunctionConfig
174 // and in addition kio.Pipeline won't create anything if there are no objects
175 // see https://github.com/kubernetes-sigs/kustomize/blob/master/kyaml/kio/kio.go#L93
176 // Since we added `local-config` annotation so it will be ignored in generator output
177 // TODO(donnyxia): This is actually not used by generator and only used to bypass a kio limitation.
178 // Need better solution.
179 if input == nil {
180 yml, err := functionConfig.String()
181 if err != nil {
182 return nil, err
183 }
184 input = []byte(yml)
185 }
186
187 // Configure and Execute Fn. We don't need to convert resources to ResourceList here
188 // because function runtime will do that. See kyaml/fn/runtime/runtimeutil/runtimeutil.go
189 var ouputBuffer bytes.Buffer
190 p.runFns.Input = bytes.NewReader(input)
191 p.runFns.Functions = append(p.runFns.Functions, functionConfig)
192 p.runFns.Output = &ouputBuffer
193
194 err = p.runFns.Execute()
195 if err != nil {
196 return nil, errors.WrapPrefixf(
197 err, "couldn't execute function")
198 }
199
200 return ouputBuffer.Bytes(), nil
201 }