From 7ecc895baaaf1c61f38bc1d1bde7ce2ab6699ee6 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 16:28:45 -0500 Subject: [PATCH] fix(docker): time-limit docker calls and pass names after -- (#47) * fix(docker): time-limit docker calls and pass names after -- Non-streaming docker calls are killed after 30 s (docker run after 10 minutes, stop after its own timeout plus 30 s) with a message naming the stalled command; any abnormal exit kills the process, streaming calls included; container and image names are passed after -- so a name starting with '-' is never read as a flag. * fix(docker): time-limit the daemon probe and let stop --timeout -1 wait indefinitely The doctor's daemon probe and the install probe now share the time limit and cleanup of every other docker call. A negative stop timeout is docker's wait-indefinitely (checked against Docker 29.8.2), so that call is no longer cut off after 29 seconds. Adds tests for the probe, both stop cases and interrupted streaming calls. --- README.md | 1 + .../io/floci/cli/commands/StopCommand.java | 2 +- .../io/floci/cli/docker/DockerClient.java | 116 ++++++++++---- .../cli/unit/DockerClientProcessTest.java | 141 ++++++++++++++++++ 4 files changed, 232 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 33793a8..bd89781 100644 --- a/README.md +++ b/README.md @@ -453,6 +453,7 @@ instead. Run `floci doctor` to see which endpoint was resolved. ```sh floci stop # graceful stop (10s timeout) floci stop --timeout 30 # wait up to 30s before force-kill +floci stop --timeout -1 # never force-kill: wait for the container to exit floci stop --remove # also remove the container after stopping ``` diff --git a/src/main/java/io/floci/cli/commands/StopCommand.java b/src/main/java/io/floci/cli/commands/StopCommand.java index ace8b66..87f2749 100644 --- a/src/main/java/io/floci/cli/commands/StopCommand.java +++ b/src/main/java/io/floci/cli/commands/StopCommand.java @@ -34,7 +34,7 @@ public class StopCommand implements Callable { @Option(names = {"--remove", "-r"}, description = "Remove the container after stopping") boolean remove; - @Option(names = {"--timeout"}, description = "Seconds to wait before forcefully killing (default: 10)", defaultValue = "10", paramLabel = "") + @Option(names = {"--timeout"}, description = "Seconds to wait before forcefully killing; -1 waits indefinitely (default: 10)", defaultValue = "10", paramLabel = "") int timeout; @Override diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index cd71b56..1197268 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -4,11 +4,13 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; /** * Thin subprocess wrapper around the docker CLI. @@ -16,7 +18,11 @@ import java.util.concurrent.CompletableFuture; */ public class DockerClient { + /** How long a non-streaming docker call may take before it is killed. */ + public static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(30); + private final String binary; + private final Duration timeout; public DockerClient() { this("docker"); @@ -24,7 +30,13 @@ public class DockerClient { /** Test seam: run {@code binary} in place of {@code docker}. */ public DockerClient(String binary) { + this(binary, DEFAULT_TIMEOUT); + } + + /** Test seam: run {@code binary}, killing any non-streaming call that outlives {@code timeout}. */ + public DockerClient(String binary, Duration timeout) { this.binary = binary; + this.timeout = timeout; } public record ContainerInfo( @@ -45,14 +57,12 @@ public class DockerClient { // Probe connectivity by exit code only. `docker info` / `podman info` // exit 0 when the daemon (or DOCKER_HOST socket) is reachable. Avoid a // Docker-only template field like {{.ServerVersion}}, which errors under - // Podman and yields a false "daemon not reachable". Output is discarded - // so the unread pipe can't fill and deadlock waitFor(). - Process p = new ProcessBuilder("docker", "info") - .redirectOutput(ProcessBuilder.Redirect.DISCARD) - .redirectError(ProcessBuilder.Redirect.DISCARD) - .start(); - return p.waitFor() == 0; - } catch (Exception e) { + // Podman and yields a false "daemon not reachable". Going through run() gives + // the probe the same time limit and cleanup as every other call, so a daemon + // that accepts the connection and then stalls reads as unreachable. + run("docker", "info"); + return true; + } catch (DockerException e) { return false; } } @@ -63,7 +73,7 @@ public class DockerClient { "--format", "{{.Id}}|{{.Name}}|{{.Config.Image}}|{{.State.Status}}|" + "{{range $p, $b := .NetworkSettings.Ports}}{{if $b}}{{(index $b 0).HostPort}}->{{$p}} {{end}}{{end}}", - name); + "--", name); if (out.isBlank()) return Optional.empty(); String[] parts = out.trim().split("\\|", -1); return Optional.of(new ContainerInfo( @@ -82,7 +92,7 @@ public class DockerClient { public boolean isImagePresent(String image) throws DockerException { try { - String out = run("docker", "images", "-q", image); + String out = run("docker", "images", "-q", "--", image); return !out.isBlank(); } catch (DockerException e) { return false; @@ -91,7 +101,7 @@ public class DockerClient { public Optional imageDigest(String image) throws DockerException { try { - String out = run("docker", "inspect", "--format", "{{index .RepoDigests 0}}", image); + String out = run("docker", "inspect", "--format", "{{index .RepoDigests 0}}", "--", image); return out.isBlank() ? Optional.empty() : Optional.of(out.trim()); } catch (DockerException e) { return Optional.empty(); @@ -102,7 +112,7 @@ public class DockerClient { public Optional imageLabel(String image, String key) throws DockerException { try { String out = run("docker", "inspect", "--format", - "{{index .Config.Labels \"" + key + "\"}}", image); + "{{index .Config.Labels \"" + key + "\"}}", "--", image); String value = out.trim(); return value.isEmpty() || "".equals(value) ? Optional.empty() : Optional.of(value); } catch (DockerException e) { @@ -113,7 +123,7 @@ public class DockerClient { public void pull(String image, String policy) throws DockerException { if ("never".equalsIgnoreCase(policy)) return; if ("missing".equalsIgnoreCase(policy) && isImagePresent(image)) return; - runStreaming("docker", "pull", image); + runStreaming("docker", "pull", "--", image); } public String startContainer(List args) throws DockerException { @@ -121,15 +131,28 @@ public class DockerClient { cmd.add("docker"); cmd.add("run"); cmd.addAll(args); - return run(cmd.toArray(String[]::new)).trim(); + // docker run may still pull the image (--pull never with a missing image), so it gets + // far longer than the lookups. + return run(Duration.ofMinutes(10), cmd.toArray(String[]::new)).trim(); } + /** + * Stops {@code name}, giving it {@code timeout} seconds before docker kills it. A negative + * {@code timeout} is docker's "wait indefinitely", so that call gets no time limit either. + */ public void stopContainer(String name, int timeout) throws DockerException { - run("docker", "stop", "--time", String.valueOf(timeout), name); + // -t is the one spelling every docker and podman accepts (--time is deprecated for --timeout). + run(stopLimit(timeout), "docker", "stop", "-t", String.valueOf(timeout), "--", name); + } + + // The container's grace period plus this client's own limit for docker to answer; null (no + // limit) when the grace period is itself unlimited. + private Duration stopLimit(int timeout) { + return timeout < 0 ? null : Duration.ofSeconds(timeout).plus(this.timeout); } public void removeContainer(String name) throws DockerException { - run("docker", "rm", name); + run("docker", "rm", "--", name); } public void streamLogs(String name, boolean follow, int tail, String since) throws DockerException { @@ -137,28 +160,40 @@ public class DockerClient { if (follow) cmd.add("--follow"); if (tail > 0) { cmd.add("--tail"); cmd.add(String.valueOf(tail)); } if (since != null && !since.isBlank()) { cmd.add("--since"); cmd.add(since); } + cmd.add("--"); cmd.add(name); runStreaming(cmd.toArray(String[]::new)); } private String run(String... cmd) throws DockerException { + return run(timeout, cmd); + } + + /** Runs {@code cmd} for at most {@code limit}; a null {@code limit} waits as long as it takes. */ + private String run(Duration limit, String... cmd) throws DockerException { Process proc = null; + boolean finished = false; try { proc = runProcess(cmd); - // Both streams drain at once, so a full stderr pipe cannot stall the process, and the - // wait below is interruptible: an abandoned lookup kills its process instead of - // leaving it running after the CLI exits. + // Both streams drain at once, so a full stderr pipe cannot stall the process; the wait + // is bounded and interruptible, and any way out of it but a normal exit kills the + // process, so no docker call outlives the CLI. CompletableFuture stdout = drain(proc.getInputStream()); CompletableFuture stderr = drain(proc.getErrorStream()); - int code = proc.waitFor(); + if (limit == null) { + proc.waitFor(); + } else if (!proc.waitFor(limit.toMillis(), TimeUnit.MILLISECONDS)) { + throw new DockerException("'" + describe(cmd) + "' did not finish within " + limit.toSeconds() + + "s.\nCheck that the Docker daemon is responsive ('docker info') and re-run the command."); + } + finished = true; String out = stdout.join(); String err = stderr.join(); - if (code != 0) { + if (proc.exitValue() != 0) { throw new DockerException(err.isBlank() ? out : err); } return out; } catch (InterruptedException e) { - if (proc != null) proc.destroyForcibly(); Thread.currentThread().interrupt(); throw new DockerException("Interrupted"); } catch (IOException e) { @@ -166,25 +201,42 @@ public class DockerClient { throw new DockerException("docker binary not found in PATH. Install Docker Desktop or Docker Engine."); } throw new DockerException(e.getMessage()); + } finally { + if (proc != null && !finished) proc.destroyForcibly(); } } + // "docker container inspect" for messages: the subcommand words, never the user's arguments. + private static String describe(String... cmd) { + StringBuilder words = new StringBuilder(); + for (String part : cmd) { + if (part.startsWith("-")) break; + if (!words.isEmpty()) words.append(' '); + words.append(part); + } + return words.toString(); + } + private void runStreaming(String... cmd) throws DockerException { + Process proc = null; + boolean finished = false; try { - Process proc = runProcess(cmd); + Process started = runProcess(cmd); + proc = started; Thread out = new Thread(() -> { - try (var reader = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { + try (var reader = new BufferedReader(new InputStreamReader(started.getInputStream()))) { reader.lines().forEach(System.out::println); } catch (IOException ignored) {} }); Thread err = new Thread(() -> { - try (var reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()))) { + try (var reader = new BufferedReader(new InputStreamReader(started.getErrorStream()))) { reader.lines().forEach(System.err::println); } catch (IOException ignored) {} }); out.start(); err.start(); int code = proc.waitFor(); + finished = true; out.join(); err.join(); if (code != 0) { @@ -195,6 +247,9 @@ public class DockerClient { throw new DockerException("Interrupted"); } catch (IOException e) { throw new DockerException(e.getMessage()); + } finally { + // Streaming calls (pull, logs --follow) have no time limit, but never outlive the CLI. + if (proc != null && !finished) proc.destroyForcibly(); } } @@ -222,8 +277,15 @@ public class DockerClient { public static boolean isInstalled() { try { - Process p = new ProcessBuilder("docker", "--version").start(); - return p.waitFor() == 0; + Process p = new ProcessBuilder("docker", "--version") + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + if (p.waitFor(DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) { + return p.exitValue() == 0; + } + p.destroyForcibly(); + return false; } catch (Exception e) { return false; } diff --git a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java index e53fc21..a90f15f 100644 --- a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java +++ b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java @@ -6,9 +6,14 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.*; @@ -47,6 +52,102 @@ class DockerClientProcessTest { assertFalse(isAlive(pid), "docker process " + pid + " outlived the interrupted call"); } + /** A stalled daemon probe is cut off at the time limit and reads as unreachable. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void aStalledDaemonProbeReportsUnreachableAndIsKilled() throws Exception { + Path pidFile = tempDir.resolve("pid"); + DockerClient docker = new DockerClient(fakeDocker("echo $$ > '" + pidFile + "'\nexec sleep 30\n"), + Duration.ofMillis(500)); + + long start = System.nanoTime(); + boolean reachable = docker.isDaemonReachable(); + long elapsedMs = (System.nanoTime() - start) / 1_000_000; + + assertFalse(reachable); + assertTrue(elapsedMs < 3_000, "took " + elapsedMs + " ms"); + assertExits(awaitPid(pidFile), "the stalled probe is still running"); + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void theDaemonProbeFollowsTheExitCode() throws Exception { + assertTrue(new DockerClient(fakeDocker("echo some output\nexit 0\n")).isDaemonReachable()); + assertFalse(new DockerClient(fakeDocker("echo cannot connect >&2\nexit 1\n")).isDaemonReachable()); + } + + /** "stop --timeout -1" is docker's wait-indefinitely, so the CLI must not cut it short. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void anIndefiniteStopIsNotTimeLimited() throws Exception { + Path argsFile = tempDir.resolve("args"); + DockerClient docker = new DockerClient( + fakeDocker("for a in \"$@\"; do echo \"$a\"; done > '" + argsFile + "'\nsleep 1.5\n"), + Duration.ofMillis(300)); + + docker.stopContainer("floci", -1); + + assertEquals(List.of("stop", "-t", "-1", "--", "floci"), Files.readAllLines(argsFile)); + } + + /** A bounded stop still gets a limit: the grace period plus the client's own. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void aBoundedStopIsStillTimeLimited() throws Exception { + DockerClient docker = new DockerClient(fakeDocker("exec sleep 30\n"), Duration.ofMillis(300)); + + DockerException e = assertThrows(DockerException.class, () -> docker.stopContainer("floci", 0)); + + assertTrue(e.getMessage().contains("did not finish within"), e.getMessage()); + } + + /** Streaming calls have no time limit, so interruption is their only way out: it must kill docker. */ + @ParameterizedTest + @ValueSource(strings = {"logs", "pull"}) + @DisabledOnOs(OS.WINDOWS) + void anInterruptedStreamingCallKillsItsDockerProcess(String call) throws Exception { + Path pidFile = tempDir.resolve("pid"); + // Lines on both streams first, so both reader threads are mid-read when the interrupt lands. + DockerClient docker = new DockerClient( + fakeDocker("echo $$ > '" + pidFile + "'\necho out\necho err >&2\nexec sleep 30\n")); + AtomicReference failure = new AtomicReference<>(); + + Thread streaming = Thread.ofPlatform().start(() -> { + try { + if ("logs".equals(call)) { + docker.streamLogs("floci", true, 0, null); + } else { + docker.pull("floci/floci:latest", "always"); + } + } catch (DockerException e) { + failure.set(e.getMessage()); + } + }); + long pid = awaitPid(pidFile); + + streaming.interrupt(); + streaming.join(5_000); + + assertFalse(streaming.isAlive(), "the streaming call should return once interrupted"); + assertEquals("Interrupted", failure.get()); + assertExits(pid, "docker process " + pid + " outlived the interrupted streaming call"); + } + + private String fakeDocker(String body) throws Exception { + Path fakeDocker = Files.createTempFile(tempDir, "docker", ""); + Files.writeString(fakeDocker, "#!/bin/sh\n" + body); + assertTrue(fakeDocker.toFile().setExecutable(true)); + return fakeDocker.toString(); + } + + private static void assertExits(long pid, String message) throws Exception { + long deadline = System.currentTimeMillis() + 3_000; + while (isAlive(pid) && System.currentTimeMillis() < deadline) { + Thread.sleep(50); + } + assertFalse(isAlive(pid), message); + } + private static long awaitPid(Path pidFile) throws Exception { long deadline = System.currentTimeMillis() + 5_000; while (System.currentTimeMillis() < deadline) { @@ -62,4 +163,44 @@ class DockerClientProcessTest { private static boolean isAlive(long pid) { return ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false); } + + /** BL-045: a stalled docker call is killed at the time limit instead of hanging the CLI. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void aCallThatOutlivesItsTimeLimitIsKilledAndReported() throws Exception { + Path pidFile = tempDir.resolve("pid"); + Path fakeDocker = tempDir.resolve("docker"); + Files.writeString(fakeDocker, "#!/bin/sh\necho $$ > '" + pidFile + "'\nexec sleep 30\n"); + assertTrue(fakeDocker.toFile().setExecutable(true)); + DockerClient docker = new DockerClient(fakeDocker.toString(), Duration.ofMillis(500)); + + long start = System.nanoTime(); + DockerException e = assertThrows(DockerException.class, docker::dockerVersion); + long elapsedMs = (System.nanoTime() - start) / 1_000_000; + + assertTrue(elapsedMs < 3_000, "took " + elapsedMs + " ms"); + assertTrue(e.getMessage().contains("did not finish within"), e.getMessage()); + long pid = awaitPid(pidFile); + long deadline = System.currentTimeMillis() + 3_000; + while (isAlive(pid) && System.currentTimeMillis() < deadline) { + Thread.sleep(50); + } + assertFalse(isAlive(pid), "the timed-out docker process is still running"); + } + + /** BL-045: names go after "--", so a name starting with '-' is never read as a flag. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void namesArePassedAfterTheEndOfOptionsMarker() throws Exception { + Path argsFile = tempDir.resolve("args"); + Path fakeDocker = tempDir.resolve("docker"); + Files.writeString(fakeDocker, "#!/bin/sh\nfor a in \"$@\"; do echo \"$a\"; done > '" + argsFile + "'\n"); + assertTrue(fakeDocker.toFile().setExecutable(true)); + DockerClient docker = new DockerClient(fakeDocker.toString()); + + docker.removeContainer("--rm-everything"); + List args = Files.readAllLines(argsFile); + + assertEquals(List.of("rm", "--", "--rm-everything"), args); + } }