Skip to content

Commit f2b1bc6

Browse files
committed
fix: preserve legacy subprocess API and report late reader failures
1 parent d39c0b3 commit f2b1bc6

5 files changed

Lines changed: 140 additions & 16 deletions

File tree

‎src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java‎

Lines changed: 63 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -186,19 +186,25 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
186186
reason = TerminationReason.IO_FAILURE;
187187
}
188188
while (reason == null) {
189+
IOException readFailure = readerFailure(stdoutReader, stderrReader);
189190
if (out.isTruncated() || err.isTruncated()) {
190191
reason = TerminationReason.OUTPUT_LIMIT;
191192
} else if (Thread.interrupted()) {
192193
interrupted = true;
193194
reason = TerminationReason.CANCELLED;
194195
} else if (request.cancellationToken.isCancelled()) {
195196
reason = TerminationReason.CANCELLED;
196-
} else if (Objects.nonNull(stdoutReader.failure) || Objects.nonNull(stderrReader.failure)) {
197-
ioFailure = Objects.nonNull(stdoutReader.failure)
198-
? stdoutReader.failure : stderrReader.failure;
197+
} else if (Objects.nonNull(readFailure)) {
198+
ioFailure = readFailure;
199199
reason = TerminationReason.IO_FAILURE;
200200
} else if (!process.isAlive() && !stdoutReader.isAlive() && !stderrReader.isAlive()) {
201-
reason = watchdog.killedProcess() ? TerminationReason.EXECUTION_TIMEOUT : TerminationReason.PROCESS_EXIT;
201+
// A reader can publish its failure between the earlier check and thread exit.
202+
ioFailure = readerFailure(stdoutReader, stderrReader);
203+
if (Objects.nonNull(ioFailure)) {
204+
reason = TerminationReason.IO_FAILURE;
205+
} else {
206+
reason = watchdog.killedProcess() ? TerminationReason.EXECUTION_TIMEOUT : TerminationReason.PROCESS_EXIT;
207+
}
202208
} else if (watchdog.killedProcess() || remaining(request.submittedAtNanos, budget) <= 0) {
203209
reason = TerminationReason.EXECUTION_TIMEOUT;
204210
} else {
@@ -464,6 +470,11 @@ public synchronized void write(byte[] bytes, int offset, int length) {
464470
synchronized void freeze() { frozen = true; }
465471
}
466472

473+
private static IOException readerFailure(Reader stdout, Reader stderr) {
474+
IOException failure = stdout.failure;
475+
return Objects.nonNull(failure) ? failure : stderr.failure;
476+
}
477+
467478
private static final class Reader extends Thread {
468479
private final InputStream input;
469480
private final BoundedCapture capture;
@@ -498,6 +509,8 @@ public static final class ExecutionRequest {
498509
private final File workingDirectory;
499510
private final Map<String, String> environment;
500511
private final long timeoutMillis;
512+
/** Requested legacy ceiling, or zero for independently configured stream limits. */
513+
private final long maxOutputBytes;
501514
private final int stdoutLimitBytes;
502515
private final int stderrLimitBytes;
503516
private final long cleanupGraceMillis;
@@ -517,7 +530,7 @@ public ExecutionRequest(CommandLine commandLine, File workingDirectory,
517530
this(commandLine, workingDirectory, environment, timeoutMillis,
518531
legacyLimit(maxOutputBytes, DEFAULT_STDOUT_LIMIT),
519532
legacyLimit(maxOutputBytes, DEFAULT_STDERR_LIMIT), WAIT_GRACE_MILLIS,
520-
System.nanoTime(), new OpenCliCancellationToken());
533+
System.nanoTime(), new OpenCliCancellationToken(), maxOutputBytes);
521534
}
522535

523536
private static int legacyLimit(long maxOutputBytes, int defaultLimit) {
@@ -528,6 +541,14 @@ public ExecutionRequest(CommandLine commandLine, File workingDirectory,
528541
Map<String, String> environment, long timeoutMillis, int stdoutLimitBytes,
529542
int stderrLimitBytes, long cleanupGraceMillis, long submittedAtNanos,
530543
OpenCliCancellationToken cancellationToken) {
544+
this(commandLine, workingDirectory, environment, timeoutMillis, stdoutLimitBytes,
545+
stderrLimitBytes, cleanupGraceMillis, submittedAtNanos, cancellationToken, 0L);
546+
}
547+
548+
private ExecutionRequest(CommandLine commandLine, File workingDirectory,
549+
Map<String, String> environment, long timeoutMillis, int stdoutLimitBytes,
550+
int stderrLimitBytes, long cleanupGraceMillis, long submittedAtNanos,
551+
OpenCliCancellationToken cancellationToken, long maxOutputBytes) {
531552
this.commandLine = Objects.requireNonNull(commandLine, "commandLine");
532553
List<String> argv = new ArrayList<>(Arrays.asList(commandLine.toStrings()));
533554
for (int i = 0; i < argv.size(); i++) {
@@ -542,6 +563,7 @@ public ExecutionRequest(CommandLine commandLine, File workingDirectory,
542563
throw new IllegalArgumentException("stdout/stderr capture budgets must be positive");
543564
}
544565
this.timeoutMillis = timeoutMillis;
566+
this.maxOutputBytes = maxOutputBytes;
545567
this.stdoutLimitBytes = stdoutLimitBytes;
546568
this.stderrLimitBytes = stderrLimitBytes;
547569
this.cleanupGraceMillis = cleanupGraceMillis;
@@ -550,10 +572,41 @@ public ExecutionRequest(CommandLine commandLine, File workingDirectory,
550572
}
551573
}
552574

575+
/** Bounded stdout or stderr snapshot returned by the low-level execution API. */
576+
public static final class BoundedOutputStream extends OutputStream {
577+
private final BoundedCapture capture;
578+
579+
private BoundedOutputStream(BoundedCapture capture) {
580+
this.capture = capture;
581+
}
582+
583+
@Override
584+
public void write(int value) {
585+
capture.write(value);
586+
}
587+
588+
@Override
589+
public void write(byte[] bytes, int offset, int length) {
590+
capture.write(bytes, offset, length);
591+
}
592+
593+
public byte[] toByteArray() {
594+
return capture.toByteArray();
595+
}
596+
597+
public boolean isOverflowed() {
598+
return capture.isTruncated();
599+
}
600+
601+
int bufferCapacity() {
602+
return capture.bufferCapacity();
603+
}
604+
}
605+
553606
@Getter
554607
public static final class RunSession {
555-
private final ByteArrayOutputStream stdout;
556-
private final ByteArrayOutputStream stderr;
608+
private final BoundedOutputStream stdout;
609+
private final BoundedOutputStream stderr;
557610
private final DefaultExecuteResultHandler handler;
558611
private final ExecuteWatchdog watchdog;
559612
private final long timeoutMillis;
@@ -563,12 +616,12 @@ public static final class RunSession {
563616
/** Raw low-level I/O evidence, which can include local paths. Exclude it from default diagnostics. */
564617
private final IOException ioFailure;
565618

566-
RunSession(ByteArrayOutputStream stdout, ByteArrayOutputStream stderr,
619+
RunSession(BoundedCapture stdout, BoundedCapture stderr,
567620
DefaultExecuteResultHandler handler, ExecuteWatchdog watchdog, long timeoutMillis,
568621
boolean waitTimedOut, OpenCliExecutionDetails executionDetails,
569622
Integer observedExitCode, IOException ioFailure) {
570-
this.stdout = stdout;
571-
this.stderr = stderr;
623+
this.stdout = new BoundedOutputStream(stdout);
624+
this.stderr = new BoundedOutputStream(stderr);
572625
this.handler = handler;
573626
this.watchdog = watchdog;
574627
this.timeoutMillis = timeoutMillis;

‎src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,8 +234,8 @@ void cancelledSubmissionDoesNotInitializeWatchdogOrSpawn() throws Exception {
234234
assertEquals(CleanupState.NOT_STARTED, session.getExecutionDetails().getCleanupState());
235235
assertNull(session.getObservedExitCode());
236236
assertNotNull(session.getWatchdog());
237-
assertEquals(0, ((SubprocessExecutionSupport.BoundedCapture) session.getStdout()).bufferCapacity());
238-
assertEquals(0, ((SubprocessExecutionSupport.BoundedCapture) session.getStderr()).bufferCapacity());
237+
assertEquals(0, session.getStdout().bufferCapacity());
238+
assertEquals(0, session.getStderr().bufferCapacity());
239239
}
240240

241241
private static void assertCleanupSurvives(boolean failStop, boolean failDestroy) throws Exception {

‎src/test/java/io/github/easy4j/opencli/core/support/SubprocessCompletionRaceTest.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ void simultaneousSignalsKeepOneResultAndReuseThePermit() throws Exception {
5151
assertEquals(CleanupState.ROOT_EXIT_CONFIRMED,
5252
session.getExecutionDetails().getCleanupState());
5353
assertEquals(0, session.getObservedExitCode());
54-
assertEquals("partial", session.getStdout().toString(StandardCharsets.UTF_8.name()));
54+
assertEquals("partial", new String(session.getStdout().toByteArray(), StandardCharsets.UTF_8));
5555
assertEquals(7, session.getExecutionDetails().getStdoutCapturedBytes());
5656
assertTrue(session.getExecutionDetails().isStreamsDrained());
5757
assertFalse(runtime.isQuarantined());

‎src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,12 @@ void shouldCapCapturedOutputAtMaxBytes() throws Exception {
9898
SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
9999
cmd, null, null, 10_000L, 16L);
100100
SubprocessExecutionSupport.RunSession session = SubprocessExecutionSupport.execute(request);
101-
assertEquals(16, session.getStdout().toByteArray().length);
101+
SubprocessExecutionSupport.BoundedOutputStream stdout = session.getStdout();
102+
SubprocessExecutionSupport.BoundedOutputStream stderr = session.getStderr();
103+
assertEquals(16L, request.getMaxOutputBytes());
104+
assertEquals(16, stdout.toByteArray().length);
105+
assertTrue(stdout.isOverflowed());
106+
assertFalse(stderr.isOverflowed());
102107
assertTrue(session.isStdoutOverflowed());
103108
}
104109

‎src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java‎

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import java.nio.charset.StandardCharsets;
1212
import java.util.concurrent.CountDownLatch;
1313
import java.util.concurrent.TimeUnit;
14+
import java.util.concurrent.atomic.AtomicReference;
1415
import org.apache.commons.exec.CommandLine;
1516
import org.apache.commons.exec.ExecuteWatchdog;
1617
import org.junit.jupiter.api.Test;
@@ -39,7 +40,72 @@ void partialOutputAndReadFailureRemainVisibleAfterRootExit() throws Exception {
3940
assertEquals(TerminationReason.IO_FAILURE,
4041
session.getExecutionDetails().getTerminationReason());
4142
assertSame(readFailure, session.getIoFailure());
42-
assertEquals("abc", session.getStdout().toString(StandardCharsets.UTF_8.name()));
43+
assertEquals("abc", new String(session.getStdout().toByteArray(), StandardCharsets.UTF_8));
44+
assertTrue(session.getExecutionDetails().isStreamsDrained());
45+
}
46+
47+
@Test
48+
void readerFailureDuringRootExitPollDoesNotReportSuccessfulCompletion() throws Exception {
49+
IOException readFailure = new IOException("reader failed while root exit was observed");
50+
CountDownLatch readersStarted = new CountDownLatch(2);
51+
CountDownLatch releaseFailure = new CountDownLatch(1);
52+
AtomicReference<Thread> stdoutThread = new AtomicReference<>();
53+
AtomicReference<Thread> stderrThread = new AtomicReference<>();
54+
InputStream stdout = new InputStream() {
55+
@Override
56+
public int read() throws IOException {
57+
stdoutThread.set(Thread.currentThread());
58+
readersStarted.countDown();
59+
try {
60+
assertTrue(releaseFailure.await(2, TimeUnit.SECONDS));
61+
} catch (InterruptedException ex) {
62+
Thread.currentThread().interrupt();
63+
throw new IOException(ex);
64+
}
65+
throw readFailure;
66+
}
67+
};
68+
Process root = new ExitedProcess(stdout) {
69+
@Override
70+
public InputStream getErrorStream() {
71+
return new InputStream() {
72+
@Override
73+
public int read() {
74+
stderrThread.set(Thread.currentThread());
75+
readersStarted.countDown();
76+
return -1;
77+
}
78+
};
79+
}
80+
81+
@Override
82+
public boolean isAlive() {
83+
if (releaseFailure.getCount() > 0) {
84+
try {
85+
assertTrue(readersStarted.await(2, TimeUnit.SECONDS));
86+
releaseFailure.countDown();
87+
stdoutThread.get().join(1_000);
88+
stderrThread.get().join(1_000);
89+
assertFalse(stdoutThread.get().isAlive());
90+
assertFalse(stderrThread.get().isAlive());
91+
} catch (InterruptedException ex) {
92+
Thread.currentThread().interrupt();
93+
throw new AssertionError(ex);
94+
}
95+
}
96+
return false;
97+
}
98+
};
99+
SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
100+
builder -> root, timeout -> new IdleWatchdog());
101+
SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
102+
CommandLine.parse("fake"), null, null, 3_000L, 32, 32, 200L,
103+
System.nanoTime(), new OpenCliCancellationToken());
104+
105+
SubprocessExecutionSupport.RunSession session = runtime.execute(request);
106+
107+
assertEquals(TerminationReason.IO_FAILURE, session.getExecutionDetails().getTerminationReason());
108+
assertSame(readFailure, session.getIoFailure());
43109
assertTrue(session.getExecutionDetails().isStreamsDrained());
44110
}
45111

@@ -96,7 +162,7 @@ private static class IdleWatchdog extends ExecuteWatchdog {
96162
public synchronized void start(Process process) { }
97163
}
98164

99-
private static final class ExitedProcess extends Process {
165+
private static class ExitedProcess extends Process {
100166
private final InputStream output;
101167

102168
ExitedProcess(InputStream output) {

0 commit comments

Comments
 (0)