88import java .io .File ;
99import java .io .IOException ;
1010import java .io .InputStream ;
11+ import java .io .OutputStream ;
1112import java .util .ArrayList ;
1213import java .util .Arrays ;
1314import java .util .Collections ;
@@ -118,7 +119,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
118119 long budget = nanos (request .timeoutMillis , "timeoutMillis" );
119120 BoundedCapture out = new BoundedCapture (request .stdoutLimitBytes );
120121 BoundedCapture err = new BoundedCapture (request .stderrLimitBytes );
121- Process process = null ;
122+ CleanupProcess process = null ;
122123 Reader stdoutReader = null ;
123124 Reader stderrReader = null ;
124125 ExecuteWatchdog watchdog = null ;
@@ -130,6 +131,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
130131 long queueWaitMillis = 0L ;
131132 Integer exit = null ;
132133 boolean streamsDrained = true ;
134+ boolean cleanupFinished = true ;
133135 try {
134136 while (!acquired && reason == null ) {
135137 if (Thread .interrupted ()) {
@@ -168,7 +170,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
168170 builder .environment ().clear ();
169171 builder .environment ().putAll (request .environment );
170172 }
171- process = processStarter .start (builder );
173+ process = new CleanupProcess ( processStarter .start (builder ) );
172174 process .getOutputStream ().close ();
173175 stdoutReader = new Reader (process .getInputStream (), out , "opencli-stdout" );
174176 stderrReader = new Reader (process .getErrorStream (), err , "opencli-stderr" );
@@ -226,23 +228,17 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
226228 long cleanupStart = System .nanoTime ();
227229 long cleanupBudget = nanos (request .cleanupGraceMillis , "cleanupGraceMillis" );
228230 if (Objects .nonNull (process )) {
229- boolean forceSent = false ;
230231 if (process .isAlive ()) {
231- try {
232- process .destroy ();
233- } catch (RuntimeException ex ) {
234- cleanupOperationFailed = true ;
235- forceSent = true ;
236- if (!tryForceStop (process )) { cleanupOperationFailed = true ; }
237- }
232+ process .destroy ();
238233 }
234+ long forceAfter = Math .min (TimeUnit .MILLISECONDS .toNanos (100L ), cleanupBudget / 2L );
239235 while (remaining (cleanupStart , cleanupBudget ) > 0
240- && (process .isAlive () || alive (stdoutReader ) || alive (stderrReader ))) {
236+ && (process .isAlive () || alive (stdoutReader ) || alive (stderrReader )
237+ || process .hasPendingStop ())) {
241238 if (Thread .interrupted ()) { interrupted = true ; }
242- if (process .isAlive () && !forceSent
243- && System .nanoTime () - cleanupStart >= Math .min (TimeUnit .MILLISECONDS .toNanos (100L ), cleanupBudget / 2 )) {
244- if (!tryForceStop (process )) { cleanupOperationFailed = true ; }
245- forceSent = true ;
239+ if (process .isAlive () && (process .graceful .failed
240+ || System .nanoTime () - cleanupStart >= forceAfter )) {
241+ process .destroyForcibly ();
246242 }
247243 try {
248244 TimeUnit .NANOSECONDS .sleep (Math .min (POLL_NANOS ,
@@ -251,13 +247,17 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
251247 interrupted = true ;
252248 }
253249 }
254- if (process .isAlive () && !tryForceStop (process )) { cleanupOperationFailed = true ; }
250+ if (process .isAlive ()) {
251+ process .destroyForcibly ();
252+ }
253+ cleanupFinished = !process .hasPendingStop ();
254+ cleanupOperationFailed |= !cleanupFinished || process .graceful .failed || process .forced .failed ;
255255 if (!process .isAlive ()) {
256256 exit = process .exitValue ();
257257 }
258258 streamsDrained = !alive (stdoutReader ) && !alive (stderrReader );
259- if (Objects .isNull (exit ) || !streamsDrained ) {
260- // A fixed runtime cannot accumulate unlimited uncertain children/ readers.
259+ if (Objects .isNull (exit ) || !streamsDrained || ! cleanupFinished ) {
260+ // Quarantine limits the number of unconfirmed children, readers and stop workers .
261261 quarantined = true ;
262262 if (reason == TerminationReason .PROCESS_EXIT ) { reason = TerminationReason .CLEANUP_UNCONFIRMED ; }
263263 }
@@ -283,7 +283,8 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
283283 OpenCliExecutionDetails details = OpenCliExecutionDetails .builder ()
284284 .terminationReason (reason )
285285 .cleanupState (process == null ? CleanupState .NOT_STARTED
286- : Objects .isNull (exit ) || !streamsDrained ? CleanupState .UNCONFIRMED : CleanupState .ROOT_EXIT_CONFIRMED )
286+ : Objects .isNull (exit ) || !streamsDrained || !cleanupFinished
287+ ? CleanupState .UNCONFIRMED : CleanupState .ROOT_EXIT_CONFIRMED )
287288 .processStarted (process != null ).streamsDrained (streamsDrained )
288289 .cleanupOperationFailed (cleanupOperationFailed )
289290 .stdoutCapturedBytes (out .size ()).stdoutObservedBytes (out .observed ()).stdoutTruncated (out .isTruncated ())
@@ -303,14 +304,81 @@ private static ExecuteWatchdog newWatchdog(long timeoutMillis) {
303304 }
304305
305306 private static boolean alive (Thread thread ) { return thread != null && thread .isAlive (); }
306- private static boolean tryForceStop (Process process ) {
307- try {
308- process .destroyForcibly ();
309- return true ;
310- } catch (RuntimeException ex ) {
311- return false ;
307+ /**
308+ * The watchdog holds its monitor when invoking destroy. Keep native stop calls
309+ * outside that monitor and the caller, as closing process pipes can block.
310+ */
311+ private static final class CleanupProcess extends Process {
312+ private final Process delegate ;
313+ private final StopRequest graceful = new StopRequest ();
314+ private final StopRequest forced = new StopRequest ();
315+
316+ CleanupProcess (Process delegate ) {
317+ this .delegate = delegate ;
318+ }
319+
320+ @ Override
321+ public OutputStream getOutputStream () { return delegate .getOutputStream (); }
322+
323+ @ Override
324+ public InputStream getInputStream () { return delegate .getInputStream (); }
325+
326+ @ Override
327+ public InputStream getErrorStream () { return delegate .getErrorStream (); }
328+
329+ @ Override
330+ public int waitFor () throws InterruptedException { return delegate .waitFor (); }
331+
332+ @ Override
333+ public int exitValue () { return delegate .exitValue (); }
334+
335+ @ Override
336+ public boolean isAlive () { return delegate .isAlive (); }
337+
338+ @ Override
339+ public void destroy () {
340+ graceful .start ("opencli-stop" , delegate ::destroy );
341+ }
342+
343+ @ Override
344+ public Process destroyForcibly () {
345+ forced .start ("opencli-force-stop" , delegate ::destroyForcibly );
346+ return this ;
347+ }
348+
349+ boolean hasPendingStop () {
350+ return graceful .isPending () || forced .isPending ();
312351 }
313352 }
353+
354+ private static final class StopRequest {
355+ private Thread worker ;
356+ private volatile boolean failed ;
357+
358+ synchronized void start (String name , Runnable signal ) {
359+ if (Objects .nonNull (worker ) || failed ) {
360+ return ;
361+ }
362+ try {
363+ worker = new Thread (() -> {
364+ try {
365+ signal .run ();
366+ } catch (RuntimeException ex ) {
367+ failed = true ;
368+ }
369+ }, name );
370+ worker .setDaemon (true );
371+ worker .start ();
372+ } catch (RuntimeException ex ) {
373+ failed = true ;
374+ }
375+ }
376+
377+ synchronized boolean isPending () {
378+ return alive (worker );
379+ }
380+ }
381+
314382 private static long remaining (long start , long budget ) { return budget - (System .nanoTime () - start ); }
315383 // The Windows JDK legacy serializer treats a surrounding quote pair as already encoded.
316384 @ SuppressWarnings ("removal" )
0 commit comments