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, when its pid file is readable.
98        pid: Option<u32>,
99        /// The lock file.
100        lock_file: PathBuf,
101    },
102    /// The process guard's lock directory cannot be created, written, or trusted.
103    RunDirUnavailable {
104        /// The directory.
105        path: PathBuf,
106        /// Why, as an I/O error (the kind and a message naming the fix).
107        source: io::Error,
108    },
109    /// No usable identifier exists for the requested basis. See
110    /// `device::report()` for the state of each source.
111    #[cfg(feature = "device-id")]
112    #[cfg_attr(docsrs, doc(cfg(feature = "device-id")))]
113    NoIdentifierSource {
114        /// The basis asked for.
115        basis: crate::device::Basis,
116    },
117    /// The hard open-file limit is below the process guard's minimum.
118    OpenFilesTooLow {
119        /// The hard limit the process has.
120        have: u64,
121        /// The minimum the guard was asked for.
122        need: u64,
123    },
124}
125
126/// Where unexpected OS data is reported.
127const ISSUES: &str = "https://github.com/jamesgober/sys-lib/issues";
128
129/// The result type used throughout sys-lib.
130pub type Result<T, E = Error> = core::result::Result<T, E>;
131
132impl Error {
133    /// True for the errors that mean "this fact is not available here", which a
134    /// caller usually treats as unknown: [`Unsupported`](Error::Unsupported),
135    /// [`PermissionDenied`](Error::PermissionDenied), and [`NotFound`](Error::NotFound).
136    ///
137    /// ```
138    /// let e = sys_lib::Error::Unsupported { what: "load average", platform: "windows" };
139    /// assert!(e.is_unavailable());
140    /// ```
141    #[must_use]
142    pub fn is_unavailable(&self) -> bool {
143        matches!(
144            self,
145            Self::Unsupported { .. } | Self::PermissionDenied { .. } | Self::NotFound { .. }
146        )
147    }
148
149    /// An [`Io`](Error::Io) error, or the more specific variant its kind maps to.
150    #[cfg_attr(
151        not(any(target_os = "linux", target_os = "android", test)),
152        allow(dead_code)
153    )]
154    pub(crate) fn io(what: &'static str, source: &'static str, err: io::Error) -> Self {
155        match err.kind() {
156            io::ErrorKind::NotFound => Self::NotFound { what, source },
157            io::ErrorKind::PermissionDenied => Self::PermissionDenied {
158                what,
159                hint: "run as a user that may read it, or treat the value as unknown",
160            },
161            _ => Self::Io { what, source: err },
162        }
163    }
164}
165
166impl fmt::Display for Error {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        match self {
169            Self::Unsupported { what, platform } => write!(
170                f,
171                "{what} is not available on {platform}; treat the value as unknown"
172            ),
173            Self::PermissionDenied { what, hint } => {
174                write!(f, "reading {what} was refused by the OS; {hint}")
175            }
176            Self::NotFound { what, source } => write!(
177                f,
178                "{what} could not be read: {source} does not exist; treat the value as unknown \
179                 (minimal containers and sandboxes often lack it)"
180            ),
181            Self::Malformed { what, source, line } => {
182                write!(f, "{what} could not be read: {source} does not parse")?;
183                if let Some(line) = line {
184                    write!(f, " (line {line})")?;
185                }
186                write!(
187                    f,
188                    "; treat the value as unknown, and report it at {ISSUES} with the file \
189                     named here"
190                )
191            }
192            Self::TooLarge { what, limit } => write!(
193                f,
194                "{what} exceeded its budget of {limit}; treat the value as unknown, and if the \
195                 machine is genuinely that large, report it at {ISSUES}"
196            ),
197            Self::TooSoon { elapsed, minimum } => write!(
198                f,
199                "sampled again after {elapsed:?}, before the OS clock moved; sample at least \
200                 {minimum:?} apart"
201            ),
202            Self::Os { what, call, code } => write!(
203                f,
204                "{what} could not be read: {call} failed with OS error {code}; the code says \
205                 why, and if it is unexpected, report it at {ISSUES}"
206            ),
207            Self::Io { what, source } => write!(
208                f,
209                "{what} could not be read: {source}; treat the value as unknown, and if it is \
210                 unexpected, report it at {ISSUES}"
211            ),
212            Self::InvalidInput { what, reason } => write!(f, "invalid {what}: {reason}"),
213            Self::AlreadyRunning { pid, lock_file } => {
214                write!(f, "another copy is already running")?;
215                if let Some(pid) = pid {
216                    write!(f, " as process {pid}")?;
217                }
218                write!(
219                    f,
220                    " and holds {}; stop it, or give this copy another lock directory",
221                    lock_file.display()
222                )
223            }
224            Self::RunDirUnavailable { path, source } => write!(
225                f,
226                "the lock directory {} cannot be used: {source}",
227                path.display()
228            ),
229            #[cfg(feature = "device-id")]
230            Self::NoIdentifierSource { basis } => write!(
231                f,
232                "no usable device identifier for {basis:?}: device::report() shows the state of each source"
233            ),
234            Self::OpenFilesTooLow { have, need } => write!(
235                f,
236                "the hard open-file limit is {have}, below the required {need}; raise it \
237                 (LimitNOFILE= in the systemd unit, `ulimit -Hn`, or launchd's HardResourceLimits)"
238            ),
239        }
240    }
241}
242
243impl std::error::Error for Error {
244    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
245        match self {
246            Self::Io { source, .. } | Self::RunDirUnavailable { source, .. } => Some(source),
247            _ => None,
248        }
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use std::error::Error as _;
255
256    use super::*;
257
258    const fn assert_send_sync<T: Send + Sync + 'static>() {}
259    const _: () = assert_send_sync::<Error>();
260
261    fn every_variant() -> Vec<Error> {
262        vec![
263            Error::Unsupported {
264                what: "load average",
265                platform: "windows",
266            },
267            Error::PermissionDenied {
268                what: "board serial",
269                hint: "run as root",
270            },
271            Error::NotFound {
272                what: "os-release",
273                source: "/etc/os-release",
274            },
275            Error::Malformed {
276                what: "cpu list",
277                source: "/proc/self/status",
278                line: Some(7),
279            },
280            Error::Malformed {
281                what: "cpu list",
282                source: "/proc/self/status",
283                line: None,
284            },
285            Error::TooLarge {
286                what: "mount list",
287                limit: 4096,
288            },
289            Error::TooSoon {
290                elapsed: Duration::from_millis(1),
291                minimum: Duration::from_millis(10),
292            },
293            Error::Os {
294                what: "host name",
295                call: "GetComputerNameExW",
296                code: 5,
297            },
298            Error::Io {
299                what: "status",
300                source: io::Error::other("disk on fire"),
301            },
302            Error::InvalidInput {
303                what: "guard name",
304                reason: "must not contain '/'",
305            },
306            Error::AlreadyRunning {
307                pid: Some(4821),
308                lock_file: PathBuf::from("/run/site/site.lock"),
309            },
310            Error::AlreadyRunning {
311                pid: None,
312                lock_file: PathBuf::from("/run/site/site.lock"),
313            },
314            Error::RunDirUnavailable {
315                path: PathBuf::from("/tmp"),
316                source: io::Error::other("writable by other users; chmod 700 it"),
317            },
318            Error::OpenFilesTooLow {
319                have: 256,
320                need: 1024,
321            },
322        ]
323    }
324
325    #[test]
326    fn test_error_display_every_variant_says_what_to_do() {
327        // NFR-15: every message names the failure and a next step.
328        for e in every_variant() {
329            let text = e.to_string();
330            assert!(!text.is_empty());
331            assert!(
332                text.contains(';') || text.contains(':'),
333                "no explanation in {text:?}"
334            );
335            assert!(!text.ends_with(' '), "trailing space in {text:?}");
336        }
337    }
338
339    #[test]
340    fn test_error_display_includes_the_specific_values() {
341        let e = Error::AlreadyRunning {
342            pid: Some(4821),
343            lock_file: PathBuf::from("site.lock"),
344        };
345        assert!(e.to_string().contains("process 4821"));
346        let e = Error::OpenFilesTooLow {
347            have: 256,
348            need: 1024,
349        };
350        assert!(e.to_string().contains("256") && e.to_string().contains("1024"));
351        let e = Error::Malformed {
352            what: "x",
353            source: "/proc/stat",
354            line: Some(3),
355        };
356        assert!(e.to_string().contains("line 3"));
357    }
358
359    #[test]
360    fn test_error_is_unavailable_only_for_unknown_facts() {
361        for e in every_variant() {
362            let expected = matches!(
363                e,
364                Error::Unsupported { .. } | Error::PermissionDenied { .. } | Error::NotFound { .. }
365            );
366            assert_eq!(e.is_unavailable(), expected, "{e:?}");
367        }
368    }
369
370    #[test]
371    fn test_error_source_only_for_wrapped_io() {
372        for e in every_variant() {
373            let wraps = matches!(e, Error::Io { .. } | Error::RunDirUnavailable { .. });
374            assert_eq!(e.source().is_some(), wraps, "{e:?}");
375        }
376    }
377
378    #[test]
379    fn test_error_io_maps_not_found_and_permission_denied() {
380        let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::NotFound));
381        assert!(matches!(
382            e,
383            Error::NotFound {
384                source: "/proc/x",
385                ..
386            }
387        ));
388        let e = Error::io(
389            "x",
390            "/proc/x",
391            io::Error::from(io::ErrorKind::PermissionDenied),
392        );
393        assert!(matches!(e, Error::PermissionDenied { .. }));
394        let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::Interrupted));
395        assert!(matches!(e, Error::Io { .. }));
396    }
397}