Skip to content

Commit f3bea56

Browse files
committed
✨ Add client.StrategicMergeFrom
1 parent 1d02366 commit f3bea56

File tree

2 files changed

+164
-1
lines changed

2 files changed

+164
-1
lines changed

pkg/client/client_test.go

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3240,7 +3240,7 @@ var _ = Describe("DelegatingClient", func() {
32403240
})
32413241

32423242
var _ = Describe("Patch", func() {
3243-
Describe("CreateMergePatch", func() {
3243+
Describe("MergeFrom", func() {
32443244
var cm *corev1.ConfigMap
32453245

32463246
BeforeEach(func() {
@@ -3303,6 +3303,98 @@ var _ = Describe("Patch", func() {
33033303
Expect(data).To(Equal([]byte(fmt.Sprintf(`{"metadata":{"annotations":{"%s":"%s"},"resourceVersion":"%s"}}`, annotationKey, annotationValue, cm.ResourceVersion))))
33043304
})
33053305
})
3306+
3307+
Describe("StrategicMergeFrom", func() {
3308+
var dep *appsv1.Deployment
3309+
3310+
BeforeEach(func() {
3311+
dep = &appsv1.Deployment{
3312+
ObjectMeta: metav1.ObjectMeta{
3313+
Namespace: metav1.NamespaceDefault,
3314+
Name: "dep",
3315+
ResourceVersion: "10",
3316+
},
3317+
Spec: appsv1.DeploymentSpec{
3318+
Template: corev1.PodTemplateSpec{
3319+
Spec: corev1.PodSpec{Containers: []corev1.Container{{
3320+
Name: "main",
3321+
Image: "foo:v1",
3322+
}, {
3323+
Name: "sidecar",
3324+
Image: "bar:v1",
3325+
}}},
3326+
},
3327+
},
3328+
}
3329+
})
3330+
3331+
It("creates a strategic merge patch with the modifications applied during the mutation", func() {
3332+
By("creating a strategic merge patch")
3333+
patch := client.StrategicMergeFrom(dep.DeepCopy())
3334+
3335+
By("returning a patch with type StrategicMergePatchType")
3336+
Expect(patch.Type()).To(Equal(types.StrategicMergePatchType))
3337+
3338+
By("updating the main container's image")
3339+
for i, c := range dep.Spec.Template.Spec.Containers {
3340+
if c.Name == "main" {
3341+
c.Image = "foo:v2"
3342+
}
3343+
dep.Spec.Template.Spec.Containers[i] = c
3344+
}
3345+
3346+
By("computing the patch data")
3347+
data, err := patch.Data(dep)
3348+
3349+
By("returning no error")
3350+
Expect(err).NotTo(HaveOccurred())
3351+
3352+
By("returning a patch with data only containing the image change")
3353+
Expect(data).To(Equal([]byte(`{"spec":{"template":{"spec":{"$setElementOrder/containers":[{"name":"main"},` +
3354+
`{"name":"sidecar"}],"containers":[{"image":"foo:v2","name":"main"}]}}}}`)))
3355+
})
3356+
3357+
It("creates a strategic merge patch with the modifications applied during the mutation, using optimistic locking", func() {
3358+
By("creating a strategic merge patch")
3359+
patch := client.StrategicMergeFromWithOptions(dep.DeepCopy(), client.MergeFromWithOptimisticLock{})
3360+
3361+
By("returning a patch with type StrategicMergePatchType")
3362+
Expect(patch.Type()).To(Equal(types.StrategicMergePatchType))
3363+
3364+
By("updating the main container's image")
3365+
for i, c := range dep.Spec.Template.Spec.Containers {
3366+
if c.Name == "main" {
3367+
c.Image = "foo:v2"
3368+
}
3369+
dep.Spec.Template.Spec.Containers[i] = c
3370+
}
3371+
3372+
By("computing the patch data")
3373+
data, err := patch.Data(dep)
3374+
3375+
By("returning no error")
3376+
Expect(err).NotTo(HaveOccurred())
3377+
3378+
By("returning a patch with data containing the image change and the resourceVersion change")
3379+
Expect(data).To(Equal([]byte(fmt.Sprintf(`{"metadata":{"resourceVersion":"%s"},`+
3380+
`"spec":{"template":{"spec":{"$setElementOrder/containers":[{"name":"main"},{"name":"sidecar"}],"containers":[{"image":"foo:v2","name":"main"}]}}}}`,
3381+
dep.ResourceVersion))))
3382+
})
3383+
3384+
It("fails if the resourceVersion was changed", func() {
3385+
By("creating a strategic merge patch")
3386+
patch := client.StrategicMergeFromWithOptions(dep.DeepCopy(), client.MergeFromWithOptimisticLock{})
3387+
3388+
By("updating the resourceVersion")
3389+
dep.SetResourceVersion("42")
3390+
3391+
By("computing the patch data")
3392+
_, err := patch.Data(dep)
3393+
3394+
By("returning no error")
3395+
Expect(err).To(MatchError(ContainSubstring("precondition failed")))
3396+
})
3397+
})
33063398
})
33073399

33083400
var _ = Describe("IgnoreNotFound", func() {

pkg/client/patch.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ import (
2525
"k8s.io/apimachinery/pkg/runtime"
2626
"k8s.io/apimachinery/pkg/types"
2727
"k8s.io/apimachinery/pkg/util/json"
28+
"k8s.io/apimachinery/pkg/util/mergepatch"
29+
"k8s.io/apimachinery/pkg/util/strategicpatch"
2830
)
2931

3032
var (
@@ -184,3 +186,72 @@ func (p applyPatch) Data(obj runtime.Object) ([]byte, error) {
184186
// client-go does, more-or-less).
185187
return json.Marshal(obj)
186188
}
189+
190+
type strategicMergeFromPatch struct {
191+
from runtime.Object
192+
opts MergeFromOptions
193+
}
194+
195+
// Type implements patch.
196+
func (s *strategicMergeFromPatch) Type() types.PatchType {
197+
return types.StrategicMergePatchType
198+
}
199+
200+
// Data implements Patch.
201+
func (s *strategicMergeFromPatch) Data(obj runtime.Object) ([]byte, error) {
202+
originalJSON, err := json.Marshal(s.from)
203+
if err != nil {
204+
return nil, err
205+
}
206+
207+
modifiedJSON, err := json.Marshal(obj)
208+
if err != nil {
209+
return nil, err
210+
}
211+
212+
preconditions := []mergepatch.PreconditionFunc{
213+
mergepatch.RequireMetadataKeyUnchanged("resourceVersion"),
214+
}
215+
216+
data, err := strategicpatch.CreateTwoWayMergePatch(originalJSON, modifiedJSON, obj, preconditions...)
217+
if err != nil {
218+
return nil, err
219+
}
220+
221+
if s.opts.OptimisticLock {
222+
dataMap := map[string]interface{}{}
223+
if err := json.Unmarshal(data, &dataMap); err != nil {
224+
return nil, err
225+
}
226+
fromMeta, ok := s.from.(metav1.Object)
227+
if !ok {
228+
return nil, fmt.Errorf("cannot use OptimisticLock, from object %q is not a valid metav1.Object", s.from)
229+
}
230+
resourceVersion := fromMeta.GetResourceVersion()
231+
if len(resourceVersion) == 0 {
232+
return nil, fmt.Errorf("cannot use OptimisticLock, from object %q does not have any resource version we can use", s.from)
233+
}
234+
u := &unstructured.Unstructured{Object: dataMap}
235+
u.SetResourceVersion(resourceVersion)
236+
data, err = json.Marshal(u)
237+
if err != nil {
238+
return nil, err
239+
}
240+
}
241+
242+
return data, nil
243+
}
244+
245+
// StrategicMergeFrom creates a Patch that patches using the strategic-merge-patch strategy with the given object as base.
246+
func StrategicMergeFrom(obj runtime.Object) Patch {
247+
return &strategicMergeFromPatch{from: obj}
248+
}
249+
250+
// StrategicMergeFromWithOptions creates a Patch that patches using the strategic-merge-patch strategy with the given object as base.
251+
func StrategicMergeFromWithOptions(obj runtime.Object, opts ...MergeFromOption) Patch {
252+
options := &MergeFromOptions{}
253+
for _, opt := range opts {
254+
opt.ApplyToMergeFrom(options)
255+
}
256+
return &strategicMergeFromPatch{from: obj, opts: *options}
257+
}

0 commit comments

Comments
 (0)