-
Notifications
You must be signed in to change notification settings - Fork 550
/
Copy pathpatch.go
2257 lines (2045 loc) · 75.8 KB
/
patch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package strategicpatch
import (
"fmt"
"reflect"
"sort"
"strings"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/mergepatch"
)
// An alternate implementation of JSON Merge Patch
// (https://tools.ietf.org/html/rfc7386) which supports the ability to annotate
// certain fields with metadata that indicates whether the elements of JSON
// lists should be merged or replaced.
//
// For more information, see the PATCH section of docs/devel/api-conventions.md.
//
// Some of the content of this package was borrowed with minor adaptations from
// evanphx/json-patch and openshift/origin.
const (
directiveMarker = "$patch"
deleteDirective = "delete"
replaceDirective = "replace"
mergeDirective = "merge"
retainKeysStrategy = "retainKeys"
deleteFromPrimitiveListDirectivePrefix = "$deleteFromPrimitiveList"
retainKeysDirective = "$" + retainKeysStrategy
setElementOrderDirectivePrefix = "$setElementOrder"
)
// JSONMap is a representations of JSON object encoded as map[string]interface{}
// where the children can be either map[string]interface{}, []interface{} or
// primitive type).
// Operating on JSONMap representation is much faster as it doesn't require any
// json marshaling and/or unmarshaling operations.
type JSONMap map[string]interface{}
type DiffOptions struct {
// SetElementOrder determines whether we generate the $setElementOrder parallel list.
SetElementOrder bool
// IgnoreChangesAndAdditions indicates if we keep the changes and additions in the patch.
IgnoreChangesAndAdditions bool
// IgnoreDeletions indicates if we keep the deletions in the patch.
IgnoreDeletions bool
// We introduce a new value retainKeys for patchStrategy.
// It indicates that all fields needing to be preserved must be
// present in the `retainKeys` list.
// And the fields that are present will be merged with live object.
// All the missing fields will be cleared when patching.
BuildRetainKeysDirective bool
}
type MergeOptions struct {
// MergeParallelList indicates if we are merging the parallel list.
// We don't merge parallel list when calling mergeMap() in CreateThreeWayMergePatch()
// which is called client-side.
// We merge parallel list iff when calling mergeMap() in StrategicMergeMapPatch()
// which is called server-side
MergeParallelList bool
// IgnoreUnmatchedNulls indicates if we should process the unmatched nulls.
IgnoreUnmatchedNulls bool
}
// The following code is adapted from github.com/openshift/origin/pkg/util/jsonmerge.
// Instead of defining a Delta that holds an original, a patch and a set of preconditions,
// the reconcile method accepts a set of preconditions as an argument.
// CreateTwoWayMergePatch creates a patch that can be passed to StrategicMergePatch from an original
// document and a modified document, which are passed to the method as json encoded content. It will
// return a patch that yields the modified document when applied to the original document, or an error
// if either of the two documents is invalid.
func CreateTwoWayMergePatch(original, modified []byte, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) {
schema, err := NewPatchMetaFromStruct(dataStruct)
if err != nil {
return nil, err
}
return CreateTwoWayMergePatchUsingLookupPatchMeta(original, modified, schema, fns...)
}
func CreateTwoWayMergePatchUsingLookupPatchMeta(
original, modified []byte, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) ([]byte, error) {
originalMap := map[string]interface{}{}
if len(original) > 0 {
if err := json.Unmarshal(original, &originalMap); err != nil {
return nil, mergepatch.ErrBadJSONDoc
}
}
modifiedMap := map[string]interface{}{}
if len(modified) > 0 {
if err := json.Unmarshal(modified, &modifiedMap); err != nil {
return nil, mergepatch.ErrBadJSONDoc
}
}
patchMap, err := CreateTwoWayMergeMapPatchUsingLookupPatchMeta(originalMap, modifiedMap, schema, fns...)
if err != nil {
return nil, err
}
return json.Marshal(patchMap)
}
// CreateTwoWayMergeMapPatch creates a patch from an original and modified JSON objects,
// encoded JSONMap.
// The serialized version of the map can then be passed to StrategicMergeMapPatch.
func CreateTwoWayMergeMapPatch(original, modified JSONMap, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) (JSONMap, error) {
schema, err := NewPatchMetaFromStruct(dataStruct)
if err != nil {
return nil, err
}
return CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified, schema, fns...)
}
func CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified JSONMap, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) (JSONMap, error) {
diffOptions := DiffOptions{
SetElementOrder: true,
}
patchMap, err := diffMaps(original, modified, schema, diffOptions)
if err != nil {
return nil, err
}
// Apply the preconditions to the patch, and return an error if any of them fail.
for _, fn := range fns {
if !fn(patchMap) {
return nil, mergepatch.NewErrPreconditionFailed(patchMap)
}
}
return patchMap, nil
}
// Returns a (recursive) strategic merge patch that yields modified when applied to original.
// Including:
// - Adding fields to the patch present in modified, missing from original
// - Setting fields to the patch present in modified and original with different values
// - Delete fields present in original, missing from modified through
// - IFF map field - set to nil in patch
// - IFF list of maps && merge strategy - use deleteDirective for the elements
// - IFF list of primitives && merge strategy - use parallel deletion list
// - IFF list of maps or primitives with replace strategy (default) - set patch value to the value in modified
// - Build $retainKeys directive for fields with retainKeys patch strategy
func diffMaps(original, modified map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) (map[string]interface{}, error) {
patch := map[string]interface{}{}
// This will be used to build the $retainKeys directive sent in the patch
retainKeysList := make([]interface{}, 0, len(modified))
// Compare each value in the modified map against the value in the original map
for key, modifiedValue := range modified {
// Get the underlying type for pointers
if diffOptions.BuildRetainKeysDirective && modifiedValue != nil {
retainKeysList = append(retainKeysList, key)
}
originalValue, ok := original[key]
if !ok {
// Key was added, so add to patch
if !diffOptions.IgnoreChangesAndAdditions {
patch[key] = modifiedValue
}
continue
}
// The patch may have a patch directive
// TODO: figure out if we need this. This shouldn't be needed by apply. When would the original map have patch directives in it?
foundDirectiveMarker, err := handleDirectiveMarker(key, originalValue, modifiedValue, patch)
if err != nil {
return nil, err
}
if foundDirectiveMarker {
continue
}
if reflect.TypeOf(originalValue) != reflect.TypeOf(modifiedValue) {
// Types have changed, so add to patch
if !diffOptions.IgnoreChangesAndAdditions {
patch[key] = modifiedValue
}
continue
}
// Types are the same, so compare values
switch originalValueTyped := originalValue.(type) {
case map[string]interface{}:
modifiedValueTyped := modifiedValue.(map[string]interface{})
err = handleMapDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)
case []interface{}:
modifiedValueTyped := modifiedValue.([]interface{})
err = handleSliceDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)
default:
replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)
}
if err != nil {
return nil, err
}
}
updatePatchIfMissing(original, modified, patch, diffOptions)
// Insert the retainKeysList iff there are values present in the retainKeysList and
// either of the following is true:
// - the patch is not empty
// - there are additional field in original that need to be cleared
if len(retainKeysList) > 0 &&
(len(patch) > 0 || hasAdditionalNewField(original, modified)) {
patch[retainKeysDirective] = sortScalars(retainKeysList)
}
return patch, nil
}
// handleDirectiveMarker handles how to diff directive marker between 2 objects
func handleDirectiveMarker(key string, originalValue, modifiedValue interface{}, patch map[string]interface{}) (bool, error) {
if key == directiveMarker {
originalString, ok := originalValue.(string)
if !ok {
return false, fmt.Errorf("invalid value for special key: %s", directiveMarker)
}
modifiedString, ok := modifiedValue.(string)
if !ok {
return false, fmt.Errorf("invalid value for special key: %s", directiveMarker)
}
if modifiedString != originalString {
patch[directiveMarker] = modifiedValue
}
return true, nil
}
return false, nil
}
// handleMapDiff diff between 2 maps `originalValueTyped` and `modifiedValue`,
// puts the diff in the `patch` associated with `key`
// key is the key associated with originalValue and modifiedValue.
// originalValue, modifiedValue are the old and new value respectively.They are both maps
// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue
// diffOptions contains multiple options to control how we do the diff.
func handleMapDiff(key string, originalValue, modifiedValue, patch map[string]interface{},
schema LookupPatchMeta, diffOptions DiffOptions) error {
subschema, patchMeta, err := schema.LookupPatchMetadataForStruct(key)
if err != nil {
// We couldn't look up metadata for the field
// If the values are identical, this doesn't matter, no patch is needed
if reflect.DeepEqual(originalValue, modifiedValue) {
return nil
}
// Otherwise, return the error
return err
}
retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
if err != nil {
return err
}
diffOptions.BuildRetainKeysDirective = retainKeys
switch patchStrategy {
// The patch strategic from metadata tells us to replace the entire object instead of diffing it
case replaceDirective:
if !diffOptions.IgnoreChangesAndAdditions {
patch[key] = modifiedValue
}
default:
patchValue, err := diffMaps(originalValue, modifiedValue, subschema, diffOptions)
if err != nil {
return err
}
// Maps were not identical, use provided patch value
if len(patchValue) > 0 {
patch[key] = patchValue
}
}
return nil
}
// handleSliceDiff diff between 2 slices `originalValueTyped` and `modifiedValue`,
// puts the diff in the `patch` associated with `key`
// key is the key associated with originalValue and modifiedValue.
// originalValue, modifiedValue are the old and new value respectively.They are both slices
// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue
// diffOptions contains multiple options to control how we do the diff.
func handleSliceDiff(key string, originalValue, modifiedValue []interface{}, patch map[string]interface{},
schema LookupPatchMeta, diffOptions DiffOptions) error {
subschema, patchMeta, err := schema.LookupPatchMetadataForSlice(key)
if err != nil {
// We couldn't look up metadata for the field
// If the values are identical, this doesn't matter, no patch is needed
if reflect.DeepEqual(originalValue, modifiedValue) {
return nil
}
// Otherwise, return the error
return err
}
retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
if err != nil {
return err
}
switch patchStrategy {
// Merge the 2 slices using mergePatchKey
case mergeDirective:
diffOptions.BuildRetainKeysDirective = retainKeys
addList, deletionList, setOrderList, err := diffLists(originalValue, modifiedValue, subschema, patchMeta.GetPatchMergeKey(), diffOptions)
if err != nil {
return err
}
if len(addList) > 0 {
patch[key] = addList
}
// generate a parallel list for deletion
if len(deletionList) > 0 {
parallelDeletionListKey := fmt.Sprintf("%s/%s", deleteFromPrimitiveListDirectivePrefix, key)
patch[parallelDeletionListKey] = deletionList
}
if len(setOrderList) > 0 {
parallelSetOrderListKey := fmt.Sprintf("%s/%s", setElementOrderDirectivePrefix, key)
patch[parallelSetOrderListKey] = setOrderList
}
default:
replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)
}
return nil
}
// replacePatchFieldIfNotEqual updates the patch if original and modified are not deep equal
// if diffOptions.IgnoreChangesAndAdditions is false.
// original is the old value, maybe either the live cluster object or the last applied configuration
// modified is the new value, is always the users new config
func replacePatchFieldIfNotEqual(key string, original, modified interface{},
patch map[string]interface{}, diffOptions DiffOptions) {
if diffOptions.IgnoreChangesAndAdditions {
// Ignoring changes - do nothing
return
}
if reflect.DeepEqual(original, modified) {
// Contents are identical - do nothing
return
}
// Create a patch to replace the old value with the new one
patch[key] = modified
}
// updatePatchIfMissing iterates over `original` when ignoreDeletions is false.
// Clear the field whose key is not present in `modified`.
// original is the old value, maybe either the live cluster object or the last applied configuration
// modified is the new value, is always the users new config
func updatePatchIfMissing(original, modified, patch map[string]interface{}, diffOptions DiffOptions) {
if diffOptions.IgnoreDeletions {
// Ignoring deletion - do nothing
return
}
// Add nils for deleted values
for key := range original {
if _, found := modified[key]; !found {
patch[key] = nil
}
}
}
// validateMergeKeyInLists checks if each map in the list has the mentryerge key.
func validateMergeKeyInLists(mergeKey string, lists ...[]interface{}) error {
for _, list := range lists {
for _, item := range list {
m, ok := item.(map[string]interface{})
if !ok {
return mergepatch.ErrBadArgType(m, item)
}
if _, ok = m[mergeKey]; !ok {
return mergepatch.ErrNoMergeKey(m, mergeKey)
}
}
}
return nil
}
// normalizeElementOrder sort `patch` list by `patchOrder` and sort `serverOnly` list by `serverOrder`.
// Then it merges the 2 sorted lists.
// It guarantee the relative order in the patch list and in the serverOnly list is kept.
// `patch` is a list of items in the patch, and `serverOnly` is a list of items in the live object.
// `patchOrder` is the order we want `patch` list to have and
// `serverOrder` is the order we want `serverOnly` list to have.
// kind is the kind of each item in the lists `patch` and `serverOnly`.
func normalizeElementOrder(patch, serverOnly, patchOrder, serverOrder []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) {
patch, err := normalizeSliceOrder(patch, patchOrder, mergeKey, kind)
if err != nil {
return nil, err
}
serverOnly, err = normalizeSliceOrder(serverOnly, serverOrder, mergeKey, kind)
if err != nil {
return nil, err
}
all := mergeSortedSlice(serverOnly, patch, serverOrder, mergeKey, kind)
return all, nil
}
// mergeSortedSlice merges the 2 sorted lists by serverOrder with best effort.
// It will insert each item in `left` list to `right` list. In most cases, the 2 lists will be interleaved.
// The relative order of left and right are guaranteed to be kept.
// They have higher precedence than the order in the live list.
// The place for a item in `left` is found by:
// scan from the place of last insertion in `right` to the end of `right`,
// the place is before the first item that is greater than the item we want to insert.
// example usage: using server-only items as left and patch items as right. We insert server-only items
// to patch list. We use the order of live object as record for comparison.
func mergeSortedSlice(left, right, serverOrder []interface{}, mergeKey string, kind reflect.Kind) []interface{} {
// Returns if l is less than r, and if both have been found.
// If l and r both present and l is in front of r, l is less than r.
less := func(l, r interface{}) (bool, bool) {
li := index(serverOrder, l, mergeKey, kind)
ri := index(serverOrder, r, mergeKey, kind)
if li >= 0 && ri >= 0 {
return li < ri, true
} else {
return false, false
}
}
// left and right should be non-overlapping.
size := len(left) + len(right)
i, j := 0, 0
s := make([]interface{}, size, size)
for k := 0; k < size; k++ {
if i >= len(left) && j < len(right) {
// have items left in `right` list
s[k] = right[j]
j++
} else if j >= len(right) && i < len(left) {
// have items left in `left` list
s[k] = left[i]
i++
} else {
// compare them if i and j are both in bound
less, foundBoth := less(left[i], right[j])
if foundBoth && less {
s[k] = left[i]
i++
} else {
s[k] = right[j]
j++
}
}
}
return s
}
// index returns the index of the item in the given items, or -1 if it doesn't exist
// l must NOT be a slice of slices, this should be checked before calling.
func index(l []interface{}, valToLookUp interface{}, mergeKey string, kind reflect.Kind) int {
var getValFn func(interface{}) interface{}
// Get the correct `getValFn` based on item `kind`.
// It should return the value of merge key for maps and
// return the item for other kinds.
switch kind {
case reflect.Map:
getValFn = func(item interface{}) interface{} {
typedItem, ok := item.(map[string]interface{})
if !ok {
return nil
}
val := typedItem[mergeKey]
return val
}
default:
getValFn = func(item interface{}) interface{} {
return item
}
}
for i, v := range l {
if getValFn(valToLookUp) == getValFn(v) {
return i
}
}
return -1
}
// extractToDeleteItems takes a list and
// returns 2 lists: one contains items that should be kept and the other contains items to be deleted.
func extractToDeleteItems(l []interface{}) ([]interface{}, []interface{}, error) {
var nonDelete, toDelete []interface{}
for _, v := range l {
m, ok := v.(map[string]interface{})
if !ok {
return nil, nil, mergepatch.ErrBadArgType(m, v)
}
directive, foundDirective := m[directiveMarker]
if foundDirective && directive == deleteDirective {
toDelete = append(toDelete, v)
} else {
nonDelete = append(nonDelete, v)
}
}
return nonDelete, toDelete, nil
}
// normalizeSliceOrder sort `toSort` list by `order`
func normalizeSliceOrder(toSort, order []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) {
var toDelete []interface{}
if kind == reflect.Map {
// make sure each item in toSort, order has merge key
err := validateMergeKeyInLists(mergeKey, toSort, order)
if err != nil {
return nil, err
}
toSort, toDelete, err = extractToDeleteItems(toSort)
if err != nil {
return nil, err
}
}
sort.SliceStable(toSort, func(i, j int) bool {
if ii := index(order, toSort[i], mergeKey, kind); ii >= 0 {
if ij := index(order, toSort[j], mergeKey, kind); ij >= 0 {
return ii < ij
}
}
return true
})
toSort = append(toSort, toDelete...)
return toSort, nil
}
// Returns a (recursive) strategic merge patch, a parallel deletion list if necessary and
// another list to set the order of the list
// Only list of primitives with merge strategy will generate a parallel deletion list.
// These two lists should yield modified when applied to original, for lists with merge semantics.
func diffLists(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, []interface{}, error) {
if len(original) == 0 {
// Both slices are empty - do nothing
if len(modified) == 0 || diffOptions.IgnoreChangesAndAdditions {
return nil, nil, nil, nil
}
// Old slice was empty - add all elements from the new slice
return modified, nil, nil, nil
}
elementType, err := sliceElementType(original, modified)
if err != nil {
return nil, nil, nil, err
}
var patchList, deleteList, setOrderList []interface{}
kind := elementType.Kind()
switch kind {
case reflect.Map:
patchList, deleteList, err = diffListsOfMaps(original, modified, schema, mergeKey, diffOptions)
if err != nil {
return nil, nil, nil, err
}
patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind)
if err != nil {
return nil, nil, nil, err
}
orderSame, err := isOrderSame(original, modified, mergeKey)
if err != nil {
return nil, nil, nil, err
}
// append the deletions to the end of the patch list.
patchList = append(patchList, deleteList...)
deleteList = nil
// generate the setElementOrder list when there are content changes or order changes
if diffOptions.SetElementOrder &&
((!diffOptions.IgnoreChangesAndAdditions && (len(patchList) > 0 || !orderSame)) ||
(!diffOptions.IgnoreDeletions && len(patchList) > 0)) {
// Generate a list of maps that each item contains only the merge key.
setOrderList = make([]interface{}, len(modified))
for i, v := range modified {
typedV := v.(map[string]interface{})
setOrderList[i] = map[string]interface{}{
mergeKey: typedV[mergeKey],
}
}
}
case reflect.Slice:
// Lists of Lists are not permitted by the api
return nil, nil, nil, mergepatch.ErrNoListOfLists
default:
patchList, deleteList, err = diffListsOfScalars(original, modified, diffOptions)
if err != nil {
return nil, nil, nil, err
}
patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind)
// generate the setElementOrder list when there are content changes or order changes
if diffOptions.SetElementOrder && ((!diffOptions.IgnoreDeletions && len(deleteList) > 0) ||
(!diffOptions.IgnoreChangesAndAdditions && !reflect.DeepEqual(original, modified))) {
setOrderList = modified
}
}
return patchList, deleteList, setOrderList, err
}
// isOrderSame checks if the order in a list has changed
func isOrderSame(original, modified []interface{}, mergeKey string) (bool, error) {
if len(original) != len(modified) {
return false, nil
}
for i, modifiedItem := range modified {
equal, err := mergeKeyValueEqual(original[i], modifiedItem, mergeKey)
if err != nil || !equal {
return equal, err
}
}
return true, nil
}
// diffListsOfScalars returns 2 lists, the first one is addList and the second one is deletionList.
// Argument diffOptions.IgnoreChangesAndAdditions controls if calculate addList. true means not calculate.
// Argument diffOptions.IgnoreDeletions controls if calculate deletionList. true means not calculate.
// original may be changed, but modified is guaranteed to not be changed
func diffListsOfScalars(original, modified []interface{}, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {
modifiedCopy := make([]interface{}, len(modified))
copy(modifiedCopy, modified)
// Sort the scalars for easier calculating the diff
originalScalars := sortScalars(original)
modifiedScalars := sortScalars(modifiedCopy)
originalIndex, modifiedIndex := 0, 0
addList := []interface{}{}
deletionList := []interface{}{}
for {
originalInBounds := originalIndex < len(originalScalars)
modifiedInBounds := modifiedIndex < len(modifiedScalars)
if !originalInBounds && !modifiedInBounds {
break
}
// we need to compare the string representation of the scalar,
// because the scalar is an interface which doesn't support either < or >
// And that's how func sortScalars compare scalars.
var originalString, modifiedString string
var originalValue, modifiedValue interface{}
if originalInBounds {
originalValue = originalScalars[originalIndex]
originalString = fmt.Sprintf("%v", originalValue)
}
if modifiedInBounds {
modifiedValue = modifiedScalars[modifiedIndex]
modifiedString = fmt.Sprintf("%v", modifiedValue)
}
originalV, modifiedV := compareListValuesAtIndex(originalInBounds, modifiedInBounds, originalString, modifiedString)
switch {
case originalV == nil && modifiedV == nil:
originalIndex++
modifiedIndex++
case originalV != nil && modifiedV == nil:
if !diffOptions.IgnoreDeletions {
deletionList = append(deletionList, originalValue)
}
originalIndex++
case originalV == nil && modifiedV != nil:
if !diffOptions.IgnoreChangesAndAdditions {
addList = append(addList, modifiedValue)
}
modifiedIndex++
default:
return nil, nil, fmt.Errorf("Unexpected returned value from compareListValuesAtIndex: %v and %v", originalV, modifiedV)
}
}
return addList, deduplicateScalars(deletionList), nil
}
// If first return value is non-nil, list1 contains an element not present in list2
// If second return value is non-nil, list2 contains an element not present in list1
func compareListValuesAtIndex(list1Inbounds, list2Inbounds bool, list1Value, list2Value string) (interface{}, interface{}) {
bothInBounds := list1Inbounds && list2Inbounds
switch {
// scalars are identical
case bothInBounds && list1Value == list2Value:
return nil, nil
// only list2 is in bound
case !list1Inbounds:
fallthrough
// list2 has additional scalar
case bothInBounds && list1Value > list2Value:
return nil, list2Value
// only original is in bound
case !list2Inbounds:
fallthrough
// original has additional scalar
case bothInBounds && list1Value < list2Value:
return list1Value, nil
default:
return nil, nil
}
}
// diffListsOfMaps takes a pair of lists and
// returns a (recursive) strategic merge patch list contains additions and changes and
// a deletion list contains deletions
func diffListsOfMaps(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {
patch := make([]interface{}, 0, len(modified))
deletionList := make([]interface{}, 0, len(original))
originalSorted, err := sortMergeListsByNameArray(original, schema, mergeKey, false)
if err != nil {
return nil, nil, err
}
modifiedSorted, err := sortMergeListsByNameArray(modified, schema, mergeKey, false)
if err != nil {
return nil, nil, err
}
originalIndex, modifiedIndex := 0, 0
for {
originalInBounds := originalIndex < len(originalSorted)
modifiedInBounds := modifiedIndex < len(modifiedSorted)
bothInBounds := originalInBounds && modifiedInBounds
if !originalInBounds && !modifiedInBounds {
break
}
var originalElementMergeKeyValueString, modifiedElementMergeKeyValueString string
var originalElementMergeKeyValue, modifiedElementMergeKeyValue interface{}
var originalElement, modifiedElement map[string]interface{}
if originalInBounds {
originalElement, originalElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(originalIndex, mergeKey, originalSorted)
if err != nil {
return nil, nil, err
}
originalElementMergeKeyValueString = fmt.Sprintf("%v", originalElementMergeKeyValue)
}
if modifiedInBounds {
modifiedElement, modifiedElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(modifiedIndex, mergeKey, modifiedSorted)
if err != nil {
return nil, nil, err
}
modifiedElementMergeKeyValueString = fmt.Sprintf("%v", modifiedElementMergeKeyValue)
}
switch {
case bothInBounds && ItemMatchesOriginalAndModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
// Merge key values are equal, so recurse
patchValue, err := diffMaps(originalElement, modifiedElement, schema, diffOptions)
if err != nil {
return nil, nil, err
}
if len(patchValue) > 0 {
patchValue[mergeKey] = modifiedElementMergeKeyValue
patch = append(patch, patchValue)
}
originalIndex++
modifiedIndex++
// only modified is in bound
case !originalInBounds:
fallthrough
// modified has additional map
case bothInBounds && ItemAddedToModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
if !diffOptions.IgnoreChangesAndAdditions {
patch = append(patch, modifiedElement)
}
modifiedIndex++
// only original is in bound
case !modifiedInBounds:
fallthrough
// original has additional map
case bothInBounds && ItemRemovedFromModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
if !diffOptions.IgnoreDeletions {
// Item was deleted, so add delete directive
deletionList = append(deletionList, CreateDeleteDirective(mergeKey, originalElementMergeKeyValue))
}
originalIndex++
}
}
return patch, deletionList, nil
}
// getMapAndMergeKeyValueByIndex return a map in the list and its merge key value given the index of the map.
func getMapAndMergeKeyValueByIndex(index int, mergeKey string, listOfMaps []interface{}) (map[string]interface{}, interface{}, error) {
m, ok := listOfMaps[index].(map[string]interface{})
if !ok {
return nil, nil, mergepatch.ErrBadArgType(m, listOfMaps[index])
}
val, ok := m[mergeKey]
if !ok {
return nil, nil, mergepatch.ErrNoMergeKey(m, mergeKey)
}
return m, val, nil
}
// StrategicMergePatch applies a strategic merge patch. The patch and the original document
// must be json encoded content. A patch can be created from an original and a modified document
// by calling CreateStrategicMergePatch.
func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) {
schema, err := NewPatchMetaFromStruct(dataStruct)
if err != nil {
return nil, err
}
return StrategicMergePatchUsingLookupPatchMeta(original, patch, schema)
}
func StrategicMergePatchUsingLookupPatchMeta(original, patch []byte, schema LookupPatchMeta) ([]byte, error) {
originalMap, err := handleUnmarshal(original)
if err != nil {
return nil, err
}
patchMap, err := handleUnmarshal(patch)
if err != nil {
return nil, err
}
result, err := StrategicMergeMapPatchUsingLookupPatchMeta(originalMap, patchMap, schema)
if err != nil {
return nil, err
}
return json.Marshal(result)
}
func handleUnmarshal(j []byte) (map[string]interface{}, error) {
if j == nil {
j = []byte("{}")
}
m := map[string]interface{}{}
err := json.Unmarshal(j, &m)
if err != nil {
return nil, mergepatch.ErrBadJSONDoc
}
return m, nil
}
// StrategicMergeMapPatch applies a strategic merge patch. The original and patch documents
// must be JSONMap. A patch can be created from an original and modified document by
// calling CreateTwoWayMergeMapPatch.
// Warning: the original and patch JSONMap objects are mutated by this function and should not be reused.
func StrategicMergeMapPatch(original, patch JSONMap, dataStruct interface{}) (JSONMap, error) {
schema, err := NewPatchMetaFromStruct(dataStruct)
if err != nil {
return nil, err
}
// We need the go struct tags `patchMergeKey` and `patchStrategy` for fields that support a strategic merge patch.
// For native resources, we can easily figure out these tags since we know the fields.
// Because custom resources are decoded as Unstructured and because we're missing the metadata about how to handle
// each field in a strategic merge patch, we can't find the go struct tags. Hence, we can't easily do a strategic merge
// for custom resources. So we should fail fast and return an error.
if _, ok := dataStruct.(*unstructured.Unstructured); ok {
return nil, mergepatch.ErrUnsupportedStrategicMergePatchFormat
}
return StrategicMergeMapPatchUsingLookupPatchMeta(original, patch, schema)
}
func StrategicMergeMapPatchUsingLookupPatchMeta(original, patch JSONMap, schema LookupPatchMeta) (JSONMap, error) {
mergeOptions := MergeOptions{
MergeParallelList: true,
IgnoreUnmatchedNulls: true,
}
return mergeMap(original, patch, schema, mergeOptions)
}
// MergeStrategicMergeMapPatchUsingLookupPatchMeta merges strategic merge
// patches retaining `null` fields and parallel lists. If 2 patches change the
// same fields and the latter one will override the former one. If you don't
// want that happen, you need to run func MergingMapsHaveConflicts before
// merging these patches. Applying the resulting merged merge patch to a JSONMap
// yields the same as merging each strategic merge patch to the JSONMap in
// succession.
func MergeStrategicMergeMapPatchUsingLookupPatchMeta(schema LookupPatchMeta, patches ...JSONMap) (JSONMap, error) {
mergeOptions := MergeOptions{
MergeParallelList: false,
IgnoreUnmatchedNulls: false,
}
merged := JSONMap{}
var err error
for _, patch := range patches {
merged, err = mergeMap(merged, patch, schema, mergeOptions)
if err != nil {
return nil, err
}
}
return merged, nil
}
// handleDirectiveInMergeMap handles the patch directive when merging 2 maps.
func handleDirectiveInMergeMap(directive interface{}, patch map[string]interface{}) (map[string]interface{}, error) {
if directive == replaceDirective {
// If the patch contains "$patch: replace", don't merge it, just use the
// patch directly. Later on, we can add a single level replace that only
// affects the map that the $patch is in.
delete(patch, directiveMarker)
return patch, nil
}
if directive == deleteDirective {
// If the patch contains "$patch: delete", don't merge it, just return
// an empty map.
return map[string]interface{}{}, nil
}
return nil, mergepatch.ErrBadPatchType(directive, patch)
}
func containsDirectiveMarker(item interface{}) bool {
m, ok := item.(map[string]interface{})
if ok {
if _, foundDirectiveMarker := m[directiveMarker]; foundDirectiveMarker {
return true
}
}
return false
}
func mergeKeyValueEqual(left, right interface{}, mergeKey string) (bool, error) {
if len(mergeKey) == 0 {
return left == right, nil
}
typedLeft, ok := left.(map[string]interface{})
if !ok {
return false, mergepatch.ErrBadArgType(typedLeft, left)
}
typedRight, ok := right.(map[string]interface{})
if !ok {
return false, mergepatch.ErrBadArgType(typedRight, right)
}
mergeKeyLeft, ok := typedLeft[mergeKey]
if !ok {
return false, mergepatch.ErrNoMergeKey(typedLeft, mergeKey)
}
mergeKeyRight, ok := typedRight[mergeKey]
if !ok {
return false, mergepatch.ErrNoMergeKey(typedRight, mergeKey)
}
return mergeKeyLeft == mergeKeyRight, nil
}
// extractKey trims the prefix and return the original key
func extractKey(s, prefix string) (string, error) {
substrings := strings.SplitN(s, "/", 2)
if len(substrings) <= 1 || substrings[0] != prefix {
switch prefix {
case deleteFromPrimitiveListDirectivePrefix:
return "", mergepatch.ErrBadPatchFormatForPrimitiveList
case setElementOrderDirectivePrefix:
return "", mergepatch.ErrBadPatchFormatForSetElementOrderList
default:
return "", fmt.Errorf("fail to find unknown prefix %q in %s\n", prefix, s)
}
}
return substrings[1], nil
}
// validatePatchUsingSetOrderList verifies:
// the relative order of any two items in the setOrderList list matches that in the patch list.
// the items in the patch list must be a subset or the same as the $setElementOrder list (deletions are ignored).
func validatePatchWithSetOrderList(patchList, setOrderList interface{}, mergeKey string) error {
typedSetOrderList, ok := setOrderList.([]interface{})
if !ok {
return mergepatch.ErrBadPatchFormatForSetElementOrderList
}
typedPatchList, ok := patchList.([]interface{})
if !ok {
return mergepatch.ErrBadPatchFormatForSetElementOrderList
}
if len(typedSetOrderList) == 0 || len(typedPatchList) == 0 {
return nil
}
var nonDeleteList []interface{}
var err error
if len(mergeKey) > 0 {
nonDeleteList, _, err = extractToDeleteItems(typedPatchList)
if err != nil {
return err
}
} else {
nonDeleteList = typedPatchList
}