From 895d39afb0087f88e1bf2630f6ce7ef089c1df8b Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Tue, 3 Nov 2026 23:53:22 -0600 Subject: [PATCH] fix(restart): show how to recover after startup fails When restart has removed the old container and the new one does not come up, it now prints a start command with the same port, image, persist dir, services and namespace. When the new container is running but did not become ready, it says to check logs and run wait instead, because start refuses a running container. Signed-off-by: Hector Ventura --- README.md | 6 + plugin.json | 2 +- skills/floci/SKILL.md | 4 +- src/main/java/io/floci/cli/GlobalOptions.java | 2 +- .../io/floci/cli/commands/RestartCommand.java | 31 ++++- .../io/floci/cli/commands/StartCommand.java | 34 ++++- .../floci/cli/unit/RestartRecoveryTest.java | 116 ++++++++++++++++++ 7 files changed, 188 insertions(+), 7 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/RestartRecoveryTest.java diff --git a/README.md b/README.md index be64838..85bc68b 100644 --- a/README.md +++ b/README.md @@ -489,6 +489,12 @@ stdout: the progress lines are left out and docker's pull progress goes to stder `restart` report `container`, `id`, `image`, `endpoint`, `state` and `ready` (`ready` is absent with `--detach`). `logs` prints the container's own output and stays plain text. +If `restart` fails after removing the old container, stderr includes a `start` command with +the resolved container, port, image, endpoint, persistence, services and namespace settings. +It also appears with structured output. Review the failure, then run that command to retry. If +the new container is running but did not become ready, stderr instead says to check `logs` and +run `wait`, because `start` refuses a running container. + ### `floci status` / `floci gcp status` / `floci az status` / `floci oci status` ```sh diff --git a/plugin.json b/plugin.json index 3df93ea..01636cc 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "floci", - "version": "1.0.0", + "version": "1.0.1", "description": "Run, wire up and troubleshoot Floci, the free local emulators for AWS, GCP, Azure and OCI: floci-cli lifecycle, safe wiring of aws, gcloud, az, oci and the SDKs, docker run and Docker Compose files, several instances side by side, and lookups in the published docs.", "author": { "name": "Floci", diff --git a/skills/floci/SKILL.md b/skills/floci/SKILL.md index 097373e..0490509 100644 --- a/skills/floci/SKILL.md +++ b/skills/floci/SKILL.md @@ -81,7 +81,9 @@ clouds the user works with; suggest installing them, do not install them unasked and create a new one: `restart` keeps the settings (port, image, services, persist dir, namespace) but not in-memory state, and on Azure the new container has a new certificate, so `floci az setup` must be run again. `start` on a running container fails. Say so before - recreating anything. + recreating anything. If restart fails after removal, follow stderr: a start command that + retries with the same settings, or `logs` and `wait` when the new container is up but not + ready. Neither restores in-memory state. 7. **Never add `-q` to `env`**: it suppresses the exports themselves. 8. **Do not guess what an emulator supports.** Check `floci services -o json` and the published docs ([references/docs.md](references/docs.md)) instead of answering from memory. diff --git a/src/main/java/io/floci/cli/GlobalOptions.java b/src/main/java/io/floci/cli/GlobalOptions.java index 50826a4..d1f45f4 100644 --- a/src/main/java/io/floci/cli/GlobalOptions.java +++ b/src/main/java/io/floci/cli/GlobalOptions.java @@ -125,7 +125,7 @@ public class GlobalOptions { } // POSIX single quotes: the hints are shell command lines like the CLI's other 'Run ...' hints. - private static String shellWord(String value) { + public static String shellWord(String value) { if (PLAIN_WORD.matcher(value).matches()) return value; return "'" + value.replace("'", "'\\''") + "'"; } diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index e7725b5..79aae27 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -96,7 +96,14 @@ public class RestartCommand implements Callable { int stopResult = buildStopCommand().call(); if (stopResult != 0) return stopResult; - return start.call(); + // Capture before start mutates its endpoint while waiting. This command stands alone, + // even if the profile is edited or deleted after the failed restart. + String recovery = start.recoveryCommand(); + int result = start.call(); + if (result != 0) { + printer.error(recoveryMessage(recovery)); + } + return result; } /** @@ -125,7 +132,7 @@ public class RestartCommand implements Callable { public StartCommand buildStartCommand() throws DockerException { // The outer parse's provider: its memoized profile is the snapshot the globals below were // resolved from, so the start settings cannot come from a newer version of the file. - StartCommand start = StartCommand.resolvedFor(profile, ProfileDefaultValueProvider.of(spec), global.profile); + StartCommand start = StartCommand.resolvedFor(profile, ProfileDefaultValueProvider.of(spec), global.profile, docker); // The real invocation's globals win: they already carry the profile plus any flag the // user passed, resolved once by the outer parse. @@ -153,6 +160,26 @@ public class RestartCommand implements Callable { }); } + // A new container that is up but has not answered yet cannot be started again: start refuses a + // running container. So the retry command is only for a container that did not come up. + private String recoveryMessage(String recovery) { + boolean running; + try { + running = docker.inspectContainer(global.container) + .filter(info -> "running".equals(info.state())).isPresent(); + } catch (DockerException e) { + running = false; + } + String selector = global.instanceSelector(); + if (running) { + return "The new container is running but did not become ready.\n" + + "Check it with '" + profile.commandPrefix() + " logs" + selector + "', then run '" + + profile.commandPrefix() + " wait" + selector + "' to wait again."; + } + return "Restart did not finish after the old container was removed.\n" + + "To retry with the same settings, run:\n" + recovery; + } + private boolean containerExists() { try { return docker.inspectContainer(global.container).isPresent(); diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index e9893e8..138d6e2 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -99,7 +99,14 @@ public class StartCommand implements Callable { public static StartCommand resolvedFor(ProductProfile product, ProfileDefaultValueProvider provider, String profileName) { - StartCommand start = new StartCommand(product); + return resolvedFor(product, provider, profileName, new DockerClient()); + } + + /** Reuse the caller's Docker client when a restart starts the resolved instance. */ + public static StartCommand resolvedFor(ProductProfile product, + ProfileDefaultValueProvider provider, + String profileName, DockerClient docker) { + StartCommand start = new StartCommand(product, docker); if (profileName != null) { new CommandLine(start) .setCaseInsensitiveEnumValuesAllowed(true) @@ -109,6 +116,22 @@ public class StartCommand implements Callable { return start; } + /** A self-contained POSIX command that recovers the resolved settings after a failed restart. */ + public String recoveryCommand() { + StringBuilder command = new StringBuilder(profile.commandPrefix()).append(" start"); + command.append(" --container ").append(GlobalOptions.shellWord(global.container)); + command.append(" --port ").append(port); + command.append(" --image ").append(GlobalOptions.shellWord(image)); + // --port already moves the default endpoint, so only a different one is worth naming. + if (!profile.defaultEndpoint().equals(global.endpoint)) { + command.append(" --endpoint ").append(GlobalOptions.shellWord(global.endpoint)); + } + if (persistDir != null) command.append(" --persist ").append(GlobalOptions.shellWord(persistDir)); + if (services != null) command.append(" --services ").append(GlobalOptions.shellWord(services)); + if (namespace != null) command.append(" --namespace ").append(GlobalOptions.shellWord(namespace)); + return command.toString(); + } + /** What a profile-resolved instance would start with. Read by {@code config show}. */ public String image() { return image; } @@ -433,9 +456,16 @@ public class StartCommand implements Callable { return exit; } + private String readinessTimeout = "30s"; + /** How long start waits for the emulator to answer. A seam: tests do not wait half a minute. */ protected String readinessTimeout() { - return "30s"; + return readinessTimeout; + } + + /** Test seam for a start built by {@code restart}, which cannot be subclassed from outside. */ + public void readinessTimeout(String timeout) { + this.readinessTimeout = timeout; } // What -o json/yaml reports for a start: 'ready' is left out when --detach did not wait for it. diff --git a/src/test/java/io/floci/cli/unit/RestartRecoveryTest.java b/src/test/java/io/floci/cli/unit/RestartRecoveryTest.java new file mode 100644 index 0000000..c41317e --- /dev/null +++ b/src/test/java/io/floci/cli/unit/RestartRecoveryTest.java @@ -0,0 +1,116 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.RestartCommand; +import io.floci.cli.commands.StartCommand; +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; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +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.*; + +class RestartRecoveryTest { + @TempDir Path profiles; + + static class FailedStart extends DockerClient { + String state = "running"; + boolean failStop; + final List actions = new ArrayList<>(); + @Override public DockerHost daemonHost() { return new DockerHost(Kind.TCP, null, "tcp://host:2375"); } + @Override public Optional inspectContainer(String name) { + return state == null ? Optional.empty() : Optional.of(new ContainerInfo("id", name, "floci/floci-gcp:0.9", state, "14588->4588/tcp")); + } + @Override public Optional inspectRunSettings(String name, int port) { + return Optional.of(new RunSettings("floci/floci-gcp:0.9", 14588, "/data/team's state", + Map.of("FLOCI_GCP_SERVICES", "storage,pubsub", "FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE", "team"))); + } + @Override public void stopContainer(String name, int timeout) throws DockerException { + if (failStop) throw new DockerException("stop failed"); + actions.add("stop"); state = "exited"; + } + @Override public void removeContainer(String name) { actions.add("remove"); state = null; } + @Override public void pull(String image, String policy) { } + @Override public void pull(String image, String policy, PrintStream stream) { } + @Override public String startContainer(List args) throws DockerException { + actions.add("run"); throw new DockerException("run failed"); + } + } + + @Test + void failedStartReportsACopyableSnapshotInTextAndJson() throws Exception { + for (String format : List.of("text", "json")) { + FailedStart docker = new FailedStart(); + var restart = new RestartCommand(ProductProfile.GCP, docker); + CommandLine command = new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(profiles))); + PrintStream out = System.out, err = System.err; + ByteArrayOutputStream captured = new ByteArrayOutputStream(), stdout = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(captured)); System.setOut(new PrintStream(stdout)); + assertEquals(1, command.execute("--container", "floci-gcp-team", "-o", format)); + } finally { System.setErr(err); System.setOut(out); } + assertEquals(List.of("stop", "remove", "run"), docker.actions); + String line = captured.toString().lines().filter(s -> s.startsWith("floci gcp start")).findFirst().orElseThrow(); + assertTrue(line.contains("--port 14588"), line); + assertTrue(line.contains("--image floci/floci-gcp:0.9"), line); + assertTrue(line.contains("--persist '/data/team'\\''s state'"), line); + assertTrue(line.contains("--services storage,pubsub --namespace team"), line); + assertTrue(line.contains("--container floci-gcp-team"), line); + assertFalse(line.contains("--endpoint"), line); + if (format.equals("json")) assertEquals("", stdout.toString()); + } + } + + @Test + void aRunningContainerThatIsNotReadyGetsLogsAndWaitNotARefusedStart() throws Exception { + FailedStart docker = new FailedStart() { + @Override public String startContainer(List args) { + actions.add("run"); state = "running"; return "new-id"; + } + }; + var restart = new RestartCommand(ProductProfile.GCP, docker) { + @Override public StartCommand buildStartCommand() throws DockerException { + StartCommand start = super.buildStartCommand(); + start.readinessTimeout("1ms"); + return start; + } + }; + CommandLine command = new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(profiles))); + PrintStream out = System.out, err = System.err; + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(stderr)); System.setOut(new PrintStream(new ByteArrayOutputStream())); + assertEquals(1, command.execute("--container", "floci-gcp-team")); + } finally { System.setErr(err); System.setOut(out); } + String text = stderr.toString(); + assertTrue(text.contains("running but did not become ready"), text); + assertTrue(text.contains("floci gcp logs --container floci-gcp-team"), text); + assertTrue(text.contains("floci gcp wait --container floci-gcp-team"), text); + assertFalse(text.contains("floci gcp start --container"), text); + } + + @Test + void failedStopDoesNotClaimTheOldContainerWasRemoved() { + FailedStart docker = new FailedStart(); docker.failStop = true; + PrintStream err = System.err; ByteArrayOutputStream captured = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(captured)); + assertEquals(1, new CommandLine(new RestartCommand(ProductProfile.GCP, docker)).execute()); + } finally { System.setErr(err); } + assertFalse(captured.toString().contains("old container was removed")); + assertTrue(docker.actions.isEmpty()); + } +}