perf: restart without a fixed pause and wait no longer than --timeout (#36)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-08 22:41:35 -05:00
1 parent fc67e72a62
commit 01d6133548
9 files changed
+407 -34

No files matched your search

@@ -40,7 +40,7 @@ public class RestartCommand implements Callable<Integer> {
// Resolve the profile BEFORE stopping anything. A failure here must not leave the
// container stopped, and the values must not be re-read from a file that could change
// during the stop plus the one second wait below.
// during the stop.
StartCommand start;
try {
start = buildStartCommand();
@@ -56,19 +56,25 @@ public class RestartCommand implements Callable<Integer> {
return 2;
}
StopCommand stop = new StopCommand(profile);
stop.global = global;
stop.remove = false;
stop.timeout = 10;
int stopResult = stop.call();
int stopResult = buildStopCommand().call();
if (stopResult != 0) return stopResult;
// Minimal wait to avoid port-already-in-use races
try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
return start.call();
}
/**
* The {@code stop} this restart runs. It removes the container: {@code docker stop} returns
* once the container has exited, and removing it releases its port bindings, so the start
* that follows needs neither a pause nor a second inspect-and-remove of its own.
*/
public StopCommand buildStopCommand() {
StopCommand stop = new StopCommand(profile);
stop.global = global;
stop.remove = true;
stop.timeout = 10;
return stop;
}
/**
* The {@code start} this restart will run. Picocli never parses this instance, so the profile
* has to be applied by hand, and copying fields out of the Profile bean is not good enough:
@@ -164,6 +164,13 @@ public class StartCommand implements Callable<Integer> {
return args;
}
// DockerClient reports a missing binary as "docker binary not found"; on Windows the JDK says
// "Cannot run program" instead.
static boolean dockerMissing(DockerException e) {
String message = e.getMessage() == null ? "" : e.getMessage();
return message.contains("docker binary not found") || message.contains("Cannot run program");
}
/** {@code endpoint} with its port replaced, or a localhost URL if it cannot be parsed. */
public static String withPort(String endpoint, int port) {
try {
@@ -193,13 +200,8 @@ public class StartCommand implements Callable<Integer> {
return 2;
}
// Verify docker is available
if (!DockerClient.isInstalled()) {
printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/");
return 1;
}
// Check if container already exists
// Check if container already exists. This is also the first docker call, so a missing
// binary shows up here, without a separate `docker --version` probe on every start.
try {
var existing = docker.inspectContainer(global.container);
if (existing.isPresent()) {
@@ -213,6 +215,10 @@ public class StartCommand implements Callable<Integer> {
docker.removeContainer(global.container);
}
} catch (DockerException e) {
if (dockerMissing(e)) {
printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/");
return 1;
}
printer.error("Failed to inspect container: " + e.getMessage());
return 1;
}
@@ -250,6 +256,7 @@ public class StartCommand implements Callable<Integer> {
printer.println(Ansi.gray("Waiting for " + profile.displayName() + " to be ready..."));
WaitCommand wait = new WaitCommand(profile);
wait.global = global;
wait.knownEndpoint = global.endpoint;
wait.timeout = "30s";
return wait.call();
}
@@ -58,10 +58,19 @@ public class UpdateCommand implements Callable<Integer> {
private static final ObjectMapper JSON = new ObjectMapper();
private final HttpClient http = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.build();
// Built on first use: picocli constructs every command on every run, and an HttpClient
// (selector thread, TLS context) is too much to pay for commands that never update.
private HttpClient http;
private HttpClient http() {
if (http == null) {
http = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.build();
}
return http;
}
/** The binary to replace; {@code null} means "resolve the running executable". Test seam. */
Path selfPath;
@@ -220,7 +229,7 @@ public class UpdateCommand implements Callable<Integer> {
// ── download + verify ────────────────────────────────────────────────────
private String fetchString(String url) throws IOException, InterruptedException {
HttpResponse<String> resp = http.send(get(url), HttpResponse.BodyHandlers.ofString());
HttpResponse<String> resp = http().send(get(url), HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) {
throw new IOException("GET " + url + " → HTTP " + resp.statusCode());
}
@@ -232,7 +241,7 @@ public class UpdateCommand implements Callable<Integer> {
}
private void fetchFile(String url, Path dest) throws IOException, InterruptedException {
HttpResponse<Path> resp = http.send(get(url), HttpResponse.BodyHandlers.ofFile(dest));
HttpResponse<Path> resp = http().send(get(url), HttpResponse.BodyHandlers.ofFile(dest));
if (resp.statusCode() != 200) {
throw new UpdateException("download failed: " + url + " → HTTP " + resp.statusCode()
+ (resp.statusCode() == 404 ? " (does that release exist?)" : ""));
@@ -2,6 +2,7 @@ package io.floci.cli.commands;
import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.http.FlociHttpClient;
import io.floci.cli.util.Durations;
import io.floci.cli.output.Ansi;
@@ -14,6 +15,10 @@ import picocli.CommandLine.*;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Command(
name = "wait",
@@ -32,26 +37,48 @@ public class WaitCommand implements Callable<Integer> {
}
protected WaitCommand(ProductProfile profile) {
this(profile, new DockerClient());
}
/** Test seam: {@code docker} answers the container lookup that finds the endpoint. */
public WaitCommand(ProductProfile profile, DockerClient docker) {
this.profile = profile;
this.global = new GlobalOptions(profile);
this.docker = docker;
}
private final DockerClient docker;
@Option(names = {"--timeout"}, description = "Maximum time to wait (e.g. 30s, 2m)", defaultValue = "30s", paramLabel = "<duration>")
String timeout;
@Option(names = {"--service"}, description = "Wait until a specific service is enabled", paramLabel = "<name>")
String service;
/**
* Set by {@code start}, which already knows the port it bound: skips the {@code docker inspect}
* that resolving the endpoint from the container would cost.
*/
String knownEndpoint;
static final long FIRST_DELAY_MS = 25;
static final long MAX_DELAY_MS = 500;
static final Duration MAX_REQUEST_TIMEOUT = Duration.ofSeconds(10);
@Override
public Integer call() {
Printer printer = global.printer();
long timeoutMillis = Durations.parseDuration(timeout);
String effectiveEndpoint = global.resolvedEndpoint(new io.floci.cli.docker.DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix());
// The deadline starts now, so the container lookup below counts against --timeout too.
Instant deadline = Instant.now().plusMillis(timeoutMillis);
String effectiveEndpoint = knownEndpoint != null ? knownEndpoint : endpointWithin(deadline);
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix());
// Poll soon after a start, then back off; never let a request or a pause run past the
// deadline, so --timeout is a real upper bound.
long delay = FIRST_DELAY_MS;
while (Instant.now().isBefore(deadline)) {
if (isReady(client, service)) {
if (isReady(client, service, requestTimeout(Duration.between(Instant.now(), deadline)))) {
if (printer.format() != OutputFormat.text) {
printer.structured(Map.of("ready", true, "endpoint", effectiveEndpoint));
} else {
@@ -60,10 +87,13 @@ public class WaitCommand implements Callable<Integer> {
return 0;
}
printSpinner(printer, deadline);
try { Thread.sleep(500); } catch (InterruptedException e) {
long remaining = Duration.between(Instant.now(), deadline).toMillis();
if (remaining <= 0) break;
try { Thread.sleep(Math.min(delay, remaining)); } catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
delay = nextDelay(delay);
}
printer.error("Timed out waiting for " + profile.displayName() + " after " + timeout
@@ -71,9 +101,48 @@ public class WaitCommand implements Callable<Integer> {
return 1;
}
private boolean isReady(FlociHttpClient client, String requiredService) {
// A stalled daemon or an unreachable remote DOCKER_HOST can hold `docker inspect` far longer
// than --timeout, so the lookup gets the time left and the configured endpoint is the fallback.
private String endpointWithin(Instant deadline) {
long remaining = Duration.between(Instant.now(), deadline).toMillis();
if (remaining <= 0) return global.endpoint;
// A detached virtual thread: a hung lookup is abandoned, not joined, and cannot keep the
// JVM alive once wait returns.
CompletableFuture<String> resolved = new CompletableFuture<>();
Thread lookup = Thread.ofVirtual().name("floci-wait-endpoint").start(() -> {
try {
resolved.complete(global.resolvedEndpoint(docker));
} catch (RuntimeException e) {
resolved.complete(global.endpoint);
}
});
try {
var health = client.health();
return resolved.get(remaining, TimeUnit.MILLISECONDS);
} catch (TimeoutException | ExecutionException e) {
lookup.interrupt(); // DockerClient kills the docker process it was waiting on
return global.endpoint;
} catch (InterruptedException e) {
lookup.interrupt();
Thread.currentThread().interrupt();
return global.endpoint;
}
}
/** 25 ms, 50, 200, 400, then 500 ms between polls: an emulator is often up within
* a few dozen milliseconds of `docker run`, and a refused local poll costs nothing. */
public static long nextDelay(long previous) {
return Math.min(previous * 2, MAX_DELAY_MS);
}
/** A request may use the time left, up to the usual 10 s, and at least a millisecond. */
public static Duration requestTimeout(Duration remaining) {
if (remaining.compareTo(MAX_REQUEST_TIMEOUT) > 0) return MAX_REQUEST_TIMEOUT;
return remaining.isNegative() || remaining.isZero() ? Duration.ofMillis(1) : remaining;
}
private boolean isReady(FlociHttpClient client, String requiredService, Duration timeout) {
try {
var health = client.health(timeout);
if (requiredService == null) return true;
for (String s : health.services()) {
if (s.equalsIgnoreCase(requiredService)) return true;
@@ -2,11 +2,13 @@ package io.floci.cli.docker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Thin subprocess wrapper around the docker CLI.
@@ -14,6 +16,17 @@ import java.util.Optional;
*/
public class DockerClient {
private final String binary;
public DockerClient() {
this("docker");
}
/** Test seam: run {@code binary} in place of {@code docker}. */
public DockerClient(String binary) {
this.binary = binary;
}
public record ContainerInfo(
String id,
String name,
@@ -129,16 +142,23 @@ public class DockerClient {
}
private String run(String... cmd) throws DockerException {
Process proc = null;
try {
Process proc = runProcess(cmd);
String stdout = new String(proc.getInputStream().readAllBytes());
String stderr = new String(proc.getErrorStream().readAllBytes());
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.
CompletableFuture<String> stdout = drain(proc.getInputStream());
CompletableFuture<String> stderr = drain(proc.getErrorStream());
int code = proc.waitFor();
String out = stdout.join();
String err = stderr.join();
if (code != 0) {
throw new DockerException(stderr.isBlank() ? stdout : stderr);
throw new DockerException(err.isBlank() ? out : err);
}
return stdout;
return out;
} catch (InterruptedException e) {
if (proc != null) proc.destroyForcibly();
Thread.currentThread().interrupt();
throw new DockerException("Interrupted");
} catch (IOException e) {
@@ -178,7 +198,23 @@ public class DockerClient {
}
}
private static CompletableFuture<String> drain(InputStream stream) {
CompletableFuture<String> text = new CompletableFuture<>();
Thread.ofVirtual().start(() -> {
try (stream) {
text.complete(new String(stream.readAllBytes()));
} catch (IOException e) {
text.complete("");
}
});
return text;
}
private Process runProcess(String... cmd) throws IOException {
if (cmd.length > 0 && "docker".equals(cmd[0])) {
cmd = cmd.clone();
cmd[0] = binary;
}
return new ProcessBuilder(cmd)
.redirectErrorStream(false)
.start();
@@ -13,6 +13,10 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FlociHttpClient {
@@ -182,13 +186,29 @@ public class FlociHttpClient {
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
// HttpRequest.timeout stops counting once the headers arrive, so a server that stalls
// mid-body would outlive it; the whole exchange is bounded here and cancelled on expiry.
CompletableFuture<HttpResponse<String>> pending = http.sendAsync(req, HttpResponse.BodyHandlers.ofString());
HttpResponse<String> resp;
try {
resp = pending.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
pending.cancel(true);
throw new FlociException("No complete response from " + endpoint + path + " within "
+ timeout.toMillis() + " ms. Is Floci running? Try 'floci status'.");
} catch (ExecutionException e) {
if (e.getCause() instanceof ConnectException) throw (ConnectException) e.getCause();
throw new FlociException("Request failed: " + e.getCause().getMessage());
}
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
}
return MAPPER.readTree(resp.body());
} catch (FlociException e) {
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new FlociException("Request interrupted.\nRe-run the command.");
} catch (ConnectException e) {
throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci status' or 'floci start'.");
} catch (Exception e) {