forked from kubernetes-sigs/kustomize
/
set.go
540 lines (476 loc) · 15.4 KB
/
set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package setters2
import (
"fmt"
"strings"
"text/template"
"k8s.io/kube-openapi/pkg/validation/spec"
"k8s.io/kube-openapi/pkg/validation/strfmt"
"k8s.io/kube-openapi/pkg/validation/validate"
"sigs.k8s.io/kustomize/kyaml/errors"
"sigs.k8s.io/kustomize/kyaml/fieldmeta"
goyaml "sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/go-yaml/yaml"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/kio/kioutil"
"sigs.k8s.io/kustomize/kyaml/openapi"
"sigs.k8s.io/kustomize/kyaml/sets"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// Set sets resource field values from an OpenAPI setter
type Set struct {
// Name is the name of the setter to set on the object. i.e. matches the x-k8s-cli.setter.name
// of the setter that should have its value applied to fields which reference it.
Name string
// Count is the number of fields that were updated by calling Filter
Count int
// SetAll if set to true will set all setters regardless of name
SetAll bool
SettersSchema *spec.Schema
}
// Filter implements Set as a yaml.Filter
func (s *Set) Filter(object *yaml.RNode) (*yaml.RNode, error) {
return object, accept(s, object, s.SettersSchema)
}
// isMatch returns true if the setter with name should have the field
// value set
func (s *Set) isMatch(name string) bool {
return s.SetAll || s.Name == name
}
func (s *Set) visitMapping(_ *yaml.RNode, p string, _ *openapi.ResourceSchema) error {
return nil
}
// visitSequence will perform setters for sequences
func (s *Set) visitSequence(object *yaml.RNode, p string, schema *openapi.ResourceSchema) error {
ext, err := getExtFromComment(schema)
if err != nil {
return err
}
if ext == nil || ext.Setter == nil || !s.isMatch(ext.Setter.Name) ||
len(ext.Setter.ListValues) == 0 {
// setter was not invoked for this sequence
return nil
}
s.Count++
// set the values on the sequences
var elements []*yaml.Node
if len(ext.Setter.ListValues) > 0 {
if err := validateAgainstSchema(ext, schema.Schema); err != nil {
return err
}
}
for i := range ext.Setter.ListValues {
v := ext.Setter.ListValues[i]
n := yaml.NewScalarRNode(v).YNode()
n.Style = yaml.DoubleQuotedStyle
elements = append(elements, n)
}
object.YNode().Content = elements
object.YNode().Style = yaml.FoldedStyle
return nil
}
// visitScalar
func (s *Set) visitScalar(object *yaml.RNode, p string, oa, settersSchema *openapi.ResourceSchema) error {
// get the openAPI for this field describing how to apply the setter
ext, err := getExtFromComment(settersSchema)
if err != nil {
return err
}
if ext == nil {
return nil
}
var k8sSchema *spec.Schema
if oa != nil {
k8sSchema = oa.Schema
}
// perform a direct set of the field if it matches
ok, err := s.set(object, ext, k8sSchema, settersSchema.Schema)
if err != nil {
return err
}
if ok {
s.Count++
return nil
}
// perform a substitution of the field if it matches
sub, err := s.substitute(object, ext)
if err != nil {
return err
}
if sub {
s.Count++
}
return nil
}
// substitute updates the value of field from ext if ext contains a substitution that
// depends on a setter whose name matches s.Name.
func (s *Set) substitute(field *yaml.RNode, ext *CliExtension) (bool, error) {
// check partial setters to see if they contain the setter as part of a
// substitution
if ext.Substitution == nil {
return false, nil
}
// track the visited nodes to detect cycles in nested substitutions
visited := sets.String{}
// nameMatch indicates if the input substitution depends on the specified setter,
// the substitution in ext is parsed recursively and if the setter in Set is hit while
// parsing, it indicates the match
nameMatch := false
res, err := s.substituteUtil(ext, visited, &nameMatch)
if err != nil {
return false, err
}
if !nameMatch {
// doesn't depend on the setter, don't modify its value
return false, nil
}
field.YNode().Value = res
// substitutions are always strings
field.YNode().Tag = yaml.NodeTagString
return true, nil
}
// substituteUtil recursively parses nested substitutions in ext and sets the setter value
// returns error if cyclic substitution is detected or any other unexpected errors
func (s *Set) substituteUtil(ext *CliExtension, visited sets.String, nameMatch *bool) (string, error) {
// check if the substitution has already been visited and throw error as cycles
// are not allowed in nested substitutions
if visited.Has(ext.Substitution.Name) {
return "", errors.Errorf(
"cyclic substitution detected with name " + ext.Substitution.Name)
}
visited.Insert(ext.Substitution.Name)
pattern := ext.Substitution.Pattern
// substitute each setter into the pattern to get the new value
// if substitution references to another substitution, recursively
// process the nested substitutions to replace the pattern with setter values
for _, v := range ext.Substitution.Values {
if v.Ref == "" {
return "", errors.Errorf(
"missing reference on substitution " + ext.Substitution.Name)
}
ref, err := spec.NewRef(v.Ref)
if err != nil {
return "", errors.Wrap(err)
}
def, err := openapi.Resolve(&ref, s.SettersSchema) // resolve the def to its openAPI def
if err != nil {
return "", errors.Wrap(err)
}
defExt, err := GetExtFromSchema(def) // parse the extension out of the openAPI
if err != nil {
return "", errors.Wrap(err)
}
if defExt.Substitution != nil {
// parse recursively if it reference is substitution
substVal, err := s.substituteUtil(defExt, visited, nameMatch)
if err != nil {
return "", err
}
pattern = strings.ReplaceAll(pattern, v.Marker, substVal)
continue
}
// if code reaches this point, this is a setter, so validate the setter schema
if err := validateAgainstSchema(defExt, def); err != nil {
return "", err
}
if s.isMatch(defExt.Setter.Name) {
// the substitution depends on the specified setter
*nameMatch = true
}
if val, found := defExt.Setter.EnumValues[defExt.Setter.Value]; found {
// the setter has an enum-map. we should replace the marker with the
// enum value looked up from the map rather than the enum key
pattern = strings.ReplaceAll(pattern, v.Marker, val)
} else {
pattern = strings.ReplaceAll(pattern, v.Marker, defExt.Setter.Value)
}
}
return pattern, nil
}
// set applies the value from ext to field if its name matches s.Name
func (s *Set) set(field *yaml.RNode, ext *CliExtension, k8sSch, sch *spec.Schema) (bool, error) {
// check full setter
if ext.Setter == nil || !s.isMatch(ext.Setter.Name) {
return false, nil
}
if err := validateAgainstSchema(ext, sch); err != nil {
return false, err
}
if val, found := ext.Setter.EnumValues[ext.Setter.Value]; found {
// the setter has an enum-map. we should replace the marker with the
// enum value looked up from the map rather than the enum key
field.YNode().Value = val
return true, nil
}
// this has a full setter, set its value
field.YNode().Value = ext.Setter.Value
// format the node so it is quoted if it is a string. If there is
// type information on the setter schema, we use it. Otherwise we
// fall back to the field schema if it exists.
if len(sch.Type) > 0 {
yaml.FormatNonStringStyle(field.YNode(), *sch)
} else if k8sSch != nil {
yaml.FormatNonStringStyle(field.YNode(), *k8sSch)
}
return true, nil
}
// validateAgainstSchema validates the input setter value against user provided
// openAI schema
func validateAgainstSchema(ext *CliExtension, sch *spec.Schema) error {
fixSchemaTypes(sch)
sc := spec.Schema{}
sc.Properties = map[string]spec.Schema{}
sc.Properties[ext.Setter.Name] = *sch
var inputYAML string
if len(ext.Setter.ListValues) > 0 {
// tmplText contains the template we will use to produce a yaml
// document that we can use for validation.
var tmplText string
if sch.Items != nil && sch.Items.Schema != nil &&
shouldQuoteSetterValue(ext.Setter.ListValues, sch.Items.Schema.Type) {
// If string is one of the legal types for the value, we
// output it with quotes in the yaml document to make sure it
// is later parsed as a string.
tmplText = `{{.key}}:{{block "list" .values}}{{"\n"}}{{range .}}{{printf "- %q\n" .}}{{end}}{{end}}`
} else {
// If string is not specifically set as the type, we just
// let the yaml unmarshaller detect the correct type. Thus, we
// do not add quotes around the value.
tmplText = `{{.key}}:{{block "list" .values}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
}
tmpl, err := template.New("validator").Parse(tmplText)
if err != nil {
return err
}
var builder strings.Builder
err = tmpl.Execute(&builder, map[string]interface{}{
"key": ext.Setter.Name,
"values": ext.Setter.ListValues,
})
if err != nil {
return err
}
inputYAML = builder.String()
} else {
var format string
// Only add quotes around the value is string is one of the
// types in the schema.
if shouldQuoteSetterValue([]string{ext.Setter.Value}, sch.Type) {
format = "%s: \"%s\""
} else {
format = "%s: %s"
}
inputYAML = fmt.Sprintf(format, ext.Setter.Name, ext.Setter.Value)
}
input := map[string]interface{}{}
err := goyaml.Unmarshal([]byte(inputYAML), &input)
if err != nil {
return err
}
err = validate.AgainstSchema(&sc, input, strfmt.Default)
if err != nil {
return errors.Errorf("The input value doesn't validate against provided OpenAPI schema: %v\n", err.Error())
}
return nil
}
// shouldQuoteSetterValue returns true if string is one of the types in the
// schema, or if the value ends in a ':' (the yaml parser gets confused by
// the ':' at the end unless the value is quoted)
func shouldQuoteSetterValue(a []string, schType spec.StringOrArray) bool {
if schType.Contains("string") {
return true
}
for _, s := range a {
if strings.HasSuffix(s, ":") {
return true
}
}
return false
}
// fixSchemaTypes traverses the schema and checks for some common
// errors for the type field. This currently involves users using
// 'int' instead of 'integer' and 'bool' instead of 'boolean'. Early versions
// of setters didn't validate this, so there are users that have invalid
// types in their packages.
func fixSchemaTypes(sc *spec.Schema) {
for i := range sc.Type {
currentType := sc.Type[i]
if currentType == "int" {
sc.Type[i] = "integer"
}
if currentType == "bool" {
sc.Type[i] = "boolean"
}
}
if items := sc.Items; items != nil {
if items.Schema != nil {
fixSchemaTypes(items.Schema)
}
for i := range items.Schemas {
schema := items.Schemas[i]
fixSchemaTypes(&schema)
}
}
}
// SetOpenAPI updates a setter value
type SetOpenAPI struct {
// Name is the name of the setter to add
Name string `yaml:"name"`
// Value is the current value of the setter
Value string `yaml:"value"`
// ListValue is the current value for a list of items
ListValues []string `yaml:"listValue"`
Description string `yaml:"description"`
SetBy string `yaml:"setBy"`
IsSet bool `yaml:"isSet"`
}
// UpdateFile updates the OpenAPI definitions in a file with the given setter value.
func (s SetOpenAPI) UpdateFile(path string) error {
return yaml.UpdateFile(s, path)
}
func (s SetOpenAPI) Filter(object *yaml.RNode) (*yaml.RNode, error) {
key := fieldmeta.SetterDefinitionPrefix + s.Name
oa, err := object.Pipe(yaml.Lookup("openAPI", "definitions", key))
if err != nil {
return nil, err
}
if oa == nil {
return nil, errors.Errorf("setter %q is not found", s.Name)
}
def, err := oa.Pipe(yaml.Lookup("x-k8s-cli", "setter"))
if err != nil {
return nil, err
}
if def == nil {
return nil, errors.Errorf("setter %q is not found", s.Name)
}
// record the OpenAPI type for the setter
var t string
if n := oa.Field("type"); n != nil {
t = n.Value.YNode().Value
}
// if the setter contains an enumValues map, then ensure the set value appears
// as a key in the map
if values, err := def.Pipe(
yaml.Lookup("enumValues")); err != nil {
// error looking up the enumValues
return nil, err
} else if values != nil {
// contains enumValues map -- validate the set value against the map entries
// get the enumValues keys
fields, err := values.Fields()
if err != nil {
return nil, err
}
// search for the user provided value in the set of allowed values
var match bool
for i := range fields {
if fields[i] == s.Value {
// found a match, we are good
match = true
break
}
}
if !match {
// no match found -- provide an informative error to the user
return nil, errors.Errorf("%s does not match the possible values for %s: [%s]",
s.Value, s.Name, strings.Join(fields, ","))
}
}
v := yaml.NewScalarRNode(s.Value)
// values are always represented as strings the OpenAPI
// since the are unmarshalled into strings. Use double quote style to
// ensure this consistently.
v.YNode().Tag = yaml.NodeTagString
v.YNode().Style = yaml.DoubleQuotedStyle
if t != "array" {
// set a scalar value
if err := def.PipeE(&yaml.FieldSetter{Name: "value", Value: v}); err != nil {
return nil, err
}
} else {
// set a list value
if err := def.PipeE(&yaml.FieldClearer{Name: "value"}); err != nil {
return nil, err
}
// create the list values
var elements []*yaml.Node
n := yaml.NewScalarRNode(s.Value).YNode()
n.Tag = yaml.NodeTagString
n.Style = yaml.DoubleQuotedStyle
elements = append(elements, n)
for i := range s.ListValues {
v := s.ListValues[i]
n := yaml.NewScalarRNode(v).YNode()
n.Style = yaml.DoubleQuotedStyle
elements = append(elements, n)
}
l := yaml.NewRNode(&yaml.Node{
Kind: yaml.SequenceNode,
Content: elements,
})
def.YNode().Style = yaml.FoldedStyle
if err := def.PipeE(&yaml.FieldSetter{Name: "listValues", Value: l}); err != nil {
return nil, err
}
}
if err := def.PipeE(&yaml.FieldSetter{Name: "setBy", StringValue: s.SetBy}); err != nil {
return nil, err
}
if s.IsSet {
n := &yaml.Node{
Kind: yaml.ScalarNode,
Value: "true",
Tag: yaml.NodeTagBool,
}
if err := def.PipeE(&yaml.FieldSetter{Name: "isSet", Value: yaml.NewRNode(n)}); err != nil {
return nil, err
}
}
if s.Description != "" {
d, err := object.Pipe(yaml.LookupCreate(
yaml.MappingNode, "openAPI", "definitions", key))
if err != nil {
return nil, err
}
if err := d.PipeE(&yaml.FieldSetter{Name: "description", StringValue: s.Description}); err != nil {
return nil, err
}
}
return object, nil
}
// SetAll applies the set filter for all yaml nodes and only returns the nodes whose
// corresponding file has at least one node with input setter
func SetAll(s *Set) kio.Filter {
return kio.FilterFunc(func(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
filesToUpdate := sets.String{}
// for each node record the set fields count before and after filter is applied and
// store the corresponding file paths if there is an increment in setters count
for i := range nodes {
preCount := s.Count
_, err := s.Filter(nodes[i])
if err != nil {
return nil, errors.Wrap(err)
}
if s.Count > preCount {
path, _, err := kioutil.GetFileAnnotations(nodes[i])
if err != nil {
return nil, errors.Wrap(err)
}
filesToUpdate.Insert(path)
}
}
var nodesInUpdatedFiles []*yaml.RNode
// return only the nodes whose corresponding file has at least one node with input setter
for i := range nodes {
path, _, err := kioutil.GetFileAnnotations(nodes[i])
if err != nil {
return nil, errors.Wrap(err)
}
if filesToUpdate.Has(path) {
nodesInUpdatedFiles = append(nodesInUpdatedFiles, nodes[i])
}
}
return nodesInUpdatedFiles, nil
})
}