fix(restart): keep the instance's port, image, data directory and services (#49)

* fix(restart): keep the instance's port, image, data directory and services

Without a profile, restart reads the running container's settings (host port, image, the directory mounted at /app/data, its services and resource namespace) before stopping it and starts it with them, instead of falling back to the defaults and moving the instance to the default port without its state. A profile still decides when one is given, and restart now starts the container when none exists instead of failing.

A container started without --persist has Docker's anonymous volume at /app/data; restart took that volume's internal path for a persist directory and failed to start again. Only a bind mount is a persist directory now.

* fix(restart): stop before the stop when the running container's settings cannot be read

A failed or timed-out inspect is no longer treated as a missing container, which removed the instance and started it on the defaults. Adds tests through call() for the missing-container, existing-container and unreadable-settings paths.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 17:38:28 -05:00
1 parent 52ebdee98d
commit f6cec794d7
4 files changed
+328 -5

No files matched your search

@@ -207,6 +207,49 @@ class DockerClientProcessTest {
assertEquals(List.of("rm", "--", "--rm-everything"), args);
}
/** BL-033: restart reads the image, host port, data mount and environment back from inspect. */
@Test
@DisabledOnOs(OS.WINDOWS)
void runSettingsAreReadFromTheContainersInspectDocument() throws Exception {
Path json = tempDir.resolve("inspect.json");
Files.writeString(json, """
{"Config":{"Image":"floci/floci-gcp:0.9","Env":["FLOCI_GCP_SERVICES=storage","PATH=/usr/bin"]},
"HostConfig":{"PortBindings":{"4588/tcp":[{"HostIp":"","HostPort":"14588"}]}},
"Mounts":[{"Type":"bind","Source":"/data/gcp","Destination":"/app/data"}]}
""");
Path fakeDocker = tempDir.resolve("docker");
Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n");
assertTrue(fakeDocker.toFile().setExecutable(true));
DockerClient.RunSettings run = new DockerClient(fakeDocker.toString())
.inspectRunSettings("floci-gcp", 4588).orElseThrow();
assertEquals("floci/floci-gcp:0.9", run.image());
assertEquals(14588, run.hostPort());
assertEquals("/data/gcp", run.persistSource());
assertEquals("storage", run.env().get("FLOCI_GCP_SERVICES"));
}
/** Without --persist the image's /app/data volume is mounted; that is not a persist directory. */
@Test
@DisabledOnOs(OS.WINDOWS)
void anAnonymousDataVolumeIsNotAPersistDirectory() throws Exception {
Path json = tempDir.resolve("inspect.json");
Files.writeString(json, """
{"Config":{"Image":"floci/floci-oci:latest","Env":[]},
"HostConfig":{"PortBindings":{"4599/tcp":[{"HostIp":"","HostPort":"4599"}]}},
"Mounts":[{"Type":"volume","Name":"3c3aef44","Source":"/var/lib/docker/volumes/3c3aef44/_data","Destination":"/app/data"}]}
""");
Path fakeDocker = tempDir.resolve("docker");
Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n");
assertTrue(fakeDocker.toFile().setExecutable(true));
DockerClient.RunSettings run = new DockerClient(fakeDocker.toString())
.inspectRunSettings("floci-oci", 4599).orElseThrow();
assertNull(run.persistSource());
}
/** BL-041: with --verbose set, each docker command is echoed to stderr before it runs. */
@Test
@DisabledOnOs(OS.WINDOWS)
@@ -3,7 +3,12 @@ package io.floci.cli.unit;
import io.floci.cli.FlociCli;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.RestartCommand;
import io.floci.cli.commands.StartCommand;
import io.floci.cli.commands.StopCommand;
import io.floci.cli.config.ProfileDefaultValueProvider;
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.io.TempDir;
import picocli.CommandLine;
@@ -16,6 +21,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@@ -32,6 +39,21 @@ class RestartCommandTest {
Path tempDir;
// Through the real wiring, so restart sees the provider the parse used.
/** A restart whose docker lookups answer from {@code settings} (none: no such container). */
private RestartCommand restartWith(ProductProfile product, DockerClient.RunSettings settings, String... args) {
DockerClient docker = new DockerClient() {
@Override
public Optional<RunSettings> inspectRunSettings(String name, int containerPort) {
return Optional.ofNullable(settings);
}
};
RestartCommand restart = new RestartCommand(product, docker);
new CommandLine(restart)
.setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir)))
.parseArgs(args);
return restart;
}
private RestartCommand parse(ProductProfile product, String... args) {
List<String> all = new ArrayList<>();
if (product != ProductProfile.AWS) all.add(product.name());
@@ -98,8 +120,8 @@ class RestartCommandTest {
}
@Test
void withoutAProfileItStillUsesTheProductDefaults() {
List<String> args = parse(ProductProfile.GCP).buildStartCommand().dockerRunArgs(SOCKET);
void withoutAProfileItStillUsesTheProductDefaults() throws Exception {
List<String> args = restartWith(ProductProfile.GCP, null).buildStartCommand().dockerRunArgs(SOCKET);
assertEquals(List.of("-d", "--name", "floci-gcp", "-p", "4588:4588",
"-v", "/sock:/sock", "floci/floci-gcp:latest"), args);
@@ -153,9 +175,157 @@ class RestartCommandTest {
/** BL-029: the stop removes the container, so start needs no pause and no second removal. */
@Test
void theStopItRunsRemovesTheContainer() {
void theStopItRunsRemovesTheContainer() throws Exception {
var stop = parse(ProductProfile.AWS).buildStopCommand();
assertEquals(Boolean.TRUE, new CommandLine(stop).getCommandSpec().findOption("--remove").getValue());
}
/** BL-033: without a profile, the running container is the record of how it was started. */
@Test
void withoutAProfileTheRunningContainersSettingsCarryOver() throws Exception {
var running = new DockerClient.RunSettings("floci/floci-gcp:0.9", 14588, "/data/gcp",
Map.of("FLOCI_GCP_SERVICES", "storage", "FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE", "team"));
List<String> args = restartWith(ProductProfile.GCP, running).buildStartCommand().dockerRunArgs(SOCKET);
assertTrue(args.contains("14588:4588"), args.toString());
assertTrue(args.contains("/data/gcp:/app/data"), args.toString());
assertTrue(args.contains("FLOCI_GCP_SERVICES=storage"), args.toString());
assertTrue(args.contains("FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE=team"), args.toString());
assertEquals("floci/floci-gcp:0.9", args.get(args.size() - 1));
}
/** A profile still decides: carry-over only fills in for a restart without one. */
@Test
void aProfileWinsOverTheRunningContainersSettings() throws Exception {
writeProfile("pinned", "port: 15000\n");
var running = new DockerClient.RunSettings("floci/floci:0.9", 14566, "/data/x", Map.of());
List<String> args = restartWith(ProductProfile.AWS, running, "--profile", "pinned")
.buildStartCommand().dockerRunArgs(SOCKET);
assertTrue(args.contains("15000:4566"), args.toString());
assertFalse(args.contains("/data/x:/app/data"), args.toString());
}
/** What a restart did, in order: "stop" and "start" as it ran them. */
private RestartCommand recordingRestart(DockerClient docker, List<String> ran) {
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
return new StartCommand(ProductProfile.AWS) {
@Override
public Integer call() {
ran.add("start");
return 0;
}
};
}
@Override
public StopCommand buildStopCommand() {
return new StopCommand(ProductProfile.AWS) {
@Override
public Integer call() {
ran.add("stop");
return 0;
}
};
}
};
new CommandLine(restart)
.setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir)))
.parseArgs();
return restart;
}
private record Ran(int exit, String out, String err) {}
private static Ran run(RestartCommand restart) {
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
return new Ran(restart.call(), outBuf.toString(), errBuf.toString());
} finally {
System.setOut(out);
System.setErr(err);
}
}
/** BL-033: with no container there is nothing to stop, so restart only starts. */
@Test
void aMissingContainerIsStartedWithoutAStop() {
DockerClient absent = new DockerClient() {
@Override
public Optional<RunSettings> inspectRunSettings(String name, int containerPort) {
return Optional.empty();
}
@Override
public Optional<ContainerInfo> inspectContainer(String name) {
return Optional.empty();
}
};
List<String> ran = new ArrayList<>();
Ran r = run(recordingRestart(absent, ran));
assertEquals(0, r.exit());
assertEquals(List.of("start"), ran);
assertTrue(r.out().contains("not found; starting it"), r.out());
}
@Test
void anExistingContainerIsStoppedThenStarted() {
DockerClient present = new DockerClient() {
@Override
public Optional<RunSettings> inspectRunSettings(String name, int containerPort) {
return Optional.of(new RunSettings("floci/floci:0.9", 14566, null, Map.of()));
}
@Override
public Optional<ContainerInfo> inspectContainer(String name) {
return Optional.of(new ContainerInfo("abc", name, "floci/floci:0.9", "running", ""));
}
};
List<String> ran = new ArrayList<>();
Ran r = run(recordingRestart(present, ran));
assertEquals(0, r.exit());
assertEquals(List.of("stop", "start"), ran);
}
/**
* A failed read of the running container's settings is not "no container": restart must stop
* there, or it would remove the instance and bring it back on the default port without its data.
*/
@Test
void settingsThatCannotBeReadFailTheRestartBeforeTheStop() {
DockerClient stalled = new DockerClient() {
@Override
public Optional<RunSettings> inspectRunSettings(String name, int containerPort) throws DockerException {
throw new DockerException("'docker container inspect' did not finish within 30s.");
}
@Override
public Optional<ContainerInfo> inspectContainer(String name) {
return Optional.of(new ContainerInfo("abc", name, "floci/floci:0.9", "running", ""));
}
};
List<String> ran = new ArrayList<>();
Ran r = run(recordingRestart(stalled, ran));
assertEquals(1, r.exit());
assertEquals(List.of(), ran);
assertTrue(r.err().contains("did not finish within 30s"), r.err());
assertTrue(r.err().contains("floci restart"), r.err());
}
}