k8s.io/kubernetes@v1.29.3/test/images/agnhost/crd-conversion-webhook/converter/example_converter.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 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 17 package converter 18 19 import ( 20 "fmt" 21 "strings" 22 23 "k8s.io/klog/v2" 24 25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 26 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 27 ) 28 29 func convertExampleCRD(Object *unstructured.Unstructured, toVersion string) (*unstructured.Unstructured, metav1.Status) { 30 klog.V(2).Info("converting crd") 31 32 convertedObject := Object.DeepCopy() 33 fromVersion := Object.GetAPIVersion() 34 35 if toVersion == fromVersion { 36 return nil, statusErrorWithMessage("conversion from a version to itself should not call the webhook: %s", toVersion) 37 } 38 39 switch Object.GetAPIVersion() { 40 case "stable.example.com/v1": 41 switch toVersion { 42 case "stable.example.com/v2": 43 hostPort, ok := convertedObject.Object["hostPort"] 44 if ok { 45 delete(convertedObject.Object, "hostPort") 46 parts := strings.Split(hostPort.(string), ":") 47 if len(parts) != 2 { 48 return nil, statusErrorWithMessage("invalid hostPort value `%v`", hostPort) 49 } 50 convertedObject.Object["host"] = parts[0] 51 convertedObject.Object["port"] = parts[1] 52 } 53 default: 54 return nil, statusErrorWithMessage("unexpected conversion version %q", toVersion) 55 } 56 case "stable.example.com/v2": 57 switch toVersion { 58 case "stable.example.com/v1": 59 host, hasHost := convertedObject.Object["host"] 60 port, hasPort := convertedObject.Object["port"] 61 if hasHost || hasPort { 62 if !hasHost { 63 host = "" 64 } 65 if !hasPort { 66 port = "" 67 } 68 convertedObject.Object["hostPort"] = fmt.Sprintf("%s:%s", host, port) 69 delete(convertedObject.Object, "host") 70 delete(convertedObject.Object, "port") 71 } 72 default: 73 return nil, statusErrorWithMessage("unexpected conversion version %q", toVersion) 74 } 75 default: 76 return nil, statusErrorWithMessage("unexpected conversion version %q", fromVersion) 77 } 78 return convertedObject, statusSucceed() 79 }