Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/openshell-container-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ gateway, supervisor, or Kubernetes driver also uses does not belong here.

## Contents

- `docker_socket` finds the local Docker API socket, including Docker Desktop's
per-user socket on macOS.
- `podman_socket`: Podman API socket discovery for native and machine-backed
installations.
33 changes: 33 additions & 0 deletions crates/openshell-container-runtime/src/docker_socket.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Docker API socket discovery for local and desktop installations.

use openshell_core::local_api_socket::{
contains_ascii, first_responsive_socket, http_response_is_success,
};
use std::path::PathBuf;

/// Return the first responsive local Docker API socket.
#[must_use]
pub fn detect_socket() -> Option<PathBuf> {
let mut candidates = Vec::new();
if let Ok(host) = std::env::var("DOCKER_HOST")
&& let Some(path) = host.trim().strip_prefix("unix://")
&& !path.is_empty()
{
candidates.push(PathBuf::from(path));
}
candidates.push(PathBuf::from("/var/run/docker.sock"));
if let Some(home) = std::env::var_os("HOME") {
candidates.push(PathBuf::from(home).join(".docker/run/docker.sock"));
}
if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") {
candidates.push(PathBuf::from(runtime_dir).join("docker.sock"));
}
first_responsive_socket(&candidates, |response| {
http_response_is_success(response)
&& contains_ascii(response, b"Api-Version:")
&& !contains_ascii(response, b"Libpod-Api-Version:")
})
}
1 change: 1 addition & 0 deletions crates/openshell-container-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
//! Everything here is used only by the Docker, Podman, and VM drivers, so the
//! crate moves with them when they leave this repository.

pub mod docker_socket;
pub mod podman_socket;
1 change: 1 addition & 0 deletions crates/openshell-driver-docker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ name = "openshell-driver-docker"
path = "src/main.rs"

[dependencies]
openshell-container-runtime = { path = "../openshell-container-runtime" }
openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction", "otel", "clap"] }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-sandbox-backend = { path = "../openshell-sandbox-backend" }
Expand Down
25 changes: 1 addition & 24 deletions crates/openshell-driver-docker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use bollard::query_parameters::{
};
use bytes::Bytes;
use futures::{Stream, StreamExt};
pub use openshell_container_runtime::docker_socket::detect_socket;
use openshell_core::config::DEFAULT_STOP_TIMEOUT_SECS;
use openshell_core::driver_mounts;
use openshell_core::driver_utils::{
Expand Down Expand Up @@ -888,30 +889,6 @@ impl ComputeDriverService {
}
}

/// Return the first responsive local Docker API socket.
#[must_use]
pub fn detect_socket() -> Option<PathBuf> {
let mut candidates = Vec::new();
if let Ok(host) = std::env::var("DOCKER_HOST")
&& let Some(path) = host.trim().strip_prefix("unix://")
&& !path.is_empty()
{
candidates.push(PathBuf::from(path));
}
candidates.push(PathBuf::from("/var/run/docker.sock"));
if let Some(home) = std::env::var_os("HOME") {
candidates.push(PathBuf::from(home).join(".docker/run/docker.sock"));
}
if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") {
candidates.push(PathBuf::from(runtime_dir).join("docker.sock"));
}
openshell_core::local_api_socket::first_responsive_socket(&candidates, |response| {
openshell_core::local_api_socket::http_response_is_success(response)
&& openshell_core::local_api_socket::contains_ascii(response, b"Api-Version:")
&& !openshell_core::local_api_socket::contains_ascii(response, b"Libpod-Api-Version:")
})
}

#[must_use]
pub fn is_available() -> bool {
detect_socket().is_some()
Expand Down
7 changes: 5 additions & 2 deletions crates/openshell-driver-vm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -305,8 +305,11 @@ create TAP devices or install nftables/iptables rules.
- Docker or Podman socket on the local CLI/gateway host when building an image
before `openshell sandbox create --from <image>`; the VM driver exports the
image via the local container engine.
Docker is tried first; if unavailable, the driver falls back to the Podman
socket. On Linux, enable the Podman API socket with
The VM driver tries Docker first, including Docker Desktop's per-user socket
at `~/.docker/run/docker.sock` on macOS. If your Docker context uses a socket
outside the standard paths, set `DOCKER_HOST=unix:///absolute/path/to/docker.sock`
in the gateway service environment. If Docker is unavailable, the driver tries
Podman. On Linux, enable the Podman API socket with
`systemctl --user start podman.socket`
- `gh` CLI (used by `mise run vm:setup` to download pre-built runtime artifacts)

Expand Down
160 changes: 142 additions & 18 deletions crates/openshell-driver-vm/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5855,35 +5855,47 @@ fn parse_registry_reference(image_ref: &str) -> Result<Reference, Status> {
})
}

/// Try to connect to a local container engine (Docker or Podman).
///
/// Tries Docker first (`connect_with_local_defaults`, which respects
/// `DOCKER_HOST`). If Docker is unavailable, falls back to the Podman
/// socket, which exposes a Docker-compatible API.
/// Try the default Unix socket, then Docker's discovered socket, then Podman.
async fn connect_local_container_engine() -> Option<Docker> {
connect_container_engine(
openshell_container_runtime::docker_socket::detect_socket,
openshell_container_runtime::podman_socket::detect_socket,
)
.await
}

