fix(reset): reset the server a profile or FLOCI_ENDPOINT names, not a local container of the default name (#64)

* fix(reset): reset the server a profile or FLOCI_ENDPOINT names, not a local container of the default name

With no container selected, an endpoint that came from a profile or the environment was replaced by the port of a container running locally under the default name, so reset --yes could wipe the wrong instance. Such an endpoint is now used as given, like a typed one.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(reset): reset nothing when the configured endpoint and a running default container are different servers

A profile carries a container name next to its endpoint, and every created profile is seeded with the default one. Using the endpoint outright could then reset a server other than a container the profile also names. When the two disagree neither is picked; the user says which with --endpoint or --container.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(reset): require a configured container to be running and to agree with a configured endpoint

A container that a profile or FLOCI_CONTAINER supplies is selected even when it has the default name, so a missing or stopped one resets nothing instead of falling back to the endpoint. A configured container and endpoint must be the same server. For a remote Docker host the published port is on the daemon's machine, so the endpoint is compared with that host, and a remote container without an endpoint is not reset through localhost.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(reset): treat a Docker daemon on this machine reached over TCP as local

tcp://127.0.0.1:2375 is this machine's daemon, so its published ports are local and a reset goes ahead as with a socket. The README sentence about exiting 1 now covers only the cases where reset refuses.
Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(reset): keep a Docker daemon reached over SSH remote, loopback address or not

ssh://user@127.0.0.1:2222 is a forwarded port to a VM or another machine. Treating it as local would let reset --yes go to localhost on this machine.
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-11 21:10:58 -05:00
1 parent 97eaa5e820
commit 885e49f81a
3 files changed
+499 -26

No files matched your search

+15 -4
View File
@@ -724,9 +724,20 @@ 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 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. `--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 Reset never guesses which server to wipe:
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. - An `--endpoint` you type is used as given.
- A container you select (`--container`, a profile's `container`, or `FLOCI_CONTAINER`) has to be
running. If it is missing or stopped, nothing is reset.
- An endpoint a profile or `FLOCI_ENDPOINT` supplies is used when no container is selected. A
container that happens to run locally under the default name never takes its place.
- When both a container and an endpoint are configured, they have to be the same server. If they
are not, nothing is reset and you are asked to pass `--endpoint` or `--container`.
- A container on a remote Docker host (`DOCKER_HOST=tcp://other-host:...` or `ssh://...`) is only
reset through an endpoint, since its published port is not on this machine. A daemon on this
machine reached over TCP (`tcp://127.0.0.1:2375`) is local.
When reset refuses to choose a server, the command exits 1 without sending anything.
### `floci config` ### `floci config`
@@ -936,7 +947,7 @@ Where a command's codes carry a specific meaning a script can rely on:
| `update` | updated, or already up to date | the update failed, or `--version` is not a release version; the binary is unchanged | bad flag | | `update` | updated, or already up to date | the update failed, or `--version` is not a release version; the binary is unchanged | bad flag |
| `start`, `restart` | started (and ready, unless `--detach`) | Docker, the image, the port or readiness failed | `--port`, `--pull` or the namespace is not valid | | `start`, `restart` | started (and ready, unless `--detach`) | Docker, the image, the port or readiness failed | `--port`, `--pull` or the namespace is not valid |
| `stop` | stopped, or was not running | no such container, or Docker failed | bad flag or profile | | `stop` | stopped, or was not running | no such container, or Docker failed | bad flag or profile |
| `reset` | state reset | declined, not available on this server, or no running instance to reset | no terminal to ask on and no `--yes` | | `reset` | state reset | declined, not available on this server, no running instance to reset, or the configuration names two different servers | no terminal to ask on and no `--yes` |
| `config validate` | no errors (warnings allowed) | errors found, or the file cannot be read | bad flag | | `config validate` | no errors (warnings allowed) | errors found, or the file cannot be read | bad flag |
| `config profile ...` | done | not found, already exists, cannot be read, `--port` is out of range, or (for `edit`) no editor is set, the editor failed or the file no longer parses | the profile name is not valid | | `config profile ...` | done | not found, already exists, cannot be read, `--port` is out of range, or (for `edit`) no editor is set, the editor failed or the file no longer parses | the profile name is not valid |
| `config default-product` | saved | not `aws`, `gcp`, `az` or `oci`, or the file cannot be written | bad flag | | `config default-product` | saved | not `aws`, `gcp`, `az` or `oci`, or the file cannot be written | bad flag |
@@ -2,6 +2,7 @@ package io.floci.cli.commands;
import io.floci.cli.GlobalOptions; import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile; import io.floci.cli.ProductProfile;
import io.floci.cli.config.ProfileDefaultValueProvider;
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.http.FlociException; import io.floci.cli.http.FlociException;
@@ -11,12 +12,16 @@ import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer; import io.floci.cli.output.Printer;
import picocli.CommandLine.*; import picocli.CommandLine.*;
import picocli.CommandLine.Model.CommandSpec;
import java.io.Console; import java.io.Console;
import java.net.URI;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.function.UnaryOperator;
@Command( @Command(
name = "reset", name = "reset",
@@ -43,14 +48,24 @@ public class ResetCommand implements Callable<Integer> {
/** Test seam: {@code docker} answers the container lookup and {@code prompt} the confirmation. */ /** Test seam: {@code docker} answers the container lookup and {@code prompt} the confirmation. */
public ResetCommand(ProductProfile profile, DockerClient docker, Prompt prompt) { public ResetCommand(ProductProfile profile, DockerClient docker, Prompt prompt) {
this(profile, docker, prompt, System::getenv);
}
/** Test seam: {@code env} answers whether {@code <PREFIX>_CONTAINER} selected the container. */
public ResetCommand(ProductProfile profile, DockerClient docker, Prompt prompt, UnaryOperator<String> env) {
this.profile = profile; this.profile = profile;
this.global = new GlobalOptions(profile); this.global = new GlobalOptions(profile, env);
this.docker = docker; this.docker = docker;
this.prompt = prompt; this.prompt = prompt;
this.env = env;
} }
private final DockerClient docker; private final DockerClient docker;
private final Prompt prompt; private final Prompt prompt;
private final UnaryOperator<String> env;
@Spec
CommandSpec spec;
/** The person at the terminal, when there is one. */ /** The person at the terminal, when there is one. */
public interface Prompt { public interface Prompt {
@@ -82,16 +97,28 @@ public class ResetCommand implements Callable<Integer> {
/** /**
* Where this reset acts. Reset deletes data, so unlike the read-only commands it never * 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 * guesses. In order:
* chose must be found running. Falling back to the configured endpoint, as * <ol>
* {@link GlobalOptions#resolvedEndpoint} does, is right only for the default container: there * <li>A typed {@code --endpoint} is used as given.</li>
* the configured endpoint names the same default instance. * <li>A typed {@code --container} must be found running, and is reset.</li>
* <li>A container that a profile or {@code <PREFIX>_CONTAINER} supplies must be found
* running too. If the profile or environment also names an endpoint other than the
* default, the two have to be the same server.</li>
* <li>With no container supplied, an endpoint from a profile or the environment is used,
* unless a container of the default name runs here and is a different server.</li>
* <li>With nothing selected at all, the default container is looked up, falling back to
* the default endpoint, which names the same default instance.</li>
* </ol>
* Whenever two things that were configured point at different servers, nothing is reset.
*/ */
public Target target() { public Target target() {
if (global.typed("--endpoint")) return new Target(global.endpoint, null); if (global.typed("--endpoint")) return new Target(global.endpoint, null);
boolean chosen = global.typed("--container") || !profile.defaultContainer().equals(global.container); boolean typedContainer = global.typed("--container");
boolean chosen = typedContainer || containerSupplied();
boolean endpointNamed = namesAServer(global.endpoint, profile);
String how = "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector() String how = "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector()
+ "' to check it, or pass --endpoint <url> to name the server to reset."; + "' to check it, or pass --endpoint <url> to name the server to reset.";
Optional<DockerClient.ContainerInfo> info; Optional<DockerClient.ContainerInfo> info;
try { try {
info = docker.inspectContainer(global.container); info = docker.inspectContainer(global.container);
@@ -99,26 +126,128 @@ public class ResetCommand implements Callable<Integer> {
if (chosen) { if (chosen) {
return new Target(null, "Could not look up container '" + global.container + "': " + e.getMessage() + how); return new Target(null, "Could not look up container '" + global.container + "': " + e.getMessage() + how);
} }
info = Optional.empty(); info = Optional.empty(); // nothing known to contradict what was configured
}
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);
} }
boolean running = info.isPresent() && "running".equals(info.get().state());
// By the emulator's own port inside the container, which never changes; the configured // 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. // 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()); Optional<String> published = running
if (chosen && published.isEmpty()) { ? GlobalOptions.publishedEndpoint(info.get().ports(), profile.defaultPort())
// No port to find it by: the configured endpoint may well be another instance. : Optional.empty();
return new Target(null, "Container '" + global.container
+ "' publishes no port for the emulator, so nothing was reset." + how); if (chosen) {
if (info.isEmpty()) {
return new Target(null, "Container '" + global.container + "' not found, so nothing was reset." + how);
}
if (!running) {
return new Target(null, "Container '" + global.container + "' is not running (state: "
+ info.get().state() + "), so nothing was reset." + how);
}
if (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); if (published.isEmpty()) {
// Nothing runs here under that name: the configured endpoint is all there is.
return new Target(global.endpoint, null);
}
DockerClient.DockerHost daemon = docker.daemonHost();
boolean remote = isRemote(daemon);
if (endpointNamed && !typedContainer) {
// A container and an endpoint were both configured: they have to be one server.
if (sameServer(published.get(), global.endpoint, daemon)) return new Target(global.endpoint, null);
return new Target(null, "The configured endpoint is " + global.endpoint + ", but container '"
+ global.container + "' is running at " + whereItRuns(published.get(), daemon)
+ ". They are different servers, so nothing was reset."
+ "\nPass --endpoint <url> or --container <name> to say which one to reset.");
}
if (remote) {
// The port was published on the daemon's machine. 'localhost' here would be this
// one, and whatever answers on that port here is not the container that was found.
return new Target(null, "Container '" + global.container + "' runs on the remote Docker host "
+ daemon.raw() + ", so its address is not known here and nothing was reset."
+ "\nPass --endpoint <url> with the address the emulator is reached at.");
}
return new Target(published.get(), null);
}
// Whether something other than the default name picked the container: a profile that sets
// one (every created profile does), <PREFIX>_CONTAINER, or simply a different name.
private boolean containerSupplied() {
if (!profile.defaultContainer().equals(global.container)) return true;
if (env.apply(profile.envVar("CONTAINER")) != null) return true;
return global.profile != null
&& ProfileDefaultValueProvider.of(spec).resolved().map(p -> p.container != null).orElse(false);
}
private static String whereItRuns(String published, DockerClient.DockerHost daemon) {
return isRemote(daemon)
? "port " + URI.create(published).getPort() + " of the remote Docker host " + daemon.raw()
: published;
}
/**
* Whether the daemon runs on another machine. Docker reached over TCP usually does, but
* {@code tcp://127.0.0.1:2375} is this machine's daemon on a socket of another kind, and its
* published ports are local like any other's. SSH is always remote: a loopback address there
* ({@code ssh://user@127.0.0.1:2222}) is a forwarded port to a VM or another machine, not a
* daemon on this one.
*/
public static boolean isRemote(DockerClient.DockerHost daemon) {
if (daemon.kind() != DockerClient.Kind.TCP) return false;
try {
URI address = URI.create(daemon.raw());
if ("ssh".equalsIgnoreCase(address.getScheme())) return true;
String host = address.getHost();
return host == null || !thisMachine(host);
} catch (IllegalArgumentException | NullPointerException e) {
return true; // cannot tell: the careful answer
}
}
private static boolean thisMachine(String host) {
String name = host.toLowerCase(Locale.ROOT);
return name.equals("localhost") || name.equals("127.0.0.1") || name.equals("[::1]") || name.equals("::1")
|| name.equals("0.0.0.0") || name.equals("localhost.floci.io");
}
/**
* Whether {@code configured} is the server a container publishes at {@code published}
* ({@code http://localhost:<port>} as docker reports it). The port has to match. For a daemon
* on this machine the configured host has to mean this machine; for a remote one it has to be
* the daemon's host, since that is where the port was published.
*/
public static boolean sameServer(String published, String configured, DockerClient.DockerHost daemon) {
try {
URI there = URI.create(withoutTrailingSlashes(configured));
if (URI.create(published).getPort() != there.getPort()) return false;
String host = there.getHost() == null ? "" : there.getHost();
if (isRemote(daemon)) {
String daemonHost = URI.create(daemon.raw()).getHost();
return daemonHost != null && daemonHost.equalsIgnoreCase(host);
}
return thisMachine(host);
} catch (IllegalArgumentException | NullPointerException 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
* does not make it a different one.
*/
public static boolean namesAServer(String endpoint, ProductProfile product) {
return endpoint != null && !withoutTrailingSlashes(endpoint).equals(product.defaultEndpoint());
}
private static String withoutTrailingSlashes(String url) {
String trimmed = url.strip();
while (trimmed.endsWith("/")) trimmed = trimmed.substring(0, trimmed.length() - 1);
return trimmed;
} }
@Override @Override
@@ -7,12 +7,15 @@ import io.floci.cli.commands.ResetCommand;
import io.floci.cli.config.ProfileDefaultValueProvider; import io.floci.cli.config.ProfileDefaultValueProvider;
import io.floci.cli.config.ProfileStore; import io.floci.cli.config.ProfileStore;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerClient.DockerHost;
import io.floci.cli.docker.DockerClient.Kind;
import io.floci.cli.docker.DockerException; import io.floci.cli.docker.DockerException;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource; import org.junit.jupiter.params.provider.ValueSource;
import picocli.CommandLine; import picocli.CommandLine;
@@ -20,11 +23,13 @@ import java.io.ByteArrayOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@@ -127,7 +132,14 @@ class ResetCommandTest {
// ---- which server a reset acts on ------------------------------------------------------- // ---- which server a reset acts on -------------------------------------------------------
private static final DockerHost LOCAL = new DockerHost(Kind.UNIX, "/var/run/docker.sock", null);
private static DockerClient dockerWith(String name, String state, String ports) { private static DockerClient dockerWith(String name, String state, String ports) {
return dockerWith(name, state, ports, LOCAL);
}
/** A docker reached through {@code daemon} that holds one container. */
private static DockerClient dockerWith(String name, String state, String ports, DockerHost daemon) {
return new DockerClient() { return new DockerClient() {
@Override @Override
public Optional<ContainerInfo> inspectContainer(String asked) { public Optional<ContainerInfo> inspectContainer(String asked) {
@@ -135,6 +147,11 @@ class ResetCommandTest {
? Optional.of(new ContainerInfo("abc", name, "floci/floci:latest", state, ports)) ? Optional.of(new ContainerInfo("abc", name, "floci/floci:latest", state, ports))
: Optional.empty(); : Optional.empty();
} }
@Override
public DockerHost daemonHost() {
return daemon;
}
}; };
} }
@@ -167,6 +184,322 @@ class ResetCommandTest {
assertNull(target.error()); assertNull(target.error());
} }
private ResetCommand.Target targetWithProfile(DockerClient docker, String yaml, String... args) throws Exception {
Files.createDirectories(tempDir);
Files.writeString(tempDir.resolve("p.yaml"), yaml);
ResetCommand reset = new ResetCommand(ProductProfile.AWS, docker, NOBODY);
List<String> all = new ArrayList<>(List.of("--profile", "p"));
all.addAll(List.of(args));
new CommandLine(reset)
.setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir)))
.parseArgs(all.toArray(String[]::new));
return reset.target();
}
/**
* 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 anEndpointFromAProfileIsNeverReplacedByTheLocalDefaultContainer() throws Exception {
DockerClient local = dockerWith("floci", "running", "4566->4566/tcp");
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 <url> or --container <name>"), 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 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 forALocalDaemonTheSameServerIsTheSamePortOnThisMachine() {
assertTrue(ResetCommand.sameServer("http://localhost:4566", "http://127.0.0.1:4566", LOCAL));
assertTrue(ResetCommand.sameServer("http://localhost:4566", "https://localhost:4566/", LOCAL));
assertFalse(ResetCommand.sameServer("http://localhost:4566", "http://localhost:14566", LOCAL));
assertFalse(ResetCommand.sameServer("http://localhost:4566", "http://remote-host:4566", LOCAL));
assertFalse(ResetCommand.sameServer("http://localhost:4566", "not a url", LOCAL));
}
/** A remote daemon publishes the port on its own machine: that host, not this one, is the server's. */
@ParameterizedTest
@CsvSource({
"ssh://deploy@remote-host, http://remote-host:14566, true",
"tcp://remote-host:2375, http://remote-host:14566, true",
"tcp://remote-host:2375, http://REMOTE-HOST:14566/, true",
"ssh://deploy@remote-host, http://localhost:14566, false",
"ssh://deploy@remote-host, http://other-host:14566, false",
"ssh://deploy@remote-host, http://remote-host:4566, false"})
void forARemoteDaemonTheSameServerIsTheSamePortOnTheDaemonsHost(String dockerHost, String endpoint, boolean same) {
DockerHost remote = DockerClient.parseDockerHost(dockerHost, null, "Linux");
assertEquals(same, ResetCommand.sameServer("http://localhost:14566", endpoint, remote));
}
/** Docker on this machine reached over TCP is local: its published ports are this machine's. */
@ParameterizedTest
@CsvSource({
"tcp://127.0.0.1:2375, false",
"tcp://localhost:2375, false",
"tcp://[::1]:2376, false",
"unix:///var/run/docker.sock, false",
"tcp://remote-host:2375, true",
"ssh://deploy@remote-host, true",
"ssh://user@127.0.0.1:2222, true",
"ssh://localhost, true",
"tcp://192.168.1.20:2375, true"})
void onlyADaemonOnAnotherMachineIsRemote(String dockerHost, boolean remote) {
assertEquals(remote, ResetCommand.isRemote(DockerClient.parseDockerHost(dockerHost, null, "Linux")));
}
@Test
void aLocalTcpDaemonResetsItsContainerLikeASocketOne() throws Exception {
DockerHost localTcp = DockerClient.parseDockerHost("tcp://127.0.0.1:2375", null, "Linux");
ResetCommand.Target plain = targetOf(dockerWith("floci", "running", "4566->4566/tcp", localTcp));
ResetCommand.Target withProfile = targetWithProfile(dockerWith("floci", "running", "14566->4566/tcp", localTcp),
"container: floci\nport: 14566\nendpoint: http://localhost:14566\n");
assertEquals("http://localhost:4566", plain.endpoint());
assertNull(withProfile.error(), withProfile.error());
assertEquals("http://localhost:14566", withProfile.endpoint());
assertTrue(ResetCommand.sameServer("http://localhost:14566", "http://localhost:14566", localTcp));
}
/** SSH to a loopback address is a forwarded port to somewhere else: never reset through localhost. */
@Test
void anSshDaemonOnALoopbackAddressIsStillRemote() {
DockerHost forwarded = DockerClient.parseDockerHost("ssh://user@127.0.0.1:2222", null, "Linux");
ResetCommand.Target target = targetOf(dockerWith("floci", "running", "4566->4566/tcp", forwarded));
assertNull(target.endpoint());
assertTrue(target.error().contains("runs on the remote Docker host ssh://user@127.0.0.1:2222"), target.error());
}
/** A profile for an instance on a remote Docker host: its endpoint and its container are one server. */
@Test
void aRemoteInstanceWhoseEndpointMatchesIsReset() throws Exception {
DockerHost remote = DockerClient.parseDockerHost("ssh://deploy@remote-host", null, "Linux");
ResetCommand.Target target = targetWithProfile(dockerWith("floci", "running", "14566->4566/tcp", remote),
"container: floci\nport: 14566\nendpoint: http://remote-host:14566\n");
assertNull(target.error(), target.error());
assertEquals("http://remote-host:14566", target.endpoint());
}
/** On a remote daemon 'localhost:<port>' is this machine, not the container: without an endpoint nothing is reset. */
@ParameterizedTest
@ValueSource(strings = {"floci", "floci-b"})
void aRemoteContainerWithoutAnEndpointResetsNothing(String container) {
DockerHost remote = DockerClient.parseDockerHost("tcp://remote-host:2375", null, "Linux");
List<String> args = container.equals("floci") ? List.of() : List.of("--container", container);
ResetCommand.Target target = targetOf(dockerWith(container, "running", "4566->4566/tcp", remote), args.toArray(String[]::new));
assertNull(target.endpoint());
assertTrue(target.error().contains("runs on the remote Docker host tcp://remote-host:2375"), target.error());
assertTrue(target.error().contains("Pass --endpoint <url>"), target.error());
}
/**
* A profile that names a container, even one with the default name, has selected it: when it is
* not running, the profile's endpoint is not a fallback and nothing is reset.
*/
@ParameterizedTest
@CsvSource({"something-else, running, not found", "floci, exited, is not running"})
void aContainerFromAProfileMustBeRunningEvenWithTheDefaultName(String name, String state, String reason) throws Exception {
ResetCommand.Target target = targetWithProfile(dockerWith(name, state, ""),
"container: floci\nendpoint: http://remote-host:4566\n");
assertNull(target.endpoint());
assertTrue(target.error().contains("Container 'floci' " + reason), target.error());
assertTrue(target.error().contains("so nothing was reset."), target.error());
}
/** The environment selects a container the same way a profile does. */
@Test
void aContainerFromTheEnvironmentMustBeRunningToo() {
ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("something-else", "running", ""), NOBODY,
Map.of("FLOCI_CONTAINER", "floci", "FLOCI_ENDPOINT", "http://remote-host:4566")::get);
new CommandLine(reset).parseArgs();
ResetCommand.Target target = reset.target();
assertNull(target.endpoint());
assertTrue(target.error().contains("Container 'floci' not found, so nothing was reset."), target.error());
}
/** FLOCI_ENDPOINT alone names a server, like an endpoint-only profile. */
@Test
void anEndpointFromTheEnvironmentIsUsedAsGiven() {
ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("something-else", "running", ""), NOBODY,
Map.of("FLOCI_ENDPOINT", "http://remote-host:4566")::get);
new CommandLine(reset).parseArgs();
assertEquals("http://remote-host:4566", reset.target().endpoint());
}
/** When docker cannot be asked, nothing contradicts the endpoint the user configured. */
@Test
void aDockerFailureDoesNotOverrideAConfiguredEndpoint() throws Exception {
DockerClient broken = new DockerClient() {
@Override
public Optional<ContainerInfo> inspectContainer(String name) throws DockerException {
throw new DockerException("Cannot connect to the Docker daemon");
}
};
assertEquals("http://remote-host:4566", targetWithProfile(broken, "endpoint: http://remote-host:4566\n").endpoint());
}
/** A profile's container and its endpoint have to be one server, whatever the container is called. */
@Test
void aProfileWhoseContainerAndEndpointDisagreeResetsNothing() throws Exception {
ResetCommand.Target target = targetWithProfile(dockerWith("floci-b", "running", "24566->4566/tcp"),
"container: floci-b\nendpoint: http://localhost:14566\n");
assertNull(target.endpoint());
assertTrue(target.error().contains("container 'floci-b' is running at http://localhost:24566"), target.error());
assertTrue(target.error().contains("They are different servers, so nothing was reset."), target.error());
}
/** A profile made by 'config profile create --container --port' keeps the default endpoint: no conflict. */
@Test
void aProfileWithTheDefaultEndpointIsFoundThroughItsContainer() throws Exception {
ResetCommand.Target target = targetWithProfile(dockerWith("floci-b", "running", "24566->4566/tcp"),
"container: floci-b\nport: 24566\nendpoint: http://localhost:4566\n");
assertNull(target.error(), target.error());
assertEquals("http://localhost:24566", target.endpoint());
}
/** A typed flag wins over the profile's endpoint, as everywhere else. */
@Test
void typedFlagsWinOverAProfilesEndpoint() throws Exception {
String yaml = "endpoint: http://remote-host:4566\n";
ResetCommand.Target typedEndpoint = targetWithProfile(dockerWith("floci", "running", "4566->4566/tcp"), yaml,
"--endpoint", "http://other-host:4566");
ResetCommand.Target typedContainer = targetWithProfile(dockerWith("floci-b", "running", "24566->4566/tcp"), yaml,
"--container", "floci-b");
assertEquals("http://other-host:4566", typedEndpoint.endpoint());
assertEquals("http://localhost:24566", typedContainer.endpoint());
}
/** The environment's endpoint counts the same way; what matters is that it is not the default. */
@ParameterizedTest
@CsvSource({
"http://remote-host:4566, true",
"http://localhost:14566, true",
"https://localhost:4566, true",
"http://localhost:4566, false",
"http://localhost:4566/, false",
"' http://localhost:4566// ', false"})
void anEndpointOtherThanTheDefaultNamesAServer(String endpoint, boolean names) {
assertEquals(names, ResetCommand.namesAServer(endpoint, ProductProfile.AWS));
}
@Test
void eachProductHasItsOwnDefaultEndpoint() {
assertFalse(ResetCommand.namesAServer("http://localhost:4588", ProductProfile.GCP));
assertTrue(ResetCommand.namesAServer("http://localhost:4566", ProductProfile.GCP));
assertFalse(ResetCommand.namesAServer(null, ProductProfile.OCI));
}
/** End to end with --yes: the request goes to the profile's server, not to the local container's port. */
@Test
void yesWithAProfileEndpointPostsToThatEndpoint() throws Exception {
Files.createDirectories(tempDir);
Files.writeString(tempDir.resolve("p.yaml"), "endpoint: http://127.0.0.1:" + server.getAddress().getPort() + "\n");
// 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();
}
ResetCommand reset = new ResetCommand(ProductProfile.AWS,
dockerWith("floci", "running", elsewhere + "->4566/tcp"), 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(1, exit);
assertEquals(List.of(), requests, "nothing was reset");
assertTrue(errBuf.toString().contains("They are different servers"), errBuf.toString());
}
@Test @Test
void theDefaultContainerIsFoundThroughItsPortMapping() { void theDefaultContainerIsFoundThroughItsPortMapping() {
ResetCommand.Target target = targetOf(dockerWith("floci", "running", "14566->4566/tcp")); ResetCommand.Target target = targetOf(dockerWith("floci", "running", "14566->4566/tcp"));