forked from argoproj/argo-cd
/
diff.go
441 lines (411 loc) · 12.7 KB
/
diff.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
package diff
import (
"encoding/json"
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/yudai/gojsondiff"
"github.com/yudai/gojsondiff/formatter"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubectl/scheme"
jsonutil "github.com/argoproj/argo-cd/util/json"
)
type DiffResult struct {
Diff gojsondiff.Diff
Modified bool
}
type DiffResultList struct {
Diffs []DiffResult
Modified bool
}
type Normalizer interface {
Normalize(un *unstructured.Unstructured) error
}
// Diff performs a diff on two unstructured objects. If the live object happens to have a
// "kubectl.kubernetes.io/last-applied-configuration", then perform a three way diff.
func Diff(config, live *unstructured.Unstructured, normalizer Normalizer) *DiffResult {
if config != nil {
config = stripTypeInformation(config)
Normalize(config, normalizer)
}
if live != nil {
live = stripTypeInformation(live)
Normalize(live, normalizer)
}
orig := GetLastAppliedConfigAnnotation(live)
if orig != nil && config != nil {
Normalize(orig, normalizer)
dr, err := ThreeWayDiff(orig, config, live)
if err == nil {
return dr
}
log.Debugf("three-way diff calculation failed: %v. Falling back to two-way diff", err)
}
return TwoWayDiff(config, live)
}
// TwoWayDiff performs a normal two-way diff between two unstructured objects. Ignores extra fields
// in the live object.
// Inputs are assumed to be stripped of type information
func TwoWayDiff(config, live *unstructured.Unstructured) *DiffResult {
var configObj, liveObj map[string]interface{}
if config != nil {
config = removeNamespaceAnnotation(config)
configObj = config.Object
}
if live != nil {
liveObj = jsonutil.RemoveMapFields(configObj, live.Object)
}
gjDiff := gojsondiff.New().CompareObjects(liveObj, configObj)
dr := DiffResult{
Diff: gjDiff,
Modified: gjDiff.Modified(),
}
return &dr
}
// ThreeWayDiff performs a diff with the understanding of how to incorporate the
// last-applied-configuration annotation in the diff.
// Inputs are assumed to be stripped of type information
func ThreeWayDiff(orig, config, live *unstructured.Unstructured) (*DiffResult, error) {
orig = removeNamespaceAnnotation(orig)
config = removeNamespaceAnnotation(config)
// Remove defaulted fields from the live object.
// This subtracts any extra fields in the live object which are not present in last-applied-configuration.
// This is needed to perform a fair comparison when we send the objects to gojsondiff
live = &unstructured.Unstructured{Object: jsonutil.RemoveMapFields(orig.Object, live.Object)}
// 1. calculate a 3-way merge patch
patchBytes, err := threeWayMergePatch(orig, config, live)
if err != nil {
return nil, err
}
// 2. apply the patch against the live object
liveBytes, err := json.Marshal(live)
if err != nil {
return nil, err
}
versionedObject, err := scheme.Scheme.New(orig.GroupVersionKind())
if err != nil {
return nil, err
}
patchedLiveBytes, err := strategicpatch.StrategicMergePatch(liveBytes, patchBytes, versionedObject)
if err != nil {
return nil, err
}
var patchedLive unstructured.Unstructured
err = json.Unmarshal(patchedLiveBytes, &patchedLive)
if err != nil {
return nil, err
}
// 3. diff the live object vs. the patched live object
gjDiff := gojsondiff.New().CompareObjects(live.Object, patchedLive.Object)
dr := DiffResult{
Diff: gjDiff,
Modified: gjDiff.Modified(),
}
return &dr, nil
}
// stripTypeInformation strips any type information (e.g. float64 vs. int) from the unstructured
// object by remarshalling the object. This is important for diffing since it will cause godiff
// to report a false difference.
func stripTypeInformation(un *unstructured.Unstructured) *unstructured.Unstructured {
unBytes, err := json.Marshal(un)
if err != nil {
panic(err)
}
var newUn unstructured.Unstructured
err = json.Unmarshal(unBytes, &newUn)
if err != nil {
panic(err)
}
return &newUn
}
// removeNamespaceAnnotation remove the namespace and an empty annotation map from the metadata.
// The namespace field is present in live (namespaced) objects, but not necessarily present in
// config or last-applied. This results in a diff which we don't care about. We delete the two so
// that the diff is more relevant.
func removeNamespaceAnnotation(orig *unstructured.Unstructured) *unstructured.Unstructured {
orig = orig.DeepCopy()
if metadataIf, ok := orig.Object["metadata"]; ok {
metadata := metadataIf.(map[string]interface{})
delete(metadata, "namespace")
if annotationsIf, ok := metadata["annotations"]; ok {
shouldDelete := false
if annotationsIf == nil {
shouldDelete = true
} else {
annotation := annotationsIf.(map[string]interface{})
if len(annotation) == 0 {
shouldDelete = true
}
}
if shouldDelete {
delete(metadata, "annotations")
}
}
}
return orig
}
func threeWayMergePatch(orig, config, live *unstructured.Unstructured) ([]byte, error) {
origBytes, err := json.Marshal(orig.Object)
if err != nil {
return nil, err
}
configBytes, err := json.Marshal(config.Object)
if err != nil {
return nil, err
}
liveBytes, err := json.Marshal(live.Object)
if err != nil {
return nil, err
}
gvk := orig.GroupVersionKind()
versionedObject, err := scheme.Scheme.New(gvk)
if err != nil {
return nil, err
}
lookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObject)
if err != nil {
return nil, err
}
return strategicpatch.CreateThreeWayMergePatch(origBytes, configBytes, liveBytes, lookupPatchMeta, true)
}
func GetLastAppliedConfigAnnotation(live *unstructured.Unstructured) *unstructured.Unstructured {
if live == nil {
return nil
}
annots := live.GetAnnotations()
if annots == nil {
return nil
}
lastAppliedStr, ok := annots[corev1.LastAppliedConfigAnnotation]
if !ok {
return nil
}
var obj unstructured.Unstructured
err := json.Unmarshal([]byte(lastAppliedStr), &obj)
if err != nil {
log.Warnf("Failed to unmarshal %s in %s", core.LastAppliedConfigAnnotation, live.GetName())
return nil
}
return &obj
}
// DiffArray performs a diff on a list of unstructured objects. Objects are expected to match
// environments
func DiffArray(configArray, liveArray []*unstructured.Unstructured, normalizer Normalizer) (*DiffResultList, error) {
numItems := len(configArray)
if len(liveArray) != numItems {
return nil, fmt.Errorf("left and right arrays have mismatched lengths")
}
diffResultList := DiffResultList{
Diffs: make([]DiffResult, numItems),
}
for i := 0; i < numItems; i++ {
config := configArray[i]
live := liveArray[i]
diffRes := Diff(config, live, normalizer)
diffResultList.Diffs[i] = *diffRes
if diffRes.Modified {
diffResultList.Modified = true
}
}
return &diffResultList, nil
}
// ASCIIFormat returns the ASCII format of the diff
func (d *DiffResult) ASCIIFormat(left *unstructured.Unstructured, formatOpts formatter.AsciiFormatterConfig) (string, error) {
if !d.Diff.Modified() {
return "", nil
}
if left == nil {
return "", errors.New("Supplied nil left object")
}
asciiFmt := formatter.NewAsciiFormatter(left.Object, formatOpts)
return asciiFmt.Format(d.Diff)
}
func Normalize(un *unstructured.Unstructured, normalizer Normalizer) {
if un == nil {
return
}
// creationTimestamp is sometimes set to null in the config when exported (e.g. SealedSecrets)
// Removing the field allows a cleaner diff.
unstructured.RemoveNestedField(un.Object, "metadata", "creationTimestamp")
gvk := un.GroupVersionKind()
if gvk.Group == "" && gvk.Kind == "Secret" {
NormalizeSecret(un)
} else if gvk.Group == "rbac.authorization.k8s.io" && (gvk.Kind == "ClusterRole" || gvk.Kind == "Role") {
normalizeRole(un)
}
if normalizer != nil {
err := normalizer.Normalize(un)
if err != nil {
log.Warnf("Failed to normalize %s/%s/%s: %v", un.GroupVersionKind(), un.GetNamespace(), un.GetName(), err)
}
}
}
// NormalizeSecret mutates the supplied object and encodes stringData to data, and converts nils to
// empty strings. If the object is not a secret, or is an invalid secret, then returns the same object.
func NormalizeSecret(un *unstructured.Unstructured) {
if un == nil {
return
}
gvk := un.GroupVersionKind()
if gvk.Group != "" || gvk.Kind != "Secret" {
return
}
var secret corev1.Secret
err := runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &secret)
if err != nil {
return
}
// We normalize nils to empty string to handle: https://github.com/argoproj/argo-cd/issues/943
for k, v := range secret.Data {
if len(v) == 0 {
secret.Data[k] = []byte("")
}
}
if len(secret.StringData) > 0 {
if secret.Data == nil {
secret.Data = make(map[string][]byte)
}
for k, v := range secret.StringData {
secret.Data[k] = []byte(v)
}
delete(un.Object, "stringData")
}
newObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&secret)
if err != nil {
log.Warnf("object unable to convert from secret: %v", err)
return
}
if secret.Data != nil {
err = unstructured.SetNestedField(un.Object, newObj["data"], "data")
if err != nil {
log.Warnf("failed to set secret.data: %v", err)
return
}
}
}
// normalizeRole mutates the supplied Role/ClusterRole and sets rules to null if it is an empty list
func normalizeRole(un *unstructured.Unstructured) {
if un == nil {
return
}
gvk := un.GroupVersionKind()
if gvk.Group != "rbac.authorization.k8s.io" || (gvk.Kind != "Role" && gvk.Kind != "ClusterRole") {
return
}
rulesIf, ok := un.Object["rules"]
if !ok {
return
}
rules, ok := rulesIf.([]interface{})
if !ok {
return
}
if rules != nil && len(rules) == 0 {
un.Object["rules"] = nil
}
}
// JSONFormat returns the diff as a JSON string
func (d *DiffResult) JSONFormat() (string, error) {
if !d.Diff.Modified() {
return "", nil
}
jsonFmt := formatter.NewDeltaFormatter()
return jsonFmt.Format(d.Diff)
}
// CreateTwoWayMergePatch is a helper to construct a two-way merge patch from objects (instead of bytes)
func CreateTwoWayMergePatch(orig, new, dataStruct interface{}) ([]byte, bool, error) {
origBytes, err := json.Marshal(orig)
if err != nil {
return nil, false, err
}
newBytes, err := json.Marshal(new)
if err != nil {
return nil, false, err
}
patch, err := strategicpatch.CreateTwoWayMergePatch(origBytes, newBytes, dataStruct)
if err != nil {
return nil, false, err
}
return patch, string(patch) != "{}", nil
}
// HideSecretData replaces secret data values in specified target, live secrets and in last applied configuration of live secret with stars. Also preserves differences between
// target, live and last applied config values. E.g. if all three are equal the values would be replaced with same number of stars. If all the are different then number of stars
// in replacement should be different.
func HideSecretData(target *unstructured.Unstructured, live *unstructured.Unstructured) (*unstructured.Unstructured, *unstructured.Unstructured, error) {
var orig *unstructured.Unstructured
if live != nil {
orig = GetLastAppliedConfigAnnotation(live)
live = live.DeepCopy()
}
if target != nil {
target = target.DeepCopy()
}
keys := map[string]bool{}
for _, obj := range []*unstructured.Unstructured{target, live, orig} {
if obj == nil {
continue
}
NormalizeSecret(obj)
if data, found, err := unstructured.NestedMap(obj.Object, "data"); found && err == nil {
for k := range data {
keys[k] = true
}
}
}
for k := range keys {
nextReplacement := "*********"
valToReplacement := make(map[string]string)
for _, obj := range []*unstructured.Unstructured{target, live, orig} {
var data map[string]interface{}
if obj != nil {
var err error
data, _, err = unstructured.NestedMap(obj.Object, "data")
if err != nil {
return nil, nil, err
}
}
if data == nil {
data = make(map[string]interface{})
}
valData, ok := data[k]
if !ok {
continue
}
val := toString(valData)
replacement, ok := valToReplacement[val]
if !ok {
replacement = nextReplacement
nextReplacement = nextReplacement + "*"
valToReplacement[val] = replacement
}
data[k] = replacement
err := unstructured.SetNestedField(obj.Object, data, "data")
if err != nil {
return nil, nil, err
}
}
}
if live != nil && orig != nil {
annotations := live.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
lastAppliedData, err := json.Marshal(orig)
if err != nil {
return nil, nil, err
}
annotations[core.LastAppliedConfigAnnotation] = string(lastAppliedData)
live.SetAnnotations(annotations)
}
return target, live, nil
}
func toString(val interface{}) string {
if val == nil {
return ""
}
return fmt.Sprintf("%s", val)
}