From fa306b38a65559020a9fba490773f51342874da3 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 22:07:41 -0500 Subject: [PATCH] feat(reset): add floci reset to delete every resource in a running emulator (#55) * feat(reset): add floci reset to delete every resource in a running emulator floci reset (and floci gcp/az/oci reset) calls the emulator's state reset endpoint, so a test run can start clean without restarting the container. It asks for confirmation on a terminal; --yes skips the prompt and is required when there is no terminal. A server without the endpoint (floci-az today) gets a 'not available' message. Signed-off-by: Hector Ventura * feat(reset): never guess which server to reset A typed --endpoint is used as given instead of being replaced by a local container's port, and a container the user selected has to be found running: a missing or stopped one resets nothing rather than falling back to the default instance. The confirmation goes through a seam, with tests for every answer. Signed-off-by: Hector Ventura * feat(reset): stop when a selected container publishes no port for the emulator A selected container that is running without a matching published port has nothing to be found by, and the configured endpoint may be another instance. Signed-off-by: Hector Ventura * feat(reset): find a selected instance by the emulator's port, not the configured host port A profile for an instance on its own host port names that port in its endpoint, while the container still listens on the emulator's; reset matched the wrong one and refused such instances. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- AGENTS.md | 2 +- README.md | 20 + src/main/java/io/floci/cli/FlociCli.java | 1 + src/main/java/io/floci/cli/GlobalOptions.java | 35 +- .../io/floci/cli/commands/ResetCommand.java | 173 ++++++++ .../io/floci/cli/commands/aws/AwsCommand.java | 1 + .../io/floci/cli/commands/az/AzCommand.java | 1 + .../floci/cli/commands/az/AzResetCommand.java | 17 + .../io/floci/cli/commands/gcp/GcpCommand.java | 1 + .../cli/commands/gcp/GcpResetCommand.java | 17 + .../io/floci/cli/commands/oci/OciCommand.java | 1 + .../cli/commands/oci/OciResetCommand.java | 17 + .../io/floci/cli/http/FlociHttpClient.java | 5 + .../cli/unit/ProductTreesParsingTest.java | 6 +- .../io/floci/cli/unit/ResetCommandTest.java | 383 ++++++++++++++++++ 15 files changed, 667 insertions(+), 13 deletions(-) create mode 100644 src/main/java/io/floci/cli/commands/ResetCommand.java create mode 100644 src/main/java/io/floci/cli/commands/az/AzResetCommand.java create mode 100644 src/main/java/io/floci/cli/commands/gcp/GcpResetCommand.java create mode 100644 src/main/java/io/floci/cli/commands/oci/OciResetCommand.java create mode 100644 src/test/java/io/floci/cli/unit/ResetCommandTest.java diff --git a/AGENTS.md b/AGENTS.md index eafc09d..16cfa6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,7 +72,7 @@ Commands call `global.printer()` at the start of `call()`; never store a `Printe **Docker:** `DockerClient` wraps `docker` CLI subprocesses, with no docker-java library. This is a deliberate native-image trade-off. `DockerClient` returns plain records (`ContainerInfo`, `ImageInfo`) and throws `DockerException` on non-zero exit codes. -**Floci server:** `FlociHttpClient` wraps `java.net.http.HttpClient` against the Floci REST API. All methods throw `FlociException`. The control-plane prefix is constructor-configurable: AWS and Azure use `/_floci`, GCP uses `/_floci-gcp`. Known live endpoints: `/_floci/health`, `/_floci/info`, `/_floci/init`, and on floci-az only `/_floci/tls-cert` (`tlsCert()`, the PEM CA; 404 when TLS is off). Snapshot endpoints (`/_floci/snapshots/*`) do not exist on the server yet. +**Floci server:** `FlociHttpClient` wraps `java.net.http.HttpClient` against the Floci REST API. All methods throw `FlociException`. The control-plane prefix is constructor-configurable: AWS and Azure use `/_floci`, GCP uses `/_floci-gcp`. Known live endpoints: `/_floci/health`, `/_floci/info`, `/_floci/init`, `POST /state/reset` (AWS, GCP and OCI; `floci reset`), and on floci-az only `/_floci/tls-cert` (`tlsCert()`, the PEM CA; 404 when TLS is off). Snapshot endpoints (`/_floci/snapshots/*`) do not exist on the server yet. ### Output pipeline diff --git a/README.md b/README.md index 266eef2..ea8e0f7 100644 --- a/README.md +++ b/README.md @@ -241,6 +241,7 @@ Commands are organized into four product groups: `floci aws` (or bare `floci`), | `floci wait` | Poll until Floci is ready (CI-friendly) | | `floci version` | Show CLI and server versions | | `floci services` | List enabled AWS services | +| `floci reset` | Delete every resource in the running emulator, keeping it running | | `floci doctor` | Run environment diagnostics | | `floci env` | Print AWS environment variables | | `floci snapshot save/load/list/delete` | Manage state snapshots | @@ -261,6 +262,7 @@ Bare `floci config ...` always means the AWS tree, whatever the default product; | `floci gcp wait` | Poll until Floci GCP is ready (CI-friendly) | | `floci gcp version` | Show CLI and server versions | | `floci gcp services` | List enabled GCP services | +| `floci gcp reset` | Delete every resource in the running emulator, keeping it running | | `floci gcp doctor` | Run GCP environment diagnostics | | `floci gcp env` | Print GCP SDK emulator host variables | | `floci gcp snapshot` | Snapshot commands (coming soon) | @@ -278,6 +280,7 @@ Bare `floci config ...` always means the AWS tree, whatever the default product; | `floci az wait` | Poll until Floci Azure is ready (CI-friendly) | | `floci az version` | Show CLI and server versions | | `floci az services` | List enabled Azure services | +| `floci az reset` | Delete every resource in the running emulator, keeping it running | | `floci az doctor` | Run Azure environment diagnostics | | `floci az env` | Print Azure connection string / SDK env vars | | `floci az setup` | Point the `az` CLI at the emulator: trust its certificate, register the cloud, log in | @@ -296,6 +299,7 @@ Bare `floci config ...` always means the AWS tree, whatever the default product; | `floci oci wait` | Poll until Floci OCI is ready (CI-friendly) | | `floci oci version` | Show CLI and server versions | | `floci oci services` | List enabled OCI services | +| `floci oci reset` | Delete every resource in the running emulator, keeping it running | | `floci oci doctor` | Run OCI environment diagnostics | | `floci oci env` | Print OCI endpoint variables | | `floci oci setup` | Create a local OCI CLI profile (API key + `~/.oci/config`) | @@ -681,6 +685,22 @@ floci services # list all enabled services floci services -o json ``` +### `floci reset` / `floci gcp reset` / `floci az reset` / `floci oci reset` + +```sh +floci reset # asks first, then deletes every resource; the emulator keeps running +floci reset --yes # no prompt (required when not on a terminal, e.g. in CI) +floci gcp reset -y -o json +``` + +It calls the emulator's `POST /state/reset`. The AWS, GCP and OCI emulators serve it; on a +server without it (currently floci-az) the command says reset is not available and exits 1. Without +`--yes` and with no terminal to ask on, it exits 2. + +Reset never guesses which server to wipe. An `--endpoint` you type is used as given. A container you +select (`--container`, a profile, or `FLOCI_CONTAINER`) has to be running: if it is missing or +stopped, nothing is reset and the command exits 1 instead of falling back to the default instance. + ### `floci config` ```sh diff --git a/src/main/java/io/floci/cli/FlociCli.java b/src/main/java/io/floci/cli/FlociCli.java index 146d811..39e98b2 100644 --- a/src/main/java/io/floci/cli/FlociCli.java +++ b/src/main/java/io/floci/cli/FlociCli.java @@ -42,6 +42,7 @@ import java.util.Arrays; WaitCommand.class, VersionCommand.class, ServicesCommand.class, + ResetCommand.class, DoctorCommand.class, EnvCommand.class, ConfigCommand.class, diff --git a/src/main/java/io/floci/cli/GlobalOptions.java b/src/main/java/io/floci/cli/GlobalOptions.java index 2d425f6..a2f895b 100644 --- a/src/main/java/io/floci/cli/GlobalOptions.java +++ b/src/main/java/io/floci/cli/GlobalOptions.java @@ -9,6 +9,7 @@ import picocli.CommandLine.Option; import picocli.CommandLine.Spec; import java.net.URI; +import java.util.Optional; import java.util.function.UnaryOperator; import java.util.regex.Pattern; @@ -105,7 +106,8 @@ public class GlobalOptions { return ""; } - private boolean typed(String option) { + /** Whether {@code option} was given on the command line, as opposed to coming from a profile, the environment or the default. */ + public boolean typed(String option) { try { return mixee != null && mixee.commandLine() != null && mixee.commandLine().getParseResult() != null @@ -150,20 +152,31 @@ public class GlobalOptions { try { int containerPort = URI.create(fallback).getPort(); if (containerPort == -1) containerPort = product.defaultPort(); - for (String mapping : ports.trim().split("\\s+")) { - int arrow = mapping.indexOf("->"); - if (arrow < 0) continue; - String hostPort = mapping.substring(0, arrow); - String rest = mapping.substring(arrow + 2); - String cPort = rest.contains("/") ? rest.substring(0, rest.indexOf('/')) : rest; - if (String.valueOf(containerPort).equals(cPort)) { - return "http://localhost:" + hostPort; - } - } + return publishedEndpoint(ports, containerPort).orElse(fallback); } catch (Exception ignored) {} return fallback; } + /** + * Where a container with these published {@code ports} ("14566->4566/tcp ...") is reached for + * its {@code containerPort}, or empty when that port is not published. For callers that must + * not fall back to a configured endpoint. + */ + public static Optional publishedEndpoint(String ports, int containerPort) { + if (ports == null || ports.isBlank()) return Optional.empty(); + for (String mapping : ports.trim().split("\\s+")) { + int arrow = mapping.indexOf("->"); + if (arrow < 0) continue; + String hostPort = mapping.substring(0, arrow); + String rest = mapping.substring(arrow + 2); + String cPort = rest.contains("/") ? rest.substring(0, rest.indexOf('/')) : rest; + if (String.valueOf(containerPort).equals(cPort)) { + return Optional.of("http://localhost:" + hostPort); + } + } + return Optional.empty(); + } + private static boolean isStdoutTty() { return System.console() != null; } diff --git a/src/main/java/io/floci/cli/commands/ResetCommand.java b/src/main/java/io/floci/cli/commands/ResetCommand.java new file mode 100644 index 0000000..5e4de19 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/ResetCommand.java @@ -0,0 +1,173 @@ +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.docker.DockerException; +import io.floci.cli.http.FlociException; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.Console; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; + +@Command( + name = "reset", + description = "Delete every resource in the running Floci AWS instance, keeping it running", + mixinStandardHelpOptions = true +) +public class ResetCommand implements Callable { + + protected final ProductProfile profile; + + @Mixin + protected GlobalOptions global; + + @Option(names = {"--yes", "-y"}, description = "Reset without asking for confirmation") + boolean yes; + + public ResetCommand() { + this(ProductProfile.AWS); + } + + protected ResetCommand(ProductProfile profile) { + this(profile, new DockerClient(), Prompt.console()); + } + + /** Test seam: {@code docker} answers the container lookup and {@code prompt} the confirmation. */ + public ResetCommand(ProductProfile profile, DockerClient docker, Prompt prompt) { + this.profile = profile; + this.global = new GlobalOptions(profile); + this.docker = docker; + this.prompt = prompt; + } + + private final DockerClient docker; + private final Prompt prompt; + + /** The person at the terminal, when there is one. */ + public interface Prompt { + + /** False when nobody can answer (a pipe, CI). */ + boolean available(); + + /** The answer to {@code question}, or null at end of input. */ + String ask(String question); + + static Prompt console() { + return new Prompt() { + @Override + public boolean available() { + Console console = System.console(); + return console != null && console.isTerminal(); + } + + @Override + public String ask(String question) { + return System.console().readLine("%s", question); + } + }; + } + } + + /** The server a reset will wipe, or why none could be settled on. Exactly one is set. */ + public record Target(String endpoint, String error) {} + + /** + * Where this reset acts. Reset deletes data, so unlike the read-only commands it never + * guesses: an {@code --endpoint} the user typed is used as given, and a container the user + * chose must be found running. Falling back to the configured endpoint, as + * {@link GlobalOptions#resolvedEndpoint} does, is right only for the default container: there + * the configured endpoint names the same default instance. + */ + public Target target() { + if (global.typed("--endpoint")) return new Target(global.endpoint, null); + boolean chosen = global.typed("--container") || !profile.defaultContainer().equals(global.container); + String how = "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector() + + "' to check it, or pass --endpoint to name the server to reset."; + Optional info; + try { + info = docker.inspectContainer(global.container); + } catch (DockerException e) { + if (chosen) { + return new Target(null, "Could not look up container '" + global.container + "': " + e.getMessage() + how); + } + info = Optional.empty(); + } + if (info.isEmpty()) { + return chosen + ? new Target(null, "Container '" + global.container + "' not found, so nothing was reset." + how) + : new Target(global.endpoint, null); + } + if (chosen && !"running".equals(info.get().state())) { + return new Target(null, "Container '" + global.container + "' is not running (state: " + + info.get().state() + "), so nothing was reset." + how); + } + // By the emulator's own port inside the container, which never changes; the configured + // endpoint names the host port, and that differs on every instance but the default one. + Optional published = GlobalOptions.publishedEndpoint(info.get().ports(), profile.defaultPort()); + if (chosen && published.isEmpty()) { + // No port to find it by: the configured endpoint may well be another instance. + return new Target(null, "Container '" + global.container + + "' publishes no port for the emulator, so nothing was reset." + how); + } + return new Target(published.orElse(global.endpoint), null); + } + + @Override + public Integer call() { + Printer printer = global.printer(); + Target target = target(); + if (target.error() != null) { + printer.error(target.error()); + return 1; + } + String effectiveEndpoint = target.endpoint(); + + if (!yes) { + if (!prompt.available()) { + // Nobody to ask: a script must say so explicitly. + printer.error("reset deletes every resource in " + profile.displayName() + " and needs confirmation.\n" + + "Pass --yes to reset without asking."); + return 2; + } + String answer = prompt.ask("Delete every resource in " + profile.displayName() + + " at " + effectiveEndpoint + "? [y/N] "); + if (answer == null || !(answer.trim().equalsIgnoreCase("y") || answer.trim().equalsIgnoreCase("yes"))) { + printer.println("Reset cancelled."); + return 1; + } + } + + try { + new FlociHttpClient(effectiveEndpoint, profile).resetState(); + } catch (FlociException e) { + if (e.endpointMissing()) { + printer.error("Resetting state is not available on this " + profile.displayName() + " server version.\n" + + "Restart it without --persist for a clean state, or track progress: " + profile.serverRepo() + "/issues"); + } else { + String message = "Failed to reset " + profile.displayName() + ": " + e.getMessage(); + // Connection errors already say what to do; others get the status hint. + printer.error(message.contains("\n") ? message + : message + "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator."); + } + return 1; + } + + if (printer.format() != OutputFormat.text) { + Map out = new LinkedHashMap<>(); + out.put("reset", true); + out.put("endpoint", effectiveEndpoint); + printer.structured(out); + return 0; + } + printer.println(Ansi.green("✓") + " " + profile.displayName() + " state reset" + Ansi.gray(" (" + effectiveEndpoint + ")")); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/aws/AwsCommand.java b/src/main/java/io/floci/cli/commands/aws/AwsCommand.java index 5eb8174..61675eb 100644 --- a/src/main/java/io/floci/cli/commands/aws/AwsCommand.java +++ b/src/main/java/io/floci/cli/commands/aws/AwsCommand.java @@ -24,6 +24,7 @@ import picocli.CommandLine.*; WaitCommand.class, VersionCommand.class, ServicesCommand.class, + ResetCommand.class, DoctorCommand.class, EnvCommand.class, ConfigCommand.class, diff --git a/src/main/java/io/floci/cli/commands/az/AzCommand.java b/src/main/java/io/floci/cli/commands/az/AzCommand.java index d847d57..87ff985 100644 --- a/src/main/java/io/floci/cli/commands/az/AzCommand.java +++ b/src/main/java/io/floci/cli/commands/az/AzCommand.java @@ -25,6 +25,7 @@ import picocli.CommandLine.*; AzWaitCommand.class, AzVersionCommand.class, AzServicesCommand.class, + AzResetCommand.class, AzDoctorCommand.class, AzEnvCommand.class, AzSetupCommand.class, diff --git a/src/main/java/io/floci/cli/commands/az/AzResetCommand.java b/src/main/java/io/floci/cli/commands/az/AzResetCommand.java new file mode 100644 index 0000000..79f0250 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzResetCommand.java @@ -0,0 +1,17 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.ResetCommand; +import picocli.CommandLine.Command; + +@Command( + name = "reset", + description = "Delete every resource in the running Floci Azure instance, keeping it running", + mixinStandardHelpOptions = true +) +public class AzResetCommand extends ResetCommand { + + public AzResetCommand() { + super(ProductProfile.AZ); + } +} diff --git a/src/main/java/io/floci/cli/commands/gcp/GcpCommand.java b/src/main/java/io/floci/cli/commands/gcp/GcpCommand.java index 5f8eb78..5e9868d 100644 --- a/src/main/java/io/floci/cli/commands/gcp/GcpCommand.java +++ b/src/main/java/io/floci/cli/commands/gcp/GcpCommand.java @@ -24,6 +24,7 @@ import picocli.CommandLine.*; GcpWaitCommand.class, GcpVersionCommand.class, GcpServicesCommand.class, + GcpResetCommand.class, GcpDoctorCommand.class, GcpEnvCommand.class, GcpConfigCommand.class, diff --git a/src/main/java/io/floci/cli/commands/gcp/GcpResetCommand.java b/src/main/java/io/floci/cli/commands/gcp/GcpResetCommand.java new file mode 100644 index 0000000..9425712 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/gcp/GcpResetCommand.java @@ -0,0 +1,17 @@ +package io.floci.cli.commands.gcp; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.ResetCommand; +import picocli.CommandLine.Command; + +@Command( + name = "reset", + description = "Delete every resource in the running Floci GCP instance, keeping it running", + mixinStandardHelpOptions = true +) +public class GcpResetCommand extends ResetCommand { + + public GcpResetCommand() { + super(ProductProfile.GCP); + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/OciCommand.java b/src/main/java/io/floci/cli/commands/oci/OciCommand.java index c704940..899c0c1 100644 --- a/src/main/java/io/floci/cli/commands/oci/OciCommand.java +++ b/src/main/java/io/floci/cli/commands/oci/OciCommand.java @@ -25,6 +25,7 @@ import picocli.CommandLine.*; OciWaitCommand.class, OciVersionCommand.class, OciServicesCommand.class, + OciResetCommand.class, OciDoctorCommand.class, OciEnvCommand.class, OciSetupCommand.class, diff --git a/src/main/java/io/floci/cli/commands/oci/OciResetCommand.java b/src/main/java/io/floci/cli/commands/oci/OciResetCommand.java new file mode 100644 index 0000000..bebe489 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciResetCommand.java @@ -0,0 +1,17 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.ResetCommand; +import picocli.CommandLine.Command; + +@Command( + name = "reset", + description = "Delete every resource in the running Floci OCI instance, keeping it running", + mixinStandardHelpOptions = true +) +public class OciResetCommand extends ResetCommand { + + public OciResetCommand() { + super(ProductProfile.OCI); + } +} diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index def58c9..1f3e2cb 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -176,6 +176,11 @@ public class FlociHttpClient { } } + /** Deletes every resource the emulator holds ({@code POST /state/reset}). */ + public Map resetState() throws FlociException { + return postJson(controlPrefix + "/state/reset", "{}"); + } + public Map postSnapshot(String name) throws FlociException { return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name), "{}"); } diff --git a/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java b/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java index e7c4929..2acb7b7 100644 --- a/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java +++ b/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java @@ -19,7 +19,7 @@ class ProductTreesParsingTest { private static final Set LIFECYCLE_COMMANDS = Set.of( "start", "stop", "restart", "status", "logs", "wait", - "version", "services", "doctor", "env", "config", "snapshot", "completion", "help"); + "version", "services", "reset", "doctor", "env", "config", "snapshot", "completion", "help"); private static CommandSpec leafSpec(String... args) { ParseResult r = new CommandLine(new FlociCli()).parseArgs(args); @@ -43,6 +43,7 @@ class ProductTreesParsingTest { void awsTreeDefaults() { assertDefaults("http://localhost:4566", "floci", "status"); assertDefaults("http://localhost:4566", "floci", "aws", "status"); + assertDefaults("http://localhost:4566", "floci", "reset"); assertStartDefaults("4566", "floci/floci:latest", "start"); assertStartDefaults("4566", "floci/floci:latest", "aws", "start"); } @@ -50,18 +51,21 @@ class ProductTreesParsingTest { @Test void gcpTreeDefaults() { assertDefaults("http://localhost:4588", "floci-gcp", "gcp", "status"); + assertDefaults("http://localhost:4588", "floci-gcp", "gcp", "reset"); assertStartDefaults("4588", "floci/floci-gcp:latest", "gcp", "start"); } @Test void azTreeDefaults() { assertDefaults("http://localhost:4577", "floci-az", "az", "status"); + assertDefaults("http://localhost:4577", "floci-az", "az", "reset"); assertStartDefaults("4577", "floci/floci-az:latest", "az", "start"); } @Test void ociTreeDefaults() { assertDefaults("http://localhost:4599", "floci-oci", "oci", "status"); + assertDefaults("http://localhost:4599", "floci-oci", "oci", "reset"); assertStartDefaults("4599", "floci/floci-oci:latest", "oci", "start"); } diff --git a/src/test/java/io/floci/cli/unit/ResetCommandTest.java b/src/test/java/io/floci/cli/unit/ResetCommandTest.java new file mode 100644 index 0000000..38288e1 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ResetCommandTest.java @@ -0,0 +1,383 @@ +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.ResetCommand; +import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-064: floci reset against a stub emulator. */ +class ResetCommandTest { + + @TempDir + Path tempDir; + + private HttpServer server; + private final List requests = new CopyOnWriteArrayList<>(); + private final AtomicInteger status = new AtomicInteger(200); + + private record Run(int exit, String out, String err) {} + + @BeforeEach + void start() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + requests.add(exchange.getRequestMethod() + " " + exchange.getRequestURI().getPath()); + byte[] body = "{\"status\":\"OK\"}".getBytes(StandardCharsets.UTF_8); + if (status.get() == 200) { + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + } else { + exchange.sendResponseHeaders(status.get(), -1); + } + exchange.close(); + }); + server.start(); + } + + @AfterEach + void stop() { + server.stop(0); + } + + private Run run(String... args) { + List all = new ArrayList<>(List.of(args)); + all.addAll(List.of("--endpoint", "http://127.0.0.1:" + server.getAddress().getPort(), + "--container", "floci-reset-test-none")); + 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 { + int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(all.toArray(String[]::new)); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void yesPostsToTheProductsResetEndpoint() { + Run r = run("gcp", "reset", "--yes"); + + assertEquals(0, r.exit(), r.err()); + assertEquals(List.of("POST /_floci-gcp/state/reset"), requests); + assertTrue(r.out().contains("state reset"), r.out()); + } + + @Test + void structuredOutputReportsTheReset() { + Run r = run("reset", "-y", "-o", "json"); + + assertEquals(0, r.exit(), r.err()); + assertEquals(List.of("POST /_floci/state/reset"), requests); + assertTrue(r.out().contains("\"reset\" : true") || r.out().contains("\"reset\":true"), r.out()); + } + + /** Nobody to ask: without --yes nothing is deleted and the exit code says it was a usage problem. */ + @Test + void withoutATerminalItNeedsYes() { + Run r = run("oci", "reset"); + + assertEquals(2, r.exit()); + assertTrue(r.err().contains("Pass --yes"), r.err()); + assertEquals(List.of(), requests, "nothing was reset"); + } + + @Test + void aServerWithoutTheEndpointSaysResetIsNotAvailable() { + status.set(404); + + Run r = run("az", "reset", "--yes"); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("not available"), r.err()); + assertTrue(r.err().contains("floci-az"), r.err()); + } + + // ---- which server a reset acts on ------------------------------------------------------- + + private static DockerClient dockerWith(String name, String state, String ports) { + return new DockerClient() { + @Override + public Optional inspectContainer(String asked) { + return asked.equals(name) + ? Optional.of(new ContainerInfo("abc", name, "floci/floci:latest", state, ports)) + : Optional.empty(); + } + }; + } + + private static final ResetCommand.Prompt NOBODY = new ResetCommand.Prompt() { + @Override + public boolean available() { + return false; + } + + @Override + public String ask(String question) { + throw new AssertionError("nobody to ask"); + } + }; + + private static ResetCommand.Target targetOf(DockerClient docker, String... args) { + ResetCommand reset = new ResetCommand(ProductProfile.AWS, docker, NOBODY); + new CommandLine(reset).parseArgs(args); + return reset.target(); + } + + /** A typed --endpoint is the server to reset, even with a local container of the same name running. */ + @Test + void aTypedEndpointIsNeverReplacedByALocalContainer() { + DockerClient local = dockerWith("floci", "running", "14566->4566/tcp"); + + ResetCommand.Target target = targetOf(local, "--endpoint", "http://remote-host:4566"); + + assertEquals("http://remote-host:4566", target.endpoint()); + assertNull(target.error()); + } + + @Test + void theDefaultContainerIsFoundThroughItsPortMapping() { + ResetCommand.Target target = targetOf(dockerWith("floci", "running", "14566->4566/tcp")); + + assertEquals("http://localhost:14566", target.endpoint()); + } + + /** A container the user chose and that is not there must not fall back to the default instance. */ + @Test + void aChosenContainerThatIsMissingResetsNothing() { + ResetCommand.Target target = targetOf(dockerWith("floci", "running", "4566->4566/tcp"), + "--container", "floci-team-b"); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("Container 'floci-team-b' not found, so nothing was reset."), target.error()); + assertTrue(target.error().contains("floci status --container floci-team-b"), target.error()); + assertTrue(target.error().contains("--endpoint "), target.error()); + } + + /** A stopped container has no port mapping; the fallback would again be the default instance. */ + @Test + void aChosenContainerThatIsStoppedResetsNothing() { + ResetCommand.Target target = targetOf(dockerWith("floci-team-b", "exited", ""), "--container", "floci-team-b"); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("is not running (state: exited)"), target.error()); + } + + /** + * Running, but with no published port for the emulator (or only an unrelated one): there is + * nothing to find it by, and the configured endpoint may be the default instance. + */ + @ParameterizedTest + @ValueSource(strings = {"", "18080->8080/tcp"}) + void aChosenContainerWithoutAMatchingPortResetsNothing(String ports) { + ResetCommand.Target target = targetOf(dockerWith("floci-team-b", "running", ports), "--container", "floci-team-b"); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("publishes no port for the emulator, so nothing was reset."), target.error()); + } + + @Test + void aChosenContainerIsFoundThroughItsPortMapping() { + ResetCommand.Target target = targetOf(dockerWith("floci-team-b", "running", "14566->4566/tcp"), + "--container", "floci-team-b"); + + assertEquals("http://localhost:14566", target.endpoint()); + } + + /** + * An instance on its own host port: the profile's endpoint names that host port (14566), the + * container still listens on the emulator's (4566). It is found by the latter. + */ + @Test + void anInstanceOnACustomHostPortIsFoundByTheEmulatorsPort() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("team-b.yaml"), + "container: floci-team-b\nendpoint: http://localhost:14566\nport: 14566\n"); + ResetCommand reset = new ResetCommand(ProductProfile.AWS, + dockerWith("floci-team-b", "running", "14566->4566/tcp"), NOBODY); + new CommandLine(reset) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .parseArgs("--profile", "team-b"); + + ResetCommand.Target target = reset.target(); + + assertNull(target.error(), target.error()); + assertEquals("http://localhost:14566", target.endpoint()); + } + + @Test + void theOtherProductsAreFoundByTheirOwnPort() { + ResetCommand gcp = new ResetCommand(ProductProfile.GCP, dockerWith("floci-gcp-b", "running", "14588->4588/tcp"), NOBODY); + new CommandLine(gcp).parseArgs("--container", "floci-gcp-b"); + + assertEquals("http://localhost:14588", gcp.target().endpoint()); + } + + /** The default container without a published port (host networking) is still the default instance. */ + @Test + void theDefaultContainerWithoutAPublishedPortUsesItsConfiguredEndpoint() { + ResetCommand.Target target = targetOf(dockerWith("floci", "running", "")); + + assertEquals("http://localhost:4566", target.endpoint()); + } + + @Test + void aChosenContainerDockerCannotLookUpResetsNothing() { + DockerClient broken = new DockerClient() { + @Override + public Optional inspectContainer(String name) throws DockerException { + throw new DockerException("Cannot connect to the Docker daemon"); + } + }; + + ResetCommand.Target target = targetOf(broken, "--container", "floci-team-b"); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("Cannot connect to the Docker daemon"), target.error()); + } + + @Test + void aChosenContainerWithATypedEndpointUsesTheEndpoint() { + ResetCommand.Target target = targetOf(dockerWith("floci", "running", "4566->4566/tcp"), + "--container", "floci-team-b", "--endpoint", "http://localhost:14577"); + + assertEquals("http://localhost:14577", target.endpoint()); + } + + /** Without any selection the default instance is meant, also when it runs outside a 'floci' container. */ + @Test + void theDefaultInstanceFallsBackToItsConfiguredEndpoint() { + ResetCommand.Target target = targetOf(dockerWith("something-else", "running", "")); + + assertEquals("http://localhost:4566", target.endpoint()); + } + + @Test + void aMissingChosenContainerSendsNoRequest() { + ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("floci", "running", "4566->4566/tcp"), NOBODY); + + Run r = execute(reset, "--yes", "--container", "floci-team-b"); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("nothing was reset"), r.err()); + assertEquals(List.of(), requests); + } + + // ---- the confirmation -------------------------------------------------------------------- + + private static ResetCommand.Prompt answering(String answer, List asked) { + return new ResetCommand.Prompt() { + @Override + public boolean available() { + return true; + } + + @Override + public String ask(String question) { + asked.add(question); + return answer; + } + }; + } + + private Run execute(ResetCommand reset, String... args) { + 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 { + int exit = new CommandLine(reset).execute(args); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + private Run confirmWith(String answer, List asked) { + ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("none", "running", ""), answering(answer, asked)); + return execute(reset, "--endpoint", "http://127.0.0.1:" + server.getAddress().getPort()); + } + + /** Anything but a yes deletes nothing: a no, a bare Enter, something else. */ + @ParameterizedTest + @ValueSource(strings = {"n", "N", "no", "", " ", "yep", "y es"}) + void decliningSendsNoRequest(String answer) { + List asked = new ArrayList<>(); + + Run r = confirmWith(answer, asked); + + assertEquals(1, r.exit()); + assertEquals(List.of(), requests, "nothing was reset"); + assertTrue(r.out().contains("Reset cancelled."), r.out()); + assertEquals(1, asked.size()); + } + + /** End of input (Ctrl-D) is not a yes. */ + @Test + void endOfInputSendsNoRequest() { + Run r = confirmWith(null, new ArrayList<>()); + + assertEquals(1, r.exit()); + assertEquals(List.of(), requests, "nothing was reset"); + } + + @ParameterizedTest + @ValueSource(strings = {"y", "Y", "yes", "YES", " yes "}) + void confirmingSendsExactlyOneRequest(String answer) { + List asked = new ArrayList<>(); + + Run r = confirmWith(answer, asked); + + assertEquals(0, r.exit(), r.err()); + assertEquals(List.of("POST /_floci/state/reset"), requests); + assertTrue(asked.get(0).contains("http://127.0.0.1:" + server.getAddress().getPort()), asked.get(0)); + } + + /** --yes asks nobody. */ + @Test + void yesDoesNotAsk() { + List asked = new ArrayList<>(); + ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("none", "running", ""), answering("n", asked)); + + Run r = execute(reset, "--yes", "--endpoint", "http://127.0.0.1:" + server.getAddress().getPort()); + + assertEquals(0, r.exit(), r.err()); + assertEquals(List.of(), asked); + assertEquals(List.of("POST /_floci/state/reset"), requests); + } +}