mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
perf: restart without a fixed pause and wait no longer than --timeout (#36)
This commit is contained in:
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) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
import io.floci.cli.docker.DockerException;
|
||||
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 java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** An abandoned docker call must not leave its process running after the CLI moves on. */
|
||||
class DockerClientProcessTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
@DisabledOnOs(OS.WINDOWS)
|
||||
void anInterruptedCallKillsItsDockerProcess() 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());
|
||||
|
||||
Thread call = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
docker.inspectContainer("floci");
|
||||
} catch (DockerException expected) {
|
||||
// "Interrupted"
|
||||
}
|
||||
});
|
||||
long pid = awaitPid(pidFile);
|
||||
|
||||
call.interrupt();
|
||||
call.join(5_000);
|
||||
|
||||
assertFalse(call.isAlive(), "the call should return once interrupted");
|
||||
long deadline = System.currentTimeMillis() + 3_000;
|
||||
while (isAlive(pid) && System.currentTimeMillis() < deadline) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
assertFalse(isAlive(pid), "docker process " + pid + " outlived the interrupted call");
|
||||
}
|
||||
|
||||
private static long awaitPid(Path pidFile) throws Exception {
|
||||
long deadline = System.currentTimeMillis() + 5_000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
if (Files.exists(pidFile)) {
|
||||
String text = Files.readString(pidFile).trim();
|
||||
if (!text.isEmpty()) return Long.parseLong(text);
|
||||
}
|
||||
Thread.sleep(20);
|
||||
}
|
||||
throw new AssertionError("fake docker never started");
|
||||
}
|
||||
|
||||
private static boolean isAlive(long pid) {
|
||||
return ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import io.floci.cli.commands.RestartCommand;
|
||||
import io.floci.cli.config.ProfileStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import picocli.CommandLine;
|
||||
import picocli.CommandLine.ParseResult;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -149,4 +150,12 @@ class RestartCommandTest {
|
||||
Files.delete(tempDir.resolve("snap.yaml"));
|
||||
assertTrue(restart.buildStartCommand().dockerRunArgs(SOCKET).contains("/from-the-parse:/app/data"));
|
||||
}
|
||||
|
||||
/** BL-029: the stop removes the container, so start needs no pause and no second removal. */
|
||||
@Test
|
||||
void theStopItRunsRemovesTheContainer() {
|
||||
var stop = parse(ProductProfile.AWS).buildStopCommand();
|
||||
|
||||
assertEquals(Boolean.TRUE, new CommandLine(stop).getCommandSpec().findOption("--remove").getValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.cli.FlociCli;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.commands.WaitCommand;
|
||||
import io.floci.cli.config.ProfileStore;
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import picocli.CommandLine;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** BL-030: wait polls soon after a start and never runs past --timeout. */
|
||||
class WaitCommandTimingTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void pollingBacksOffFromTwentyFiveMillisToHalfASecond() {
|
||||
assertEquals(50, WaitCommand.nextDelay(25));
|
||||
assertEquals(100, WaitCommand.nextDelay(50));
|
||||
assertEquals(200, WaitCommand.nextDelay(100));
|
||||
assertEquals(400, WaitCommand.nextDelay(200));
|
||||
assertEquals(500, WaitCommand.nextDelay(400));
|
||||
assertEquals(500, WaitCommand.nextDelay(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestNeverOutlivesTheDeadline() {
|
||||
assertEquals(Duration.ofSeconds(10), WaitCommand.requestTimeout(Duration.ofMinutes(2)));
|
||||
assertEquals(Duration.ofMillis(800), WaitCommand.requestTimeout(Duration.ofMillis(800)));
|
||||
assertEquals(Duration.ofMillis(1), WaitCommand.requestTimeout(Duration.ZERO));
|
||||
assertEquals(Duration.ofMillis(1), WaitCommand.requestTimeout(Duration.ofMillis(-5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerThatNeverAnswersStillTimesOutOnTime() throws Exception {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
try {
|
||||
Thread.sleep(5_000); // longer than the timeout below
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
PrintStream err = System.err;
|
||||
PrintStream out = System.out;
|
||||
System.setErr(new PrintStream(new ByteArrayOutputStream()));
|
||||
System.setOut(new PrintStream(new ByteArrayOutputStream()));
|
||||
try {
|
||||
String endpoint = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
long start = System.nanoTime();
|
||||
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(
|
||||
"wait", "--timeout", "1s", "--endpoint", endpoint, "--container", "floci-wait-timing-none");
|
||||
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
|
||||
|
||||
assertEquals(1, exit);
|
||||
// The old loop could block for a full 10 s request; allow docker's inspect on top.
|
||||
assertTrue(elapsedMs < 2_500, "took " + elapsedMs + " ms");
|
||||
} finally {
|
||||
System.setErr(err);
|
||||
System.setOut(out);
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** A stalled Docker daemon must not hold wait past --timeout either. */
|
||||
@Test
|
||||
void aHungContainerLookupStillTimesOutOnTime() {
|
||||
DockerClient hung = new DockerClient() {
|
||||
@Override
|
||||
public Optional<ContainerInfo> inspectContainer(String name) {
|
||||
try {
|
||||
Thread.sleep(5_000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
};
|
||||
PrintStream err = System.err;
|
||||
PrintStream out = System.out;
|
||||
System.setErr(new PrintStream(new ByteArrayOutputStream()));
|
||||
System.setOut(new PrintStream(new ByteArrayOutputStream()));
|
||||
try {
|
||||
long start = System.nanoTime();
|
||||
// Port 9 (discard) refuses connections quickly, so only the lookup could stall.
|
||||
int exit = new CommandLine(new WaitCommand(ProductProfile.AWS, hung))
|
||||
.execute("--timeout", "1s", "--endpoint", "http://127.0.0.1:9");
|
||||
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
|
||||
|
||||
assertEquals(1, exit);
|
||||
assertTrue(elapsedMs < 1_800, "took " + elapsedMs + " ms");
|
||||
} finally {
|
||||
System.setErr(err);
|
||||
System.setOut(out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Headers arrive at once, then the body stalls: HttpRequest.timeout alone would not cover it. */
|
||||
@Test
|
||||
void aServerThatStallsMidBodyStillTimesOutOnTime() throws Exception {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
exchange.sendResponseHeaders(200, 0); // chunked: the body never completes
|
||||
exchange.getResponseBody().write("{\"version\":".getBytes());
|
||||
exchange.getResponseBody().flush();
|
||||
try {
|
||||
Thread.sleep(5_000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
DockerClient noContainer = new DockerClient() {
|
||||
@Override
|
||||
public Optional<ContainerInfo> inspectContainer(String name) {
|
||||
return Optional.empty();
|
||||
}
|
||||
};
|
||||
PrintStream err = System.err;
|
||||
PrintStream out = System.out;
|
||||
System.setErr(new PrintStream(new ByteArrayOutputStream()));
|
||||
System.setOut(new PrintStream(new ByteArrayOutputStream()));
|
||||
try {
|
||||
long start = System.nanoTime();
|
||||
int exit = new CommandLine(new WaitCommand(ProductProfile.AWS, noContainer)).execute(
|
||||
"--timeout", "1s", "--endpoint", "http://127.0.0.1:" + server.getAddress().getPort());
|
||||
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
|
||||
|
||||
assertEquals(1, exit);
|
||||
assertTrue(elapsedMs < 1_800, "took " + elapsedMs + " ms");
|
||||
} finally {
|
||||
System.setErr(err);
|
||||
System.setOut(out);
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user