-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathsummary.go
More file actions
648 lines (582 loc) · 18.6 KB
/
Copy pathsummary.go
File metadata and controls
648 lines (582 loc) · 18.6 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
package context
import (
"fmt"
"reflect"
"strings"
"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/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/skyhook-io/radar/pkg/cronsched"
"github.com/skyhook-io/radar/pkg/hpadiag"
"github.com/skyhook-io/radar/pkg/resourcecontext"
)
// ResourceSummary is the typed output for Summary-level minification.
// Typed struct ensures no extra fields can leak.
type ResourceSummary struct {
Kind string `json:"kind"`
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
Status string `json:"status,omitempty"`
Ready string `json:"ready,omitempty"`
Issue string `json:"issue,omitempty"`
Age string `json:"age,omitempty"`
// Terminating signals that metadata.deletionTimestamp is set on the
// resource. AI agents need this signal to avoid suggesting
// mutating actions that will fail (e.g. "run kubectl rollout restart"
// on a Pod that's being torn down) and to correctly diagnose "why is
// this stuck" scenarios where the resource is a finalizer-blocked
// zombie. Pruned when false.
Terminating bool `json:"terminating,omitempty"`
// Finalizers names the keys blocking deletion when Terminating is
// true. The owning controller is responsible for clearing each key
// during cleanup; if it doesn't, the resource lingers as a zombie.
// Pruned when empty.
Finalizers []string `json:"finalizers,omitempty"`
// Type-specific fields (only populated when relevant)
Image string `json:"image,omitempty"`
Ports string `json:"ports,omitempty"`
Schedule string `json:"schedule,omitempty"`
Type string `json:"type,omitempty"` // Service type, Secret type
Selector string `json:"selector,omitempty"`
ClusterIP string `json:"clusterIP,omitempty"`
Hosts []string `json:"hosts,omitempty"`
Restarts int32 `json:"restarts,omitempty"`
Node string `json:"node,omitempty"`
Strategy string `json:"strategy,omitempty"`
Completions string `json:"completions,omitempty"`
Duration string `json:"duration,omitempty"`
Suspended *bool `json:"suspended,omitempty"`
Unschedulable *bool `json:"unschedulable,omitempty"`
Active int `json:"active,omitempty"`
Target string `json:"target,omitempty"`
MinReplicas *int32 `json:"minReplicas,omitempty"`
MaxReplicas int32 `json:"maxReplicas,omitempty"`
Current int32 `json:"current,omitempty"`
Desired int32 `json:"desired,omitempty"`
Roles []string `json:"roles,omitempty"`
Version string `json:"version,omitempty"`
Pressures []string `json:"pressures,omitempty"`
Keys []string `json:"keys,omitempty"`
StorageClass string `json:"storageClass,omitempty"`
Capacity string `json:"capacity,omitempty"`
AccessModes []string `json:"accessModes,omitempty"`
Owner string `json:"owner,omitempty"`
// SummaryContext is the per-row enrichment attached by AI-facing list
// surfaces (REST /api/ai/resources/{kind}, MCP list_resources, search
// hits). Populated by handlers post-minify via resourcecontext.BuildSummary;
// nil when the caller opted out (?context=none) or when no fields apply.
// Type is resourcecontext.ResourceSummaryContext — the field name keeps
// the shorter "SummaryContext" form to match the wire JSON tag.
SummaryContext *resourcecontext.ResourceSummaryContext `json:"summaryContext,omitempty"`
}
// summarize dispatches to the appropriate per-type extractor and then
// fills in lifecycle fields (Terminating, Finalizers) shared across all
// kinds. Filling these once at the dispatch boundary avoids touching
// every per-type summarizer; all K8s resource types implement
// metav1.Object, so the cast is universal.
func summarize(obj runtime.Object) (*ResourceSummary, error) {
// Typed-nil-through-interface trap: a (*v1.Pod)(nil) assigned to
// runtime.Object compares != nil but calling methods panics. Catch
// it once at the boundary so per-type summarizers and
// applyLifecycleFields can assume non-nil concrete values.
if isNilObject(obj) {
return &ResourceSummary{Kind: "Unknown"}, nil
}
var s *ResourceSummary
switch o := obj.(type) {
case *corev1.Pod:
s = summarizePod(o)
case *appsv1.Deployment:
s = summarizeDeployment(o)
case *appsv1.StatefulSet:
s = summarizeStatefulSet(o)
case *appsv1.DaemonSet:
s = summarizeDaemonSet(o)
case *corev1.Service:
s = summarizeService(o)
case *networkingv1.Ingress:
s = summarizeIngress(o)
case *batchv1.Job:
s = summarizeJob(o)
case *batchv1.CronJob:
s = summarizeCronJob(o)
case *autoscalingv2.HorizontalPodAutoscaler:
s = summarizeHPA(o)
case *corev1.Node:
s = summarizeNode(o)
case *corev1.ConfigMap:
s = summarizeConfigMap(o)
case *corev1.Secret:
s = summarizeSecret(o)
case *corev1.PersistentVolumeClaim:
s = summarizePVC(o)
case *appsv1.ReplicaSet:
s = summarizeReplicaSet(o)
case *corev1.Namespace:
s = summarizeNamespace(o)
default:
// Generic fallback is better than erroring — a single unsupported
// kind would otherwise break the whole MCP list_resources response.
// Add an explicit case above when richer per-kind output is worth
// maintaining.
s = summarizeGeneric(obj)
}
applyLifecycleFields(s, obj)
return s, nil
}
// summarizeGeneric is the default summarizer for kinds without a hand-written case.
func summarizeGeneric(obj runtime.Object) *ResourceSummary {
if isNilObject(obj) {
return &ResourceSummary{Kind: "Unknown"}
}
s := &ResourceSummary{}
if kinder, ok := obj.(interface{ GetObjectKind() schema.ObjectKind }); ok {
s.Kind = kinder.GetObjectKind().GroupVersionKind().Kind
}
if s.Kind == "" {
// TypeMeta isn't populated on informer-cached objects. Fall back to
// the Go type name with the package qualifier stripped (e.g.
// "*v1.NetworkPolicy" → "NetworkPolicy").
typeName := fmt.Sprintf("%T", obj)
if i := strings.LastIndex(typeName, "."); i >= 0 {
typeName = typeName[i+1:]
}
s.Kind = typeName
}
mo, ok := obj.(interface {
GetName() string
GetNamespace() string
GetCreationTimestamp() metav1.Time
})
if !ok {
return s
}
s.Name = mo.GetName()
s.Namespace = mo.GetNamespace()
s.Age = age(mo.GetCreationTimestamp().Time)
return s
}
// isNilObject handles Go's typed-nil-in-interface trap: a (*v1.Pod)(nil)
// assigned to a runtime.Object interface compares != nil but calling
// methods on it panics. Reflection is the only way to detect this case.
func isNilObject(obj runtime.Object) bool {
if obj == nil {
return true
}
v := reflect.ValueOf(obj)
return v.Kind() == reflect.Ptr && v.IsNil()
}
// applyLifecycleFields populates Terminating + Finalizers on a
// ResourceSummary by reading metadata via the metav1.Object interface
// that every K8s typed object implements. No-ops on a nil summary or
// a non-metav1 object so it's safe to call from any caller.
func applyLifecycleFields(s *ResourceSummary, obj runtime.Object) {
if s == nil {
return
}
mo, ok := obj.(interface {
GetDeletionTimestamp() *metav1.Time
GetFinalizers() []string
})
if !ok {
return
}
if dt := mo.GetDeletionTimestamp(); dt != nil && !dt.IsZero() {
s.Terminating = true
s.Finalizers = mo.GetFinalizers()
}
}
func summarizePod(pod *corev1.Pod) *ResourceSummary {
s := &ResourceSummary{
Kind: "Pod",
Name: pod.Name,
Namespace: pod.Namespace,
Status: string(pod.Status.Phase),
Node: pod.Spec.NodeName,
Age: age(pod.CreationTimestamp.Time),
}
// Image from first container
if len(pod.Spec.Containers) > 0 {
s.Image = pod.Spec.Containers[0].Image
}
// Ready count and restarts
ready, total := int32(0), int32(len(pod.Status.ContainerStatuses))
var restarts int32
for _, cs := range pod.Status.ContainerStatuses {
if cs.Ready {
ready++
}
restarts += cs.RestartCount
}
if total > 0 {
s.Ready = fmt.Sprintf("%d/%d", ready, total)
}
s.Restarts = restarts
// Detect issue
s.Issue = getPodIssue(pod)
if s.Issue != "" {
s.Status = s.Issue
}
return s
}
func summarizeDeployment(dep *appsv1.Deployment) *ResourceSummary {
s := &ResourceSummary{
Kind: "Deployment",
Name: dep.Name,
Namespace: dep.Namespace,
Ready: fmt.Sprintf("%d/%d", dep.Status.ReadyReplicas, dep.Status.Replicas),
Strategy: string(dep.Spec.Strategy.Type),
Age: age(dep.CreationTimestamp.Time),
}
if dep.Status.ReadyReplicas == dep.Status.Replicas && dep.Status.Replicas > 0 {
s.Status = "Running"
} else if dep.Status.Replicas == 0 {
s.Status = "Scaled to 0"
} else {
s.Status = "Progressing"
}
// Image from first container in template
if len(dep.Spec.Template.Spec.Containers) > 0 {
s.Image = dep.Spec.Template.Spec.Containers[0].Image
}
return s
}
func summarizeStatefulSet(sts *appsv1.StatefulSet) *ResourceSummary {
replicas := int32(1)
if sts.Spec.Replicas != nil {
replicas = *sts.Spec.Replicas
}
s := &ResourceSummary{
Kind: "StatefulSet",
Name: sts.Name,
Namespace: sts.Namespace,
Ready: fmt.Sprintf("%d/%d", sts.Status.ReadyReplicas, replicas),
Age: age(sts.CreationTimestamp.Time),
}
if sts.Status.ReadyReplicas == replicas && replicas > 0 {
s.Status = "Running"
} else if replicas == 0 {
s.Status = "Scaled to 0"
} else {
s.Status = "Progressing"
}
if len(sts.Spec.Template.Spec.Containers) > 0 {
s.Image = sts.Spec.Template.Spec.Containers[0].Image
}
return s
}
func summarizeDaemonSet(ds *appsv1.DaemonSet) *ResourceSummary {
s := &ResourceSummary{
Kind: "DaemonSet",
Name: ds.Name,
Namespace: ds.Namespace,
Ready: fmt.Sprintf("%d/%d", ds.Status.NumberReady, ds.Status.DesiredNumberScheduled),
Age: age(ds.CreationTimestamp.Time),
}
if ds.Status.NumberReady == ds.Status.DesiredNumberScheduled && ds.Status.DesiredNumberScheduled > 0 {
s.Status = "Running"
} else {
s.Status = "Progressing"
}
if len(ds.Spec.Template.Spec.Containers) > 0 {
s.Image = ds.Spec.Template.Spec.Containers[0].Image
}
return s
}
func summarizeService(svc *corev1.Service) *ResourceSummary {
s := &ResourceSummary{
Kind: "Service",
Name: svc.Name,
Namespace: svc.Namespace,
Type: string(svc.Spec.Type),
ClusterIP: svc.Spec.ClusterIP,
Age: age(svc.CreationTimestamp.Time),
}
// Format ports
var ports []string
for _, p := range svc.Spec.Ports {
ports = append(ports, fmt.Sprintf("%d/%s", p.Port, p.Protocol))
}
if len(ports) > 0 {
s.Ports = strings.Join(ports, ", ")
}
// Format selector
if len(svc.Spec.Selector) > 0 {
var pairs []string
for k, v := range svc.Spec.Selector {
pairs = append(pairs, fmt.Sprintf("%s=%s", k, v))
}
s.Selector = strings.Join(pairs, ",")
}
return s
}
func summarizeIngress(ing *networkingv1.Ingress) *ResourceSummary {
s := &ResourceSummary{
Kind: "Ingress",
Name: ing.Name,
Namespace: ing.Namespace,
Age: age(ing.CreationTimestamp.Time),
}
if ing.Spec.IngressClassName != nil {
s.Type = *ing.Spec.IngressClassName
} else if v, ok := ing.Annotations["kubernetes.io/ingress.class"]; ok {
s.Type = v
}
hostSet := make(map[string]bool)
for _, rule := range ing.Spec.Rules {
if rule.Host != "" {
hostSet[rule.Host] = true
}
}
for h := range hostSet {
s.Hosts = append(s.Hosts, h)
}
return s
}
func summarizeJob(job *batchv1.Job) *ResourceSummary {
s := &ResourceSummary{
Kind: "Job",
Name: job.Name,
Namespace: job.Namespace,
Age: age(job.CreationTimestamp.Time),
}
// Status from conditions
s.Status = "Running"
for _, c := range job.Status.Conditions {
if c.Type == batchv1.JobComplete && c.Status == corev1.ConditionTrue {
s.Status = "Complete"
} else if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue {
s.Status = "Failed"
}
}
// Completions
target := int32(1)
if job.Spec.Completions != nil {
target = *job.Spec.Completions
}
s.Completions = fmt.Sprintf("%d/%d", job.Status.Succeeded, target)
// Duration
if job.Status.StartTime != nil && job.Status.CompletionTime != nil {
d := job.Status.CompletionTime.Sub(job.Status.StartTime.Time)
s.Duration = formatDuration(d)
}
return s
}
func summarizeCronJob(cj *batchv1.CronJob) *ResourceSummary {
s := &ResourceSummary{
Kind: "CronJob",
Name: cj.Name,
Namespace: cj.Namespace,
Schedule: cj.Spec.Schedule,
Active: len(cj.Status.Active),
Age: age(cj.CreationTimestamp.Time),
}
if cj.Spec.Suspend != nil && *cj.Spec.Suspend {
s.Suspended = cj.Spec.Suspend
} else {
// Staleness is relative to the schedule's cadence, not a flat day: a
// weekly job that ran on schedule 25h ago is healthy, not stale.
threshold := cronsched.StaleThreshold(cj.Spec.Schedule)
if cj.Status.LastScheduleTime != nil && time.Since(cj.Status.LastScheduleTime.Time) > threshold {
s.Issue = "no recent runs"
} else if cj.Status.LastScheduleTime == nil && time.Since(cj.CreationTimestamp.Time) > threshold {
s.Issue = "never scheduled"
}
}
return s
}
func summarizeHPA(hpa *autoscalingv2.HorizontalPodAutoscaler) *ResourceSummary {
s := &ResourceSummary{
Kind: "HorizontalPodAutoscaler",
Name: hpa.Name,
Namespace: hpa.Namespace,
Target: fmt.Sprintf("%s/%s", hpa.Spec.ScaleTargetRef.Kind, hpa.Spec.ScaleTargetRef.Name),
MaxReplicas: hpa.Spec.MaxReplicas,
Current: hpa.Status.CurrentReplicas,
Desired: hpa.Status.DesiredReplicas,
Age: age(hpa.CreationTimestamp.Time),
}
if hpa.Spec.MinReplicas != nil {
s.MinReplicas = hpa.Spec.MinReplicas
}
if diagnosis := hpadiag.Analyze(hpa); diagnosis != nil {
switch diagnosis.State {
case hpadiag.StateLimitedMax:
s.Issue = "maxed"
case hpadiag.StateMetricsUnavailable, hpadiag.StateUnableToScale:
s.Issue = diagnosis.Summary
}
}
return s
}
func summarizeNode(node *corev1.Node) *ResourceSummary {
s := &ResourceSummary{
Kind: "Node",
Name: node.Name,
Version: node.Status.NodeInfo.KubeletVersion,
Age: age(node.CreationTimestamp.Time),
}
// Roles from labels
for label := range node.Labels {
const prefix = "node-role.kubernetes.io/"
if strings.HasPrefix(label, prefix) {
s.Roles = append(s.Roles, label[len(prefix):])
}
}
// Status and pressure conditions
for _, c := range node.Status.Conditions {
if c.Type == corev1.NodeReady {
if c.Status == corev1.ConditionTrue {
s.Status = "Ready"
} else {
s.Status = "NotReady"
s.Issue = c.Reason
}
}
if c.Status == corev1.ConditionTrue {
switch c.Type {
case corev1.NodeMemoryPressure:
s.Pressures = append(s.Pressures, "MemoryPressure")
case corev1.NodeDiskPressure:
s.Pressures = append(s.Pressures, "DiskPressure")
case corev1.NodePIDPressure:
s.Pressures = append(s.Pressures, "PIDPressure")
}
}
}
// Cordoned/unschedulable status
if node.Spec.Unschedulable {
unschedulable := true
s.Unschedulable = &unschedulable
if s.Status != "" {
s.Status += ",SchedulingDisabled"
} else {
s.Status = "SchedulingDisabled"
}
}
return s
}
func summarizeConfigMap(cm *corev1.ConfigMap) *ResourceSummary {
keys := make([]string, 0, len(cm.Data))
for k := range cm.Data {
keys = append(keys, k)
}
return &ResourceSummary{
Kind: "ConfigMap",
Name: cm.Name,
Namespace: cm.Namespace,
Keys: keys,
Age: age(cm.CreationTimestamp.Time),
}
}
func summarizeSecret(secret *corev1.Secret) *ResourceSummary {
keys := make([]string, 0, len(secret.Data)+len(secret.StringData))
for k := range secret.Data {
keys = append(keys, k)
}
for k := range secret.StringData {
keys = append(keys, k)
}
return &ResourceSummary{
Kind: "Secret",
Name: secret.Name,
Namespace: secret.Namespace,
Type: string(secret.Type),
Keys: keys,
Age: age(secret.CreationTimestamp.Time),
}
}
func summarizePVC(pvc *corev1.PersistentVolumeClaim) *ResourceSummary {
s := &ResourceSummary{
Kind: "PersistentVolumeClaim",
Name: pvc.Name,
Namespace: pvc.Namespace,
Status: string(pvc.Status.Phase),
Age: age(pvc.CreationTimestamp.Time),
}
if pvc.Spec.StorageClassName != nil {
s.StorageClass = *pvc.Spec.StorageClassName
}
if cap, ok := pvc.Status.Capacity[corev1.ResourceStorage]; ok {
s.Capacity = cap.String()
}
for _, m := range pvc.Spec.AccessModes {
s.AccessModes = append(s.AccessModes, string(m))
}
return s
}
func summarizeReplicaSet(rs *appsv1.ReplicaSet) *ResourceSummary {
s := &ResourceSummary{
Kind: "ReplicaSet",
Name: rs.Name,
Namespace: rs.Namespace,
Ready: fmt.Sprintf("%d/%d", rs.Status.ReadyReplicas, rs.Status.Replicas),
Age: age(rs.CreationTimestamp.Time),
}
if len(rs.Spec.Template.Spec.Containers) > 0 {
s.Image = rs.Spec.Template.Spec.Containers[0].Image
}
if len(rs.OwnerReferences) > 0 {
s.Owner = fmt.Sprintf("%s/%s", rs.OwnerReferences[0].Kind, rs.OwnerReferences[0].Name)
}
return s
}
func summarizeNamespace(ns *corev1.Namespace) *ResourceSummary {
return &ResourceSummary{
Kind: "Namespace",
Name: ns.Name,
Status: string(ns.Status.Phase),
Age: age(ns.CreationTimestamp.Time),
}
}
// getPodIssue extracts the primary issue from a pod's status.
func getPodIssue(pod *corev1.Pod) string {
// Check container statuses for waiting reasons
for _, cs := range pod.Status.ContainerStatuses {
if cs.State.Waiting != nil && cs.State.Waiting.Reason != "" {
return cs.State.Waiting.Reason
}
if cs.State.Terminated != nil && cs.State.Terminated.Reason != "" && cs.State.Terminated.Reason != "Completed" {
return cs.State.Terminated.Reason
}
if cs.LastTerminationState.Terminated != nil && cs.LastTerminationState.Terminated.Reason != "" && cs.LastTerminationState.Terminated.Reason != "Completed" {
return cs.LastTerminationState.Terminated.Reason
}
}
// Check init container statuses
for _, cs := range pod.Status.InitContainerStatuses {
if cs.State.Waiting != nil && cs.State.Waiting.Reason != "" {
return cs.State.Waiting.Reason
}
if cs.State.Terminated != nil && cs.State.Terminated.Reason != "" && cs.State.Terminated.Reason != "Completed" {
return cs.State.Terminated.Reason
}
}
return ""
}
// age formats a duration since the given time as a human-readable string.
func age(created time.Time) string {
if created.IsZero() {
return ""
}
d := time.Since(created)
return formatDuration(d)
}
func formatDuration(d time.Duration) string {
switch {
case d < time.Minute:
return fmt.Sprintf("%ds", int(d.Seconds()))
case d < time.Hour:
return fmt.Sprintf("%dm", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%dh", int(d.Hours()))
default:
return fmt.Sprintf("%dd", int(d.Hours()/24))
}
}