Serge Bazanski | be538db | 2020-11-12 00:22:42 +0100 | [diff] [blame] | 1 | // Copyright 2017 The kubecfg authors |
| 2 | // |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | package utils |
| 17 | |
| 18 | import ( |
| 19 | "fmt" |
| 20 | |
| 21 | log "github.com/sirupsen/logrus" |
| 22 | "k8s.io/apimachinery/pkg/api/errors" |
| 23 | "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 24 | "k8s.io/apimachinery/pkg/runtime/schema" |
| 25 | "k8s.io/client-go/discovery" |
| 26 | "k8s.io/kube-openapi/pkg/util/proto" |
| 27 | "k8s.io/kube-openapi/pkg/util/proto/validation" |
| 28 | "k8s.io/kubectl/pkg/util/openapi" |
| 29 | ) |
| 30 | |
| 31 | // OpenAPISchema represents an OpenAPI schema for a given GroupVersionKind. |
| 32 | type OpenAPISchema struct { |
| 33 | schema proto.Schema |
| 34 | } |
| 35 | |
| 36 | // NewOpenAPISchemaFor returns the OpenAPISchema object ready to validate objects of given GroupVersion |
| 37 | func NewOpenAPISchemaFor(delegate discovery.OpenAPISchemaInterface, gvk schema.GroupVersionKind) (*OpenAPISchema, error) { |
| 38 | log.Debugf("Fetching schema for %v", gvk) |
| 39 | doc, err := delegate.OpenAPISchema() |
| 40 | if err != nil { |
| 41 | return nil, err |
| 42 | } |
| 43 | res, err := openapi.NewOpenAPIData(doc) |
| 44 | if err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | |
| 48 | sc := res.LookupResource(gvk) |
| 49 | if sc == nil { |
| 50 | gvr := schema.GroupResource{ |
| 51 | // TODO(mkm): figure out a meaningful group+resource for schemas. |
| 52 | Group: "schema", |
| 53 | Resource: "schema", |
| 54 | } |
| 55 | return nil, errors.NewNotFound(gvr, fmt.Sprintf("%s", gvk)) |
| 56 | } |
| 57 | return &OpenAPISchema{schema: sc}, nil |
| 58 | } |
| 59 | |
| 60 | // Validate is the primary entrypoint into this class |
| 61 | func (s *OpenAPISchema) Validate(obj *unstructured.Unstructured) []error { |
| 62 | gvk := obj.GroupVersionKind() |
| 63 | log.Infof("validate object %q", gvk) |
| 64 | return validation.ValidateModel(obj.UnstructuredContent(), s.schema, fmt.Sprintf("%s.%s", gvk.Version, gvk.Kind)) |
| 65 | } |