use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use super::{Error, TimedOut};
use crate::state::RunState;
pub const DETAIL_VERSION: u32 = 2;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[non_exhaustive]
pub struct ErrorDetail {
pub v: u32,
#[serde(flatten)]
pub data: Detail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DownloadKind {
Images,
Boxes,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProviderNeed {
Plugin,
Virtiofsd,
Automation,
AppApproval,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[non_exhaustive]
pub struct PortHolder {
pub pid: u32,
pub program: String,
}
impl PortHolder {
#[must_use]
pub fn new(pid: u32, program: impl Into<String>) -> PortHolder {
PortHolder { pid, program: program.into() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Detail {
PortInUse {
port: u16,
protocol: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
holder: Option<PortHolder>,
},
ToolMissing {
tool: String,
},
ToolTooOld {
tool: String,
found: String,
required: String,
},
ToolUnanswered {
tool: String,
},
Timeout {
timed_out: TimedOut,
},
DownloadStalled {
what: DownloadKind,
after_s: u64,
},
DownloadFailed {
what: DownloadKind,
reason: String,
},
Elevation {
reason: String,
},
NotReady {
condition: String,
detail: String,
},
RunningElsewhere {
recorded: String,
asked: String,
},
NotParkable {
mode: String,
},
PartlyGone {
machines: Vec<String>,
},
SecretMissing {
name: String,
},
InputInvalid {
name: String,
reason: String,
},
ToolFailed {
reason: String,
},
ProjectInvalid {
dir: PathBuf,
},
MachineUnknown {
machine: String,
},
NetworkUnknown {
network: String,
},
ProviderRefused {
provider: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
need: Option<ProviderNeed>,
},
ToolDenied {
tool: String,
},
CredentialsExpired {
#[serde(default, skip_serializing_if = "Option::is_none")]
cloud: Option<crate::project::platform::Cloud>,
reason: String,
},
AddressPoolOverlap {
reason: String,
},
NoConsole {
machine: String,
},
ServerAuthFailed {
server: Option<String>,
},
Io {
path: PathBuf,
action: String,
},
StateConflict {
expected: RunState,
found: Option<RunState>,
},
LeaseHeld {
scope: String,
pid: u32,
},
}
impl Error {
#[must_use]
pub fn detail(&self) -> Option<ErrorDetail> {
let data = self.tool_detail().or_else(|| self.run_detail())?;
Some(ErrorDetail { v: DETAIL_VERSION, data })
}
fn tool_detail(&self) -> Option<Detail> {
Some(match self {
Error::PortInUse { port, protocol, holder } => Detail::PortInUse {
port: port.get(),
protocol: protocol.clone(),
holder: holder.clone(),
},
Error::ToolMissing { tool, .. } => Detail::ToolMissing { tool: tool.clone() },
Error::ToolTooOld { tool, found, required } => Detail::ToolTooOld {
tool: tool.clone(),
found: found.clone(),
required: required.clone(),
},
Error::ToolUnanswered { tool, .. } => Detail::ToolUnanswered { tool: tool.clone() },
Error::Timeout { timed_out, .. } => Detail::Timeout { timed_out: timed_out.clone() },
Error::DownloadStalled { what, after_s, .. } => Detail::DownloadStalled {
what: *what,
after_s: *after_s,
},
Error::DownloadFailed { what, reason, .. } => Detail::DownloadFailed {
what: *what,
reason: reason.clone(),
},
Error::Elevation { reason } => Detail::Elevation { reason: reason.clone() },
Error::NotReady { condition, detail } => Detail::NotReady {
condition: condition.clone(),
detail: detail.clone(),
},
Error::ToolFailed { reason, .. } => Detail::ToolFailed { reason: reason.clone() },
Error::ToolDenied { tool, .. } => Detail::ToolDenied { tool: tool.clone() },
Error::CredentialsExpired { cloud, reason, .. } => Detail::CredentialsExpired {
cloud: *cloud,
reason: reason.clone(),
},
Error::AddressPoolOverlap { reason, .. } => Detail::AddressPoolOverlap { reason: reason.clone() },
_ => return None,
})
}
fn run_detail(&self) -> Option<Detail> {
Some(match self {
Error::RunningElsewhere { recorded, asked, .. } => Detail::RunningElsewhere {
recorded: recorded.clone(),
asked: asked.clone(),
},
Error::NotParkable { mode, .. } => Detail::NotParkable { mode: (*mode).to_owned() },
Error::PartlyGone { machines, .. } => Detail::PartlyGone { machines: machines.clone() },
Error::SecretMissing { name } => Detail::SecretMissing { name: name.clone() },
Error::Input { name, reason } => Detail::InputInvalid {
name: name.clone(),
reason: reason.clone(),
},
Error::Project { dir, .. } => Detail::ProjectInvalid { dir: dir.clone() },
Error::MachineUnknown { machine, .. } => Detail::MachineUnknown { machine: machine.clone() },
Error::NetworkUnknown { network, .. } => Detail::NetworkUnknown { network: network.clone() },
Error::Provider { provider, need, .. } => Detail::ProviderRefused {
provider: provider.clone(),
need: *need,
},
Error::NoConsole { machine, .. } => Detail::NoConsole { machine: machine.clone() },
Error::ServerAuthFailed { server, .. } => Detail::ServerAuthFailed { server: server.clone() },
Error::Io { path, action, .. } => Detail::Io {
path: path.clone(),
action: (*action).to_owned(),
},
Error::StateConflict { expected, found, .. } => Detail::StateConflict {
expected: *expected,
found: *found,
},
Error::LeaseHeld { scope, pid } => Detail::LeaseHeld {
scope: scope.clone(),
pid: *pid,
},
_ => return None,
})
}
}
impl ErrorDetail {
pub(crate) fn masked(self, mask: impl Fn(&str) -> String) -> ErrorDetail {
let data = match self.data {
Detail::Timeout { timed_out } => Detail::Timeout {
timed_out: timed_out.masked(&mask),
},
Detail::DownloadFailed { what, reason } => Detail::DownloadFailed { what, reason: mask(&reason) },
Detail::Elevation { reason } => Detail::Elevation { reason: mask(&reason) },
Detail::ToolFailed { reason } => Detail::ToolFailed { reason: mask(&reason) },
Detail::CredentialsExpired { cloud, reason } => Detail::CredentialsExpired { cloud, reason: mask(&reason) },
Detail::AddressPoolOverlap { reason } => Detail::AddressPoolOverlap { reason: mask(&reason) },
Detail::InputInvalid { name, reason } => Detail::InputInvalid { name, reason: mask(&reason) },
Detail::NotReady { condition, detail } => Detail::NotReady {
condition,
detail: mask(&detail),
},
other => other,
};
ErrorDetail { data, ..self }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_port_in_use_says_its_port_versioned_and_flat() {
let e = Error::PortInUse {
port: crate::port::HostPort::new(8080),
protocol: "tcp".to_owned(),
holder: None,
};
let json = serde_json::to_value(e.detail().expect("a detail")).expect("json");
assert_eq!(json, serde_json::json!({ "v": 2, "kind": "port_in_use", "port": 8080, "protocol": "tcp" }));
let held = Error::PortInUse {
port: crate::port::HostPort::new(8080),
protocol: "tcp".to_owned(),
holder: Some(PortHolder::new(4123, "nginx")),
};
let held_json = serde_json::to_value(held.detail().expect("a detail")).expect("json");
assert_eq!(held_json["holder"], serde_json::json!({ "pid": 4123, "program": "nginx" }));
assert!(held.to_string().ends_with(": `nginx` (pid 4123) listens on it"), "{held}");
}
#[test]
fn what_a_tool_printed_in_the_fields_is_masked_as_the_message_is() {
let timeout = Error::Timeout {
step: "up".to_owned(),
timed_out: TimedOut::NoProgress {
after_s: 30,
last_line: Some("token=s3cret".to_owned()),
},
};
let failed = Error::DownloadFailed {
what: DownloadKind::Images,
step: "pull-up".to_owned(),
reason: "denied for s3cret".to_owned(),
};
for e in [timeout, failed] {
let detail = e.detail().expect("a detail");
assert!(serde_json::to_string(&detail).expect("json").contains("s3cret"));
let masked = serde_json::to_string(&detail.masked(|t| t.replace("s3cret", "***"))).expect("json");
assert!(!masked.contains("s3cret"), "{masked}");
}
}
#[test]
fn a_download_says_what_it_fetches() {
let e = Error::DownloadStalled {
what: DownloadKind::Boxes,
step: "up".to_owned(),
after_s: 900,
last_line: None,
};
let json = serde_json::to_value(e.detail().expect("a detail")).expect("json");
assert_eq!(json, serde_json::json!({ "v": 2, "kind": "download_stalled", "what": "boxes", "after_s": 900 }));
}
#[test]
fn a_failure_with_only_a_message_has_no_detail() {
let e = Error::Locked { run: "r".to_owned() };
assert!(e.detail().is_none());
}
}