-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitops_compare.go
More file actions
388 lines (324 loc) · 12.4 KB
/
Copy pathgitops_compare.go
File metadata and controls
388 lines (324 loc) · 12.4 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
log "github.com/rs/zerolog/log"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// Cache for discovered GVR mappings
var (
gvrCache = make(map[string]schema.GroupVersionResource)
gvrCacheLock sync.RWMutex
gvrCacheInit sync.Once
)
// compareManifests compares generated manifests with live cluster resources
func compareManifests(repoState *gitOpsRepositoryState) error {
log.Debug().Str("repository", repoState.name).Msg("Comparing manifests with cluster state")
// Generate manifests using Kustomize
manifests, err := generateKustomizeManifests(repoState)
if err != nil {
return fmt.Errorf("failed to generate manifests for repository %s: %w", repoState.name, err)
}
log.Debug().
Str("repository", repoState.name).
Int("manifests", len(manifests)).
Msg("Generated manifests from repository")
// Compare each manifest with cluster state
for _, manifest := range manifests {
if err := compareManifestWithCluster(repoState, manifest); err != nil {
log.Error().
Err(err).
Str("repository", repoState.name).
Str("resource", fmt.Sprintf("%s/%s", manifest.GetKind(), manifest.GetName())).
Msg("Failed to compare manifest with cluster")
}
}
return nil
}
// compareManifestWithCluster compares a single manifest with its cluster counterpart
func compareManifestWithCluster(repoState *gitOpsRepositoryState, manifest *unstructured.Unstructured) error {
kind := manifest.GetKind()
name := manifest.GetName()
namespace := manifest.GetNamespace()
log.Debug().
Str("repository", repoState.name).
Str("kind", kind).
Str("name", name).
Str("namespace", namespace).
Msg("Comparing manifest with cluster")
// Get the GroupVersionResource for this resource
gvr, err := getGVRForKind(kind)
if err != nil {
return fmt.Errorf("failed to get GVR for kind %s: %w", kind, err)
}
// Get the resource from the cluster
var clusterResource *unstructured.Unstructured
if namespace != "" {
// Namespaced resource
clusterResource, err = dynamicClient.Resource(gvr).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{})
} else {
// Cluster-scoped resource
clusterResource, err = dynamicClient.Resource(gvr).Get(context.TODO(), name, metav1.GetOptions{})
}
if err != nil {
if errors.IsNotFound(err) {
// Resource is missing from cluster
return processGitOpsMismatch(repoState, manifest, nil, "missing")
}
return fmt.Errorf("failed to get resource %s/%s from cluster: %w", kind, name, err)
}
// Compare the resources
if resourcesAreDifferent(manifest, clusterResource) {
return processGitOpsMismatch(repoState, manifest, clusterResource, "different")
}
// Resources match - clear any previous error state
return processGitOpsMatch(repoState, manifest)
}
// resourcesAreDifferent compares two unstructured resources using server-side apply dry-run
func resourcesAreDifferent(expected, actual *unstructured.Unstructured) bool {
// Get the GroupVersionResource for this resource
gvr, err := getGVRForKind(expected.GetKind())
if err != nil {
log.Error().Err(err).Str("kind", expected.GetKind()).Msg("Failed to get GVR for resource comparison")
return false // If we can't get GVR, assume no difference to avoid false positives
}
// Perform server-side apply dry-run to see if there would be changes
// This is exactly what kubectl diff does internally
var result *unstructured.Unstructured
if expected.GetNamespace() != "" {
// Namespaced resource
result, err = dynamicClient.Resource(gvr).Namespace(expected.GetNamespace()).
Apply(context.TODO(), expected.GetName(), expected, metav1.ApplyOptions{
DryRun: []string{metav1.DryRunAll},
FieldManager: "sun-gitops",
Force: true,
})
} else {
// Cluster-scoped resource
result, err = dynamicClient.Resource(gvr).
Apply(context.TODO(), expected.GetName(), expected, metav1.ApplyOptions{
DryRun: []string{metav1.DryRunAll},
FieldManager: "sun-gitops",
Force: true,
})
}
if err != nil {
log.Error().
Err(err).
Str("kind", expected.GetKind()).
Str("name", expected.GetName()).
Str("namespace", expected.GetNamespace()).
Msg("Failed to perform server-side apply dry-run")
return false // If dry-run fails, assume no difference to avoid false positives
}
// Compare the spec and metadata of the dry-run result with the actual resource
// The dry-run result shows what the resource would look like after applying the expected manifest
// If it's different from the actual resource, there's drift
different := !resourcesEqual(result, actual)
if different {
log.Debug().
Str("kind", expected.GetKind()).
Str("name", expected.GetName()).
Str("namespace", expected.GetNamespace()).
Msg("Server-side apply dry-run detected differences")
// Log the differences for debugging
if log.Debug().Enabled() {
resultJSON, _ := json.MarshalIndent(result.Object, "", " ")
actualJSON, _ := json.MarshalIndent(actual.Object, "", " ")
log.Debug().
Str("kind", expected.GetKind()).
Str("name", expected.GetName()).
Str("dryRunResult", string(resultJSON)).
Str("actualResource", string(actualJSON)).
Msg("Dry-run vs actual resource comparison")
}
}
return different
}
// resourcesEqual compares the meaningful parts of two resources
func resourcesEqual(dryRunResult, actual *unstructured.Unstructured) bool {
if dryRunResult == nil || actual == nil {
return dryRunResult == actual
}
// Compare the spec sections - this is where the actual configuration lives
dryRunSpec, dryRunSpecExists, _ := unstructured.NestedMap(dryRunResult.Object, "spec")
actualSpec, actualSpecExists, _ := unstructured.NestedMap(actual.Object, "spec")
if dryRunSpecExists != actualSpecExists {
return false
}
if dryRunSpecExists {
dryRunSpecJSON, _ := json.Marshal(dryRunSpec)
actualSpecJSON, _ := json.Marshal(actualSpec)
if string(dryRunSpecJSON) != string(actualSpecJSON) {
return false
}
}
// Compare relevant metadata (labels and annotations that aren't system-managed)
dryRunMeta, dryRunMetaExists, _ := unstructured.NestedMap(dryRunResult.Object, "metadata")
actualMeta, actualMetaExists, _ := unstructured.NestedMap(actual.Object, "metadata")
if dryRunMetaExists && actualMetaExists {
// Compare labels (excluding system-managed ones)
dryRunLabels, _, _ := unstructured.NestedStringMap(dryRunMeta, "labels")
actualLabels, _, _ := unstructured.NestedStringMap(actualMeta, "labels")
// Remove system-managed labels for comparison
cleanLabels := func(labels map[string]string) map[string]string {
cleaned := make(map[string]string)
for k, v := range labels {
// Skip system-managed labels
if k == "app.kubernetes.io/managed-by" ||
k == "helm.sh/chart" ||
k == "app.kubernetes.io/instance" ||
k == "app.kubernetes.io/version" {
continue
}
cleaned[k] = v
}
return cleaned
}
cleanedDryRunLabels := cleanLabels(dryRunLabels)
cleanedActualLabels := cleanLabels(actualLabels)
dryRunLabelsJSON, _ := json.Marshal(cleanedDryRunLabels)
actualLabelsJSON, _ := json.Marshal(cleanedActualLabels)
if string(dryRunLabelsJSON) != string(actualLabelsJSON) {
return false
}
// Compare annotations (excluding system-managed ones)
dryRunAnnotations, _, _ := unstructured.NestedStringMap(dryRunMeta, "annotations")
actualAnnotations, _, _ := unstructured.NestedStringMap(actualMeta, "annotations")
// Remove system-managed annotations for comparison
cleanAnnotations := func(annotations map[string]string) map[string]string {
cleaned := make(map[string]string)
for k, v := range annotations {
// Skip system-managed annotations
if k == "kubectl.kubernetes.io/last-applied-configuration" ||
k == "deployment.kubernetes.io/revision" ||
k == "meta.helm.sh/release-name" ||
k == "meta.helm.sh/release-namespace" {
continue
}
cleaned[k] = v
}
return cleaned
}
cleanedDryRunAnnotations := cleanAnnotations(dryRunAnnotations)
cleanedActualAnnotations := cleanAnnotations(actualAnnotations)
dryRunAnnotationsJSON, _ := json.Marshal(cleanedDryRunAnnotations)
actualAnnotationsJSON, _ := json.Marshal(cleanedActualAnnotations)
if string(dryRunAnnotationsJSON) != string(actualAnnotationsJSON) {
return false
}
}
return true
}
// initializeGVRCache initializes the GVR cache using discovery client
func initializeGVRCache() {
log.Debug().Msg("Initializing GVR cache using discovery client")
// Create discovery client using the existing Kubernetes client
discoveryClient := client.Discovery()
// Get server resources
apiResourceLists, err := discoveryClient.ServerPreferredResources()
if err != nil {
log.Fatal().Err(err).Msg("Failed to get server resources")
return
}
gvrCacheLock.Lock()
defer gvrCacheLock.Unlock()
resourceCount := 0
for _, apiResourceList := range apiResourceLists {
if apiResourceList == nil {
continue
}
gv, err := schema.ParseGroupVersion(apiResourceList.GroupVersion)
if err != nil {
log.Warn().Err(err).Str("groupVersion", apiResourceList.GroupVersion).Msg("Failed to parse group version")
continue
}
for _, apiResource := range apiResourceList.APIResources {
// Skip subresources (they contain '/')
if strings.Contains(apiResource.Name, "/") {
continue
}
gvr := schema.GroupVersionResource{
Group: gv.Group,
Version: gv.Version,
Resource: apiResource.Name,
}
gvrCache[apiResource.Kind] = gvr
resourceCount++
log.Debug().
Str("kind", apiResource.Kind).
Str("group", gv.Group).
Str("version", gv.Version).
Str("resource", apiResource.Name).
Bool("namespaced", apiResource.Namespaced).
Msg("Cached GVR mapping")
}
}
log.Info().Int("resourceCount", resourceCount).Msg("Successfully initialized GVR cache from discovery")
}
// getGVRForKind returns the GroupVersionResource for a given Kind using discovery
func getGVRForKind(kind string) (schema.GroupVersionResource, error) {
// Initialize cache once
gvrCacheInit.Do(initializeGVRCache)
gvrCacheLock.RLock()
gvr, exists := gvrCache[kind]
gvrCacheLock.RUnlock()
if !exists {
return schema.GroupVersionResource{}, fmt.Errorf("unknown kind: %s", kind)
}
return gvr, nil
}
// processGitOpsMismatch handles when a resource doesn't match between Git and cluster
func processGitOpsMismatch(repoState *gitOpsRepositoryState, expected, actual *unstructured.Unstructured, mismatchType string) error {
kind := expected.GetKind()
name := expected.GetName()
namespace := expected.GetNamespace()
key := fmt.Sprintf("%s/%s/%s/%s", repoState.name, namespace, kind, name)
log.Error().
Str("repository", repoState.name).
Str("kind", kind).
Str("name", name).
Str("namespace", namespace).
Str("mismatchType", mismatchType).
Msg("GitOps mismatch detected")
// Update GitOps state
updateGitOpsState(key, true, fmt.Sprintf("Resource %s: %s", mismatchType, getResourceDescription(expected, actual, mismatchType)),
repoState.name, kind, name, namespace, mismatchType, "", "")
// Check if we should send an alert
if shouldSendGitOpsAlert(key) {
sendGitOpsMismatchAlert(repoState.name, expected, actual, mismatchType)
markGitOpsAlertSent(key)
}
return nil
}
// processGitOpsMatch handles when a resource matches between Git and cluster
func processGitOpsMatch(repoState *gitOpsRepositoryState, manifest *unstructured.Unstructured) error {
kind := manifest.GetKind()
name := manifest.GetName()
namespace := manifest.GetNamespace()
key := fmt.Sprintf("%s/%s/%s/%s", repoState.name, namespace, kind, name)
// Check for recovery
checkGitOpsRecovery(key, repoState.name, kind, name, namespace)
// Update state to indicate no error
updateGitOpsState(key, false, "", repoState.name, kind, name, namespace, "", "", "")
return nil
}
// getResourceDescription creates a human-readable description of the resource mismatch
func getResourceDescription(expected, actual *unstructured.Unstructured, mismatchType string) string {
switch mismatchType {
case "missing":
return fmt.Sprintf("%s/%s is missing from cluster", expected.GetKind(), expected.GetName())
case "different":
return fmt.Sprintf("%s/%s differs between Git and cluster", expected.GetKind(), expected.GetName())
case "extra":
return fmt.Sprintf("%s/%s exists in cluster but not in Git", actual.GetKind(), actual.GetName())
default:
return fmt.Sprintf("Unknown mismatch type: %s", mismatchType)
}
}