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/// match sys::process::io() {
280/// Ok(before) => {
281/// // ... work ...
282/// let d = sys::process::io()? - before;
283/// println!("wrote {} ({})", d.written, Rate::per(d.written, Duration::from_secs(1)));
284/// }
285/// // FreeBSD and iOS do not count this process's bytes.
286/// Err(e) if e.is_unavailable() => {}
287/// Err(e) => return Err(e),
288/// }
289/// # Ok::<(), sys_lib::Error>(())
290/// ```
291///
292/// # Errors
293///
294/// `NotFound` or `PermissionDenied` when `/proc/self/io` is hidden;
295/// `Unsupported` on FreeBSD (it counts block operations, not bytes) and iOS;
296/// `Os`.
297pub fn io() -> Result<ProcessIo> {
298 crate::sys::process_io()
299}
300
301/// The share of CPU this process used over an interval.
302#[derive(Clone, Copy, Debug)]
303#[non_exhaustive]
304pub struct ProcessUsage {
305 /// Of one core, 0.0 ..= 100.0 × logical CPUs: 250.0 is two and a half
306 /// cores busy.
307 pub of_one_core: f32,
308 /// Of every logical CPU.
309 pub of_machine: Percent,
310 /// The time the values cover.
311 pub interval: Duration,
312}
313
314/// Measures this process's CPU use between samples. Owned by the caller: two
315/// monitors keep two samplers and never disturb each other. `sample` never
316/// blocks and allocates nothing.
317///
318/// ```
319/// use std::time::Duration;
320///
321/// let mut cpu = sys_lib::process::CpuSampler::new()?;
322/// std::thread::sleep(Duration::from_millis(50));
323/// let u = cpu.sample()?;
324/// println!("this process: {:.1}% of one core, {} of the machine", u.of_one_core, u.of_machine);
325/// # Ok::<(), sys_lib::Error>(())
326/// ```
327#[derive(Debug)]
328pub struct CpuSampler {
329 previous: CpuTime,
330 at: Instant,
331}
332
333impl CpuSampler {
334 /// Takes the first reading.
335 ///
336 /// # Errors
337 ///
338 /// As [`cpu_time`].
339 pub fn new() -> Result<CpuSampler> {
340 Ok(CpuSampler {
341 previous: cpu_time()?,
342 at: Instant::now(),
343 })
344 }
345
346 /// This process's CPU use since the previous sample.
347 ///
348 /// # Errors
349 ///
350 /// `TooSoon` when no time passed since the previous sample.
351 pub fn sample(&mut self) -> Result<ProcessUsage> {
352 let now = cpu_time()?;
353 let at = Instant::now();
354 let interval = at.duration_since(self.at);
355 if interval.is_zero() {
356 return Err(Error::TooSoon {
357 elapsed: interval,
358 minimum: Duration::from_millis(1),
359 });
360 }
361 let used = now.total().saturating_sub(self.previous.total());
362 let cpus = crate::cpu::logical() as f32;
363 let of_one_core = (used.as_secs_f64() / interval.as_secs_f64() * 100.0) as f32;
364 let of_one_core = of_one_core.clamp(0.0, 100.0 * cpus);
365 self.previous = now;
366 self.at = at;
367 Ok(ProcessUsage {
368 of_one_core,
369 of_machine: Percent::from_value(of_one_core / cpus),
370 interval,
371 })
372 }
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn test_process_readings_live() {
381 let rss = memory().unwrap();
382 assert!(rss.raw() > 0);
383 assert!(peak_memory().unwrap() >= rss || cfg!(windows));
384 let d = memory_detail().unwrap();
385 assert!(d.virtual_size >= d.resident || d.virtual_size.raw() == 0);
386 let t = cpu_time().unwrap();
387 assert!(t.total() >= t.user);
388 assert!(threads().unwrap() >= 1);
389 assert!(open_files().unwrap() >= 1);
390 let l = limits().unwrap();
391 if let (Some(s), Some(h)) = (l.open_files.soft, l.open_files.hard) {
392 assert!(s <= h);
393 }
394 let started = started_at().unwrap();
395 assert!(started <= SystemTime::now());
396 let info = info().unwrap();
397 assert_eq!(info.id, super::super::id());
398 // FreeBSD and iOS do not count the bytes.
399 match io() {
400 Ok(io) => assert_eq!((io - io).read, Bytes::ZERO),
401 Err(e) => assert!(e.is_unavailable(), "{e}"),
402 }
403 }
404
405 #[test]
406 fn test_process_cpu_sampler_bounded() {
407 let mut s = CpuSampler::new().unwrap();
408 let mut x = 0u64;
409 let start = Instant::now();
410 while start.elapsed() < Duration::from_millis(30) {
411 x = x.wrapping_mul(31).wrapping_add(7);
412 }
413 std::hint::black_box(x);
414 let u = s.sample().unwrap();
415 assert!(u.of_one_core >= 0.0 && u.of_one_core <= 100.0 * crate::cpu::logical() as f32);
416 assert!(u.of_machine <= Percent::FULL);
417 }
418
419 #[test]
420 fn test_process_io_subtracts_saturating() {
421 let a = ProcessIo {
422 read: Bytes::new(10),
423 written: Bytes::new(20),
424 read_ops: Some(3),
425 write_ops: None,
426 storage_only: true,
427 };
428 let b = ProcessIo {
429 read: Bytes::new(15),
430 written: Bytes::new(5),
431 read_ops: Some(5),
432 write_ops: Some(1),
433 storage_only: true,
434 };
435 let d = b - a;
436 assert_eq!(
437 (d.read.raw(), d.written.raw(), d.read_ops, d.write_ops),
438 (5, 0, Some(2), None)
439 );
440 }
441}