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 <hectorvent@gmail.com>

* 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 <hectorvent@gmail.com>

* 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 <hectorvent@gmail.com>

* 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 <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 22:07:41 -05:00
1 parent 24b4280f69
commit fa306b38a6
15 files changed
+667 -13

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ import java.util.Arrays;
WaitCommand.class,
VersionCommand.class,
ServicesCommand.class,
ResetCommand.class,
DoctorCommand.class,
EnvCommand.class,
ConfigCommand.class,
+24 -11
View File
@@ -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<String> 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;
}
@@ -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<Integer> {
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 <url> to name the server to reset.";
Optional<DockerClient.ContainerInfo> 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<String> 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<String, Object> 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;
}
}
@@ -24,6 +24,7 @@ import picocli.CommandLine.*;
WaitCommand.class,
VersionCommand.class,
ServicesCommand.class,
ResetCommand.class,
DoctorCommand.class,
EnvCommand.class,
ConfigCommand.class,
@@ -25,6 +25,7 @@ import picocli.CommandLine.*;
AzWaitCommand.class,
AzVersionCommand.class,
AzServicesCommand.class,
AzResetCommand.class,
AzDoctorCommand.class,
AzEnvCommand.class,
AzSetupCommand.class,
@@ -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);
}
}
@@ -24,6 +24,7 @@ import picocli.CommandLine.*;
GcpWaitCommand.class,
GcpVersionCommand.class,
GcpServicesCommand.class,
GcpResetCommand.class,
GcpDoctorCommand.class,
GcpEnvCommand.class,
GcpConfigCommand.class,
@@ -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);
}
}
@@ -25,6 +25,7 @@ import picocli.CommandLine.*;
OciWaitCommand.class,
OciVersionCommand.class,
OciServicesCommand.class,
OciResetCommand.class,
OciDoctorCommand.class,
OciEnvCommand.class,
OciSetupCommand.class,
@@ -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);
}
}
@@ -176,6 +176,11 @@ public class FlociHttpClient {
}
}
/** Deletes every resource the emulator holds ({@code POST <prefix>/state/reset}). */
public Map<String, Object> resetState() throws FlociException {
return postJson(controlPrefix + "/state/reset", "{}");
}
public Map<String, Object> postSnapshot(String name) throws FlociException {
return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name), "{}");
}