-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatch-node-cpu.py
More file actions
executable file
·1979 lines (1819 loc) · 91.8 KB
/
watch-node-cpu.py
File metadata and controls
executable file
·1979 lines (1819 loc) · 91.8 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
#!/usr/bin/env python3
"""
Watch Kubernetes node CPU usage with line graphs.
Similar to htop but for your k8s cluster nodes.
"""
import subprocess
import sys
import time
import select
import termios
import tty
import os
from collections import defaultdict
from datetime import datetime
from typing import Dict, List, Tuple
import json
from rich.console import Console
from rich.table import Table
from rich.live import Live
from rich.layout import Layout
from rich.panel import Panel
from rich.text import Text
import sparklines
class NodeCPUWatcher:
def __init__(self, history_points: int = 60):
self.console = Console()
self.history_points = history_points
self.cpu_history: Dict[str, List[float]] = defaultdict(list)
self.timestamp_history: List[str] = []
self.update_count = 0
self.last_error: str = ""
# cache for pods
self.pod_metrics: List[
Tuple[str, float, str, str, str, str, float]
] = [] # (pod, cpu_cores, namespace, node, status, last_restart, mem_mib)
# selection state
self.selected_node_index: int = 0
self.nodes_for_selection: List[str] = ["all"]
# terminal state
self._orig_term_attrs = None
# key handling - simple and direct
# last render signatures to avoid unnecessary updates
self._last_nodes_sig = None
self._last_pods_sig = None
self._last_selected_node = None
self._last_controls_sig = None
# cached filtered/sorted pods to avoid re-sorting on every frame
self._cached_filtered_pods: List[
Tuple[str, float, str, str, str, str, float]
] = []
# node metadata
self.node_status: Dict[str, str] = {}
self.node_roles: Dict[str, str] = {}
# sort mode for pods table
self.sort_modes: List[str] = [
"CPU",
"Memory",
"Status",
"Namespace",
"Restarts",
]
self.selected_sort_index: int = 0
# focus and selection
self.focused_panel: str = "nodes" # 'nodes' or 'pods'
self.selected_pod_index: int = 0
self.pod_scroll_offset: int = 0 # For windowing/scrolling pod list
self.pod_window_size: int = (
20 # Number of pods to show at once (dynamically updated)
)
# text filter for pods
self.pod_filter_text: str = ""
self.show_filter_input: bool = False
# pod action modal
self.show_pod_modal: bool = False
self.selected_pod_for_action: Tuple[str, str, str] = (
"",
"",
"",
) # (pod_name, namespace, node)
self.pod_action_options: List[str] = [] # Dynamically built based on pod type
self.selected_action_index: int = 0
# vcluster detection
self.is_vcluster: bool = self._detect_vcluster()
self.vcluster_warning_shown: bool = False
def _detect_vcluster(self) -> bool:
"""
Detect if we're running against a vcluster context.
Returns True if the current context appears to be a vcluster.
"""
try:
result = subprocess.run(
["kubectl", "config", "current-context"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
context = result.stdout.strip()
# Check if context name contains 'vcluster'
return "vcluster" in context.lower()
except Exception:
pass
return False
def _estimate_panel_height_for_table(self, num_rows: int) -> int:
"""
Estimate the height of a Panel(Table(...), padding=(1,2)).
Overhead accounts for table title, borders, header, separator, panel borders and padding.
"""
# Overhead components (approx):
# table title (1) + top border (1) + header (1) + header separator (1) + bottom border (1)
# panel top/bottom borders (2) + panel padding top/bottom (2)
overhead = 9
return max(5, overhead + num_rows)
def _calculate_pod_window_size(self, nodes_panel_height: int) -> int:
"""
Calculate how many pods can fit in the available terminal space.
Returns the number of pod rows that will fit in the pods panel.
"""
try:
terminal_height = self.console.size.height
# Account for: title (3) + nodes panel + controls (3 or 4 for vcluster) + pod panel overhead (9)
controls_height = 4 if self.is_vcluster else 3
used_height = 3 + nodes_panel_height + controls_height + 9
available_for_pods = terminal_height - used_height
# Ensure at least 5 rows, cap at reasonable maximum
return max(5, min(available_for_pods, 100))
except Exception:
# Fallback to a reasonable default
return 20
def _enable_raw_mode(self):
try:
fd = sys.stdin.fileno()
self._orig_term_attrs = termios.tcgetattr(fd)
# Use cbreak mode - allows signal processing but immediate char input
tty.setcbreak(fd)
except Exception:
self._orig_term_attrs = None
def _disable_raw_mode(self):
try:
if self._orig_term_attrs is not None:
termios.tcsetattr(
sys.stdin.fileno(), termios.TCSADRAIN, self._orig_term_attrs
)
except Exception:
pass
def _read_key(self) -> str:
"""Simple non-blocking key read."""
try:
fd = sys.stdin.fileno()
# Check if input available with very short timeout
rlist, _, _ = select.select([fd], [], [], 0)
if not rlist:
return ""
# Read one character directly from file descriptor
import os
ch1 = os.read(fd, 1).decode("utf-8", errors="ignore")
if ch1 == "q":
return "q"
if ch1 in ("k", "K"):
return "UP"
if ch1 in ("j", "J"):
return "DOWN"
if ch1 in ("h", "H"):
return "LEFT"
if ch1 in ("l", "L"):
return "RIGHT"
if ch1 in ("\r", "\n"):
return "ENTER"
if ch1 == "\x7f" or ch1 == "\x08":
return ch1 # Backspace
if ch1 != "\x1b":
# Return the character itself (for filter input, etc.)
return ch1
# Read escape sequence quickly
import os
seq = ch1
for _ in range(2):
if select.select([fd], [], [], 0.01)[0]:
seq += os.read(fd, 1).decode("utf-8", errors="ignore")
else:
break
if seq == "\x1b[A" or seq == "\x1bOA":
return "UP"
elif seq == "\x1b[B" or seq == "\x1bOB":
return "DOWN"
elif seq == "\x1b[D" or seq == "\x1bOD":
return "LEFT"
elif seq == "\x1b[C" or seq == "\x1bOC":
return "RIGHT"
elif seq == "\x1b":
return "ESC"
return ""
except Exception:
return ""
def _parse_memory_value_to_mib(self, mem_raw: str) -> float:
"""Parse a Kubernetes memory value like '5947Mi', '8Gi', '1024Ki' to MiB float."""
try:
mem_raw = mem_raw.strip()
units = ["Ki", "Mi", "Gi", "Ti", "Pi", "Ei"]
for unit in units:
if mem_raw.endswith(unit):
value = float(mem_raw[: -len(unit)])
factor = {
"Ki": 1.0 / 1024.0,
"Mi": 1.0,
"Gi": 1024.0,
"Ti": 1024.0 * 1024.0,
"Pi": 1024.0 * 1024.0 * 1024.0,
"Ei": 1024.0 * 1024.0 * 1024.0 * 1024.0,
}[unit]
return value * factor
# Fallback: plain bytes? try interpret as Mi directly
return float(mem_raw)
except Exception:
return 0.0
def _parse_restart_to_seconds(self, restart_str: str) -> float:
"""Convert restart time string like '5m', '2h', '3d' to seconds. Returns infinity for 'never'."""
if restart_str == "never" or restart_str == "?":
return float("inf")
try:
if restart_str.endswith("s"):
return float(restart_str[:-1])
elif restart_str.endswith("m"):
return float(restart_str[:-1]) * 60
elif restart_str.endswith("h"):
return float(restart_str[:-1]) * 3600
elif restart_str.endswith("d"):
return float(restart_str[:-1]) * 86400
return float("inf")
except Exception:
return float("inf")
def _create_cpu_bar(self, cpu_pct: float, width: int = 20) -> str:
"""
Create htop-style visual bar from CPU percentage.
Returns a colored bar string using Unicode block characters.
"""
if cpu_pct < 0:
cpu_pct = 0.0
elif cpu_pct > 100:
cpu_pct = 100.0
# Calculate filled blocks
filled = (cpu_pct / 100.0) * width
filled_blocks = int(filled)
partial = filled - filled_blocks
# Determine partial block character
if partial < 0.25:
partial_char = ""
elif partial < 0.5:
partial_char = "░"
elif partial < 0.75:
partial_char = "▒"
else:
partial_char = "▓"
# Build the bar
bar = "█" * filled_blocks
if filled_blocks < width and partial_char:
bar += partial_char
filled_blocks += 1
bar += "░" * (width - filled_blocks)
# Apply color based on CPU percentage
if cpu_pct > 80:
color = "red"
elif cpu_pct > 50:
color = "yellow"
else:
color = "green"
return f"[{color}]{bar}[/{color}]"
def get_node_metrics(self) -> Dict[str, Tuple[float, float, float, float]]:
"""
Fetch node CPU usage using kubectl top.
Returns dict of {node_name: (cpu_cores, cpu_percentage)}
"""
try:
result = subprocess.run(
["kubectl", "top", "nodes", "--no-headers"],
capture_output=True,
text=True,
timeout=10,
)
metrics: Dict[str, Tuple[float, float, float, float]] = {}
self.last_error = ""
if result.returncode != 0:
self.last_error = result.stderr.strip() or "kubectl top nodes failed"
return {}
stdout = result.stdout.strip()
if not stdout:
self.last_error = "No output from 'kubectl top nodes'"
return {}
if "No resources found" in stdout:
self.last_error = stdout
return {}
for line_text in stdout.split("\n"):
if not line_text.strip():
continue
parts = line_text.split()
# Expect at least: NAME CPU(cores) CPU% [...]
if len(parts) < 3:
self.last_error = (
f"Unexpected 'kubectl top nodes' format: {line_text}"
)
continue
node_name = parts[0]
tokens = parts[1:]
# Identify CPU%, MEM% positions
percent_indices = [
i for i, tok in enumerate(tokens) if tok.endswith("%")
]
cpu_pct_raw = tokens[percent_indices[0]] if percent_indices else None
mem_pct_raw = (
tokens[percent_indices[1]] if len(percent_indices) > 1 else None
)
if not cpu_pct_raw:
self.last_error = f"Could not locate CPU% column in: {line_text}"
continue
# Identify memory bytes token
mem_units = ("Ki", "Mi", "Gi", "Ti", "Pi", "Ei")
mem_bytes_idx = next(
(i for i, tok in enumerate(tokens) if tok.endswith(mem_units)), None
)
# Identify CPU cores token: first non-percent, non-mem token
cpu_cores_idx = next(
(
i
for i, tok in enumerate(tokens)
if not tok.endswith("%") and not tok.endswith(mem_units)
),
None,
)
if cpu_cores_idx is None:
self.last_error = f"Could not locate CPU cores in: {line_text}"
continue
cpu_str_raw = tokens[cpu_cores_idx]
try:
if cpu_str_raw.endswith("m"):
cpu_cores = float(cpu_str_raw[:-1]) / 1000.0
elif cpu_str_raw.endswith("n"):
cpu_cores = float(cpu_str_raw[:-1]) / 1_000_000_000.0
else:
cpu_cores = float(cpu_str_raw)
except ValueError:
self.last_error = f"Could not parse CPU cores: {cpu_str_raw}"
continue
try:
cpu_pct = float(cpu_pct_raw.rstrip("%"))
except ValueError:
self.last_error = f"Could not parse CPU%: {cpu_pct_raw}"
continue
# Memory values
mem_mib = 0.0
mem_pct = 0.0
if mem_bytes_idx is not None:
mem_mib = self._parse_memory_value_to_mib(tokens[mem_bytes_idx])
if mem_pct_raw:
try:
mem_pct = float(mem_pct_raw.rstrip("%"))
except ValueError:
mem_pct = 0.0
metrics[node_name] = (cpu_cores, cpu_pct, mem_mib, mem_pct)
if not metrics and not self.last_error:
self.last_error = (
"No metrics parsed; ensure metrics-server is installed."
)
return metrics
except subprocess.TimeoutExpired:
self.last_error = "kubectl command timed out"
return {}
except Exception as e:
self.last_error = f"Error fetching metrics: {e}"
return {}
def get_node_metadata(self) -> None:
"""Populate node status and roles from kubectl get nodes -o json."""
try:
proc = subprocess.run(
["kubectl", "get", "nodes", "-o", "json"],
capture_output=True,
text=True,
timeout=10,
)
if proc.returncode != 0:
return
data = json.loads(proc.stdout)
self.node_status.clear()
self.node_roles.clear()
for item in data.get("items", []):
meta = item.get("metadata", {})
status = item.get("status", {})
node_name = meta.get("name", "")
# Status: Ready/NotReady
conds = status.get("conditions", []) or []
ready = next((c for c in conds if c.get("type") == "Ready"), None)
node_state = (
"Ready" if ready and ready.get("status") == "True" else "NotReady"
)
self.node_status[node_name] = node_state
# Roles from labels like node-role.kubernetes.io/control-plane=""
labels = meta.get("labels", {}) or {}
roles = []
for k, v in labels.items():
if k.startswith("node-role.kubernetes.io/"):
roles.append(k.split("/", 1)[1])
if not roles and labels.get("kubernetes.io/role"):
roles.append(labels.get("kubernetes.io/role"))
self.node_roles[node_name] = ",".join(sorted(set(roles))) or "worker"
except Exception:
pass
def get_pod_metrics(self) -> List[Tuple[str, float, str, str, str, str, float]]:
"""
Fetch pod CPU and node mapping.
Returns list of (pod_name, cpu_cores, namespace, node_name, status, last_restart, mem_mib)
"""
try:
# Get pod CPU from `kubectl top pods -A --containers=false --no-headers`
pods_top = subprocess.run(
[
"kubectl",
"top",
"pods",
"-A",
"--no-headers",
"--containers=false",
],
capture_output=True,
text=True,
timeout=10,
)
# Build map of (namespace, pod) -> (cpu cores, mem_mib) from top output
metrics_by_ns_pod: Dict[Tuple[str, str], Tuple[float, float]] = {}
# If metrics are available, parse them
if pods_top.returncode == 0 and pods_top.stdout.strip():
for line_text in pods_top.stdout.strip().split("\n"):
if not line_text.strip():
continue
# Format: NAMESPACE POD CPU(M) MEMORY(Mi)
parts = line_text.split()
if len(parts) < 4:
continue
ns, pod, cpu_raw, mem_raw = parts[0], parts[1], parts[2], parts[3]
try:
if cpu_raw.endswith("m"):
cpu_cores = float(cpu_raw[:-1]) / 1000.0
else:
cpu_cores = float(cpu_raw)
mem_mib = self._parse_memory_value_to_mib(mem_raw)
except ValueError:
continue
metrics_by_ns_pod[(ns, pod)] = (cpu_cores, mem_mib)
# If metrics not available (e.g., in vcluster), continue anyway to show pods without metrics
# Get pod -> node mapping
pods_nodes = subprocess.run(
[
"kubectl",
"get",
"pods",
"-A",
"-o",
"json",
],
capture_output=True,
text=True,
timeout=15,
)
if pods_nodes.returncode != 0:
self.last_error = pods_nodes.stderr.strip() or "kubectl get pods failed"
return []
result: List[Tuple[str, float, str, str, str, str, float]] = []
try:
data = json.loads(pods_nodes.stdout)
except Exception as e:
self.last_error = f"Failed to parse pods JSON: {e}"
return []
items = data.get("items", [])
for item in items:
meta = item.get("metadata", {})
status_obj = item.get("status", {})
spec_obj = item.get("spec", {})
ns = meta.get("namespace", "")
pod = meta.get("name", "")
node = spec_obj.get("nodeName", "")
phase = status_obj.get("phase", "")
# Calculate last restart time
containers = status_obj.get("containerStatuses", []) or []
last_restart = "never"
waiting_reason = None
most_recent_restart_time = None
for cs in containers:
state = cs.get("state", {}) or {}
if state.get("waiting") and state["waiting"].get("reason"):
waiting_reason = state["waiting"]["reason"]
# Check lastState for terminated info (indicates a restart)
last_state = cs.get("lastState", {}) or {}
if last_state.get("terminated"):
finished_at = last_state["terminated"].get("finishedAt")
if finished_at:
try:
from datetime import datetime, timezone
restart_time = datetime.fromisoformat(
finished_at.replace("Z", "+00:00")
)
if (
most_recent_restart_time is None
or restart_time > most_recent_restart_time
):
most_recent_restart_time = restart_time
except Exception:
pass
# Format last restart time
if most_recent_restart_time:
try:
from datetime import datetime, timezone
seconds_since_restart = (
datetime.now(timezone.utc) - most_recent_restart_time
).total_seconds()
if seconds_since_restart < 60:
last_restart = f"{int(seconds_since_restart)}s"
elif seconds_since_restart < 3600:
last_restart = f"{int(seconds_since_restart / 60)}m"
elif seconds_since_restart < 86400:
last_restart = f"{int(seconds_since_restart / 3600)}h"
else:
last_restart = f"{int(seconds_since_restart / 86400)}d"
except Exception:
last_restart = "?"
# Determine status
if waiting_reason:
status = waiting_reason
elif phase == "Running":
status = "Running"
elif phase:
status = phase
else:
status = "Unknown"
cores, mem_mib = metrics_by_ns_pod.get((ns, pod), (0.0, 0.0))
result.append((pod, cores, ns, node, status, last_restart, mem_mib))
# Sort by CPU cores descending
result.sort(key=lambda x: x[1], reverse=True)
return result
except subprocess.TimeoutExpired:
self.last_error = "kubectl command timed out"
return []
except Exception as e:
self.last_error = f"Error fetching pod metrics: {e}"
return []
def update_history(self, metrics: Dict[str, Tuple[float, float, float, float]]):
"""Update historical data with new metrics."""
# Record timestamp
timestamp = datetime.now().strftime("%H:%M:%S")
self.timestamp_history.append(timestamp)
if len(self.timestamp_history) > self.history_points:
self.timestamp_history.pop(0)
# Aggregate 'all' CPU percent as average of node percentages
if metrics:
avg_pct = sum(v[1] for v in metrics.values()) / max(1, len(metrics))
self.cpu_history["all"].append(avg_pct)
if len(self.cpu_history["all"]) > self.history_points:
self.cpu_history["all"].pop(0)
# Update CPU history for each node
for node_name, (cpu_cores, cpu_pct, mem_mib, mem_pct) in metrics.items():
self.cpu_history[node_name].append(cpu_pct)
if len(self.cpu_history[node_name]) > self.history_points:
self.cpu_history[node_name].pop(0)
# Remove old nodes that are no longer in metrics
for node_name in list(self.cpu_history.keys()):
if node_name not in metrics and node_name != "all":
del self.cpu_history[node_name]
def format_table(
self, metrics: Dict[str, Tuple[float, float, float, float]], selected_node: str
) -> Table:
"""Create a formatted table with node metrics and sparklines."""
title = "Kubernetes Node CPU Usage"
if self.is_vcluster:
title += " [dim yellow](vcluster - limited metrics)[/dim yellow]"
table = Table(
title=title,
show_header=True,
header_style="bold cyan",
expand=True,
)
table.add_column("Node", style="cyan", no_wrap=True)
table.add_column("Roles", style="cyan", width=15)
table.add_column("Status", style="cyan", width=10)
table.add_column("CPU (cores)", justify="right", style="magenta", width=10)
table.add_column("CPU %", justify="right", style="yellow", width=7)
table.add_column("CPU", min_width=20)
table.add_column("Mem (Mi)", justify="right", style="green", width=10)
table.add_column("Mem %", justify="right", style="green", width=7)
# First add aggregate 'all' row
total_cores = sum(v[0] for v in metrics.values()) if metrics else 0.0
total_mem_mib = sum(v[2] for v in metrics.values()) if metrics else 0.0
avg_pct = (
sum(v[1] for v in metrics.values()) / max(1, len(metrics))
if metrics
else 0.0
)
avg_mem_pct = (
sum(v[3] for v in metrics.values()) / max(1, len(metrics))
if metrics
else 0.0
)
# In vcluster with zero metrics, show N/A for all row
if self.is_vcluster and total_cores == 0.0 and avg_pct == 0.0:
cores_str = "N/A"
pct_str = "N/A"
mem_str = "N/A"
mem_pct_str = "N/A"
cpu_bar = "N/A"
else:
cores_str = f"{total_cores:.2f}"
pct_str = f"{avg_pct:.1f}"
mem_str = f"{total_mem_mib:.0f}"
mem_pct_str = f"{avg_mem_pct:.1f}"
cpu_bar = self._create_cpu_bar(avg_pct)
all_row_style = "reverse bold" if selected_node == "all" else None
table.add_row(
"all",
"-",
"-",
cores_str,
pct_str,
cpu_bar,
mem_str,
mem_pct_str,
style=all_row_style,
)
# Sort by node name for consistent ordering
sorted_nodes = sorted(metrics.keys())
for node_name in sorted_nodes:
cpu_cores, cpu_pct, mem_mib, mem_pct = metrics[node_name]
# In vcluster with zero metrics, show as unavailable
if self.is_vcluster and cpu_cores == 0.0 and cpu_pct == 0.0:
cpu_cores_str = "N/A"
cpu_pct_str = "N/A"
mem_mib_str = "N/A"
mem_pct_str = "N/A"
cpu_bar = "N/A"
else:
# Determine color based on CPU percentage
if cpu_pct > 80:
color = "red"
elif cpu_pct > 50:
color = "yellow"
else:
color = "green"
cpu_cores_str = f"{cpu_cores:.2f}"
cpu_pct_str = f"[{color}]{cpu_pct:.1f}[/{color}]"
mem_mib_str = f"{mem_mib:.0f}"
mem_pct_str = f"{mem_pct:.1f}"
cpu_bar = self._create_cpu_bar(cpu_pct)
row_style = "reverse bold" if selected_node == node_name else None
table.add_row(
node_name,
self.node_roles.get(node_name, ""),
self.node_status.get(node_name, ""),
cpu_cores_str,
cpu_pct_str,
cpu_bar,
mem_mib_str,
mem_pct_str,
style=row_style,
)
return table
def format_aggregate_trend(self) -> Panel:
"""
Create a btop-style trend display for cluster aggregate CPU usage.
Shows sparkline graph of the "all" aggregate history.
"""
all_history = self.cpu_history.get("all", [])
if all_history and len(all_history) > 1:
try:
spark = sparklines.sparklines(all_history, minimum=0, maximum=100)[0]
except Exception:
spark = "─"
else:
spark = "─"
# Calculate current average CPU percentage and stats
if all_history:
current_pct = all_history[-1] if all_history else 0.0
if len(all_history) > 1:
min_pct = min(all_history)
max_pct = max(all_history)
else:
min_pct = max_pct = current_pct
else:
current_pct = min_pct = max_pct = 0.0
# Format the trend display with extra spacing for better visibility
trend_text = Text()
trend_text.append("Cluster CPU: ", style="bold cyan")
trend_text.append(f"{current_pct:.1f}%", style="yellow")
if len(all_history) > 1:
trend_text.append(" (", style="dim")
trend_text.append(f"min: {min_pct:.1f}%", style="dim")
trend_text.append(", ", style="dim")
trend_text.append(f"max: {max_pct:.1f}%", style="dim")
trend_text.append(")", style="dim")
trend_text.append("\n", style="dim")
trend_text.append(spark, style="green")
return Panel(
trend_text, title="Cluster Trend", border_style="cyan", padding=(1, 1)
)
def format_pods_table(
self,
rows: List[Tuple[str, float, str, str, str, str, float]],
selected_node: str,
hottest_node: str,
) -> Table:
total_pods = len(rows)
# Apply windowing when focused on pods
if self.focused_panel == "pods" and total_pods > self.pod_window_size:
# Ensure selected pod is visible in window
if self.selected_pod_index < self.pod_scroll_offset:
self.pod_scroll_offset = self.selected_pod_index
elif (
self.selected_pod_index >= self.pod_scroll_offset + self.pod_window_size
):
self.pod_scroll_offset = (
self.selected_pod_index - self.pod_window_size + 1
)
# Window the rows
visible_rows = rows[
self.pod_scroll_offset : self.pod_scroll_offset + self.pod_window_size
]
scroll_info = f" [{self.pod_scroll_offset + 1}-{min(self.pod_scroll_offset + self.pod_window_size, total_pods)} of {total_pods}]"
else:
visible_rows = rows
scroll_info = ""
# Count total running pods across all nodes
total_running_pods = len(self.pod_metrics)
title_filter = (
f" • node: {selected_node}"
if selected_node and selected_node != "all"
else ""
)
# Text filter indicator
text_filter_indicator = ""
if self.pod_filter_text:
text_filter_indicator = f" • search: '{self.pod_filter_text}'"
elif self.show_filter_input:
text_filter_indicator = " • search: _"
frozen_indicator = " [PAUSED]" if self.focused_panel == "pods" else ""
vcluster_indicator = (
" [dim yellow](limited metrics)[/dim yellow]" if self.is_vcluster else ""
)
# Show filtered count vs total if filtered
if selected_node and selected_node != "all":
pod_counter = f" • {total_pods}/{total_running_pods} pods"
else:
pod_counter = f" • {total_running_pods} pods"
table = Table(
title=f"Top Pods by CPU (cores){title_filter}{text_filter_indicator}{pod_counter}{scroll_info}{frozen_indicator}{vcluster_indicator}",
show_header=True,
header_style="bold cyan",
expand=True,
)
table.add_column("Namespace", style="cyan", no_wrap=True)
table.add_column("Pod", style="cyan", no_wrap=True)
table.add_column("CPU", justify="right", style="magenta", width=7)
table.add_column("Memory", justify="right", style="green", width=9)
table.add_column("Status", style="yellow", width=12)
table.add_column("Restarts", justify="right", style="blue", width=8)
table.add_column("Node", style="yellow", no_wrap=True)
for index, (pod, cores, ns, node, status, last_restart, mem_mib) in enumerate(
visible_rows
):
# Calculate the actual index in the full list
actual_index = index + (
self.pod_scroll_offset
if self.focused_panel == "pods" and total_pods > self.pod_window_size
else 0
)
row_style = "red" if node == hottest_node else None
if self.focused_panel == "pods" and actual_index == self.selected_pod_index:
row_style = "reverse bold"
# Color last restart based on recency
restart_style = "dim"
if last_restart != "never":
if last_restart.endswith("s") or (
last_restart.endswith("m") and int(last_restart[:-1]) < 5
):
restart_style = "bold red"
elif last_restart.endswith("m") or (
last_restart.endswith("h") and int(last_restart[:-1]) < 1
):
restart_style = "yellow"
# Show N/A for unavailable metrics (vcluster)
if self.is_vcluster and cores == 0.0 and mem_mib == 0.0:
cpu_str = "N/A"
mem_str = "N/A"
else:
cpu_str = f"{cores:.3f}"
mem_str = f"{mem_mib:.0f}Mi"
table.add_row(
ns,
pod,
cpu_str,
mem_str,
status,
f"[{restart_style}]{last_restart}[/]",
node,
style=row_style,
)
return table
def _is_vcluster_pod(self, pod_name: str, namespace: str) -> bool:
"""Check if a pod is a vcluster pod by examining its labels."""
try:
result = subprocess.run(
["kubectl", "get", "pod", pod_name, "-n", namespace, "-o", "json"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
data = json.loads(result.stdout)
labels = data.get("metadata", {}).get("labels", {})
# Check for common vcluster labels
if (
labels.get("app") == "vcluster"
or labels.get("app.kubernetes.io/name") == "vcluster"
or "vcluster" in namespace.lower()
):
return True
except Exception:
pass
return False
def _get_vcluster_name(self, pod_name: str, namespace: str) -> str:
"""Extract the vcluster name from pod metadata."""
try:
result = subprocess.run(
["kubectl", "get", "pod", pod_name, "-n", namespace, "-o", "json"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
data = json.loads(result.stdout)
labels = data.get("metadata", {}).get("labels", {})
# Try to get vcluster name from labels
vcluster_name = (
labels.get("release")
or labels.get("app.kubernetes.io/instance")
or labels.get("vcluster.loft.sh/name")
)
if vcluster_name:
return vcluster_name
# Fallback: try to extract from pod name (remove statefulset suffix like -0, -1, etc.)
if pod_name.endswith(tuple(f"-{i}" for i in range(10))):
return pod_name.rsplit("-", 1)[0]
except Exception:
pass
# Final fallback: use namespace name as vcluster name
return namespace
def create_pod_action_modal(self) -> Panel:
"""Create a modal dialog for pod actions."""
from rich.console import Group
pod_name, namespace, node = self.selected_pod_for_action
# Check if this is a vcluster pod
is_vcluster_pod = self._is_vcluster_pod(pod_name, namespace)
# Create pod info text
info_text = Text()
info_text.append(f"Node: {node}\n", style="dim")
if is_vcluster_pod:
info_text.append("Type: vCluster\n", style="cyan")
info_text.append("\n")
# Build action options based on pod type
actions = ["Describe", "Logs", "List Namespace Resources"]
if is_vcluster_pod:
actions.append("Connect to vCluster")
actions.extend(["Delete", "Cancel"])
# Store actions for navigation
self.pod_action_options = actions
# Create the action menu
menu_table = Table(show_header=False, box=None, padding=(0, 0))
menu_table.add_column("Action", style="bold")
for index, action in enumerate(actions):
if index == self.selected_action_index:
menu_table.add_row(f"▶ {action}", style="reverse bold cyan")
else:
menu_table.add_row(f" {action}")
# Create panel with pod info and menu
title = f"Pod Actions: {namespace}/{pod_name}"
return Panel(
Group(info_text, menu_table),
title=title,
border_style="bold yellow",
padding=(1, 2),
)
def run(self, refresh_interval: float = 3.3):
"""Main loop - continuously update and display metrics."""
self.console.clear()
try:
# Build a persistent layout once to reduce blinking
layout = Layout()
with Live(
layout, refresh_per_second=1, screen=False, auto_refresh=False
) as live:
self._enable_raw_mode()