diff --git a/README.md b/README.md index a225315..f11f5eb 100644 --- a/README.md +++ b/README.md @@ -724,9 +724,10 @@ It calls the emulator's `POST /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, and so is an -endpoint that a profile or `FLOCI_ENDPOINT` supplies when no container is selected: a container -that happens to run locally under the default name does not take its place. A container you +Reset never guesses which server to wipe. An `--endpoint` you type is used as given. An endpoint +that a profile or `FLOCI_ENDPOINT` supplies is used too, and a container that happens to run +locally under the default name never takes its place: if that container is a different server +than the endpoint, nothing is reset and you are asked to pass `--endpoint` or `--container`. 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. diff --git a/src/main/java/io/floci/cli/commands/ResetCommand.java b/src/main/java/io/floci/cli/commands/ResetCommand.java index 37cc050..97ec74b 100644 --- a/src/main/java/io/floci/cli/commands/ResetCommand.java +++ b/src/main/java/io/floci/cli/commands/ResetCommand.java @@ -13,7 +13,9 @@ import io.floci.cli.output.Printer; import picocli.CommandLine.*; import java.io.Console; +import java.net.URI; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.concurrent.Callable; @@ -86,16 +88,17 @@ public class ResetCommand implements Callable { * chose must be found running. * *

An endpoint that a profile or {@code _ENDPOINT} supplies names a server just as - * a typed one does. With no container chosen it is used as given too: looking up the default - * container instead, as {@link GlobalOptions#resolvedEndpoint} does, would reset whatever - * runs locally under the default name rather than the server the user pointed at. Only when + * a typed one does, so with no container chosen it is not silently replaced by a container + * that runs locally under the default name. But a profile carries a container name as well + * (every created profile is seeded with the default one), so the two can point at different + * servers. When they do, nothing is reset: the user has to say which one is meant. Only when * nothing at all was selected is the default container looked up, falling back to the * default endpoint, which 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); - if (!chosen && namesAServer(global.endpoint, profile)) return new Target(global.endpoint, null); + if (!chosen && namesAServer(global.endpoint, profile)) return namedEndpoint(); String how = "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check it, or pass --endpoint to name the server to reset."; Optional info; @@ -127,6 +130,43 @@ public class ResetCommand implements Callable { return new Target(published.orElse(global.endpoint), null); } + // The configured endpoint names a server and the container name is only the default one. The + // endpoint is used, unless a container of that name is running here and is a different + // server: then the configuration is ambiguous, and a reset must not pick. + private Target namedEndpoint() { + Optional local; + try { + local = docker.inspectContainer(global.container) + .filter(info -> "running".equals(info.state())) + .flatMap(info -> GlobalOptions.publishedEndpoint(info.ports(), profile.defaultPort())); + } catch (DockerException e) { + local = Optional.empty(); // nothing known to contradict the endpoint + } + if (local.isEmpty() || sameLocalServer(local.get(), global.endpoint)) { + return new Target(global.endpoint, null); + } + return new Target(null, "The configured endpoint is " + global.endpoint + ", but container '" + global.container + + "' is running at " + local.get() + ". They are different servers, so nothing was reset." + + "\nPass --endpoint or --container to say which one to reset."); + } + + /** + * Whether {@code configured} is the server a local container publishes at {@code published} + * ({@code http://localhost:}): the same port, on a host name that means this machine. + */ + public static boolean sameLocalServer(String published, String configured) { + try { + URI here = URI.create(published); + URI there = URI.create(withoutTrailingSlashes(configured)); + String host = there.getHost() == null ? "" : there.getHost().toLowerCase(Locale.ROOT); + boolean thisMachine = host.equals("localhost") || host.equals("127.0.0.1") || host.equals("[::1]") + || host.equals("::1") || host.equals("0.0.0.0") || host.equals("localhost.floci.io"); + return thisMachine && here.getPort() == there.getPort(); + } catch (IllegalArgumentException e) { + return false; + } + } + /** * Whether {@code endpoint} is something other than the product's default, that is, whether a * profile or the environment pointed this command at a particular server. A trailing slash diff --git a/src/test/java/io/floci/cli/unit/ResetCommandTest.java b/src/test/java/io/floci/cli/unit/ResetCommandTest.java index e781be8..2f5d184 100644 --- a/src/test/java/io/floci/cli/unit/ResetCommandTest.java +++ b/src/test/java/io/floci/cli/unit/ResetCommandTest.java @@ -182,31 +182,75 @@ class ResetCommandTest { } /** - * BL-084: an endpoint from a profile names a server just as a typed one does. A container that - * happens to run locally under the default name must not take its place. + * BL-084: an endpoint from a profile names a server, and a container that happens to run + * locally under the default name must never take its place. A created profile also carries + * that default container name, so when the two are different servers nothing is reset. */ @Test - void anEndpointFromAProfileIsNotReplacedByTheLocalDefaultContainer() throws Exception { + void anEndpointFromAProfileIsNeverReplacedByTheLocalDefaultContainer() throws Exception { DockerClient local = dockerWith("floci", "running", "4566->4566/tcp"); - ResetCommand.Target target = targetWithProfile(local, "endpoint: http://remote-host:4566\n"); + ResetCommand.Target target = targetWithProfile(local, "container: floci\nendpoint: http://remote-host:4566\n"); + + assertNull(target.endpoint(), "neither server is picked"); + assertTrue(target.error().contains("The configured endpoint is http://remote-host:4566"), target.error()); + assertTrue(target.error().contains("container 'floci' is running at http://localhost:4566"), target.error()); + assertTrue(target.error().contains("so nothing was reset."), target.error()); + assertTrue(target.error().contains("Pass --endpoint or --container "), target.error()); + } + + /** The same holds with the container name left out of the profile, or a local port that differs. */ + @ParameterizedTest + @ValueSource(strings = {"endpoint: http://remote-host:4566\n", "endpoint: http://localhost:14566\n", + "container: floci\nendpoint: http://localhost:14566\nport: 14566\n"}) + void aRunningDefaultContainerThatIsAnotherServerStopsTheReset(String yaml) throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith("floci", "running", "4566->4566/tcp"), yaml); + + assertNull(target.endpoint(), yaml); + assertTrue(target.error().contains("They are different servers, so nothing was reset."), target.error()); + } + + /** No local container to contradict it: the endpoint the profile names is the server. */ + @ParameterizedTest + @CsvSource({"something-else, running, ''", "floci, exited, ''", "floci, running, '18080->8080/tcp'"}) + void anEndpointFromAProfileIsUsedWhenNoLocalContainerContradictsIt(String name, String state, String ports) throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith(name, state, ports), "endpoint: http://remote-host:4566\n"); assertNull(target.error(), target.error()); assertEquals("http://remote-host:4566", target.endpoint()); } - /** The same server is reset whether or not something runs locally under the default name. */ + /** The endpoint and the running container are one server: the profile is consistent, reset goes ahead. */ + @ParameterizedTest + @ValueSource(strings = {"http://localhost:14566", "http://127.0.0.1:14566", "http://localhost.floci.io:14566", "http://localhost:14566/"}) + void anEndpointThatIsTheRunningContainerIsUsed(String endpoint) throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith("floci", "running", "14566->4566/tcp"), + "container: floci\nport: 14566\nendpoint: " + endpoint + "\n"); + + assertNull(target.error(), target.error()); + assertEquals(endpoint, target.endpoint()); + } + @Test - void anEndpointFromAProfileResolvesTheSameWithOrWithoutALocalContainer() throws Exception { - String yaml = "endpoint: http://localhost:14566\n"; + void sameLocalServerComparesPortAndWhetherTheHostIsThisMachine() { + assertTrue(ResetCommand.sameLocalServer("http://localhost:4566", "http://127.0.0.1:4566")); + assertTrue(ResetCommand.sameLocalServer("http://localhost:4566", "https://localhost:4566/")); + assertFalse(ResetCommand.sameLocalServer("http://localhost:4566", "http://localhost:14566")); + assertFalse(ResetCommand.sameLocalServer("http://localhost:4566", "http://remote-host:4566")); + assertFalse(ResetCommand.sameLocalServer("http://localhost:4566", "not a url")); + } - ResetCommand.Target running = targetWithProfile(dockerWith("floci", "running", "4566->4566/tcp"), yaml); - ResetCommand.Target absent = targetWithProfile(dockerWith("something-else", "running", ""), yaml); - ResetCommand.Target stopped = targetWithProfile(dockerWith("floci", "exited", ""), yaml); + /** When docker cannot be asked, nothing contradicts the endpoint the user configured. */ + @Test + void aDockerFailureDoesNotOverrideAConfiguredEndpoint() throws Exception { + DockerClient broken = new DockerClient() { + @Override + public Optional inspectContainer(String name) throws DockerException { + throw new DockerException("Cannot connect to the Docker daemon"); + } + }; - assertEquals("http://localhost:14566", running.endpoint()); - assertEquals(running, absent); - assertEquals(running, stopped); + assertEquals("http://remote-host:4566", targetWithProfile(broken, "endpoint: http://remote-host:4566\n").endpoint()); } /** A profile that names a container is found through the container, endpoint or not. */ @@ -257,7 +301,32 @@ class ResetCommandTest { void yesWithAProfileEndpointPostsToThatEndpoint() throws Exception { Files.createDirectories(tempDir); Files.writeString(tempDir.resolve("p.yaml"), "endpoint: http://127.0.0.1:" + server.getAddress().getPort() + "\n"); - // A local default container on another port: resetting it would hit nothing and fail. + // A stopped container of the default name does not contradict the profile's endpoint. + ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("floci", "exited", ""), NOBODY); + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(new ByteArrayOutputStream())); + System.setErr(new PrintStream(errBuf)); + int exit; + try { + exit = new CommandLine(reset) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .execute("--yes", "--profile", "p"); + } finally { + System.setOut(out); + System.setErr(err); + } + + assertEquals(0, exit, errBuf.toString()); + assertEquals(List.of("POST /_floci/state/reset"), requests); + } + + /** End to end with --yes: two different servers, no request at all. */ + @Test + void yesWithAContradictingLocalContainerSendsNothing() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("p.yaml"), "endpoint: http://127.0.0.1:" + server.getAddress().getPort() + "\n"); int elsewhere; try (ServerSocket socket = new ServerSocket(0)) { elsewhere = socket.getLocalPort(); @@ -279,8 +348,9 @@ class ResetCommandTest { System.setErr(err); } - assertEquals(0, exit, errBuf.toString()); - assertEquals(List.of("POST /_floci/state/reset"), requests); + assertEquals(1, exit); + assertEquals(List.of(), requests, "nothing was reset"); + assertTrue(errBuf.toString().contains("They are different servers"), errBuf.toString()); } @Test