fix(start): mount a relative --persist path as a directory and validate --port and --pull (#50)

* fix(start): mount a relative --persist path as a directory and validate --port and --pull

--persist ./data is resolved to an absolute path and created before docker run, so state lands in that directory instead of a Docker named volume; --port outside 1-65535 and an unknown --pull policy are rejected with exit 2 (restart checks them before stopping anything).

start creates the persist directory itself (preparePersistDir). restart now does that before it stops anything, so an unwritable directory fails the restart with the instance still running, instead of after the container was already removed.

* fix(start): leave a remote daemon's persist directory alone and accept pull policies in any locale

The persist directory is created only for a local daemon, an invalid path is reported instead of thrown while building the message, and pull policies are lowercased with Locale.ROOT. The permission test is skipped when permissions do not bind the user.

* fix(start): check the persist path for a remote daemon before restart stops anything

A remote daemon skips only the local directory creation. The path itself is resolved for every daemon, so an unusable one is reported before the stop instead of thrown while building the run arguments afterwards.

* test(restart): let the recorded start answer restart's pre-stop checks

The recording start used by the call-path tests was never parsed, so the new --pull validation rejected it. It now delegates the checks to the start restart really built.

* fix(start): pass a remote daemon's persist path on unchanged

A remote daemon's bind source is no longer resolved by the CLI machine's path rules, which turned /srv/data into a drive path on a Windows CLI. Only a local daemon has relative paths resolved.

* fix(start): refuse a relative --persist path for a remote daemon

A remote daemon cannot resolve a path relative to the CLI's working directory, and docker reads a bare name as a named volume, so the state would land somewhere a later restart does not carry over.

* refactor(start): keep bindSource's javadoc on the method
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 17:55:29 -05:00
1 parent f6cec794d7
commit 3ca4108498
4 files changed
+302 -3

No files matched your search

@@ -73,6 +73,11 @@ public class RestartCommand implements Callable<Integer> {
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.
@@ -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<Integer> {
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<String> 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.
*
* <p>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<Integer> {
* the ambient {@code DOCKER_HOST} and so differs per machine.
*/
public List<String> dockerRunArgs(List<String> 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<String> dockerRunArgs(List<String> socketArgs, DockerClient.DockerHost daemon) {
List<String> 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<Integer> {
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<Integer> {
return 1;
}
List<String> args = dockerRunArgs(DockerClient.dockerSocketRunArgs());
List<String> args = dockerRunArgs(DockerClient.dockerSocketRunArgs(), DockerClient.dockerHost());
try {
printer.println("Starting " + Ansi.gold(profile.displayName()) + " container...");
@@ -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");
@@ -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<String> 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));