Skip to main content

isothrum_runner/
error.rs

1//! Why an operation failed: one enum for the crate, each variant with a stable [`ErrorCode`].
2//! Messages are plain and technical; the embedder maps codes to its own wording.
3
4use std::path::PathBuf;
5
6pub use self::code::ErrorCode;
7pub use self::detail::{DETAIL_VERSION, Detail, DownloadKind, ErrorDetail, PortHolder, ProviderNeed};
8pub use self::report::ErrorReport;
9pub use self::timed_out::TimedOut;
10pub(crate) use self::timed_out::kept_line;
11
12mod code;
13mod detail;
14mod report;
15mod timed_out;
16
17/// The runner's `Result`: its error is a [`Error`] unless said otherwise.
18pub type Result<T, E = Error> = std::result::Result<T, E>;
19
20/// Why an operation of the runner failed.
21#[derive(Debug, thiserror::Error)]
22#[non_exhaustive]
23pub enum Error {
24    /// The manifest needs something this runner doesn't do, or the call asks the run for
25    /// something its target can't do.
26    #[error("{what} isn't supported")]
27    Unsupported {
28        /// What, in a few words: target `cloud-vm` on this host; step `up`: the action
29        /// `ssh.run` on a compose run.
30        what: String,
31    },
32    /// The run's format doesn't do the operation asked (Terraform parks, resumes and provisions
33    /// nothing; Compose provisions nothing): refused before anything acts on the run. Its code is
34    /// `unsupported`.
35    #[error("{what} isn't supported")]
36    Declined {
37        /// What, in a few words: `parking on a Terraform run: …`.
38        what: String,
39    },
40    /// A file or folder couldn't be read or written, or a loopback port bound.
41    #[error("{} couldn't be {action}: {source}", path.display())]
42    Io {
43        /// The file or folder (or the port: `a tcp port on 127.0.0.1`).
44        path: PathBuf,
45        /// What was done to it (`read`, `written`, `created`, `locked`, `bound`).
46        action: &'static str,
47        /// The OS's reason.
48        source: std::io::Error,
49    },
50    /// Another process holds the run's lock.
51    #[error("run `{run}` is busy: another process runs an operation on it")]
52    Locked {
53        /// The run.
54        run: String,
55    },
56    /// A step's tool isn't on PATH.
57    #[error("step `{step}`: `{tool}` isn't installed or isn't on PATH")]
58    ToolMissing {
59        /// The step.
60        step: String,
61        /// The tool.
62        tool: String,
63    },
64    /// A tool answers at a version older than the manifest's `min_version` for it.
65    #[error("`{tool}` is version {found}; this run needs {required} or later")]
66    ToolTooOld {
67        /// The tool.
68        tool: String,
69        /// The version it answered with.
70        found: String,
71        /// The oldest version the run takes.
72        required: String,
73    },
74    /// A step's tool ran and failed.
75    #[error("step `{step}` failed: {reason}")]
76    ToolFailed {
77        /// The step.
78        step: String,
79        /// Its last error lines, or its exit status (secrets masked).
80        reason: String,
81    },
82    /// A tool the run needs is installed, but its service didn't answer: a container engine
83    /// stopped, or quit while a step ran. Said by its code, so a caller never reads it out of a
84    /// [`Error::ToolFailed`]'s wording.
85    #[error("step `{step}` failed: `{tool}` doesn't answer: {reason}")]
86    ToolUnanswered {
87        /// The probing step (`tools`).
88        step: String,
89        /// The tool, by its manifest name (`docker`).
90        tool: String,
91        /// What it said, or why its answer is none (secrets masked).
92        reason: String,
93    },
94    /// A tool refused this account: Docker's engine its socket or named pipe.
95    #[error("step `{step}` failed: `{tool}` refused this account: {reason}")]
96    ToolDenied {
97        /// The step.
98        step: String,
99        /// The tool (`docker`).
100        tool: String,
101        /// What it said (secrets masked).
102        reason: String,
103    },
104    /// A cloud refused the sign-in the run's tools use: it ran out, or was never made.
105    #[error("step `{step}`: the sign-in to {} ran out or is missing: {reason}", cloud.map_or_else(|| "the cloud".to_owned(), |c| format!("`{}`", crate::encoding::wire_name(&c))))]
106    CredentialsExpired {
107        /// The step.
108        step: String,
109        /// The cloud, when the failure names its Terraform provider.
110        cloud: Option<crate::project::platform::Cloud>,
111        /// What the tool said (secrets masked).
112        reason: String,
113    },
114    /// A network the run makes needs an address block another network holds.
115    #[error("step `{step}`: another network holds the addresses a network of the run needs: {reason}")]
116    AddressPoolOverlap {
117        /// The step.
118        step: String,
119        /// What the tool said (secrets masked).
120        reason: String,
121    },
122    /// A step ran out of time: it showed no progress for its limit, or it ran to the ceiling.
123    #[error("step `{step}` {timed_out}")]
124    Timeout {
125        /// The step.
126        step: String,
127        /// Which limit it ran into.
128        timed_out: TimedOut,
129    },
130    /// A download (what a step downloads in its own phase before it runs, or a step the manifest
131    /// marks a download) showed no progress for `after_s` seconds, and was stopped. A download
132    /// has no other limit: one still moving runs as long as it moves.
133    #[error("step `{step}` showed no progress downloading for {after_s}s and was stopped{}", last_line.as_ref().map_or_else(String::new, |l| format!("; its last line: `{l}`")))]
134    DownloadStalled {
135        /// What it downloads.
136        what: DownloadKind,
137        /// The download's step (`pull-up` or `boxes-up`, before the `up` it downloads for; a
138        /// manifest's own, `pull-start`).
139        step: String,
140        /// How long it went without progress, in seconds.
141        after_s: u64,
142        /// The last line it printed (secrets masked, cut to 300 bytes); none when it printed
143        /// nothing.
144        last_line: Option<String>,
145    },
146    /// A download couldn't be made.
147    #[error("step `{step}` couldn't download what it needs: {reason}")]
148    DownloadFailed {
149        /// What it downloads.
150        what: DownloadKind,
151        /// The download's step (`pull-up`, `boxes-up`, `pull-start`).
152        step: String,
153        /// The last try's last error lines, or its exit status (secrets masked).
154        reason: String,
155    },
156    /// The run is already up.
157    #[error("run `{run}` is already running")]
158    AlreadyRunning {
159        /// The run.
160        run: String,
161    },
162    /// The run is recorded somewhere else.
163    #[error("run `{run}` is recorded on `{recorded}`, not `{asked}`")]
164    RunningElsewhere {
165        /// The run.
166        run: String,
167        /// Where its record says it is.
168        recorded: String,
169        /// Where this operation was asked to run.
170        asked: String,
171    },
172    /// A host port the run publishes is taken.
173    #[error("host port {port}/{protocol} is in use{}", holder.as_ref().map_or_else(String::new, |h| format!(": `{}` (pid {}) listens on it", h.program, h.pid)))]
174    PortInUse {
175        /// The port, on the host.
176        port: crate::port::HostPort,
177        /// `tcp` or `udp`.
178        protocol: String,
179        /// The process listening on it, when the runner found it (looked up once the operation
180        /// failed, best-effort).
181        holder: Option<PortHolder>,
182    },
183    /// No park steps for that mode.
184    #[error("run `{run}` can't be parked ({mode}): its manifest has no steps for it")]
185    NotParkable {
186        /// The run.
187        run: String,
188        /// The mode asked for.
189        mode: &'static str,
190    },
191    /// Nothing left to resume.
192    #[error("run `{run}` has nothing left to resume: start it again")]
193    NothingToResume {
194        /// The run.
195        run: String,
196    },
197    /// Some of the run's machines are gone (removed outside the runner): a resume brings back
198    /// only what was kept, so it can't bring the run back as it was.
199    #[error("run `{run}` can't resume as it was: {} gone: start it again", gone(machines))]
200    PartlyGone {
201        /// The run.
202        run: String,
203        /// Its machines that are gone.
204        machines: Vec<String>,
205    },
206    /// The run isn't up.
207    #[error("run `{run}` isn't running")]
208    NotRunning {
209        /// The run.
210        run: String,
211    },
212    /// A ready condition didn't hold.
213    #[error("not ready: {condition}: {detail}")]
214    NotReady {
215        /// The condition (`step_ok up`, `tcp 127.0.0.1:8080`).
216        condition: String,
217        /// Why.
218        detail: String,
219    },
220    /// A required secret or input has no value.
221    #[error("secret `{name}` is required and has no value")]
222    SecretMissing {
223        /// The slot.
224        name: String,
225    },
226    /// A folder that isn't a project Isothrum runs.
227    #[error("{}: not a project to run: {reason}", dir.display())]
228    Project {
229        /// The folder.
230        dir: PathBuf,
231        /// Why, with the fix.
232        reason: String,
233    },
234    /// A value or secret that can't be handed to the tools (its name empty or holding `=`, a NUL
235    /// in it).
236    #[error("input `{name}`: {reason}")]
237    Input {
238        /// Its name.
239        name: String,
240        /// Why.
241        reason: String,
242    },
243    /// A machine the run doesn't have (to provision, console into, attach, detach or retire).
244    #[error("run `{run}` has no machine `{machine}`")]
245    MachineUnknown {
246        /// The run.
247        run: String,
248        /// The machine asked for.
249        machine: String,
250    },
251    /// The run has several machines the call could mean, and it named none.
252    #[error("run `{run}` has several {which} ({machines}): name one")]
253    MachineAmbiguous {
254        /// The run.
255        run: String,
256        /// Which machines the call could mean (`on-demand machines`).
257        which: &'static str,
258        /// Their names, comma-separated.
259        machines: String,
260    },
261    /// A network the run doesn't have.
262    #[error("run `{run}` has no network `{network}`")]
263    NetworkUnknown {
264        /// The run.
265        run: String,
266        /// The network asked for.
267        network: String,
268    },
269    /// The elevation the run's commands need couldn't be had.
270    #[error("elevation: {reason}")]
271    Elevation {
272        /// Why (the permission prompt declined, the elevated session ended).
273        reason: String,
274    },
275    /// The run's Vagrant provider can't run it.
276    #[error("provider `{provider}`: {reason}")]
277    Provider {
278        /// The provider asked for.
279        provider: String,
280        /// Why it can't run the run, and what to do.
281        reason: String,
282        /// What this computer lacks for it, when that is what refused it.
283        need: Option<ProviderNeed>,
284    },
285    /// A Vagrant run was asked for with no provider.
286    #[error("a Vagrant run needs a provider: pass one of this run's ({providers})")]
287    NoProvider {
288        /// The run's providers, as the manifest names them (`` `virtualbox`, `libvirt` ``).
289        providers: String,
290    },
291    /// A deployment that can't be taken over as a run.
292    #[error("run `{run}` can't take the deployment over: {reason}")]
293    Adopt {
294        /// The run it would have become.
295        run: String,
296        /// Why.
297        reason: String,
298    },
299    /// A run name that can't name a run.
300    #[error(
301        "`{value}` can't name a run: use 1 to 63 lowercase letters, digits, `-` or `_`, starting with a letter or digit, not a Windows device name (`con`, `nul`, `com1`…)"
302    )]
303    RunName {
304        /// The name as given.
305        value: String,
306    },
307    /// A machine with no graphical console to reach, and why.
308    #[error("machine `{machine}` has no graphical console: {why}")]
309    NoConsole {
310        /// The machine.
311        machine: String,
312        /// Why.
313        why: String,
314    },
315    /// The server the run is on refused the run's credentials (a 401 or 403 from its API, its
316    /// tool's failed sign-in): an API token revoked, a password changed.
317    #[error("step `{step}`: {} refused the run's credentials: {reason}", server.as_ref().map_or_else(|| "the server".to_owned(), |s| format!("server `{s}`")))]
318    ServerAuthFailed {
319        /// The step (`up`; `status` for a status read).
320        step: String,
321        /// The server, as the run's params name it (its API's host, the ESXi host), when they do.
322        server: Option<String>,
323        /// What the server or its tool said (secrets masked).
324        reason: String,
325    },
326    /// A file of the runner's own is there but isn't what it wrote (not JSON, or another
327    /// version's shape): told apart from a file that can't be read, which is the OS's to explain.
328    #[error("{} holds no {what} this runner reads: {source}", path.display())]
329    Corrupt {
330        /// The file.
331        path: PathBuf,
332        /// What it should hold (`record`, `ledger entry`).
333        what: &'static str,
334        /// Why it doesn't parse.
335        #[source]
336        source: serde_json::Error,
337    },
338    /// The home's store couldn't do what was asked.
339    #[error("the home's state store couldn't be {action}: {reason}")]
340    Store {
341        /// What (`opened`, `read`, `written`, `migrated`).
342        action: &'static str,
343        /// The failure's code (`locked`, `store_corrupt`, `store_version`, `io`).
344        code: ErrorCode,
345        /// SQLite's word, or the store's.
346        reason: String,
347    },
348    /// The run's state machine refused the move.
349    #[error(transparent)]
350    IllegalTransition(#[from] crate::state::IllegalTransition),
351    /// The run moved between the read and the write that would have moved it.
352    #[error("run `{run}` was expected {expected} but is {}", found.map_or("not recorded", crate::state::RunState::as_str))]
353    StateConflict {
354        /// The run.
355        run: String,
356        /// Where the move started.
357        expected: crate::state::RunState,
358        /// Where the run stood instead.
359        found: Option<crate::state::RunState>,
360    },
361    /// A live process holds the lease asked for.
362    #[error("`{scope}` is held by process {pid}")]
363    LeaseHeld {
364        /// The lease.
365        scope: String,
366        /// Its holder's process id.
367        pid: u32,
368    },
369}
370
371impl Error {
372    /// The step the failure happened in, when it names one.
373    pub(crate) fn step(&self) -> Option<&str> {
374        match self {
375            Error::ToolMissing { step, .. }
376            | Error::ToolFailed { step, .. }
377            | Error::ToolUnanswered { step, .. }
378            | Error::ToolDenied { step, .. }
379            | Error::CredentialsExpired { step, .. }
380            | Error::AddressPoolOverlap { step, .. }
381            | Error::Timeout { step, .. }
382            | Error::DownloadStalled { step, .. }
383            | Error::DownloadFailed { step, .. }
384            | Error::ServerAuthFailed { step, .. } => Some(step),
385            _ => None,
386        }
387    }
388
389    /// What ran out of time, for a step that did.
390    #[cfg(test)]
391    pub(crate) fn timed_out(&self) -> Option<&TimedOut> {
392        match self {
393            Error::Timeout { timed_out, .. } => Some(timed_out),
394            _ => None,
395        }
396    }
397
398    /// The failure's stable code.
399    #[must_use]
400    pub fn code(&self) -> ErrorCode {
401        match self {
402            Error::Unsupported { .. } | Error::Declined { .. } => ErrorCode::Unsupported,
403            Error::Project { .. } => ErrorCode::ProjectInvalid,
404            Error::Io { .. } => ErrorCode::Io,
405            Error::Corrupt { .. } => ErrorCode::Corrupt,
406            Error::Locked { .. } => ErrorCode::Locked,
407            Error::ToolMissing { .. } => ErrorCode::ToolMissing,
408            Error::ToolTooOld { .. } => ErrorCode::ToolTooOld,
409            Error::ToolFailed { .. } => ErrorCode::ToolFailed,
410            Error::ToolUnanswered { .. } => ErrorCode::ToolUnanswered,
411            Error::ToolDenied { .. } => ErrorCode::ToolDenied,
412            Error::CredentialsExpired { .. } => ErrorCode::CredentialsExpired,
413            Error::AddressPoolOverlap { .. } => ErrorCode::AddressPoolOverlap,
414            Error::Timeout { .. } => ErrorCode::Timeout,
415            Error::DownloadStalled { .. } => ErrorCode::DownloadStalled,
416            Error::DownloadFailed { .. } => ErrorCode::DownloadFailed,
417            Error::AlreadyRunning { .. } => ErrorCode::AlreadyRunning,
418            Error::RunningElsewhere { .. } => ErrorCode::RunningElsewhere,
419            Error::PortInUse { .. } => ErrorCode::PortInUse,
420            Error::NotParkable { .. } => ErrorCode::NotParkable,
421            Error::NothingToResume { .. } | Error::PartlyGone { .. } => ErrorCode::NothingToResume,
422            Error::NotRunning { .. } => ErrorCode::NotRunning,
423            Error::NotReady { .. } => ErrorCode::NotReady,
424            Error::SecretMissing { .. } => ErrorCode::SecretMissing,
425            Error::Input { .. } => ErrorCode::InputInvalid,
426            Error::RunName { .. } => ErrorCode::RunName,
427            Error::Provider { .. } | Error::NoProvider { .. } => ErrorCode::ProviderRefused,
428            Error::Elevation { .. } => ErrorCode::ElevationFailed,
429            Error::MachineUnknown { .. } => ErrorCode::MachineUnknown,
430            Error::MachineAmbiguous { .. } => ErrorCode::MachineAmbiguous,
431            Error::NetworkUnknown { .. } => ErrorCode::NetworkUnknown,
432            Error::Adopt { .. } => ErrorCode::AdoptRefused,
433            Error::NoConsole { .. } => ErrorCode::NoConsole,
434            Error::ServerAuthFailed { .. } => ErrorCode::ServerAuthFailed,
435            Error::Store { code, .. } => *code,
436            Error::IllegalTransition(_) => ErrorCode::IllegalTransition,
437            Error::StateConflict { .. } => ErrorCode::StateConflict,
438            Error::LeaseHeld { .. } => ErrorCode::LeaseHeld,
439        }
440    }
441
442    /// An I/O failure on `path`.
443    pub(crate) fn io(path: impl Into<PathBuf>, action: &'static str) -> impl FnOnce(std::io::Error) -> Error {
444        let path = path.into();
445        move |source| Error::Io { path, action, source }
446    }
447}
448
449/// Machines `machines` as an error says they are gone: `web is`, `web and db are`, `a, b and c are`.
450fn gone(machines: &[String]) -> String {
451    let quoted: Vec<String> = machines.iter().map(|m| format!("`{m}`")).collect();
452    match quoted.as_slice() {
453        [] => "nothing is".to_owned(),
454        [one] => format!("machine {one} is"),
455        [rest @ .., last] => format!("machines {} and {last} are", rest.join(", ")),
456    }
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    #[test]
464    fn every_code_is_written_as_serde_writes_it() {
465        crate::testing::assert_named_as_serde(ErrorCode::as_str);
466    }
467
468    #[test]
469    fn a_run_partly_gone_names_its_gone_machines_and_has_nothing_to_resume() {
470        let one = Error::PartlyGone {
471            run: "r".into(),
472            machines: vec!["web".into()],
473        };
474        assert_eq!(one.code(), ErrorCode::NothingToResume);
475        assert_eq!(one.to_string(), "run `r` can't resume as it was: machine `web` is gone: start it again");
476        let three = Error::PartlyGone {
477            run: "r".into(),
478            machines: vec!["a".into(), "b".into(), "c".into()],
479        };
480        assert!(three.to_string().contains("machines `a`, `b` and `c` are gone"), "{three}");
481    }
482
483    #[test]
484    fn an_elevation_that_failed_has_its_code_whatever_ended_it() {
485        let lost = Error::Elevation {
486            reason: "the elevated session ended: the broker stopped".into(),
487        };
488        assert_eq!((lost.code(), lost.code().as_str()), (ErrorCode::ElevationFailed, "elevation_failed"));
489    }
490}