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.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 16:28:45 -05:00
1 parent 522e54ef3c
commit 7ecc895baa
4 files changed
+232 -28

No files matched your search

@@ -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<String> 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<String> 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() || "<no value>".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<String> 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<String> stdout = drain(proc.getInputStream());
CompletableFuture<String> 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;
}