mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-12-02 17:58:06 -05:00
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:
4 files changed
+132
-13
No files matched your search
@@ -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
|
||||
```
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ public class StopCommand implements Callable<Integer> {
|
||||
@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 = "<seconds>")
|
||||
@Option(names = {"--timeout"}, description = "Seconds to wait before forcefully killing; -1 waits indefinitely (default: 10)", defaultValue = "10", paramLabel = "<seconds>")
|
||||
int timeout;
|
||||
|
||||
@Override
|
||||
|
||||
@@ -57,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;
|
||||
}
|
||||
}
|
||||
@@ -138,8 +136,19 @@ public class DockerClient {
|
||||
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(Duration.ofSeconds(timeout).plus(DEFAULT_TIMEOUT), "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 {
|
||||
@@ -160,6 +169,7 @@ public class DockerClient {
|
||||
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;
|
||||
@@ -170,7 +180,9 @@ public class DockerClient {
|
||||
// process, so no docker call outlives the CLI.
|
||||
CompletableFuture<String> stdout = drain(proc.getInputStream());
|
||||
CompletableFuture<String> stderr = drain(proc.getErrorStream());
|
||||
if (!proc.waitFor(limit.toMillis(), TimeUnit.MILLISECONDS)) {
|
||||
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.");
|
||||
}
|
||||
@@ -265,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;
|
||||
}
|
||||
|
||||
@@ -6,11 +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.*;
|
||||
|
||||
@@ -49,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<String> 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) {
|
||||
|
||||
Reference in new issue
Block a user