ltop 0.2.4

btop-styled TUI monitoring only local network, LAN neighbours and disk I/O
Documentation
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
//! Replay / analysis of session JSONL logs written by `MonLog`
//! (`~/.local/state/ltop/session-*.jsonl`).
//!
//! The log stores cumulative per-process counters per snapshot, so replay
//! reconstructs recording-period increments as deltas between consecutive
//! snapshots (counter resets from a restarted pid are clamped at zero).

use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::path::PathBuf;

use anyhow::{Context, Result};

const DEFAULT_TOP: usize = 15;

#[derive(Debug, Default, Clone)]
pub struct ProcAgg {
    pub pid: u32,
    pub name: String,
    pub first_ts: u64,
    pub last_ts: u64,
    pub samples: u32,
    /// recording-period increments, bytes
    pub net_recv: u64,
    pub net_sent: u64,
    pub udp_recv: u64,
    pub udp_sent: u64,
    pub disk_r: u64,
    pub disk_w: u64,
    /// busiest single interval, net (recv+sent) bytes/sec
    pub peak_net_bps: f64,
}

impl ProcAgg {
    pub fn total(&self) -> u64 {
        self.net_recv + self.net_sent + self.disk_r + self.disk_w
    }
}

#[derive(Debug)]
pub struct Session {
    pub path: PathBuf,
    pub host: String,
    pub start: u64,
    pub interval_s: u64,
    pub samples: usize,
    pub procs: Vec<ProcAgg>,
    /// (ts, total net B/s) busiest intervals, sorted desc
    pub busy: Vec<(u64, f64)>,
}

/// `ltop --replay [FILE] [--top N] [--csv OUT]` — analyze one session log
/// (default: the newest in the state dir) and print a per-process report.
pub fn run_replay(args: &[String]) -> Result<()> {
    let mut file: Option<PathBuf> = None;
    let mut top = DEFAULT_TOP;
    let mut csv: Option<PathBuf> = None;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--replay" => {
                if let Some(n) = args.get(i + 1) {
                    if !n.starts_with('-') {
                        file = Some(PathBuf::from(n));
                        i += 1;
                    }
                }
            }
            "--top" => {
                if let Some(n) = args.get(i + 1).and_then(|v| v.parse::<usize>().ok()) {
                    top = n.max(1);
                    i += 1;
                }
            }
            "--csv" => {
                if let Some(n) = args.get(i + 1) {
                    if !n.starts_with('-') {
                        csv = Some(PathBuf::from(n));
                        i += 1;
                    }
                }
            }
            _ => {}
        }
        i += 1;
    }

    let zh = crate::cli_lang_zh();
    let p = |en: &str, c: &str| crate::pick_s(zh, en, c);
    let path = match file {
        Some(p) => p,
        None => newest_in(&log_dir()).context(p(
            "no session log in the state dir; record with the L key or --log first, or specify a file: ltop --replay <session-*.jsonl>",
            "state 目录里没有会话日志;先用 `L` 键或 --log 录制,或指定文件:ltop --replay <session-*.jsonl>",
        ))?,
    };
    let ses = load_file(&path)?;
    print_report(&ses, top, zh);
    if let Some(out) = csv {
        write_csv(&ses, &out)?;
        println!(
            "{}",
            p(
                &format!("CSV exported to {}", out.display()),
                &format!("CSV 已导出到 {}", out.display())
            )
        );
    }
    Ok(())
}