async fn connect_container_engine(
docker_socket: impl FnOnce() -> Option<PathBuf> + Send + 'static,
podman_socket: impl FnOnce() -> Option<PathBuf> + Send + 'static,
) -> Option<Docker> {
if let Ok(docker) = Docker::connect_with_local_defaults()
&& docker.ping().await.is_ok()
{
return Some(docker);
}

let podman_socket = detect_podman_socket()?;
if let Ok(docker) =
Docker::connect_with_unix(podman_socket.to_str()?, 120, bollard::API_DEFAULT_VERSION)
&& docker.ping().await.is_ok()
{
info!(
socket = %podman_socket.display(),
"vm driver: connected to Podman (Docker-compatible API)"
);
if let Some(docker) = connect_engine_socket("Docker", docker_socket).await {
return Some(docker);
}

None
connect_engine_socket("Podman", podman_socket).await
}

fn detect_podman_socket() -> Option<PathBuf> {
openshell_container_runtime::podman_socket::detect_socket()
async fn connect_engine_socket(
engine: &str,
detect_socket: impl FnOnce() -> Option<PathBuf> + Send + 'static,
) -> Option<Docker> {
let socket = match tokio::task::spawn_blocking(detect_socket).await {
Ok(socket) => socket?,
Err(err) => {
warn!(engine, error = %err, "vm driver: socket discovery task failed");
return None;
}
};
let docker =
Docker::connect_with_unix(socket.to_str()?, 120, bollard::API_DEFAULT_VERSION).ok()?;
docker.ping().await.ok()?;
info!(engine, socket = %socket.display(), "vm driver: connected to local container engine");
Some(docker)
}

fn is_openshell_local_build_image_ref(image_ref: &str) -> bool {
Expand Down Expand Up @@ -8358,6 +8370,118 @@ mod tests {
static ENV_LOCK: std::sync::LazyLock<std::sync::Mutex<()>> =
std::sync::LazyLock::new(|| std::sync::Mutex::new(()));

const DOCKER_PING: &[u8] =
b"HTTP/1.1 200 OK\r\nApi-Version: 1.43\r\nContent-Length: 6\r\nConnection: close\r\n\r\ndocker";
const PODMAN_PING: &[u8] =
b"HTTP/1.1 200 OK\r\nLibpod-Api-Version: 5.0\r\nContent-Length: 6\r\nConnection: close\r\n\r\npodman";
const FAILED_PING: &[u8] =
b"HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";

fn serve_engine_pings(socket: &Path, responses: &'static [&'static [u8]]) -> Arc<AtomicUsize> {
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

let listener = tokio::net::UnixListener::bind(socket).unwrap();
let requests = Arc::new(AtomicUsize::new(0));
let served = Arc::clone(&requests);
tokio::spawn(async move {
while let Ok((mut stream, _)) = listener.accept().await {
let mut buffer = [0_u8; 1024];
if stream.read(&mut buffer).await.unwrap() > 0 {
let index = served.fetch_add(1, Ordering::Relaxed);
let response = responses[index.min(responses.len() - 1)];
stream.write_all(response).await.unwrap();
}
}
});
requests
}

fn with_engine_sockets(docker: &Path, podman: &Path, scenario: impl Future<Output = ()>) {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
temp_env::with_vars(
[
("DOCKER_HOST", Some(format!("unix://{}", docker.display()))),
(
"OPENSHELL_PODMAN_SOCKET",
Some(podman.display().to_string()),
),
],
|| runtime.block_on(scenario),
);
}

#[test]
fn container_engine_discovers_docker_before_podman() {
// Keep the socket paths under /tmp because macOS's TMPDIR can be too long for a Unix socket.
let dir = tempfile::tempdir_in("/tmp").unwrap();
let docker = dir.path().join("docker.sock");
let podman = dir.path().join("podman.sock");
with_engine_sockets(&docker, &podman, async {
// Fail the default connection once so the VM must run real socket discovery.
let docker_pings = serve_engine_pings(&docker, &[FAILED_PING, DOCKER_PING]);
let podman_pings = serve_engine_pings(&podman, &[PODMAN_PING]);
let engine = connect_local_container_engine().await.unwrap();
assert_eq!(engine.ping().await.unwrap(), "docker");
assert!(docker_pings.load(Ordering::Relaxed) >= 3);
assert_eq!(podman_pings.load(Ordering::Relaxed), 0);
});
}

#[test]
fn container_engine_handles_socket_discovery_failures() {
let dir = tempfile::tempdir_in("/tmp").unwrap();
let podman = dir.path().join("podman.sock");
with_engine_sockets(&dir.path().join("absent.sock"), &podman, async {
let stale = dir.path().join("stale.sock");
drop(std::os::unix::net::UnixListener::bind(&stale).unwrap());
let docker = dir.path().join("desktop.sock");
serve_engine_pings(&docker, &[DOCKER_PING]);
serve_engine_pings(&podman, &[PODMAN_PING]);

for (docker, expected) in [
(Some(docker), "docker"),
(None, "podman"),
(Some(stale.clone()), "podman"),
] {
let podman = podman.clone();
let engine = connect_container_engine(move || docker, move || Some(podman))
.await
.unwrap();
assert_eq!(engine.ping().await.unwrap(), expected);
}
assert!(
connect_container_engine(move || Some(stale), || None)
.await
.is_none()
);

let log = dir.path().join("discovery.log");
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::WARN)
.with_ansi(false)
.with_writer(fs::File::create(&log).unwrap())
.finish();
let _tracing = tracing::subscriber::set_default(subscriber);
let podman = podman.clone();
let engine =
connect_container_engine(|| panic!("test probe panic"), move || Some(podman))
.await
.unwrap();
assert_eq!(engine.ping().await.unwrap(), "podman");
let warnings = fs::read_to_string(log).unwrap();
assert!(
warnings
.lines()
.any(|line| line.contains("engine=\"Docker\"")
&& line.contains("test probe panic")),
"{warnings}"
);
});
}

#[test]
fn vm_console_diagnostic_is_bounded_to_the_tail() {
let directory = tempfile::tempdir().unwrap();
Expand Down
Loading