apply.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. Copyright 2024 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 apply
  14. import (
  15. "fmt"
  16. cbor "k8s.io/apimachinery/pkg/runtime/serializer/cbor/direct"
  17. "k8s.io/apimachinery/pkg/types"
  18. "k8s.io/apimachinery/pkg/util/json"
  19. "k8s.io/client-go/features"
  20. "k8s.io/client-go/rest"
  21. )
  22. // NewRequest builds a new server-side apply request. The provided apply configuration object will
  23. // be marshalled to the request's body using the default encoding, and the Content-Type header will
  24. // be set to application/apply-patch with the appropriate structured syntax name suffix (today,
  25. // either +yaml or +cbor, see
  26. // https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml).
  27. func NewRequest(client rest.Interface, applyConfiguration interface{}) (*rest.Request, error) {
  28. pt := types.ApplyYAMLPatchType
  29. marshal := json.Marshal
  30. if features.FeatureGates().Enabled(features.ClientsAllowCBOR) && features.FeatureGates().Enabled(features.ClientsPreferCBOR) {
  31. pt = types.ApplyCBORPatchType
  32. marshal = cbor.Marshal
  33. }
  34. body, err := marshal(applyConfiguration)
  35. if err != nil {
  36. return nil, fmt.Errorf("failed to marshal apply configuration: %w", err)
  37. }
  38. return client.Patch(pt).Body(body), nil
  39. }