From 3d20a43b41f3762dd919f0b3cdc2e89948b1b700 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 16:58:54 -0500 Subject: [PATCH] feat(start): ask docker which daemon it uses before probing the port The port probe and the socket hint follow the daemon docker resolved (DOCKER_HOST, else the active context), a number that is no port is not probed, and a missing socket gets a start-the-daemon hint instead of a permissions one. Adds tests for the free port, remote daemon, socket guidance and context paths. --- .../io/floci/cli/commands/StartCommand.java | 23 +- .../io/floci/cli/docker/DockerClient.java | 20 ++ .../cli/doctor/checks/DockerSocketCheck.java | 12 +- .../io/floci/cli/unit/StartPreflightTest.java | 217 +++++++++++++++--- 4 files changed, 231 insertions(+), 41 deletions(-) diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 6724406..b07fe5d 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -230,14 +230,14 @@ 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() + socketGuidance()); + printer.error("Failed to inspect container: " + e.getMessage() + socketGuidance(docker.daemonHost())); 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 (DockerClient.dockerHost().kind() != DockerClient.Kind.TCP && !PortAvailableCheck.isPortFree(port)) { + if (probesPortLocally(docker.daemonHost(), 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; @@ -281,10 +281,21 @@ public class StartCommand implements Callable { return wait.call(); } - // When the daemon is unreachable because its local socket is missing, say so: docker's own - // error ("Cannot connect to the Docker daemon") does not say what to do about it. - private static String socketGuidance() { - CheckResult socket = new DockerSocketCheck().run(null, null); + /** + * 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 1197268..25acf5d 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -343,6 +343,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/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 7fca838..0a97321 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -3,15 +3,24 @@ 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 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 java.util.concurrent.atomic.AtomicBoolean; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -19,43 +28,187 @@ 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<>(); + + 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) { + 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 { - assumeTrue(DockerClient.dockerHost().kind() != DockerClient.Kind.TCP, "a remote daemon skips the local probe"); - AtomicBoolean pulled = new AtomicBoolean(); - DockerClient docker = new DockerClient() { - @Override - public Optional inspectContainer(String name) { - return Optional.empty(); - } - - @Override - public void pull(String image, String policy) { - pulled.set(true); - } - }; - + FakeDocker docker = new FakeDocker(LOCAL); try (ServerSocket taken = new ServerSocket()) { taken.bind(new InetSocketAddress(0)); int port = taken.getLocalPort(); - 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(new StartCommand(ProductProfile.GCP, docker)) - .execute("--port", String.valueOf(port), "--container", "floci-gcp-preflight"); - } finally { - System.setOut(out); - System.setErr(err); - } - assertEquals(1, exit); - assertTrue(errBuf.toString().contains("Port " + port + " is already in use"), errBuf.toString()); - assertTrue(errBuf.toString().contains("--port "), errBuf.toString()); - assertFalse(pulled.get(), "nothing is pulled for a start that cannot bind"); + 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); + } + } + + @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 tcp://build-host:2376\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("tcp://build-host:2376", 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()); + } }