all_smi/device/process_list/sampler_linux.rs
1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Per-process CPU, memory, state and run time on Linux, read in-process
16//! from `/proc/<pid>/stat` instead of sysinfo's per-tick refresh (issue
17//! #428).
18//!
19//! The local collector refreshes the tracked top-500 PIDs every tick and
20//! every PID every fifth tick. On Linux, sysinfo 0.39.6 makes a process
21//! outside the tracked set read about five times its real CPU percent:
22//!
23//! 1. **One global interval for every process.** `update_procs_cpu`
24//! (sysinfo, `src/unix/linux/system.rs:188-207`) recomputes `cpu_usage`
25//! for *every* process in its map on every refresh call, dividing each
26//! process's task-time delta by the total CPU tick delta since the
27//! previous refresh call divided by the CPU count (`compute_cpu_usage`,
28//! `src/unix/linux/process.rs:346-361`). `set_time`
29//! (`process.rs:363-368`) moves a process's own baseline only when that
30//! process was actually refreshed, so a process outside the tracked set
31//! keeps a five-tick task-time delta while the divisor is a one-tick
32//! interval. Unlike macOS this happens on every tick, not only on full
33//! ticks, because the recomputation loop also covers processes the
34//! current call did not refresh: their five-tick delta keeps being
35//! divided by fresh one-tick intervals. The only guard is the
36//! `cpus * 100` clamp, which does nothing below the ceiling. That
37//! inflated number is the sort key for the displayed list, so unrelated
38//! processes jump onto the screen, and the inflated ranking decides the
39//! next tick's tracked set. Windows is immune (it keeps per-process
40//! copies of the global times, `src/windows/process.rs:1049-1105`);
41//! macOS has the same class of defect through a different path and is
42//! fixed natively in #427.
43//!
44//! This sampler keeps, per PID, the previous `utime + stime` and the
45//! `CLOCK_MONOTONIC` time at which it was read, and reports CPU percent as
46//! the task-time delta over that PID's own elapsed wall time, per core:
47//! `used_ticks / clk_tck / elapsed_seconds * 100`. A PID it has not seen
48//! before reports no CPU reading, as sysinfo does for a process it just
49//! discovered (`compute_cpu_usage` requires a non-zero previous total); a
50//! counter that does not move reads 0, which is the deliberate difference
51//! from sysinfo's stale value. Memory comes from the same `/proc/<pid>/stat`
52//! fields sysinfo reads (`rss` times the page size, `vsize` bytes), the
53//! state code is derived by the same rule sysinfo's `ProcessStatus::from`
54//! applies (see [`state_code`]), and `start_time` is `/proc/stat`'s `btime`
55//! plus `starttime / clk_tck`, as sysinfo's `start_time()`, with `run_time`
56//! measured the way sysinfo's `run_time()` measures it, against
57//! `/proc/uptime`.
58//!
59//! What the sampler does *not* do: discover processes or supply their
60//! static metadata (name, user, parent, command). sysinfo still does that
61//! on every fifth tick; see `refresh_linux` for how the two are combined.
62
63use std::collections::HashMap;
64
65/// One PID's readings for this tick.
66#[derive(Clone, Debug, PartialEq)]
67pub struct ProcessSample {
68 /// Task-time delta over the sampler's elapsed time for this PID, as a
69 /// percentage of one core. `None` on the first sighting of a PID (or of
70 /// a reused PID), when there is nothing to take a delta against.
71 pub cpu_percent: Option<f64>,
72 /// `rss` (field 24) times the page size, bytes.
73 pub memory_rss: u64,
74 /// `vsize` (field 23), bytes.
75 pub memory_vms: u64,
76 /// Single-letter state code as the process table shows it.
77 pub state: &'static str,
78 /// Seconds since the process started, as sysinfo's `run_time()`.
79 pub run_time: u64,
80 /// `/proc/stat`'s `btime` plus `starttime / clk_tck`, epoch seconds:
81 /// what tells a reused PID apart from the process that had it before.
82 pub start_time: u64,
83}
84
85/// What sampling one PID found.
86#[derive(Clone, Debug, PartialEq)]
87pub enum Sampled {
88 /// The process is alive and readable.
89 Live(ProcessSample),
90 /// The kernel would not say (`EPERM`, a malformed or short read). The
91 /// process may be alive; a caller keeps whatever it had.
92 Unreadable,
93 /// The kernel has no such process (`ENOENT`, an empty read): exited.
94 Gone,
95}
96
97/// Where a PID's counters stood when it was last sampled.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99struct Baseline {
100 /// `starttime` (field 22), clock ticks since boot; a different value
101 /// under the same PID means a new process.
102 start_time: u64,
103 /// `utime + stime` (fields 14 + 15), clock ticks.
104 task_time: u64,
105 /// `CLOCK_MONOTONIC` nanoseconds right before the stat was read.
106 sampled_at: u64,
107}
108
109/// The system constants the sampler's arithmetic needs, separated from the
110/// `/proc` reads so tests can feed fixed values.
111#[derive(Clone, Copy, Debug)]
112struct Constants {
113 /// `sysconf(_SC_CLK_TCK)`, clock ticks per second.
114 clk_tck: u64,
115 /// `sysconf(_SC_PAGESIZE)`, bytes.
116 page_size: u64,
117 /// `/proc/stat`'s `btime`, epoch seconds, the clock sysinfo's Linux
118 /// `start_time()` adds to a process's start time.
119 btime: u64,
120}
121
122impl Constants {
123 fn read(btime: u64) -> Self {
124 // SAFETY: sysconf takes no pointers and has no preconditions; both
125 // constants are always valid on Linux. A failure reads as -1, which
126 // the `max` turns into a division-safe 1.
127 Constants {
128 clk_tck: unsafe { libc::sysconf(libc::_SC_CLK_TCK) }.max(1) as u64,
129 page_size: unsafe { libc::sysconf(libc::_SC_PAGESIZE) }.max(1) as u64,
130 btime,
131 }
132 }
133}
134
135/// The kernel readings for one PID, separated from the arithmetic so the
136/// latter can be tested without a kernel.
137#[derive(Clone, Copy, Debug)]
138struct Readings {
139 stat: Result<Stat, StatError>,
140}
141
142/// One process's `/proc/<pid>/stat` fields.
143#[derive(Clone, Copy, Debug)]
144struct Stat {
145 state: Option<char>,
146 /// `utime + stime`, clock ticks.
147 task_time: u64,
148 /// `starttime`, clock ticks since boot.
149 start_time_raw: u64,
150 /// `vsize`, bytes.
151 vsize: u64,
152 /// `rss`, pages.
153 rss_pages: u64,
154}
155
156/// Why a `/proc/<pid>/stat` read found nothing usable.
157#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158enum StatError {
159 /// `ENOENT` or an empty read: the process exited.
160 Gone,
161 /// `EPERM`, or a malformed or short read: the process may be alive.
162 Unreadable,
163}
164
165/// Per-PID baselines and the sampling that updates them.
166#[derive(Debug, Default)]
167pub struct ProcessSampler {
168 baselines: HashMap<u32, Baseline>,
169 /// `/proc/stat`'s boot time, read on the first sample; it only changes
170 /// on reboot.
171 btime: Option<u64>,
172}
173
174impl ProcessSampler {
175 pub fn new() -> Self {
176 Self::default()
177 }
178
179 /// Sample every PID in `pids`, updating its baseline.
180 ///
181 /// Each PID costs one `/proc/<pid>/stat` read, the same file sysinfo
182 /// reads for a refreshed process, so the pass over the tracked 500 is
183 /// 500 small reads instead of sysinfo's O(table) refresh.
184 pub fn sample<I: IntoIterator<Item = u32>>(&mut self, pids: I) -> HashMap<u32, Sampled> {
185 let btime = *self.btime.get_or_insert_with(read_btime);
186 let constants = Constants::read(btime);
187 let uptime = uptime_secs();
188 pids.into_iter()
189 .map(|pid| {
190 let sampled_at = mono_now();
191 let readings = Readings::read(pid);
192 (
193 pid,
194 self.fold(pid, readings, sampled_at, uptime, &constants),
195 )
196 })
197 .collect()
198 }
199
200 /// Drop the baselines of PIDs `keep` rejects, so they do not accumulate
201 /// for processes that have left the cache.
202 pub fn retain(&mut self, mut keep: impl FnMut(u32) -> bool) {
203 self.baselines.retain(|pid, _| keep(*pid));
204 }
205
206 /// Whether `pid` has a baseline.
207 #[cfg(test)]
208 pub(super) fn contains(&self, pid: u32) -> bool {
209 self.baselines.contains_key(&pid)
210 }
211
212 /// Number of PIDs with a baseline.
213 #[cfg(test)]
214 pub(super) fn len(&self) -> usize {
215 self.baselines.len()
216 }
217
218 #[cfg(test)]
219 pub(super) fn is_empty(&self) -> bool {
220 self.baselines.is_empty()
221 }
222
223 /// Fold one PID's readings into its baseline and produce its sample.
224 fn fold(
225 &mut self,
226 pid: u32,
227 readings: Readings,
228 sampled_at: u64,
229 uptime: u64,
230 constants: &Constants,
231 ) -> Sampled {
232 let stat = match readings.stat {
233 Ok(stat) => stat,
234 Err(StatError::Gone) => {
235 self.baselines.remove(&pid);
236 return Sampled::Gone;
237 }
238 Err(StatError::Unreadable) => return Sampled::Unreadable,
239 };
240 let previous = self.baselines.get(&pid).copied();
241 // A different start time under the same PID is a new process: its
242 // counters have nothing to do with the old baseline.
243 let previous = previous.filter(|baseline| baseline.start_time == stat.start_time_raw);
244 let cpu_percent = cpu_percent(
245 previous.map(|baseline| (baseline.task_time, baseline.sampled_at)),
246 stat.task_time,
247 sampled_at,
248 constants.clk_tck,
249 );
250 self.baselines.insert(
251 pid,
252 Baseline {
253 start_time: stat.start_time_raw,
254 task_time: stat.task_time,
255 sampled_at,
256 },
257 );
258 Sampled::Live(ProcessSample {
259 cpu_percent,
260 memory_rss: stat.rss_pages.saturating_mul(constants.page_size),
261 memory_vms: stat.vsize,
262 state: state_code(stat.state),
263 run_time: uptime.saturating_sub(stat.start_time_raw / constants.clk_tck),
264 start_time: constants
265 .btime
266 .saturating_add(stat.start_time_raw / constants.clk_tck),
267 })
268 }
269}
270
271impl Readings {
272 fn read(pid: u32) -> Self {
273 Readings {
274 stat: read_stat(pid),
275 }
276 }
277}
278
279/// The `/proc/<pid>/stat` fields the sampler keeps, indexed after the `comm`
280/// parentheses (`proc(5)`): 0 state, 11 utime, 12 stime, 19 starttime,
281/// 20 vsize, 21 rss.
282const STATE: usize = 0;
283const UTIME: usize = 11;
284const STIME: usize = 12;
285const START_TIME: usize = 19;
286const VSIZE: usize = 20;
287const RSS: usize = 21;
288
289/// One `/proc/<pid>/stat` read.
290fn read_stat(pid: u32) -> Result<Stat, StatError> {
291 let data = std::fs::read_to_string(format!("/proc/{pid}/stat")).map_err(|error| {
292 if error.kind() == std::io::ErrorKind::NotFound {
293 StatError::Gone
294 } else {
295 StatError::Unreadable
296 }
297 })?;
298 if data.is_empty() {
299 return Err(StatError::Gone);
300 }
301 parse_stat(&data).ok_or(StatError::Unreadable)
302}
303
304/// Parse the stat fields out of one `/proc/<pid>/stat` read.
305fn parse_stat(data: &str) -> Option<Stat> {
306 // The process name is in parentheses and may itself contain spaces and
307 // parens, so the fields start after the last `)`, the way
308 // `get_process_priority_nice` in `process_list.rs` already splits it.
309 let after_name = data.rfind(')')? + 1;
310 let fields: Vec<&str> = data[after_name..].split_whitespace().collect();
311 if fields.len() <= RSS {
312 return None;
313 }
314 Some(Stat {
315 state: fields[STATE].chars().next(),
316 task_time: fields[UTIME]
317 .parse::<u64>()
318 .unwrap_or(0)
319 .saturating_add(fields[STIME].parse::<u64>().unwrap_or(0)),
320 start_time_raw: fields[START_TIME].parse().unwrap_or(0),
321 vsize: fields[VSIZE].parse().unwrap_or(0),
322 rss_pages: fields[RSS].parse().unwrap_or(0),
323 })
324}
325
326/// CPU percent of one core: the task-time delta (clock ticks) over the
327/// elapsed time since the previous sample, scaled by `clk_tck` ticks per
328/// second. Per core, so it can exceed 100, as sysinfo's can.
329///
330/// `None` without a previous sample or when no time has elapsed; a counter
331/// that has not moved reads `Some(0.0)`.
332fn cpu_percent(
333 previous: Option<(u64, u64)>,
334 task_time: u64,
335 sampled_at: u64,
336 clk_tck: u64,
337) -> Option<f64> {
338 let (previous_task_time, previous_at) = previous?;
339 let elapsed = sampled_at
340 .checked_sub(previous_at)
341 .filter(|elapsed| *elapsed > 0)?;
342 let used = task_time.saturating_sub(previous_task_time);
343 let seconds = used as f64 / clk_tck as f64;
344 Some(seconds / (elapsed as f64 / 1e9) * 100.0)
345}
346
347/// The single-letter state the process table shows, by the rule sysinfo's
348/// `ProcessStatus::from(char)` applies on Linux
349/// (`src/unix/linux/process.rs:37-52`), mapped through the same table
350/// `convert_process_state` uses for the `Display` strings.
351///
352/// `R`, `S`, `I`, `D`, `Z`, `T` and `X` (and `x`) map to their own letters,
353/// while `t` (Tracing), `K` (Wakekill), `W` (Waking), `P` (Parked) and
354/// anything else map through sysinfo's `Display` strings to `?`.
355fn state_code(state: Option<char>) -> &'static str {
356 match state {
357 Some('R') => "R",
358 Some('S') => "S",
359 Some('I') => "I",
360 Some('D') => "D",
361 Some('Z') => "Z",
362 Some('T') => "T",
363 Some('X') | Some('x') => "X",
364 _ => "?",
365 }
366}
367
368fn mono_now() -> u64 {
369 let mut now = libc::timespec {
370 tv_sec: 0,
371 tv_nsec: 0,
372 };
373 // SAFETY: `now` is a writable timespec; the call fills it on success and
374 // it starts zeroed, so a failure reads as zero elapsed time.
375 unsafe {
376 libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
377 }
378 now.tv_sec as u64 * 1_000_000_000 + now.tv_nsec as u64
379}
380
381/// Seconds since boot from `/proc/uptime`, the clock sysinfo's `run_time()`
382/// measures against (`src/unix/linux/system.rs:349-357`).
383fn uptime_secs() -> u64 {
384 let Ok(uptime) = std::fs::read_to_string("/proc/uptime") else {
385 return 0;
386 };
387 uptime
388 .split('.')
389 .next()
390 .and_then(|secs| secs.parse().ok())
391 .unwrap_or(0)
392}
393
394/// Boot time from `/proc/stat`'s `btime` line, the clock sysinfo's Linux
395/// `start_time()` adds to a process's start time.
396fn read_btime() -> u64 {
397 let Ok(stat) = std::fs::read_to_string("/proc/stat") else {
398 return 0;
399 };
400 for line in stat.lines() {
401 if line.starts_with("btime") {
402 return line
403 .split_whitespace()
404 .nth(1)
405 .and_then(|secs| secs.parse().ok())
406 .unwrap_or(0);
407 }
408 }
409 0
410}
411
412#[cfg(test)]
413#[path = "sampler_linux/tests.rs"]
414mod tests;