Skip to content

Commit

Permalink
✨ Add client.StrategicMergeFrom
Browse files Browse the repository at this point in the history
  • Loading branch information
timebertt committed Mar 1, 2021
1 parent 1d02366 commit f3bea56
Show file tree
Hide file tree
Showing 2 changed files with 164 additions and 1 deletion.
94 changes: 93 additions & 1 deletion pkg/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3240,7 +3240,7 @@ var _ = Describe("DelegatingClient", func() {
})

var _ = Describe("Patch", func() {
Describe("CreateMergePatch", func() {
Describe("MergeFrom", func() {
var cm *corev1.ConfigMap

BeforeEach(func() {
Expand Down Expand Up @@ -3303,6 +3303,98 @@ var _ = Describe("Patch", func() {
Expect(data).To(Equal([]byte(fmt.Sprintf(`{"metadata":{"annotations":{"%s":"%s"},"resourceVersion":"%s"}}`, annotationKey, annotationValue, cm.ResourceVersion))))
})
})

Describe("StrategicMergeFrom", func() {
var dep *appsv1.Deployment

BeforeEach(func() {
dep = &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Namespace: metav1.NamespaceDefault,
Name: "dep",
ResourceVersion: "10",
},
Spec: appsv1.DeploymentSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{Containers: []corev1.Container{{
Name: "main",
Image: "foo:v1",
}, {
Name: "sidecar",
Image: "bar:v1",
}}},
},
},
}
})

It("creates a strategic merge patch with the modifications applied during the mutation", func() {
By("creating a strategic merge patch")
patch := client.StrategicMergeFrom(dep.DeepCopy())

By("returning a patch with type StrategicMergePatchType")
Expect(patch.Type()).To(Equal(types.StrategicMergePatchType))

By("updating the main container's image")
for i, c := range dep.Spec.Template.Spec.Containers {
if c.Name == "main" {
c.Image = "foo:v2"
}
dep.Spec.Template.Spec.Containers[i] = c
}

By("computing the patch data")
data, err := patch.Data(dep)

By("returning no error")
Expect(err).NotTo(HaveOccurred())

By("returning a patch with data only containing the image change")
Expect(data).To(Equal([]byte(`{"spec":{"template":{"spec":{"$setElementOrder/containers":[{"name":"main"},` +
`{"name":"sidecar"}],"containers":[{"image":"foo:v2","name":"main"}]}}}}`)))
})

It("creates a strategic merge patch with the modifications applied during the mutation, using optimistic locking", func() {
By("creating a strategic merge patch")
patch := client.StrategicMergeFromWithOptions(dep.DeepCopy(), client.MergeFromWithOptimisticLock{})

By("returning a patch with type StrategicMergePatchType")
Expect(patch.Type()).To(Equal(types.StrategicMergePatchType))

By("updating the main container's image")
for i, c := range dep.Spec.Template.Spec.Containers {
if c.Name == "main" {
c.Image = "foo:v2"
}
dep.Spec.Template.Spec.Containers[i] = c
}

By("computing the patch data")
data, err := patch.Data(dep)

By("returning no error")
Expect(err).NotTo(HaveOccurred())

By("returning a patch with data containing the image change and the resourceVersion change")
Expect(data).To(Equal([]byte(fmt.Sprintf(`{"metadata":{"resourceVersion":"%s"},`+
`"spec":{"template":{"spec":{"$setElementOrder/containers":[{"name":"main"},{"name":"sidecar"}],"containers":[{"image":"foo:v2","name":"main"}]}}}}`,
dep.ResourceVersion))))
})

It("fails if the resourceVersion was changed", func() {
By("creating a strategic merge patch")
patch := client.StrategicMergeFromWithOptions(dep.DeepCopy(), client.MergeFromWithOptimisticLock{})

By("updating the resourceVersion")
dep.SetResourceVersion("42")

By("computing the patch data")
_, err := patch.Data(dep)

By("returning no error")
Expect(err).To(MatchError(ContainSubstring("precondition failed")))
})
})
})

var _ = Describe("IgnoreNotFound", func() {
Expand Down
71 changes: 71 additions & 0 deletions pkg/client/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/mergepatch"
"k8s.io/apimachinery/pkg/util/strategicpatch"
)

var (
Expand Down Expand Up @@ -184,3 +186,72 @@ func (p applyPatch) Data(obj runtime.Object) ([]byte, error) {
// client-go does, more-or-less).
return json.Marshal(obj)
}

type strategicMergeFromPatch struct {
from runtime.Object
opts MergeFromOptions
}

// Type implements patch.
func (s *strategicMergeFromPatch) Type() types.PatchType {
return types.StrategicMergePatchType
}

// Data implements Patch.
func (s *strategicMergeFromPatch) Data(obj runtime.Object) ([]byte, error) {
originalJSON, err := json.Marshal(s.from)
if err != nil {
return nil, err
}

modifiedJSON, err := json.Marshal(obj)
if err != nil {
return nil, err
}

preconditions := []mergepatch.PreconditionFunc{
mergepatch.RequireMetadataKeyUnchanged("resourceVersion"),
}

data, err := strategicpatch.CreateTwoWayMergePatch(originalJSON, modifiedJSON, obj, preconditions...)
if err != nil {
return nil, err
}

if s.opts.OptimisticLock {
dataMap := map[string]interface{}{}
if err := json.Unmarshal(data, &dataMap); err != nil {
return nil, err
}
fromMeta, ok := s.from.(metav1.Object)
if !ok {
return nil, fmt.Errorf("cannot use OptimisticLock, from object %q is not a valid metav1.Object", s.from)
}
resourceVersion := fromMeta.GetResourceVersion()
if len(resourceVersion) == 0 {
return nil, fmt.Errorf("cannot use OptimisticLock, from object %q does not have any resource version we can use", s.from)
}
u := &unstructured.Unstructured{Object: dataMap}
u.SetResourceVersion(resourceVersion)
data, err = json.Marshal(u)
if err != nil {
return nil, err
}
}

return data, nil
}

// StrategicMergeFrom creates a Patch that patches using the strategic-merge-patch strategy with the given object as base.
func StrategicMergeFrom(obj runtime.Object) Patch {
return &strategicMergeFromPatch{from: obj}
}

// StrategicMergeFromWithOptions creates a Patch that patches using the strategic-merge-patch strategy with the given object as base.
func StrategicMergeFromWithOptions(obj runtime.Object, opts ...MergeFromOption) Patch {
options := &MergeFromOptions{}
for _, opt := range opts {
opt.ApplyToMergeFrom(options)
}
return &strategicMergeFromPatch{from: obj, opts: *options}
}

0 comments on commit f3bea56

Please sign in to comment.