-
Notifications
You must be signed in to change notification settings - Fork 428
/
Copy pathschema.go
549 lines (486 loc) · 19.2 KB
/
schema.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
541
542
543
544
545
546
547
548
549
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package crd
import (
"errors"
"fmt"
"go/ast"
"go/token"
"go/types"
"sort"
"strings"
apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers"
"sigs.k8s.io/controller-tools/pkg/loader"
"sigs.k8s.io/controller-tools/pkg/markers"
)
// Schema flattening is done in a recursive mapping method.
// Start reading at infoToSchema.
const (
// defPrefix is the prefix used to link to definitions in the OpenAPI schema.
defPrefix = "#/definitions/"
)
// byteType is the types.Type for byte (see the types documention
// for why we need to look this up in the Universe), saved
// for quick comparison.
var byteType = types.Universe.Lookup("byte").Type()
// SchemaMarker is any marker that needs to modify the schema of the underlying type or field.
type SchemaMarker interface {
// ApplyToSchema is called after the rest of the schema for a given type
// or field is generated, to modify the schema appropriately.
ApplyToSchema(*apiext.JSONSchemaProps) error
}
// applyFirstMarker is applied before any other markers. It's a bit of a hack.
type applyFirstMarker interface {
ApplyFirst()
}
// schemaRequester knows how to marker that another schema (e.g. via an external reference) is necessary.
type schemaRequester interface {
NeedSchemaFor(typ TypeIdent)
}
// schemaContext stores and provides information across a hierarchy of schema generation.
type schemaContext struct {
pkg *loader.Package
info *markers.TypeInfo
schemaRequester schemaRequester
PackageMarkers markers.MarkerValues
allowDangerousTypes bool
ignoreUnexportedFields bool
}
// newSchemaContext constructs a new schemaContext for the given package and schema requester.
// It must have type info added before use via ForInfo.
func newSchemaContext(pkg *loader.Package, req schemaRequester, allowDangerousTypes, ignoreUnexportedFields bool) *schemaContext {
pkg.NeedTypesInfo()
return &schemaContext{
pkg: pkg,
schemaRequester: req,
allowDangerousTypes: allowDangerousTypes,
ignoreUnexportedFields: ignoreUnexportedFields,
}
}
// ForInfo produces a new schemaContext with containing the same information
// as this one, except with the given type information.
func (c *schemaContext) ForInfo(info *markers.TypeInfo) *schemaContext {
return &schemaContext{
pkg: c.pkg,
info: info,
schemaRequester: c.schemaRequester,
allowDangerousTypes: c.allowDangerousTypes,
ignoreUnexportedFields: c.ignoreUnexportedFields,
}
}
// requestSchema asks for the schema for a type in the package with the
// given import path.
func (c *schemaContext) requestSchema(pkgPath, typeName string) {
pkg := c.pkg
if pkgPath != "" {
pkg = c.pkg.Imports()[pkgPath]
}
c.schemaRequester.NeedSchemaFor(TypeIdent{
Package: pkg,
Name: typeName,
})
}
// infoToSchema creates a schema for the type in the given set of type information.
func infoToSchema(ctx *schemaContext) *apiext.JSONSchemaProps {
if obj := ctx.pkg.Types.Scope().Lookup(ctx.info.Name); obj != nil {
switch {
// If the obj implements a JSON marshaler and has a marker, use the
// markers value and do not traverse as the marshaler could be doing
// anything. If there is no marker, fall back to traversing.
case implements(obj.Type(), jsonMarshaler):
schema := &apiext.JSONSchemaProps{}
applyMarkers(ctx, ctx.info.Markers, schema, ctx.info.RawSpec.Type)
if schema.Type != "" {
return schema
}
// If the obj implements a text marshaler, encode it as a string.
case implements(obj.Type(), textMarshaler):
schema := &apiext.JSONSchemaProps{Type: "string"}
applyMarkers(ctx, ctx.info.Markers, schema, ctx.info.RawSpec.Type)
if schema.Type != "string" {
err := fmt.Errorf("%q implements encoding.TextMarshaler but schema type is not string: %q", ctx.info.RawSpec.Name, schema.Type)
ctx.pkg.AddError(loader.ErrFromNode(err, ctx.info.RawSpec.Type))
}
return schema
}
}
return typeToSchema(ctx, ctx.info.RawSpec.Type)
}
type schemaMarkerWithName struct {
SchemaMarker SchemaMarker
Name string
}
// applyMarkers applies schema markers given their priority to the given schema
func applyMarkers(ctx *schemaContext, markerSet markers.MarkerValues, props *apiext.JSONSchemaProps, node ast.Node) {
markers := make([]schemaMarkerWithName, 0, len(markerSet))
itemsMarkers := make([]schemaMarkerWithName, 0, len(markerSet))
for markerName, markerValues := range markerSet {
for _, markerValue := range markerValues {
if schemaMarker, isSchemaMarker := markerValue.(SchemaMarker); isSchemaMarker {
if strings.HasPrefix(markerName, crdmarkers.ValidationItemsPrefix) {
itemsMarkers = append(itemsMarkers, schemaMarkerWithName{
SchemaMarker: schemaMarker,
Name: markerName,
})
} else {
markers = append(markers, schemaMarkerWithName{
SchemaMarker: schemaMarker,
Name: markerName,
})
}
}
}
}
cmpPriority := func(markers []schemaMarkerWithName, i, j int) bool {
var iPriority, jPriority crdmarkers.ApplyPriority
switch m := markers[i].SchemaMarker.(type) {
case crdmarkers.ApplyPriorityMarker:
iPriority = m.ApplyPriority()
case applyFirstMarker:
iPriority = crdmarkers.ApplyPriorityFirst
default:
iPriority = crdmarkers.ApplyPriorityDefault
}
switch m := markers[j].SchemaMarker.(type) {
case crdmarkers.ApplyPriorityMarker:
jPriority = m.ApplyPriority()
case applyFirstMarker:
jPriority = crdmarkers.ApplyPriorityFirst
default:
jPriority = crdmarkers.ApplyPriorityDefault
}
return iPriority < jPriority
}
sort.Slice(markers, func(i, j int) bool { return cmpPriority(markers, i, j) })
sort.Slice(itemsMarkers, func(i, j int) bool { return cmpPriority(itemsMarkers, i, j) })
for _, schemaMarker := range markers {
if err := schemaMarker.SchemaMarker.ApplyToSchema(props); err != nil {
ctx.pkg.AddError(loader.ErrFromNode(err /* an okay guess */, node))
}
}
for _, schemaMarker := range itemsMarkers {
if props.Type != "array" || props.Items == nil || props.Items.Schema == nil {
err := fmt.Errorf("must apply %s to an array value, found %s", schemaMarker.Name, props.Type)
ctx.pkg.AddError(loader.ErrFromNode(err, node))
} else {
itemsSchema := props.Items.Schema
if err := schemaMarker.SchemaMarker.ApplyToSchema(itemsSchema); err != nil {
ctx.pkg.AddError(loader.ErrFromNode(err /* an okay guess */, node))
}
}
}
}
// typeToSchema creates a schema for the given AST type.
func typeToSchema(ctx *schemaContext, rawType ast.Expr) *apiext.JSONSchemaProps {
var props *apiext.JSONSchemaProps
switch expr := rawType.(type) {
case *ast.Ident:
props = localNamedToSchema(ctx, expr)
case *ast.SelectorExpr:
props = namedToSchema(ctx, expr)
case *ast.ArrayType:
props = arrayToSchema(ctx, expr)
case *ast.MapType:
props = mapToSchema(ctx, expr)
case *ast.StarExpr:
props = typeToSchema(ctx, expr.X)
case *ast.StructType:
props = structToSchema(ctx, expr)
default:
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unsupported AST kind %T", expr), rawType))
// NB(directxman12): we explicitly don't handle interfaces
return &apiext.JSONSchemaProps{}
}
props.Description = ctx.info.Doc
applyMarkers(ctx, ctx.info.Markers, props, rawType)
return props
}
// qualifiedName constructs a JSONSchema-safe qualified name for a type
// (`<typeName>` or `<safePkgPath>~0<typeName>`, where `<safePkgPath>`
// is the package path with `/` replaced by `~1`, according to JSONPointer
// escapes).
func qualifiedName(pkgName, typeName string) string {
if pkgName != "" {
return strings.Replace(pkgName, "/", "~1", -1) + "~0" + typeName
}
return typeName
}
// TypeRefLink creates a definition link for the given type and package.
func TypeRefLink(pkgName, typeName string) string {
return defPrefix + qualifiedName(pkgName, typeName)
}
// localNamedToSchema creates a schema (ref) for a *potentially* local type reference
// (could be external from a dot-import).
func localNamedToSchema(ctx *schemaContext, ident *ast.Ident) *apiext.JSONSchemaProps {
typeInfo := ctx.pkg.TypesInfo.TypeOf(ident)
if typeInfo == types.Typ[types.Invalid] {
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %s", ident.Name), ident))
return &apiext.JSONSchemaProps{}
}
// This reproduces the behavior we had pre gotypesalias=1 (needed if this
// project is compiled with default settings and Go >= 1.23).
if aliasInfo, isAlias := typeInfo.(*types.Alias); isAlias {
typeInfo = aliasInfo.Rhs()
}
if basicInfo, isBasic := typeInfo.(*types.Basic); isBasic {
typ, fmt, err := builtinToType(basicInfo, ctx.allowDangerousTypes)
if err != nil {
ctx.pkg.AddError(loader.ErrFromNode(err, ident))
}
// Check for type aliasing to a basic type for gotypesalias=0. See more
// in documentation https://pkg.go.dev/go/types#Alias:
// > For gotypesalias=1, alias declarations produce an Alias type.
// > Otherwise, the alias information is only in the type name, which
// > points directly to the actual (aliased) type.
if basicInfo.Name() != ident.Name {
ctx.requestSchema("", ident.Name)
link := TypeRefLink("", ident.Name)
return &apiext.JSONSchemaProps{
Type: typ,
Format: fmt,
Ref: &link,
}
}
return &apiext.JSONSchemaProps{
Type: typ,
Format: fmt,
}
}
// NB(directxman12): if there are dot imports, this might be an external reference,
// so use typechecking info to get the actual object
typeNameInfo := typeInfo.(interface{ Obj() *types.TypeName }).Obj()
pkg := typeNameInfo.Pkg()
pkgPath := loader.NonVendorPath(pkg.Path())
if pkg == ctx.pkg.Types {
pkgPath = ""
}
ctx.requestSchema(pkgPath, typeNameInfo.Name())
link := TypeRefLink(pkgPath, typeNameInfo.Name())
return &apiext.JSONSchemaProps{
Ref: &link,
}
}
// namedSchema creates a schema (ref) for an explicitly external type reference.
func namedToSchema(ctx *schemaContext, named *ast.SelectorExpr) *apiext.JSONSchemaProps {
typeInfoRaw := ctx.pkg.TypesInfo.TypeOf(named)
if typeInfoRaw == types.Typ[types.Invalid] {
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %v.%s", named.X, named.Sel.Name), named))
return &apiext.JSONSchemaProps{}
}
typeInfo := typeInfoRaw.(interface{ Obj() *types.TypeName })
typeNameInfo := typeInfo.Obj()
nonVendorPath := loader.NonVendorPath(typeNameInfo.Pkg().Path())
ctx.requestSchema(nonVendorPath, typeNameInfo.Name())
link := TypeRefLink(nonVendorPath, typeNameInfo.Name())
return &apiext.JSONSchemaProps{
Ref: &link,
}
// NB(directxman12): we special-case things like resource.Quantity during the "collapse" phase.
}
// arrayToSchema creates a schema for the items of the given array, dealing appropriately
// with the special `[]byte` type (according to OpenAPI standards).
func arrayToSchema(ctx *schemaContext, array *ast.ArrayType) *apiext.JSONSchemaProps {
eltType := ctx.pkg.TypesInfo.TypeOf(array.Elt)
if eltType == byteType && array.Len == nil {
// byte slices are represented as base64-encoded strings
// (the format is defined in OpenAPI v3, but not JSON Schema)
return &apiext.JSONSchemaProps{
Type: "string",
Format: "byte",
}
}
// TODO(directxman12): backwards-compat would require access to markers from base info
items := typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), array.Elt)
return &apiext.JSONSchemaProps{
Type: "array",
Items: &apiext.JSONSchemaPropsOrArray{Schema: items},
}
}
// mapToSchema creates a schema for items of the given map. Key types must eventually resolve
// to string (other types aren't allowed by JSON, and thus the kubernetes API standards).
func mapToSchema(ctx *schemaContext, mapType *ast.MapType) *apiext.JSONSchemaProps {
keyInfo := ctx.pkg.TypesInfo.TypeOf(mapType.Key)
// check that we've got a type that actually corresponds to a string
for keyInfo != nil {
switch typedKey := keyInfo.(type) {
case *types.Basic:
if typedKey.Info()&types.IsString == 0 {
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map keys must be strings, not %s", keyInfo.String()), mapType.Key))
return &apiext.JSONSchemaProps{}
}
keyInfo = nil // stop iterating
case *types.Named:
keyInfo = typedKey.Underlying()
default:
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map keys must be strings, not %s", keyInfo.String()), mapType.Key))
return &apiext.JSONSchemaProps{}
}
}
// TODO(directxman12): backwards-compat would require access to markers from base info
var valSchema *apiext.JSONSchemaProps
switch val := mapType.Value.(type) {
case *ast.Ident:
valSchema = localNamedToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
case *ast.SelectorExpr:
valSchema = namedToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
case *ast.ArrayType:
valSchema = arrayToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
case *ast.StarExpr:
valSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
case *ast.MapType:
valSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
default:
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("not a supported map value type: %T", mapType.Value), mapType.Value))
return &apiext.JSONSchemaProps{}
}
return &apiext.JSONSchemaProps{
Type: "object",
AdditionalProperties: &apiext.JSONSchemaPropsOrBool{
Schema: valSchema,
Allows: true, /* set automatically by serialization, but useful for testing */
},
}
}
// structToSchema creates a schema for the given struct. Embedded fields are placed in AllOf,
// and can be flattened later with a Flattener.
func structToSchema(ctx *schemaContext, structType *ast.StructType) *apiext.JSONSchemaProps {
props := &apiext.JSONSchemaProps{
Type: "object",
Properties: make(map[string]apiext.JSONSchemaProps),
}
if ctx.info.RawSpec.Type != structType {
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("encountered non-top-level struct (possibly embedded), those aren't allowed"), structType))
return props
}
for _, field := range ctx.info.Fields {
// Skip if the field is not an inline field, ignoreUnexportedFields is true, and the field is not exported
if field.Name != "" && ctx.ignoreUnexportedFields && !ast.IsExported(field.Name) {
continue
}
jsonTag, hasTag := field.Tag.Lookup("json")
if !hasTag {
// if the field doesn't have a JSON tag, it doesn't belong in output (and shouldn't exist in a serialized type)
ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("encountered struct field %q without JSON tag in type %q", field.Name, ctx.info.Name), field.RawField))
continue
}
jsonOpts := strings.Split(jsonTag, ",")
if len(jsonOpts) == 1 && jsonOpts[0] == "-" {
// skipped fields have the tag "-" (note that "-," means the field is named "-")
continue
}
inline := false
omitEmpty := false
for _, opt := range jsonOpts[1:] {
switch opt {
case "inline":
inline = true
case "omitempty":
omitEmpty = true
}
}
fieldName := jsonOpts[0]
inline = inline || fieldName == "" // anonymous fields are inline fields in YAML/JSON
// if no default required mode is set, default to required
defaultMode := "required"
if ctx.PackageMarkers.Get("kubebuilder:validation:Optional") != nil {
defaultMode = "optional"
}
switch {
case field.Markers.Get("kubebuilder:validation:Optional") != nil:
// explicity optional - kubebuilder
case field.Markers.Get("kubebuilder:validation:Required") != nil:
// explicitly required - kubebuilder
props.Required = append(props.Required, fieldName)
case field.Markers.Get("optional") != nil:
// explicity optional - kubernetes
case field.Markers.Get("required") != nil:
// explicitly required - kubernetes
props.Required = append(props.Required, fieldName)
// if this package isn't set to optional default...
case defaultMode == "required":
// ...everything that's not inline / omitempty is required
if !inline && !omitEmpty {
props.Required = append(props.Required, fieldName)
}
// if this package isn't set to required default...
case defaultMode == "optional":
// implicitly optional
}
var propSchema *apiext.JSONSchemaProps
if field.Markers.Get(crdmarkers.SchemalessName) != nil {
propSchema = &apiext.JSONSchemaProps{}
} else {
propSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), field.RawField.Type)
}
propSchema.Description = field.Doc
applyMarkers(ctx, field.Markers, propSchema, field.RawField)
if inline {
props.AllOf = append(props.AllOf, *propSchema)
continue
}
props.Properties[fieldName] = *propSchema
}
return props
}
// builtinToType converts builtin basic types to their equivalent JSON schema form.
// It *only* handles types allowed by the kubernetes API standards. Floats are not
// allowed unless allowDangerousTypes is true
func builtinToType(basic *types.Basic, allowDangerousTypes bool) (typ string, format string, err error) {
// NB(directxman12): formats from OpenAPI v3 are slightly different than those defined
// in JSONSchema. This'll use the OpenAPI v3 ones, since they're useful for bounding our
// non-string types.
basicInfo := basic.Info()
switch {
case basicInfo&types.IsBoolean != 0:
typ = "boolean"
case basicInfo&types.IsString != 0:
typ = "string"
case basicInfo&types.IsInteger != 0:
typ = "integer"
case basicInfo&types.IsFloat != 0:
if allowDangerousTypes {
typ = "number"
} else {
return "", "", errors.New("found float, the usage of which is highly discouraged, as support for them varies across languages. Please consider serializing your float as string instead. If you are really sure you want to use them, re-run with crd:allowDangerousTypes=true")
}
default:
return "", "", fmt.Errorf("unsupported type %q", basic.String())
}
switch basic.Kind() {
case types.Int32, types.Uint32:
format = "int32"
case types.Int64, types.Uint64:
format = "int64"
}
return typ, format, nil
}
// Open coded go/types representation of encoding/json.Marshaller
var jsonMarshaler = types.NewInterfaceType([]*types.Func{
types.NewFunc(token.NoPos, nil, "MarshalJSON",
types.NewSignatureType(nil, nil, nil, nil,
types.NewTuple(
types.NewVar(token.NoPos, nil, "", types.NewSlice(types.Universe.Lookup("byte").Type())),
types.NewVar(token.NoPos, nil, "", types.Universe.Lookup("error").Type())), false)),
}, nil).Complete()
// Open coded go/types representation of encoding.TextMarshaler
var textMarshaler = types.NewInterfaceType([]*types.Func{
types.NewFunc(token.NoPos, nil, "MarshalText",
types.NewSignatureType(nil, nil, nil, nil,
types.NewTuple(
types.NewVar(token.NoPos, nil, "text", types.NewSlice(types.Universe.Lookup("byte").Type())),
types.NewVar(token.NoPos, nil, "err", types.Universe.Lookup("error").Type())), false)),
}, nil).Complete()
func implements(typ types.Type, iface *types.Interface) bool {
return types.Implements(typ, iface) || types.Implements(types.NewPointer(typ), iface)
}