From 8f06a847e6bb9b4eaf3a9b18f04b530213857867 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 16:30:12 -0500 Subject: [PATCH] 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. --- .../io/floci/cli/commands/RestartCommand.java | 47 +++++++++++++- .../io/floci/cli/docker/DockerClient.java | 61 +++++++++++++++++++ .../cli/unit/DockerClientProcessTest.java | 43 +++++++++++++ .../io/floci/cli/unit/RestartCommandTest.java | 49 ++++++++++++++- 4 files changed, 198 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index 484eb61..93bb886 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -2,8 +2,10 @@ package io.floci.cli.commands; import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; -import io.floci.cli.config.ProfileNotFoundException; import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileNotFoundException; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; import io.floci.cli.output.Printer; import picocli.CommandLine.*; import picocli.CommandLine.Model.CommandSpec; @@ -30,10 +32,18 @@ public class RestartCommand implements Callable { } protected RestartCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + /** Test seam: {@code docker} answers the inspect that recovers the running instance's settings. */ + public RestartCommand(ProductProfile profile, DockerClient docker) { this.profile = profile; this.global = new GlobalOptions(profile); + this.docker = docker; } + private final DockerClient docker; + @Override public Integer call() { Printer printer = global.printer(); @@ -56,6 +66,12 @@ public class RestartCommand implements Callable { return 2; } + if (!containerExists()) { + // Nothing to stop: start it, rather than failing on the stop. + printer.println("Container '" + global.container + "' not found; starting it."); + return start.call(); + } + int stopResult = buildStopCommand().call(); if (stopResult != 0) return stopResult; @@ -93,6 +109,35 @@ public class RestartCommand implements Callable { start.global = global; start.pull = "missing"; start.detach = false; + if (global.profile == null) carryOver(start); return start; } + + // Without a profile, the running container is the only record of how it was started: its + // port, image, data directory and services come back from it, or a restart would quietly + // move the instance to the default port and drop its state. Read before the stop, which + // removes the container. + private void carryOver(StartCommand start) { + try { + docker.inspectRunSettings(global.container, profile.defaultPort()).ifPresent(run -> { + if (run.hostPort() != null) start.port = run.hostPort(); + if (run.image() != null) start.image = run.image(); + if (run.persistSource() != null) start.persistDir = run.persistSource(); + String services = run.env().get(profile.envVar("SERVICES")); + if (services != null) start.services = services; + String namespace = run.env().get(profile.envVar("DOCKER_RESOURCE_NAMESPACE")); + if (namespace != null) start.namespace = namespace; + }); + } catch (DockerException e) { + // Unreadable settings: the restart falls back to the defaults, as it did before. + } + } + + private boolean containerExists() { + try { + return docker.inspectContainer(global.container).isPresent(); + } catch (DockerException e) { + return true; // let stop report the docker problem + } + } } diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index 1197268..399e242 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -1,5 +1,8 @@ package io.floci.cli.docker; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -7,7 +10,9 @@ import java.io.InputStreamReader; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @@ -48,6 +53,62 @@ public class DockerClient { public record ImageInfo(String id, String repository, String tag, String digest) {} + /** + * What a container was started with, as {@code restart} needs it back: the image, the host + * port bound to {@code containerPort}, the host directory bind-mounted at {@code /app/data} + * (null for a docker volume), and the environment. Any of them may be absent (null, or an empty map). + */ + public record RunSettings(String image, Integer hostPort, String persistSource, Map env) {} + + private static final ObjectMapper JSON = new ObjectMapper(); + + public Optional inspectRunSettings(String name, int containerPort) throws DockerException { + String out; + try { + out = run("docker", "container", "inspect", "--format", "{{json .}}", "--", name); + } catch (DockerException e) { + if (e.getMessage() != null && e.getMessage().toLowerCase().contains("no such")) { + return Optional.empty(); + } + throw e; + } + if (out.isBlank()) return Optional.empty(); + try { + JsonNode c = JSON.readTree(out); + String image = textOrNull(c.path("Config").path("Image")); + Integer hostPort = null; + JsonNode binding = c.path("HostConfig").path("PortBindings").path(containerPort + "/tcp"); + if (binding.isArray() && !binding.isEmpty()) { + String text = binding.get(0).path("HostPort").asText(""); + if (!text.isBlank()) hostPort = Integer.valueOf(text); + } + String persist = null; + for (JsonNode mount : c.path("Mounts")) { + // Only a host directory is a --persist. The images declare /app/data as a volume, + // so without --persist docker mounts an anonymous volume there; its Source is a + // path inside the docker VM, not something start can mount again. + if ("/app/data".equals(mount.path("Destination").asText()) + && "bind".equals(mount.path("Type").asText())) { + persist = textOrNull(mount.path("Source")); + } + } + Map env = new LinkedHashMap<>(); + for (JsonNode entry : c.path("Config").path("Env")) { + String kv = entry.asText(); + int eq = kv.indexOf('='); + if (eq > 0) env.put(kv.substring(0, eq), kv.substring(eq + 1)); + } + return Optional.of(new RunSettings(image, hostPort, persist, Map.copyOf(env))); + } catch (Exception e) { + throw new DockerException("Could not read the settings of container '" + name + "': " + e.getMessage()); + } + } + + private static String textOrNull(JsonNode node) { + String text = node.asText(""); + return text.isBlank() ? null : text; + } + public String dockerVersion() throws DockerException { return run("docker", "version", "--format", "{{.Server.Version}}").trim(); } diff --git a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java index a90f15f..fd5bf83 100644 --- a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java +++ b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java @@ -203,4 +203,47 @@ 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()); + } } diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java index 5c2d6b5..35db9d1 100644 --- a/src/test/java/io/floci/cli/unit/RestartCommandTest.java +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -3,7 +3,9 @@ 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.config.ProfileDefaultValueProvider; import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import picocli.CommandLine; @@ -16,6 +18,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 +36,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 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 all = new ArrayList<>(); if (product != ProductProfile.AWS) all.add(product.name()); @@ -99,7 +118,7 @@ class RestartCommandTest { @Test void withoutAProfileItStillUsesTheProductDefaults() { - List args = parse(ProductProfile.GCP).buildStartCommand().dockerRunArgs(SOCKET); + List 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); @@ -158,4 +177,32 @@ class RestartCommandTest { 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() { + 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 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 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()); + } }