sys_lib/probe.rs
1//! Explicit roots for monitoring agents (Linux).
2//!
3//! A monitoring agent in a container that has the host's root filesystem
4//! mounted (say at `/host`, with the host's `/proc` and `/sys` under it) reads
5//! the host's values through an explicit root. gopsutil offers the same
6//! through the `HOST_PROC` and `HOST_SYS` environment variables; sys-lib offers
7//! it only as a constructor in code, so no deployment can redirect a normal
8//! program's readings through its environment (threat T4). The readings are
9//! the same code the rest of the crate uses on `/`.
10//!
11//! The host's mounts and network counters are read through its process 1
12//! (`/proc/1/mountinfo`, `/proc/1/net/dev`), which is the host's view when the
13//! agent shares the host's process namespace (`hostPID`); otherwise they are
14//! the agent's own. CPU, memory, disk I/O, load, and uptime are system-wide.
15//!
16//! ```no_run
17//! # #[cfg(target_os = "linux")]
18//! # fn main() -> sys_lib::Result<()> {
19//! use sys_lib::probe::Probe;
20//!
21//! let host = Probe::with_root("/host")?;
22//! let m = host.memory()?;
23//! println!("host memory {} free of {}", m.free, m.total);
24//! let mut cpu = host.cpu_sampler()?;
25//! std::thread::sleep(std::time::Duration::from_secs(1));
26//! println!("host cpu {}", cpu.sample()?.used());
27//! # Ok(())
28//! # }
29//! # #[cfg(not(target_os = "linux"))]
30//! # fn main() {}
31//! ```
32
33use core::time::Duration;
34use std::{
35 path::{Path, PathBuf},
36 sync::Arc,
37};
38
39use crate::{
40 Error, Result, cpu,
41 disk::{self, Disk, ListOptions},
42 host::Processes,
43 linux::{self as tree, Root},
44 mem::{self, MemWant},
45 net,
46 origin::{Host, Origin},
47};
48
49/// The most processes counted (T7).
50const MAX_PROCESSES: u64 = 4_000_000;
51
52/// A host's `/proc` and `/sys`, read through an explicit root.
53#[derive(Clone, Debug)]
54pub struct Probe {
55 host: Arc<Host>,
56 base: PathBuf,
57 mountinfo: &'static str,
58}
59
60impl Probe {
61 /// A probe of the host whose root filesystem is mounted at `root`.
62 ///
63 /// # Errors
64 ///
65 /// `NotFound` when `root` has no readable `proc/stat` (the host's `/proc`
66 /// is not mounted there).
67 pub fn with_root(root: impl Into<PathBuf>) -> Result<Probe> {
68 let base: PathBuf = root.into();
69 let tree = Root::at(&base);
70 if tree.text("/proc/stat").is_none() {
71 return Err(Error::NotFound {
72 what: "probe root",
73 source: "<root>/proc/stat",
74 });
75 }
76 let net_dev = if tree.exists("/proc/1/net/dev") {
77 "/proc/1/net/dev"
78 } else {
79 "/proc/net/dev"
80 };
81 let mountinfo = if tree.exists("/proc/1/mountinfo") {
82 "/proc/1/mountinfo"
83 } else {
84 "/proc/self/mountinfo"
85 };
86 Ok(Probe {
87 host: Arc::new(Host {
88 root: tree,
89 net_dev,
90 }),
91 base,
92 mountinfo,
93 })
94 }
95
96 fn root(&self) -> &Root {
97 &self.host.root
98 }
99
100 fn origin(&self) -> Origin {
101 Origin::host(Arc::clone(&self.host))
102 }
103
104 /// The host's memory, without any cgroup limit.
105 ///
106 /// # Errors
107 ///
108 /// As [`mem::snapshot`].
109 pub fn memory(&self) -> Result<mem::Memory> {
110 tree::mem::read(self.root(), None, false, MemWant::ALL).map(mem::from_raw)
111 }
112
113 /// A CPU sampler over the host's counters.
114 ///
115 /// # Errors
116 ///
117 /// As [`cpu::Sampler::new`].
118 pub fn cpu_sampler(&self) -> Result<cpu::Sampler> {
119 cpu::Sampler::from(self.origin())
120 }
121
122 /// The host's load average.
123 ///
124 /// # Errors
125 ///
126 /// As [`cpu::load`].
127 pub fn load(&self) -> Result<Option<cpu::Load>> {
128 tree::stat::load(self.root())
129 }
130
131 /// The host's uptime.
132 ///
133 /// # Errors
134 ///
135 /// As [`host::uptime`](crate::host::uptime).
136 pub fn uptime(&self) -> Result<Duration> {
137 tree::stat::uptime(self.root())
138 }
139
140 /// The host's filesystems, as [`disk::list`] selects them, with mount
141 /// points as the host sees them and space read through the root.
142 ///
143 /// # Errors
144 ///
145 /// As [`disk::list`].
146 pub fn disks(&self) -> Result<Vec<Disk>> {
147 let mounts = tree::disk::mounts_at(self.root(), self.mountinfo, &ListOptions::default())?;
148 Ok(mounts
149 .into_iter()
150 .map(|m| {
151 let inside = self.base.join(
152 m.mount_point
153 .strip_prefix("/")
154 .unwrap_or(Path::new(&m.mount_point)),
155 );
156 Disk {
157 space: crate::sys::disk_space(&inside).ok(),
158 mount_point: m.mount_point,
159 device: m.device,
160 label: None,
161 filesystem: m.filesystem,
162 kind: m.kind,
163 read_only: m.read_only,
164 removable: m.removable,
165 }
166 })
167 .collect())
168 }
169
170 /// A disk I/O sampler over the host's counters.
171 ///
172 /// # Errors
173 ///
174 /// As [`disk::IoSampler::new`].
175 pub fn disk_io(&self) -> Result<disk::IoSampler> {
176 disk::IoSampler::from(self.origin())
177 }
178
179 /// A network sampler over the host's counters.
180 ///
181 /// # Errors
182 ///
183 /// As [`net::Sampler::new`].
184 pub fn net(&self) -> Result<net::Sampler> {
185 net::Sampler::from(self.origin())
186 }
187
188 /// The host's process and thread counts.
189 ///
190 /// # Errors
191 ///
192 /// `Io` when the host's `/proc` cannot be listed; `TooLarge` past four
193 /// million processes.
194 pub fn processes(&self) -> Result<Processes> {
195 let total = self.root().count_entries("/proc", MAX_PROCESSES, |name| {
196 name.bytes().all(|b| b.is_ascii_digit())
197 })?;
198 Ok(Processes {
199 total,
200 threads: tree::stat::threads(self.root()),
201 running: tree::stat::procs_running(self.root()),
202 })
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209 use crate::linux::fixtures;
210
211 fn fixture() -> PathBuf {
212 PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/wsl2"))
213 }
214
215 #[test]
216 fn test_probe_rejects_a_root_without_proc() {
217 let err = Probe::with_root(std::env::temp_dir().join("sys-lib-no-such-root")).unwrap_err();
218 assert!(matches!(err, Error::NotFound { .. }), "{err}");
219 }
220
221 #[test]
222 fn test_probe_reads_a_fixture_host() {
223 let p = Probe::with_root(fixture()).unwrap();
224 let m = p.memory().unwrap();
225 let expect = tree::mem::read(&fixtures::root("wsl2"), None, false, MemWant::ALL)
226 .map(mem::from_raw)
227 .unwrap();
228 assert_eq!(m.total, expect.total);
229 assert!(p.load().unwrap().is_some());
230 assert!(p.uptime().unwrap() > Duration::ZERO);
231 let mut s = p.cpu_sampler().unwrap();
232 // A fixture's counters never move.
233 assert!(matches!(s.sample(), Err(Error::TooSoon { .. })));
234 assert!(p.disk_io().is_ok());
235 assert!(p.net().is_ok());
236 assert!(p.processes().is_ok());
237 let _ = p.disks();
238 }
239}