Skip to content

Commit 49b7d37

Browse files
committed
fix(drivers): address review findings on launched drivers
Do not exit the gateway when a driver ends during gateway shutdown. Hash the staged trust artifact through openshell-crypto so openshell-driver-sdk no longer depends on sha2 directly. End the Podman driver when its gateway disappears. Wait up to 30 seconds for a driver socket. Read driver output while it runs so large output is reported as oversized, and remove a partially written startup document. Run the VM preflight tests against a stand-in driver, and check that every flag the startup document covers is a real argument. Signed-off-by: Evan Lezar <elezar@nvidia.com>
1 parent cd922b8 commit 49b7d37

12 files changed

Lines changed: 223 additions & 24 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/openshell-driver-podman/src/main.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,12 @@ async fn main() -> Result<()> {
285285
run_probe();
286286
}
287287
let (args, document) = parse_args().map_err(|err| miette::miette!("{err}"))?;
288+
// A gateway that is killed must not leave this driver running.
289+
if document.is_some()
290+
&& let Err(error) = openshell_driver_sdk::parent::die_with_parent()
291+
{
292+
eprintln!("warning: {error}; a gateway crash may orphan this driver");
293+
}
288294
let _tracing = openshell_otel::install_driver_tracing(
289295
openshell_driver_podman::otel_tracing::TRACING,
290296
openshell_otel::DriverTracingConfig {

‎crates/openshell-driver-sdk/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ repository.workspace = true
1313
[dependencies]
1414
clap = { workspace = true, optional = true }
1515
base64 = { workspace = true }
16-
sha2 = { workspace = true }
16+
openshell-crypto = { workspace = true }
1717
openshell-core = { path = "../openshell-core", default-features = false }
1818
serde = { workspace = true }
1919
serde_json = { workspace = true }

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#[cfg(feature = "clap")]
2525
pub mod cli;
2626
pub mod network_trust;
27+
pub mod parent;
2728
pub mod preflight;
2829
pub mod probe;
2930

‎crates/openshell-driver-sdk/src/network_trust.rs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@
77
//! certificate count. The driver reads the bounded artifact once, checks it
88
//! against those values, and keeps its own immutable copy.
99
10+
use std::fmt::Write as _;
1011
use std::fs;
1112
use std::io::Read;
1213
use std::path::Path;
1314

1415
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
1516
use openshell_core::NetworkSupervisorTrustBundle;
1617
use openshell_core::network_trust::MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES;
17-
use sha2::{Digest, Sha256};
1818
#[cfg(unix)]
1919
use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt};
2020

@@ -47,7 +47,14 @@ pub fn load_staged_bundle(
4747
// staged-artifact drift; trust comes from the gateway's
4848
// normalization and TLS verification. Classified as a non-security
4949
// identity hash in openshell-crypto/README.md.
50-
let actual_digest = format!("sha256:{:x}", Sha256::digest(&pem));
50+
let digest = openshell_crypto::sha256(&pem)
51+
.map_err(|error| format!("failed to hash additional CA artifact: {error}"))?;
52+
let actual_digest = digest
53+
.iter()
54+
.fold(String::from("sha256:"), |mut text, byte| {
55+
let _ = write!(text, "{byte:02x}");
56+
text
57+
});
5158
if actual_digest != expected_digest {
5259
return Err(format!(
5360
"additional CA artifact '{}' does not match expected digest {}",
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
//! Ending a launched driver when its gateway disappears.
5+
//!
6+
//! The gateway launches a driver and removes its socket on the next launch. A
7+
//! gateway that is killed outside its init system would otherwise leave the
8+
//! driver running, and the next launch would start a second one.
9+
10+
#[cfg(unix)]
11+
use std::time::Duration;
12+
13+
/// Exit this process when its parent process ends.
14+
///
15+
/// The check polls the parent process id once a second, so the driver ends
16+
/// within about a second of the gateway. It works on every unix and needs no
17+
/// platform-specific kernel interface.
18+
///
19+
/// # Errors
20+
///
21+
/// Returns a message when the parent is already gone or the watcher cannot
22+
/// start.
23+
#[cfg(unix)]
24+
pub fn die_with_parent() -> Result<(), String> {
25+
die_with_parent_polling(Duration::from_secs(1), || std::process::exit(1))
26+
}
27+
28+
#[cfg(unix)]
29+
fn die_with_parent_polling(
30+
interval: Duration,
31+
on_orphaned: impl FnOnce() + Send + 'static,
32+
) -> Result<(), String> {
33+
let parent = std::os::unix::process::parent_id();
34+
if parent == 1 {
35+
return Err("the parent process has already ended".to_string());
36+
}
37+
std::thread::Builder::new()
38+
.name("parent-guard".to_string())
39+
.spawn(move || {
40+
loop {
41+
std::thread::sleep(interval);
42+
if std::os::unix::process::parent_id() != parent {
43+
on_orphaned();
44+
return;
45+
}
46+
}
47+
})
48+
.map(|_| ())
49+
.map_err(|error| format!("failed to start the parent guard: {error}"))
50+
}
51+
52+
#[cfg(all(test, unix))]
53+
mod tests {
54+
use super::*;
55+
56+
#[test]
57+
fn a_running_parent_is_not_reported() {
58+
let (sender, receiver) = std::sync::mpsc::channel();
59+
die_with_parent_polling(Duration::from_millis(10), move || {
60+
let _ = sender.send(());
61+
})
62+
.unwrap();
63+
assert!(receiver.recv_timeout(Duration::from_millis(200)).is_err());
64+
}
65+
}

‎crates/openshell-driver-vm/src/main.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,6 +1071,19 @@ mod tests {
10711071
assert!(args.provider_spiffe_allow_guest_tcp);
10721072
}
10731073

1074+
/// A flag renamed in `Args` must also be renamed in the list, or the
1075+
/// conflict check silently stops guarding it.
1076+
#[test]
1077+
fn every_flag_covered_by_config_is_a_real_argument() {
1078+
let command = <Args as clap::CommandFactory>::command();
1079+
for name in crate::FLAGS_COVERED_BY_CONFIG {
1080+
assert!(
1081+
command.get_arguments().any(|arg| arg.get_id() == *name),
1082+
"{name} is not an argument"
1083+
);
1084+
}
1085+
}
1086+
10741087
#[test]
10751088
fn config_cannot_be_combined_with_a_flag_it_covers() {
10761089
let dir = tempfile::tempdir().unwrap();

‎crates/openshell-gateway/src/launcher.rs‎

Lines changed: 99 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> Result<()> {
302302
pub async fn launch(
303303
driver: &DriverProcess<'_>,
304304
otlp_config: Option<&OtlpConfig>,
305+
shutdown: tokio::sync::watch::Receiver<bool>,
305306
build_document: impl FnOnce(&Path) -> Result<openshell_driver_sdk::StartupDocument>,
306307
) -> Result<AcquiredRemoteDriverEndpoint> {
307308
let name = driver.name;
@@ -339,6 +340,8 @@ pub async fn launch(
339340
Arc::downgrade(&process),
340341
name.to_string(),
341342
EXIT_POLL_INTERVAL,
343+
shutdown,
344+
SHUTDOWN_GRACE,
342345
|message| {
343346
tracing::error!("{message}");
344347
std::process::exit(1);
@@ -375,6 +378,17 @@ fn run_bounded(
375378
.stderr(Stdio::null())
376379
.spawn()
377380
.map_err(|error| format!("failed to run '{}': {error}", binary.display()))?;
381+
// Read while the process runs, so output beyond the pipe buffer cannot
382+
// block it. Reading stops one byte past the limit, which closes the pipe.
383+
let reader = child.stdout.take().map(|stdout| {
384+
std::thread::spawn(move || {
385+
let mut output = Vec::new();
386+
stdout
387+
.take(max_output as u64 + 1)
388+
.read_to_end(&mut output)
389+
.map(|_| output)
390+
})
391+
});
378392
let deadline = std::time::Instant::now() + timeout;
379393
let status = loop {
380394
match child.try_wait() {
@@ -390,16 +404,21 @@ fn run_bounded(
390404
Err(error) => return Err(format!("failed to wait for the process: {error}")),
391405
}
392406
};
407+
let output = match reader {
408+
Some(reader) => reader
409+
.join()
410+
.map_err(|_| "output reader panicked".to_string())?
411+
.map_err(|error| format!("failed to read output: {error}"))?,
412+
None => Vec::new(),
413+
};
414+
// Output past the limit closes the pipe on the process, which then ends
415+
// with SIGPIPE. Hand it back so the caller reports the size, not the signal.
416+
if output.len() > max_output {
417+
return Ok(output);
418+
}
393419
if !status.success() {
394420
return Err(format!("exited with {status}"));
395421
}
396-
let mut output = Vec::new();
397-
if let Some(stdout) = child.stdout.take() {
398-
stdout
399-
.take(max_output as u64 + 1)
400-
.read_to_end(&mut output)
401-
.map_err(|error| format!("failed to read output: {error}"))?;
402-
}
403422
Ok(output)
404423
}
405424

@@ -502,27 +521,45 @@ pub fn preflight(
502521
#[cfg(unix)]
503522
const EXIT_POLL_INTERVAL: Duration = Duration::from_millis(500);
504523

524+
/// How long the watcher waits for the gateway's own shutdown to begin after a
525+
/// driver exits. A stop signal reaches the driver and the gateway together, so
526+
/// the driver can end a moment before the gateway notices it must shut down.
527+
#[cfg(unix)]
528+
const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
529+
505530
/// Call `on_exit` with a message naming the driver if the process ends while
506-
/// the gateway still holds it. A driver the gateway shut down is not reported.
507-
/// The gateway cannot serve sandboxes without its driver, so the caller exits
508-
/// and leaves a restart to the init system.
531+
/// the gateway still holds it and is not shutting down. The gateway cannot
532+
/// serve sandboxes without its driver, so the caller exits and leaves a
533+
/// restart to the init system.
509534
#[cfg(unix)]
510535
fn watch_for_exit(
511536
process: std::sync::Weak<ManagedDriverProcess>,
512537
name: String,
513538
interval: Duration,
539+
mut shutdown: tokio::sync::watch::Receiver<bool>,
540+
grace: Duration,
514541
on_exit: impl FnOnce(String) + Send + 'static,
515542
) {
516543
tokio::spawn(async move {
517544
loop {
518545
tokio::time::sleep(interval).await;
546+
if *shutdown.borrow() {
547+
return;
548+
}
519549
let Some(process) = process.upgrade() else {
520550
return;
521551
};
522552
match process.poll_exit() {
523553
DriverProcessState::Running => {}
524554
DriverProcessState::Released => return,
525555
DriverProcessState::Exited(status) => {
556+
drop(process);
557+
if tokio::time::timeout(grace, shutdown.wait_for(|stopping| *stopping))
558+
.await
559+
.is_ok()
560+
{
561+
return;
562+
}
526563
on_exit(format!(
527564
"{name} compute driver exited unexpectedly with status {status}"
528565
));
@@ -615,6 +652,7 @@ fn write_startup_document(
615652
.open(path)
616653
.and_then(|mut file| file.write_all(text.as_bytes()))
617654
.map_err(|error| {
655+
let _ = std::fs::remove_file(path);
618656
Error::execution(format!(
619657
"failed to write startup document '{}': {error}",
620658
path.display()
@@ -641,13 +679,19 @@ fn apply_trace_headers_env(command: &mut Command, otlp_config: Option<&OtlpConfi
641679
pub async fn launch(
642680
_driver: &DriverProcess<'_>,
643681
_otlp_config: Option<&OtlpConfig>,
682+
_shutdown: tokio::sync::watch::Receiver<bool>,
644683
_build_document: impl FnOnce(&Path) -> Result<openshell_driver_sdk::StartupDocument>,
645684
) -> Result<AcquiredRemoteDriverEndpoint> {
646685
Err(Error::config(
647686
"launched compute drivers require unix domain socket support",
648687
))
649688
}
650689

690+
/// Readiness polls, 100 ms apart. The Podman driver retries its API ping for
691+
/// about ten seconds before it binds its socket, so the wait is longer.
692+
#[cfg(unix)]
693+
const READY_POLLS: u32 = 300;
694+
651695
#[cfg(unix)]
652696
#[tracing::instrument(
653697
name = "driver.wait_for_ready",
@@ -664,7 +708,7 @@ async fn wait_for_compute_driver(
664708
child: &mut tokio::process::Child,
665709
) -> Result<Channel> {
666710
let mut last_error: Option<String> = None;
667-
for _ in 0..100 {
711+
for _ in 0..READY_POLLS {
668712
let try_wait_result = child.try_wait().map_err(|e| {
669713
Error::execution(format!("failed to poll {name} compute driver process: {e}"))
670714
})?;
@@ -1092,10 +1136,13 @@ mod tests {
10921136
.unwrap();
10931137
let process = Arc::new(ManagedDriverProcess::new(child, dir.path().join("d.sock")));
10941138
let (sender, receiver) = tokio::sync::oneshot::channel();
1139+
let (_shutdown_tx, shutdown) = tokio::sync::watch::channel(false);
10951140
watch_for_exit(
10961141
Arc::downgrade(&process),
10971142
"vm".to_string(),
10981143
Duration::from_millis(10),
1144+
shutdown,
1145+
Duration::from_millis(50),
10991146
move |message| {
11001147
let _ = sender.send(message);
11011148
},
@@ -1119,10 +1166,13 @@ mod tests {
11191166
dir.path().join("d.sock"),
11201167
));
11211168
let (sender, mut receiver) = tokio::sync::oneshot::channel::<String>();
1169+
let (_shutdown_tx, shutdown) = tokio::sync::watch::channel(false);
11221170
watch_for_exit(
11231171
Arc::downgrade(&process),
11241172
"vm".to_string(),
11251173
Duration::from_millis(10),
1174+
shutdown,
1175+
Duration::from_millis(50),
11261176
move |message| {
11271177
let _ = sender.send(message);
11281178
},
@@ -1132,6 +1182,44 @@ mod tests {
11321182
drop(process);
11331183
}
11341184

1185+
/// A stop signal reaches the driver and the gateway together. A driver that
1186+
/// ends while the gateway is shutting down is not a failure.
1187+
#[tokio::test]
1188+
async fn a_driver_that_exits_during_gateway_shutdown_is_not_reported() {
1189+
let dir = tempdir().unwrap();
1190+
let child = tokio::process::Command::new("sh")
1191+
.args(["-c", "exit 0"])
1192+
.spawn()
1193+
.unwrap();
1194+
let process = Arc::new(ManagedDriverProcess::new(child, dir.path().join("d.sock")));
1195+
let (sender, mut receiver) = tokio::sync::oneshot::channel::<String>();
1196+
let (shutdown_tx, shutdown) = tokio::sync::watch::channel(false);
1197+
watch_for_exit(
1198+
Arc::downgrade(&process),
1199+
"vm".to_string(),
1200+
Duration::from_millis(10),
1201+
shutdown,
1202+
Duration::from_secs(5),
1203+
move |message| {
1204+
let _ = sender.send(message);
1205+
},
1206+
);
1207+
// The driver has exited by the time the watcher notices. The gateway
1208+
// begins its own shutdown inside the grace period.
1209+
tokio::time::sleep(Duration::from_millis(100)).await;
1210+
shutdown_tx.send_replace(true);
1211+
tokio::time::sleep(Duration::from_millis(200)).await;
1212+
assert!(receiver.try_recv().is_err());
1213+
}
1214+
1215+
#[test]
1216+
fn output_beyond_the_limit_is_not_mistaken_for_a_timeout() {
1217+
let dir = tempdir().unwrap();
1218+
let binary = probe_script(dir.path(), "head -c 300000 /dev/zero | tr '\\0' x");
1219+
let output = super::run_bounded(&binary, &[], Duration::from_secs(5), 4096).unwrap();
1220+
assert_eq!(output.len(), 4097);
1221+
}
1222+
11351223
fn probe_script(dir: &Path, body: &str) -> PathBuf {
11361224
let binary = driver_binary(dir, 0o755, 0o755);
11371225
std::fs::write(&binary, format!("#!/bin/sh\n{body}\n")).unwrap();

‎crates/openshell-gateway/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,7 @@ impl openshell_server::ComputeDriverFactory for PodmanFactory {
510510
tls_ca: context.guest_tls_ca(),
511511
otlp_config: context.otlp_config(),
512512
network_trust: context.network_trust_bundle(),
513+
shutdown: context.shutdown_receiver(),
513514
driver_config,
514515
})
515516
.await?;
@@ -570,6 +571,7 @@ impl openshell_server::ComputeDriverFactory for VmFactory {
570571
tls_ca: context.guest_tls_ca(),
571572
otlp_config: context.otlp_config(),
572573
network_trust: context.network_trust_bundle(),
574+
shutdown: context.shutdown_receiver(),
573575
settings: &settings,
574576
driver_config,
575577
})

0 commit comments

Comments
 (0)