pub fn load_file(path: &std::path::Path) -> Result<Session> {
    let f = std::fs::File::open(path).with_context(|| {
        crate::pick_s(
            crate::cli_lang_zh(),
            &format!("cannot open {}", path.display()),
            &format!("打不开 {}", path.display()),
        )
    })?;
    let rd = std::io::BufReader::new(f);
    let mut ses = Session {
        path: path.to_path_buf(),
        host: String::new(),
        start: 0,
        interval_s: 0,
        samples: 0,
        procs: Vec::new(),
        busy: Vec::new(),
    };
    // (pid, name) -> previous snapshot counters
    let mut prev: HashMap<(u32, String), [u64; 6]> = HashMap::new();
    let mut prev_ts: Option<u64> = None;
    let mut interval_total: Vec<(u64, u64)> = Vec::new(); // (ts, net bytes in interval)

    for line in rd.lines() {
        let line = line?;
        if line.contains("\"session_start\"") {
            ses.start = num(&line, "session_start").unwrap_or(0);
            if let Some(h) = text(&line, "host") {
                ses.host = h;
            }
            ses.interval_s = num(&line, "interval_s").unwrap_or(0);
            continue;
        }
        let Some(ts) = num(&line, "ts") else {
            continue;
        };
        let procs = parse_procs(&line);
        ses.samples += 1;
        let dt = prev_ts.map_or(0, |t| ts.saturating_sub(t));
        let mut net_sum = 0u64;
        for sp in &procs {
            let key = (sp.pid, sp.name.clone());
            let cur = [
                sp.net_recv,
                sp.net_sent,
                sp.udp_recv,
                sp.udp_sent,
                sp.disk_r,
                sp.disk_w,
            ];
            let agg = ses
                .procs
                .iter_mut()
                .find(|a| a.pid == sp.pid && a.name == sp.name);
            let agg = match agg {
                Some(a) => a,
                None => {
                    ses.procs.push(ProcAgg {
                        pid: sp.pid,
                        name: sp.name.clone(),
                        first_ts: ts,
                        ..Default::default()
                    });
                    ses.procs.last_mut().unwrap()
                }
            };
            agg.last_ts = ts;
            agg.samples += 1;
            let base = prev.get(&key).map_or(cur, |p| *p);
            let mut d = [0u64; 6];
            for k in 0..6 {
                d[k] = cur[k].saturating_sub(base[k]);
            }
            agg.net_recv += d[0];
            agg.net_sent += d[1];
            agg.udp_recv += d[2];
            agg.udp_sent += d[3];
            agg.disk_r += d[4];
            agg.disk_w += d[5];
            net_sum += d[0] + d[1];
            if dt > 0 {
                let rate = (d[0] + d[1]) as f64 / dt as f64;
                if rate > agg.peak_net_bps {
                    agg.peak_net_bps = rate;
                }
            }
            prev.insert(key, cur);
        }
        if dt > 0 {
            interval_total.push((ts, net_sum));
        }
        prev_ts = Some(ts);
    }
    interval_total.sort_by_key(|&(_, bytes)| std::cmp::Reverse(bytes));
    ses.busy = interval_total
        .into_iter()
        .take(3)
        .map(|(ts, bytes)| {
            let rate = bytes as f64 / ses.interval_s.max(1) as f64;
            (ts, rate)
        })
        .collect();
    ses.procs.sort_by_key(|a| std::cmp::Reverse(a.total()));
    Ok(ses)
}

pub fn newest_in(dir: &std::path::Path) -> Option<PathBuf> {
    let mut best: Option<(u64, PathBuf)> = None;
    for e in std::fs::read_dir(dir).ok()?.flatten() {
        let p = e.path();
        let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
        if let Some(ts) = name
            .strip_prefix("session-")
            .and_then(|r| r.strip_suffix(".jsonl"))
            .and_then(|r| r.parse::<u64>().ok())
        {
            if best.as_ref().is_none_or(|(b, _)| ts > *b) {
                best = Some((ts, p));
            }
        }
    }
    best.map(|(_, p)| p)
}

fn log_dir() -> PathBuf {
    if let Ok(x) = std::env::var("XDG_STATE_HOME") {
        if !x.is_empty() {
            return PathBuf::from(x).join("ltop");
        }
    }
    match std::env::var("HOME") {
        Ok(h) if !h.is_empty() => PathBuf::from(h).join(".local/state/ltop"),
        _ => PathBuf::from("/tmp/ltop"),
    }
}

struct SnapProc {
    pid: u32,
    name: String,
    net_recv: u64,
    net_sent: u64,
    udp_recv: u64,
    udp_sent: u64,
    disk_r: u64,
    disk_w: u64,
}

