Skip to main content

all_smi/device/process_list/
refresh_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//! One tick of the local process pass on Linux (issue #428).
16//!
17//! The collector refreshes the tracked top-500 PIDs every tick and the whole
18//! table every fifth tick. Here the two kinds of tick take different paths:
19//!
20//! * **Selective tick**: sysinfo is not called for processes at all. The
21//!   sampler reads the tracked PIDs, and the cache is walked directly: a
22//!   tracked row takes its CPU percent, memory, state and run time from its
23//!   sample, leaves when the sampler says the process is gone (or that the
24//!   PID now belongs to a different process), and keeps its values when the
25//!   kernel would not answer. Untracked rows keep the values of the last
26//!   full tick, as they did when sysinfo's map was walked instead. sysinfo's
27//!   map is deliberately not walked: it still holds every tracked PID that
28//!   has died since the last full tick, and a walk would put those rows
29//!   back.
30//! * **Full tick**: sysinfo refreshes everything, because it is what
31//!   discovers new processes and supplies the static metadata (name, user,
32//!   parent, start time, command). The sampler then reads every PID sysinfo
33//!   holds, and every row's dynamic fields come from its sample, so CPU
34//!   percent for a process outside the tracked set is its task-time delta
35//!   over the five ticks since its baseline, not sysinfo's five-tick delta
36//!   over a one-tick interval (`sampler_linux` explains the defect). A row
37//!   whose sample is unreadable takes sysinfo's values.
38//!
39//! A row whose start time changed under the same PID is replaced (full
40//! tick) or dropped until the next full tick rediscovers it (selective
41//! tick), so a reused PID never shows the previous process's name.
42
43use std::collections::{HashMap, HashSet};
44use std::time::{Duration, Instant};
45
46use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
47
48use super::sampler_linux::{ProcessSample, ProcessSampler, Sampled};
49use super::{mark_gpu, new_entry_from_sysinfo, refresh_entry_from_sysinfo};
50use crate::device::types::ProcessInfo;
51
52/// How long the parts of one tick took, for `perf_tick_stages`.
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
54pub struct ProcessRefreshTimings {
55    /// sysinfo's `refresh_processes_specifics` (full ticks only) plus
56    /// `refresh_memory`.
57    pub sysinfo: Duration,
58    /// The sampler's pass over the tracked PIDs (selective) or every PID
59    /// sysinfo holds (full).
60    pub sampler: Duration,
61    /// Folding the samples and sysinfo's map into the cache.
62    pub cache: Duration,
63}
64
65/// The shared process-row refresh kind (issue #504): CPU, memory, the user
66/// and the command line once, no threads. sysinfo still recomputes every
67/// process's `cpu_usage` from one global interval on this call (see
68/// `sampler_linux`), which is why the sampler's values override it.
69fn refresh_kind() -> ProcessRefreshKind {
70    super::process_row_refresh_kind()
71}
72
73/// Run the process pass of one tick and return the rows for it.
74///
75/// `full` asks for a full tick; an empty `tracked` set forces one, as it
76/// always did, since there is nothing to sample selectively.
77pub fn refresh_processes(
78    system: &mut System,
79    sampler: &mut ProcessSampler,
80    tracked: &[Pid],
81    full: bool,
82    gpu_pids: &HashSet<u32>,
83    cache: &mut HashMap<u32, ProcessInfo>,
84) -> (Vec<ProcessInfo>, ProcessRefreshTimings) {
85    let mut timings = ProcessRefreshTimings::default();
86    let rows = if full || tracked.is_empty() {
87        let started = Instant::now();
88        system.refresh_processes_specifics(ProcessesToUpdate::All, true, refresh_kind());
89        system.refresh_memory();
90        timings.sysinfo = started.elapsed();
91
92        let started = Instant::now();
93        let samples = sampler.sample(system.processes().keys().map(|pid| pid.as_u32()));
94        timings.sampler = started.elapsed();
95
96        let started = Instant::now();
97        let rows = update_cache_full(system, gpu_pids, cache, &samples);
98        timings.cache = started.elapsed();
99        rows
100    } else {
101        let started = Instant::now();
102        let samples = sampler.sample(tracked.iter().map(|pid| pid.as_u32()));
103        timings.sampler = started.elapsed();
104
105        let started = Instant::now();
106        system.refresh_memory();
107        timings.sysinfo = started.elapsed();
108
109        let started = Instant::now();
110        let rows = update_cache_selective(system.total_memory(), gpu_pids, cache, &samples);
111        timings.cache = started.elapsed();
112        rows
113    };
114    sampler.retain(|pid| cache.contains_key(&pid));
115    (rows, timings)
116}
117
118/// Full tick: walk sysinfo's freshly refreshed map, creating rows for new
119/// processes and taking every row's dynamic fields from its sample.
120fn update_cache_full(
121    system: &System,
122    gpu_pids: &HashSet<u32>,
123    cache: &mut HashMap<u32, ProcessInfo>,
124    samples: &HashMap<u32, Sampled>,
125) -> Vec<ProcessInfo> {
126    let mut seen_pids: HashSet<u32> = HashSet::with_capacity(system.processes().len());
127    let total_memory = system.total_memory();
128
129    for (pid, process) in system.processes() {
130        let pid_u32 = pid.as_u32();
131        let sample = match samples.get(&pid_u32) {
132            // Exited between sysinfo's refresh and the sampler's pass: not
133            // seen, so the row goes now rather than one tick later.
134            Some(Sampled::Gone) => continue,
135            Some(Sampled::Live(sample)) => Some(sample),
136            Some(Sampled::Unreadable) | None => None,
137        };
138        seen_pids.insert(pid_u32);
139        let uses_gpu = gpu_pids.contains(&pid_u32);
140
141        let same_process = cache
142            .get(&pid_u32)
143            .is_some_and(|cached| started_at(cached, process.start_time()));
144        if let Some(cached) = cache.get_mut(&pid_u32).filter(|_| same_process) {
145            match sample {
146                Some(sample) => apply_sample(cached, sample, total_memory),
147                None => refresh_entry_from_sysinfo(cached, process, total_memory),
148            }
149            mark_gpu(cached, uses_gpu);
150        } else {
151            // New, or a reused PID whose row still described the previous
152            // process: build it from sysinfo's static metadata.
153            let mut entry = new_entry_from_sysinfo(pid_u32, process, total_memory, uses_gpu);
154            if let Some(sample) = sample {
155                apply_sample(&mut entry, sample, total_memory);
156            }
157            cache.insert(pid_u32, entry);
158        }
159    }
160
161    cache.retain(|pid, _| seen_pids.contains(pid));
162    rows_of(cache)
163}
164
165/// Selective tick: walk the cache, applying the tracked PIDs' samples.
166fn update_cache_selective(
167    total_memory: u64,
168    gpu_pids: &HashSet<u32>,
169    cache: &mut HashMap<u32, ProcessInfo>,
170    samples: &HashMap<u32, Sampled>,
171) -> Vec<ProcessInfo> {
172    cache.retain(|pid, cached| {
173        match samples.get(pid) {
174            Some(Sampled::Gone) => return false,
175            Some(Sampled::Live(sample)) => {
176                if !started_at(cached, sample.start_time) {
177                    // The PID belongs to a different process now; the next
178                    // full tick creates its row with the right metadata.
179                    return false;
180                }
181                apply_sample(cached, sample, total_memory);
182            }
183            // The kernel would not answer, or the row is not tracked this
184            // tick: its values stand until the next full tick.
185            Some(Sampled::Unreadable) | None => {}
186        }
187        mark_gpu(cached, gpu_pids.contains(pid));
188        true
189    });
190    rows_of(cache)
191}
192
193/// Whether `cached` describes the process that started at `start_time`.
194///
195/// The cache stores the start time as sysinfo's `start_time()` formatted,
196/// so a row that was created from sysinfo compares equal to sysinfo's value
197/// and to the sampler's, which is the same `btime + starttime / clk_tck`.
198fn started_at(cached: &ProcessInfo, start_time: u64) -> bool {
199    cached.start_time.parse::<u64>().ok() == Some(start_time)
200}
201
202/// The dynamic fields of one row, from its sample.
203///
204/// A sample without a CPU reading (first sighting) leaves the row's CPU
205/// percent alone: 0 on a row just built from sysinfo, which is sysinfo's own
206/// value for a process it just discovered, and the previous reading on an
207/// existing row. No value is invented either way.
208fn apply_sample(row: &mut ProcessInfo, sample: &ProcessSample, total_memory: u64) {
209    if let Some(cpu_percent) = sample.cpu_percent {
210        row.cpu_percent = cpu_percent;
211    }
212    row.memory_rss = sample.memory_rss;
213    row.memory_vms = sample.memory_vms;
214    row.memory_percent = (sample.memory_rss as f64 / total_memory as f64) * 100.0;
215    if row.state != sample.state {
216        row.state = sample.state.to_string();
217    }
218    row.cpu_time = sample.run_time;
219}
220
221fn rows_of(cache: &HashMap<u32, ProcessInfo>) -> Vec<ProcessInfo> {
222    let mut rows: Vec<ProcessInfo> = cache.values().cloned().collect();
223    rows.sort_by_key(|row| row.pid);
224    rows
225}