From dd38f6dc27307d7297d5fcc5c1a02897f8bb9f03 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 8 Oct 2026 21:28:58 -0500 Subject: [PATCH] perf(doctor): run checks concurrently and share docker lookups (#32) --- .../io/floci/cli/commands/DoctorCommand.java | 115 +++++++++-- .../floci/cli/docker/CachingDockerClient.java | 85 ++++++++ .../io/floci/cli/docker/DockerClient.java | 12 ++ src/main/java/io/floci/cli/doctor/Check.java | 9 + .../doctor/checks/AwsCliEndpointCheck.java | 5 + .../doctor/checks/AwsCliS3PathStyleCheck.java | 5 + .../checks/AzCliConnectionStringCheck.java | 5 + .../doctor/checks/AzCliInstalledCheck.java | 5 + .../doctor/checks/ContainerRunningCheck.java | 18 +- .../cli/doctor/checks/DockerDaemonCheck.java | 17 +- .../doctor/checks/DockerInstalledCheck.java | 30 ++- .../cli/doctor/checks/DockerSocketCheck.java | 5 + .../cli/doctor/checks/DockerVersionCheck.java | 18 +- .../doctor/checks/EndpointReachableCheck.java | 21 +- .../cli/doctor/checks/ImagePresentCheck.java | 13 +- .../cli/doctor/checks/ImageVersionCheck.java | 30 ++- .../cli/doctor/checks/PortAvailableCheck.java | 17 +- .../io/floci/cli/http/FlociHttpClient.java | 13 +- .../io/floci/cli/unit/DoctorCommandTest.java | 195 ++++++++++++++++++ .../cli/unit/EndpointReachableCheckTest.java | 56 +++++ 20 files changed, 623 insertions(+), 51 deletions(-) create mode 100644 src/main/java/io/floci/cli/docker/CachingDockerClient.java create mode 100644 src/test/java/io/floci/cli/unit/DoctorCommandTest.java create mode 100644 src/test/java/io/floci/cli/unit/EndpointReachableCheckTest.java diff --git a/src/main/java/io/floci/cli/commands/DoctorCommand.java b/src/main/java/io/floci/cli/commands/DoctorCommand.java index 19f5937..c8aa501 100644 --- a/src/main/java/io/floci/cli/commands/DoctorCommand.java +++ b/src/main/java/io/floci/cli/commands/DoctorCommand.java @@ -5,6 +5,7 @@ import io.floci.cli.ProductProfile; import io.floci.cli.doctor.Check; import io.floci.cli.doctor.CheckResult; import io.floci.cli.doctor.CheckStatus; +import io.floci.cli.docker.CachingDockerClient; import io.floci.cli.docker.DockerClient; import io.floci.cli.doctor.checks.AwsCliEndpointCheck; import io.floci.cli.doctor.checks.AwsCliS3PathStyleCheck; @@ -29,6 +30,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; @Command( name = "doctor", @@ -50,15 +55,23 @@ public class DoctorCommand implements Callable { /** The base environment checks every product runs, in order: Docker first, then server. */ public static List dockerChecks(ProductProfile profile) { + return dockerChecks(profile, new CachingDockerClient()); + } + + /** + * As above, all asking one {@code docker}: with a {@link CachingDockerClient} the version, + * container and image lookups several checks share run once per doctor run, not once per check. + */ + public static List dockerChecks(ProductProfile profile, DockerClient docker) { return List.of( - new DockerInstalledCheck(), - new DockerDaemonCheck(), + new DockerInstalledCheck(docker), + new DockerDaemonCheck(docker), new DockerSocketCheck(), - new DockerVersionCheck(), - new PortAvailableCheck(), - new ImagePresentCheck(profile.image()), - new ImageVersionCheck(profile.image()), - new ContainerRunningCheck(), + new DockerVersionCheck(docker), + new PortAvailableCheck(docker), + new ImagePresentCheck(profile.image(), docker), + new ImageVersionCheck(profile.image(), docker), + new ContainerRunningCheck(docker), new EndpointReachableCheck(profile.controlPrefix()) ); } @@ -73,21 +86,37 @@ public class DoctorCommand implements Callable { new AzCliConnectionStringCheck() ); + private final DockerClient docker; + private final List allChecks; public DoctorCommand() { this(ProductProfile.AWS, AWS_COMPANION_CHECKS); } - /** Test seam and shim constructor: base docker checks for the profile + product companions. */ + /** Shim constructor: base docker checks for the profile + product companions. */ public DoctorCommand(ProductProfile profile, List companionChecks) { + this(profile, companionChecks, new CachingDockerClient()); + } + + private DoctorCommand(ProductProfile profile, List companionChecks, DockerClient docker) { + this(profile, docker, concat(dockerChecks(profile, docker), companionChecks)); + } + + /** Test seam: exactly these checks, and {@code docker} for the endpoint lookup. */ + public DoctorCommand(ProductProfile profile, DockerClient docker, List checks) { this.profile = profile; this.global = new GlobalOptions(profile); - List checks = new ArrayList<>(dockerChecks(profile)); - checks.addAll(companionChecks); + this.docker = docker; this.allChecks = List.copyOf(checks); } + private static List concat(List first, List second) { + List checks = new ArrayList<>(first); + checks.addAll(second); + return checks; + } + public List allChecks() { return allChecks; } @@ -95,8 +124,15 @@ public class DoctorCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + List selected = selected(); + if (selected.isEmpty()) { + printer.error("Unknown check '" + checkName + "'.\nRun '" + profile.commandPrefix() + + " doctor' to see every check, or pass one of: " + String.join(", ", knownNames()) + "."); + return ExitCode.USAGE; + } + List results = new ArrayList<>(); - String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + String effectiveEndpoint = global.resolvedEndpoint(docker); boolean textMode = printer.format() == OutputFormat.text; @@ -105,11 +141,19 @@ public class DoctorCommand implements Callable { printer.println(""); } - for (Check check : allChecks) { - CheckResult result = check.run(effectiveEndpoint, global.container); - if (checkName != null && !result.name().equals(checkName)) continue; - results.add(result); - if (textMode) printResult(printer, result); + // The checks are independent and mostly wait on docker or the network, so they run + // concurrently; results are still printed in list order as each one becomes available. + try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) { + List> pending = selected.stream() + .map(check -> pool.submit(() -> runSafely(check, effectiveEndpoint, global.container))) + .toList(); + for (int i = 0; i < selected.size(); i++) { + CheckResult result = await(selected.get(i), pending.get(i)); + // A check without a declared name is only known to match once it has run. + if (checkName != null && !result.name().equals(checkName)) continue; + results.add(result); + if (textMode) printResult(printer, result); + } } if (!textMode) { @@ -140,6 +184,45 @@ public class DoctorCommand implements Callable { return fails > 0 ? 1 : 0; } + // --check selects by declared name before anything runs; undeclared names are run and + // filtered by their result, as before. + private List selected() { + if (checkName == null) return allChecks; + return allChecks.stream() + .filter(c -> c.name() == null || c.name().equals(checkName)) + .toList(); + } + + private List knownNames() { + return allChecks.stream().map(Check::name).filter(n -> n != null).toList(); + } + + // One failing check must not abort the run: report it and keep going. + private static CheckResult runSafely(Check check, String endpoint, String container) { + try { + return check.run(endpoint, container); + } catch (RuntimeException e) { + return failed(check, e); + } + } + + private static CheckResult await(Check check, Future result) { + try { + return result.get(); + } catch (ExecutionException e) { + return failed(check, e.getCause()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return failed(check, e); + } + } + + private static CheckResult failed(Check check, Throwable cause) { + String name = check.name() != null ? check.name() : check.getClass().getSimpleName(); + return CheckResult.fail(name, "check failed: " + cause.getMessage(), + "Report it at https://github.com/floci-io/floci-cli/issues if it persists."); + } + public static void printResult(Printer printer, CheckResult r) { String icon = switch (r.status()) { case ok -> Ansi.green("✓"); diff --git a/src/main/java/io/floci/cli/docker/CachingDockerClient.java b/src/main/java/io/floci/cli/docker/CachingDockerClient.java new file mode 100644 index 0000000..49eea00 --- /dev/null +++ b/src/main/java/io/floci/cli/docker/CachingDockerClient.java @@ -0,0 +1,85 @@ +package io.floci.cli.docker; + +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A {@link DockerClient} that answers each read-only query once per instance: the first caller + * runs the docker subprocess and every later or concurrent caller gets the same answer (or the + * same failure). Meant for one diagnostic run, where several checks ask the same questions; never + * hold one across a command that changes container or image state. + */ +public class CachingDockerClient extends DockerClient { + + private final DockerClient delegate; + + private final ConcurrentHashMap> memos = new ConcurrentHashMap<>(); + + public CachingDockerClient() { + this(new DockerClient()); + } + + /** {@code delegate} answers the first call for each query; a test seam for counting. */ + public CachingDockerClient(DockerClient delegate) { + this.delegate = delegate; + } + + @Override + public String dockerVersion() throws DockerException { + return memo("version", delegate::dockerVersion); + } + + @Override + public boolean isDaemonReachable() { + try { + return memo("daemon", delegate::isDaemonReachable); + } catch (DockerException e) { + return false; + } + } + + @Override + public Optional inspectContainer(String name) throws DockerException { + return memo("container:" + name, () -> delegate.inspectContainer(name)); + } + + @Override + public boolean isImagePresent(String image) throws DockerException { + return memo("image:" + image, () -> delegate.isImagePresent(image)); + } + + @Override + public Optional imageLabel(String image, String key) throws DockerException { + return memo("label:" + image + ":" + key, () -> delegate.imageLabel(image, key)); + } + + @SuppressWarnings("unchecked") + private T memo(String key, DockerCall call) throws DockerException { + return ((Memo) memos.computeIfAbsent(key, k -> new Memo<>())).get(call); + } + + @FunctionalInterface + private interface DockerCall { + T call() throws DockerException; + } + + // One answer per key, computed by the first caller while concurrent callers wait on the lock. + private static final class Memo { + private boolean done; + private T value; + private DockerException failure; + + synchronized T get(DockerCall call) throws DockerException { + if (!done) { + try { + value = call.call(); + } catch (DockerException e) { + failure = e; + } + done = true; + } + if (failure != null) throw failure; + return value; + } + } +} diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index 572557a..3899c6c 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -85,6 +85,18 @@ public class DockerClient { } } + /** The value of label {@code key} on a local image, empty when the label or image is missing. */ + public Optional imageLabel(String image, String key) throws DockerException { + try { + String out = run("docker", "inspect", "--format", + "{{index .Config.Labels \"" + key + "\"}}", image); + String value = out.trim(); + return value.isEmpty() || "".equals(value) ? Optional.empty() : Optional.of(value); + } catch (DockerException e) { + return Optional.empty(); + } + } + public void pull(String image, String policy) throws DockerException { if ("never".equalsIgnoreCase(policy)) return; if ("missing".equalsIgnoreCase(policy) && isImagePresent(image)) return; diff --git a/src/main/java/io/floci/cli/doctor/Check.java b/src/main/java/io/floci/cli/doctor/Check.java index e0a9f5b..891bf39 100644 --- a/src/main/java/io/floci/cli/doctor/Check.java +++ b/src/main/java/io/floci/cli/doctor/Check.java @@ -3,4 +3,13 @@ package io.floci.cli.doctor; @FunctionalInterface public interface Check { CheckResult run(String endpoint, String container); + + /** + * The name this check reports under ({@code docker.installed}, ...), so {@code doctor --check} + * can select it without running every other check first. {@code null} means unknown until + * the check has run. + */ + default String name() { + return null; + } } diff --git a/src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java b/src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java index ecb4436..8e71bf5 100644 --- a/src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java @@ -9,6 +9,11 @@ import java.net.URISyntaxException; public class AwsCliEndpointCheck implements Check { + @Override + public String name() { + return "aws.cli.endpoint"; + } + @Override public CheckResult run(String endpoint, String container) { if (!isAwsCliInstalled()) { diff --git a/src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java b/src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java index 25d69e6..256fd03 100644 --- a/src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java @@ -9,6 +9,11 @@ import java.nio.file.Path; public class AwsCliS3PathStyleCheck implements Check { + @Override + public String name() { + return "aws.cli.s3.pathstyle"; + } + @Override public CheckResult run(String endpoint, String container) { Path awsConfig = Path.of(System.getProperty("user.home"), ".aws", "config"); diff --git a/src/main/java/io/floci/cli/doctor/checks/AzCliConnectionStringCheck.java b/src/main/java/io/floci/cli/doctor/checks/AzCliConnectionStringCheck.java index 782a7f0..40176cf 100644 --- a/src/main/java/io/floci/cli/doctor/checks/AzCliConnectionStringCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/AzCliConnectionStringCheck.java @@ -10,6 +10,11 @@ import java.util.regex.Pattern; public class AzCliConnectionStringCheck implements Check { + @Override + public String name() { + return "az.cli.connection-string"; + } + private static final Pattern ENDPOINT_PORT_PATTERN = Pattern.compile("BlobEndpoint=https?://[^:]+:(\\d+)/", Pattern.CASE_INSENSITIVE); diff --git a/src/main/java/io/floci/cli/doctor/checks/AzCliInstalledCheck.java b/src/main/java/io/floci/cli/doctor/checks/AzCliInstalledCheck.java index 8f417ff..1e3e1b5 100644 --- a/src/main/java/io/floci/cli/doctor/checks/AzCliInstalledCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/AzCliInstalledCheck.java @@ -5,6 +5,11 @@ import io.floci.cli.doctor.CheckResult; public class AzCliInstalledCheck implements Check { + @Override + public String name() { + return "az.cli.installed"; + } + @Override public CheckResult run(String endpoint, String container) { try { diff --git a/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java b/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java index 36dde6e..c306fdd 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java @@ -7,10 +7,26 @@ import io.floci.cli.doctor.CheckResult; public class ContainerRunningCheck implements Check { + private final DockerClient docker; + + public ContainerRunningCheck() { + this(new DockerClient()); + } + + /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ + public ContainerRunningCheck(DockerClient docker) { + this.docker = docker; + } + + @Override + public String name() { + return "container.running"; + } + @Override public CheckResult run(String endpoint, String container) { try { - var info = new DockerClient().inspectContainer(container); + var info = docker.inspectContainer(container); if (info.isEmpty()) { return CheckResult.warn("container.running", "Container '" + container + "' not found", diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java index bd6a1c8..a09ebd6 100644 --- a/src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java @@ -6,9 +6,24 @@ import io.floci.cli.doctor.CheckResult; public class DockerDaemonCheck implements Check { + private final DockerClient docker; + + public DockerDaemonCheck() { + this(new DockerClient()); + } + + /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ + public DockerDaemonCheck(DockerClient docker) { + this.docker = docker; + } + + @Override + public String name() { + return "docker.daemon"; + } + @Override public CheckResult run(String endpoint, String container) { - DockerClient docker = new DockerClient(); if (docker.isDaemonReachable()) { return CheckResult.ok("docker.daemon", "Daemon reachable"); } diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java index 5278cf3..22fddc0 100644 --- a/src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java @@ -6,17 +6,35 @@ import io.floci.cli.doctor.CheckResult; public class DockerInstalledCheck implements Check { + private final DockerClient docker; + + public DockerInstalledCheck() { + this(new DockerClient()); + } + + /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ + public DockerInstalledCheck(DockerClient docker) { + this.docker = docker; + } + + @Override + public String name() { + return "docker.installed"; + } + @Override public CheckResult run(String endpoint, String container) { - if (!DockerClient.isInstalled()) { - return CheckResult.fail("docker.installed", - "docker binary not found in PATH", - "Install Docker Desktop from https://docs.docker.com/get-docker/"); - } + // The version query is shared with docker.version; only when it fails is a separate + // probe needed to tell "not installed" from "installed, daemon down". try { - String version = new DockerClient().dockerVersion(); + String version = docker.dockerVersion(); return CheckResult.ok("docker.installed", "Docker " + version + " detected"); } catch (Exception e) { + if (!DockerClient.isInstalled()) { + return CheckResult.fail("docker.installed", + "docker binary not found in PATH", + "Install Docker Desktop from https://docs.docker.com/get-docker/"); + } return CheckResult.ok("docker.installed", "Docker detected"); } } diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java index a60f8f4..a4620f0 100644 --- a/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java @@ -9,6 +9,11 @@ import java.nio.file.Path; public class DockerSocketCheck implements Check { + @Override + public String name() { + return "docker.socket"; + } + @Override public CheckResult run(String endpoint, String container) { DockerClient.DockerHost host = DockerClient.dockerHost(); diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java index dc081a3..573ddb1 100644 --- a/src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java @@ -7,13 +7,29 @@ import io.floci.cli.doctor.CheckResult; public class DockerVersionCheck implements Check { + private final DockerClient docker; + + public DockerVersionCheck() { + this(new DockerClient()); + } + + /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ + public DockerVersionCheck(DockerClient docker) { + this.docker = docker; + } + + @Override + public String name() { + return "docker.version"; + } + private static final int MIN_MAJOR = 20; private static final int MIN_MINOR = 10; @Override public CheckResult run(String endpoint, String container) { try { - String raw = new DockerClient().dockerVersion(); + String raw = docker.dockerVersion(); if (meetsMinimum(raw)) { return CheckResult.ok("docker.version", "Docker " + raw + " (>= 20.10)"); } diff --git a/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java b/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java index 3b865ac..dcf22c6 100644 --- a/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java @@ -4,8 +4,15 @@ import io.floci.cli.doctor.Check; import io.floci.cli.doctor.CheckResult; import io.floci.cli.http.FlociHttpClient; +import java.time.Duration; + public class EndpointReachableCheck implements Check { + @Override + public String name() { + return "endpoint.reachable"; + } + private final String controlPrefix; public EndpointReachableCheck() { @@ -19,12 +26,14 @@ public class EndpointReachableCheck implements Check { @Override public CheckResult run(String endpoint, String container) { FlociHttpClient client = new FlociHttpClient(endpoint, controlPrefix); - if (client.isReachable()) { - try { - var health = client.health(); - return CheckResult.ok("endpoint.reachable", - endpoint + " is reachable (server v" + health.version() + ")"); - } catch (Exception e) { + try { + var health = client.health(Duration.ofSeconds(3)); + return CheckResult.ok("endpoint.reachable", + endpoint + " is reachable (server v" + health.version() + ")"); + } catch (Exception e) { + // The health body could not be read as JSON, or the request failed. Only then ask the + // cheaper status-only question, so a reachable server with an odd body still passes. + if (client.isReachable()) { return CheckResult.ok("endpoint.reachable", endpoint + " is reachable"); } } diff --git a/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java index 868f6ad..d9f66a3 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java @@ -7,20 +7,31 @@ import io.floci.cli.doctor.CheckResult; public class ImagePresentCheck implements Check { + @Override + public String name() { + return "image.present"; + } + private final String image; + private final DockerClient docker; public ImagePresentCheck() { this("floci/floci"); } public ImagePresentCheck(String image) { + this(image, new DockerClient()); + } + + /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ + public ImagePresentCheck(String image, DockerClient docker) { this.image = image; + this.docker = docker; } @Override public CheckResult run(String endpoint, String container) { try { - DockerClient docker = new DockerClient(); if (docker.isImagePresent(image)) { return CheckResult.ok("image.present", image + " image present locally"); } diff --git a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java index a4bbdb1..003f557 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java @@ -7,7 +7,13 @@ import io.floci.cli.doctor.CheckResult; public class ImageVersionCheck implements Check { + @Override + public String name() { + return "image.version"; + } + private final String image; + private final DockerClient docker; private static final String MIN_VERSION = "1.5.0"; public ImageVersionCheck() { @@ -15,13 +21,18 @@ public class ImageVersionCheck implements Check { } public ImageVersionCheck(String image) { + this(image, new DockerClient()); + } + + /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ + public ImageVersionCheck(String image, DockerClient docker) { this.image = image; + this.docker = docker; } @Override public CheckResult run(String endpoint, String container) { try { - DockerClient docker = new DockerClient(); if (!docker.isImagePresent(image)) { return CheckResult.warn("image.version", image + " not present — version cannot be checked", "floci start --pull always"); @@ -42,21 +53,8 @@ public class ImageVersionCheck implements Check { } } - private String readImageLabel(DockerClient docker, String image) { - try { - String raw = runDockerInspect(image); - return raw.isBlank() ? null : raw.trim(); - } catch (Exception e) { - return null; - } - } - - private String runDockerInspect(String image) throws Exception { - Process p = new ProcessBuilder("docker", "inspect", "--format", - "{{index .Config.Labels \"org.opencontainers.image.version\"}}", image).start(); - String out = new String(p.getInputStream().readAllBytes()).trim(); - p.waitFor(); - return out; + private String readImageLabel(DockerClient docker, String image) throws DockerException { + return docker.imageLabel(image, "org.opencontainers.image.version").orElse(null); } public static boolean meetsMinimum(String version, String minimum) { diff --git a/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java index 3f3b5d5..545ac1c 100644 --- a/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java @@ -11,11 +11,26 @@ import java.net.URI; public class PortAvailableCheck implements Check { + private final DockerClient docker; + + public PortAvailableCheck() { + this(new DockerClient()); + } + + /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ + public PortAvailableCheck(DockerClient docker) { + this.docker = docker; + } + + @Override + public String name() { + return "port.available"; + } + @Override public CheckResult run(String endpoint, String container) { int port = extractPort(endpoint); // If a Floci container is already listening on the port, that's fine - DockerClient docker = new DockerClient(); try { var info = docker.inspectContainer(container); if (info.isPresent() && "running".equals(info.get().state())) { diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index bacccc2..ec33fb7 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -43,7 +43,12 @@ public class FlociHttpClient { } public HealthInfo health() throws FlociException { - JsonNode node = getJson(controlPrefix + "/health"); + return health(Duration.ofSeconds(10)); + } + + /** {@link #health()} with its own request timeout, for probes that must answer quickly. */ + public HealthInfo health(Duration timeout) throws FlociException { + JsonNode node = getJson(controlPrefix + "/health", timeout); return new HealthInfo( node.path("version").asText("unknown"), node.path("original_edition").asText(node.path("edition").asText("community")), @@ -120,10 +125,14 @@ public class FlociHttpClient { } private JsonNode getJson(String path) throws FlociException { + return getJson(path, Duration.ofSeconds(10)); + } + + private JsonNode getJson(String path, Duration timeout) throws FlociException { try { HttpRequest req = HttpRequest.newBuilder() .uri(URI.create(endpoint + path)) - .timeout(Duration.ofSeconds(10)) + .timeout(timeout) .header("Accept", "application/json") .GET() .build(); diff --git a/src/test/java/io/floci/cli/unit/DoctorCommandTest.java b/src/test/java/io/floci/cli/unit/DoctorCommandTest.java new file mode 100644 index 0000000..041abcf --- /dev/null +++ b/src/test/java/io/floci/cli/unit/DoctorCommandTest.java @@ -0,0 +1,195 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.DoctorCommand; +import io.floci.cli.docker.CachingDockerClient; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; +import org.junit.jupiter.api.Test; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-028: doctor selects before running, survives a crashing check, and keeps its output order. */ +class DoctorCommandTest { + + /** No docker subprocess: the endpoint lookup sees no container. */ + private static final DockerClient NO_DOCKER = new DockerClient() { + @Override + public Optional inspectContainer(String name) { + return Optional.empty(); + } + }; + + private record Named(String name, AtomicInteger runs, Check body) implements Check { + Named(String name, Check body) { + this(name, new AtomicInteger(), body); + } + + @Override + public CheckResult run(String endpoint, String container) { + runs.incrementAndGet(); + return body.run(endpoint, container); + } + } + + private static Named ok(String name) { + return new Named(name, (e, c) -> CheckResult.ok(name, "fine")); + } + + private record Run(int exit, String out, String err) {} + + private static Run doctor(List checks, String... args) { + CommandLine cmd = new CommandLine(new DoctorCommand(ProductProfile.AWS, NO_DOCKER, checks)); + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + try { + return new Run(cmd.execute(args), outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void checkOptionRunsOnlyTheNamedCheck() { + Named a = ok("a.check"); + Named b = ok("b.check"); + + Run r = doctor(List.of(a, b), "--check", "b.check"); + + assertEquals(0, r.exit(), r.err()); + assertEquals(0, a.runs().get()); + assertEquals(1, b.runs().get()); + assertTrue(r.out().contains("b.check"), r.out()); + assertFalse(r.out().contains("a.check"), r.out()); + } + + @Test + void anUnknownCheckNameExitsTwoAndListsTheNames() { + Run r = doctor(List.of(ok("a.check"), ok("b.check")), "--check", "nope"); + + assertEquals(2, r.exit()); + assertTrue(r.err().contains("Unknown check 'nope'"), r.err()); + assertTrue(r.err().contains("a.check, b.check"), r.err()); + } + + @Test + void aCrashingCheckIsReportedAndTheOthersStillRun() { + Named boom = new Named("boom.check", (e, c) -> { throw new IllegalStateException("kaput"); }); + Named after = ok("after.check"); + + Run r = doctor(List.of(boom, after), "-o", "json"); + + assertEquals(1, after.runs().get()); + assertTrue(r.out().contains("\"boom.check\""), r.out()); + assertTrue(r.out().contains("check failed: kaput"), r.out()); + assertTrue(r.out().contains("\"after.check\""), r.out()); + } + + @Test + void resultsKeepListOrderEvenWhenLaterChecksFinishFirst() { + CountDownLatch secondDone = new CountDownLatch(1); + Named slow = new Named("first.check", (e, c) -> { + try { + // Finishes only after the second check has completed. + assertTrue(secondDone.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + return CheckResult.ok("first.check", "slow"); + }); + Named fast = new Named("second.check", (e, c) -> { + secondDone.countDown(); + return CheckResult.ok("second.check", "fast"); + }); + + Run r = doctor(List.of(slow, fast)); + + // Both checks must have succeeded: a timed-out latch would surface as "check failed". + assertEquals(0, r.exit(), r.out() + r.err()); + assertFalse(r.out().contains("check failed"), r.out()); + assertTrue(r.out().indexOf("first.check") < r.out().indexOf("second.check"), r.out()); + } + + @Test + void theCachingClientRunsEachLookupOnceAcrossThreads() throws Exception { + AtomicInteger versionCalls = new AtomicInteger(); + AtomicInteger inspectCalls = new AtomicInteger(); + // Counts what reaches the delegate, i.e. what would spawn a docker subprocess. + DockerClient counting = new DockerClient() { + @Override + public String dockerVersion() { + versionCalls.incrementAndGet(); + sleepBriefly(); + return "27.0.0"; + } + + @Override + public Optional inspectContainer(String name) { + inspectCalls.incrementAndGet(); + sleepBriefly(); + return Optional.empty(); + } + }; + CachingDockerClient cache = new CachingDockerClient(counting); + + // Futures, not bare threads: an assertion failing on a worker must fail this test. + try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) { + List> workers = new ArrayList<>(); + for (int i = 0; i < 8; i++) { + workers.add(pool.submit(() -> { + assertEquals("27.0.0", cache.dockerVersion()); + assertTrue(cache.inspectContainer("floci").isEmpty()); + return null; + })); + } + for (Future worker : workers) worker.get(); + } + + assertEquals(1, versionCalls.get()); + assertEquals(1, inspectCalls.get()); + } + + @Test + void theCachingClientRemembersFailuresToo() { + AtomicInteger calls = new AtomicInteger(); + CachingDockerClient cache = new CachingDockerClient(new DockerClient() { + @Override + public String dockerVersion() throws DockerException { + calls.incrementAndGet(); + throw new DockerException("daemon down"); + } + }); + + assertThrows(DockerException.class, cache::dockerVersion); + assertThrows(DockerException.class, cache::dockerVersion); + assertEquals(1, calls.get()); + } + + private static void sleepBriefly() { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/src/test/java/io/floci/cli/unit/EndpointReachableCheckTest.java b/src/test/java/io/floci/cli/unit/EndpointReachableCheckTest.java new file mode 100644 index 0000000..57cd5a1 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/EndpointReachableCheckTest.java @@ -0,0 +1,56 @@ +package io.floci.cli.unit; + +import com.sun.net.httpserver.HttpServer; +import io.floci.cli.doctor.CheckResult; +import io.floci.cli.doctor.CheckStatus; +import io.floci.cli.doctor.checks.EndpointReachableCheck; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.*; + +class EndpointReachableCheckTest { + + private static CheckResult checkAgainst(int status, String body) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/_floci/health", exchange -> { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + server.start(); + try { + return new EndpointReachableCheck("/_floci") + .run("http://127.0.0.1:" + server.getAddress().getPort(), "floci"); + } finally { + server.stop(0); + } + } + + @Test + void reportsTheServerVersionFromItsHealthDocument() throws Exception { + CheckResult r = checkAgainst(200, "{\"version\":\"9.9.9\",\"services\":[]}"); + + assertEquals(CheckStatus.ok, r.status()); + assertTrue(r.message().contains("v9.9.9"), r.message()); + } + + /** A 200 with a body that is not JSON is still a reachable server. */ + @Test + void aReachableServerWithAnUnreadableBodyStillPasses() throws Exception { + CheckResult r = checkAgainst(200, "OK"); + + assertEquals(CheckStatus.ok, r.status(), r.message()); + } + + @Test + void anErrorStatusFails() throws Exception { + assertEquals(CheckStatus.fail, checkAgainst(503, "down").status()); + } +}