pod.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Copyright 2018 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. "encoding/json"
  17. "fmt"
  18. v1 "k8s.io/api/core/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/types"
  21. "k8s.io/apimachinery/pkg/util/strategicpatch"
  22. clientset "k8s.io/client-go/kubernetes"
  23. )
  24. // PatchPodStatus patches pod status.
  25. func PatchPodStatus(c clientset.Interface, namespace, name string, uid types.UID, oldPodStatus, newPodStatus v1.PodStatus) (*v1.Pod, []byte, error) {
  26. patchBytes, err := preparePatchBytesForPodStatus(namespace, name, uid, oldPodStatus, newPodStatus)
  27. if err != nil {
  28. return nil, nil, err
  29. }
  30. updatedPod, err := c.CoreV1().Pods(namespace).Patch(context.TODO(), name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, "status")
  31. if err != nil {
  32. return nil, nil, fmt.Errorf("failed to patch status %q for pod %q/%q: %v", patchBytes, namespace, name, err)
  33. }
  34. return updatedPod, patchBytes, nil
  35. }
  36. func preparePatchBytesForPodStatus(namespace, name string, uid types.UID, oldPodStatus, newPodStatus v1.PodStatus) ([]byte, error) {
  37. oldData, err := json.Marshal(v1.Pod{
  38. Status: oldPodStatus,
  39. })
  40. if err != nil {
  41. return nil, fmt.Errorf("failed to Marshal oldData for pod %q/%q: %v", namespace, name, err)
  42. }
  43. newData, err := json.Marshal(v1.Pod{
  44. ObjectMeta: metav1.ObjectMeta{UID: uid}, // only put the uid in the new object to ensure it appears in the patch as a precondition
  45. Status: newPodStatus,
  46. })
  47. if err != nil {
  48. return nil, fmt.Errorf("failed to Marshal newData for pod %q/%q: %v", namespace, name, err)
  49. }
  50. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Pod{})
  51. if err != nil {
  52. return nil, fmt.Errorf("failed to CreateTwoWayMergePatch for pod %q/%q: %v", namespace, name, err)
  53. }
  54. return patchBytes, nil
  55. }