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
6use serde::{Deserialize, Serialize};
7
8pub use self::timed_out::TimedOut;
9
10mod timed_out;
11
12/// The stable code of a failure, the same in the Rust API and the event stream (`error.code`).
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
14#[serde(rename_all = "snake_case")]
15#[non_exhaustive]
16pub enum ErrorCode {
17    /// The manifest isn't valid JSON or breaks the contract, a value it gives can't be used as
18    /// written (a step's `verdict` that isn't a regular expression, an SSH login, a `wait_s`, a
19    /// `tcp` condition's port), or it names a value the operation doesn't have (a placeholder
20    /// with none, a guest delivery's machine whose address no output gives, a Terraform module
21    /// with no `.tf` file).
22    ManifestInvalid,
23    /// The manifest is another version of the contract.
24    ManifestVersion,
25    /// The manifest needs something this runner doesn't do (a target that doesn't run on this
26    /// host, a delivery its driver doesn't take, an action of another driver's, a step with no
27    /// command for this host), or the call asks the run for something its target can't do (a
28    /// console into a Compose service with no VM, a Vagrant VM joined to another network).
29    Unsupported,
30    /// A file or folder couldn't be read or written, or a socket on this computer bound.
31    Io,
32    /// Another process runs an operation on this run, or holds the home's slot pick.
33    Locked,
34    /// A tool a step runs isn't installed.
35    ToolMissing,
36    /// A step's tool ran and failed.
37    ToolFailed,
38    /// A tool answers at a version older than the run needs.
39    ToolTooOld,
40    /// A step showed no progress for its time limit, or ran to the ceiling every step stops at,
41    /// and was stopped, with what it started (the `error` event's `timeout` says which).
42    Timeout,
43    /// A download (what a step needs, fetched in a phase of its own before it: a Compose start's
44    /// images, a Vagrant start's boxes; or a step the manifest marks a download) showed no
45    /// progress for as long as a download may, and was stopped.
46    DownloadStalled,
47    /// A download couldn't be made: its tool failed (the message says why: a registry or a box
48    /// catalog refusing it, a name it doesn't know, the network). A failure for the network that
49    /// passes (a connection reset, refused or timed out, a gateway's 502, 503 or 504) was tried
50    /// again first, up to three more times: the message is the last try's.
51    DownloadFailed,
52    /// The run is already up.
53    AlreadyRunning,
54    /// The run is recorded on another place (server or account) than the one asked for.
55    RunningElsewhere,
56    /// A host port the run publishes is taken.
57    PortInUse,
58    /// The manifest has no park steps for that mode.
59    NotParkable,
60    /// Nothing of the run, or not every one of its machines, is left to resume.
61    NothingToResume,
62    /// The run isn't up.
63    NotRunning,
64    /// A ready condition didn't hold.
65    NotReady,
66    /// A required secret or input has no value.
67    SecretMissing,
68    /// A param is unknown, missing or holds a value it doesn't allow.
69    ParamInvalid,
70    /// A run name that can't name a run.
71    RunName,
72    /// The run's Vagrant provider is missing, unknown, not on this host, refused by the run, or
73    /// lacks its plugin.
74    ProviderRefused,
75    /// The elevation Hyper-V's commands need couldn't be had or was lost: the permission prompt
76    /// declined or unanswered, the elevated session not started or ended before the operation
77    /// (the message says which).
78    ElevationFailed,
79    /// A machine the run doesn't have.
80    MachineUnknown,
81    /// The run has several machines the call could mean, and it named none.
82    MachineAmbiguous,
83    /// A network the run doesn't have.
84    NetworkUnknown,
85    /// Every slot of the place is held by another run.
86    SlotsFull,
87    /// A deployment can't be taken over as a run.
88    AdoptRefused,
89    /// A machine a step goes to over SSH never answered.
90    Unreachable,
91    /// The run's seal failed: it is up, but not sealed, so not ready.
92    NotSealed,
93    /// The operation was cut short before it ended (its future dropped: an embedder's cancel, the
94    /// command line's Ctrl-C or SIGTERM); the tools it started were asked to stop, and are ended
95    /// once they have, or 30 seconds later.
96    Cancelled,
97    /// The embedder was asked for something that makes no sense (the command line: a run folder
98    /// with no manifest, a value missing or malformed), so no operation started.
99    Usage,
100    /// The machine has no graphical console to reach: its target or provider gives none (the
101    /// error says why), it isn't running, or its hypervisor doesn't say where it is.
102    NoConsole,
103    /// The server the run is on (Proxmox VE, ESXi) refused the run's credentials: its API
104    /// answered 401 or 403, or its tool said the sign-in failed (an API token revoked, a password
105    /// changed).
106    ServerAuthFailed,
107}
108
109impl ErrorCode {
110    /// The code as written in JSON (`port_in_use`).
111    #[must_use]
112    pub fn as_str(self) -> &'static str {
113        match self {
114            ErrorCode::ManifestInvalid => "manifest_invalid",
115            ErrorCode::ManifestVersion => "manifest_version",
116            ErrorCode::Unsupported => "unsupported",
117            ErrorCode::Io => "io",
118            ErrorCode::Locked => "locked",
119            ErrorCode::ToolMissing => "tool_missing",
120            ErrorCode::ToolFailed => "tool_failed",
121            ErrorCode::ToolTooOld => "tool_too_old",
122            ErrorCode::Timeout => "timeout",
123            ErrorCode::DownloadStalled => "download_stalled",
124            ErrorCode::DownloadFailed => "download_failed",
125            ErrorCode::AlreadyRunning => "already_running",
126            ErrorCode::RunningElsewhere => "running_elsewhere",
127            ErrorCode::PortInUse => "port_in_use",
128            ErrorCode::NotParkable => "not_parkable",
129            ErrorCode::NothingToResume => "nothing_to_resume",
130            ErrorCode::NotRunning => "not_running",
131            ErrorCode::NotReady => "not_ready",
132            ErrorCode::SecretMissing => "secret_missing",
133            ErrorCode::ParamInvalid => "param_invalid",
134            ErrorCode::RunName => "run_name",
135            ErrorCode::ProviderRefused => "provider_refused",
136            ErrorCode::ElevationFailed => "elevation_failed",
137            ErrorCode::MachineUnknown => "machine_unknown",
138            ErrorCode::MachineAmbiguous => "machine_ambiguous",
139            ErrorCode::NetworkUnknown => "network_unknown",
140            ErrorCode::SlotsFull => "slots_full",
141            ErrorCode::AdoptRefused => "adopt_refused",
142            ErrorCode::Unreachable => "unreachable",
143            ErrorCode::NotSealed => "not_sealed",
144            ErrorCode::NoConsole => "no_console",
145            ErrorCode::Cancelled => "cancelled",
146            ErrorCode::Usage => "usage",
147            ErrorCode::ServerAuthFailed => "server_auth_failed",
148        }
149    }
150}
151
152/// The runner's `Result`: its error is a [`Error`] unless said otherwise.
153pub type Result<T, E = Error> = std::result::Result<T, E>;
154
155/// Why an operation of the runner failed.
156#[derive(Debug, thiserror::Error)]
157#[non_exhaustive]
158pub enum Error {
159    /// The manifest was refused (its own error names the field and the fix).
160    #[error("{}: {source}", path.display())]
161    Manifest {
162        /// The manifest's file.
163        path: PathBuf,
164        /// Why, with Isoloom's stable code (`source.code()`).
165        source: isoloom_manifest::Error,
166    },
167    /// The manifest needs something this runner doesn't do, or the call asks the run for
168    /// something its target can't do.
169    #[error("{what} isn't supported")]
170    Unsupported {
171        /// What, in a few words: target `cloud-vm` on this host; step `up`: the action
172        /// `ssh.run` on a compose run.
173        what: String,
174    },
175    /// A value the manifest gives that can't be used as written.
176    #[error("{at}: {reason}")]
177    Malformed {
178        /// Where (`lifecycle.up.copy.with.wait_s`).
179        at: String,
180        /// What is wrong with it.
181        reason: String,
182    },
183    /// A file or folder couldn't be read or written, or a loopback port bound.
184    #[error("{} couldn't be {action}: {source}", path.display())]
185    Io {
186        /// The file or folder (or the port: `a tcp port on 127.0.0.1`).
187        path: PathBuf,
188        /// What was done to it (`read`, `written`, `created`, `locked`, `bound`).
189        action: &'static str,
190        /// The OS's reason.
191        source: std::io::Error,
192    },
193    /// Another process holds the run's lock.
194    #[error("run `{run}` is busy: another process runs an operation on it")]
195    Locked {
196        /// The run.
197        run: String,
198    },
199    /// Another start held the home's slot pick for as long as a start waits for it.
200    #[error("another start has held this home's slot pick for {waited_s} s; it may hang")]
201    SlotsLocked {
202        /// How long this start waited, in seconds.
203        waited_s: u64,
204    },
205    /// A step's tool isn't on PATH.
206    #[error("step `{step}`: `{tool}` isn't installed or isn't on PATH")]
207    ToolMissing {
208        /// The step.
209        step: String,
210        /// The tool.
211        tool: String,
212    },
213    /// A tool answers at a version older than the manifest's `min_version` for it.
214    #[error("`{tool}` is version {found}; this run needs {required} or later")]
215    ToolTooOld {
216        /// The tool.
217        tool: String,
218        /// The version it answered with.
219        found: String,
220        /// The oldest version the run takes.
221        required: String,
222    },
223    /// A step's tool ran and failed.
224    #[error("step `{step}` failed: {reason}")]
225    ToolFailed {
226        /// The step.
227        step: String,
228        /// Its last error lines, or its exit status (secrets masked).
229        reason: String,
230    },
231    /// A step ran out of time: it showed no progress for its limit, or it ran to the ceiling.
232    #[error("step `{step}` {timed_out}")]
233    Timeout {
234        /// The step.
235        step: String,
236        /// Which limit it ran into.
237        timed_out: TimedOut,
238    },
239    /// A download (what a step downloads in its own phase before it runs, or a step the manifest
240    /// marks a download) showed no progress for `after_s` seconds, and was stopped. A download
241    /// has no other limit: one still moving runs as long as it moves.
242    #[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}`")))]
243    DownloadStalled {
244        /// The download's step (`pull-up` or `boxes-up`, before the `up` it downloads for; a
245        /// manifest's own, `pull-start`).
246        step: String,
247        /// How long it went without progress, in seconds.
248        after_s: u64,
249        /// The last line it printed (secrets masked, cut to 300 bytes); none when it printed
250        /// nothing.
251        last_line: Option<String>,
252    },
253    /// A download couldn't be made.
254    #[error("step `{step}` couldn't download what it needs: {reason}")]
255    DownloadFailed {
256        /// The download's step (`pull-up`, `boxes-up`, `pull-start`).
257        step: String,
258        /// The last try's last error lines, or its exit status (secrets masked).
259        reason: String,
260    },
261    /// The run is already up.
262    #[error("run `{run}` is already running")]
263    AlreadyRunning {
264        /// The run.
265        run: String,
266    },
267    /// The run is recorded somewhere else.
268    #[error("run `{run}` is recorded on `{recorded}`, not `{asked}`")]
269    RunningElsewhere {
270        /// The run.
271        run: String,
272        /// Where its record says it is.
273        recorded: String,
274        /// Where this operation was asked to run.
275        asked: String,
276    },
277    /// A host port the run publishes is taken.
278    #[error("host port {port}/{protocol} is in use")]
279    PortInUse {
280        /// The port.
281        port: u16,
282        /// `tcp` or `udp`.
283        protocol: String,
284    },
285    /// No park steps for that mode.
286    #[error("run `{run}` can't be parked ({mode}): its manifest has no steps for it")]
287    NotParkable {
288        /// The run.
289        run: String,
290        /// The mode asked for.
291        mode: &'static str,
292    },
293    /// Nothing left to resume.
294    #[error("run `{run}` has nothing left to resume: start it again")]
295    NothingToResume {
296        /// The run.
297        run: String,
298    },
299    /// Some of the run's machines are gone (removed outside the runner): a resume brings back
300    /// only what was kept, so it can't bring the run back as it was.
301    #[error("run `{run}` can't resume as it was: {} gone: start it again", gone(machines))]
302    PartlyGone {
303        /// The run.
304        run: String,
305        /// Its machines that are gone.
306        machines: Vec<String>,
307    },
308    /// The run isn't up.
309    #[error("run `{run}` isn't running")]
310    NotRunning {
311        /// The run.
312        run: String,
313    },
314    /// A ready condition didn't hold.
315    #[error("not ready: {condition}: {detail}")]
316    NotReady {
317        /// The condition (`step_ok up`, `tcp 127.0.0.1:8080`).
318        condition: String,
319        /// Why.
320        detail: String,
321    },
322    /// A required secret or input has no value.
323    #[error("secret `{name}` is required and has no value")]
324    SecretMissing {
325        /// The slot.
326        name: String,
327    },
328    /// A param that can't be used as given.
329    #[error("param `{name}`: {reason}")]
330    Param {
331        /// The param.
332        name: String,
333        /// Why.
334        reason: String,
335    },
336    /// A placeholder with no value at run time.
337    #[error("{at}: `${{{placeholder}}}` has no value in this operation")]
338    Unbound {
339        /// Where (`lifecycle.up.up`).
340        at: String,
341        /// The placeholder.
342        placeholder: String,
343    },
344    /// A machine the run doesn't have (to provision, console into, attach, detach or retire).
345    #[error("run `{run}` has no machine `{machine}`")]
346    MachineUnknown {
347        /// The run.
348        run: String,
349        /// The machine asked for.
350        machine: String,
351    },
352    /// The run has several machines the call could mean, and it named none.
353    #[error("run `{run}` has several {which} ({machines}): name one")]
354    MachineAmbiguous {
355        /// The run.
356        run: String,
357        /// Which machines the call could mean (`on-demand machines`).
358        which: &'static str,
359        /// Their names, comma-separated.
360        machines: String,
361    },
362    /// A network the run doesn't have.
363    #[error("run `{run}` has no network `{network}`")]
364    NetworkUnknown {
365        /// The run.
366        run: String,
367        /// The network asked for.
368        network: String,
369    },
370    /// The macOS relays to an ESXi host couldn't be set up (a relay that can't listen on the
371    /// loopback, a `PATH` that isn't UTF-8, the ovftool wrapper's folder that can't be written).
372    #[error("the relays to ESXi host `{host}` couldn't be set up: {source}")]
373    Relay {
374        /// The ESXi host.
375        host: String,
376        /// Why.
377        source: std::io::Error,
378    },
379    /// The elevation the run's commands need couldn't be had.
380    #[error("elevation: {reason}")]
381    Elevation {
382        /// Why (the permission prompt declined, the elevated session ended).
383        reason: String,
384    },
385    /// The run's Vagrant provider can't run it.
386    #[error("provider `{provider}`: {reason}")]
387    Provider {
388        /// The provider asked for.
389        provider: String,
390        /// Why it can't run the run, and what to do.
391        reason: String,
392    },
393    /// A Vagrant run was asked for with no provider.
394    #[error("a Vagrant run needs a provider: pass one of this run's ({providers})")]
395    NoProvider {
396        /// The run's providers, as the manifest names them (`` `virtualbox`, `libvirt` ``).
397        providers: String,
398    },
399    /// Every slot of the run's place is held by another run.
400    #[error("no slot is free on `{place}`: {held} runs hold one; stop one first")]
401    SlotsFull {
402        /// The place (the embedder's label for it, or `this host`).
403        place: String,
404        /// How many runs hold a slot there.
405        held: usize,
406    },
407    /// A machine a step goes to over SSH never answered within the step's `wait_s` (a guest
408    /// delivery's: 15 minutes).
409    #[error("step `{step}`: {login} didn't answer over SSH within {after_s}s: {reason}")]
410    Unreachable {
411        /// The step.
412        step: String,
413        /// The login it tried (`user@host`).
414        login: String,
415        /// How long it tried, in seconds.
416        after_s: u64,
417        /// ssh's last word.
418        reason: String,
419    },
420    /// The run's seal failed: it is up, unsealed, and never reported ready.
421    #[error("run `{run}` couldn't be sealed, so it isn't ready (stop it to remove it): {reason}")]
422    Unsealed {
423        /// The run.
424        run: String,
425        /// Why the seal failed.
426        reason: String,
427    },
428    /// A deployment that can't be taken over as a run.
429    #[error("run `{run}` can't take the deployment over: {reason}")]
430    Adopt {
431        /// The run it would have become.
432        run: String,
433        /// Why.
434        reason: String,
435    },
436    /// A run name that can't name a run.
437    #[error("`{value}` can't name a run: use 1 to 63 lowercase letters, digits, `-` or `_`, starting with a letter or digit")]
438    RunName {
439        /// The name as given.
440        value: String,
441    },
442    /// A machine with no graphical console to reach, and why.
443    #[error("machine `{machine}` has no graphical console: {why}")]
444    NoConsole {
445        /// The machine.
446        machine: String,
447        /// Why.
448        why: String,
449    },
450    /// The server the run is on refused the run's credentials (a 401 or 403 from its API, its
451    /// tool's failed sign-in): an API token revoked, a password changed.
452    #[error("step `{step}`: {} refused the run's credentials: {reason}", server.as_ref().map_or_else(|| "the server".to_owned(), |s| format!("server `{s}`")))]
453    ServerAuthFailed {
454        /// The step (`up`; `status` for a status read).
455        step: String,
456        /// The server, as the run's params name it (its API's host, the ESXi host), when they do.
457        server: Option<String>,
458        /// What the server or its tool said (secrets masked).
459        reason: String,
460    },
461}
462
463impl Error {
464    /// The failure's stable code.
465    #[must_use]
466    pub fn code(&self) -> ErrorCode {
467        match self {
468            Error::Manifest { source, .. } if source.code() == "version" => ErrorCode::ManifestVersion,
469            Error::Manifest { .. } | Error::Malformed { .. } | Error::Unbound { .. } => ErrorCode::ManifestInvalid,
470            Error::Unsupported { .. } => ErrorCode::Unsupported,
471            Error::Io { .. } | Error::Relay { .. } => ErrorCode::Io,
472            Error::Locked { .. } | Error::SlotsLocked { .. } => ErrorCode::Locked,
473            Error::ToolMissing { .. } => ErrorCode::ToolMissing,
474            Error::ToolTooOld { .. } => ErrorCode::ToolTooOld,
475            Error::ToolFailed { .. } => ErrorCode::ToolFailed,
476            Error::Timeout { .. } => ErrorCode::Timeout,
477            Error::DownloadStalled { .. } => ErrorCode::DownloadStalled,
478            Error::DownloadFailed { .. } => ErrorCode::DownloadFailed,
479            Error::AlreadyRunning { .. } => ErrorCode::AlreadyRunning,
480            Error::RunningElsewhere { .. } => ErrorCode::RunningElsewhere,
481            Error::PortInUse { .. } => ErrorCode::PortInUse,
482            Error::NotParkable { .. } => ErrorCode::NotParkable,
483            Error::NothingToResume { .. } | Error::PartlyGone { .. } => ErrorCode::NothingToResume,
484            Error::NotRunning { .. } => ErrorCode::NotRunning,
485            Error::NotReady { .. } => ErrorCode::NotReady,
486            Error::SecretMissing { .. } => ErrorCode::SecretMissing,
487            Error::Param { .. } => ErrorCode::ParamInvalid,
488            Error::RunName { .. } => ErrorCode::RunName,
489            Error::Provider { .. } | Error::NoProvider { .. } => ErrorCode::ProviderRefused,
490            Error::Elevation { .. } => ErrorCode::ElevationFailed,
491            Error::MachineUnknown { .. } => ErrorCode::MachineUnknown,
492            Error::MachineAmbiguous { .. } => ErrorCode::MachineAmbiguous,
493            Error::NetworkUnknown { .. } => ErrorCode::NetworkUnknown,
494            Error::SlotsFull { .. } => ErrorCode::SlotsFull,
495            Error::Adopt { .. } => ErrorCode::AdoptRefused,
496            Error::Unreachable { .. } => ErrorCode::Unreachable,
497            Error::Unsealed { .. } => ErrorCode::NotSealed,
498            Error::NoConsole { .. } => ErrorCode::NoConsole,
499            Error::ServerAuthFailed { .. } => ErrorCode::ServerAuthFailed,
500        }
501    }
502
503    /// An I/O failure on `path`.
504    pub(crate) fn io(path: impl Into<PathBuf>, action: &'static str) -> impl FnOnce(std::io::Error) -> Error {
505        let path = path.into();
506        move |source| Error::Io { path, action, source }
507    }
508}
509
510/// Machines `machines` as an error says they are gone: `web is`, `web and db are`, `a, b and c are`.
511fn gone(machines: &[String]) -> String {
512    let quoted: Vec<String> = machines.iter().map(|m| format!("`{m}`")).collect();
513    match quoted.as_slice() {
514        [] => "nothing is".to_owned(),
515        [one] => format!("machine {one} is"),
516        [rest @ .., last] => format!("machines {} and {last} are", rest.join(", ")),
517    }
518}
519
520impl std::fmt::Display for ErrorCode {
521    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
522        f.write_str(self.as_str())
523    }
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529
530    #[test]
531    fn every_code_is_written_as_serde_writes_it() {
532        crate::testing::assert_named_as_serde(ErrorCode::as_str);
533    }
534
535    #[test]
536    fn a_run_partly_gone_names_its_gone_machines_and_has_nothing_to_resume() {
537        let one = Error::PartlyGone {
538            run: "r".into(),
539            machines: vec!["web".into()],
540        };
541        assert_eq!(one.code(), ErrorCode::NothingToResume);
542        assert_eq!(one.to_string(), "run `r` can't resume as it was: machine `web` is gone: start it again");
543        let three = Error::PartlyGone {
544            run: "r".into(),
545            machines: vec!["a".into(), "b".into(), "c".into()],
546        };
547        assert!(three.to_string().contains("machines `a`, `b` and `c` are gone"), "{three}");
548    }
549
550    #[test]
551    fn an_elevation_that_failed_has_its_code_whatever_ended_it() {
552        let lost = Error::Elevation {
553            reason: "the elevated session ended: the broker stopped".into(),
554        };
555        assert_eq!((lost.code(), lost.code().as_str()), (ErrorCode::ElevationFailed, "elevation_failed"));
556    }
557
558    #[test]
559    fn another_manifest_version_has_its_own_code() {
560        for other in [0, 2] {
561            let err = isoloom_manifest::parse(&format!(r#"{{"manifest_version": {other}}}"#)).unwrap_err();
562            let err = Error::Manifest {
563                path: "run.json".into(),
564                source: err,
565            };
566            assert_eq!(err.code(), ErrorCode::ManifestVersion);
567            assert!(err.to_string().starts_with(&format!("run.json: manifest_version {other}")), "{err}");
568        }
569    }
570}