knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/kmeta/accessor.go (about) 1 /* 2 Copyright 2018 The Knative 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 kmeta 18 19 import ( 20 "fmt" 21 22 corev1 "k8s.io/api/core/v1" 23 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 24 "k8s.io/apimachinery/pkg/runtime" 25 "k8s.io/apimachinery/pkg/runtime/schema" 26 "k8s.io/client-go/tools/cache" 27 ) 28 29 // Accessor is a collection of interfaces from metav1.TypeMeta, 30 // runtime.Object and metav1.Object that Kubernetes API types 31 // registered with runtime.Scheme must support. 32 type Accessor interface { 33 metav1.Object 34 35 // Interfaces for metav1.TypeMeta 36 GroupVersionKind() schema.GroupVersionKind 37 SetGroupVersionKind(gvk schema.GroupVersionKind) 38 39 // Interfaces for runtime.Object 40 GetObjectKind() schema.ObjectKind 41 DeepCopyObject() runtime.Object 42 } 43 44 // DeletionHandlingAccessor tries to convert given interface into Accessor first; 45 // and to handle deletion, it try to fetch info from DeletedFinalStateUnknown on failure. 46 // The name is a reference to cache.DeletionHandlingMetaNamespaceKeyFunc 47 func DeletionHandlingAccessor(obj interface{}) (Accessor, error) { 48 accessor, ok := obj.(Accessor) 49 if !ok { 50 // To handle obj deletion, try to fetch info from DeletedFinalStateUnknown. 51 tombstone, ok := obj.(cache.DeletedFinalStateUnknown) 52 if !ok { 53 return nil, fmt.Errorf("couldn't get Accessor from tombstone %#v", obj) 54 } 55 accessor, ok = tombstone.Obj.(Accessor) 56 if !ok { 57 return nil, fmt.Errorf("the object that Tombstone contained is not of kmeta.Accessor %#v", obj) 58 } 59 } 60 61 return accessor, nil 62 } 63 64 // ObjectReference returns an core/v1.ObjectReference for the given object 65 func ObjectReference(obj Accessor) corev1.ObjectReference { 66 gvk := obj.GroupVersionKind() 67 apiVersion, kind := gvk.ToAPIVersionAndKind() 68 69 return corev1.ObjectReference{ 70 APIVersion: apiVersion, 71 Kind: kind, 72 Namespace: obj.GetNamespace(), 73 Name: obj.GetName(), 74 } 75 }