-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.rs
More file actions
2484 lines (2294 loc) · 86 KB
/
Copy pathapp.rs
File metadata and controls
2484 lines (2294 loc) · 86 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
use super::theme::Theme;
use crate::net::{self, IfStats, NetRate};
use crate::stat::{self, PortStat};
use crate::trace::{PortMetrics, Recorder};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use std::collections::HashMap;
/// Which hardware class a `PortThroughput` row belongs to; one TUI tab each.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DeviceClass {
Rdma,
Xgmi,
Nvlink,
}
impl DeviceClass {
/// Display name used by the tab bar, header, and table titles.
pub fn label(&self) -> &'static str {
match self {
DeviceClass::Rdma => "RDMA",
DeviceClass::Xgmi => "XGMI",
DeviceClass::Nvlink => "NVLink",
}
}
}
/// Per-port computed throughput (delta / interval).
#[derive(Clone, Debug)]
pub struct PortThroughput {
pub dev_name: String,
pub port: u32,
/// Port line rate in Gbps, used to scale the throughput bar.
pub link_gbps: Option<f64>,
pub tx_gbps: f64,
pub rx_gbps: f64,
pub tx_pkts_per_sec: f64,
pub rx_pkts_per_sec: f64,
pub rx_drops_per_sec: f64,
pub counter_rates: Vec<CounterRate>,
/// Optional override for the Port column text. Used by NVLink rows.
pub port_label: Option<String>,
/// NVLink metadata attached to this row.
pub nvlink: Option<NvLinkThroughputMeta>,
/// XGMI metadata attached to this row.
pub xgmi: Option<XgmiThroughputMeta>,
pub class: DeviceClass,
}
/// Per-GPU XGMI metadata. Mirrors `NvLinkThroughputMeta`; `links[]`
/// tx/rx are rewritten as per-second byte rates for the detail pane.
#[derive(Clone, Debug)]
pub struct XgmiThroughputMeta {
/// Not rendered yet (rows already show `amdgpu<index>` via `dev_name`);
/// kept so future panels (e.g. topology graph) can reference it.
#[allow(dead_code)]
pub gpu_index: u32,
/// Marketing name (e.g. "AMD Instinct MI325X"); Name column on the tab.
pub gpu_name: String,
pub active_links: u32,
pub links: Vec<crate::xgmi::XgmiLinkSnapshot>,
/// Live GPU health (util/vram/temp/power/clock) for the gauge strip
/// and detail pane.
pub metrics: Option<crate::gpu::GpuMetrics>,
}
/// Per-GPU NVLink metadata. The TUI uses this to show per-link details
/// and error counters in the detail pane.
#[derive(Clone, Debug)]
pub struct NvLinkThroughputMeta {
/// GPU index reported by NVML. Not directly rendered by the TUI today
/// (the row already shows `nvidia<index>` via `PortThroughput::dev_name`)
/// but kept so future panels (e.g. topology graph) can reference it.
#[allow(dead_code)]
pub gpu_index: u32,
/// Marketing name of the GPU (e.g. "H100"); Name column on the tab.
pub gpu_name: String,
pub active_links: u32,
pub links: Vec<crate::nvlink::LinkSnapshot>,
/// Live GPU health (util/vram/temp/power/clock) for the gauge strip
/// and detail pane.
pub metrics: Option<crate::gpu::GpuMetrics>,
}
#[derive(Clone, Debug)]
pub struct CounterRate {
pub name: String,
pub value: u64,
pub delta: u64,
pub rate: f64,
pub is_bytes: bool,
}
/// Columns available for the main throughput table.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TableColumn {
Device,
Port,
TxBar,
TxGbps,
RxBar,
RxGbps,
TxPps,
RxPps,
Drops,
/// A raw hw counter rate column, keyed by counter name.
Counter(String),
}
impl TableColumn {
pub fn label(&self) -> String {
match self {
Self::Device => "Device".into(),
Self::Port => "Port".into(),
Self::TxBar => "TX ▏".into(),
Self::TxGbps => "TX Gbps".into(),
Self::RxBar => "RX ▏".into(),
Self::RxGbps => "RX Gbps".into(),
Self::TxPps => "TX pps".into(),
Self::RxPps => "RX pps".into(),
Self::Drops => "Drops/s".into(),
Self::Counter(name) => name.clone(),
}
}
/// Table-header text: the bar column names the direction ("TX"/"RX")
/// and the value column next to it is just "Gbps" — no duplication.
pub fn header_label(&self) -> String {
match self {
Self::TxBar => "TX".into(),
Self::RxBar => "RX".into(),
Self::TxGbps | Self::RxGbps => "Gbps".into(),
_ => self.label(),
}
}
pub fn width(&self) -> u16 {
match self {
Self::Device => 16,
Self::Port => 6,
Self::TxBar | Self::RxBar => BAR_WIDTH as u16,
Self::TxGbps | Self::RxGbps => 9,
Self::TxPps | Self::RxPps => 10,
Self::Drops => 9,
Self::Counter(name) => (name.len() as u16 + 2).max(12),
}
}
}
pub const BAR_WIDTH: usize = 12;
/// Stats refresh interval bounds (seconds). Sampling runs on a background
/// thread, so the floor only bounds sampler load; it must stay above the
/// 0.1s duplicate-snapshot guard in `apply_snapshot`.
pub const REFRESH_DEFAULT_SECS: f64 = 1.0;
const REFRESH_MIN_SECS: f64 = 0.2;
const REFRESH_MAX_SECS: f64 = 10.0;
const REFRESH_STEP_SECS: f64 = 0.5;
/// All counter names that can be added as extra columns.
pub const EXTRA_COUNTERS: &[&str] = &[
"send_bytes",
"send_wrs",
"recv_bytes",
"recv_wrs",
"rdma_write_bytes",
"rdma_write_wrs",
"rdma_write_wr_err",
"rdma_write_recv_bytes",
"rdma_read_bytes",
"rdma_read_wrs",
"rdma_read_wr_err",
"rdma_read_resp_bytes",
"retrans_bytes",
"retrans_pkts",
"retrans_timeout_events",
"unresponsive_remote_events",
"impaired_remote_conn_events",
];
/// Returns the default set of visible columns.
pub fn default_columns() -> Vec<TableColumn> {
vec![
TableColumn::Device,
TableColumn::Port,
TableColumn::TxBar,
TableColumn::TxGbps,
TableColumn::RxBar,
TableColumn::RxGbps,
TableColumn::TxPps,
TableColumn::RxPps,
TableColumn::Drops,
]
}
/// Returns all possible columns (built-in + extra counters).
pub fn all_columns() -> Vec<TableColumn> {
let mut cols = default_columns();
for name in EXTRA_COUNTERS {
cols.push(TableColumn::Counter(name.to_string()));
}
cols
}
/// Rolling average calculator: stores recent PortThroughput samples per device
/// and computes the mean over a configurable window.
pub struct RollingAvgState {
/// Per-device key "dev_name/port" → ring buffer of samples
samples: HashMap<String, VecDeque<PortThroughput>>,
/// Window size in seconds (each sample ≈ 1s)
pub window_secs: usize,
}
pub const ROLLING_AVG_DEFAULT_WINDOW: usize = 5;
const ROLLING_AVG_MIN_WINDOW: usize = 1;
const ROLLING_AVG_MAX_WINDOW: usize = 300;
impl RollingAvgState {
pub fn new(window_secs: usize) -> Self {
Self {
samples: HashMap::new(),
window_secs,
}
}
/// Push a new set of throughput samples (called once per refresh).
/// Prunes stale device/port keys that no longer appear in `throughputs`.
pub fn push(&mut self, throughputs: &[PortThroughput]) {
let mut seen = std::collections::HashSet::new();
for t in throughputs {
let key = throughput_key(t);
seen.insert(key.clone());
let buf = self
.samples
.entry(key)
.or_insert_with(|| VecDeque::with_capacity(ROLLING_AVG_MAX_WINDOW + 1));
if buf.len() >= ROLLING_AVG_MAX_WINDOW {
buf.pop_front();
}
buf.push_back(t.clone());
}
self.samples.retain(|k, _| seen.contains(k));
}
/// Compute averaged throughput for all devices currently tracked.
pub fn averages(&self) -> Vec<PortThroughput> {
self.samples
.values()
.filter_map(|buf| Self::average_window(buf, self.window_secs))
.collect()
}
/// Compute the rolling average for a single device's sample buffer.
fn average_window(
buf: &VecDeque<PortThroughput>,
window_secs: usize,
) -> Option<PortThroughput> {
if buf.is_empty() {
return None;
}
let start = buf.len().saturating_sub(window_secs);
let window: Vec<_> = buf.iter().skip(start).collect();
let n = window.len() as f64;
// Copy metadata from the latest sample. For NVLink rows, the oldest
// sample's `port`/`port_label` may reflect a stale active-link count;
// using the latest keeps the averaged row's metadata fresh.
// `nvlink` is also metadata; preserving it lets `throughput_key`
// identify averaged NVLink rows by `dev_name` alone.
let latest = window.last().unwrap();
let mut avg = PortThroughput {
dev_name: latest.dev_name.clone(),
port: latest.port,
link_gbps: latest.link_gbps,
tx_gbps: window.iter().map(|s| s.tx_gbps).sum::<f64>() / n,
rx_gbps: window.iter().map(|s| s.rx_gbps).sum::<f64>() / n,
tx_pkts_per_sec: window.iter().map(|s| s.tx_pkts_per_sec).sum::<f64>() / n,
rx_pkts_per_sec: window.iter().map(|s| s.rx_pkts_per_sec).sum::<f64>() / n,
rx_drops_per_sec: window.iter().map(|s| s.rx_drops_per_sec).sum::<f64>() / n,
counter_rates: Vec::new(),
port_label: latest.port_label.clone(),
nvlink: latest.nvlink.clone(),
xgmi: latest.xgmi.clone(),
class: latest.class,
};
if let Some(template) = window.last() {
avg.counter_rates = template
.counter_rates
.iter()
.map(|cr| Self::average_counter_rate(cr, &window))
.collect();
}
Some(avg)
}
/// Compute the average of a single counter rate across a window of samples.
/// Only samples that contain the counter contribute; the divisor matches the
/// number of contributing samples so a counter that is briefly absent doesn't
/// pull the average toward zero.
fn average_counter_rate(cr: &CounterRate, window: &[&PortThroughput]) -> CounterRate {
let present: Vec<&CounterRate> = window
.iter()
.filter_map(|s| s.counter_rates.iter().find(|r| r.name == cr.name))
.collect();
let n = present.len();
if n == 0 {
return CounterRate {
name: cr.name.clone(),
value: cr.value,
delta: 0,
rate: 0.0,
is_bytes: cr.is_bytes,
};
}
let sum_rate: f64 = present.iter().map(|r| r.rate).sum();
let sum_delta: u64 = present.iter().map(|r| r.delta).sum();
let latest_value = present.last().map(|r| r.value).unwrap_or(cr.value);
CounterRate {
name: cr.name.clone(),
value: latest_value,
delta: sum_delta / n as u64,
rate: sum_rate / n as f64,
is_bytes: cr.is_bytes,
}
}
pub fn sample_count(&self) -> usize {
self.samples
.values()
.map(|b| b.len().min(self.window_secs))
.max()
.unwrap_or(0)
}
pub fn increase_window(&mut self) {
self.window_secs = (self.window_secs + 1).min(ROLLING_AVG_MAX_WINDOW);
}
pub fn decrease_window(&mut self) {
self.window_secs = self
.window_secs
.saturating_sub(1)
.max(ROLLING_AVG_MIN_WINDOW);
}
pub fn set_window(&mut self, secs: usize) {
self.window_secs = secs.clamp(ROLLING_AVG_MIN_WINDOW, ROLLING_AVG_MAX_WINDOW);
}
}
pub struct App {
pub should_quit: bool,
pub throughputs: Vec<PortThroughput>,
pub selected_row: usize,
pub show_detail: bool,
pub show_help: bool,
pub processes: Vec<stat::ProcessRdmaInfo>,
pub detail_scroll: u16,
pub detail_max_scroll: u16,
pub theme: Theme,
pub sysinfo: SysInfo,
pub history: HashMap<String, DeviceHistory>,
pub cpu_history: Vec<f32>,
prev_stats: Vec<PortStat>,
prev_ifstats: Vec<IfStats>,
// Per-subsystem baselines: each timestamp marks when its subsystem last
// read successfully, so a failed read holds that subsystem's state and
// the next success diffs over the true elapsed span.
prev_stats_at: Option<Instant>,
prev_ifstats_at: Option<Instant>,
prev_nvlink_at: Option<Instant>,
prev_xgmi_at: Option<Instant>,
prev_taken_at: Option<Instant>,
rdma_rows: Vec<PortThroughput>,
nvlink_rows: Vec<PortThroughput>,
xgmi_rows: Vec<PortThroughput>,
net_rate: NetRate,
pub has_data: bool,
/// Panic message from a dead sampler thread; None while it is alive.
pub sampler_error: Option<String>,
pub rolling_avg: RollingAvgState,
pub show_rolling_avg: bool,
pub show_window_input: bool,
pub window_input_buf: String,
pub columns: Vec<TableColumn>,
pub show_column_picker: bool,
pub column_picker_cursor: usize,
pub h_scroll: usize,
pub h_scroll_max: usize,
pub table_offset: usize,
pub refresh_interval: Duration,
cached_display: Vec<PortThroughput>,
/// Active Perfetto recorder when recording; None when idle.
pub recorder: Option<Recorder>,
/// Transient message shown after a recording is saved or fails.
pub record_status: Option<String>,
prev_nvlink: Vec<crate::nvlink::NvLinkSnapshot>,
prev_xgmi: Vec<crate::xgmi::XgmiSnapshot>,
pub active_tab: DeviceClass,
pub seen_tabs: Vec<DeviceClass>,
tab_selection: HashMap<DeviceClass, usize>,
}
const HISTORY_LEN: usize = 60;
#[derive(Clone, Debug)]
pub struct DeviceHistory {
pub tx: Vec<f64>,
pub rx: Vec<f64>,
pub util: Vec<f64>,
}
impl DeviceHistory {
fn new() -> Self {
Self {
tx: Vec::with_capacity(HISTORY_LEN),
rx: Vec::with_capacity(HISTORY_LEN),
util: Vec::with_capacity(HISTORY_LEN),
}
}
fn push(&mut self, tx: f64, rx: f64) {
if self.tx.len() >= HISTORY_LEN {
self.tx.remove(0);
self.rx.remove(0);
}
self.tx.push(tx);
self.rx.push(rx);
}
fn push_util(&mut self, util: f64) {
if self.util.len() >= HISTORY_LEN {
self.util.remove(0);
}
self.util.push(util);
}
}
#[derive(Clone)]
pub struct SysInfo {
pub hostname: String,
pub uptime: String,
pub load_avg: String,
pub mem_total_mb: u64,
pub mem_used_mb: u64,
pub mem_pct: f32,
pub cpu_pct: f32,
pub net: NetRate,
}
impl App {
pub fn new() -> Self {
Self {
should_quit: false,
throughputs: Vec::new(),
selected_row: 0,
theme: Theme::Default,
show_detail: false,
show_help: false,
processes: Vec::new(),
detail_scroll: 0,
detail_max_scroll: 0,
sysinfo: read_sysinfo(NetRate::default()),
history: HashMap::new(),
cpu_history: Vec::with_capacity(HISTORY_LEN),
prev_stats: Vec::new(),
prev_ifstats: Vec::new(),
prev_stats_at: None,
prev_ifstats_at: None,
prev_nvlink_at: None,
prev_xgmi_at: None,
prev_taken_at: None,
rdma_rows: Vec::new(),
nvlink_rows: Vec::new(),
xgmi_rows: Vec::new(),
net_rate: NetRate::default(),
has_data: false,
sampler_error: None,
rolling_avg: RollingAvgState::new(ROLLING_AVG_DEFAULT_WINDOW),
show_rolling_avg: false,
show_window_input: false,
window_input_buf: String::new(),
columns: default_columns(),
show_column_picker: false,
column_picker_cursor: 0,
h_scroll: 0,
h_scroll_max: 0,
table_offset: 0,
refresh_interval: Duration::from_secs_f64(REFRESH_DEFAULT_SECS),
cached_display: Vec::new(),
recorder: None,
record_status: None,
prev_nvlink: Vec::new(),
prev_xgmi: Vec::new(),
active_tab: DeviceClass::Rdma,
seen_tabs: vec![DeviceClass::Rdma],
tab_selection: HashMap::new(),
}
}
/// Fold one sampler snapshot into the app state, per subsystem: a failed
/// read (None) keeps that subsystem's previous rows and baseline, so one
/// broken source never blocks the others. Each subsystem's first success
/// is its baseline (prev == curr, zero rates); real rates follow. Elapsed
/// comes from sampler-side timestamps so UI queue latency can't skew rates.
pub fn apply_snapshot(&mut self, snap: crate::sampler::Snapshot) {
if let Some(prev) = self.prev_taken_at {
if snap.taken_at.duration_since(prev).as_secs_f64() < 0.1 {
return;
}
}
// Per-subsystem elapsed: each sample carries its own read-adjacent
// timestamp, measured to that subsystem's last success, so neither
// another subsystem's latency nor a skipped tick can skew the span.
let since =
|now: Instant, at: Option<Instant>| at.map(|a| now.duration_since(a).as_secs_f64());
if let Some(s) = snap.stats {
self.rdma_rows = match since(s.taken_at, self.prev_stats_at) {
Some(e) => compute_throughputs(&self.prev_stats, &s.data, e),
None => compute_throughputs(&s.data, &s.data, 1.0), // baseline
};
self.prev_stats = s.data;
self.prev_stats_at = Some(s.taken_at);
}
if let Some(s) = snap.nvlink {
self.nvlink_rows = match since(s.taken_at, self.prev_nvlink_at) {
Some(e) => compute_nvlink_throughputs(&self.prev_nvlink, &s.data, e),
None => compute_nvlink_throughputs(&s.data, &s.data, 1.0), // baseline
};
self.prev_nvlink = s.data;
self.prev_nvlink_at = Some(s.taken_at);
}
if let Some(s) = snap.xgmi {
self.xgmi_rows = match since(s.taken_at, self.prev_xgmi_at) {
Some(e) => compute_xgmi_throughputs(&self.prev_xgmi, &s.data, e),
None => compute_xgmi_throughputs(&s.data, &s.data, 1.0), // baseline
};
self.prev_xgmi = s.data;
self.prev_xgmi_at = Some(s.taken_at);
}
if let Some(s) = snap.ifstats {
if let Some(e) = since(s.taken_at, self.prev_ifstats_at) {
self.net_rate = net::compute_net_rate(&self.prev_ifstats, &s.data, e);
}
self.prev_ifstats = s.data;
self.prev_ifstats_at = Some(s.taken_at);
}
if let Some(processes) = snap.processes {
self.processes = processes;
}
self.throughputs = self.rdma_rows.clone();
self.throughputs.extend(self.nvlink_rows.iter().cloned());
self.throughputs.extend(self.xgmi_rows.iter().cloned());
// Stable display order: sort once here so history, rolling averages,
// recording, and the display all inherit the same order.
sort_by_device_order(&mut self.throughputs);
detect_tabs(&mut self.seen_tabs, &self.throughputs);
self.prev_taken_at = Some(snap.taken_at);
self.has_data = true;
self.clamp_selection();
self.update_history();
self.rolling_avg.push(&self.throughputs);
if let Some(rec) = &mut self.recorder {
rec.push(snap.taken_at, port_metrics(&self.throughputs));
}
self.sysinfo = read_sysinfo(self.net_rate.clone());
if self.cpu_history.len() >= HISTORY_LEN {
self.cpu_history.remove(0);
}
self.cpu_history.push(self.sysinfo.cpu_pct);
self.recompute_display();
}
/// Seconds since the last applied snapshot when it exceeds a staleness
/// threshold (3x the refresh interval, min 2s); `None` while fresh.
/// Lets the UI flag a stalled sampler, which `sampler_error` cannot see.
pub fn stale_secs(&self) -> Option<u64> {
let at = self.prev_taken_at?;
let threshold = (self.refresh_interval * 3).max(Duration::from_secs(2));
let age = at.elapsed();
(age > threshold).then_some(age.as_secs())
}
/// Recompute the cached display throughputs (call after any change to
/// `throughputs`, `show_rolling_avg`, `active_tab`, or rolling avg state).
fn recompute_display(&mut self) {
let rows: Vec<PortThroughput> = if self.show_rolling_avg {
let mut avgs = self.rolling_avg.averages();
sort_by_throughput_order(&mut avgs, &self.throughputs);
avgs
} else {
self.throughputs.clone()
};
self.cached_display = rows
.into_iter()
.filter(|t| t.class == self.active_tab)
.collect();
// Keep the cursor inside the (possibly shorter) filtered view.
self.selected_row = self
.selected_row
.min(self.cached_display.len().saturating_sub(1));
}
fn update_history(&mut self) {
for t in &self.throughputs {
let util = t
.nvlink
.as_ref()
.and_then(|m| m.metrics.as_ref())
.or_else(|| t.xgmi.as_ref().and_then(|m| m.metrics.as_ref()))
.and_then(|m| m.util_pct);
let entry = self
.history
.entry(t.dev_name.clone())
.or_insert_with(DeviceHistory::new);
entry.push(t.tx_gbps, t.rx_gbps);
if let Some(u) = util {
entry.push_util(u as f64);
}
}
}
pub fn move_up(&mut self) {
self.selected_row = self.selected_row.saturating_sub(1);
}
pub fn move_down(&mut self) {
if !self.cached_display.is_empty() && self.selected_row < self.cached_display.len() - 1 {
self.selected_row += 1;
}
}
pub fn toggle_detail(&mut self) {
self.show_detail = !self.show_detail;
self.detail_scroll = 0;
}
pub fn detail_scroll_up(&mut self) {
if self.detail_scroll > 0 {
self.detail_scroll -= 1;
} else if self.selected_row > 0 {
self.selected_row -= 1;
self.detail_scroll = 0;
}
}
pub fn detail_scroll_down(&mut self, max: u16) {
if self.detail_scroll < max {
self.detail_scroll += 1;
} else if !self.cached_display.is_empty()
&& self.selected_row < self.cached_display.len() - 1
{
self.selected_row += 1;
self.detail_scroll = 0;
}
}
pub fn cycle_theme(&mut self) {
self.theme = self.theme.next();
}
pub fn toggle_rolling_avg(&mut self) {
self.show_rolling_avg = !self.show_rolling_avg;
self.recompute_display();
}
/// Toggle recording: start if idle; otherwise stop and flush the trace.
/// On a write error the buffer is kept so no captured data is lost.
pub fn toggle_recording(&mut self) {
let Some(rec) = self.recorder.take() else {
self.recorder = Some(Recorder::new());
self.record_status = None;
return;
};
if rec.is_empty() {
self.record_status = Some("recording stopped (nothing captured)".to_string());
return;
}
let path = trace_filename();
if let Err(e) = rec.write_to(&path) {
self.record_status = Some(format!("save failed: {} (still recording)", e));
self.recorder = Some(rec);
return;
}
self.record_status = Some(format!("saved {} ({} samples)", path, rec.sample_count()));
}
/// (elapsed seconds, sample count) for the active recording, if any.
pub fn recording_progress(&self) -> Option<(u64, usize)> {
self.recorder
.as_ref()
.map(|r| (r.elapsed_secs(), r.sample_count()))
}
pub fn increase_avg_window(&mut self) {
self.rolling_avg.increase_window();
if self.show_rolling_avg {
self.recompute_display();
}
}
pub fn decrease_avg_window(&mut self) {
self.rolling_avg.decrease_window();
if self.show_rolling_avg {
self.recompute_display();
}
}
/// Slow the refresh by one step (longer interval), clamped to the max.
pub fn increase_refresh_interval(&mut self) {
let secs = (self.refresh_interval.as_secs_f64() + REFRESH_STEP_SECS).min(REFRESH_MAX_SECS);
self.refresh_interval = Duration::from_secs_f64(secs);
}
/// Speed the refresh up by one step (shorter interval), clamped to the min.
pub fn decrease_refresh_interval(&mut self) {
let secs = (self.refresh_interval.as_secs_f64() - REFRESH_STEP_SECS).max(REFRESH_MIN_SECS);
self.refresh_interval = Duration::from_secs_f64(secs);
}
pub fn open_window_input(&mut self) {
self.window_input_buf = self.rolling_avg.window_secs.to_string();
self.show_window_input = true;
}
pub fn cancel_window_input(&mut self) {
self.show_window_input = false;
self.window_input_buf.clear();
}
pub fn confirm_window_input(&mut self) {
if let Ok(val) = self.window_input_buf.parse::<usize>() {
self.rolling_avg
.set_window(val.clamp(ROLLING_AVG_MIN_WINDOW, ROLLING_AVG_MAX_WINDOW));
if self.show_rolling_avg {
self.recompute_display();
}
}
self.show_window_input = false;
self.window_input_buf.clear();
}
pub fn open_column_picker(&mut self) {
// Column layout is configurable only on the RDMA tab; GPU tabs
// render a fixed column set.
if self.active_tab != DeviceClass::Rdma {
return;
}
self.show_column_picker = true;
self.column_picker_cursor = 0;
}
pub fn close_column_picker(&mut self) {
self.show_column_picker = false;
}
pub fn column_picker_up(&mut self) {
self.column_picker_cursor = self.column_picker_cursor.saturating_sub(1);
}
pub fn column_picker_down(&mut self) {
let max = all_columns().len().saturating_sub(1);
if self.column_picker_cursor < max {
self.column_picker_cursor += 1;
}
}
pub fn column_picker_toggle(&mut self) {
let all = all_columns();
if let Some(col) = all.get(self.column_picker_cursor) {
if let Some(pos) = self.columns.iter().position(|c| c == col) {
if self.columns.len() > 1 {
self.columns.remove(pos);
}
} else {
self.columns.push(col.clone());
}
}
self.clamp_h_scroll();
}
pub fn scroll_left(&mut self) {
self.h_scroll = self.h_scroll.saturating_sub(1);
}
pub fn scroll_right(&mut self) {
if self.h_scroll < self.h_scroll_max {
self.h_scroll += 1;
}
}
pub fn clamp_h_scroll(&mut self) {
if self.h_scroll >= self.columns.len() {
self.h_scroll = self.columns.len().saturating_sub(1);
}
}
/// Returns the throughputs to display: rolling avg if enabled, otherwise instant.
/// Uses a cached value recomputed once per refresh.
pub fn display_throughputs(&self) -> &[PortThroughput] {
&self.cached_display
}
pub fn selected_throughput(&self) -> Option<&PortThroughput> {
self.cached_display.get(self.selected_row)
}
pub fn selected_device_processes(&self) -> Vec<&stat::ProcessRdmaInfo> {
let Some(t) = self.selected_throughput() else {
return Vec::new();
};
self.processes
.iter()
.filter(|p| p.dev_name == t.dev_name)
.collect()
}
fn clamp_selection(&mut self) {
if !self.cached_display.is_empty() && self.selected_row >= self.cached_display.len() {
self.selected_row = self.cached_display.len() - 1;
}
}
/// Cycle the active tab (Tab forward, Shift-Tab back); remembers the
/// cursor per tab and resets scroll state.
pub fn cycle_tab(&mut self, forward: bool) {
if self.seen_tabs.len() < 2 {
return;
}
let idx = self
.seen_tabs
.iter()
.position(|&t| t == self.active_tab)
.unwrap_or(0);
let n = self.seen_tabs.len();
let next = if forward {
(idx + 1) % n
} else {
(idx + n - 1) % n
};
self.tab_selection
.insert(self.active_tab, self.selected_row);
self.active_tab = self.seen_tabs[next];
self.selected_row = *self.tab_selection.get(&self.active_tab).unwrap_or(&0);
self.table_offset = 0;
self.h_scroll = 0;
// Tab also works with the detail pane open; start it at the top.
self.detail_scroll = 0;
self.recompute_display();
}
}
/// A class's tab appears the first time it produces rows and stays for the
/// session, so a transient sampling failure cannot flicker it away.
fn detect_tabs(seen: &mut Vec<DeviceClass>, rows: &[PortThroughput]) {
for class in [DeviceClass::Xgmi, DeviceClass::Nvlink] {
if !seen.contains(&class) && rows.iter().any(|t| t.class == class) {
seen.push(class);
seen.sort_by_key(|c| *c as usize); // Rdma < Xgmi < Nvlink
}
}
}
fn read_file_trimmed(path: &str) -> String {
std::fs::read_to_string(path)
.unwrap_or_default()
.trim()
.to_string()
}
fn read_hostname() -> String {
let h = read_file_trimmed("/etc/hostname");
if h.is_empty() {
"unknown".into()
} else {
h
}
}
fn read_uptime() -> String {
let secs: u64 = read_file_trimmed("/proc/uptime")
.split_whitespace()
.next()
.and_then(|s| s.parse::<f64>().ok())
.unwrap_or(0.0) as u64;
format!(
"up {} days, {}:{:02}",
secs / 86400,
(secs % 86400) / 3600,
(secs % 3600) / 60
)
}
fn read_load_avg() -> String {
read_file_trimmed("/proc/loadavg")
.split_whitespace()
.take(3)
.collect::<Vec<_>>()
.join(", ")
}
fn read_meminfo() -> (u64, u64) {
let content = read_file_trimmed("/proc/meminfo");
let mut total = 0u64;
let mut avail = 0u64;
for line in content.lines() {
let val = || {
line.split_whitespace()
.nth(1)
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(0)
};
if line.starts_with("MemTotal:") {
total = val();
}
if line.starts_with("MemAvailable:") {
avail = val();
}
}
(total / 1024, (total.saturating_sub(avail)) / 1024)
}
fn read_cpu_usage() -> f32 {
let content = read_file_trimmed("/proc/stat");
let first = content.lines().next().unwrap_or("");
let vals: Vec<u64> = first
.split_whitespace()
.skip(1)
.filter_map(|v| v.parse().ok())
.collect();
if vals.len() < 4 {
return 0.0;
}
let idle = vals[3];
let total: u64 = vals.iter().sum();
if total == 0 {
return 0.0;
}
((total - idle) as f32 / total as f32) * 100.0
}
fn read_sysinfo(net: NetRate) -> SysInfo {
let (mem_total_mb, mem_used_mb) = read_meminfo();
let mem_pct = if mem_total_mb > 0 {
(mem_used_mb as f32 / mem_total_mb as f32) * 100.0
} else {
0.0
};
SysInfo {
hostname: read_hostname(),
uptime: read_uptime(),
load_avg: read_load_avg(),
mem_total_mb,
mem_used_mb,
mem_pct,
cpu_pct: read_cpu_usage(),
net,
}
}
/// Map the display throughputs into the recorder's metric shape.
fn port_metrics(throughputs: &[PortThroughput]) -> Vec<PortMetrics> {
throughputs
.iter()
.map(|t| PortMetrics {
dev_name: t.dev_name.clone(),
port: t.port,
tx_gbps: t.tx_gbps,
rx_gbps: t.rx_gbps,
tx_pps: t.tx_pkts_per_sec,
rx_pps: t.rx_pkts_per_sec,
rx_drops_per_sec: t.rx_drops_per_sec,
})
.collect()
}
/// Trace output path in the cwd, named by wall-clock seconds for uniqueness.
fn trace_filename() -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
format!("rdmatop-{}.json", secs)
}
fn find_prev<'a>(prev: &'a [PortStat], dev: &str, port: u32) -> Option<&'a PortStat> {
prev.iter().find(|s| s.dev_name == dev && s.port == port)
}
fn bytes_to_gbps(bytes_per_sec: f64) -> f64 {
bytes_per_sec * 8.0 / 1_000_000_000.0