@@ -302,6 +302,7 @@ fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> Result<()> {
302302pub 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) ]
503522const 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) ]
510535fn 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
641679pub 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 ( ) ;
0 commit comments