mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
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>
This commit is contained in:
4 files changed
+294
-6
No files matched your search
@@ -698,6 +698,10 @@ It calls the emulator's `POST <prefix>/state/reset`. The AWS, GCP and OCI emulat
|
||||
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
|
||||
|
||||
@@ -105,7 +105,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
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.cli.commands;
|
||||
import io.floci.cli.GlobalOptions;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
import io.floci.cli.docker.DockerException;
|
||||
import io.floci.cli.http.FlociException;
|
||||
import io.floci.cli.http.FlociHttpClient;
|
||||
import io.floci.cli.output.Ansi;
|
||||
@@ -13,6 +14,7 @@ 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(
|
||||
@@ -35,25 +37,100 @@ public class ResetCommand implements Callable<Integer> {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return new Target(global.endpointFromPorts(info.get().ports(), global.endpoint), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
Printer printer = global.printer();
|
||||
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
|
||||
Target target = target();
|
||||
if (target.error() != null) {
|
||||
printer.error(target.error());
|
||||
return 1;
|
||||
}
|
||||
String effectiveEndpoint = target.endpoint();
|
||||
|
||||
if (!yes) {
|
||||
Console console = System.console();
|
||||
if (console == null || !console.isTerminal()) {
|
||||
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 = console.readLine("Delete every resource in %s at %s? [y/N] ",
|
||||
profile.displayName(), effectiveEndpoint);
|
||||
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;
|
||||
|
||||
@@ -2,11 +2,18 @@ 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.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;
|
||||
@@ -16,6 +23,7 @@ import java.nio.charset.StandardCharsets;
|
||||
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;
|
||||
|
||||
@@ -114,4 +122,202 @@ class ResetCommandTest {
|
||||
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<ContainerInfo> 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 <url>"), 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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChosenContainerDockerCannotLookUpResetsNothing() {
|
||||
DockerClient broken = new DockerClient() {
|
||||
@Override
|
||||
public Optional<ContainerInfo> 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<String> 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<String> 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<String> 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<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user