fix(doctor): fail -o json on a failed check and name each product in its hints (#52)

* fix(doctor): fail -o json on a failed check and name each product in its hints

doctor -o json now exits 1 when a check fails, as text output does; hints and HTTP errors name the product's own command (floci gcp start, ...) and the port check falls back to the product's default port; a warnings-only run no longer reads as '0 issue(s) found'; an https AWS_ENDPOINT_URL without a port means 443.

* fix(http): name the product's status command when a request times out

Both ways a request can time out now give the same message with the product's own command. The hint tests use their own local endpoints instead of port 9.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 18:45:05 -05:00
1 parent 4cd39a957a
commit 771b353733
20 files changed
+266 -35

No files matched your search

@@ -68,11 +68,11 @@ public class DoctorCommand implements Callable<Integer> {
new DockerDaemonCheck(docker), new DockerDaemonCheck(docker),
new DockerSocketCheck(), new DockerSocketCheck(),
new DockerVersionCheck(docker), new DockerVersionCheck(docker),
new PortAvailableCheck(docker), new PortAvailableCheck(docker, profile),
new ImagePresentCheck(profile.image(), docker), new ImagePresentCheck(profile, docker),
new ImageVersionCheck(profile.image(), docker), new ImageVersionCheck(profile, docker),
new ContainerRunningCheck(docker), new ContainerRunningCheck(docker, profile),
new EndpointReachableCheck(profile.controlPrefix()) new EndpointReachableCheck(profile)
); );
} }
@@ -167,7 +167,8 @@ public class DoctorCommand implements Callable<Integer> {
structured.add(m); structured.add(m);
} }
printer.structured(structured); printer.structured(structured);
return 0; // Same contract as text output: scripts read the exit code, whatever the format.
return results.stream().anyMatch(r -> r.status() == CheckStatus.fail) ? 1 : 0;
} }
long fails = results.stream().filter(r -> r.status() == CheckStatus.fail).count(); long fails = results.stream().filter(r -> r.status() == CheckStatus.fail).count();
@@ -176,6 +177,9 @@ public class DoctorCommand implements Callable<Integer> {
printer.println(""); printer.println("");
if (fails == 0 && warns == 0) { if (fails == 0 && warns == 0) {
printer.println(Ansi.green("All checks passed.")); printer.println(Ansi.green("All checks passed."));
} else if (fails == 0) {
// Nothing failed: say so, rather than "0 issue(s) found" next to the warnings.
printer.println(Ansi.green("No failures") + ", " + warns + " warning(s) to review.");
} else { } else {
printer.println(fails + " issue(s) found (" + fails + " fail, " + warns + " warn)." printer.println(fails + " issue(s) found (" + fails + " fail, " + warns + " warn)."
+ (fix ? "" : " Run with --fix to auto-resolve fixable issues.")); + (fix ? "" : " Run with --fix to auto-resolve fixable issues."));
@@ -44,7 +44,7 @@ public class ServicesCommand implements Callable<Integer> {
// Resolve the endpoint from the container's port mapping, like status/wait/env do, // Resolve the endpoint from the container's port mapping, like status/wait/env do,
// so a container started with --port <n> is still found without --endpoint. // so a container started with --port <n> is still found without --endpoint.
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
List<String> services; List<String> services;
try { try {
@@ -62,7 +62,7 @@ public class StatusCommand implements Callable<Integer> {
String serverVersion = "unavailable"; String serverVersion = "unavailable";
String serverEdition = ""; String serverEdition = "";
boolean reachable = false; boolean reachable = false;
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try { try {
var health = client.health(); var health = client.health();
serverVersion = health.version(); serverVersion = health.version();
@@ -46,7 +46,7 @@ public class VersionCommand implements Callable<Integer> {
var docker = new io.floci.cli.docker.DockerClient(); var docker = new io.floci.cli.docker.DockerClient();
String effectiveEndpoint = global.resolvedEndpoint(docker); String effectiveEndpoint = global.resolvedEndpoint(docker);
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try { try {
var info = client.info(); var info = client.info();
serverVersion = info.version(); serverVersion = info.version();
@@ -90,7 +90,7 @@ public class WaitCommand implements Callable<Integer> {
// The deadline starts now, so the container lookup below counts against --timeout too. // The deadline starts now, so the container lookup below counts against --timeout too.
Instant deadline = Instant.now().plusMillis(timeoutMillis); Instant deadline = Instant.now().plusMillis(timeoutMillis);
String effectiveEndpoint = knownEndpoint != null ? knownEndpoint : endpointWithin(deadline); String effectiveEndpoint = knownEndpoint != null ? knownEndpoint : endpointWithin(deadline);
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
// Poll soon after a start, then back off; never let a request or a pause run past the // 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. // deadline, so --timeout is a real upper bound.
@@ -73,7 +73,7 @@ public class AzEnvCommand implements Callable<Integer> {
public AzEnvCommand() { public AzEnvCommand() {
this(InstanceState.defaultRoot(), this(InstanceState.defaultRoot(),
endpoint -> new FlociHttpClient(endpoint, ProductProfile.AZ.controlPrefix()).tlsCert()); endpoint -> new FlociHttpClient(endpoint, ProductProfile.AZ).tlsCert());
} }
/** /**
@@ -96,7 +96,7 @@ public class AzSetupCommand implements Callable<Integer> {
public AzSetupCommand() { public AzSetupCommand() {
this(InstanceState.defaultRoot(), new ProcessAzCli(), this(InstanceState.defaultRoot(), new ProcessAzCli(),
endpoint -> new FlociHttpClient(endpoint, ProductProfile.AZ.controlPrefix()).tlsCert(), endpoint -> new FlociHttpClient(endpoint, ProductProfile.AZ).tlsCert(),
new DockerClient(), Duration.ofSeconds(2)); new DockerClient(), Duration.ofSeconds(2));
} }
@@ -41,7 +41,7 @@ public class SnapshotDeleteCommand implements Callable<Integer> {
// Resolve the endpoint from the container's port mapping, like status/services/wait do, // Resolve the endpoint from the container's port mapping, like status/services/wait do,
// so a container started with --port <n> is still found without --endpoint. // so a container started with --port <n> is still found without --endpoint.
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try { try {
client.deleteSnapshot(name); client.deleteSnapshot(name);
printer.println(Ansi.green("Snapshot deleted:") + " " + name); printer.println(Ansi.green("Snapshot deleted:") + " " + name);
@@ -39,7 +39,7 @@ public class SnapshotListCommand implements Callable<Integer> {
// Resolve the endpoint from the container's port mapping, like status/services/wait do, // Resolve the endpoint from the container's port mapping, like status/services/wait do,
// so a container started with --port <n> is still found without --endpoint. // so a container started with --port <n> is still found without --endpoint.
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try { try {
var node = client.listSnapshots(); var node = client.listSnapshots();
if (printer.format() != OutputFormat.text) { if (printer.format() != OutputFormat.text) {
@@ -41,7 +41,7 @@ public class SnapshotLoadCommand implements Callable<Integer> {
// Resolve the endpoint from the container's port mapping, like status/services/wait do, // Resolve the endpoint from the container's port mapping, like status/services/wait do,
// so a container started with --port <n> is still found without --endpoint. // so a container started with --port <n> is still found without --endpoint.
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try { try {
client.loadSnapshot(name); client.loadSnapshot(name);
printer.println(Ansi.green("Snapshot loaded:") + " " + name); printer.println(Ansi.green("Snapshot loaded:") + " " + name);
@@ -44,7 +44,7 @@ public class SnapshotSaveCommand implements Callable<Integer> {
// Resolve the endpoint from the container's port mapping, like status/services/wait do, // Resolve the endpoint from the container's port mapping, like status/services/wait do,
// so a container started with --port <n> is still found without --endpoint. // so a container started with --port <n> is still found without --endpoint.
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile.controlPrefix()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try { try {
client.postSnapshot(name); client.postSnapshot(name);
printer.println(Ansi.green("Snapshot saved:") + " " + name); printer.println(Ansi.green("Snapshot saved:") + " " + name);
@@ -37,10 +37,13 @@ public class AwsCliEndpointCheck implements Check {
ShellExport.formatExport("bash", "AWS_ENDPOINT_URL", suggested)); ShellExport.formatExport("bash", "AWS_ENDPOINT_URL", suggested));
} }
private int extractPort(String url) { /** The URL's port, or the scheme default (443 for https, 80 otherwise); -1 if unparseable. */
public static int extractPort(String url) {
try { try {
int port = URI.create(url).getPort(); URI uri = URI.create(url);
return port == -1 ? 80 : port; int port = uri.getPort();
if (port != -1) return port;
return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80;
} catch (Exception e) { } catch (Exception e) {
return -1; return -1;
} }
@@ -1,5 +1,6 @@
package io.floci.cli.doctor.checks; package io.floci.cli.doctor.checks;
import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException; import io.floci.cli.docker.DockerException;
import io.floci.cli.doctor.Check; import io.floci.cli.doctor.Check;
@@ -15,9 +16,19 @@ public class ContainerRunningCheck implements Check {
/** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */
public ContainerRunningCheck(DockerClient docker) { public ContainerRunningCheck(DockerClient docker) {
this.docker = docker; this(docker, ProductProfile.AWS);
} }
/** Hints name {@code product}'s tree ({@code floci gcp start}, ...). */
public ContainerRunningCheck(DockerClient docker, ProductProfile product) {
this.docker = docker;
this.start = product.commandPrefix() + " start";
this.stop = product.commandPrefix() + " stop";
}
private final String start;
private final String stop;
@Override @Override
public String name() { public String name() {
return "container.running"; return "container.running";
@@ -30,7 +41,7 @@ public class ContainerRunningCheck implements Check {
if (info.isEmpty()) { if (info.isEmpty()) {
return CheckResult.warn("container.running", return CheckResult.warn("container.running",
"Container '" + container + "' not found", "Container '" + container + "' not found",
"floci start"); start);
} }
String state = info.get().state(); String state = info.get().state();
if ("running".equals(state)) { if ("running".equals(state)) {
@@ -38,7 +49,7 @@ public class ContainerRunningCheck implements Check {
} }
return CheckResult.fail("container.running", return CheckResult.fail("container.running",
"Container '" + container + "' exists but state is '" + state + "'", "Container '" + container + "' exists but state is '" + state + "'",
"floci start (or 'floci stop && floci start' to restart)"); start + " (or '" + stop + " && " + start + "' to restart)");
} catch (DockerException e) { } catch (DockerException e) {
return CheckResult.warn("container.running", "Could not inspect container: " + e.getMessage(), null); return CheckResult.warn("container.running", "Could not inspect container: " + e.getMessage(), null);
} }
@@ -1,5 +1,6 @@
package io.floci.cli.doctor.checks; package io.floci.cli.doctor.checks;
import io.floci.cli.ProductProfile;
import io.floci.cli.doctor.Check; import io.floci.cli.doctor.Check;
import io.floci.cli.doctor.CheckResult; import io.floci.cli.doctor.CheckResult;
import io.floci.cli.http.FlociHttpClient; import io.floci.cli.http.FlociHttpClient;
@@ -14,13 +15,24 @@ public class EndpointReachableCheck implements Check {
} }
private final String controlPrefix; private final String controlPrefix;
private final String commandPrefix;
public EndpointReachableCheck() { public EndpointReachableCheck() {
this(FlociHttpClient.DEFAULT_CONTROL_PREFIX); this(FlociHttpClient.DEFAULT_CONTROL_PREFIX);
} }
public EndpointReachableCheck(String controlPrefix) { public EndpointReachableCheck(String controlPrefix) {
this(controlPrefix, "floci");
}
/** {@code product}'s health endpoint, with a hint that names its tree. */
public EndpointReachableCheck(ProductProfile product) {
this(product.controlPrefix(), product.commandPrefix());
}
private EndpointReachableCheck(String controlPrefix, String commandPrefix) {
this.controlPrefix = controlPrefix; this.controlPrefix = controlPrefix;
this.commandPrefix = commandPrefix;
} }
@Override @Override
@@ -39,6 +51,6 @@ public class EndpointReachableCheck implements Check {
} }
return CheckResult.fail("endpoint.reachable", return CheckResult.fail("endpoint.reachable",
"GET " + controlPrefix + "/health at " + endpoint + " did not return 200", "GET " + controlPrefix + "/health at " + endpoint + " did not return 200",
"Is Floci running? Try 'floci start'."); "Is Floci running? Try '" + commandPrefix + " start'.");
} }
} }
@@ -1,5 +1,6 @@
package io.floci.cli.doctor.checks; package io.floci.cli.doctor.checks;
import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException; import io.floci.cli.docker.DockerException;
import io.floci.cli.doctor.Check; import io.floci.cli.doctor.Check;
@@ -25,10 +26,22 @@ public class ImagePresentCheck implements Check {
/** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */
public ImagePresentCheck(String image, DockerClient docker) { public ImagePresentCheck(String image, DockerClient docker) {
this(image, docker, "floci");
}
/** {@code product}'s image, with hints that name its tree. */
public ImagePresentCheck(ProductProfile product, DockerClient docker) {
this(product.image(), docker, product.commandPrefix());
}
private ImagePresentCheck(String image, DockerClient docker, String commandPrefix) {
this.image = image; this.image = image;
this.docker = docker; this.docker = docker;
this.pullHint = commandPrefix + " start --pull always";
} }
private final String pullHint;
@Override @Override
public CheckResult run(String endpoint, String container) { public CheckResult run(String endpoint, String container) {
try { try {
@@ -37,7 +50,7 @@ public class ImagePresentCheck implements Check {
} }
return CheckResult.fail("image.present", return CheckResult.fail("image.present",
image + " not pulled locally", image + " not pulled locally",
"floci start --pull always"); pullHint);
} catch (DockerException e) { } catch (DockerException e) {
return CheckResult.warn("image.present", "Could not check image presence: " + e.getMessage(), null); return CheckResult.warn("image.present", "Could not check image presence: " + e.getMessage(), null);
} }
@@ -1,5 +1,6 @@
package io.floci.cli.doctor.checks; package io.floci.cli.doctor.checks;
import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException; import io.floci.cli.docker.DockerException;
import io.floci.cli.doctor.Check; import io.floci.cli.doctor.Check;
@@ -26,16 +27,28 @@ public class ImageVersionCheck implements Check {
/** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */
public ImageVersionCheck(String image, DockerClient docker) { public ImageVersionCheck(String image, DockerClient docker) {
this(image, docker, "floci");
}
/** {@code product}'s image, with hints that name its tree. */
public ImageVersionCheck(ProductProfile product, DockerClient docker) {
this(product.image(), docker, product.commandPrefix());
}
private ImageVersionCheck(String image, DockerClient docker, String commandPrefix) {
this.image = image; this.image = image;
this.docker = docker; this.docker = docker;
this.pullHint = commandPrefix + " start --pull always";
} }
private final String pullHint;
@Override @Override
public CheckResult run(String endpoint, String container) { public CheckResult run(String endpoint, String container) {
try { try {
if (!docker.isImagePresent(image)) { if (!docker.isImagePresent(image)) {
return CheckResult.warn("image.version", image + " not present — version cannot be checked", return CheckResult.warn("image.version", image + " not present — version cannot be checked",
"floci start --pull always"); pullHint);
} }
// Try reading version label from the image // Try reading version label from the image
String version = readImageLabel(docker, image); String version = readImageLabel(docker, image);
@@ -1,5 +1,6 @@
package io.floci.cli.doctor.checks; package io.floci.cli.doctor.checks;
import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException; import io.floci.cli.docker.DockerException;
import io.floci.cli.doctor.Check; import io.floci.cli.doctor.Check;
@@ -24,9 +25,19 @@ public class PortAvailableCheck implements Check {
/** {@code docker} is shared across one doctor run so each docker fact is fetched once. */ /** {@code docker} is shared across one doctor run so each docker fact is fetched once. */
public PortAvailableCheck(DockerClient docker) { public PortAvailableCheck(DockerClient docker) {
this.docker = docker; this(docker, ProductProfile.AWS);
} }
/** Falls back to {@code product}'s default port and names its tree in the hint. */
public PortAvailableCheck(DockerClient docker, ProductProfile product) {
this.docker = docker;
this.defaultPort = product.defaultPort();
this.startCommand = product.commandPrefix() + " start";
}
private final int defaultPort;
private final String startCommand;
@Override @Override
public String name() { public String name() {
return "port.available"; return "port.available";
@@ -34,7 +45,7 @@ public class PortAvailableCheck implements Check {
@Override @Override
public CheckResult run(String endpoint, String container) { public CheckResult run(String endpoint, String container) {
int port = extractPort(endpoint); int port = extractPort(endpoint, defaultPort);
// If a Floci container is already listening on the port, that's fine // If a Floci container is already listening on the port, that's fine
try { try {
var info = docker.inspectContainer(container); var info = docker.inspectContainer(container);
@@ -48,7 +59,7 @@ public class PortAvailableCheck implements Check {
} }
return CheckResult.fail("port.available", return CheckResult.fail("port.available",
"Port " + port + " is occupied by another process", "Port " + port + " is occupied by another process",
"Run 'lsof -i :" + port + "' to identify the process, or start Floci with --port <other>"); "Run 'lsof -i :" + port + "' to identify the process, or '" + startCommand + " --port <other>'.");
} }
/** /**
@@ -89,11 +100,16 @@ public class PortAvailableCheck implements Check {
} }
public static int extractPort(String endpoint) { public static int extractPort(String endpoint) {
return extractPort(endpoint, ProductProfile.AWS.defaultPort());
}
/** The endpoint's port, or {@code fallback} when it names none or cannot be parsed. */
public static int extractPort(String endpoint, int fallback) {
try { try {
int port = URI.create(endpoint).getPort(); int port = URI.create(endpoint).getPort();
return port > 0 ? port : 4566; return port > 0 ? port : fallback;
} catch (Exception e) { } catch (Exception e) {
return 4566; return fallback;
} }
} }
} }
@@ -2,12 +2,14 @@ package io.floci.cli.http;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.cli.ProductProfile;
import java.net.ConnectException; import java.net.ConnectException;
import java.net.URI; import java.net.URI;
import java.net.http.HttpClient; import java.net.http.HttpClient;
import java.net.http.HttpRequest; import java.net.http.HttpRequest;
import java.net.http.HttpResponse; import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -28,6 +30,7 @@ public class FlociHttpClient {
private final String endpoint; private final String endpoint;
private final String query; private final String query;
private final String controlPrefix; private final String controlPrefix;
private final String commandPrefix;
private final HttpClient http; private final HttpClient http;
public FlociHttpClient(String endpoint) { public FlociHttpClient(String endpoint) {
@@ -39,6 +42,16 @@ public class FlociHttpClient {
* (e.g. {@code /_floci} for AWS/Azure, {@code /_floci-gcp} for GCP). * (e.g. {@code /_floci} for AWS/Azure, {@code /_floci-gcp} for GCP).
*/ */
public FlociHttpClient(String endpoint, String controlPrefix) { public FlociHttpClient(String endpoint, String controlPrefix) {
this(endpoint, controlPrefix, "floci");
}
/** A client for {@code product}'s emulator: its control prefix, and hints that name its tree. */
public FlociHttpClient(String endpoint, ProductProfile product) {
this(endpoint, product.controlPrefix(), product.commandPrefix());
}
private FlociHttpClient(String endpoint, String controlPrefix, String commandPrefix) {
this.commandPrefix = commandPrefix;
// Request paths go before an endpoint's query: http://h:1/?x=1 + /health is http://h:1/health?x=1. // Request paths go before an endpoint's query: http://h:1/?x=1 + /health is http://h:1/health?x=1.
// A fragment is never sent, so it is dropped. // A fragment is never sent, so it is dropped.
int fragment = endpoint.indexOf('#'); int fragment = endpoint.indexOf('#');
@@ -152,7 +165,7 @@ public class FlociHttpClient {
} catch (FlociException e) { } catch (FlociException e) {
throw e; throw e;
} catch (ConnectException e) { } catch (ConnectException e) {
throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci status' or 'floci start'."); throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try '" + commandPrefix + " status' or '" + commandPrefix + " start'.");
} catch (Exception e) { } catch (Exception e) {
throw new FlociException("Request failed: " + e.getMessage()); throw new FlociException("Request failed: " + e.getMessage());
} }
@@ -194,10 +207,12 @@ public class FlociHttpClient {
resp = pending.get(timeout.toMillis(), TimeUnit.MILLISECONDS); resp = pending.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) { } catch (TimeoutException e) {
pending.cancel(true); pending.cancel(true);
throw new FlociException("No complete response from " + endpoint + path + " within " throw timedOut(path, timeout);
+ timeout.toMillis() + " ms. Is Floci running? Try 'floci status'.");
} catch (ExecutionException e) { } catch (ExecutionException e) {
if (e.getCause() instanceof ConnectException) throw (ConnectException) e.getCause(); if (e.getCause() instanceof ConnectException) throw (ConnectException) e.getCause();
// The request's own timeout (no headers yet) can fire just before the one above:
// the same event, so the same message.
if (e.getCause() instanceof HttpTimeoutException) throw timedOut(path, timeout);
throw new FlociException("Request failed: " + e.getCause().getMessage()); throw new FlociException("Request failed: " + e.getCause().getMessage());
} }
if (resp.statusCode() >= 400) { if (resp.statusCode() >= 400) {
@@ -210,12 +225,17 @@ public class FlociHttpClient {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
throw new FlociException("Request interrupted.\nRe-run the command."); throw new FlociException("Request interrupted.\nRe-run the command.");
} catch (ConnectException e) { } catch (ConnectException e) {
throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci status' or 'floci start'."); throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try '" + commandPrefix + " status' or '" + commandPrefix + " start'.");
} catch (Exception e) { } catch (Exception e) {
throw new FlociException("Request failed: " + e.getMessage()); throw new FlociException("Request failed: " + e.getMessage());
} }
} }
private FlociException timedOut(String path, Duration timeout) {
return new FlociException("No complete response from " + endpoint + path + " within "
+ timeout.toMillis() + " ms. Is Floci running? Try '" + commandPrefix + " status'.");
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<String, Object> postJson(String path, String body) throws FlociException { private Map<String, Object> postJson(String path, String body) throws FlociException {
try { try {
@@ -234,7 +254,7 @@ public class FlociHttpClient {
} catch (FlociException e) { } catch (FlociException e) {
throw e; throw e;
} catch (ConnectException e) { } catch (ConnectException e) {
throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci start'."); throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try '" + commandPrefix + " start'.");
} catch (Exception e) { } catch (Exception e) {
throw new FlociException("Request failed: " + e.getMessage()); throw new FlociException("Request failed: " + e.getMessage());
} }
@@ -192,4 +192,27 @@ class DoctorCommandTest {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
/** BL-036: -o json reports a failed check through the exit code, as text output does. */
@Test
void jsonOutputExitsOneWhenACheckFails() {
Named failing = new Named("bad.check", (e, c) -> CheckResult.fail("bad.check", "broken", "fix it"));
Run r = doctor(List.of(ok("a.check"), failing), "-o", "json");
assertEquals(1, r.exit(), r.out());
assertTrue(r.out().contains("\"bad.check\""), r.out());
}
/** BL-038: warnings alone are not reported as "0 issue(s) found". */
@Test
void warningsOnlyDoNotReadAsZeroIssues() {
Named warning = new Named("warn.check", (e, c) -> CheckResult.warn("warn.check", "hmm", null));
Run r = doctor(List.of(ok("a.check"), warning));
assertEquals(0, r.exit());
assertFalse(r.out().contains("0 issue(s)"), r.out());
assertTrue(r.out().contains("1 warning(s) to review"), r.out());
}
} }
@@ -0,0 +1,116 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.doctor.CheckResult;
import io.floci.cli.doctor.checks.AwsCliEndpointCheck;
import io.floci.cli.doctor.checks.ContainerRunningCheck;
import io.floci.cli.doctor.checks.EndpointReachableCheck;
import io.floci.cli.doctor.checks.PortAvailableCheck;
import io.floci.cli.http.FlociException;
import io.floci.cli.http.FlociHttpClient;
import org.junit.jupiter.api.Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** BL-037/BL-038: doctor's hints and fallbacks belong to the product being diagnosed. */
class DoctorHintsTest {
private static final DockerClient NO_CONTAINER = new DockerClient() {
@Override
public Optional<ContainerInfo> inspectContainer(String name) {
return Optional.empty();
}
};
@Test
void containerHintNamesTheProductTree() {
CheckResult r = new ContainerRunningCheck(NO_CONTAINER, ProductProfile.GCP).run("http://localhost:4588", "floci-gcp");
assertEquals("floci gcp start", r.fix());
}
@Test
void endpointHintNamesTheProductTree() throws Exception {
// A server of our own that answers 500: the check fails without depending on what the
// machine happens to run on some port.
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(500, -1);
exchange.close();
});
server.start();
try {
CheckResult r = new EndpointReachableCheck(ProductProfile.OCI)
.run("http://127.0.0.1:" + server.getAddress().getPort(), "floci-oci");
assertTrue(r.fix().contains("floci oci start"), r.fix());
} finally {
server.stop(0);
}
}
@Test
void portFallbackIsTheProductsDefaultPort() {
assertEquals(4588, PortAvailableCheck.extractPort("not a url", ProductProfile.GCP.defaultPort()));
assertEquals(4566, PortAvailableCheck.extractPort("not a url"));
}
@Test
void httpClientErrorsNameTheProductTree() throws Exception {
// A port that was just bound and released: nothing listens there, so the connection is refused.
int closed;
try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
closed = socket.getLocalPort();
}
FlociException e = assertThrows(FlociException.class,
() -> new FlociHttpClient("http://127.0.0.1:" + closed, ProductProfile.AZ).health());
assertTrue(e.getMessage().contains("Connection refused"), e.getMessage());
assertTrue(e.getMessage().contains("floci az start"), e.getMessage());
}
/** A request that times out names the product's own status command, like the refused one. */
@Test
void httpClientTimeoutsNameTheProductTree() throws Exception {
CountDownLatch release = new CountDownLatch(1);
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/", exchange -> {
try {
release.await(10, TimeUnit.SECONDS); // held until the client has given up
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
exchange.close();
});
server.start();
try {
FlociHttpClient client = new FlociHttpClient("http://127.0.0.1:" + server.getAddress().getPort(), ProductProfile.GCP);
FlociException e = assertThrows(FlociException.class, () -> client.health(Duration.ofMillis(200)));
assertTrue(e.getMessage().contains("floci gcp status"), e.getMessage());
assertFalse(e.getMessage().contains("'floci status'"), e.getMessage());
} finally {
release.countDown();
server.stop(0);
}
}
@Test
void httpsWithoutAPortMeans443() {
assertEquals(443, AwsCliEndpointCheck.extractPort("https://floci.example"));
assertEquals(80, AwsCliEndpointCheck.extractPort("http://floci.example"));
assertEquals(4566, AwsCliEndpointCheck.extractPort("https://floci.example:4566"));
}
}