1/* 2Copyright 2019 The Kubernetes Authors. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package defaulting 18 19import ( 20 "fmt" 21 "reflect" 22 23 structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" 24 structuralobjectmeta "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta" 25 "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning" 26 "k8s.io/apimachinery/pkg/runtime" 27) 28 29// PruneDefaults prunes default values according to the schema and according to 30// the ObjectMeta definition of the running server. It mutates the passed schema. 31func PruneDefaults(s *structuralschema.Structural) error { 32 p := pruner{s} 33 _, err := p.pruneDefaults(s, NewRootObjectFunc()) 34 return err 35} 36 37type pruner struct { 38 rootSchema *structuralschema.Structural 39} 40 41func (p *pruner) pruneDefaults(s *structuralschema.Structural, f SurroundingObjectFunc) (changed bool, err error) { 42 if s == nil { 43 return false, nil 44 } 45 46 if s.Default.Object != nil { 47 orig := runtime.DeepCopyJSONValue(s.Default.Object) 48 49 obj, acc, err := f(s.Default.Object) 50 if err != nil { 51 return false, fmt.Errorf("failed to prune default value: %v", err) 52 } 53 if err := structuralobjectmeta.Coerce(nil, obj, p.rootSchema, true, true); err != nil { 54 return false, fmt.Errorf("failed to prune default value: %v", err) 55 } 56 pruning.Prune(obj, p.rootSchema, true) 57 s.Default.Object, _, err = acc(obj) 58 if err != nil { 59 return false, fmt.Errorf("failed to prune default value: %v", err) 60 } 61 62 changed = changed || !reflect.DeepEqual(orig, s.Default.Object) 63 } 64 65 if s.AdditionalProperties != nil && s.AdditionalProperties.Structural != nil { 66 c, err := p.pruneDefaults(s.AdditionalProperties.Structural, f.Child("*")) 67 if err != nil { 68 return false, err 69 } 70 changed = changed || c 71 } 72 if s.Items != nil { 73 c, err := p.pruneDefaults(s.Items, f.Index()) 74 if err != nil { 75 return false, err 76 } 77 changed = changed || c 78 } 79 for k, subSchema := range s.Properties { 80 c, err := p.pruneDefaults(&subSchema, f.Child(k)) 81 if err != nil { 82 return false, err 83 } 84 if c { 85 s.Properties[k] = subSchema 86 changed = true 87 } 88 } 89 90 return changed, nil 91} 92