mirror_client.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package pod
  14. import (
  15. "context"
  16. "fmt"
  17. v1 "k8s.io/api/core/v1"
  18. apierrors "k8s.io/apimachinery/pkg/api/errors"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/types"
  21. clientset "k8s.io/client-go/kubernetes"
  22. "k8s.io/klog"
  23. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  24. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  25. )
  26. // MirrorClient knows how to create/delete a mirror pod in the API server.
  27. type MirrorClient interface {
  28. // CreateMirrorPod creates a mirror pod in the API server for the given
  29. // pod or returns an error. The mirror pod will have the same annotations
  30. // as the given pod as well as an extra annotation containing the hash of
  31. // the static pod.
  32. CreateMirrorPod(pod *v1.Pod) error
  33. // DeleteMirrorPod deletes the mirror pod with the given full name from
  34. // the API server or returns an error.
  35. DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error)
  36. }
  37. // nodeGetter is a subset a NodeLister, simplified for testing.
  38. type nodeGetter interface {
  39. // Get retrieves the Node for a given name.
  40. Get(name string) (*v1.Node, error)
  41. }
  42. // basicMirrorClient is a functional MirrorClient. Mirror pods are stored in
  43. // the kubelet directly because they need to be in sync with the internal
  44. // pods.
  45. type basicMirrorClient struct {
  46. apiserverClient clientset.Interface
  47. nodeGetter nodeGetter
  48. nodeName string
  49. }
  50. // NewBasicMirrorClient returns a new MirrorClient.
  51. func NewBasicMirrorClient(apiserverClient clientset.Interface, nodeName string, nodeGetter nodeGetter) MirrorClient {
  52. return &basicMirrorClient{
  53. apiserverClient: apiserverClient,
  54. nodeName: nodeName,
  55. nodeGetter: nodeGetter,
  56. }
  57. }
  58. func (mc *basicMirrorClient) CreateMirrorPod(pod *v1.Pod) error {
  59. if mc.apiserverClient == nil {
  60. return nil
  61. }
  62. // Make a copy of the pod.
  63. copyPod := *pod
  64. copyPod.Annotations = make(map[string]string)
  65. for k, v := range pod.Annotations {
  66. copyPod.Annotations[k] = v
  67. }
  68. hash := getPodHash(pod)
  69. copyPod.Annotations[kubetypes.ConfigMirrorAnnotationKey] = hash
  70. // With the MirrorPodNodeRestriction feature, mirror pods are required to have an owner reference
  71. // to the owning node.
  72. // See http://git.k8s.io/enhancements/keps/sig-auth/20190916-noderestriction-pods.md
  73. nodeUID, err := mc.getNodeUID()
  74. if err != nil {
  75. return fmt.Errorf("failed to get node UID: %v", err)
  76. }
  77. controller := true
  78. copyPod.OwnerReferences = []metav1.OwnerReference{{
  79. APIVersion: v1.SchemeGroupVersion.String(),
  80. Kind: "Node",
  81. Name: mc.nodeName,
  82. UID: nodeUID,
  83. Controller: &controller,
  84. }}
  85. apiPod, err := mc.apiserverClient.CoreV1().Pods(copyPod.Namespace).Create(context.TODO(), &copyPod, metav1.CreateOptions{})
  86. if err != nil && apierrors.IsAlreadyExists(err) {
  87. // Check if the existing pod is the same as the pod we want to create.
  88. if h, ok := apiPod.Annotations[kubetypes.ConfigMirrorAnnotationKey]; ok && h == hash {
  89. return nil
  90. }
  91. }
  92. return err
  93. }
  94. // DeleteMirrorPod deletes a mirror pod.
  95. // It takes the full name of the pod and optionally a UID. If the UID
  96. // is non-nil, the pod is deleted only if its UID matches the supplied UID.
  97. // It returns whether the pod was actually deleted, and any error returned
  98. // while parsing the name of the pod.
  99. // Non-existence of the pod or UID mismatch is not treated as an error; the
  100. // routine simply returns false in that case.
  101. func (mc *basicMirrorClient) DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error) {
  102. if mc.apiserverClient == nil {
  103. return false, nil
  104. }
  105. name, namespace, err := kubecontainer.ParsePodFullName(podFullName)
  106. if err != nil {
  107. klog.Errorf("Failed to parse a pod full name %q", podFullName)
  108. return false, err
  109. }
  110. klog.V(2).Infof("Deleting a mirror pod %q (uid %#v)", podFullName, uid)
  111. var GracePeriodSeconds int64
  112. if err := mc.apiserverClient.CoreV1().Pods(namespace).Delete(context.TODO(), name, &metav1.DeleteOptions{GracePeriodSeconds: &GracePeriodSeconds, Preconditions: &metav1.Preconditions{UID: uid}}); err != nil {
  113. // Unfortunately, there's no generic error for failing a precondition
  114. if !(apierrors.IsNotFound(err) || apierrors.IsConflict(err)) {
  115. // We should return the error here, but historically this routine does
  116. // not return an error unless it can't parse the pod name
  117. klog.Errorf("Failed deleting a mirror pod %q: %v", podFullName, err)
  118. }
  119. return false, nil
  120. }
  121. return true, nil
  122. }
  123. func (mc *basicMirrorClient) getNodeUID() (types.UID, error) {
  124. node, err := mc.nodeGetter.Get(mc.nodeName)
  125. if err != nil {
  126. return "", err
  127. }
  128. if node.UID == "" {
  129. return "", fmt.Errorf("UID unset for node %s", mc.nodeName)
  130. }
  131. return node.UID, nil
  132. }
  133. // IsStaticPod returns true if the passed Pod is static.
  134. func IsStaticPod(pod *v1.Pod) bool {
  135. source, err := kubetypes.GetPodSource(pod)
  136. return err == nil && source != kubetypes.ApiserverSource
  137. }
  138. func getHashFromMirrorPod(pod *v1.Pod) (string, bool) {
  139. hash, ok := pod.Annotations[kubetypes.ConfigMirrorAnnotationKey]
  140. return hash, ok
  141. }
  142. func getPodHash(pod *v1.Pod) string {
  143. // The annotation exists for all static pods.
  144. return pod.Annotations[kubetypes.ConfigHashAnnotationKey]
  145. }