/// Extract the objects of the `"procs":[...]` array from a snapshot line.
fn parse_procs(line: &str) -> Vec<SnapProc> {
    let Some(start) = line.find("\"procs\":") else {
        return Vec::new();
    };
    let bytes = line.as_bytes();
    let Some(mut i) = bytes[start..]
        .iter()
        .position(|&b| b == b'[')
        .map(|p| start + p + 1)
    else {
        return Vec::new();
    };
    let mut out = Vec::new();
    while i < bytes.len() {
        if bytes[i] == b']' {
            break;
        }
        if bytes[i] != b'{' {
            i += 1;
            continue;
        }
        // find the matching '}' honouring string escapes
        let mut depth = 0usize;
        let mut in_str = false;
        let mut esc = false;
        let mut j = i;
        while j < bytes.len() {
            let b = bytes[j];
            if in_str {
                if esc {
                    esc = false;
                } else if b == b'\\' {
                    esc = true;
                } else if b == b'"' {
                    in_str = false;
                }
            } else {
                match b {
                    b'"' => in_str = true,
                    b'{' => depth += 1,
                    b'}' => {
                        depth -= 1;
                        if depth == 0 {
                            break;
                        }
                    }
                    _ => {}
                }
            }
            j += 1;
        }
        if j >= bytes.len() {
            break;
        }
        let obj = &line[i..=j];
        if let Some(p) = decode_proc(obj) {
            out.push(p);
        }
        i = j + 1;
    }
    out
}

fn decode_proc(obj: &str) -> Option<SnapProc> {
    Some(SnapProc {
        pid: num(obj, "pid")? as u32,
        name: text(obj, "name").unwrap_or_default(),
        net_recv: num(obj, "net_recv").unwrap_or(0),
        net_sent: num(obj, "net_sent").unwrap_or(0),
        udp_recv: num(obj, "udp_recv").unwrap_or(0),
        udp_sent: num(obj, "udp_sent").unwrap_or(0),
        disk_r: num(obj, "disk_r").unwrap_or(0),
        disk_w: num(obj, "disk_w").unwrap_or(0),
    })
}

/// value of `"key":<number>` anywhere in a flat JSON object string
fn num(s: &str, key: &str) -> Option<u64> {
    let pat = format!("\"{key}\":");
    let mut from = 0;
    loop {
        let p = s[from..].find(&pat)? + from;
        let rest = &s[p + pat.len()..];
        let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
        if !digits.is_empty() {
            return digits.parse().ok();
        }
        from = p + pat.len();
    }
}

/// value of `"key":"..."` with the escapes written by `json_str` decoded
fn text(s: &str, key: &str) -> Option<String> {
    let pat = format!("\"{key}\":\"");
    let p = s.find(&pat)? + pat.len();
    let mut out = String::new();
    let mut chars = s[p..].chars();
    while let Some(c) = chars.next() {
        match c {
            '"' => break,
            '\\' => match chars.next()? {
                'n' => out.push('\n'),
                't' => out.push('\t'),
                'r' => out.push('\r'),
                'u' => {
                    let hex: String = chars.by_ref().take(4).collect();
                    let v = u32::from_str_radix(&hex, 16).ok()?;
                    out.push(char::from_u32(v)?);
                }
                other => out.push(other),
            },
            other => out.push(other),
        }
    }
    Some(out)
}

pub fn print_report(ses: &Session, top: usize, zh: bool) {
    let p = |en: &str, c: &str| crate::pick_s(zh, en, c);
    println!(
        "{}",
        p("== ltop replay ==", "== ltop 回放 ==")
    );
    println!(
        "{}",
        p(
            &format!(
                "file  {}\nhost  {}  start {}  {} snapshots  interval {}s",
                ses.path.display(),
                if ses.host.is_empty() { "—" } else { &ses.host },
                fmt_ts(ses.start),
                ses.samples,
                ses.interval_s
            ),
            &format!(
                "file  {}\nhost  {}  开始 {}  快照 {} 个  间隔 {}s",
                ses.path.display(),
                if ses.host.is_empty() { "—" } else { &ses.host },
                fmt_ts(ses.start),
                ses.samples,
                ses.interval_s
            )
        )
    );
    if ses.procs.is_empty() {
        println!(
            "{}",
            p("(no process snapshots in the log)", "(日志里没有进程快照)")
        );
        return;
    }
    println!(
        "\n{:<28} {:>9} {:>9} {:>9} {:>9} {:>10} {:>4}",
        p("Process", "进程"),
        p("Σrx", "Σ收"),
        p("Σtx", "Σ发"),
        p("Σrd", "Σ读盘"),
        p("Σwr", "Σ写盘"),
        p("peak B/s", "峰值网速"),
        p("smp", "采样")
    );
    for a in ses.procs.iter().take(top) {
        println!(
            "{:<28} {:>9} {:>9} {:>9} {:>9} {:>10} {:>4}",
            format!("{}({})", a.name, a.pid),
            crate::fmt_human(a.net_recv as f64),
            crate::fmt_human(a.net_sent as f64),
            crate::fmt_human(a.disk_r as f64),
            crate::fmt_human(a.disk_w as f64),
            format!("{}/s", crate::fmt_human(a.peak_net_bps)),
            a.samples
        );
    }
    let shown = ses.procs.len().min(top);
    if ses.procs.len() > shown {
        println!(
            "{}",
            p(
                &format!(
                    "({} more processes not shown; adjust --top N)",
                    ses.procs.len() - shown
                ),
                &format!("(其余 {} 个进程未列出,--top N 调整)", ses.procs.len() - shown)
            )
        );
    }
    if !ses.busy.is_empty() {
        println!(
            "{}",
            p("\nBusiest intervals:", "\n最忙时段:")
        );
        for (ts, rate) in &ses.busy {
            println!("  {}  {}/s", fmt_ts(*ts), crate::fmt_human(*rate));
        }
    }
}

