-
Notifications
You must be signed in to change notification settings - Fork 367
/
serving_info.go
414 lines (366 loc) · 15.1 KB
/
serving_info.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
/*
Copyright 2022 The KCP 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 apiserver
import (
"fmt"
"github.com/kcp-dev/logicalcluster/v3"
apiextensionsinternal "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsapiserver "k8s.io/apiextensions-apiserver/pkg/apiserver"
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
structuraldefaulting "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting"
apiservervalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation"
"k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder"
"k8s.io/apiextensions-apiserver/pkg/crdserverscheme"
"k8s.io/apiextensions-apiserver/pkg/registry/customresource/tableconvertor"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/managedfields"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apiserver/pkg/endpoints/handlers"
"k8s.io/apiserver/pkg/endpoints/openapi"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/registry/rest"
genericapiserver "k8s.io/apiserver/pkg/server"
utilopenapi "k8s.io/apiserver/pkg/util/openapi"
"k8s.io/klog/v2"
"k8s.io/kube-openapi/pkg/validation/spec"
kcpfeatures "github.com/kcp-dev/kcp/pkg/features"
"github.com/kcp-dev/kcp/pkg/virtual/framework/dynamic/apidefinition"
apisv1alpha1 "github.com/kcp-dev/kcp/sdk/apis/apis/v1alpha1"
)
var _ apidefinition.APIDefinition = (*servingInfo)(nil)
// RestProviderFunc is the type of a function that builds REST storage implementations for the main resource and sub-resources, based on information passed by the resource handler about a given API.
type RestProviderFunc func(resource schema.GroupVersionResource, kind schema.GroupVersionKind, listKind schema.GroupVersionKind, typer runtime.ObjectTyper, tableConvertor rest.TableConvertor, namespaceScoped bool, schemaValidator apiservervalidation.SchemaValidator, subresourcesSchemaValidator map[string]apiservervalidation.SchemaValidator, structuralSchema *structuralschema.Structural) (mainStorage rest.Storage, subresourceStorages map[string]rest.Storage)
// CreateServingInfoFor builds an APIDefinition for a apiResourceSchema.
func CreateServingInfoFor(genericConfig genericapiserver.CompletedConfig, apiResourceSchema *apisv1alpha1.APIResourceSchema, version string, restProvider RestProviderFunc) (apidefinition.APIDefinition, error) {
equivalentResourceRegistry := runtime.NewEquivalentResourceRegistry()
// find given version in schema
apiResourceVersion, found := findAPIResourceVersion(apiResourceSchema, version)
if !found {
return nil, fmt.Errorf("version %q not found in APIResourceSchema %s|%s", version, logicalcluster.From(apiResourceSchema), apiResourceSchema.Name)
}
internalSchema := &apiextensionsinternal.JSONSchemaProps{}
openapiSchema, err := apiResourceVersion.GetSchema()
if err != nil {
return nil, err
}
if err := apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(openapiSchema, internalSchema, nil); err != nil {
return nil, fmt.Errorf("failed converting CRD validation to internal version: %w", err)
}
structuralSchema, err := structuralschema.NewStructural(internalSchema)
if err != nil {
// This should never happen. If it does, it is a programming error.
utilruntime.HandleError(fmt.Errorf("failed to convert schema to structural: %w", err))
return nil, fmt.Errorf("the server could not properly serve the CR schema") // validation should avoid this
}
// we don't own structuralSchema completely, e.g. defaults are not deep-copied. So better make a copy here.
structuralSchema = structuralSchema.DeepCopy()
gvr := schema.GroupVersionResource{Group: apiResourceSchema.Spec.Group, Version: version, Resource: apiResourceSchema.Spec.Names.Plural}
gvk := schema.GroupVersionKind{Group: apiResourceSchema.Spec.Group, Version: version, Kind: apiResourceSchema.Spec.Names.Kind}
listGVK := schema.GroupVersionKind{Group: apiResourceSchema.Spec.Group, Version: version, Kind: apiResourceSchema.Spec.Names.ListKind}
if err := structuraldefaulting.PruneDefaults(structuralSchema); err != nil {
// This should never happen. If it does, it is a programming error.
utilruntime.HandleError(fmt.Errorf("failed to prune defaults for schema %s|%s: %w", logicalcluster.From(apiResourceSchema), gvr.String(), err))
return nil, fmt.Errorf("the server could not properly serve the CR schema") // validation should avoid this
}
s, err := buildOpenAPIV2(
apiResourceSchema,
apiResourceVersion,
builder.Options{
V2: true,
SkipFilterSchemaForKubectlOpenAPIV2Validation: true,
StripValueValidation: true,
StripNullable: true,
AllowNonStructural: false})
if err != nil {
return nil, err
}
var modelsByGKV openapi.ModelsByGKV
openAPIModels, err := utilopenapi.ToProtoModels(s)
if err != nil {
utilruntime.HandleError(fmt.Errorf("error building openapi models for %s: %w", gvk.String(), err))
openAPIModels = nil
} else {
modelsByGKV, err = openapi.GetModelsByGKV(openAPIModels)
if err != nil {
utilruntime.HandleError(fmt.Errorf("error gathering openapi models by GKV for %s: %w", gvk.String(), err))
modelsByGKV = nil
}
}
typeConverter := managedfields.NewDeducedTypeConverter()
if openAPIModels != nil {
schemas := make(map[string]*spec.Schema, len(s.Definitions))
for k, v := range s.Definitions {
v := v
schemas[k] = &v
}
typeConverter, err = managedfields.NewTypeConverter(schemas, false)
if err != nil {
return nil, err
}
}
safeConverter, unsafeConverter := &nopConverter{}, &nopConverter{}
if err != nil {
return nil, err
}
// In addition to Unstructured objects (Custom Resources), we also may sometimes need to
// decode unversioned Options objects, so we delegate to parameterScheme for such types.
parameterScheme := runtime.NewScheme()
parameterScheme.AddUnversionedTypes(schema.GroupVersion{Group: apiResourceSchema.Spec.Group, Version: version},
&metav1.ListOptions{},
&metav1.GetOptions{},
&metav1.DeleteOptions{},
)
parameterCodec := runtime.NewParameterCodec(parameterScheme)
equivalentResourceRegistry.RegisterKindFor(gvr, "", gvk)
typer := apiextensionsapiserver.UnstructuredObjectTyper{
Delegate: parameterScheme,
UnstructuredTyper: crdserverscheme.NewUnstructuredObjectTyper(),
}
creator := unstructuredCreator{}
internalValidationSchema := &apiextensionsinternal.CustomResourceValidation{
OpenAPIV3Schema: internalSchema,
}
validator, _, err := apiservervalidation.NewSchemaValidator(internalSchema)
if err != nil {
return nil, err
}
subResourcesValidators := map[string]apiservervalidation.SchemaValidator{}
if status := apiResourceVersion.Subresources.Status; status != nil {
var statusValidator apiservervalidation.SchemaValidator
equivalentResourceRegistry.RegisterKindFor(gvr, "status", gvk)
// for the status subresource, validate only against the status schema
if internalValidationSchema != nil && internalValidationSchema.OpenAPIV3Schema != nil && internalValidationSchema.OpenAPIV3Schema.Properties != nil {
if statusSchema, ok := internalValidationSchema.OpenAPIV3Schema.Properties["status"]; ok {
statusValidator, _, err = apiservervalidation.NewSchemaValidator(&statusSchema)
if err != nil {
return nil, err
}
}
}
subResourcesValidators["status"] = statusValidator
}
table, err := tableconvertor.New(apiResourceVersion.AdditionalPrinterColumns)
if err != nil {
klog.Background().V(2).WithValues("cluster", logicalcluster.From(apiResourceSchema), "gvk", gvk, "err", err).Info("the CRD has an invalid printer specification, falling back to default printing")
}
storage, subresourceStorages := restProvider(
gvr,
gvk,
listGVK,
typer,
table,
apiResourceSchema.Spec.Scope == apiextensionsv1.NamespaceScoped,
validator,
subResourcesValidators,
structuralSchema,
)
clusterScoped := apiResourceSchema.Spec.Scope == apiextensionsv1.ClusterScoped
// CRDs explicitly do not support protobuf, but some objects returned by the API server do
negotiatedSerializer := apiextensionsapiserver.NewUnstructuredNegotiatedSerializer(
typer,
creator,
safeConverter,
map[string]*structuralschema.Structural{gvk.Version: structuralSchema},
gvk.GroupKind(),
false,
)
supportedMediaTypes := negotiatedSerializer.SupportedMediaTypes()
standardSerializers := make([]runtime.SerializerInfo, 0, len(supportedMediaTypes))
for _, s := range supportedMediaTypes {
if s.MediaType == runtime.ContentTypeProtobuf {
continue
}
standardSerializers = append(standardSerializers, s)
}
requestScope := &handlers.RequestScope{
Namer: handlers.ContextBasedNaming{
Namer: runtime.Namer(meta.NewAccessor()),
ClusterScoped: clusterScoped,
},
Serializer: negotiatedSerializer,
ParameterCodec: parameterCodec,
StandardSerializers: standardSerializers,
Creater: creator,
Convertor: safeConverter,
Defaulter: apiextensionsapiserver.NewUnstructuredDefaulter(
parameterScheme,
map[string]*structuralschema.Structural{gvk.Version: structuralSchema},
gvk.GroupKind(),
),
Typer: typer,
UnsafeConvertor: unsafeConverter,
EquivalentResourceMapper: equivalentResourceRegistry,
Resource: gvr,
Kind: gvk,
HubGroupVersion: gvk.GroupVersion(),
MetaGroupVersion: metav1.SchemeGroupVersion,
TableConvertor: table,
Authorizer: genericConfig.Authorization.Authorizer,
MaxRequestBodyBytes: genericConfig.MaxRequestBodyBytes,
OpenapiModels: modelsByGKV,
}
if kcpfeatures.DefaultFeatureGate.Enabled(features.ServerSideApply) {
if withResetFields, canGetResetFields := storage.(rest.ResetFieldsStrategy); canGetResetFields {
resetFields := withResetFields.GetResetFields()
reqScope := *requestScope
reqScope, err = apiextensionsapiserver.ScopeWithFieldManager(
typeConverter,
reqScope,
resetFields,
"",
)
if err != nil {
return nil, err
}
requestScope = &reqScope
} else {
return nil, fmt.Errorf("storage for resource %q should define GetResetFields", gvk.String())
}
}
var statusScope handlers.RequestScope
statusStorage, statusEnabled := subresourceStorages["status"]
if statusEnabled {
// shallow copy
statusScope = *requestScope
statusScope.Subresource = "status"
statusScope.Namer = handlers.ContextBasedNaming{
Namer: runtime.Namer(meta.NewAccessor()),
ClusterScoped: clusterScoped,
}
if kcpfeatures.DefaultFeatureGate.Enabled(features.ServerSideApply) {
if withResetFields, canGetResetFields := statusStorage.(rest.ResetFieldsStrategy); canGetResetFields {
resetFields := withResetFields.GetResetFields()
statusScope, err = apiextensionsapiserver.ScopeWithFieldManager(
typeConverter,
statusScope,
resetFields,
"status",
)
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("storage for resource %q status should define GetResetFields", gvk.String())
}
}
}
ret := &servingInfo{
apiResourceSchema: apiResourceSchema,
storage: storage,
statusStorage: statusStorage,
requestScope: requestScope,
statusRequestScope: &statusScope,
logicalClusterName: logicalcluster.From(apiResourceSchema),
}
return ret, nil
}
// servingInfo stores enough information to serve the storage for the apiResourceSchema.
type servingInfo struct {
logicalClusterName logicalcluster.Name
apiResourceSchema *apisv1alpha1.APIResourceSchema
storage rest.Storage
statusStorage rest.Storage
requestScope *handlers.RequestScope
statusRequestScope *handlers.RequestScope
}
// Implement APIDefinition interface
func (apiDef *servingInfo) GetAPIResourceSchema() *apisv1alpha1.APIResourceSchema {
return apiDef.apiResourceSchema
}
func (apiDef *servingInfo) GetClusterName() logicalcluster.Name {
return apiDef.logicalClusterName
}
func (apiDef *servingInfo) GetStorage() rest.Storage {
return apiDef.storage
}
func (apiDef *servingInfo) GetSubResourceStorage(subresource string) rest.Storage {
if subresource == "status" {
return apiDef.statusStorage
}
return nil
}
func (apiDef *servingInfo) GetRequestScope() *handlers.RequestScope {
return apiDef.requestScope
}
func (apiDef *servingInfo) GetSubResourceRequestScope(subresource string) *handlers.RequestScope {
if subresource == "status" {
return apiDef.statusRequestScope
}
return nil
}
func (apiDef *servingInfo) TearDown() {
}
var _ runtime.ObjectConvertor = nopConverter{}
type nopConverter struct{}
func (u nopConverter) Convert(in, out, context interface{}) error {
sv, err := conversion.EnforcePtr(in)
if err != nil {
return err
}
dv, err := conversion.EnforcePtr(out)
if err != nil {
return err
}
dv.Set(sv)
return nil
}
func (u nopConverter) ConvertToVersion(in runtime.Object, gv runtime.GroupVersioner) (out runtime.Object, err error) {
return in, nil
}
func (u nopConverter) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error) {
return label, value, nil
}
// buildOpenAPIV2 builds OpenAPI v2 for the given apiResourceSpec.
func buildOpenAPIV2(apiResourceSchema *apisv1alpha1.APIResourceSchema, apiResourceVersion *apisv1alpha1.APIResourceVersion, opts builder.Options) (*spec.Swagger, error) {
openapiSchema, err := apiResourceVersion.GetSchema()
if err != nil {
return nil, err
}
crd := &apiextensionsv1.CustomResourceDefinition{
Spec: apiextensionsv1.CustomResourceDefinitionSpec{
Group: apiResourceSchema.Spec.Group,
Names: apiResourceSchema.Spec.Names,
Versions: []apiextensionsv1.CustomResourceDefinitionVersion{
{
Name: apiResourceVersion.Name,
Schema: &apiextensionsv1.CustomResourceValidation{
OpenAPIV3Schema: openapiSchema,
},
Subresources: &apiResourceVersion.Subresources,
},
},
Scope: apiResourceSchema.Spec.Scope,
},
}
return builder.BuildOpenAPIV2(crd, apiResourceVersion.Name, opts)
}
func findAPIResourceVersion(schema *apisv1alpha1.APIResourceSchema, version string) (*apisv1alpha1.APIResourceVersion, bool) {
for i := range schema.Spec.Versions {
if vs := &schema.Spec.Versions[i]; vs.Name == version {
return vs, true
}
}
return nil, false
}
type unstructuredCreator struct{}
func (c unstructuredCreator) New(kind schema.GroupVersionKind) (runtime.Object, error) {
ret := &unstructured.Unstructured{}
ret.SetGroupVersionKind(kind)
return ret, nil
}