-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathcache.go
More file actions
1922 lines (1733 loc) · 62.9 KB
/
Copy pathcache.go
File metadata and controls
1922 lines (1733 loc) · 62.9 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
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
package k8s
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"sync"
"time"
appsv1 "k8s.io/api/apps/v1"
autoscalingv2 "k8s.io/api/autoscaling/v2"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/skyhook-io/radar/internal/timeline"
"github.com/skyhook-io/radar/pkg/k8score"
"github.com/skyhook-io/radar/pkg/topology"
)
// DebugEvents enables verbose event debugging when true (set via --debug-events flag)
var DebugEvents bool
// ListPageSize, when > 0, makes high-cardinality informers (Pods, ReplicaSets)
// paginate their initial LIST instead of pulling it in one response (set via
// --list-page-size flag). Opt-in hardening for very large clusters where
// WatchList streaming isn't available; 0 keeps the standard behavior.
var ListPageSize int64
// ForceNamespaceScope pins all namespaced informer caches to one namespace.
// Cluster-scoped resources still use cluster-wide informers.
var ForceNamespaceScope bool
// TimingLogs enables [startup-timing] log lines when true (set via --dev flag).
// These are useful for profiling startup but too noisy for production.
var TimingLogs bool
// LogTiming prints a [startup-timing] log line if TimingLogs is enabled.
func LogTiming(format string, args ...any) {
if TimingLogs {
log.Printf("[startup-timing] "+format, args...)
}
}
var logTiming = LogTiming
// initialSyncComplete is set to true after the initial cache sync completes.
// During initial sync, "add" events are skipped since they represent existing
// resources, not new creations. Only adds after sync are recorded.
var initialSyncComplete bool
// deferredResources lists informer keys that are NOT required for the initial
// dashboard render. These sync in the background after the critical informers
// complete, so the UI can render immediately with core resources.
// Critical: pods, deployments, services, statefulsets, daemonsets, nodes, namespaces, ingresses, jobs, cronjobs.
var deferredResources = map[string]bool{
"secrets": true,
"events": true,
"configmaps": true,
"persistentvolumeclaims": true,
"persistentvolumes": true,
"storageclasses": true,
"poddisruptionbudgets": true,
"networkpolicies": true,
"replicasets": true, // topology-only (Deployment→RS→Pod); can be very large
"horizontalpodautoscalers": true, // problems detection, not critical for first render
"serviceaccounts": true, // audit inheritance lookups, not first-render
"limitranges": true, // audit inheritance lookups, not first-render
"resourcequotas": true, // scheduling/admission diagnostics, not first-render
}
// minimalFirstPaintSet is the subset of critical informers the home
// dashboard needs to feel coherent. Pods are included despite being
// typically the largest kind — without pods the topology graph and
// resource counts are empty. The patience window absorbs pod-sync
// latency on healthy clusters; on slow ones, the user sees a working
// home view sooner with a "still loading" hint for the rest.
var minimalFirstPaintSet = map[string]bool{
"pods": true,
"namespaces": true,
"nodes": true,
"services": true,
"deployments": true,
}
// firstPaintPatience is how long we wait for ALL critical informers before
// falling back to the minimal set. On most clusters the full critical set
// syncs well inside this window, so first paint is complete and there is
// no progressive fill-in. Slow clusters fall through to the minimal-set
// gate and render with whatever is ready then.
const firstPaintPatience = 8 * time.Second
// firstPaintBackstop now lives in deadlines.go as the exported package
// variable FirstPaintBackstop so operators can widen the bound from the
// command line without recompiling. The 5-minute default is preserved.
// ResourceChange is a type alias for the canonical definition in pkg/k8score.
type ResourceChange = k8score.ResourceChange
// ResourceCache provides fast, eventually-consistent access to K8s resources
// using SharedInformers. It embeds *k8score.ResourceCache for the shared
// informer logic and adds Radar-specific extensions (dynamic cache, resource
// status, pod workload lookup, timeline integration).
type ResourceCache struct {
*k8score.ResourceCache
secretsEnabled bool // Whether secrets informer is running (requires RBAC)
// argoDrift tracks how long each manual-sync ArgoCD Application has been
// continuously OutOfSync. Lives here so its lifecycle is the cache's:
// recreated per cluster, dropped on a kubeconfig context switch.
argoDrift *argoDriftTracker
// secretWriteTimes preserves verified Secret data-owner write times that
// the shared informer transform intentionally strips before caching.
secretWriteTimes *secretDataManagerWriteIndex
}
type secretDataManagerWrite struct {
uid string
at time.Time
}
type secretDataManagerWriteVersion struct {
namespace string
name string
uid string
resourceVersion string
}
type pendingSecretDataManagerWrite struct {
write *secretDataManagerWrite
helm bool
}
type secretDataManagerWriteIndex struct {
mu sync.Mutex
committed map[string]secretDataManagerWrite
pending map[secretDataManagerWriteVersion]pendingSecretDataManagerWrite
pendingLimit int
}
const maxPendingSecretDataManagerWrites = 10_000
func newSecretDataManagerWriteIndex() *secretDataManagerWriteIndex {
return &secretDataManagerWriteIndex{
committed: make(map[string]secretDataManagerWrite),
pending: make(map[secretDataManagerWriteVersion]pendingSecretDataManagerWrite),
pendingLimit: maxPendingSecretDataManagerWrites,
}
}
func secretWriteKey(namespace, name string) string {
return namespace + "\x00" + name
}
func secretChangeWritesData(change k8score.ResourceChange) bool {
if change.Diff == nil {
return false
}
for _, field := range change.Diff.Fields {
if isSecretDataWritePath(field.Path) {
return true
}
}
return false
}
func isSecretDataWritePath(path string) bool {
switch path {
case "data (added keys)", "data (removed keys)", "data (modified keys)",
"stringData (added keys)", "stringData (removed keys)", "stringData (modified keys)":
return true
default:
return false
}
}
func (index *secretDataManagerWriteIndex) capture(obj any) {
secret, ok := obj.(*corev1.Secret)
if !ok || secret == nil || index == nil {
return
}
var latest time.Time
for _, entry := range secret.ManagedFields {
if entry.Time == nil || entry.FieldsV1 == nil ||
(entry.Operation != metav1.ManagedFieldsOperationApply && entry.Operation != metav1.ManagedFieldsOperationUpdate) {
continue
}
raw := entry.FieldsV1.Raw
if !bytes.Contains(raw, []byte(`"f:data"`)) && !bytes.Contains(raw, []byte(`"f:stringData"`)) {
continue
}
var fields map[string]json.RawMessage
if json.Unmarshal(raw, &fields) != nil {
continue
}
if _, ownsData := fields["f:data"]; !ownsData {
if _, ownsStringData := fields["f:stringData"]; !ownsStringData {
continue
}
}
if entry.Time.Time.After(latest) {
latest = entry.Time.Time
}
}
version := secretDataManagerWriteVersion{
namespace: secret.Namespace,
name: secret.Name,
uid: string(secret.UID),
resourceVersion: secret.ResourceVersion,
}
pending := pendingSecretDataManagerWrite{
helm: secret.Type == corev1.SecretType("helm.sh/release.v1"),
}
if !latest.IsZero() {
pending.write = &secretDataManagerWrite{uid: string(secret.UID), at: latest}
}
index.mu.Lock()
if _, exists := index.pending[version]; !exists && len(index.pending) >= index.pendingLimit {
// Transform observations are advisory. Under callback starvation,
// discard unmatched candidates rather than grow without bound; a
// missing fallback fails closed and a later object version can restage.
clear(index.pending)
}
index.pending[version] = pending
index.mu.Unlock()
}
func (index *secretDataManagerWriteIndex) reconcile(change k8score.ResourceChange, obj any) {
if index == nil || change.Kind != "Secret" {
return
}
key := secretWriteKey(change.Namespace, change.Name)
index.mu.Lock()
defer index.mu.Unlock()
if change.Operation == k8score.OpDelete {
if write, ok := index.committed[key]; ok && write.uid == change.UID {
delete(index.committed, key)
}
for version := range index.pending {
if version.namespace == change.Namespace && version.name == change.Name && version.uid == change.UID {
delete(index.pending, version)
}
}
return
}
meta, ok := obj.(metav1.Object)
if !ok || meta == nil {
return
}
version := secretDataManagerWriteVersion{
namespace: change.Namespace,
name: change.Name,
uid: change.UID,
resourceVersion: meta.GetResourceVersion(),
}
pending, ok := index.pending[version]
if !ok {
return
}
delete(index.pending, version)
if pending.helm {
if write, ok := index.committed[key]; !ok || write.uid == change.UID {
delete(index.committed, key)
}
return
}
if change.Operation == k8score.OpUpdate && !secretChangeWritesData(change) {
return
}
if write, ok := index.committed[key]; ok && write.uid != change.UID && change.Operation != k8score.OpAdd {
return
}
if pending.write == nil {
delete(index.committed, key)
return
}
index.committed[key] = *pending.write
}
func (index *secretDataManagerWriteIndex) load(namespace, name string) (secretDataManagerWrite, bool) {
if index == nil {
return secretDataManagerWrite{}, false
}
index.mu.Lock()
defer index.mu.Unlock()
write, ok := index.committed[secretWriteKey(namespace, name)]
return write, ok
}
var (
resourceCache *ResourceCache
cacheOnce = new(sync.Once)
cacheMu sync.Mutex
)
// tombstones retains recently-seen resource enrichment (owner/labels/createdAt)
// for a short window after objects leave the informer cache, so delete-time and
// late K8s events (the "Killing" class, processed after the involved object is
// already gone from cache) carry owner/labels/createdAt as fact instead of
// shipping anonymous. Fed from informer add/update/delete callbacks (an
// already-seen relist add returns before recording, so it skips the feed);
// consulted after the live cache during event enrichment. Bounded + TTL'd so
// it cannot grow without limit; misses are silent (null enrichment).
var tombstones = timeline.NewTombstoneCache(15*time.Minute, 4000)
// InitResourceCache initializes the resource cache with timeline-wired callbacks.
func InitResourceCache(ctx context.Context) error {
var initErr error
cacheOnce.Do(func() {
if k8sClient == nil {
initErr = fmt.Errorf("cannot create resource cache: k8s client not initialized")
return
}
// Probe per-resource list access before creating informers. The
// returned scope map is authoritative for both enablement and
// per-kind namespace scoping (some kinds may be cluster-wide while
// others are namespace-scoped to the same fallback namespace).
rbacStart := time.Now()
rbacCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
permResult := CheckResourcePermissions(rbacCtx)
cancel()
logTiming(" Resource access probes: %v", time.Since(rbacStart))
if ctx.Err() != nil {
initErr = ctx.Err()
return
}
// scopes drives which informers are created and at what scope.
// k8score routes each kind through the matching factory (cluster-wide
// or namespace-scoped) based on these per-kind decisions.
scopes := permResult.Scopes
if scopes == nil {
scopes = map[string]k8score.ResourceScope{}
}
// Captured ONCE at wiring time and closed over by the callbacks below.
// Informer shutdown on context switch is asynchronous (up to 5s, then
// abandoned), so a late callback reading ActiveClusterContext() at
// delivery time would stamp the OLD cluster's event with the NEW
// cluster's name — permanently, under SQLite storage. Closing over the
// wiring-time value keeps late events truthfully attributed to the
// cluster they came from.
recordClusterContext := ActiveClusterContext()
secretWriteTimes := newSecretDataManagerWriteIndex()
cfg := k8score.CacheConfig{
Client: k8sClient,
ResourceScopes: scopes,
ResourceScopeNamespaces: permResult.ScopeNamespaces,
DeferredTypes: deferredResources,
DebugEvents: DebugEvents,
TimingLogger: logTiming,
PatienceWindow: firstPaintPatience,
MinimalSet: minimalFirstPaintSet,
SyncTimeout: FirstPaintBackstop,
SyncProgress: emitSyncProgress,
DeferredSyncTimeout: 3 * time.Minute,
ListPageSize: ListPageSize,
OnReceived: func(kind string) {
timeline.IncrementReceived(kind)
},
OnTransform: func(obj any) {
secretWriteTimes.capture(obj)
},
OnChange: func(change k8score.ResourceChange, obj, oldObj any) {
secretWriteTimes.reconcile(change, obj)
if DebugEvents && change.Operation == "add" &&
(change.Kind == "Pod" || change.Kind == "Deployment" || change.Kind == "Service") {
log.Printf("[DEBUG] enqueueChange: %s add %s/%s", change.Kind, change.Namespace, change.Name)
}
// Record to timeline store
recordToTimelineStore(recordClusterContext, change.Kind, change.Namespace, change.Name, change.UID, change.Operation, oldObj, obj, change.Diff, true)
},
OnEventChange: func(obj any, op string) {
// Event deletes are not recorded to timeline — events represent
// things that happened and should remain in history.
if op == "delete" {
return
}
recordK8sEventToTimeline(recordClusterContext, obj)
},
OnDrop: func(kind, ns, name, reason, op string) {
timeline.RecordDrop(kind, ns, name, reason, op)
if DebugEvents {
log.Printf("[DEBUG] Change dropped: %s/%s/%s reason=%s op=%s", kind, ns, name, reason, op)
}
},
ComputeDiff: func(kind string, oldObj, newObj any) *k8score.DiffInfo {
return ComputeDiff(kind, oldObj, newObj)
},
IsNoisyResource: isNoisyResource,
}
core, err := k8score.NewResourceCache(cfg)
if err != nil {
initErr = err
return
}
initialSyncComplete = core.IsSyncComplete()
resourceCache = &ResourceCache{
ResourceCache: core,
secretsEnabled: scopes["secrets"].Enabled,
argoDrift: newArgoDriftTracker(),
secretWriteTimes: secretWriteTimes,
}
})
return initErr
}
// GetResourceCache returns the singleton cache instance.
func GetResourceCache() *ResourceCache {
return resourceCache
}
// ResetResourceCache stops and clears the resource cache so it can be
// reinitialized for a new cluster after context switch.
func ResetResourceCache() {
cacheMu.Lock()
defer cacheMu.Unlock()
if resourceCache != nil {
resourceCache.Stop()
resourceCache = nil
}
cacheOnce = new(sync.Once)
initialSyncComplete = false
resetRecreateStash()
// Tombstone keys are UID-first, falling back to an apiVersion|kind|ns|name
// composite (no cluster context) when a source lacks a UID; a leftover
// UID-less entry could mis-enrich a same-named resource on the next cluster.
// Drop them all in place (not a var reassignment) so concurrent informer
// readers of the stable pointer don't race with the reset.
tombstones.Clear()
}
// recordK8sEventToTimeline records a K8s Event to the timeline store.
// clusterContext is the wiring-time capture (see InitResourceCache), not the
// live active context — a late callback must stamp the cluster it came from.
func recordK8sEventToTimeline(clusterContext string, obj any) {
event, ok := obj.(*corev1.Event)
if !ok {
return
}
store := timeline.GetStore()
if store == nil {
return
}
if DebugEvents {
timeline.IncrementReceived("K8sEvent:" + event.InvolvedObject.Kind)
}
owner, labels, createdAt := enrichInvolvedObject(event)
timelineEvent := timeline.NewK8sEventTimelineEvent(event, owner)
timelineEvent.Labels = labels
timelineEvent.CreatedAt = createdAt
timelineEvent.ClusterContext = clusterContext
ctx := context.Background()
if err := timeline.RecordEventWithBroadcast(ctx, timelineEvent); err != nil {
log.Printf("Warning: failed to record K8s event to timeline store: %v", err)
} else if DebugEvents {
timeline.IncrementRecorded("K8sEvent:" + event.InvolvedObject.Kind)
}
}
// enrichInvolvedObject resolves the K8s Event's involved object to its
// controller owner, grouping labels, and creation time. The live informer cache
// is consulted first (freshest); the tombstone second, which is what carries the
// answer for delete-time and late events (e.g. "Killing") whose involved object
// has already left the cache. A total miss returns nils — the event ships with
// whatever the event itself provides, exactly as before.
func enrichInvolvedObject(event *corev1.Event) (owner *timeline.OwnerInfo, labels map[string]string, createdAt *time.Time) {
inv := event.InvolvedObject
if o, l, c, ok := liveInvolvedObject(string(inv.UID), inv.Kind, event.Namespace, inv.Name); ok {
return o, l, c
}
if entry, ok := tombstones.Get(string(inv.UID), inv.APIVersion, inv.Kind, event.Namespace, inv.Name); ok {
return entry.Owner, entry.Labels, entry.CreatedAt
}
return nil, nil, nil
}
// liveInvolvedObject reads the involved object straight from the typed informer
// cache when it is still present. ok=false means the object is not (or no longer)
// cached, so the caller should fall back to the tombstone.
func liveInvolvedObject(uid, kind, namespace, name string) (owner *timeline.OwnerInfo, labels map[string]string, createdAt *time.Time, ok bool) {
cache := GetResourceCache()
if cache == nil {
return nil, nil, nil, false
}
// The typed lister lookup is by kind/ns/name; when the event names a UID,
// verify it so a same-named different object (a CRD kind collision, or a
// recreated object) can't lend its enrichment. A mismatch falls through to
// the tombstone, which is keyed by UID.
uidMatches := func(obj metav1.Object) bool {
return uid == "" || string(obj.GetUID()) == uid
}
switch kind {
case "Pod":
if cache.Pods() == nil {
return nil, nil, nil, false
}
pod, err := cache.Pods().Pods(namespace).Get(name)
if err != nil || pod == nil || !uidMatches(pod) {
return nil, nil, nil, false
}
return controllerOwner(pod.OwnerReferences), timeline.ExtractLabels(pod), creationPtr(pod), true
case "ReplicaSet":
if cache.ReplicaSets() == nil {
return nil, nil, nil, false
}
rs, err := cache.ReplicaSets().ReplicaSets(namespace).Get(name)
if err != nil || rs == nil || !uidMatches(rs) {
return nil, nil, nil, false
}
return controllerOwner(rs.OwnerReferences), timeline.ExtractLabels(rs), creationPtr(rs), true
}
return nil, nil, nil, false
}
// controllerOwner returns the controller owner reference as OwnerInfo, or nil
// when the object has no controller (e.g. a bare pod).
func controllerOwner(refs []metav1.OwnerReference) *timeline.OwnerInfo {
for _, ref := range refs {
if ref.Controller != nil && *ref.Controller {
return &timeline.OwnerInfo{Kind: ref.Kind, Name: ref.Name}
}
}
return nil
}
func creationPtr(obj metav1.Object) *time.Time {
ct := obj.GetCreationTimestamp().Time
if ct.IsZero() {
return nil
}
return &ct
}
// emitSyncProgress is the SyncProgress callback wired into the resource
// cache. It keeps the connection's progressMessage in step with the live
// informer-sync count so the connecting screen ticks up instead of
// sitting on a static message during a 30–60s sync. Once the cache
// returns and connection state flips to "connected", further progress
// lives in the home dashboard's deferred-loading indicator.
func emitSyncProgress(synced, total int, minimalReady bool) {
if total == 0 {
return
}
// Only update while we're still in the connecting phase. Once
// connected, the connecting screen is gone and the message is moot.
if GetConnectionStatus().State != StateConnecting {
return
}
var msg string
switch {
case synced == total:
msg = "Finalizing…"
case minimalReady:
msg = fmt.Sprintf("Loading cluster data… %d of %d ready (showing partial)", synced, total)
default:
msg = fmt.Sprintf("Loading cluster data… %d of %d ready", synced, total)
}
UpdateConnectionProgress(msg)
}
// isNoisyResource returns true if this resource generates constant updates that aren't interesting
func isNoisyResource(kind, name, op string) bool {
if op != "update" {
return false
}
switch kind {
case "Lease", "Endpoints", "EndpointSlice", "Event":
return true
case "VerticalPodAutoscalerCheckpoint":
// VPA writes per-container resource recommendations here on every
// reconcile (~1m). The whole point of the resource is to be a live
// ticker — per-update is never user-meaningful.
return true
}
if kind == "ConfigMap" {
noisyPatterns := []string{
"-lock", "-lease", "-leader-election", "-heartbeat",
"cluster-kubestore", "cluster-autoscaler-status",
"datadog-token", "datadog-operator-lock", "datadog-leader-election",
"kube-root-ca.certs",
}
for _, pattern := range noisyPatterns {
if strings.Contains(name, pattern) {
return true
}
}
}
if kind == "Secret" {
if strings.HasSuffix(name, "-token") || strings.Contains(name, "leader-election") {
return true
}
}
return false
}
// getGeneration returns the metadata.generation of an informer object, or 0
// if the object is nil or doesn't expose metav1.Object. Both typed K8s
// resources and *unstructured.Unstructured satisfy metav1.Object.
func getGeneration(obj any) int64 {
if obj == nil {
return 0
}
m, ok := obj.(metav1.Object)
if !ok {
return 0
}
return m.GetGeneration()
}
// recordToTimelineStore records a resource change to the timeline.
// clusterContext is the wiring-time capture (see InitResourceCache), not the
// live active context — a late callback must stamp the cluster it came from.
// When the caller has already computed the update diff (the cache layer does,
// before firing OnChange), it passes it via precomputedDiff +
// diffPrecomputed=true so we don't recompute the identical diff on the hottest
// per-update path; callers without one (tests, non-cache paths) pass nil +
// false and the diff is computed here.
func recordToTimelineStore(clusterContext, kind, namespace, name, uid, op string, oldObj, newObj any, precomputedDiff *DiffInfo, diffPrecomputed bool) {
store := timeline.GetStore()
if store == nil {
return
}
if op == "add" {
if store.IsResourceSeen(clusterContext, kind, namespace, name) {
timeline.RecordDrop(kind, namespace, name, timeline.DropReasonAlreadySeen, op)
if DebugEvents {
log.Printf("[DEBUG] Already seen, skipping: %s/%s/%s", kind, namespace, name)
}
return
}
} else if op == "delete" {
store.ClearResourceSeen(clusterContext, kind, namespace, name)
}
obj := newObj
if obj == nil {
obj = oldObj
}
resourceVersion := ""
if obj != nil {
if meta, ok := obj.(metav1.Object); ok {
resourceVersion = meta.GetResourceVersion()
}
}
if op == "delete" {
stashDeletedForRecreate(kind, namespace, name, uid, obj)
}
// One extraction of owner/labels/createdAt, reused for both the event and
// the tombstone. ExtractTombstoneEntry unwraps DeletedFinalStateUnknown, so
// a delete whose payload is that wrapper still yields the final object.
entry, extracted := timeline.ExtractTombstoneEntry(obj)
owner := entry.Owner
labels := entry.Labels
createdAt := entry.CreatedAt
healthState := classifyTimelineHealth(kind, obj, time.Now())
apiVersion := extractAPIVersion(obj)
// Feed the tombstone on every add/update/delete. While the object is live
// this mirrors its enrichment; once it is gone (delete, or a late K8s event
// after eviction) the retained copy is the only source of owner/labels.
// Only when the object actually unwrapped — an extract failure yields an
// empty entry, and storing it would clobber the enrichment a prior good
// entry was preserving.
if name != "" && extracted {
tombstones.Put(uid, apiVersion, kind, namespace, name, entry)
}
var diff *timeline.DiffInfo
if op == "update" && oldObj != nil && newObj != nil {
// Reuse the cache layer's already-computed diff on the hot path; only
// recompute for callers (tests / non-cache) that didn't precompute it.
localDiff := precomputedDiff
if !diffPrecomputed {
localDiff = ComputeDiff(kind, oldObj, newObj)
}
if localDiff != nil {
diff = &timeline.DiffInfo{
Fields: make([]timeline.FieldChange, len(localDiff.Fields)),
Summary: localDiff.Summary,
}
for i, f := range localDiff.Fields {
diff.Fields[i] = timeline.FieldChange{
Path: f.Path,
OldValue: f.OldValue,
NewValue: f.NewValue,
}
}
} else if KindHasDiffer(kind) || isUnstructuredUpdate(oldObj, newObj) {
// Diff handling found nothing observable — usually a heartbeat,
// managedFields-only update, or reconcile counter.
// Before dropping, check metadata.generation: it bumps only on
// spec changes (status updates don't touch it), so a generation
// flip with a nil diff means our diff function missed a real spec
// field. Record those with a fallback summary instead of silently
// losing them — diff coverage gaps shouldn't become silent drops.
if oldGen, newGen := getGeneration(oldObj), getGeneration(newObj); oldGen != newGen && oldGen > 0 && newGen > 0 {
diff = &timeline.DiffInfo{
Fields: []timeline.FieldChange{{
Path: "metadata.generation",
OldValue: oldGen,
NewValue: newGen,
}},
Summary: fmt.Sprintf("spec changed (gen %d→%d, fields not specifically tracked)", oldGen, newGen),
}
} else {
timeline.RecordDrop(kind, namespace, name, timeline.DropReasonNoDiff, op)
if DebugEvents {
log.Printf("[DEBUG] No-diff update, skipping: %s/%s/%s", kind, namespace, name)
}
return
}
}
}
// Recreate-join: an add that replaces a just-deleted object of the same
// name but a different UID carries the diff against its predecessor, so
// the change feed can show what the recreate changed instead of a
// contentless delete+add pair. Guarded to young objects post-sync — the
// same conditions under which the add below is recorded at all.
//
// Status is stripped from BOTH sides before diffing: every recreate
// resets status, so cross-recreate status deltas (ready 1→0, condition
// flips) are tautological noise — and worse, a spec-identical recreate
// (namespace re-apply) would otherwise emit a status-only "recreated
// with changes" entry that reads as a config change.
recreated := false
if op == "add" && newObj != nil && initialSyncComplete {
if meta, ok := newObj.(metav1.Object); ok && time.Since(meta.GetCreationTimestamp().Time) <= 30*time.Second {
if stashed, ok := takeRecreateMatch(kind, namespace, name, uid); ok {
if localDiff := ComputeDiff(kind, stripStatusForRecreateDiff(stashed), stripStatusForRecreateDiff(newObj)); localDiff != nil && len(localDiff.Fields) > 0 {
diff = &timeline.DiffInfo{
Fields: make([]timeline.FieldChange, len(localDiff.Fields)),
Summary: "recreated with changes: " + localDiff.Summary,
}
for i, f := range localDiff.Fields {
diff.Fields[i] = timeline.FieldChange{
Path: f.Path,
OldValue: f.OldValue,
NewValue: f.NewValue,
}
}
recreated = true
}
}
}
}
event := timeline.NewInformerEvent(
kind, apiVersion, namespace, name, uid, resourceVersion,
timeline.OperationToEventType(op),
healthState,
diff,
owner,
labels,
createdAt,
)
event.ClusterContext = clusterContext
if recreated {
event.Reason = timeline.ReasonRecreated
}
var events []timeline.TimelineEvent
if op == "add" && newObj != nil {
historicalEvents := extractTimelineHistoricalEvents(clusterContext, kind, apiVersion, namespace, name, newObj, owner, labels)
for i := range historicalEvents {
historicalEvents[i].ClusterContext = event.ClusterContext
}
events = append(events, historicalEvents...)
}
if op == "add" {
isSyncEvent := false
if !initialSyncComplete {
isSyncEvent = true
}
if !isSyncEvent && obj != nil {
if meta, ok := obj.(metav1.Object); ok {
creationTime := meta.GetCreationTimestamp().Time
age := time.Since(creationTime)
if age > 30*time.Second {
isSyncEvent = true
if DebugEvents {
log.Printf("[DEBUG] Skipping stale add event (age=%v): %s/%s/%s", age, kind, namespace, name)
}
}
}
}
if isSyncEvent {
if DebugEvents {
log.Printf("[DEBUG] Skipping sync add event: %s/%s/%s (extracted %d historical events)", kind, namespace, name, len(events))
}
if len(events) > 0 {
ctx := context.Background()
if err := timeline.RecordEventsWithBroadcast(ctx, events); err != nil {
log.Printf("Warning: failed to record historical events: %v", err)
timeline.RecordDrop(kind, namespace, name, timeline.DropReasonStoreFailed, op)
return
}
}
store.MarkResourceSeen(clusterContext, kind, namespace, name)
return
}
}
events = append(events, event)
ctx := context.Background()
if err := timeline.RecordEventsWithBroadcast(ctx, events); err != nil {
log.Printf("Warning: failed to record to timeline store: %v", err)
timeline.RecordDrop(kind, namespace, name, timeline.DropReasonStoreFailed, op)
return
}
timeline.IncrementRecorded(kind)
if op == "add" {
store.MarkResourceSeen(clusterContext, kind, namespace, name)
}
}
func isUnstructuredUpdate(oldObj, newObj any) bool {
_, oldOK := oldObj.(*unstructured.Unstructured)
_, newOK := newObj.(*unstructured.Unstructured)
return oldOK && newOK
}
// extractAPIVersion returns the resource's apiVersion (e.g. "cluster.x-k8s.io/v1beta1")
// for unstructured/CRD objects. Typed informer objects strip kind/apiVersion, so they
// fall through to "" — the navigation layer treats an empty group as "core/typed kind",
// which is correct since core kinds don't collide.
func extractAPIVersion(obj any) string {
if u, ok := obj.(*unstructured.Unstructured); ok {
return u.GetAPIVersion()
}
return ""
}
// extractTimelineHistoricalEvents extracts historical events from resource metadata/status
func extractTimelineHistoricalEvents(clusterContext, kind, apiVersion, namespace, name string, obj any, owner *timeline.OwnerInfo, labels map[string]string) []timeline.TimelineEvent {
var events []timeline.TimelineEvent
switch kind {
case "Pod":
if pod, ok := obj.(*corev1.Pod); ok {
if !pod.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
pod.CreationTimestamp.Time, "created", "", timeline.HealthUnknown, owner, labels))
}
if pod.Status.StartTime != nil && !pod.Status.StartTime.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
pod.Status.StartTime.Time, "started", "", timeline.HealthDegraded, owner, labels))
}
for _, cond := range pod.Status.Conditions {
if cond.LastTransitionTime.IsZero() {
continue
}
health := timeline.HealthUnknown
if cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {
health = timeline.HealthHealthy
} else if cond.Status == corev1.ConditionFalse {
health = timeline.HealthDegraded
}
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
cond.LastTransitionTime.Time, string(cond.Type), cond.Message, health, owner, labels))
}
}
case "Deployment":
if deploy, ok := obj.(*appsv1.Deployment); ok {
if !deploy.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
deploy.CreationTimestamp.Time, "created", "", timeline.HealthUnknown, owner, labels))
}
for _, cond := range deploy.Status.Conditions {
if cond.LastTransitionTime.IsZero() {
continue
}
health := timeline.HealthUnknown
if cond.Type == appsv1.DeploymentAvailable && cond.Status == corev1.ConditionTrue {
health = timeline.HealthHealthy
} else if cond.Status == corev1.ConditionFalse {
health = timeline.HealthDegraded
}
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
cond.LastTransitionTime.Time, string(cond.Type), cond.Message, health, owner, labels))
}
}
case "ReplicaSet":
if rs, ok := obj.(*appsv1.ReplicaSet); ok {
if !rs.CreationTimestamp.IsZero() {
health := timeline.HealthUnknown
if rs.Status.ReadyReplicas > 0 && rs.Status.ReadyReplicas == rs.Status.Replicas {
health = timeline.HealthHealthy
}
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
rs.CreationTimestamp.Time, "created", "", health, owner, labels))
}
}
case "StatefulSet":
if sts, ok := obj.(*appsv1.StatefulSet); ok {
if !sts.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
sts.CreationTimestamp.Time, "created", "", timeline.HealthUnknown, owner, labels))
}
}
case "DaemonSet":
if ds, ok := obj.(*appsv1.DaemonSet); ok {
if !ds.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
ds.CreationTimestamp.Time, "created", "", timeline.HealthUnknown, owner, labels))
}
}
case "Service":
if svc, ok := obj.(*corev1.Service); ok {
if !svc.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
svc.CreationTimestamp.Time, "created", "", timeline.HealthHealthy, owner, labels))
}
}
case "Ingress":
if ing, ok := obj.(*networkingv1.Ingress); ok {
if !ing.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
ing.CreationTimestamp.Time, "created", "", timeline.HealthHealthy, owner, labels))
}
}
case "CronJob":
if cj, ok := obj.(*batchv1.CronJob); ok {
if !cj.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
cj.CreationTimestamp.Time, "created", "", timeline.HealthHealthy, owner, labels))
}
}
case "HorizontalPodAutoscaler":
if hpa, ok := obj.(*autoscalingv2.HorizontalPodAutoscaler); ok {
if !hpa.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
hpa.CreationTimestamp.Time, "created", "", timeline.HealthHealthy, owner, labels))
}
}
case "Job":
if job, ok := obj.(*batchv1.Job); ok {
if !job.CreationTimestamp.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,
job.CreationTimestamp.Time, "created", "", timeline.HealthUnknown, owner, labels))
}
if job.Status.StartTime != nil && !job.Status.StartTime.IsZero() {
events = append(events, timeline.NewHistoricalEvent(clusterContext, kind, apiVersion, namespace, name,