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>,
102 lock_file: PathBuf,
104 },
105 RunDirUnavailable {
107 path: PathBuf,
109 source: io::Error,
111 },
112 #[cfg(feature = "device-id")]
115 #[cfg_attr(docsrs, doc(cfg(feature = "device-id")))]
116 NoIdentifierSource {
117 basis: crate::device::Basis,
119 },
120 OpenFilesTooLow {
122 have: u64,
124 need: u64,
126 },
127}
128
129const ISSUES: &str = "https://github.com/jamesgober/sys-lib/issues";
131
132pub type Result<T, E = Error> = core::result::Result<T, E>;
134
135impl Error {
136 #[must_use]
145 pub fn is_unavailable(&self) -> bool {
146 matches!(
147 self,
148 Self::Unsupported { .. } | Self::PermissionDenied { .. } | Self::NotFound { .. }
149 )
150 }
151
152 #[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 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}