diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index aaceb30..4d79b83 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -5,6 +5,10 @@ import io.floci.cli.ProductProfile; import io.floci.cli.config.ProfileDefaultValueProvider; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.CheckResult; +import io.floci.cli.doctor.CheckStatus; +import io.floci.cli.doctor.checks.DockerSocketCheck; +import io.floci.cli.doctor.checks.PortAvailableCheck; import io.floci.cli.output.Ansi; import io.floci.cli.output.Printer; import picocli.CommandLine; @@ -33,11 +37,19 @@ public class StartCommand implements Callable { @Mixin protected GlobalOptions global; + private final DockerClient docker; + public StartCommand() { this(ProductProfile.AWS); } protected StartCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + /** Test seam: {@code docker} answers every docker call this start makes. */ + public StartCommand(ProductProfile profile, DockerClient docker) { + this.docker = docker; this.profile = profile; this.global = new GlobalOptions(profile); this.port = profile.defaultPort(); @@ -167,7 +179,8 @@ public class StartCommand implements Callable { * a directory it cannot write to itself. */ public String preparePersistDir() { - return preparePersistDir(DockerClient.dockerHost()); + // The daemon docker resolved, so a remote context counts as remote here too. + return preparePersistDir(docker.daemonHost()); } /** {@link #preparePersistDir()} for a daemon reached through {@code daemon}; the test seam. */ @@ -282,7 +295,6 @@ public class StartCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); - DockerClient docker = new DockerClient(); String invalid = validationError(); if (invalid != null) { @@ -290,7 +302,11 @@ public class StartCommand implements Callable { return 2; } - String unwritable = preparePersistDir(); + // Asked once: the persist directory, the port probe and the bind source all turn on + // whether the daemon docker will talk to is on this machine. + DockerClient.DockerHost daemon = docker.daemonHost(); + + String unwritable = preparePersistDir(daemon); if (unwritable != null) { printer.error(unwritable); return 1; @@ -315,7 +331,16 @@ public class StartCommand implements Callable { printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/"); return 1; } - printer.error("Failed to inspect container: " + e.getMessage()); + printer.error("Failed to inspect container: " + e.getMessage() + socketGuidance(daemon)); + return 1; + } + + // Checked here rather than left to 'docker run', whose bind error names neither the port + // flag nor how to find what holds the port. A remote daemon publishes on another machine, + // so a local probe would say nothing about it. + if (probesPortLocally(daemon, port) && !PortAvailableCheck.isPortFree(port)) { + printer.error("Port " + port + " is already in use by another process.\n" + + "Run 'lsof -i :" + port + "' to find it, or pass --port to use a different port."); return 1; } @@ -328,7 +353,7 @@ public class StartCommand implements Callable { return 1; } - List args = dockerRunArgs(DockerClient.dockerSocketRunArgs(), DockerClient.dockerHost()); + List args = dockerRunArgs(DockerClient.dockerSocketRunArgs(), daemon); try { printer.println("Starting " + Ansi.gold(profile.displayName()) + " container..."); @@ -356,4 +381,24 @@ public class StartCommand implements Callable { wait.timeout = "30s"; return wait.call(); } + + /** + * Whether a busy local {@code port} would stop this start. Not for a remote daemon, which + * publishes the port on its own machine, and not for a number that is no port at all: + * docker reports that one, and a socket cannot be opened on it to probe. + */ + public static boolean probesPortLocally(DockerClient.DockerHost daemon, int port) { + return daemon.kind() != DockerClient.Kind.TCP && port >= 1 && port <= 65535; + } + + /** + * What to do when {@code daemon} is unreachable because its local socket is missing, or + * nothing: docker's own error ("Cannot connect to the Docker daemon") does not say. + */ + public static String socketGuidance(DockerClient.DockerHost daemon) { + CheckResult socket = DockerSocketCheck.check(daemon); + return socket.status() == CheckStatus.fail + ? "\n" + socket.message() + ".\n" + socket.fix() + ", then re-run the command." + : ""; + } } diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index 337a596..ad9ff2f 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -356,7 +356,7 @@ public class DockerClient { } } - /** How the Docker daemon is reached, resolved from the environment. */ + /** How the Docker daemon is reached. {@code TCP} is any remote daemon: tcp, http(s) or ssh. */ public enum Kind { UNIX, TCP, NPIPE } /** @@ -388,7 +388,10 @@ public class DockerClient { if (value.startsWith("unix://")) { return new DockerHost(Kind.UNIX, value.substring("unix://".length()), value); } - if (value.startsWith("tcp://") || value.startsWith("http://") || value.startsWith("https://")) { + // ssh:// is as remote as tcp://: the daemon, its ports and its bind paths are on + // another machine. Read as a bare path it would have been taken for a local socket. + if (value.startsWith("tcp://") || value.startsWith("http://") || value.startsWith("https://") + || value.startsWith("ssh://")) { return new DockerHost(Kind.TCP, null, value); } if (value.startsWith("npipe://")) { @@ -408,6 +411,26 @@ public class DockerClient { return new DockerHost(Kind.UNIX, DEFAULT_UNIX_SOCKET, null); } + /** + * The daemon the docker CLI will actually talk to. {@link #dockerHost()} only reads the + * environment, which does not show a context selected with {@code DOCKER_CONTEXT} or + * {@code docker context use}; docker itself reports the endpoint it resolved. An explicit + * {@code DOCKER_HOST} wins over any context, so it is answered without asking. + */ + public DockerHost daemonHost() { + DockerHost fromEnvironment = dockerHost(); + if (fromEnvironment.raw() != null) return fromEnvironment; + try { + String endpoint = run("docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}").trim(); + if (!endpoint.isBlank()) { + return parseDockerHost(endpoint, null, System.getProperty("os.name", "")); + } + } catch (DockerException e) { + // Podman, or a docker without contexts: the environment is all there is. + } + return fromEnvironment; + } + /** Back-compat accessor for the resolved local socket/pipe path (null for TCP). */ public static String socketPath() { return dockerHost().socketPath(); diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java index a4620f0..61c94da 100644 --- a/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java @@ -16,7 +16,11 @@ public class DockerSocketCheck implements Check { @Override public CheckResult run(String endpoint, String container) { - DockerClient.DockerHost host = DockerClient.dockerHost(); + return check(DockerClient.dockerHost()); + } + + /** The check for a daemon reached through {@code host}; pure, so start can ask about the daemon it resolved. */ + public static CheckResult check(DockerClient.DockerHost host) { switch (host.kind()) { case NPIPE: return CheckResult.ok("docker.socket", "Windows named pipe (" + host.socketPath() + ")"); @@ -30,9 +34,11 @@ public class DockerSocketCheck implements Check { return CheckResult.ok("docker.socket", socketPath + " accessible"); } String os = System.getProperty("os.name", "").toLowerCase(); + // The socket is missing, so the daemon is not running: permissions are not the problem + // (a socket that exists but refuses this user passes this check and fails docker.daemon). String fix = os.contains("mac") ? "Open Docker Desktop — the socket is created when Docker Desktop is running" - : "sudo chmod 666 " + socketPath + " OR add your user to the docker group"; - return CheckResult.fail("docker.socket", socketPath + " not found or not accessible", fix); + : "Start the Docker daemon ('sudo systemctl start docker', or open Docker Desktop)"; + return CheckResult.fail("docker.socket", socketPath + " not found", fix); } } diff --git a/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java index 545ac1c..26772e9 100644 --- a/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java @@ -6,8 +6,13 @@ import io.floci.cli.doctor.Check; import io.floci.cli.doctor.CheckResult; import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; import java.net.ServerSocket; +import java.net.Socket; import java.net.URI; +import java.util.Locale; +import java.util.function.BooleanSupplier; public class PortAvailableCheck implements Check { @@ -46,9 +51,38 @@ public class PortAvailableCheck implements Check { "Run 'lsof -i :" + port + "' to identify the process, or start Floci with --port "); } - private static boolean isPortFree(int port) { + /** + * False only when {@code port} is known to be taken. A bind that fails on a privileged port + * may just be this user lacking the right to bind it (Linux below 1024), while the Docker + * daemon can publish it fine, so there the port counts as taken only if something answers on it. + */ + public static boolean isPortFree(int port) { try (ServerSocket s = new ServerSocket(port)) { return true; + } catch (IOException e) { + return !takenAfterFailedBind(port, e.getMessage(), () -> listensOnLoopback(port)); + } + } + + /** The ports a user may be refused for lack of privilege rather than because they are taken. */ + static final int FIRST_UNPRIVILEGED_PORT = 1024; + + /** + * What a failed bind of {@code port} means, given the bind's error {@code message}. An + * "address already in use" error is the answer on any port; {@code listening} is asked only + * for a privileged port whose error says something else (permission denied). + */ + public static boolean takenAfterFailedBind(int port, String message, BooleanSupplier listening) { + if (port >= FIRST_UNPRIVILEGED_PORT) return true; + if (message != null && message.toLowerCase(Locale.ROOT).contains("in use")) return true; + return listening.getAsBoolean(); + } + + /** Whether something accepts a connection on {@code port} on this machine. */ + public static boolean listensOnLoopback(int port) { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), port), 500); + return true; } catch (IOException e) { return false; } diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java new file mode 100644 index 0000000..0930b69 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -0,0 +1,291 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.StartCommand; +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.doctor.checks.PortAvailableCheck; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** BL-058: start reports a busy host port itself, before pulling or running anything. */ +class StartPreflightTest { + + private static final DockerHost LOCAL = new DockerHost(Kind.UNIX, "/var/run/docker.sock", null); + private static final DockerHost REMOTE = new DockerHost(Kind.TCP, null, "tcp://build-host:2375"); + + @TempDir + Path tempDir; + + /** A docker that has no container, records what start asked of it, and is reached through {@code daemon}. */ + private static class FakeDocker extends DockerClient { + final DockerHost daemon; + final List calls = new ArrayList<>(); + final List runArgs = new ArrayList<>(); + + FakeDocker(DockerHost daemon) { + this.daemon = daemon; + } + + @Override + public DockerHost daemonHost() { + return daemon; + } + + @Override + public Optional inspectContainer(String name) throws DockerException { + return Optional.empty(); + } + + @Override + public void pull(String image, String policy) { + calls.add("pull"); + } + + @Override + public String startContainer(List args) { + runArgs.addAll(args); + calls.add("run"); + return "0123456789abcdef"; + } + } + + private record Out(int exit, String err) {} + + private static Out start(DockerClient docker, String... args) { + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(new ByteArrayOutputStream())); + System.setErr(new PrintStream(errBuf)); + try { + int exit = new CommandLine(new StartCommand(ProductProfile.GCP, docker)).execute(args); + return new Out(exit, errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void aBusyPortStopsTheStartWithAHint() throws Exception { + FakeDocker docker = new FakeDocker(LOCAL); + try (ServerSocket taken = new ServerSocket()) { + taken.bind(new InetSocketAddress(0)); + int port = taken.getLocalPort(); + + Out r = start(docker, "--port", String.valueOf(port), "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("Port " + port + " is already in use"), r.err()); + assertTrue(r.err().contains("--port "), r.err()); + assertEquals(List.of(), docker.calls, "nothing is pulled or run for a start that cannot bind"); + } + } + + @Test + void aFreePortGoesOnToPullAndRun() throws Exception { + FakeDocker docker = new FakeDocker(LOCAL); + int port; + try (ServerSocket free = new ServerSocket(0)) { + port = free.getLocalPort(); + } + + Out r = start(docker, "--port", String.valueOf(port), "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(0, r.exit(), r.err()); + assertEquals(List.of("pull", "run"), docker.calls); + } + + /** The port is published on the daemon's machine, so what holds it here is beside the point. */ + @Test + void aBusyLocalPortDoesNotBlockARemoteDaemon() throws Exception { + FakeDocker docker = new FakeDocker(REMOTE); + try (ServerSocket taken = new ServerSocket()) { + taken.bind(new InetSocketAddress(0)); + + Out r = start(docker, "--port", String.valueOf(taken.getLocalPort()), + "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(0, r.exit(), r.err()); + assertEquals(List.of("pull", "run"), docker.calls); + } + } + + /** A daemon reached over SSH (DOCKER_HOST or a context) is remote too: its ports are not this machine's. */ + @Test + void aDaemonReachedOverSshIsNotProbedLocally() throws Exception { + DockerHost ssh = DockerClient.parseDockerHost("ssh://deploy@build-host", null, "Linux"); + assertEquals(Kind.TCP, ssh.kind()); + assertEquals("ssh://deploy@build-host", ssh.raw()); + assertFalse(StartCommand.probesPortLocally(ssh, 4588)); + + FakeDocker docker = new FakeDocker(ssh); + try (ServerSocket taken = new ServerSocket()) { + taken.bind(new InetSocketAddress(0)); + + Out r = start(docker, "--port", String.valueOf(taken.getLocalPort()), + "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(0, r.exit(), r.err()); + assertEquals(List.of("pull", "run"), docker.calls); + } + } + + /** + * One answer for the whole start: a daemon that is remote only through its context also gets + * its persist path passed on as given, and a relative one refused, as with DOCKER_HOST=tcp://. + */ + @Test + void aRemoteContextDecidesThePersistPathToo() { + FakeDocker docker = new FakeDocker(REMOTE); + + Out ok = start(docker, "--persist", "/srv/floci-data", "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(0, ok.exit(), ok.err()); + assertTrue(docker.runArgs.contains("/srv/floci-data:/app/data"), docker.runArgs.toString()); + + FakeDocker refused = new FakeDocker(REMOTE); + Out relative = start(refused, "--persist", "data", "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(1, relative.exit()); + assertTrue(relative.err().contains("must be an absolute path on the daemon's machine"), relative.err()); + assertEquals(List.of(), refused.calls); + } + + /** + * A user who may not bind a privileged port (Linux below 1024) cannot tell "taken" from "not + * allowed" by binding, while the Docker daemon can publish it: only an answering listener + * makes such a port taken. Above that range a failed bind is the answer. + */ + @Test + void aFailedBindOnAPrivilegedPortIsNotProofItIsTaken() { + assertFalse(PortAvailableCheck.takenAfterFailedBind(80, "Permission denied", () -> false)); + assertFalse(PortAvailableCheck.takenAfterFailedBind(443, null, () -> false)); + assertTrue(PortAvailableCheck.takenAfterFailedBind(80, "Permission denied", () -> true)); + assertTrue(PortAvailableCheck.takenAfterFailedBind(1024, "Permission denied", () -> false)); + assertTrue(PortAvailableCheck.takenAfterFailedBind(4566, null, () -> false)); + } + + /** "Address already in use" is the answer on its own, also for a listener loopback cannot reach. */ + @Test + void anAddressInUseErrorMeansTakenOnAnyPort() { + assertTrue(PortAvailableCheck.takenAfterFailedBind(80, "Address already in use", () -> false)); + assertTrue(PortAvailableCheck.takenAfterFailedBind(443, "Address already in use: bind", () -> false)); + } + + @Test + void aListenerIsFoundOnLoopbackAndAClosedPortIsNot() throws Exception { + int port; + try (ServerSocket listening = new ServerSocket(0)) { + port = listening.getLocalPort(); + assertTrue(PortAvailableCheck.listensOnLoopback(port)); + assertFalse(PortAvailableCheck.isPortFree(port)); + } + assertFalse(PortAvailableCheck.listensOnLoopback(port)); + assertTrue(PortAvailableCheck.isPortFree(port)); + } + + @Test + void onlyARealPortOnALocalDaemonIsProbed() { + assertTrue(StartCommand.probesPortLocally(LOCAL, 4588)); + assertTrue(StartCommand.probesPortLocally(new DockerHost(Kind.NPIPE, "\\\\.\\pipe\\docker_engine", null), 4588)); + assertFalse(StartCommand.probesPortLocally(REMOTE, 4588)); + // Not ports: a socket cannot even be opened on them, and docker reports them itself. + assertFalse(StartCommand.probesPortLocally(LOCAL, 70000)); + assertFalse(StartCommand.probesPortLocally(LOCAL, 0)); + assertFalse(StartCommand.probesPortLocally(LOCAL, -1)); + } + + /** A number that is no port must reach docker's own error, not a stack trace from the probe. */ + @Test + void anOutOfRangePortIsNotProbed() { + FakeDocker docker = new FakeDocker(LOCAL); + + Out r = start(docker, "--port", "70000", "--container", "floci-gcp-preflight", "--detach"); + + assertFalse(r.err().contains("Exception"), r.err()); + assertFalse(r.err().contains("already in use"), r.err()); + } + + @Test + void aMissingSocketSaysHowToBringDockerUp() { + DockerHost missing = new DockerHost(Kind.UNIX, tempDir.resolve("docker.sock").toString(), null); + + String guidance = StartCommand.socketGuidance(missing); + + assertTrue(guidance.contains("docker.sock not found"), guidance); + assertTrue(guidance.contains("Docker"), guidance); + assertTrue(guidance.endsWith(", then re-run the command."), guidance); + // The socket does not exist, so permissions on it are not the fix. + assertFalse(guidance.contains("chmod"), guidance); + assertFalse(guidance.contains("docker group"), guidance); + } + + @Test + void aSocketThatExistsOrARemoteDaemonGetsNoSocketGuidance() throws Exception { + Path present = Files.createFile(tempDir.resolve("docker.sock")); + + assertEquals("", StartCommand.socketGuidance(new DockerHost(Kind.UNIX, present.toString(), null))); + assertEquals("", StartCommand.socketGuidance(REMOTE)); + } + + /** The inspect failure carries the guidance for the daemon docker resolved. */ + @Test + void anUnreachableDaemonWithAMissingSocketGetsTheGuidance() { + DockerHost missing = new DockerHost(Kind.UNIX, tempDir.resolve("docker.sock").toString(), null); + FakeDocker docker = new FakeDocker(missing) { + @Override + public Optional inspectContainer(String name) throws DockerException { + throw new DockerException("Cannot connect to the Docker daemon"); + } + }; + + Out r = start(docker, "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("Cannot connect to the Docker daemon"), r.err()); + assertTrue(r.err().contains("docker.sock not found"), r.err()); + assertEquals(List.of(), docker.calls); + } + + /** A context selected with DOCKER_CONTEXT or 'docker context use' is not in the environment: docker is asked. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void theDaemonComesFromDockersActiveContext() throws Exception { + assumeTrue(DockerClient.dockerHost().raw() == null, "DOCKER_HOST or DOCKER_SOCK is set and wins"); + Path argsFile = tempDir.resolve("args"); + Path remoteContext = tempDir.resolve("docker-remote"); + Files.writeString(remoteContext, "#!/bin/sh\necho \"$1 $2\" > '" + argsFile + "'\necho ssh://deploy@build-host\n"); + Path noContexts = tempDir.resolve("docker-plain"); + Files.writeString(noContexts, "#!/bin/sh\necho unknown command >&2\nexit 125\n"); + assertTrue(remoteContext.toFile().setExecutable(true)); + assertTrue(noContexts.toFile().setExecutable(true)); + + DockerHost fromContext = new DockerClient(remoteContext.toString()).daemonHost(); + + assertEquals(Kind.TCP, fromContext.kind()); + assertEquals("ssh://deploy@build-host", fromContext.raw()); + assertEquals("context inspect", Files.readString(argsFile).trim()); + // No contexts (Podman, an old docker): the environment's answer stands. + assertEquals(DockerClient.dockerHost(), new DockerClient(noContexts.toString()).daemonHost()); + } +}