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