fn write_csv(ses: &Session, out: &std::path::Path) -> Result<()> {
    let mut w = std::io::BufWriter::new(
        std::fs::File::create(out).with_context(|| {
            crate::pick_s(
                crate::cli_lang_zh(),
                &format!("cannot create {}", out.display()),
                &format!("创建 {} 失败", out.display()),
            )
        })?,
    );
    writeln!(
        w,
        "name,pid,first_ts,last_ts,samples,net_recv,net_sent,udp_recv,udp_sent,disk_r,disk_w,peak_net_bps"
    )?;
    for a in &ses.procs {
        writeln!(
            w,
            "{},{},{},{},{},{},{},{},{},{},{},{}",
            csv_field(&a.name),
            a.pid,
            a.first_ts,
            a.last_ts,
            a.samples,
            a.net_recv,
            a.net_sent,
            a.udp_recv,
            a.udp_sent,
            a.disk_r,
            a.disk_w,
            a.peak_net_bps as u64
        )?;
    }
    w.flush()?;
    Ok(())
}

fn csv_field(s: &str) -> String {
    if s.contains('"') || s.contains(',') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

pub(crate) fn fmt_ts(ts: u64) -> String {
    let t = ts as i64 as libc::time_t;
    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    unsafe {
        libc::localtime_r(&t, &mut tm);
    }
    format!(
        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
        tm.tm_year + 1900,
        tm.tm_mon + 1,
        tm.tm_mday,
        tm.tm_hour,
        tm.tm_min,
        tm.tm_sec
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    const SAMPLE: &str = concat!(
        "{\"session_start\":1700000000,\"host\":\"omarchy\",\"interval_s\":60}\n",
        "{\"ts\":1700000060,\"procs\":[",
        "{\"pid\":100,\"name\":\"firefox\",\"net_recv\":1000,\"net_sent\":200,\"disk_r\":0,\"disk_w\":0},",
        "{\"pid\":200,\"name\":\"sync\",\"net_recv\":0,\"net_sent\":0,\"disk_r\":50,\"disk_w\":70}]}\n",
        "{\"ts\":1700000120,\"procs\":[",
        "{\"pid\":100,\"name\":\"firefox\",\"net_recv\":3000,\"net_sent\":600,\"disk_r\":0,\"disk_w\":0},",
        "{\"pid\":300,\"name\":\"new\",\"net_recv\":500,\"net_sent\":0,\"disk_r\":0,\"disk_w\":0}]}\n",
        "{\"ts\":1700000180,\"procs\":[",
        "{\"pid\":100,\"name\":\"firefox\",\"net_recv\":2500,\"net_sent\":600,\"disk_r\":0,\"disk_w\":0},",
        "{\"pid\":200,\"name\":\"sync\",\"net_recv\":0,\"net_sent\":0,\"disk_r\":90,\"disk_w\":70}]}\n",
    );

    fn load_str(tag: &str, s: &str) -> Session {
        let dir =
            std::env::temp_dir().join(format!("ltop-replay-test-{}-{tag}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let p = dir.join("session-1700000000.jsonl");
        std::fs::write(&p, s).unwrap();
        let ses = load_file(&p).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        ses
    }

    #[test]
    fn header_and_snapshots_parse() {
        let ses = load_str("header", SAMPLE);
        assert_eq!(ses.host, "omarchy");
        assert_eq!(ses.start, 1700000000);
        assert_eq!(ses.interval_s, 60);
        assert_eq!(ses.samples, 3);
    }

    #[test]
    fn deltas_accumulate_positive_and_clamp_resets() {
        let ses = load_str("deltas", SAMPLE);
        let ff = ses.procs.iter().find(|a| a.name == "firefox").unwrap();
        // 1000->3000 (+2000) then 3000->2500 (reset, clamped)
        assert_eq!(ff.net_recv, 2000);
        assert_eq!(ff.net_sent, 400);
        assert_eq!(ff.disk_r + ff.disk_w, 0);
        // peak: 2000+400=2400 bytes over 60s
        assert!((ff.peak_net_bps - 40.0).abs() < 1e-9);
        assert_eq!(ff.samples, 3);
    }

    #[test]
    fn new_process_baseline_is_first_snapshot() {
        let ses = load_str("baseline", SAMPLE);
        let new = ses.procs.iter().find(|a| a.name == "new").unwrap();
        assert_eq!(new.net_recv, 0); // first sighting records no delta
        assert_eq!(new.samples, 1);
    }

    #[test]
    fn disk_counters_count() {
        let ses = load_str("disk", SAMPLE);
        let sync = ses.procs.iter().find(|a| a.name == "sync").unwrap();
        // 50->90 (+40); write counter unchanged
        assert_eq!(sync.disk_r, 40);
        assert_eq!(sync.disk_w, 0);
        assert_eq!(sync.samples, 2);
    }

    #[test]
    fn busiest_interval_ranked() {
        let ses = load_str("busy", SAMPLE);
        assert_eq!(ses.busy[0].0, 1700000120);
        assert!((ses.busy[0].1 - 2400.0 / 60.0).abs() < 1e-9);
    }

    #[test]
    fn sorts_by_total_desc() {
        let ses = load_str("sort", SAMPLE);
        let totals: Vec<u64> = ses.procs.iter().map(|a| a.total()).collect();
        assert!(totals.windows(2).all(|w| w[0] >= w[1]));
    }

    #[test]
    fn udp_columns_are_parsed_and_exported() {
        // eBPF 落地后快照带 udp_recv/udp_sent;回放按同规则差分出分项增量
        let with_udp = concat!(
            "{\"session_start\":1700000000,\"host\":\"omarchy\",\"interval_s\":60}\n",
            "{\"ts\":1700000060,\"procs\":[",
            "{\"pid\":100,\"name\":\"ff\",\"net_recv\":1000,\"net_sent\":200,",
            "\"udp_recv\":800,\"udp_sent\":100,\"disk_r\":0,\"disk_w\":0}]}\n",
            "{\"ts\":1700000120,\"procs\":[",
            "{\"pid\":100,\"name\":\"ff\",\"net_recv\":2000,\"net_sent\":300,",
            "\"udp_recv\":1600,\"udp_sent\":150,\"disk_r\":0,\"disk_w\":0}]}\n",
        );
        let ses = load_str("udp_keys", with_udp);
        let ff = ses.procs.iter().find(|a| a.name == "ff").unwrap();
        assert_eq!(ff.net_recv, 1000);
        assert_eq!(ff.net_sent, 100);
        assert_eq!(ff.udp_recv, 800, "UDP 分项差分");
        assert_eq!(ff.udp_sent, 50);
        // 旧格式(无 udp 键)不炸,分项为 0
        let ses = load_str("udp_keys", SAMPLE);
        assert!(ses.procs.iter().all(|a| a.udp_recv + a.udp_sent == 0));
    }

    #[test]
    fn text_unescapes_json_strings() {
        assert_eq!(
            text("{\"name\":\"a\\\"b\\\\c\"}", "name").unwrap(),
            "a\"b\\c"
        );
        assert_eq!(text("{\"name\":\"中文\"}", "name").unwrap(), "中文");
        assert_eq!(num("{\"ts\":123,\"x\":1}", "ts"), Some(123));
    }

    #[test]
    fn csv_quotes_fields_with_commas() {
        assert_eq!(csv_field("plain"), "plain");
        assert_eq!(csv_field("a,b"), "\"a,b\"");
        assert_eq!(csv_field("say\"hi"), "\"say\"\"hi\"");
    }
}