Skip to main content

isothrum_runner/error/
detail.rs

1//! What a failure says besides its code and message, as typed fields an embedder acts on (the
2//! port to free, the tool to install and the version it needs, how long a download stalled, the
3//! server that refused a sign-in, the secret to give). Versioned ([`DETAIL_VERSION`]), so a field
4//! a later runner adds is a new version, never a changed meaning.
5//!
6//! Never a secret. What a tool printed (a download's reason, a timed-out step's last line) is
7//! masked as the message is, wherever the event stream masks it.
8
9use std::path::PathBuf;
10
11use serde::{Deserialize, Serialize};
12
13use super::{Error, TimedOut};
14use crate::state::RunState;
15
16/// The version of [`ErrorDetail`]'s fields.
17pub const DETAIL_VERSION: u32 = 2;
18
19/// A failure's typed fields.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
21#[non_exhaustive]
22pub struct ErrorDetail {
23    /// The version of the fields ([`DETAIL_VERSION`]).
24    pub v: u32,
25    /// The fields, by the failure's kind.
26    #[serde(flatten)]
27    pub data: Detail,
28}
29
30/// What a download fetches.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
32#[serde(rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum DownloadKind {
35    /// Container images (a Compose start's pull).
36    Images,
37    /// Vagrant boxes (what a Vagrant start boots).
38    Boxes,
39}
40
41/// What a computer lacks for a Vagrant provider to run a run.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
43#[serde(rename_all = "snake_case")]
44#[non_exhaustive]
45pub enum ProviderNeed {
46    /// The Vagrant plugin the provider runs through (`Provider::plugin`: vagrant-qemu,
47    /// vagrant-libvirt, ...) isn't installed. A caller installs it for this account
48    /// (`vagrant plugin install <plugin>`, no administrator), then starts again.
49    Plugin,
50    /// virtiofsd, which libvirt and QEMU start to share a host folder with a VM through virtiofs
51    /// (Linux): none is installed where they look.
52    Virtiofsd,
53    /// The automation of the hypervisor's app: the program driving it through Apple events (UTM,
54    /// by `vagrant_utm`) may not send them (`-1743`, `Not authorized to send Apple events`, macOS's
55    /// Automation permission). Waiting doesn't fix it; the user's settings do.
56    Automation,
57    /// The system's approval of the hypervisor's app: it answered the machine's start, driven
58    /// through Apple events, with the system's `Operation not permitted` (UTM's `utmctl start`:
59    /// `OSStatus error -2700`) though the events reached it. The system refused to run the app's
60    /// own helper that launches machines: an app downloaded and quarantined, never approved when
61    /// opened, whose sandboxed helper gets no prompt. Waiting doesn't fix it; opening the app once
62    /// from the system's file manager, or reinstalling it, does.
63    AppApproval,
64}
65
66/// The process that holds a host port: what a `port_in_use` names so the user knows what to stop.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
68#[non_exhaustive]
69pub struct PortHolder {
70    /// Its process id.
71    pub pid: u32,
72    /// Its program's name, as the system lists it (`nginx`, `com.docke`: `lsof` cuts it to 9
73    /// characters).
74    pub program: String,
75}
76
77impl PortHolder {
78    /// Process `pid` running `program`.
79    #[must_use]
80    pub fn new(pid: u32, program: impl Into<String>) -> PortHolder {
81        PortHolder { pid, program: program.into() }
82    }
83}
84
85/// A failure's typed fields, by its kind.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
87#[serde(tag = "kind", rename_all = "snake_case")]
88#[non_exhaustive]
89pub enum Detail {
90    /// A host port the run publishes is taken.
91    PortInUse {
92        /// The port.
93        port: u16,
94        /// `tcp` or `udp`.
95        protocol: String,
96        /// The process listening on it, when it was found.
97        #[serde(default, skip_serializing_if = "Option::is_none")]
98        holder: Option<PortHolder>,
99    },
100    /// A tool isn't installed.
101    ToolMissing {
102        /// The tool.
103        tool: String,
104    },
105    /// A tool is older than the run needs.
106    ToolTooOld {
107        /// The tool.
108        tool: String,
109        /// The version it answered with.
110        found: String,
111        /// The oldest version the run takes.
112        required: String,
113    },
114    /// A tool's service didn't answer (Docker's engine).
115    ToolUnanswered {
116        /// The tool.
117        tool: String,
118    },
119    /// A step ran out of time.
120    Timeout {
121        /// Which limit it ran into.
122        timed_out: TimedOut,
123    },
124    /// A download showed no progress for as long as a download may.
125    DownloadStalled {
126        /// What it downloads.
127        what: DownloadKind,
128        /// How long it went with no progress, in seconds.
129        after_s: u64,
130    },
131    /// A download couldn't be made.
132    DownloadFailed {
133        /// What it downloads.
134        what: DownloadKind,
135        /// The last try's last error lines, or its exit status (masked).
136        reason: String,
137    },
138    /// The elevation the run's commands need couldn't be had.
139    Elevation {
140        /// Why (the prompt declined, the elevated session ended).
141        reason: String,
142    },
143    /// A ready condition didn't hold.
144    NotReady {
145        /// The condition (`every machine of the run`, `tcp 127.0.0.1:8080`).
146        condition: String,
147        /// Why it didn't.
148        detail: String,
149    },
150    /// The run is recorded on another place than the one asked for.
151    RunningElsewhere {
152        /// Where it is recorded.
153        recorded: String,
154        /// Where it was asked for.
155        asked: String,
156    },
157    /// The run can't be parked in that mode.
158    NotParkable {
159        /// The mode.
160        mode: String,
161    },
162    /// Machines of the run are gone, so it can't be resumed whole.
163    PartlyGone {
164        /// The machines gone.
165        machines: Vec<String>,
166    },
167    /// A secret the run needs has no value.
168    SecretMissing {
169        /// Its name.
170        name: String,
171    },
172    /// A value the run was given can't be used.
173    InputInvalid {
174        /// Its name.
175        name: String,
176        /// Why (masked: it may quote the value).
177        reason: String,
178    },
179    /// A step's tool ran and failed.
180    ToolFailed {
181        /// Its last error lines, or its exit status (masked).
182        reason: String,
183    },
184    /// The folder isn't a project to run.
185    ProjectInvalid {
186        /// The folder.
187        dir: PathBuf,
188    },
189    /// A machine the run doesn't have.
190    MachineUnknown {
191        /// The machine asked for.
192        machine: String,
193    },
194    /// A network the run doesn't have.
195    NetworkUnknown {
196        /// The network asked for.
197        network: String,
198    },
199    /// A Vagrant provider refused.
200    ProviderRefused {
201        /// The provider.
202        provider: String,
203        /// What this computer lacks for it, when that is what refused it.
204        #[serde(default, skip_serializing_if = "Option::is_none")]
205        need: Option<ProviderNeed>,
206    },
207    /// A tool refused this account.
208    ToolDenied {
209        /// The tool.
210        tool: String,
211    },
212    /// A cloud refused the sign-in the run's tools use.
213    CredentialsExpired {
214        /// The cloud, when the failure names its Terraform provider.
215        #[serde(default, skip_serializing_if = "Option::is_none")]
216        cloud: Option<crate::project::platform::Cloud>,
217        /// What the tool said (masked).
218        reason: String,
219    },
220    /// A network the run makes needs an address block another network holds.
221    AddressPoolOverlap {
222        /// What the tool said (masked).
223        reason: String,
224    },
225    /// A machine has no graphical console to reach.
226    NoConsole {
227        /// The machine.
228        machine: String,
229    },
230    /// The server the run is on refused its credentials.
231    ServerAuthFailed {
232        /// The server, when known.
233        server: Option<String>,
234    },
235    /// A file or folder couldn't be read or written.
236    Io {
237        /// The path.
238        path: PathBuf,
239        /// What was being done (`read`, `create`).
240        action: String,
241    },
242    /// The run moved between a read and the write that would have moved it.
243    StateConflict {
244        /// Where the write expected it.
245        expected: RunState,
246        /// Where it was.
247        found: Option<RunState>,
248    },
249    /// A live process holds the lease asked for.
250    LeaseHeld {
251        /// What the lease covers.
252        scope: String,
253        /// The holder's process id.
254        pid: u32,
255    },
256}
257
258impl Error {
259    /// The failure's typed fields, for one that has any beyond its code and message.
260    #[must_use]
261    pub fn detail(&self) -> Option<ErrorDetail> {
262        let data = self.tool_detail().or_else(|| self.run_detail())?;
263        Some(ErrorDetail { v: DETAIL_VERSION, data })
264    }
265
266    /// The fields of a failure of a tool, a download or a step.
267    fn tool_detail(&self) -> Option<Detail> {
268        Some(match self {
269            Error::PortInUse { port, protocol, holder } => Detail::PortInUse {
270                port: port.get(),
271                protocol: protocol.clone(),
272                holder: holder.clone(),
273            },
274            Error::ToolMissing { tool, .. } => Detail::ToolMissing { tool: tool.clone() },
275            Error::ToolTooOld { tool, found, required } => Detail::ToolTooOld {
276                tool: tool.clone(),
277                found: found.clone(),
278                required: required.clone(),
279            },
280            Error::ToolUnanswered { tool, .. } => Detail::ToolUnanswered { tool: tool.clone() },
281            Error::Timeout { timed_out, .. } => Detail::Timeout { timed_out: timed_out.clone() },
282            Error::DownloadStalled { what, after_s, .. } => Detail::DownloadStalled {
283                what: *what,
284                after_s: *after_s,
285            },
286            Error::DownloadFailed { what, reason, .. } => Detail::DownloadFailed {
287                what: *what,
288                reason: reason.clone(),
289            },
290            Error::Elevation { reason } => Detail::Elevation { reason: reason.clone() },
291            Error::NotReady { condition, detail } => Detail::NotReady {
292                condition: condition.clone(),
293                detail: detail.clone(),
294            },
295            Error::ToolFailed { reason, .. } => Detail::ToolFailed { reason: reason.clone() },
296            Error::ToolDenied { tool, .. } => Detail::ToolDenied { tool: tool.clone() },
297            Error::CredentialsExpired { cloud, reason, .. } => Detail::CredentialsExpired {
298                cloud: *cloud,
299                reason: reason.clone(),
300            },
301            Error::AddressPoolOverlap { reason, .. } => Detail::AddressPoolOverlap { reason: reason.clone() },
302            _ => return None,
303        })
304    }
305
306    /// The fields of a failure of the run, its inputs or the home.
307    fn run_detail(&self) -> Option<Detail> {
308        Some(match self {
309            Error::RunningElsewhere { recorded, asked, .. } => Detail::RunningElsewhere {
310                recorded: recorded.clone(),
311                asked: asked.clone(),
312            },
313            Error::NotParkable { mode, .. } => Detail::NotParkable { mode: (*mode).to_owned() },
314            Error::PartlyGone { machines, .. } => Detail::PartlyGone { machines: machines.clone() },
315            Error::SecretMissing { name } => Detail::SecretMissing { name: name.clone() },
316            Error::Input { name, reason } => Detail::InputInvalid {
317                name: name.clone(),
318                reason: reason.clone(),
319            },
320            Error::Project { dir, .. } => Detail::ProjectInvalid { dir: dir.clone() },
321            Error::MachineUnknown { machine, .. } => Detail::MachineUnknown { machine: machine.clone() },
322            Error::NetworkUnknown { network, .. } => Detail::NetworkUnknown { network: network.clone() },
323            Error::Provider { provider, need, .. } => Detail::ProviderRefused {
324                provider: provider.clone(),
325                need: *need,
326            },
327            Error::NoConsole { machine, .. } => Detail::NoConsole { machine: machine.clone() },
328            Error::ServerAuthFailed { server, .. } => Detail::ServerAuthFailed { server: server.clone() },
329            Error::Io { path, action, .. } => Detail::Io {
330                path: path.clone(),
331                action: (*action).to_owned(),
332            },
333            Error::StateConflict { expected, found, .. } => Detail::StateConflict {
334                expected: *expected,
335                found: *found,
336            },
337            Error::LeaseHeld { scope, pid } => Detail::LeaseHeld {
338                scope: scope.clone(),
339                pid: *pid,
340            },
341            _ => return None,
342        })
343    }
344}
345
346impl ErrorDetail {
347    /// The same, the text a tool printed passed through `mask`.
348    pub(crate) fn masked(self, mask: impl Fn(&str) -> String) -> ErrorDetail {
349        let data = match self.data {
350            Detail::Timeout { timed_out } => Detail::Timeout {
351                timed_out: timed_out.masked(&mask),
352            },
353            Detail::DownloadFailed { what, reason } => Detail::DownloadFailed { what, reason: mask(&reason) },
354            Detail::Elevation { reason } => Detail::Elevation { reason: mask(&reason) },
355            Detail::ToolFailed { reason } => Detail::ToolFailed { reason: mask(&reason) },
356            Detail::CredentialsExpired { cloud, reason } => Detail::CredentialsExpired { cloud, reason: mask(&reason) },
357            Detail::AddressPoolOverlap { reason } => Detail::AddressPoolOverlap { reason: mask(&reason) },
358            Detail::InputInvalid { name, reason } => Detail::InputInvalid { name, reason: mask(&reason) },
359            Detail::NotReady { condition, detail } => Detail::NotReady {
360                condition,
361                detail: mask(&detail),
362            },
363            other => other,
364        };
365        ErrorDetail { data, ..self }
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn a_port_in_use_says_its_port_versioned_and_flat() {
375        let e = Error::PortInUse {
376            port: crate::port::HostPort::new(8080),
377            protocol: "tcp".to_owned(),
378            holder: None,
379        };
380        let json = serde_json::to_value(e.detail().expect("a detail")).expect("json");
381        assert_eq!(json, serde_json::json!({ "v": 2, "kind": "port_in_use", "port": 8080, "protocol": "tcp" }));
382        let held = Error::PortInUse {
383            port: crate::port::HostPort::new(8080),
384            protocol: "tcp".to_owned(),
385            holder: Some(PortHolder::new(4123, "nginx")),
386        };
387        let held_json = serde_json::to_value(held.detail().expect("a detail")).expect("json");
388        assert_eq!(held_json["holder"], serde_json::json!({ "pid": 4123, "program": "nginx" }));
389        assert!(held.to_string().ends_with(": `nginx` (pid 4123) listens on it"), "{held}");
390    }
391
392    #[test]
393    fn what_a_tool_printed_in_the_fields_is_masked_as_the_message_is() {
394        let timeout = Error::Timeout {
395            step: "up".to_owned(),
396            timed_out: TimedOut::NoProgress {
397                after_s: 30,
398                last_line: Some("token=s3cret".to_owned()),
399            },
400        };
401        let failed = Error::DownloadFailed {
402            what: DownloadKind::Images,
403            step: "pull-up".to_owned(),
404            reason: "denied for s3cret".to_owned(),
405        };
406        for e in [timeout, failed] {
407            let detail = e.detail().expect("a detail");
408            assert!(serde_json::to_string(&detail).expect("json").contains("s3cret"));
409            let masked = serde_json::to_string(&detail.masked(|t| t.replace("s3cret", "***"))).expect("json");
410            assert!(!masked.contains("s3cret"), "{masked}");
411        }
412    }
413
414    #[test]
415    fn a_download_says_what_it_fetches() {
416        let e = Error::DownloadStalled {
417            what: DownloadKind::Boxes,
418            step: "up".to_owned(),
419            after_s: 900,
420            last_line: None,
421        };
422        let json = serde_json::to_value(e.detail().expect("a detail")).expect("json");
423        assert_eq!(json, serde_json::json!({ "v": 2, "kind": "download_stalled", "what": "boxes", "after_s": 900 }));
424    }
425
426    #[test]
427    fn a_failure_with_only_a_message_has_no_detail() {
428        let e = Error::Locked { run: "r".to_owned() };
429        assert!(e.detail().is_none());
430    }
431}