Skip to content

Commit 2d46f5b

Browse files
committed
fix(docker): make attach host runtime portable
Signed-off-by: Drew Newberry <anewberry@nvidia.com>
1 parent 216eed4 commit 2d46f5b

4 files changed

Lines changed: 149 additions & 35 deletions

File tree

‎crates/openshell-driver-docker/src/isolation.rs‎

Lines changed: 94 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use std::os::unix::fs::PermissionsExt as _;
2222
use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
2323
use std::path::{Path, PathBuf};
2424
use std::sync::Arc;
25+
use std::sync::atomic::{AtomicBool, Ordering};
2526
use std::time::Duration;
2627

2728
use async_trait::async_trait;
@@ -591,34 +592,27 @@ impl ReadyBoundary for DockerReady {
591592
listener_guard,
592593
mediation,
593594
} = *self;
594-
let expected_metadata = topology.listener_metadata.clone();
595-
let expected_container = topology.container_id.clone();
596-
let accept_task = tokio::task::spawn_blocking(move || {
597-
let (stream, _) = listener.accept().map_err(|error| {
598-
BackendError::Process(format!("accept Docker seccomp listener: {error}"))
599-
})?;
600-
receive_listener_fd(stream, &expected_metadata, &expected_container)
601-
});
595+
let (listener_runtime, first_listener) = DockerListenerRuntime::start(
596+
listener,
597+
topology.listener_metadata.clone(),
598+
topology.container_id.clone(),
599+
mediation.clone(),
600+
)?;
602601

603602
if let Err(error) = docker.start_container(&topology.container_id, None).await {
604-
accept_task.abort();
605603
return Err(docker_error("start Docker boundary", error));
606604
}
607605

608-
let listener_fd = tokio::time::timeout(LISTENER_ACCEPT_TIMEOUT, accept_task)
606+
tokio::time::timeout(LISTENER_ACCEPT_TIMEOUT, first_listener)
609607
.await
610608
.map_err(|_| {
611609
BackendError::Process(
612610
"timed out waiting for Docker seccomp listener FD".to_string(),
613611
)
614612
})?
615613
.map_err(|error| {
616-
BackendError::Process(format!("Docker seccomp listener task failed: {error}"))
614+
BackendError::Process(format!("Docker seccomp listener stopped: {error}"))
617615
})??;
618-
let mediation_for_worker = mediation.clone();
619-
tokio::task::spawn_blocking(move || {
620-
run_notification_worker(listener_fd, mediation_for_worker);
621-
});
622616

623617
let process = Arc::new(DockerProcess {
624618
docker: docker.clone(),
@@ -633,15 +627,90 @@ impl ReadyBoundary for DockerReady {
633627
}),
634628
port_forward: Arc::new(UnsupportedDockerPortForward),
635629
_listener_guard: listener_guard,
630+
_listener_runtime: listener_runtime,
636631
}))
637632
}
638633
}
639634

