Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua): split create runtime errors by cause; actionable engine and cloud hints (#5000)

Francesco Bonacci43a76de6f8de
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx
index 7a5b204fcf..dbd39e89a7 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx
@@ -1640,4 +1640,4 @@ pub type RouteFuture = Pin<Box<dyn Future<Output = RouteDecision> + Send>>;
## Re-exports
-`sandbox::BuildFile`, `sandbox::BuildSpec`, `tokio_util::sync::CancellationToken`, `cua_vmm::cleanup`, `cua_fleet`, `cua_spacesd_client`, `cua_vmm::gpu`, `sandbox::ImageLayer`, `rmcp`, `cua_vmm::progress`, `sandbox::RegistryCredentials`, `sandbox::Sidecar`.
+`sandbox::BuildFile`, `sandbox::BuildSpec`, `tokio_util::sync::CancellationToken`, `cua_vmm::cleanup`, `cua_fleet`, `cua_spacesd_client`, `cua_vmm::gpu`, `sandbox::ImageLayer`, `rmcp`, `cua_vmm::progress`, `sandbox::RegistryCredentials`, `cua_vmm::error::failure_kind`, `sandbox::Sidecar`.
diff --git a/libs/cua/crates/cua-cli/src/sandbox.rs b/libs/cua/crates/cua-cli/src/sandbox.rs
index aaeb177c94..1f6d04861d 100644
--- a/libs/cua/crates/cua-cli/src/sandbox.rs
+++ b/libs/cua/crates/cua-cli/src/sandbox.rs
@@ -1355,6 +1355,13 @@ pub fn on_backend(e: CuaError, backend: &str) -> CuaError {
}
}
+/// Appended when `--on cloud` has no Cua cloud account: Spaces run on
+/// compute you bring, so point at the ways that need no Cua cloud.
+const BYO_COMPUTE_HINT: &str = "Cua Spaces run on computers you bring: this one (`--on local`), \
+ a machine you own (`cua auth login`, then `cua host setup --profile spare` on that machine \
+ and `--on host:<machine>` here), or your own cloud account (`cua cloud connect \
+ aws|gcp|modal`, then `--on aws`)";
+
/// What a failed create kept: the sandbox ref, its cloud claim (pool and
/// namespace) when it has one, and how to delete it.
fn kept_message(i: &SandboxInfo) -> String {
@@ -1545,12 +1552,20 @@ async fn create(
let sb = created
.map_err(|e| match e {
// The cloud came from a default: say how to sign in or go back.
- CuaError::ProviderNotConfigured(m) => CuaError::ProviderNotConfigured(
- match cua_sandbox_core::settings::cloud_default_hint(&placement.on_source) {
- Some(hint) => format!("{m}; {hint}"),
- None => m,
- },
- ),
+ // The cloud came from a default: say how to sign in or go back
+ // (once: some SDK paths have said it already).
+ CuaError::ProviderNotConfigured(mut m) => {
+ if let Some(hint) =
+ cua_sandbox_core::settings::cloud_default_hint(&placement.on_source)
+ && !m.contains(&hint)
+ {
+ m = format!("{m}; {hint}");
+ }
+ if on == On::Cloud {
+ m = format!("{m}. {BYO_COMPUTE_HINT}");
+ }
+ CuaError::ProviderNotConfigured(m)
+ }
other => other,
})
.map_err(|e| on_backend(e, &label))?;
diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rs
index 6e7713d175..e1ced0bac9 100644
--- a/libs/cua/crates/cua-daemon/src/local.rs
+++ b/libs/cua/crates/cua-daemon/src/local.rs
@@ -85,8 +85,8 @@ pub fn vmm_error(e: VmmError) -> Error {
}
VmmError::Invalid(m) => Error::InvalidArgument(m),
VmmError::UnsupportedImage { reason, .. } => Error::Unsupported(reason),
- VmmError::Missing { what, hint } => {
- Error::ProviderNotConfigured(format!("{what} is not available: {hint}"))
+ e @ (VmmError::Missing { .. } | VmmError::NotRunning { .. }) => {
+ Error::ProviderNotConfigured(e.to_string())
}
VmmError::InsufficientDisk(d) => Error::InsufficientDisk(d.to_string()),
other => Error::Runtime(other.to_string()),
diff --git a/libs/cua/crates/cua-sandbox-core/src/lib.rs b/libs/cua/crates/cua-sandbox-core/src/lib.rs
index 4b142f8741..c205572763 100644
--- a/libs/cua/crates/cua-sandbox-core/src/lib.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/lib.rs
@@ -23,6 +23,9 @@ pub mod mcp;
pub mod placement;
/// Clean-up a dropped (cancelled) create hands off ([`cleanup::settle`]).
pub use cua_vmm::cleanup;
+/// Why a local create failed, as a bounded telemetry word
+/// ([`cua_vmm::error::failure_kind`]).
+pub use cua_vmm::error::failure_kind as runtime_failure_kind;
/// GPU options per runtime ([`gpu::GpuSupport`]).
pub use cua_vmm::gpu;
/// Create progress: what a create is doing (pulling, booting, waiting for
diff --git a/libs/cua/crates/cua-sdk/src/native/telemetry.rs b/libs/cua/crates/cua-sdk/src/native/telemetry.rs
index e4b9ab2ecf..e07178e8f1 100644
--- a/libs/cua/crates/cua-sdk/src/native/telemetry.rs
+++ b/libs/cua/crates/cua-sdk/src/native/telemetry.rs
@@ -252,6 +252,20 @@ pub(crate) fn variant<T>(r: &Result<T>) -> Option<&'static str> {
r.as_ref().err().map(CuaError::variant)
}
+/// A create's error kind: a local runtime failure split by cause
+/// (`runtime_missing`, `runtime_not_running`, `runtime_permission`,
+/// `image_pull`), else the variant. Only the bounded word leaves the
+/// process, never the message.
+fn create_error_kind<T>(on: &str, r: &Result<T>) -> Option<&'static str> {
+ let e = r.as_ref().err()?;
+ let local_runtime =
+ on == "local" && matches!(e, CuaError::Runtime(_) | CuaError::ProviderNotConfigured(_));
+ if local_runtime && let Some(kind) = cua_sandbox_core::runtime_failure_kind(&e.to_string()) {
+ return Some(kind);
+ }
+ Some(e.variant())
+}
+
fn outcome<T>(r: &Result<T>) -> Outcome {
if r.is_ok() {
Outcome::Ok
@@ -332,7 +346,7 @@ impl CreateFacts {
with_build: self.build,
},
outcome(r),
- variant(r),
+ create_error_kind(&self.on, r),
self.started.elapsed(),
);
t().capture(e);
@@ -413,6 +427,43 @@ mod cua_keyvault_links {
mod tests {
use super::*;
+ #[test]
+ fn create_error_kind_splits_local_runtime_failures() {
+ let err = |e: CuaError| -> Result<()> { Err(e) };
+ let kind = |on: &str, e: CuaError| {
+ create_error_kind(on, &err(e)).map(cua_telemetry::events::error_kind)
+ };
+ let no_engine = "local runtime: [local] a container engine is not available: no socket";
+ assert_eq!(
+ kind("local", CuaError::Runtime(no_engine.into())),
+ Some("runtime_missing")
+ );
+ assert_eq!(
+ kind("local", CuaError::ProviderNotConfigured(no_engine.into())),
+ Some("runtime_missing")
+ );
+ assert_eq!(
+ kind(
+ "local",
+ CuaError::Runtime("permission denied on unix:///x: add".into())
+ ),
+ Some("runtime_permission")
+ );
+ assert_eq!(
+ kind("local", CuaError::Runtime("boom".into())),
+ Some("runtime")
+ );
+ // A cloud without an account stays provider_not_configured.
+ assert_eq!(
+ kind(
+ "cloud",
+ CuaError::ProviderNotConfigured("x is not available: y".into())
+ ),
+ Some("provider_not_configured")
+ );
+ assert_eq!(create_error_kind::<()>("local", &Ok(())), None);
+ }
+
#[test]
fn requires_cua_app_maps_to_its_own_outcome() {
let m = "Teleport requires the Cua app, which keeps your sessions in its Keyvault and asks you before anything moves. Install it from https://cua.ai/download.";
diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rs
index 50213c6088..eec20d2a23 100644
--- a/libs/cua/crates/cua-telemetry/src/schema.rs
+++ b/libs/cua/crates/cua-telemetry/src/schema.rs
@@ -137,6 +137,11 @@ pub const ERROR_KINDS: &[&str] = &[
"fleet",
"fleet_admission_denied",
"runtime",
+ // A local create's runtime failure, split by cause (cua_sandbox_created).
+ "runtime_missing",
+ "runtime_not_running",
+ "runtime_permission",
+ "image_pull",
"env",
"http",
"unauthenticated",
diff --git a/libs/cua/crates/cua-vmm/src/auto.rs b/libs/cua/crates/cua-vmm/src/auto.rs
index 860996786b..7a94df6bef 100644
--- a/libs/cua/crates/cua-vmm/src/auto.rs
+++ b/libs/cua/crates/cua-vmm/src/auto.rs
@@ -488,13 +488,14 @@ pub fn select(req: &SelectRequest, report: &DoctorReport) -> Result<Selection> {
provisioning: m.provisioning,
});
}
+ // An engine was found but is stopped or refused: its own
+ // message says how to start it or get access.
+ if report.container.endpoint.is_some() {
+ return Err(VmmError::other(c.detail));
+ }
Err(VmmError::missing(
"a container engine",
- format!(
- "{}. Install Docker (or Colima), or set `runtime.linux` to `auto` to use \
- the built-in Linux runtime on a Mac",
- c.detail
- ),
+ format!("{}; {}", c.detail, engine_install_hint()),
))
}
ImageKind::Vm => match req.os {
@@ -553,6 +554,18 @@ pub fn select(req: &SelectRequest, report: &DoctorReport) -> Result<Selection> {
}
}
+/// How to get a container engine here.
+fn engine_install_hint() -> &'static str {
+ #[cfg(feature = "container")]
+ {
+ crate::container::engine::install_hint()
+ }
+ #[cfg(not(feature = "container"))]
+ {
+ "install Docker or Podman and start it"
+ }
+}
+
/// The Lume binary the setting picks (see [`crate::lume::builtin`]).
fn lume_binary() -> Option<PathBuf> {
#[cfg(feature = "lume")]
diff --git a/libs/cua/crates/cua-vmm/src/container/engine.rs b/libs/cua/crates/cua-vmm/src/container/engine.rs
index cb5e215d09..6b143ef7af 100644
--- a/libs/cua/crates/cua-vmm/src/container/engine.rs
+++ b/libs/cua/crates/cua-vmm/src/container/engine.rs
@@ -125,6 +125,128 @@ fn well_known_sockets() -> Vec<PathBuf> {
v
}
+/// Docker Desktop's engine pipe on Windows (the docker CLI's `default`
+/// context).
+#[cfg(windows)]
+const WINDOWS_ENGINE_PIPE: &str = r"\\.\pipe\docker_engine";
+
+/// How to get a container engine on this host, for "no engine found".
+pub fn install_hint() -> &'static str {
+ match std::env::consts::OS {
+ "linux" => {
+ "install Docker Engine (`curl -fsSL https://get.docker.com | sh`, then \
+ `sudo systemctl enable --now docker`) or Podman (`systemctl --user enable --now \
+ podman.socket`)"
+ }
+ "macos" => {
+ "install one (`brew install colima docker && colima start`, Docker Desktop or \
+ OrbStack), or set `runtime.linux` to `auto` to use the built-in Linux runtime"
+ }
+ "windows" => {
+ "install Docker Desktop (https://docs.docker.com/desktop/setup/install/windows-install/) \
+ and start it"
+ }
+ _ => "install Docker or Podman and start it",
+ }
+}
+
+/// How to start the engine `kind`, for "the engine does not answer".
+pub fn start_hint(kind: &EngineKind) -> &'static str {
+ match kind {
+ EngineKind::Colima { .. } => "start it with `colima start`",
+ EngineKind::DockerDesktop => "open Docker Desktop and wait until it says it is running",
+ EngineKind::OrbStack => "start it with `orb start`",
+ EngineKind::Podman if cfg!(target_os = "linux") => {
+ "start it with `systemctl --user start podman.socket`"
+ }
+ EngineKind::Podman => "start it with `podman machine start`",
+ EngineKind::NativeLinux => "start it with `sudo systemctl start docker`",
+ EngineKind::Unknown if cfg!(target_os = "linux") => {
+ "start it (`sudo systemctl start docker`, or `systemctl --user start podman.socket`)"
+ }
+ EngineKind::Unknown => "start your container engine",
+ }
+}
+
+/// How to get access to `socket`, for "permission denied".
+pub fn permission_hint(socket: &str) -> String {
+ if cfg!(target_os = "linux") {
+ format!(
+ "permission denied on {socket}: add yourself to the `docker` group \
+ (`sudo usermod -aG docker $USER`, then log out and back in), or use rootless \
+ Docker or Podman"
+ )
+ } else {
+ format!("permission denied on {socket}: check that your user may use the engine's socket")
+ }
+}
+
+/// What a connect to a Unix engine socket found before speaking HTTP.
+#[derive(Debug, PartialEq, Eq)]
+pub enum SocketCheck {
+ /// Something accepted the connection.
+ Accepting,
+ /// The socket file is gone (or dangling): no engine is installed or running.
+ Missing,
+ /// Nothing listens on it: the engine is installed but not running.
+ NotListening,
+ /// This user may not connect.
+ PermissionDenied,
+ /// Any other error (kept as text).
+ Other(String),
+}
+
+/// Connects to the Unix socket behind `uri` (`unix:///path` or a path)
+/// without speaking HTTP, so "not running" and "permission denied" are
+/// told apart before the ping. `None` for other URIs (tcp, npipe) and when
+/// the connect does not finish in 5 s (a hung engine: the ping decides).
+pub async fn check_socket(uri: &str) -> Option<SocketCheck> {
+ #[cfg(unix)]
+ {
+ let path = uri
+ .strip_prefix("unix://")
+ .or_else(|| uri.starts_with('/').then_some(uri))?;
+ let connect = tokio::net::UnixStream::connect(path);
+ let r = tokio::time::timeout(std::time::Duration::from_secs(5), connect)
+ .await
+ .ok()?;
+ Some(match r {
+ Ok(_) => SocketCheck::Accepting,
+ Err(e) => match e.kind() {
+ std::io::ErrorKind::PermissionDenied => SocketCheck::PermissionDenied,
+ std::io::ErrorKind::NotFound => SocketCheck::Missing,
+ std::io::ErrorKind::ConnectionRefused => SocketCheck::NotListening,
+ _ => SocketCheck::Other(e.to_string()),
+ },
+ })
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = uri;
+ None
+ }
+}
+
+fn docker_config_dir() -> PathBuf {
+ std::env::var_os("DOCKER_CONFIG")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| host::home_dir().join(".docker"))
+}
+
+/// The docker CLI's current context when its Unix socket is gone: an
+/// engine that is installed but stopped (Docker Desktop quit). For the
+/// "no engine" message only; [`discover`] never returns it.
+pub fn stopped_context() -> Option<EngineEndpoint> {
+ let env_ctx = std::env::var("DOCKER_CONTEXT").ok();
+ let (name, h) = context_endpoint(&docker_config_dir(), env_ctx.as_deref())?;
+ let path = h.strip_prefix("unix://")?;
+ (!Path::new(path).exists()).then(|| EngineEndpoint {
+ kind: classify(&h),
+ uri: h.clone(),
+ source: format!("context:{name}"),
+ })
+}
+
/// Find the engine endpoint the way the docker CLI would.
pub fn discover() -> Option<EngineEndpoint> {
if let Ok(h) = std::env::var("DOCKER_HOST")
@@ -136,9 +258,7 @@ pub fn discover() -> Option<EngineEndpoint> {
source: "DOCKER_HOST".into(),
});
}
- let docker_dir = std::env::var_os("DOCKER_CONFIG")
- .map(PathBuf::from)
- .unwrap_or_else(|| host::home_dir().join(".docker"));
+ let docker_dir = docker_config_dir();
let env_ctx = std::env::var("DOCKER_CONTEXT").ok();
if let Some((name, h)) = context_endpoint(&docker_dir, env_ctx.as_deref()) {
let path = h.trim_start_matches("unix://");
@@ -150,6 +270,14 @@ pub fn discover() -> Option<EngineEndpoint> {
});
}
}
+ #[cfg(windows)]
+ if Path::new(WINDOWS_ENGINE_PIPE).exists() {
+ return Some(EngineEndpoint {
+ uri: "npipe:////./pipe/docker_engine".into(),
+ source: "socket".into(),
+ kind: EngineKind::DockerDesktop,
+ });
+ }
well_known_sockets()
.into_iter()
.find(|p| p.exists())
@@ -195,6 +323,48 @@ mod tests {
);
}
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn check_socket_tells_not_running_from_missing_and_up() {
+ let d = tempfile::tempdir().unwrap();
+ let path = d.path().join("docker.sock");
+ let uri = format!("unix://{}", path.display());
+ assert_eq!(check_socket(&uri).await, Some(SocketCheck::Missing));
+ let listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
+ assert_eq!(check_socket(&uri).await, Some(SocketCheck::Accepting));
+ // The engine stopped and left its socket file behind.
+ drop(listener);
+ // A child another test forks can hold the listener a moment longer.
+ let mut seen = None;
+ for _ in 0..50 {
+ seen = check_socket(&uri).await;
+ if seen == Some(SocketCheck::NotListening) {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ assert_eq!(seen, Some(SocketCheck::NotListening));
+ assert_eq!(check_socket("tcp://127.0.0.1:2375").await, None);
+ }
+
+ #[test]
+ fn hints_name_this_hosts_commands() {
+ if cfg!(target_os = "linux") {
+ assert!(install_hint().contains("get.docker.com"));
+ assert!(start_hint(&EngineKind::NativeLinux).contains("systemctl start docker"));
+ assert!(permission_hint("unix:///var/run/docker.sock").contains("usermod -aG docker"));
+ }
+ if cfg!(target_os = "macos") {
+ assert!(install_hint().contains("colima"));
+ }
+ assert!(
+ start_hint(&EngineKind::Colima {
+ profile: "default".into()
+ })
+ .contains("colima start")
+ );
+ }
+
#[test]
fn reads_current_context_from_docker_config() {
let d = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-vmm/src/container/mod.rs b/libs/cua/crates/cua-vmm/src/container/mod.rs
index 533a0b4bee..45e51a3b53 100644
--- a/libs/cua/crates/cua-vmm/src/container/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/container/mod.rs
@@ -159,24 +159,65 @@ impl ContainerRuntime {
/// Connect to the engine (discovering it when no endpoint is configured).
pub async fn connect(cfg: ContainerConfig) -> Result<Self> {
let endpoint = match &cfg.endpoint {
- Some(uri) => EngineEndpoint { kind: engine::classify(uri), uri: uri.clone(), source: "config".into() },
- None => engine::discover().ok_or_else(|| {
- VmmError::missing(
- "a container engine",
- "no Docker-API socket found (DOCKER_HOST, docker context, ~/.colima, ~/.orbstack, \
- ~/.docker/run, /var/run/docker.sock). Install one (macOS: `brew install colima docker && colima start`) \
- or let cua boot its managed runtime VM",
- )
- })?,
+ Some(uri) => EngineEndpoint {
+ kind: engine::classify(uri),
+ uri: uri.clone(),
+ source: "config".into(),
+ },
+ None => match engine::discover() {
+ Some(ep) => ep,
+ // Docker Desktop quit (its context's socket is gone): start
+ // it, rather than install one.
+ None => match engine::stopped_context() {
+ Some(ep) => {
+ return Err(VmmError::NotRunning {
+ what: format!("container engine at {}", ep.uri),
+ hint: engine::start_hint(&ep.kind).into(),
+ });
+ }
+ None => {
+ return Err(VmmError::missing(
+ "a container engine",
+ format!(
+ "no Docker-API socket found (DOCKER_HOST, docker context, \
+ ~/.colima, ~/.orbstack, ~/.docker/run, /var/run/docker.sock); {}",
+ engine::install_hint()
+ ),
+ ));
+ }
+ },
+ },
};
+ let at = format!("container engine at {}", endpoint.uri);
+ let check = engine::check_socket(&endpoint.uri).await;
+ match &check {
+ Some(engine::SocketCheck::PermissionDenied) => {
+ return Err(VmmError::PermissionDenied(engine::permission_hint(
+ &endpoint.uri,
+ )));
+ }
+ Some(engine::SocketCheck::Missing | engine::SocketCheck::NotListening) => {
+ return Err(VmmError::NotRunning {
+ what: at,
+ hint: engine::start_hint(&endpoint.kind).into(),
+ });
+ }
+ _ => {}
+ }
let docker = connect_uri(&endpoint.uri)?;
- docker.ping().await.map_err(|e| {
- VmmError::missing(
- format!("container engine at {}", endpoint.uri),
- format!(
- "engine did not answer ping ({e}); is it running? (Colima: `colima start`)"
+ docker.ping().await.map_err(|e| match check {
+ // Something accepts on the socket but does not speak the
+ // Docker API as expected: an engine error, not a stopped one.
+ Some(engine::SocketCheck::Accepting) => {
+ VmmError::Engine(format!("{at} did not answer ping: {e}"))
+ }
+ _ => VmmError::NotRunning {
+ what: at,
+ hint: format!(
+ "it did not answer ({e}); {}",
+ engine::start_hint(&endpoint.kind)
),
- )
+ },
})?;
Ok(Self {
docker,
diff --git a/libs/cua/crates/cua-vmm/src/error.rs b/libs/cua/crates/cua-vmm/src/error.rs
index 8ccef447ce..11dc664428 100644
--- a/libs/cua/crates/cua-vmm/src/error.rs
+++ b/libs/cua/crates/cua-vmm/src/error.rs
@@ -17,6 +17,16 @@ pub enum VmmError {
#[error("{what} is not available: {hint}")]
Missing { what: String, hint: String },
+ /// A host prerequisite is installed but not running (a container
+ /// engine whose socket accepts nothing). `hint` says how to start it.
+ #[error("{what} is not running: {hint}")]
+ NotRunning { what: String, hint: String },
+
+ /// This user may not use a host prerequisite (the engine socket, KVM).
+ /// The message names it and how to get access.
+ #[error("{0}")]
+ PermissionDenied(String),
+
/// No instance with that name is known to the backend.
#[error("sandbox '{0}' not found")]
NotFound(String),
@@ -89,6 +99,31 @@ pub enum VmmError {
Other(String),
}
+/// Why a local create failed, as a bounded word for telemetry (never the
+/// message): `runtime_missing`, `runtime_not_running`,
+/// `runtime_permission`, `image_pull`, else `None`.
+pub fn failure_kind(message: &str) -> Option<&'static str> {
+ let m = message.to_ascii_lowercase();
+ if m.contains("container engine: pull ")
+ || m.contains("manifest unknown")
+ || m.contains("pull access denied")
+ || m.contains("toomanyrequests")
+ {
+ Some("image_pull")
+ } else if m.contains("permission denied") {
+ Some("runtime_permission")
+ } else if m.contains(" is not running: ") {
+ Some("runtime_not_running")
+ } else if m.contains(" is not available: ")
+ && !m.contains("local network access")
+ && !m.contains("network route")
+ {
+ Some("runtime_missing")
+ } else {
+ None
+ }
+}
+
impl VmmError {
pub fn missing(what: impl Into<String>, hint: impl Into<String>) -> Self {
Self::Missing {
@@ -105,3 +140,33 @@ impl VmmError {
Self::Other(msg.into())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Each cause classifies from the message the create shows, also when
+ /// a caller wrapped it (`local runtime: [local] ...`).
+ #[test]
+ fn failure_kind_splits_runtime_causes() {
+ let wrap = |e: VmmError| format!("local runtime: [local] {e}");
+ let missing = VmmError::missing("a container engine", "no Docker-API socket found");
+ assert_eq!(failure_kind(&wrap(missing)), Some("runtime_missing"));
+ let down = VmmError::NotRunning {
+ what: "container engine at unix:///var/run/docker.sock".into(),
+ hint: "start it with `sudo systemctl start docker`".into(),
+ };
+ assert_eq!(failure_kind(&wrap(down)), Some("runtime_not_running"));
+ let denied = VmmError::PermissionDenied(
+ "permission denied on unix:///var/run/docker.sock: add yourself".into(),
+ );
+ assert_eq!(failure_kind(&wrap(denied)), Some("runtime_permission"));
+ let pull = VmmError::Engine("pull ghcr.io/x/y:1: manifest unknown".into());
+ assert_eq!(failure_kind(&wrap(pull)), Some("image_pull"));
+ let denied_pull = VmmError::Engine("pull x: pull access denied for x".into());
+ assert_eq!(failure_kind(&denied_pull.to_string()), Some("image_pull"));
+ assert_eq!(failure_kind(&VmmError::other("boom").to_string()), None);
+ let lan = VmmError::missing("Local Network access", "click Allow");
+ assert_eq!(failure_kind(&lan.to_string()), None);
+ }
+}