patch.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Copyright 2019 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 service
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. v1 "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/types"
  19. "k8s.io/apimachinery/pkg/util/strategicpatch"
  20. v1core "k8s.io/client-go/kubernetes/typed/core/v1"
  21. )
  22. // patch patches service's Status or ObjectMeta given the origin and
  23. // updated ones. Change to spec will be ignored.
  24. func patch(c v1core.CoreV1Interface, oldSvc *v1.Service, newSvc *v1.Service) (*v1.Service, error) {
  25. // Reset spec to make sure only patch for Status or ObjectMeta.
  26. newSvc.Spec = oldSvc.Spec
  27. patchBytes, err := getPatchBytes(oldSvc, newSvc)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return c.Services(oldSvc.Namespace).Patch(oldSvc.Name, types.StrategicMergePatchType, patchBytes, "status")
  32. }
  33. func getPatchBytes(oldSvc *v1.Service, newSvc *v1.Service) ([]byte, error) {
  34. oldData, err := json.Marshal(oldSvc)
  35. if err != nil {
  36. return nil, fmt.Errorf("failed to Marshal oldData for svc %s/%s: %v", oldSvc.Namespace, oldSvc.Name, err)
  37. }
  38. newData, err := json.Marshal(newSvc)
  39. if err != nil {
  40. return nil, fmt.Errorf("failed to Marshal newData for svc %s/%s: %v", newSvc.Namespace, newSvc.Name, err)
  41. }
  42. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Service{})
  43. if err != nil {
  44. return nil, fmt.Errorf("failed to CreateTwoWayMergePatch for svc %s/%s: %v", oldSvc.Namespace, oldSvc.Name, err)
  45. }
  46. return patchBytes, nil
  47. }