github.com/stefanmcshane/helm@v0.0.0-20221213002717-88a4a2c6e77d/pkg/lint/rules/deprecations.go (about) 1 /* 2 Copyright The Helm 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 rules // import "github.com/stefanmcshane/helm/pkg/lint/rules" 18 19 import ( 20 "fmt" 21 "strconv" 22 23 "k8s.io/apimachinery/pkg/runtime" 24 "k8s.io/apimachinery/pkg/runtime/schema" 25 "k8s.io/apiserver/pkg/endpoints/deprecation" 26 kscheme "k8s.io/client-go/kubernetes/scheme" 27 ) 28 29 var ( 30 // This should be set in the Makefile based on the version of client-go being imported. 31 // These constants will be overwritten with LDFLAGS. The version components must be 32 // strings in order for LDFLAGS to set them. 33 k8sVersionMajor = "1" 34 k8sVersionMinor = "20" 35 ) 36 37 // deprecatedAPIError indicates than an API is deprecated in Kubernetes 38 type deprecatedAPIError struct { 39 Deprecated string 40 Message string 41 } 42 43 func (e deprecatedAPIError) Error() string { 44 msg := e.Message 45 return msg 46 } 47 48 func validateNoDeprecations(resource *K8sYamlStruct) error { 49 // if `resource` does not have an APIVersion or Kind, we cannot test it for deprecation 50 if resource.APIVersion == "" { 51 return nil 52 } 53 if resource.Kind == "" { 54 return nil 55 } 56 57 runtimeObject, err := resourceToRuntimeObject(resource) 58 if err != nil { 59 // do not error for non-kubernetes resources 60 if runtime.IsNotRegisteredError(err) { 61 return nil 62 } 63 return err 64 } 65 maj, err := strconv.Atoi(k8sVersionMajor) 66 if err != nil { 67 return err 68 } 69 min, err := strconv.Atoi(k8sVersionMinor) 70 if err != nil { 71 return err 72 } 73 74 if !deprecation.IsDeprecated(runtimeObject, maj, min) { 75 return nil 76 } 77 gvk := fmt.Sprintf("%s %s", resource.APIVersion, resource.Kind) 78 return deprecatedAPIError{ 79 Deprecated: gvk, 80 Message: deprecation.WarningMessage(runtimeObject), 81 } 82 } 83 84 func resourceToRuntimeObject(resource *K8sYamlStruct) (runtime.Object, error) { 85 scheme := runtime.NewScheme() 86 kscheme.AddToScheme(scheme) 87 88 gvk := schema.FromAPIVersionAndKind(resource.APIVersion, resource.Kind) 89 out, err := scheme.New(gvk) 90 if err != nil { 91 return nil, err 92 } 93 out.GetObjectKind().SetGroupVersionKind(gvk) 94 return out, nil 95 }