-
Notifications
You must be signed in to change notification settings - Fork 617
/
diff.go
299 lines (255 loc) · 7.75 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
package kustomization
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta2"
"github.com/fluxcd/pkg/ssa"
"github.com/gonvenience/bunt"
"github.com/gonvenience/ytbx"
"github.com/google/go-cmp/cmp"
"github.com/homeport/dyff/pkg/dyff"
"github.com/lucasb-eyer/go-colorful"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/cli-utils/pkg/kstatus/polling"
"sigs.k8s.io/cli-utils/pkg/object"
"sigs.k8s.io/yaml"
)
const (
controllerName = "kustomize-controller"
controllerGroup = "kustomize.toolkit.fluxcd.io"
)
func (b *Builder) Manager() (*ssa.ResourceManager, error) {
statusPoller := polling.NewStatusPoller(b.client, b.restMapper)
owner := ssa.Owner{
Field: controllerName,
Group: controllerGroup,
}
return ssa.NewResourceManager(b.client, statusPoller, owner), nil
}
func (b *Builder) Diff() (string, error) {
output := strings.Builder{}
res, err := b.Build()
if err != nil {
return "", err
}
// convert the build result into Kubernetes unstructured objects
objects, err := ssa.ReadObjects(bytes.NewReader(res))
if err != nil {
return "", err
}
resourceManager, err := b.Manager()
if err != nil {
return "", err
}
resourceManager.SetOwnerLabels(objects, b.kustomization.GetName(), b.kustomization.GetNamespace())
ctx, cancel := context.WithTimeout(context.Background(), b.timeout)
defer cancel()
if err := ssa.SetNativeKindsDefaults(objects); err != nil {
return "", err
}
// create an inventory of objects to be reconciled
newInventory := newInventory()
for _, obj := range objects {
change, liveObject, mergedObject, err := resourceManager.Diff(ctx, obj)
if err != nil {
if b.kustomization.Spec.Force && isImmutableError(err) {
output.WriteString(writeString(fmt.Sprintf("► %s created\n", obj.GetName()), bunt.Green))
} else {
output.WriteString(writeString(fmt.Sprint(`✗`, err), bunt.Red))
}
continue
}
// if the object is a sops secret, we need to
// make sure we diff only if the keys are different
if obj.GetKind() == "Secret" && change.Action == string(ssa.ConfiguredAction) {
diffSopsSecret(obj, liveObject, mergedObject, change)
}
if change.Action == string(ssa.CreatedAction) {
output.WriteString(writeString(fmt.Sprintf("► %s created\n", change.Subject), bunt.Green))
}
if change.Action == string(ssa.ConfiguredAction) {
output.WriteString(writeString(fmt.Sprintf("► %s drifted\n", change.Subject), bunt.WhiteSmoke))
liveFile, mergedFile, tmpDir, err := writeYamls(liveObject, mergedObject)
if err != nil {
return "", err
}
defer cleanupDir(tmpDir)
err = diff(liveFile, mergedFile, &output)
if err != nil {
return "", err
}
}
addObjectsToInventory(newInventory, change)
}
if b.kustomization.Spec.Prune {
oldStatus := b.kustomization.Status.DeepCopy()
if oldStatus.Inventory != nil {
diffObjects, err := diffInventory(oldStatus.Inventory, newInventory)
if err != nil {
return "", err
}
for _, object := range diffObjects {
output.WriteString(writeString(fmt.Sprintf("► %s deleted\n", ssa.FmtUnstructured(object)), bunt.OrangeRed))
}
}
}
return output.String(), nil
}
func writeYamls(liveObject, mergedObject *unstructured.Unstructured) (string, string, string, error) {
tmpDir, err := os.MkdirTemp("", "")
if err != nil {
return "", "", "", err
}
liveYAML, _ := yaml.Marshal(liveObject)
liveFile := filepath.Join(tmpDir, "live.yaml")
if err := os.WriteFile(liveFile, liveYAML, 0644); err != nil {
return "", "", "", err
}
mergedYAML, _ := yaml.Marshal(mergedObject)
mergedFile := filepath.Join(tmpDir, "merged.yaml")
if err := os.WriteFile(mergedFile, mergedYAML, 0644); err != nil {
return "", "", "", err
}
return liveFile, mergedFile, tmpDir, nil
}
func writeString(t string, color colorful.Color) string {
return bunt.Style(
t,
bunt.EachLine(),
bunt.Foreground(color),
)
}
func cleanupDir(dir string) error {
return os.RemoveAll(dir)
}
func diff(liveFile, mergedFile string, output io.Writer) error {
from, to, err := ytbx.LoadFiles(liveFile, mergedFile)
if err != nil {
return fmt.Errorf("failed to load input files: %w", err)
}
report, err := dyff.CompareInputFiles(from, to,
dyff.IgnoreOrderChanges(false),
dyff.KubernetesEntityDetection(true),
)
if err != nil {
return fmt.Errorf("failed to compare input files: %w", err)
}
reportWriter := &dyff.HumanReport{
Report: report,
OmitHeader: true,
}
if err := reportWriter.WriteReport(output); err != nil {
return fmt.Errorf("failed to print report: %w", err)
}
return nil
}
func diffSopsSecret(obj, liveObject, mergedObject *unstructured.Unstructured, change *ssa.ChangeSetEntry) {
data := obj.Object["data"]
for _, v := range data.(map[string]interface{}) {
v, err := base64.StdEncoding.DecodeString(v.(string))
if err != nil {
fmt.Println(err)
}
if bytes.Contains(v, []byte(mask)) {
if liveObject != nil && mergedObject != nil {
change.Action = string(ssa.UnchangedAction)
dataLive := liveObject.Object["data"].(map[string]interface{})
dataMerged := mergedObject.Object["data"].(map[string]interface{})
if cmp.Diff(keys(dataLive), keys(dataMerged)) != "" {
change.Action = string(ssa.ConfiguredAction)
}
}
}
}
}
func keys(m map[string]interface{}) []string {
keys := make([]string, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
return keys
}
// diffInventory returns the slice of objects that do not exist in the target inventory.
func diffInventory(inv *kustomizev1.ResourceInventory, target *kustomizev1.ResourceInventory) ([]*unstructured.Unstructured, error) {
versionOf := func(i *kustomizev1.ResourceInventory, objMetadata object.ObjMetadata) string {
for _, entry := range i.Entries {
if entry.ID == objMetadata.String() {
return entry.Version
}
}
return ""
}
objects := make([]*unstructured.Unstructured, 0)
aList, err := listMetaInInventory(inv)
if err != nil {
return nil, err
}
bList, err := listMetaInInventory(target)
if err != nil {
return nil, err
}
list := aList.Diff(bList)
if len(list) == 0 {
return objects, nil
}
for _, metadata := range list {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: metadata.GroupKind.Group,
Kind: metadata.GroupKind.Kind,
Version: versionOf(inv, metadata),
})
u.SetName(metadata.Name)
u.SetNamespace(metadata.Namespace)
objects = append(objects, u)
}
sort.Sort(ssa.SortableUnstructureds(objects))
return objects, nil
}
// listMetaInInventory returns the inventory entries as object.ObjMetadata objects.
func listMetaInInventory(inv *kustomizev1.ResourceInventory) (object.ObjMetadataSet, error) {
var metas []object.ObjMetadata
for _, e := range inv.Entries {
m, err := object.ParseObjMetadata(e.ID)
if err != nil {
return metas, err
}
metas = append(metas, m)
}
return metas, nil
}
func newInventory() *kustomizev1.ResourceInventory {
return &kustomizev1.ResourceInventory{
Entries: []kustomizev1.ResourceRef{},
}
}
// addObjectsToInventory extracts the metadata from the given objects and adds it to the inventory.
func addObjectsToInventory(inv *kustomizev1.ResourceInventory, entry *ssa.ChangeSetEntry) error {
if entry == nil {
return nil
}
inv.Entries = append(inv.Entries, kustomizev1.ResourceRef{
ID: entry.ObjMetadata.String(),
Version: entry.GroupVersion,
})
return nil
}
func isImmutableError(err error) bool {
// Detect immutability like kubectl does
// https://github.com/kubernetes/kubectl/blob/8165f83007/pkg/cmd/apply/patcher.go#L201
if errors.IsConflict(err) || errors.IsInvalid(err) {
return true
}
return false
}