Skip to main content

container_pid/
errors.rs

1use std::fmt::Write;
2use std::path::PathBuf;
3use thiserror::Error;
4
5use crate::RawPid;
6
7/// Errors that can occur while resolving a container name to a PID.
8#[derive(Debug, Error)]
9pub enum Error {
10    /// The container runtime CLI needed for this backend is not installed.
11    #[error("{runtime} runtime not found: '{tool}' command is not available")]
12    RuntimeNotFound {
13        runtime: &'static str,
14        tool: &'static str,
15    },
16    /// Spawning the runtime CLI failed.
17    #[error("failed to execute command: {command}")]
18    CommandFailedToRun {
19        command: String,
20        #[source]
21        source: std::io::Error,
22    },
23    /// The runtime CLI ran but exited with an error.
24    #[error("{command} failed (exit status {status}): {stderr}")]
25    CommandFailed {
26        command: String,
27        status: String,
28        stderr: String,
29    },
30    /// The runtime CLI produced output we could not parse.
31    #[error("unexpected output from {command}: {message}")]
32    UnexpectedOutput { command: String, message: String },
33    /// The runtime reported a PID that is not a number.
34    #[error("invalid PID '{pid}' reported by {runtime} for container '{container}'")]
35    InvalidPid {
36        pid: String,
37        runtime: &'static str,
38        container: String,
39        #[source]
40        source: std::num::ParseIntError,
41    },
42    /// The container exists but is not running.
43    #[error("container '{0}' is not running")]
44    NotRunning(String),
45    /// No container matched the given name/ID for this backend.
46    #[error("container '{container}' not found: {message}")]
47    ContainerNotFound { container: String, message: String },
48    /// Reading a file or directory failed.
49    #[error("failed to read {path}")]
50    Io {
51        path: PathBuf,
52        #[source]
53        source: std::io::Error,
54    },
55    /// The given container ID is not a valid process ID.
56    #[error("'{0}' is not a valid PID (process ID)")]
57    InvalidProcessId(String, #[source] std::num::ParseIntError),
58    /// No process with the given PID exists.
59    #[error("no process with PID {0} found")]
60    NoSuchProcess(RawPid),
61
62    /// None of the tried container runtimes could resolve the container.
63    #[error("failed to find container '{container}' - tried the following runtimes:{tried}")]
64    NoRuntimeMatched { container: String, tried: String },
65}
66
67/// Format an error together with its full source chain.
68pub(crate) fn format_chain(err: &dyn std::error::Error) -> String {
69    let mut msg = err.to_string();
70    let mut source = err.source();
71    while let Some(cause) = source {
72        let _ = write!(msg, ": {}", cause);
73        source = cause.source();
74    }
75    msg
76}