k8s.io/kubernetes@v1.29.3/pkg/kubelet/pod/mirror_client.go (about)

     1  /*
     2  Copyright 2015 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 pod
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	v1 "k8s.io/api/core/v1"
    24  	apierrors "k8s.io/apimachinery/pkg/api/errors"
    25  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    26  	"k8s.io/apimachinery/pkg/types"
    27  	clientset "k8s.io/client-go/kubernetes"
    28  	"k8s.io/klog/v2"
    29  	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
    30  	kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
    31  )
    32  
    33  // MirrorClient knows how to create/delete a mirror pod in the API server.
    34  type MirrorClient interface {
    35  	// CreateMirrorPod creates a mirror pod in the API server for the given
    36  	// pod or returns an error.  The mirror pod will have the same annotations
    37  	// as the given pod as well as an extra annotation containing the hash of
    38  	// the static pod.
    39  	CreateMirrorPod(pod *v1.Pod) error
    40  	// DeleteMirrorPod deletes the mirror pod with the given full name from
    41  	// the API server or returns an error.
    42  	DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error)
    43  }
    44  
    45  // nodeGetter is a subset of NodeLister, simplified for testing.
    46  type nodeGetter interface {
    47  	// Get retrieves the Node for a given name.
    48  	Get(name string) (*v1.Node, error)
    49  }
    50  
    51  // basicMirrorClient is a functional MirrorClient.  Mirror pods are stored in
    52  // the kubelet directly because they need to be in sync with the internal
    53  // pods.
    54  type basicMirrorClient struct {
    55  	apiserverClient clientset.Interface
    56  	nodeGetter      nodeGetter
    57  	nodeName        string
    58  }
    59  
    60  // NewBasicMirrorClient returns a new MirrorClient.
    61  func NewBasicMirrorClient(apiserverClient clientset.Interface, nodeName string, nodeGetter nodeGetter) MirrorClient {
    62  	return &basicMirrorClient{
    63  		apiserverClient: apiserverClient,
    64  		nodeName:        nodeName,
    65  		nodeGetter:      nodeGetter,
    66  	}
    67  }
    68  
    69  func (mc *basicMirrorClient) CreateMirrorPod(pod *v1.Pod) error {
    70  	if mc.apiserverClient == nil {
    71  		return nil
    72  	}
    73  	// Make a copy of the pod.
    74  	copyPod := *pod
    75  	copyPod.Annotations = make(map[string]string)
    76  
    77  	for k, v := range pod.Annotations {
    78  		copyPod.Annotations[k] = v
    79  	}
    80  	hash := getPodHash(pod)
    81  	copyPod.Annotations[kubetypes.ConfigMirrorAnnotationKey] = hash
    82  
    83  	// With the MirrorPodNodeRestriction feature, mirror pods are required to have an owner reference
    84  	// to the owning node.
    85  	// See https://git.k8s.io/enhancements/keps/sig-auth/1314-node-restriction-pods/README.md
    86  	nodeUID, err := mc.getNodeUID()
    87  	if err != nil {
    88  		return fmt.Errorf("failed to get node UID: %v", err)
    89  	}
    90  	controller := true
    91  	copyPod.OwnerReferences = []metav1.OwnerReference{{
    92  		APIVersion: v1.SchemeGroupVersion.String(),
    93  		Kind:       "Node",
    94  		Name:       mc.nodeName,
    95  		UID:        nodeUID,
    96  		Controller: &controller,
    97  	}}
    98  
    99  	apiPod, err := mc.apiserverClient.CoreV1().Pods(copyPod.Namespace).Create(context.TODO(), &copyPod, metav1.CreateOptions{})
   100  	if err != nil && apierrors.IsAlreadyExists(err) {
   101  		// Check if the existing pod is the same as the pod we want to create.
   102  		if h, ok := apiPod.Annotations[kubetypes.ConfigMirrorAnnotationKey]; ok && h == hash {
   103  			return nil
   104  		}
   105  	}
   106  	return err
   107  }
   108  
   109  // DeleteMirrorPod deletes a mirror pod.
   110  // It takes the full name of the pod and optionally a UID.  If the UID
   111  // is non-nil, the pod is deleted only if its UID matches the supplied UID.
   112  // It returns whether the pod was actually deleted, and any error returned
   113  // while parsing the name of the pod.
   114  // Non-existence of the pod or UID mismatch is not treated as an error; the
   115  // routine simply returns false in that case.
   116  func (mc *basicMirrorClient) DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error) {
   117  	if mc.apiserverClient == nil {
   118  		return false, nil
   119  	}
   120  	name, namespace, err := kubecontainer.ParsePodFullName(podFullName)
   121  	if err != nil {
   122  		klog.ErrorS(err, "Failed to parse a pod full name", "podFullName", podFullName)
   123  		return false, err
   124  	}
   125  
   126  	var uidValue types.UID
   127  	if uid != nil {
   128  		uidValue = *uid
   129  	}
   130  	klog.V(2).InfoS("Deleting a mirror pod", "pod", klog.KRef(namespace, name), "podUID", uidValue)
   131  
   132  	var GracePeriodSeconds int64
   133  	if err := mc.apiserverClient.CoreV1().Pods(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{GracePeriodSeconds: &GracePeriodSeconds, Preconditions: &metav1.Preconditions{UID: uid}}); err != nil {
   134  		// Unfortunately, there's no generic error for failing a precondition
   135  		if !(apierrors.IsNotFound(err) || apierrors.IsConflict(err)) {
   136  			// We should return the error here, but historically this routine does
   137  			// not return an error unless it can't parse the pod name
   138  			klog.ErrorS(err, "Failed deleting a mirror pod", "pod", klog.KRef(namespace, name))
   139  		}
   140  		return false, nil
   141  	}
   142  	return true, nil
   143  }
   144  
   145  func (mc *basicMirrorClient) getNodeUID() (types.UID, error) {
   146  	node, err := mc.nodeGetter.Get(mc.nodeName)
   147  	if err != nil {
   148  		return "", err
   149  	}
   150  	if node.UID == "" {
   151  		return "", fmt.Errorf("UID unset for node %s", mc.nodeName)
   152  	}
   153  	return node.UID, nil
   154  }
   155  
   156  func getHashFromMirrorPod(pod *v1.Pod) (string, bool) {
   157  	hash, ok := pod.Annotations[kubetypes.ConfigMirrorAnnotationKey]
   158  	return hash, ok
   159  }
   160  
   161  func getPodHash(pod *v1.Pod) string {
   162  	// The annotation exists for all static pods.
   163  	return pod.Annotations[kubetypes.ConfigHashAnnotationKey]
   164  }