Skip to main content

sys_lib/
summary.rs

1//! Every static fact plus one memory snapshot and the uptime, for the start-up
2//! log line, a health endpoint, or a support bundle.
3
4use core::{fmt, time::Duration};
5
6use crate::{cpu, host, mem, os, virt};
7
8/// See [`summary`]. It deliberately carries no host name, user name, MAC
9/// address, or device id, because it is meant for output that leaves the
10/// machine (threat T13).
11#[derive(Clone, Debug)]
12#[non_exhaustive]
13pub struct Summary {
14    /// [`os::name`].
15    pub os: &'static str,
16    /// [`os::kernel`].
17    pub kernel: &'static str,
18    /// [`cpu::name`].
19    pub cpu: &'static str,
20    /// [`cpu::count`].
21    pub cpu_counts: cpu::Counts,
22    /// [`mem::snapshot`].
23    pub memory: Option<mem::Memory>,
24    /// [`cpu::quota`].
25    pub cpu_quota: Option<cpu::CpuQuota>,
26    /// [`virt::detect`].
27    pub virtualization: &'static virt::Virtualization,
28    /// [`os::form_factor`].
29    pub form_factor: os::FormFactor,
30    /// [`host::uptime`].
31    pub uptime: Option<Duration>,
32    /// [`cpu::load`].
33    pub load: Option<cpu::Load>,
34}
35
36/// The facts for a log line or a support bundle. Never fails: a reading that
37/// fails becomes `None` in its field.
38///
39/// ```
40/// use sys_lib as sys;
41///
42/// let summary = sys::summary();
43/// println!("{summary}");
44///
45/// let mut line = String::new();
46/// summary.write_json(&mut line)?;
47/// # Ok::<(), std::fmt::Error>(())
48/// ```
49#[must_use]
50pub fn summary() -> Summary {
51    Summary {
52        os: os::name(),
53        kernel: os::kernel(),
54        cpu: cpu::name(),
55        cpu_counts: cpu::count(),
56        memory: mem::snapshot().ok(),
57        cpu_quota: cpu::quota().ok().flatten(),
58        virtualization: virt::detect(),
59        form_factor: os::form_factor(),
60        uptime: host::uptime().ok(),
61        load: cpu::load().ok().flatten(),
62    }
63}
64
65impl Summary {
66    fn virt_name(&self) -> String {
67        let v = self.virtualization;
68        let mut parts = Vec::new();
69        if let Some(c) = v.container {
70            parts.push(format!("{c:?}").to_lowercase());
71        }
72        if let Some(h) = v.hypervisor {
73            parts.push(format!("{h:?}").to_lowercase());
74        }
75        if parts.is_empty() {
76            "none".to_owned()
77        } else {
78            parts.join("+")
79        }
80    }
81
82    fn limit_name(&self) -> Option<&'static str> {
83        match self.memory?.source {
84            mem::MemorySource::Cgroup1 => Some("cgroup1"),
85            mem::MemorySource::Cgroup2 => Some("cgroup2"),
86            mem::MemorySource::JobObject => Some("job"),
87            mem::MemorySource::Lxcfs => Some("lxcfs"),
88            _ => None,
89        }
90    }
91
92    /// `key=value` pairs, one per fact, separated by `sep`.
93    fn pairs(&self, out: &mut dyn fmt::Write, sep: &str) -> fmt::Result {
94        let c = &self.cpu_counts;
95        write!(
96            out,
97            "os={}{sep}kernel={}",
98            quoted(self.os),
99            quoted(self.kernel)
100        )?;
101        write!(out, "{sep}cpu={}", quoted(self.cpu))?;
102        write!(out, "{sep}cores={}{sep}threads={}", c.physical, c.logical)?;
103        write!(out, "{sep}available={}", c.available)?;
104        if let Some(m) = &self.memory {
105            write!(
106                out,
107                "{sep}memory.total={}{sep}memory.used={}",
108                m.total, m.used
109            )?;
110        }
111        if let Some(limit) = self.limit_name() {
112            write!(out, "{sep}limit={limit}")?;
113        }
114        write!(out, "{sep}virt={}", self.virt_name())?;
115        write!(out, "{sep}form={}", self.form_factor.name())?;
116        if let Some(up) = self.uptime {
117            write!(out, "{sep}uptime={}s", up.as_secs())?;
118        }
119        if let Some(l) = self.load {
120            write!(out, "{sep}load={:.2}", l.one)?;
121        }
122        Ok(())
123    }
124
125    /// `key=value` pairs on one line.
126    ///
127    /// # Errors
128    ///
129    /// Whatever `out` returns.
130    pub fn write_kv(&self, out: &mut impl fmt::Write) -> fmt::Result {
131        self.pairs(out, " ")
132    }
133
134    /// One JSON object.
135    ///
136    /// # Errors
137    ///
138    /// Whatever `out` returns.
139    pub fn write_json(&self, out: &mut impl fmt::Write) -> fmt::Result {
140        let c = &self.cpu_counts;
141        write!(out, "{{\"os\":")?;
142        json(out, self.os)?;
143        write!(out, ",\"kernel\":")?;
144        json(out, self.kernel)?;
145        write!(out, ",\"cpu\":")?;
146        json(out, self.cpu)?;
147        write!(
148            out,
149            ",\"cores\":{},\"threads\":{},\"packages\":{},\"available\":{},\"online\":{}",
150            c.physical, c.logical, c.packages, c.available, c.online
151        )?;
152        if let Some(m) = &self.memory {
153            write!(
154                out,
155                ",\"memory\":{{\"total\":{},\"used\":{},\"free\":{}}}",
156                m.total.raw(),
157                m.used.raw(),
158                m.free.raw()
159            )?;
160        }
161        if let Some(q) = &self.cpu_quota {
162            write!(out, ",\"cpu_quota\":{}", q.cpus)?;
163        }
164        if let Some(limit) = self.limit_name() {
165            write!(out, ",\"limit\":\"{limit}\"")?;
166        }
167        write!(out, ",\"virt\":")?;
168        json(out, &self.virt_name())?;
169        write!(out, ",\"form\":\"{}\"", self.form_factor.name())?;
170        if let Some(up) = self.uptime {
171            write!(out, ",\"uptime_seconds\":{}", up.as_secs())?;
172        }
173        if let Some(l) = self.load {
174            write!(out, ",\"load\":[{},{},{}]", l.one, l.five, l.fifteen)?;
175        }
176        out.write_str("}")
177    }
178}
179
180impl fmt::Display for Summary {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        self.pairs(f, " ")
183    }
184}
185
186/// `text`, in double quotes when it has a space, quote, or control character.
187fn quoted(text: &str) -> String {
188    if text.is_empty() || text.chars().any(|c| c == ' ' || c == '"' || c.is_control()) {
189        format!("{:?}", text)
190    } else {
191        text.to_owned()
192    }
193}
194
195/// `text` as a JSON string.
196fn json(out: &mut dyn fmt::Write, text: &str) -> fmt::Result {
197    out.write_char('"')?;
198    for c in text.chars() {
199        match c {
200            '"' => out.write_str("\\\"")?,
201            '\\' => out.write_str("\\\\")?,
202            c if u32::from(c) < 0x20 => write!(out, "\\u{:04x}", u32::from(c))?,
203            c => out.write_char(c)?,
204        }
205    }
206    out.write_char('"')
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn test_summary_live_outputs() {
215        let s = summary();
216        let text = s.to_string();
217        assert!(text.starts_with("os=") && text.contains(" cpu=") && text.contains(" virt="));
218        let mut kv = String::new();
219        s.write_kv(&mut kv).unwrap();
220        assert_eq!(kv, text);
221        let mut j = String::new();
222        s.write_json(&mut j).unwrap();
223        assert!(j.starts_with("{\"os\":\"") && j.ends_with('}'));
224    }
225
226    #[test]
227    fn test_summary_t13_no_identifying_values() {
228        // T13: the host name and the user name stay out.
229        let s = summary();
230        let (mut kv, mut j) = (String::new(), String::new());
231        s.write_kv(&mut kv).unwrap();
232        s.write_json(&mut j).unwrap();
233        let debug = format!("{s:?}");
234        let mut secrets = Vec::new();
235        if let Ok(h) = host::name() {
236            secrets.push(h);
237        }
238        if let Ok(u) = crate::process::user() {
239            secrets.push(u.name);
240        }
241        for secret in secrets.iter().filter(|s| s.len() >= 4) {
242            // A machine named after its OS or CPU would match by accident.
243            if s.os.contains(secret.as_str()) || s.kernel.contains(secret.as_str()) {
244                continue;
245            }
246            assert!(!kv.contains(secret.as_str()), "{secret}");
247            assert!(!j.contains(secret.as_str()), "{secret}");
248            assert!(!debug.contains(secret.as_str()), "{secret}");
249        }
250    }
251
252    #[test]
253    fn test_summary_json_escapes() {
254        let mut out = String::new();
255        json(&mut out, "a\"b\\c\nd").unwrap();
256        assert_eq!(out, r#""a\"b\\c\u000ad""#);
257        assert_eq!(quoted("plain"), "plain");
258        assert_eq!(quoted("two words"), "\"two words\"");
259        assert_eq!(quoted(""), "\"\"");
260    }
261}