1use core::fmt;
4use std::{io, path::PathBuf, time::Duration};
5
6#[derive(Debug)]
26#[non_exhaustive]
27pub enum Error {
28 Unsupported {
30 what: &'static str,
32 platform: &'static str,
34 },
35 PermissionDenied {
37 what: &'static str,
39 hint: &'static str,
41 },
42 NotFound {
44 what: &'static str,
46 source: &'static str,
48 },
49 Malformed {
51 what: &'static str,
53 source: &'static str,
55 line: Option<u32>,
57 },
58 TooLarge {
60 what: &'static str,
62 limit: u64,
64 },
65 TooSoon {
67 elapsed: Duration,
69 minimum: Duration,
71 },
72 Os {
74 what: &'static str,
76 call: &'static str,
78 code: i32,
80 },
81 Io {
83 what: &'static str,
85 source: io::Error,
87 },
88 InvalidInput {
90 what: &'static str,
92 reason: &'static str,
94 },
95 AlreadyRunning {
97 pid: Option<u32>,
99 lock_file: PathBuf,
101 },
102 RunDirUnavailable {
104 path: PathBuf,
106 source: io::Error,
108 },
109 #[cfg(feature = "device-id")]
112 #[cfg_attr(docsrs, doc(cfg(feature = "device-id")))]
113 NoIdentifierSource {
114 basis: crate::device::Basis,
116 },
117 OpenFilesTooLow {
119 have: u64,
121 need: u64,
123 },
124}
125
126const ISSUES: &str = "https://github.com/jamesgober/sys-lib/issues";
128
129pub type Result<T, E = Error> = core::result::Result<T, E>;
131
132impl Error {
133 #[must_use]
142 pub fn is_unavailable(&self) -> bool {
143 matches!(
144 self,
145 Self::Unsupported { .. } | Self::PermissionDenied { .. } | Self::NotFound { .. }
146 )
147 }
148
149 #[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 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}