k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/pkg/kubelet/util/nodelease.go (about) 1 /* 2 Copyright 2020 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 util 18 19 import ( 20 "context" 21 22 coordinationv1 "k8s.io/api/coordination/v1" 23 corev1 "k8s.io/api/core/v1" 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 clientset "k8s.io/client-go/kubernetes" 26 27 "k8s.io/klog/v2" 28 ) 29 30 // SetNodeOwnerFunc helps construct a newLeasePostProcessFunc which sets 31 // a node OwnerReference to the given lease object 32 func SetNodeOwnerFunc(c clientset.Interface, nodeName string) func(lease *coordinationv1.Lease) error { 33 return func(lease *coordinationv1.Lease) error { 34 // Setting owner reference needs node's UID. Note that it is different from 35 // kubelet.nodeRef.UID. When lease is initially created, it is possible that 36 // the connection between master and node is not ready yet. So try to set 37 // owner reference every time when renewing the lease, until successful. 38 if len(lease.OwnerReferences) == 0 { 39 if node, err := c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{}); err == nil { 40 lease.OwnerReferences = []metav1.OwnerReference{ 41 { 42 APIVersion: corev1.SchemeGroupVersion.WithKind("Node").Version, 43 Kind: corev1.SchemeGroupVersion.WithKind("Node").Kind, 44 Name: nodeName, 45 UID: node.UID, 46 }, 47 } 48 } else { 49 klog.ErrorS(err, "Failed to get node when trying to set owner ref to the node lease", "node", klog.KRef("", nodeName)) 50 return err 51 } 52 } 53 return nil 54 } 55 }