1use std::collections::{BTreeSet, HashMap};
7
8use serde_json::Value;
9
10use crate::procfs::fmt_kb;
11
12struct Entry {
13 comm: String,
14 rss_kb: u64,
15 pss_kb: Option<u64>,
16}
17
18pub struct Opts {
20 pub min_delta_kb: u64,
22 pub top: usize,
23}
24
25impl Default for Opts {
26 fn default() -> Self {
27 Opts {
28 min_delta_kb: 0,
29 top: 30,
30 }
31 }
32}
33
34pub fn parse_size(text: &str) -> Option<u64> {
36 let t = text.trim();
37 let (num, mult) = match t.chars().last()? {
38 'k' | 'K' => (&t[..t.len() - 1], 1u64),
39 'm' | 'M' => (&t[..t.len() - 1], 1024),
40 'g' | 'G' => (&t[..t.len() - 1], 1024 * 1024),
41 _ => (t, 1),
42 };
43 num.parse::<u64>().ok().map(|n| n.saturating_mul(mult))
44}
45
46struct Doc {
48 at_ms: u64,
49 self_pid: Option<u32>,
50 procs: HashMap<u32, Entry>,
51}
52
53fn parse(text: &str, name: &str) -> Result<Doc, String> {
54 let v: Value = serde_json::from_str(text).map_err(|e| format!("{name}: not JSON ({e})"))?;
55 match v.get("schema").and_then(Value::as_str) {
56 Some("mtop.snapshot.v1") => {}
57 Some(other) => return Err(format!("{name}: unsupported snapshot schema {other:?}")),
58 None => return Err(format!("{name}: missing schema")),
59 }
60 let at = v.get("at_unix_ms").and_then(Value::as_u64).unwrap_or(0);
61 let self_pid = v.get("self_pid").and_then(Value::as_u64).map(|p| p as u32);
62 let procs = v
63 .get("procs")
64 .and_then(Value::as_array)
65 .ok_or_else(|| format!("{name}: missing procs"))?;
66 let mut map = HashMap::with_capacity(procs.len());
67 for (i, p) in procs.iter().enumerate() {
68 let pid = p
69 .get("pid")
70 .and_then(Value::as_u64)
71 .ok_or_else(|| format!("{name}: procs[{i}] has no pid"))?;
72 map.insert(
73 pid as u32,
74 Entry {
75 comm: p
76 .get("comm")
77 .and_then(Value::as_str)
78 .unwrap_or("?")
79 .to_string(),
80 rss_kb: p.get("rss_kb").and_then(Value::as_u64).unwrap_or(0),
81 pss_kb: p
82 .get("pss")
83 .and_then(|v| v.get("pss_kb"))
84 .and_then(Value::as_u64),
85 },
86 );
87 }
88 Ok(Doc {
89 at_ms: at,
90 self_pid,
91 procs: map,
92 })
93}
94
95fn signed_kb(delta: i64) -> String {
96 let sign = if delta > 0 {
97 "+"
98 } else if delta < 0 {
99 "-"
100 } else {
101 " "
102 };
103 format!("{sign}{}", fmt_kb(delta.unsigned_abs()))
104}
105
106struct Row {
107 pid: u32,
108 comm: String,
109 drss: i64,
110 rss_now: u64,
111 pss_now: Option<u64>,
112 dpss: Option<i64>,
113 note: &'static str,
114}
115
116pub fn render(a_text: &str, b_text: &str, opts: &Opts) -> Result<String, String> {
117 let a = parse(a_text, "A")?;
118 let b = parse(b_text, "B")?;
119 let (a_at, a_self) = (a.at_ms, a.self_pid);
120 let (b_at, b_self) = (b.at_ms, b.self_pid);
121
122 let mut pids: BTreeSet<u32> = BTreeSet::new();
123 pids.extend(a.procs.keys().copied());
124 pids.extend(b.procs.keys().copied());
125
126 let mut rows: Vec<Row> = Vec::new();
127 let (mut grew, mut shrank, mut new, mut gone) = (0, 0, 0, 0);
128 for pid in pids {
129 if Some(pid) == a_self || Some(pid) == b_self {
132 continue;
133 }
134 match (a.procs.get(&pid), b.procs.get(&pid)) {
135 (Some(x), Some(y)) => {
136 let drss = y.rss_kb as i64 - x.rss_kb as i64;
137 if drss > 0 {
138 grew += 1;
139 } else if drss < 0 {
140 shrank += 1;
141 }
142 rows.push(Row {
143 pid,
144 comm: y.comm.clone(),
145 drss,
146 rss_now: y.rss_kb,
147 pss_now: y.pss_kb,
148 dpss: match (x.pss_kb, y.pss_kb) {
149 (Some(p), Some(q)) => Some(q as i64 - p as i64),
150 _ => None,
151 },
152 note: "",
153 });
154 }
155 (None, Some(y)) => {
156 new += 1;
157 rows.push(Row {
158 pid,
159 comm: y.comm.clone(),
160 drss: y.rss_kb as i64,
161 rss_now: y.rss_kb,
162 pss_now: y.pss_kb,
163 dpss: None,
164 note: "new",
165 });
166 }
167 (Some(x), None) => {
168 gone += 1;
169 rows.push(Row {
170 pid,
171 comm: x.comm.clone(),
172 drss: -(x.rss_kb as i64),
173 rss_now: 0,
174 pss_now: None,
175 dpss: None,
176 note: "gone",
177 });
178 }
179 (None, None) => {}
180 }
181 }
182
183 rows.retain(|r| r.drss.unsigned_abs() >= opts.min_delta_kb);
184 rows.sort_by_key(|r| (std::cmp::Reverse(r.drss.unsigned_abs()), r.pid));
185 rows.truncate(opts.top);
186
187 let span = b_at.saturating_sub(a_at) / 1000;
188 let mut out = String::new();
189 out.push_str(&format!(
190 "mtop diff over {span}s ({} -> {} procs) {grew} grew, {shrank} shrank, {new} new, {gone} gone",
191 a.procs.len(),
192 b.procs.len()
193 ));
194 if opts.min_delta_kb > 0 {
195 out.push_str(&format!(" min |ΔRSS| {}", fmt_kb(opts.min_delta_kb)));
196 }
197 out.push('\n');
198 out.push_str(&format!(
199 "{:>8} {:<24} {:>9} {:>9} {:>9} {:>9} {}\n",
200 "PID", "COMM", "ΔRSS", "ΔPSS", "RSS now", "PSS now", "note"
201 ));
202 for r in &rows {
203 out.push_str(&format!(
204 "{:>8} {:<24} {:>9} {:>9} {:>9} {:>9} {}\n",
205 r.pid,
206 truncate(&r.comm, 24),
207 signed_kb(r.drss),
208 r.dpss.map(signed_kb).unwrap_or_else(|| "—".into()),
209 fmt_kb(r.rss_now),
210 r.pss_now.map(fmt_kb).unwrap_or_else(|| "—".into()),
211 r.note
212 ));
213 }
214 if rows.is_empty() {
215 if opts.min_delta_kb > 0 {
216 out.push_str(&format!(
217 "(no rows above min |ΔRSS| {})\n",
218 fmt_kb(opts.min_delta_kb)
219 ));
220 } else {
221 out.push_str("(no process changes)\n");
222 }
223 }
224 Ok(out)
225}
226
227fn truncate(s: &str, n: usize) -> String {
228 if s.chars().count() <= n {
229 s.to_string()
230 } else {
231 s.chars().take(n.saturating_sub(1)).collect::<String>() + "…"
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::parse_size;
238
239 #[test]
240 fn sizes_accept_suffixes_and_bare_kb() {
241 assert_eq!(parse_size("50M"), Some(51_200));
242 assert_eq!(parse_size("512k"), Some(512));
243 assert_eq!(parse_size("2G"), Some(2_097_152));
244 assert_eq!(parse_size("4096"), Some(4_096));
245 assert_eq!(parse_size(" 8m "), Some(8_192));
246 assert_eq!(parse_size("garbage"), None);
247 assert_eq!(parse_size("M"), None);
248 }
249}