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...");