635+
struct DockerListenerRuntime {
636+
shutdown: Arc<AtomicBool>,
637+
task: tokio::task::JoinHandle<()>,
638+
}
639+
640+
impl DockerListenerRuntime {
641+
fn start(
642+
listener: UnixListener,
643+
expected_metadata: String,
644+
expected_container: String,
645+
mediation: Arc<DockerMediation>,
646+
) -> Result<(Self, oneshot::Receiver<Result<(), BackendError>>), BackendError> {
647+
listener.set_nonblocking(true).map_err(|error| {
648+
BackendError::Process(format!("prepare Docker seccomp listener: {error}"))
649+
})?;
650+
let shutdown = Arc::new(AtomicBool::new(false));
651+
let worker_shutdown = shutdown.clone();
652+
let runtime = tokio::runtime::Handle::current();
653+
let (first_tx, first_rx) = oneshot::channel();
654+
let task = tokio::task::spawn_blocking(move || {
655+
let mut first_tx = Some(first_tx);
656+
while !worker_shutdown.load(Ordering::Acquire) {
657+
let stream = match listener.accept() {
658+
Ok((stream, _)) => stream,
659+
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
660+
std::thread::sleep(Duration::from_millis(10));
661+
continue;
662+
}
663+
Err(error) => {
664+
if let Some(first_tx) = first_tx.take() {
665+
let _ = first_tx.send(Err(BackendError::Process(format!(
666+
"accept Docker seccomp listener: {error}"
667+
))));
668+
}
669+
break;
670+
}
671+
};
672+
if let Err(error) = stream.set_nonblocking(false) {
673+
if let Some(first_tx) = first_tx.take() {
674+
let _ = first_tx.send(Err(BackendError::Process(format!(
675+
"prepare accepted Docker seccomp listener: {error}"
676+
))));
677+
}
678+
break;
679+
}
680+
let listener_fd =
681+
match receive_listener_fd(stream, &expected_metadata, &expected_container) {
682+
Ok(listener_fd) => listener_fd,
683+
Err(error) => {
684+
if let Some(first_tx) = first_tx.take() {
685+
let _ = first_tx.send(Err(error));
686+
}
687+
break;
688+
}
689+
};
690+
let mediation = mediation.clone();
691+
runtime.spawn_blocking(move || run_notification_worker(listener_fd, mediation));
692+
if let Some(first_tx) = first_tx.take() {
693+
let _ = first_tx.send(Ok(()));
694+
}
695+
}
696+
});
697+
Ok((Self { shutdown, task }, first_rx))
698+
}
699+
}
700+
701+
impl Drop for DockerListenerRuntime {
702+
fn drop(&mut self) {
703+
self.shutdown.store(true, Ordering::Release);
704+
self.task.abort();
705+
}
706+
}
707+
640708
struct DockerRunning {
641709
process: Arc<DockerProcess>,
642710
exec: Arc<DockerExec>,
643711
port_forward: Arc<UnsupportedDockerPortForward>,
644712
_listener_guard: Arc<ListenerPathGuard>,
713+
_listener_runtime: DockerListenerRuntime,
645714
}
646715

