Debian Codegraph @

kyaml/fn/runtime/runtimeutil/functiontypes.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package runtimeutil
5
6 import (
7 "fmt"
8 "os"
9 "sort"
10 "strings"
11
12 "sigs.k8s.io/kustomize/kyaml/yaml"
13 k8syaml "sigs.k8s.io/yaml"
14 )
15
16 const (
17 FunctionAnnotationKey = "config.kubernetes.io/function"
18 oldFunctionAnnotationKey = "config.k8s.io/function"
19 )
20
21 var functionAnnotationKeys = []string{FunctionAnnotationKey, oldFunctionAnnotationKey}
22
23 // ContainerNetworkName is a type for network name used in container
24 type ContainerNetworkName string
25
26 const (
27 NetworkNameNone ContainerNetworkName = "none"
28 NetworkNameHost ContainerNetworkName = "host"
29 )
30 const defaultEnvValue string = "true"
31
32 // ContainerEnv defines the environment present in a container.
33 type ContainerEnv struct {
34 // EnvVars is a key-value map that will be set as env in container
35 EnvVars map[string]string
36
37 // VarsToExport are only env key. Value will be the value in the host system
38 VarsToExport []string
39 }
40
41 // GetDockerFlags returns docker run style env flags
42 func (ce *ContainerEnv) GetDockerFlags() []string {
43 envs := ce.EnvVars
44 if envs == nil {
45 envs = make(map[string]string)
46 }
47
48 flags := []string{}
49 // return in order to keep consistent among different runs
50 keys := []string{}
51 for k := range envs {
52 keys = append(keys, k)
53 }
54 sort.Strings(keys)
55 for _, key := range keys {
56 flags = append(flags, "-e", key+"="+envs[key])
57 }
58
59 for _, key := range ce.VarsToExport {
60 flags = append(flags, "-e", key)
61 }
62
63 return flags
64 }
65
66 // AddKeyValue adds a key-value pair into the envs
67 func (ce *ContainerEnv) AddKeyValue(key, value string) {
68 if ce.EnvVars == nil {
69 ce.EnvVars = make(map[string]string)
70 }
71 ce.EnvVars[key] = value
72 }
73
74 // HasExportedKey returns true if the key is a exported key
75 func (ce *ContainerEnv) HasExportedKey(key string) bool {
76 for _, k := range ce.VarsToExport {
77 if k == key {
78 return true
79 }
80 }
81 return false
82 }
83
84 // AddKey adds a key into the envs
85 func (ce *ContainerEnv) AddKey(key string) {
86 if !ce.HasExportedKey(key) {
87 ce.VarsToExport = append(ce.VarsToExport, key)
88 }
89 }
90
91 // Raw returns a slice of string which represents the envs.
92 // Example: [foo=bar, baz]
93 func (ce *ContainerEnv) Raw() []string {
94 var ret []string
95 for k, v := range ce.EnvVars {
96 ret = append(ret, k+"="+v)
97 }
98
99 ret = append(ret, ce.VarsToExport...)
100 return ret
101 }
102
103 // NewContainerEnv returns a pointer to a new ContainerEnv
104 func NewContainerEnv() *ContainerEnv {
105 var ce ContainerEnv
106 ce.EnvVars = make(map[string]string)
107 // default envs
108 ce.EnvVars["LOG_TO_STDERR"] = defaultEnvValue
109 ce.EnvVars["STRUCTURED_RESULTS"] = defaultEnvValue
110 return &ce
111 }
112
113 // NewContainerEnvFromStringSlice returns a new ContainerEnv pointer with parsing
114 // input envStr. envStr example: ["foo=bar", "baz"]
115 func NewContainerEnvFromStringSlice(envStr []string) *ContainerEnv {
116 ce := NewContainerEnv()
117 for _, e := range envStr {
118 parts := strings.SplitN(e, "=", 2)
119 if len(parts) == 1 {
120 ce.AddKey(e)
121 } else {
122 ce.AddKeyValue(parts[0], parts[1])
123 }
124 }
125 return ce
126 }
127
128 // FunctionSpec defines a spec for running a function
129 type FunctionSpec struct {
130 DeferFailure bool `json:"deferFailure,omitempty" yaml:"deferFailure,omitempty"`
131
132 // Container is the spec for running a function as a container
133 Container ContainerSpec `json:"container,omitempty" yaml:"container,omitempty"`
134
135 // ExecSpec is the spec for running a function as an executable
136 Exec ExecSpec `json:"exec,omitempty" yaml:"exec,omitempty"`
137 }
138
139 type ExecSpec struct {
140 Path string `json:"path,omitempty" yaml:"path,omitempty"`
141
142 // Args is a slice of args that will be passed as arguments to script
143 Args []string `json:"args,omitempty" yaml:"args,omitempty"`
144
145 // Env is a slice of env string that will be exposed to container
146 Env []string `json:"envs,omitempty" yaml:"envs,omitempty"`
147 }
148
149 // ContainerSpec defines a spec for running a function as a container
150 type ContainerSpec struct {
151 // Image is the container image to run
152 Image string `json:"image,omitempty" yaml:"image,omitempty"`
153
154 // Network defines network specific configuration
155 Network bool `json:"network,omitempty" yaml:"network,omitempty"`
156
157 // Mounts are the storage or directories to mount into the container
158 StorageMounts []StorageMount `json:"mounts,omitempty" yaml:"mounts,omitempty"`
159
160 // Env is a slice of env string that will be exposed to container
161 Env []string `json:"envs,omitempty" yaml:"envs,omitempty"`
162 }
163
164 // StorageMount represents a container's mounted storage option(s)
165 type StorageMount struct {
166 // Type of mount e.g. bind mount, local volume, etc.
167 MountType string `json:"type,omitempty" yaml:"type,omitempty"`
168
169 // Source for the storage to be mounted.
170 // For named volumes, this is the name of the volume.
171 // For anonymous volumes, this field is omitted (empty string).
172 // For bind mounts, this is the path to the file or directory on the host.
173 Src string `json:"src,omitempty" yaml:"src,omitempty"`
174
175 // The path where the file or directory is mounted in the container.
176 DstPath string `json:"dst,omitempty" yaml:"dst,omitempty"`
177
178 // Mount in ReadWrite mode if it's explicitly configured
179 // See https://docs.docker.com/storage/bind-mounts/#use-a-read-only-bind-mount
180 ReadWriteMode bool `json:"rw,omitempty" yaml:"rw,omitempty"`
181 }
182
183 func (s *StorageMount) String() string {
184 mode := ""
185 if !s.ReadWriteMode {
186 mode = ",readonly"
187 }
188 return fmt.Sprintf("type=%s,source=%s,target=%s%s", s.MountType, s.Src, s.DstPath, mode)
189 }
190
191 // GetFunctionSpec returns the FunctionSpec for a resource. Returns
192 // nil if the resource does not have a FunctionSpec.
193 //
194 // The FunctionSpec is read from the resource metadata.annotation
195 // "config.kubernetes.io/function"
196 func GetFunctionSpec(n *yaml.RNode) (*FunctionSpec, error) {
197 meta, err := n.GetMeta()
198 if err != nil {
199 return nil, fmt.Errorf("failed to get ResourceMeta: %w", err)
200 }
201
202 fn, err := getFunctionSpecFromAnnotation(n, meta)
203 if err != nil {
204 return nil, err
205 }
206 if fn != nil {
207 return fn, nil
208 }
209
210 // legacy function specification for backwards compatibility
211 container := meta.Annotations["config.kubernetes.io/container"]
212 if container != "" {
213 return &FunctionSpec{Container: ContainerSpec{Image: container}}, nil
214 }
215 return nil, nil
216 }
217
218 // getFunctionSpecFromAnnotation parses the config function from an annotation
219 // if it is found
220 func getFunctionSpecFromAnnotation(n *yaml.RNode, meta yaml.ResourceMeta) (*FunctionSpec, error) {
221 var fs FunctionSpec
222 for _, s := range functionAnnotationKeys {
223 fn := meta.Annotations[s]
224 if fn != "" {
225 if err := k8syaml.UnmarshalStrict([]byte(fn), &fs); err != nil {
226 return nil, fmt.Errorf("%s unmarshal error: %w", s, err)
227 }
228 return &fs, nil
229 }
230 }
231 n, err := n.Pipe(yaml.Lookup("metadata", "configFn"))
232 if err != nil {
233 return nil, fmt.Errorf("failed to look up metadata.configFn: %w", err)
234 }
235 if yaml.IsMissingOrNull(n) {
236 return nil, nil
237 }
238 s, err := n.String()
239 if err != nil {
240 fmt.Fprintf(os.Stderr, "configFn parse error: %v\n", err)
241 return nil, fmt.Errorf("configFn parse error: %w", err)
242 }
243 if err := k8syaml.UnmarshalStrict([]byte(s), &fs); err != nil {
244 return nil, fmt.Errorf("%s unmarshal error: %w", "configFn", err)
245 }
246 return &fs, nil
247 }
248
249 func StringToStorageMount(s string) StorageMount {
250 m := make(map[string]string)
251 options := strings.Split(s, ",")
252 for _, option := range options {
253 keyVal := strings.SplitN(option, "=", 2)
254 if len(keyVal) == 2 {
255 m[keyVal[0]] = keyVal[1]
256 }
257 }
258 var sm StorageMount
259 for key, value := range m {
260 switch {
261 case key == "type":
262 sm.MountType = value
263 case key == "src" || key == "source":
264 sm.Src = value
265 case key == "dst" || key == "target":
266 sm.DstPath = value
267 case key == "rw" && value == "true":
268 sm.ReadWriteMode = true
269 }
270 }
271 return sm
272 }
273
274 // IsReconcilerFilter filters Resources based on whether or not they are Reconciler Resource.
275 // Resources with an apiVersion starting with '*.gcr.io', 'gcr.io' or 'docker.io' are considered
276 // Reconciler Resources.
277 type IsReconcilerFilter struct {
278 // ExcludeReconcilers if set to true, then Reconcilers will be excluded -- e.g.
279 // Resources with a reconcile container through the apiVersion (gcr.io prefix) or
280 // through the annotations
281 ExcludeReconcilers bool `yaml:"excludeReconcilers,omitempty"`
282
283 // IncludeNonReconcilers if set to true, the NonReconciler will be included.
284 IncludeNonReconcilers bool `yaml:"includeNonReconcilers,omitempty"`
285 }
286
287 // Filter implements kio.Filter
288 func (c *IsReconcilerFilter) Filter(inputs []*yaml.RNode) ([]*yaml.RNode, error) {
289 var out []*yaml.RNode
290 for i := range inputs {
291 functionSpec, err := GetFunctionSpec(inputs[i])
292 if err != nil {
293 return nil, err
294 }
295 isFnResource := functionSpec != nil
296 if isFnResource && !c.ExcludeReconcilers {
297 out = append(out, inputs[i])
298 }
299 if !isFnResource && c.IncludeNonReconcilers {
300 out = append(out, inputs[i])
301 }
302 }
303 return out, nil
304 }