Skip to main content

sys_lib/process/
usage.rs

1//! This process's resource use: memory, CPU time, threads, open files,
2//! limits, start time, and disk I/O, and the CPU sampler.
3
4use core::{ops::Sub, time::Duration};
5use std::time::{Instant, SystemTime};
6
7use super::{Limit, User};
8use crate::{Bytes, Error, Percent, Result};
9
10/// This process's parent, or `None` when it has none (an orphan adopted by
11/// init reports init) or the OS does not say. Windows: from a process
12/// snapshot, cached after the first call.
13#[must_use]
14pub fn parent_id() -> Option<u32> {
15    crate::sys::parent_id()
16}
17
18/// This process's resident memory (RSS): one read, no allocation.
19///
20/// ```
21/// println!("rss {} peak {}", sys_lib::process::memory()?, sys_lib::process::peak_memory()?);
22/// # Ok::<(), sys_lib::Error>(())
23/// ```
24///
25/// # Errors
26///
27/// `NotFound` when `/proc/self` is hidden; `Os` when the call fails.
28pub fn memory() -> Result<Bytes> {
29    crate::sys::process_memory()
30}
31
32/// The highest resident memory this process has reached.
33///
34/// # Errors
35///
36/// As [`memory`].
37pub fn peak_memory() -> Result<Bytes> {
38    crate::sys::peak_memory()
39}
40
41/// This process's memory in detail.
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
43#[non_exhaustive]
44pub struct ProcessMemory {
45    /// Resident in RAM.
46    pub resident: Bytes,
47    /// The highest resident size reached.
48    pub peak_resident: Bytes,
49    /// The virtual address space reserved.
50    pub virtual_size: Bytes,
51    /// Private (anonymous) memory; Windows: the commit charge.
52    pub private: Option<Bytes>,
53    /// Shared with other processes (file-backed and shared memory).
54    pub shared: Option<Bytes>,
55    /// Swapped out.
56    pub swapped: Option<Bytes>,
57}
58
59/// This process's memory in detail. Shipped with 0.4 so that [`info`] can
60/// carry it (D-044).
61///
62/// # Errors
63///
64/// As [`memory`].
65pub fn memory_detail() -> Result<ProcessMemory> {
66    crate::sys::memory_detail()
67}
68
69/// CPU time this process has used.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
71#[non_exhaustive]
72pub struct CpuTime {
73    /// Running user code.
74    pub user: Duration,
75    /// Running kernel code on this process's behalf.
76    pub system: Duration,
77}
78
79impl CpuTime {
80    /// User plus system time.
81    #[must_use]
82    pub fn total(&self) -> Duration {
83        self.user.saturating_add(self.system)
84    }
85}
86
87/// The CPU time this process has used so far: one system call, no
88/// allocation.
89///
90/// ```
91/// let t = sys_lib::process::cpu_time()?;
92/// println!("cpu {:?} (user {:?}, system {:?})", t.total(), t.user, t.system);
93/// # Ok::<(), sys_lib::Error>(())
94/// ```
95///
96/// # Errors
97///
98/// `Os` when the call fails.
99pub fn cpu_time() -> Result<CpuTime> {
100    crate::sys::cpu_time()
101}
102
103/// This process's threads. Linux and macOS: one read, no allocation. Windows:
104/// a system-wide thread snapshot, whose cost grows with the machine's thread
105/// count.
106///
107/// # Errors
108///
109/// As [`memory`].
110pub fn threads() -> Result<usize> {
111    crate::sys::threads()
112}
113
114/// This process's open file descriptors (Unix) or handles (Windows).
115///
116/// ```
117/// let files = sys_lib::process::limits()?.open_files;
118/// println!("open files {} of {:?}", sys_lib::process::open_files()?, files.soft);
119/// # Ok::<(), sys_lib::Error>(())
120/// ```
121///
122/// # Errors
123///
124/// As [`memory`].
125pub fn open_files() -> Result<usize> {
126    crate::sys::open_files()
127}
128
129/// This process's resource limits.
130#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
131#[non_exhaustive]
132pub struct Limits {
133    /// Open files (`RLIMIT_NOFILE`).
134    pub open_files: Limit,
135    /// Processes for this user (`RLIMIT_NPROC`); Windows: the job's active
136    /// process limit.
137    pub processes: Limit,
138    /// The address space (`RLIMIT_AS`); Windows: the job's process memory
139    /// limit.
140    pub address_space: Limit,
141    /// Core dump size (`RLIMIT_CORE`).
142    pub core_dump: Limit,
143    /// The main thread's stack (`RLIMIT_STACK`).
144    pub stack: Limit,
145}
146
147/// This process's resource limits. Windows has no `rlimit`: the job object's
148/// limits when there is one, otherwise every value `None`.
149///
150/// # Errors
151///
152/// `Os` when a call fails.
153pub fn limits() -> Result<Limits> {
154    crate::sys::limits()
155}
156
157/// When this process started.
158///
159/// # Errors
160///
161/// As [`memory`].
162pub fn started_at() -> Result<SystemTime> {
163    crate::sys::started_at()
164}
165
166/// Everything about this process, in the fewest reads.
167#[derive(Clone, Debug)]
168#[non_exhaustive]
169pub struct ProcessInfo {
170    /// [`super::id`].
171    pub id: u32,
172    /// [`parent_id`].
173    pub parent_id: Option<u32>,
174    /// [`memory_detail`].
175    pub memory: ProcessMemory,
176    /// [`cpu_time`].
177    pub cpu_time: CpuTime,
178    /// [`threads`], when read (Windows: only with `with_threads`).
179    pub threads: Option<usize>,
180    /// [`open_files`], when it could be read.
181    pub open_files: Option<usize>,
182    /// [`limits`].
183    pub limits: Limits,
184    /// [`started_at`], when it could be read.
185    pub started_at: Option<SystemTime>,
186    /// [`super::user`], when it could be read.
187    pub user: Option<User>,
188    /// [`super::is_elevated`], when it could be read.
189    pub is_elevated: Option<bool>,
190}
191
192/// What [`info_with`] reads.
193#[derive(Clone, Copy, Debug, Default)]
194#[non_exhaustive]
195pub struct InfoOptions {
196    /// Count threads on Windows, which walks a system-wide snapshot (default
197    /// false; Linux and macOS always count them).
198    pub with_threads: bool,
199}
200
201/// Everything about this process (Windows skips the thread count).
202///
203/// # Errors
204///
205/// As [`memory`] and [`cpu_time`]; the optional readings are `None` instead
206/// of failing.
207pub fn info() -> Result<ProcessInfo> {
208    info_with(InfoOptions::default())
209}
210
211/// Everything about this process, with `options`.
212///
213/// # Errors
214///
215/// As [`info`].
216pub fn info_with(options: InfoOptions) -> Result<ProcessInfo> {
217    let threads = if cfg!(windows) && !options.with_threads {
218        None
219    } else {
220        threads().ok()
221    };
222    Ok(ProcessInfo {
223        id: super::id(),
224        parent_id: parent_id(),
225        memory: memory_detail()?,
226        cpu_time: cpu_time()?,
227        threads,
228        open_files: open_files().ok(),
229        limits: limits()?,
230        started_at: started_at().ok(),
231        user: super::user().ok(),
232        is_elevated: super::is_elevated().ok(),
233    })
234}
235
236/// How much this process has read from and written to storage since it
237/// started.
238#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
239#[non_exhaustive]
240pub struct ProcessIo {
241    /// Bytes read from storage.
242    pub read: Bytes,
243    /// Bytes written to storage.
244    pub written: Bytes,
245    /// Read calls, when reported.
246    pub read_ops: Option<u64>,
247    /// Write calls, when reported.
248    pub write_ops: Option<u64>,
249    /// False where the OS counts all I/O, not only storage (Windows counts
250    /// network and device I/O too).
251    pub storage_only: bool,
252}
253
254impl Sub for ProcessIo {
255    type Output = ProcessIo;
256
257    /// The I/O between two readings, saturating at zero.
258    fn sub(self, earlier: ProcessIo) -> ProcessIo {
259        let ops = |a: Option<u64>, b: Option<u64>| Some(a?.saturating_sub(b?));
260        ProcessIo {
261            read: self.read.saturating_sub(earlier.read),
262            written: self.written.saturating_sub(earlier.written),
263            read_ops: ops(self.read_ops, earlier.read_ops),
264            write_ops: ops(self.write_ops, earlier.write_ops),
265            storage_only: self.storage_only,
266        }
267    }
268}
269
270/// How much this process has read from and written to storage, for a
271/// database's own write amplification or a backup tool's throughput. Two
272/// readings subtract; [`Rate::per`](crate::Rate::per) turns the difference
273/// into a rate.
274///
275/// ```
276/// use std::time::Duration;
277/// use sys_lib::{self as sys, Rate};
278///
279/// let before = sys::process::io()?;
280/// // ... work ...
281/// let d = sys::process::io()? - before;
282/// println!("wrote {} ({})", d.written, Rate::per(d.written, Duration::from_secs(1)));
283/// # Ok::<(), sys_lib::Error>(())
284/// ```
285///
286/// # Errors
287///
288/// `NotFound` or `PermissionDenied` when `/proc/self/io` is hidden; `Os`.
289pub fn io() -> Result<ProcessIo> {
290    crate::sys::process_io()
291}
292
293/// The share of CPU this process used over an interval.
294#[derive(Clone, Copy, Debug)]
295#[non_exhaustive]
296pub struct ProcessUsage {
297    /// Of one core, 0.0 ..= 100.0 × logical CPUs: 250.0 is two and a half
298    /// cores busy.
299    pub of_one_core: f32,
300    /// Of every logical CPU.
301    pub of_machine: Percent,
302    /// The time the values cover.
303    pub interval: Duration,
304}
305
306/// Measures this process's CPU use between samples. Owned by the caller: two
307/// monitors keep two samplers and never disturb each other. `sample` never
308/// blocks and allocates nothing.
309///
310/// ```
311/// use std::time::Duration;
312///
313/// let mut cpu = sys_lib::process::CpuSampler::new()?;
314/// std::thread::sleep(Duration::from_millis(50));
315/// let u = cpu.sample()?;
316/// println!("this process: {:.1}% of one core, {} of the machine", u.of_one_core, u.of_machine);
317/// # Ok::<(), sys_lib::Error>(())
318/// ```
319#[derive(Debug)]
320pub struct CpuSampler {
321    previous: CpuTime,
322    at: Instant,
323}
324
325impl CpuSampler {
326    /// Takes the first reading.
327    ///
328    /// # Errors
329    ///
330    /// As [`cpu_time`].
331    pub fn new() -> Result<CpuSampler> {
332        Ok(CpuSampler {
333            previous: cpu_time()?,
334            at: Instant::now(),
335        })
336    }
337
338    /// This process's CPU use since the previous sample.
339    ///
340    /// # Errors
341    ///
342    /// `TooSoon` when no time passed since the previous sample.
343    pub fn sample(&mut self) -> Result<ProcessUsage> {
344        let now = cpu_time()?;
345        let at = Instant::now();
346        let interval = at.duration_since(self.at);
347        if interval.is_zero() {
348            return Err(Error::TooSoon {
349                elapsed: interval,
350                minimum: Duration::from_millis(1),
351            });
352        }
353        let used = now.total().saturating_sub(self.previous.total());
354        let cpus = crate::cpu::logical() as f32;
355        let of_one_core = (used.as_secs_f64() / interval.as_secs_f64() * 100.0) as f32;
356        let of_one_core = of_one_core.clamp(0.0, 100.0 * cpus);
357        self.previous = now;
358        self.at = at;
359        Ok(ProcessUsage {
360            of_one_core,
361            of_machine: Percent::from_value(of_one_core / cpus),
362            interval,
363        })
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    #[test]
372    fn test_process_readings_live() {
373        let rss = memory().unwrap();
374        assert!(rss.raw() > 0);
375        assert!(peak_memory().unwrap() >= rss || cfg!(windows));
376        let d = memory_detail().unwrap();
377        assert!(d.virtual_size >= d.resident || d.virtual_size.raw() == 0);
378        let t = cpu_time().unwrap();
379        assert!(t.total() >= t.user);
380        assert!(threads().unwrap() >= 1);
381        assert!(open_files().unwrap() >= 1);
382        let l = limits().unwrap();
383        if let (Some(s), Some(h)) = (l.open_files.soft, l.open_files.hard) {
384            assert!(s <= h);
385        }
386        let started = started_at().unwrap();
387        assert!(started <= SystemTime::now());
388        let info = info().unwrap();
389        assert_eq!(info.id, super::super::id());
390        let io = io().unwrap();
391        assert_eq!((io - io).read, Bytes::ZERO);
392    }
393
394    #[test]
395    fn test_process_cpu_sampler_bounded() {
396        let mut s = CpuSampler::new().unwrap();
397        let mut x = 0u64;
398        let start = Instant::now();
399        while start.elapsed() < Duration::from_millis(30) {
400            x = x.wrapping_mul(31).wrapping_add(7);
401        }
402        std::hint::black_box(x);
403        let u = s.sample().unwrap();
404        assert!(u.of_one_core >= 0.0 && u.of_one_core <= 100.0 * crate::cpu::logical() as f32);
405        assert!(u.of_machine <= Percent::FULL);
406    }
407
408    #[test]
409    fn test_process_io_subtracts_saturating() {
410        let a = ProcessIo {
411            read: Bytes::new(10),
412            written: Bytes::new(20),
413            read_ops: Some(3),
414            write_ops: None,
415            storage_only: true,
416        };
417        let b = ProcessIo {
418            read: Bytes::new(15),
419            written: Bytes::new(5),
420            read_ops: Some(5),
421            write_ops: Some(1),
422            storage_only: true,
423        };
424        let d = b - a;
425        assert_eq!(
426            (d.read.raw(), d.written.raw(), d.read_ops, d.write_ops),
427            (5, 0, Some(2), None)
428        );
429    }
430}