diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index ff75cef..85b2e11 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -73,6 +73,11 @@ public class RestartCommand implements Callable { printer.error(invalid); return 2; } + String unwritable = start.preparePersistDir(); + if (unwritable != null) { + printer.error(unwritable); + return 1; + } if (!containerExists()) { // Nothing to stop: start it, rather than failing on the stop. diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 3f63e08..aaceb30 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -11,8 +11,12 @@ import picocli.CommandLine; import picocli.CommandLine.*; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.regex.Pattern; @@ -114,9 +118,87 @@ public class StartCommand implements Callable { if (namespace != null && !namespace.isBlank() && !NAMESPACE.matcher(namespace).matches()) { return "Invalid namespace '" + namespace + "'.\nUse letters, digits, '_', '.' and '-', starting with a letter or digit."; } + if (port < 1 || port > 65535) { + return "--port must be between 1 and 65535, but was " + port + ".\nPick a free port, for example " + + (profile.defaultPort() + 10000) + "."; + } + if (pull == null || !PULL_POLICIES.contains(pull.toLowerCase(Locale.ROOT))) { + // Anything else used to fall through to a pull, so a typo silently meant "always". + return "Invalid --pull '" + pull + "'.\nUse always, missing or never."; + } return null; } + private static final List PULL_POLICIES = List.of("always", "missing", "never"); + + /** + * {@code persistDir} as an absolute, normalized path. Docker reads a bind source without a + * leading slash as a named volume, so {@code --persist ./data} would otherwise keep the state + * in an anonymous Docker volume instead of the directory the user named. + */ + public String persistPath() { + return Path.of(persistDir).toAbsolutePath().normalize().toString(); + } + + // Absolute on the daemon's machine, whichever system that is: a leading slash, a drive + // letter with a separator, or a UNC share. + // Not decided by this machine's Path rules, which know only its own file system. + private static final Pattern REMOTE_ABSOLUTE = Pattern.compile("^(/|[A-Za-z]:[\\\\/]|\\\\\\\\)"); + + /** + * The bind source handed to a daemon reached through {@code daemon}. A remote daemon gets + * {@code persistDir} exactly as given: the path names a directory on its machine, and + * resolving it here would apply this machine's rules to it (a Windows CLI turns + * {@code /srv/data} into a drive path). Only a local daemon gets {@link #persistPath()}. + */ + public String bindSource(DockerClient.DockerHost daemon) { + return daemon.kind() == DockerClient.Kind.TCP ? persistDir : persistPath(); + } + + /** + * Creates the state directory, returning why it could not be created, or {@code null}. Done by + * the CLI rather than docker: a bind source docker creates is owned by root on Linux, and the + * emulator then cannot write to it. Restart calls this before it stops anything, so a + * directory that cannot be created leaves the running instance alone. + * + *

An existing directory is accepted as it is, with no write check: the emulator runs as its + * own user (uid 1001) and the AWS image re-owns its data directory at startup, so whether the + * CLI's user can write there says nothing about whether the emulator can. The emulator reports + * a directory it cannot write to itself. + */ + public String preparePersistDir() { + return preparePersistDir(DockerClient.dockerHost()); + } + + /** {@link #preparePersistDir()} for a daemon reached through {@code daemon}; the test seam. */ + public String preparePersistDir(DockerClient.DockerHost daemon) { + if (persistDir == null || persistDir.isBlank()) return null; + // A remote daemon reads the bind source on its own machine, where this CLI can neither + // create nor check it; it is passed on untouched (bindSource), so nothing here can fail + // on it later either. It does have to be absolute: there is no working directory to + // resolve it against over there, and docker reads a bare name as a named volume. + if (daemon.kind() == DockerClient.Kind.TCP) { + return REMOTE_ABSOLUTE.matcher(persistDir).find() ? null + : "With a remote Docker daemon, --persist must be an absolute path on the daemon's machine, but was '" + + persistDir + "'.\nPass an absolute path, for example /srv/floci-data."; + } + Path path; + try { + path = Path.of(persistPath()); + } catch (InvalidPathException e) { + // Names persistDir as given: resolving it is what failed. + return "Invalid persist directory '" + persistDir + "': " + e.getReason() + + ".\nPass a --persist path that is valid on this system."; + } + try { + Files.createDirectories(path); + return null; + } catch (Exception e) { + return "Could not create the persist directory " + path + ": " + e.getMessage() + + "\nPass a --persist directory you can write to."; + } + } + public String resourceNamespace() { return resourceNamespaceFor(global.container); } @@ -134,12 +216,20 @@ public class StartCommand implements Callable { * the ambient {@code DOCKER_HOST} and so differs per machine. */ public List dockerRunArgs(List socketArgs) { + return dockerRunArgs(socketArgs, LOCAL_DAEMON); + } + + private static final DockerClient.DockerHost LOCAL_DAEMON = + new DockerClient.DockerHost(DockerClient.Kind.UNIX, null, null); + + /** {@link #dockerRunArgs(List)} for a daemon reached through {@code daemon}, which decides the bind source. */ + public List dockerRunArgs(List socketArgs, DockerClient.DockerHost daemon) { List args = new ArrayList<>(); args.addAll(List.of("-d", "--name", global.container)); args.addAll(List.of("-p", port + ":" + profile.defaultPort())); args.addAll(socketArgs); if (persistDir != null && !persistDir.isBlank()) { - args.addAll(List.of("-v", persistDir + ":/app/data")); + args.addAll(List.of("-v", bindSource(daemon) + ":/app/data")); // The server defaults to in-memory storage; enable persistent mode so // state is actually written to the mounted directory and survives restarts. args.addAll(List.of("-e", profile.envVar("STORAGE_MODE") + "=persistent")); @@ -200,6 +290,12 @@ public class StartCommand implements Callable { return 2; } + String unwritable = preparePersistDir(); + if (unwritable != null) { + printer.error(unwritable); + return 1; + } + // Check if container already exists. This is also the first docker call, so a missing // binary shows up here, without a separate `docker --version` probe on every start. try { @@ -232,7 +328,7 @@ public class StartCommand implements Callable { return 1; } - List args = dockerRunArgs(DockerClient.dockerSocketRunArgs()); + List args = dockerRunArgs(DockerClient.dockerSocketRunArgs(), DockerClient.dockerHost()); try { printer.println("Starting " + Ansi.gold(profile.displayName()) + " container..."); diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java index ee85a95..d5283ac 100644 --- a/src/test/java/io/floci/cli/unit/RestartCommandTest.java +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -10,6 +10,8 @@ import io.floci.cli.config.ProfileStore; import io.floci.cli.docker.DockerClient; 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 picocli.CommandLine.ParseResult; @@ -25,6 +27,7 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeFalse; /** * Restart builds its StartCommand programmatically, so picocli never applies the profile to it. @@ -156,6 +159,37 @@ class RestartCommandTest { } } + /** + * A persist directory that cannot be created fails the restart before the stop, so the running + * instance is left alone instead of being removed and never started again. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void anUnwritablePersistDirFailsBeforeTheStop() throws Exception { + Path readOnly = Files.createDirectories(tempDir.resolve("read-only")); + assertTrue(readOnly.toFile().setWritable(false)); + writeProfile("ro", "container: floci-ro-none\npersistDir: " + readOnly.resolve("state") + "\n"); + RestartCommand restart = parse(ProductProfile.AWS, "--profile", "ro"); + + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + try { + // Root writes through the permission bits; the restart would then reach Docker. + assumeFalse(Files.isWritable(readOnly), "permissions do not bind this user (root)"); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + assertEquals(1, restart.call()); + } finally { + System.setOut(out); + System.setErr(err); + readOnly.toFile().setWritable(true); + } + assertTrue(errBuf.toString().contains("Could not create the persist directory"), errBuf.toString()); + assertFalse(outBuf.toString().contains("Stopping"), "nothing was stopped: " + outBuf); + } + /** * One snapshot: restart applies the profile the parse read, not a second read of the file, so * an edit or delete in between cannot mix two versions into one restart. @@ -214,8 +248,20 @@ class RestartCommandTest { RestartCommand restart = new RestartCommand(ProductProfile.AWS, docker) { @Override public StartCommand buildStartCommand() throws DockerException { - super.buildStartCommand(); // the real one first, so its docker failure still surfaces + // The real one first, so its docker failure still surfaces; it also answers the + // checks restart runs before the stop, as only it carries the resolved settings. + StartCommand real = super.buildStartCommand(); return new StartCommand(ProductProfile.AWS) { + @Override + public String validationError() { + return real.validationError(); + } + + @Override + public String preparePersistDir() { + return real.preparePersistDir(); + } + @Override public Integer call() { ran.add("start"); diff --git a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java index 34ca95c..fbdfe19 100644 --- a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java +++ b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java @@ -3,8 +3,13 @@ package io.floci.cli.unit; import io.floci.cli.FlociCli; import io.floci.cli.commands.StartCommand; import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; 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 org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import picocli.CommandLine.ParseResult; import java.io.ByteArrayOutputStream; @@ -13,6 +18,7 @@ import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Locale; import static org.junit.jupiter.api.Assertions.*; @@ -191,6 +197,152 @@ class StartCommandArgsTest { .dockerRunArgs(SOCKET).contains("FLOCI_BASE_URL=http://floci.internal:14566")); } + /** BL-034: Docker reads "./data:/app/data" as a named volume, so the path goes in absolute. */ + @Test + void aRelativePersistDirIsMountedAsAnAbsoluteBindPath() { + String expected = Path.of("data").toAbsolutePath().normalize() + ":/app/data"; + + List args = parse("start", "--persist", "./data").dockerRunArgs(SOCKET); + + assertTrue(args.contains(expected), args.toString()); + assertFalse(args.contains("./data:/app/data"), args.toString()); + } + + /** BL-035: an out-of-range port or an unknown pull policy is refused before docker runs. */ + @Test + void portAndPullPolicyAreValidated() { + assertNull(parse("start").validationError()); + assertNull(parse("start", "--pull", "ALWAYS").validationError()); + assertTrue(parse("start", "--port", "0").validationError().contains("--port must be between 1 and 65535")); + assertTrue(parse("start", "--port", "70000").validationError().contains("--port must be between 1 and 65535")); + assertTrue(parse("start", "--pull", "alwayz").validationError().contains("Invalid --pull 'alwayz'")); + } + + /** Pull policies are plain ASCII words: a Turkish default locale lowercases "MISSING" with a dotless i. */ + @Test + void pullPolicyDoesNotDependOnTheDefaultLocale() { + Locale before = Locale.getDefault(); + Locale.setDefault(Locale.forLanguageTag("tr-TR")); + try { + assertNull(parse("start", "--pull", "MISSING").validationError()); + } finally { + Locale.setDefault(before); + } + } + + private static final DockerClient.DockerHost LOCAL = + new DockerClient.DockerHost(DockerClient.Kind.UNIX, "/var/run/docker.sock", null); + private static final DockerClient.DockerHost REMOTE = + new DockerClient.DockerHost(DockerClient.Kind.TCP, null, "tcp://build-host:2375"); + + @Test + void aLocalDaemonGetsItsPersistDirCreated() { + Path state = tempDir.resolve("made").resolve("state"); + + assertNull(parse("start", "--persist", state.toString()).preparePersistDir(LOCAL)); + + assertTrue(Files.isDirectory(state)); + } + + /** A remote daemon reads the bind source on its own machine: nothing is created or refused here. */ + @Test + void aRemoteDaemonsPersistDirIsNotCreatedLocally() throws Exception { + Path blocker = Files.writeString(Files.createDirectories(tempDir).resolve("a-file"), "x"); + Path state = blocker.resolve("state"); // cannot exist locally: its parent is a file + + assertNull(parse("start", "--persist", state.toString()).preparePersistDir(REMOTE)); + assertFalse(Files.exists(state)); + assertNotNull(parse("start", "--persist", state.toString()).preparePersistDir(LOCAL)); + } + + /** A path that is not valid on this platform gets the same hint, not an exception from building the message. */ + @Test + void anInvalidPersistPathIsReportedNotThrown() { + String invalid = "data\u0000dir"; // NUL is rejected by every platform's Path + + String error = parse("start", "--persist", invalid).preparePersistDir(LOCAL); + + assertNotNull(error); + assertTrue(error.startsWith("Invalid persist directory"), error); + assertTrue(error.contains("Pass a --persist path"), error); + } + + /** + * A remote daemon's path is its own: an absolute one is passed on as given, never resolved by + * this machine's rules (a Windows CLI would turn /srv/floci-data into a drive path). + */ + @Test + void aRemoteDaemonGetsThePersistPathExactlyAsGiven() { + StartCommand start = parse("start", "--persist", "/srv/floci-data/../state"); + + assertNull(start.preparePersistDir(REMOTE)); + assertEquals("/srv/floci-data/../state", start.bindSource(REMOTE)); + assertTrue(start.dockerRunArgs(SOCKET, REMOTE).contains("/srv/floci-data/../state:/app/data")); + } + + /** Only a local daemon has relative paths resolved against this machine's working directory. */ + @Test + void onlyALocalDaemonHasItsPersistPathResolved() { + StartCommand start = parse("start", "--persist", "./data"); + String resolved = Path.of("data").toAbsolutePath().normalize().toString(); + + assertEquals(resolved, start.bindSource(LOCAL)); + assertTrue(start.dockerRunArgs(SOCKET, LOCAL).contains(resolved + ":/app/data")); + } + + /** + * A remote daemon has no working directory of ours to resolve against, and docker reads a bare + * name as a named volume: a relative path is refused before anything is started or stopped. + */ + @ParameterizedTest + @ValueSource(strings = {"data", "./data", "../state", "C:data"}) + void aRemoteDaemonRefusesARelativePersistPath(String relative) { + String error = parse("start", "--persist", relative).preparePersistDir(REMOTE); + + assertNotNull(error); + assertTrue(error.contains("must be an absolute path on the daemon's machine"), error); + assertTrue(error.contains("'" + relative + "'"), error); + } + + /** Absolute for the daemon's system, whichever it is; this machine's path rules do not decide. */ + @ParameterizedTest + @ValueSource(strings = {"/srv/floci-data", "C:\\floci\\data", "c:/floci/data", "\\\\nas\\share\\floci"}) + void aRemoteDaemonAcceptsAnAbsolutePathOfEitherSystem(String absolute) { + StartCommand start = parse("start", "--persist", absolute); + + assertNull(start.preparePersistDir(REMOTE)); + assertEquals(absolute, start.bindSource(REMOTE)); + } + + /** + * What preparePersistDir accepts, dockerRunArgs can build. Restart runs the check before the + * stop, so a path this machine cannot even parse must not throw afterwards for a remote daemon. + */ + @Test + void aPathThisMachineCannotParseStillBuildsForARemoteDaemon() { + StartCommand start = parse("start", "--persist", "/srv/data\u0000dir"); + + assertNull(start.preparePersistDir(REMOTE)); + assertDoesNotThrow(() -> start.dockerRunArgs(SOCKET, REMOTE)); + assertNotNull(start.preparePersistDir(LOCAL)); + } + + /** + * An existing directory this user cannot write to is left to the emulator, which runs as its + * own user and reports an unwritable data directory itself. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void anExistingDirectoryIsAcceptedWithoutAWriteCheck() throws Exception { + Path readOnly = Files.createDirectories(tempDir.resolve("read-only")); + assertTrue(readOnly.toFile().setWritable(false)); + try { + assertNull(parse("start", "--persist", readOnly.toString()).preparePersistDir(LOCAL)); + } finally { + readOnly.toFile().setWritable(true); + } + } + @Test void readinessPollKeepsTheHostFromTheEndpointWhenSwappingThePort() { assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599));