647716
impl RunningBoundary for DockerRunning {
@@ -974,7 +1043,7 @@ struct UnsupportedDockerPortForward;
9741043
impl BoundaryPortForward for UnsupportedDockerPortForward {
9751044
async fn connect(&self, _target: LoopbackTarget) -> Result<BoundaryDuplexStream, BackendError> {
9761045
Err(BackendError::Unsupported(
977-
"Docker create proof does not implement port forwarding".to_string(),
1046+
"Docker attach proof does not implement port forwarding".to_string(),
9781047
))
9791048
}
9801049
}
@@ -1103,25 +1172,25 @@ const IOC_READ: u32 = 2;
11031172

11041173
// Linux reserves IOC_SIZEBITS for the payload size. Both fixed seccomp
11051174
// notification structs are far smaller than u32::MAX on supported targets.
1106-
#[allow(clippy::cast_possible_truncation)]
1107-
const fn ioctl_read_write<T>(kind: u8, number: u8) -> libc::c_ulong {
1175+
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
1176+
const fn ioctl_read_write<T>(kind: u8, number: u8) -> libc::Ioctl {
11081177
((IOC_READ | IOC_WRITE) << IOC_DIRSHIFT
11091178
| (kind as u32) << IOC_TYPESHIFT
11101179
| (number as u32) << IOC_NRSHIFT
1111-
| (size_of::<T>() as u32) << IOC_SIZESHIFT) as libc::c_ulong
1180+
| (size_of::<T>() as u32) << IOC_SIZESHIFT) as libc::Ioctl
11121181
}
11131182

1114-
#[allow(clippy::cast_possible_truncation)]
1115-
const fn ioctl_write<T>(kind: u8, number: u8) -> libc::c_ulong {
1183+
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
1184+
const fn ioctl_write<T>(kind: u8, number: u8) -> libc::Ioctl {
11161185
(IOC_WRITE << IOC_DIRSHIFT
11171186
| (kind as u32) << IOC_TYPESHIFT
11181187
| (number as u32) << IOC_NRSHIFT
1119-
| (size_of::<T>() as u32) << IOC_SIZESHIFT) as libc::c_ulong
1188+
| (size_of::<T>() as u32) << IOC_SIZESHIFT) as libc::Ioctl
11201189
}
11211190

1122-
const SECCOMP_IOCTL_NOTIF_RECV: libc::c_ulong = ioctl_read_write::<SeccompNotif>(b'!', 0);
1123-
const SECCOMP_IOCTL_NOTIF_SEND: libc::c_ulong = ioctl_read_write::<SeccompNotifResp>(b'!', 1);
1124-
const SECCOMP_IOCTL_NOTIF_ADDFD: libc::c_ulong = ioctl_write::<SeccompNotifAddfd>(b'!', 3);
1191+
const SECCOMP_IOCTL_NOTIF_RECV: libc::Ioctl = ioctl_read_write::<SeccompNotif>(b'!', 0);
1192+
const SECCOMP_IOCTL_NOTIF_SEND: libc::Ioctl = ioctl_read_write::<SeccompNotifResp>(b'!', 1);
1193+
const SECCOMP_IOCTL_NOTIF_ADDFD: libc::Ioctl = ioctl_write::<SeccompNotifAddfd>(b'!', 3);
11251194
const SECCOMP_USER_NOTIF_FLAG_CONTINUE: u32 = 1;
11261195
const SECCOMP_ADDFD_FLAG_SEND: u32 = 2;
11271196

‎crates/openshell-driver-docker/src/lib.rs‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,9 @@ use tracing::{Instrument as _, debug, info, warn};
7373
use tracing_opentelemetry::OpenTelemetrySpanExt as _;
7474
use url::Url;
7575

76+
#[cfg(target_os = "linux")]
77+
use sha2::{Digest as _, Sha256};
78+
7679
const WATCH_BUFFER: usize = 128;
7780
const WATCH_POLL_INTERVAL: Duration = Duration::from_secs(2);
7881
const WATCH_POLL_MAX_BACKOFF: Duration = Duration::from_secs(30);
@@ -572,6 +575,11 @@ impl DockerComputeDriver {
572575
if let Some(spec) = sandbox.spec.as_ref() {
573576
workload_env.extend(spec.environment.clone());
574577
}
578+
let host_user = current_process_user().map_err(|error| {
579+
Status::failed_precondition(format!(
580+
"Docker host-supervisor mode requires a host user identity: {error}"
581+
))
582+
})?;
575583
let descriptor = isolation::DockerBoundarySpec {
576584
image: image.id.clone(),
577585
launch_generation: uuid::Uuid::new_v4().to_string(),
@@ -582,20 +590,16 @@ impl DockerComputeDriver {
582590
.into_iter()
583591
.map(|(name, value)| format!("{name}={value}"))
584592
.collect(),
585-
user: Some(current_process_user().map_err(|error| {
586-
Status::failed_precondition(format!(
587-
"Docker host-supervisor mode requires a host user identity: {error}"
588-
))
589-
})?),
593+
user: Some(host_user.clone()),
590594
}
591595
.into_topology_descriptor()
592596
.map_err(|error| Status::internal(error.to_string()))?;
593597

594598
let supervisor_binary = &self.config.supervisor_bin;
595-
let ssh_socket = state_dir.join("ssh.sock");
596599
let proxy_tls_dir = state_dir.join("proxy-tls");
597-
let listener_dir = state_dir.join("seccomp");
598-
for directory in [&proxy_tls_dir, &listener_dir] {
600+
let runtime_dir = docker_runtime_dir(&sandbox.id);
601+
let ssh_socket = runtime_dir.join("ssh.sock");
602+
for directory in [&proxy_tls_dir, &runtime_dir] {
599603
openshell_core::paths::create_dir_restricted(directory).map_err(|error| {
600604
Status::internal(format!(
601605
"create Docker host-supervisor directory '{}': {error}",
@@ -636,7 +640,7 @@ impl DockerComputeDriver {
636640
.env(openshell_core::sandbox_env::SANDBOX_TOKEN_FILE, &token_path)
637641
.env(openshell_core::sandbox_env::SSH_SOCKET_PATH, &ssh_socket)
638642
.env(openshell_core::sandbox_env::PROXY_TLS_DIR, &proxy_tls_dir)
639-
.env(openshell_core::sandbox_env::OCI_IMAGE_USER, &image.user)
643+
.env(openshell_core::sandbox_env::OCI_IMAGE_USER, &host_user)
640644
.env(
641645
openshell_core::sandbox_env::LOG_LEVEL,
642646
openshell_core::driver_utils::sandbox_log_level(sandbox, &self.config.log_level),
@@ -646,7 +650,7 @@ impl DockerComputeDriver {
646650
openshell_core::telemetry::enabled_env_value(),
647651
)
648652
.env(isolation::DOCKER_SOCKET_ENV, &self.config.socket_path)
649-
.env(isolation::DOCKER_LISTENER_DIR_ENV, &listener_dir);
653+
.env(isolation::DOCKER_LISTENER_DIR_ENV, &runtime_dir);
650654
if let Some(tls) = &self.config.guest_tls {
651655
command
652656
.env(openshell_core::sandbox_env::TLS_CA, &tls.ca)
@@ -2385,6 +2389,13 @@ fn sandbox_token_host_path_by_id(
23852389
})
23862390
}
23872391

2392+
#[cfg(target_os = "linux")]
2393+
fn docker_runtime_dir(sandbox_id: &str) -> PathBuf {
2394+
let digest = Sha256::digest(sandbox_id.as_bytes());
2395+
let suffix = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&digest[..8]);
2396+
std::env::temp_dir().join(format!("openshell-docker-{suffix}"))
2397+
}
2398+
23882399
async fn write_sandbox_token_file(
23892400
sandbox: &DriverSandbox,
23902401
config: &DockerDriverRuntimeConfig,
@@ -2454,6 +2465,12 @@ fn cleanup_sandbox_token_file_by_id(sandbox_id: &str, config: &DockerDriverRunti
24542465
if let Some(dir) = path.parent() {
24552466
let _ = std::fs::remove_dir(dir);
24562467
}
2468+
#[cfg(target_os = "linux")]
2469+
{
2470+
let runtime_dir = docker_runtime_dir(sandbox_id);
2471+
let _ = std::fs::remove_file(runtime_dir.join("ssh.sock"));
2472+
let _ = std::fs::remove_dir(runtime_dir);
2473+
}
24572474
}
24582475

24592476
fn docker_cdi_gpu_inventory(info: &SystemInfo) -> CdiGpuInventory {

‎crates/openshell-driver-docker/src/tests.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,25 @@ fn runtime_config() -> DockerDriverRuntimeConfig {
107107
}
108108
}
109109

110+
#[cfg(target_os = "linux")]
111+
#[test]
112+
fn docker_runtime_directory_is_short_and_stable() {
113+
let runtime_dir = docker_runtime_dir("sandbox-id");
114+
115+
assert_eq!(runtime_dir, docker_runtime_dir("sandbox-id"));
116+
assert_ne!(runtime_dir, docker_runtime_dir("another-sandbox-id"));
117+
for socket_name in ["0123456789abcdef.sock", "ssh.sock"] {
118+
assert!(
119+
runtime_dir
120+
.join(socket_name)
121+
.as_os_str()
122+
.as_encoded_bytes()
123+
.len()
124+
< 104
125+
);
126+
}
127+
}
128+
110129
fn test_driver_with_config(config: DockerDriverRuntimeConfig) -> DockerComputeDriver {
111130
let allow_all_default_gpu = config.allow_all_default_gpu;
112131
DockerComputeDriver {

‎e2e/with-docker-gateway.sh‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,15 @@ cleanup() {
176176
cat "${DRIVER_LOG}" || true
177177
echo "=== end external Docker compute driver log ==="
178178
fi
179+
if [ "${exit_code}" -ne 0 ] && [ -d "${XDG_STATE_HOME}/openshell/docker-sandbox-tokens" ]; then
180+
echo "=== Docker host-supervisor logs ==="
181+
while IFS= read -r supervisor_log; do
182+
echo "--- ${supervisor_log} ---"
183+
tail -n 200 "${supervisor_log}" || true
184+
done < <(find "${XDG_STATE_HOME}/openshell/docker-sandbox-tokens" \
185+
-type f -name 'supervisor*.log' -print)
186+
echo "=== end Docker host-supervisor logs ==="
187+
fi
179188

180189
rm -rf "${WORKDIR}" 2>/dev/null || true
181190
}

0 commit comments

Comments
 (0)