Skip to main content

sys_lib/
error.rs

1//! The error type: every failure says what failed and what to do.
2
3use core::fmt;
4use std::{io, path::PathBuf, time::Duration};
5
6/// Everything that can go wrong in sys-lib.
7///
8/// Every variant's message is one sentence saying what failed, followed by
9/// what to do about it. No variant ever carries file content, registry content,
10/// or identifier values: [`Error::Malformed`] names the source (a constant
11/// path) and a line number only.
12///
13/// # Examples
14///
15/// ```
16/// use sys_lib as sys;
17///
18/// match sys::host::name() {
19///     Ok(name) => println!("host {name}"),
20///     Err(e) if e.is_unavailable() => println!("host name unknown here: {e}"),
21///     Err(e) => return Err(e),
22/// }
23/// # Ok::<(), sys_lib::Error>(())
24/// ```
25#[derive(Debug)]
26#[non_exhaustive]
27pub enum Error {
28    /// This reading does not exist on this platform. Treat the value as unknown.
29    Unsupported {
30        /// The reading.
31        what: &'static str,
32        /// The platform that lacks it.
33        platform: &'static str,
34    },
35    /// The OS refused (root-only files, a sandbox, SELinux, seccomp).
36    PermissionDenied {
37        /// The reading.
38        what: &'static str,
39        /// The permission that would allow it.
40        hint: &'static str,
41    },
42    /// A file or key that should exist does not (a container with a reduced `/proc`).
43    NotFound {
44        /// The reading.
45        what: &'static str,
46        /// The file, key, or call that was missing.
47        source: &'static str,
48    },
49    /// The OS returned data that does not parse.
50    Malformed {
51        /// The reading.
52        what: &'static str,
53        /// The file, key, or call the data came from.
54        source: &'static str,
55        /// The line, when the data is line-based.
56        line: Option<u32>,
57    },
58    /// A file, a list, or a caller's buffer exceeded its budget.
59    TooLarge {
60        /// The reading.
61        what: &'static str,
62        /// The budget that was exceeded.
63        limit: u64,
64    },
65    /// A sampler was asked again before any time passed on the OS clock.
66    TooSoon {
67        /// The time since the previous sample.
68        elapsed: Duration,
69        /// The shortest interval that gives a meaningful value.
70        minimum: Duration,
71    },
72    /// A system call failed.
73    Os {
74        /// The reading.
75        what: &'static str,
76        /// The call that failed.
77        call: &'static str,
78        /// The OS error code (`errno`, a Win32 error, an `NTSTATUS`, a `kern_return_t`).
79        code: i32,
80    },
81    /// File I/O failed outside the cases above.
82    Io {
83        /// The reading.
84        what: &'static str,
85        /// The underlying error.
86        source: io::Error,
87    },
88    /// Invalid input from the caller.
89    InvalidInput {
90        /// The input.
91        what: &'static str,
92        /// The rule it broke.
93        reason: &'static str,
94    },
95    /// The process guard found another copy holding the lock.
96    AlreadyRunning {
97        /// The other copy's process id from its pid file, when readable. A
98        /// hint, not proof: the file can still hold an earlier run's pid
99        /// for a moment after a copy starts, and that pid may since belong
100        /// to another program. Check it before stopping it.
101        pid: Option<u32>,
102        /// The lock file.
103        lock_file: PathBuf,
104    },
105    /// The process guard's lock directory cannot be created, written, or trusted.
106    RunDirUnavailable {
107        /// The directory.
108        path: PathBuf,
109        /// Why, as an I/O error (the kind and a message naming the fix).
110        source: io::Error,
111    },
112    /// No usable identifier exists for the requested basis. See
113    /// `device::report()` for the state of each source.
114    #[cfg(feature = "device-id")]
115    #[cfg_attr(docsrs, doc(cfg(feature = "device-id")))]
116    NoIdentifierSource {
117        /// The basis asked for.
118        basis: crate::device::Basis,
119    },
120    /// The hard open-file limit is below the process guard's minimum.
121    OpenFilesTooLow {
122        /// The hard limit the process has.
123        have: u64,
124        /// The minimum the guard was asked for.
125        need: u64,
126    },
127}
128
129/// Where unexpected OS data is reported.
130const ISSUES: &str = "https://github.com/jamesgober/sys-lib/issues";
131
132/// The result type used throughout sys-lib.
133pub type Result<T, E = Error> = core::result::Result<T, E>;
134
135impl Error {
136    /// True for the errors that mean "this fact is not available here", which a
137    /// caller usually treats as unknown: [`Unsupported`](Error::Unsupported),
138    /// [`PermissionDenied`](Error::PermissionDenied), and [`NotFound`](Error::NotFound).
139    ///
140    /// ```
141    /// let e = sys_lib::Error::Unsupported { what: "load average", platform: "windows" };
142    /// assert!(e.is_unavailable());
143    /// ```
144    #[must_use]
145    pub fn is_unavailable(&self) -> bool {
146        matches!(
147            self,
148            Self::Unsupported { .. } | Self::PermissionDenied { .. } | Self::NotFound { .. }
149        )
150    }
151
152    /// An [`Io`](Error::Io) error, or the more specific variant its kind maps to.
153    #[cfg_attr(
154        not(any(target_os = "linux", target_os = "android", test)),
155        allow(dead_code)
156    )]
157    pub(crate) fn io(what: &'static str, source: &'static str, err: io::Error) -> Self {
158        match err.kind() {
159            io::ErrorKind::NotFound => Self::NotFound { what, source },
160            io::ErrorKind::PermissionDenied => Self::PermissionDenied {
161                what,
162                hint: "run as a user that may read it, or treat the value as unknown",
163            },
164            _ => Self::Io { what, source: err },
165        }
166    }
167}
168
169impl fmt::Display for Error {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        match self {
172            Self::Unsupported { what, platform } => write!(
173                f,
174                "{what} is not available on {platform}; treat the value as unknown"
175            ),
176            Self::PermissionDenied { what, hint } => {
177                write!(f, "reading {what} was refused by the OS; {hint}")
178            }
179            Self::NotFound { what, source } => write!(
180                f,
181                "{what} could not be read: {source} does not exist; treat the value as unknown \
182                 (minimal containers and sandboxes often lack it)"
183            ),
184            Self::Malformed { what, source, line } => {
185                write!(f, "{what} could not be read: {source} does not parse")?;
186                if let Some(line) = line {
187                    write!(f, " (line {line})")?;
188                }
189                write!(
190                    f,
191                    "; treat the value as unknown, and report it at {ISSUES} with the file \
192                     named here"
193                )
194            }
195            Self::TooLarge { what, limit } => write!(
196                f,
197                "{what} exceeded its budget of {limit}; treat the value as unknown, and if the \
198                 machine is genuinely that large, report it at {ISSUES}"
199            ),
200            Self::TooSoon { elapsed, minimum } => write!(
201                f,
202                "sampled again after {elapsed:?}, before the OS clock moved; sample at least \
203                 {minimum:?} apart"
204            ),
205            Self::Os { what, call, code } => write!(
206                f,
207                "{what} could not be read: {call} failed with OS error {code}; the code says \
208                 why, and if it is unexpected, report it at {ISSUES}"
209            ),
210            Self::Io { what, source } => write!(
211                f,
212                "{what} could not be read: {source}; treat the value as unknown, and if it is \
213                 unexpected, report it at {ISSUES}"
214            ),
215            Self::InvalidInput { what, reason } => write!(f, "invalid {what}: {reason}"),
216            Self::AlreadyRunning { pid, lock_file } => {
217                write!(f, "another copy is already running")?;
218                write!(f, " and holds {}", lock_file.display())?;
219                if let Some(pid) = pid {
220                    write!(
221                        f,
222                        " (its pid file names process {pid}; check that it is this program)"
223                    )?;
224                }
225                write!(f, "; stop it, or give this copy another lock directory")
226            }
227            Self::RunDirUnavailable { path, source } => write!(
228                f,
229                "the lock directory {} cannot be used: {source}",
230                path.display()
231            ),
232            #[cfg(feature = "device-id")]
233            Self::NoIdentifierSource { basis } => write!(
234                f,
235                "no usable device identifier for {basis:?}: device::report() shows the state of each source"
236            ),
237            Self::OpenFilesTooLow { have, need } => write!(
238                f,
239                "the hard open-file limit is {have}, below the required {need}; raise it \
240                 (LimitNOFILE= in the systemd unit, `ulimit -Hn`, or launchd's HardResourceLimits)"
241            ),
242        }
243    }
244}
245
246impl std::error::Error for Error {
247    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
248        match self {
249            Self::Io { source, .. } | Self::RunDirUnavailable { source, .. } => Some(source),
250            _ => None,
251        }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use std::error::Error as _;
258
259    use super::*;
260
261    const fn assert_send_sync<T: Send + Sync + 'static>() {}
262    const _: () = assert_send_sync::<Error>();
263
264    fn every_variant() -> Vec<Error> {
265        vec![
266            Error::Unsupported {
267                what: "load average",
268                platform: "windows",
269            },
270            Error::PermissionDenied {
271                what: "board serial",
272                hint: "run as root",
273            },
274            Error::NotFound {
275                what: "os-release",
276                source: "/etc/os-release",
277            },
278            Error::Malformed {
279                what: "cpu list",
280                source: "/proc/self/status",
281                line: Some(7),
282            },
283            Error::Malformed {
284                what: "cpu list",
285                source: "/proc/self/status",
286                line: None,
287            },
288            Error::TooLarge {
289                what: "mount list",
290                limit: 4096,
291            },
292            Error::TooSoon {
293                elapsed: Duration::from_millis(1),
294                minimum: Duration::from_millis(10),
295            },
296            Error::Os {
297                what: "host name",
298                call: "GetComputerNameExW",
299                code: 5,
300            },
301            Error::Io {
302                what: "status",
303                source: io::Error::other("disk on fire"),
304            },
305            Error::InvalidInput {
306                what: "guard name",
307                reason: "must not contain '/'",
308            },
309            Error::AlreadyRunning {
310                pid: Some(4821),
311                lock_file: PathBuf::from("/run/site/site.lock"),
312            },
313            Error::AlreadyRunning {
314                pid: None,
315                lock_file: PathBuf::from("/run/site/site.lock"),
316            },
317            Error::RunDirUnavailable {
318                path: PathBuf::from("/tmp"),
319                source: io::Error::other("writable by other users; chmod 700 it"),
320            },
321            Error::OpenFilesTooLow {
322                have: 256,
323                need: 1024,
324            },
325        ]
326    }
327
328    #[test]
329    fn test_error_display_every_variant_says_what_to_do() {
330        // NFR-15: every message names the failure and a next step.
331        for e in every_variant() {
332            let text = e.to_string();
333            assert!(!text.is_empty());
334            assert!(
335                text.contains(';') || text.contains(':'),
336                "no explanation in {text:?}"
337            );
338            assert!(!text.ends_with(' '), "trailing space in {text:?}");
339        }
340    }
341
342    #[test]
343    fn test_error_display_includes_the_specific_values() {
344        let e = Error::AlreadyRunning {
345            pid: Some(4821),
346            lock_file: PathBuf::from("site.lock"),
347        };
348        assert!(e.to_string().contains("process 4821"));
349        let e = Error::OpenFilesTooLow {
350            have: 256,
351            need: 1024,
352        };
353        assert!(e.to_string().contains("256") && e.to_string().contains("1024"));
354        let e = Error::Malformed {
355            what: "x",
356            source: "/proc/stat",
357            line: Some(3),
358        };
359        assert!(e.to_string().contains("line 3"));
360    }
361
362    #[test]
363    fn test_error_is_unavailable_only_for_unknown_facts() {
364        for e in every_variant() {
365            let expected = matches!(
366                e,
367                Error::Unsupported { .. } | Error::PermissionDenied { .. } | Error::NotFound { .. }
368            );
369            assert_eq!(e.is_unavailable(), expected, "{e:?}");
370        }
371    }
372
373    #[test]
374    fn test_error_source_only_for_wrapped_io() {
375        for e in every_variant() {
376            let wraps = matches!(e, Error::Io { .. } | Error::RunDirUnavailable { .. });
377            assert_eq!(e.source().is_some(), wraps, "{e:?}");
378        }
379    }
380
381    #[test]
382    fn test_error_io_maps_not_found_and_permission_denied() {
383        let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::NotFound));
384        assert!(matches!(
385            e,
386            Error::NotFound {
387                source: "/proc/x",
388                ..
389            }
390        ));
391        let e = Error::io(
392            "x",
393            "/proc/x",
394            io::Error::from(io::ErrorKind::PermissionDenied),
395        );
396        assert!(matches!(e, Error::PermissionDenied { .. }));
397        let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::Interrupted));
398        assert!(matches!(e, Error::Io { .. }));
399    }
400}