mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
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:
1 parent
52ebdee98d
commit
f6cec794d7
4 files changed
+328
-5
No files matched your search
@@ -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<Integer> {
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -49,6 +59,14 @@ public class RestartCommand implements Callable<Integer> {
|
||||
// exit code matches a bad --profile at parse time.
|
||||
printer.error(e.getMessage());
|
||||
return ExitCode.USAGE;
|
||||
} catch (DockerException e) {
|
||||
// The container may well be there with settings this restart could not read. Going
|
||||
// on would remove it and bring it back on the defaults, so stop here instead.
|
||||
printer.error("Could not read how container '" + global.container + "' was started, so it was left as it is: "
|
||||
+ e.getMessage()
|
||||
+ "\nCheck that Docker is responsive ('docker info'), then re-run '"
|
||||
+ profile.commandPrefix() + " restart" + global.instanceSelector() + "'.");
|
||||
return 1;
|
||||
}
|
||||
String invalid = start.validationError();
|
||||
if (invalid != null) {
|
||||
@@ -56,6 +74,12 @@ public class RestartCommand implements Callable<Integer> {
|
||||
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;
|
||||
|
||||
@@ -83,7 +107,7 @@ public class RestartCommand implements Callable<Integer> {
|
||||
* provider, the same precedence and the same interpolation, so one profile cannot mean one
|
||||
* directory on {@code start} and a different one on {@code restart}.
|
||||
*/
|
||||
public StartCommand buildStartCommand() {
|
||||
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);
|
||||
@@ -93,6 +117,32 @@ public class RestartCommand implements Callable<Integer> {
|
||||
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. Only a container that does not exist (an empty result) means
|
||||
// "start with the defaults"; a failed read is thrown, so the caller can stop before the stop.
|
||||
private void carryOver(StartCommand start) throws DockerException {
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
private boolean containerExists() {
|
||||
try {
|
||||
return docker.inspectContainer(global.container).isPresent();
|
||||
} catch (DockerException e) {
|
||||
return true; // let stop report the docker problem
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.floci.cli.docker;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.cli.GlobalOptions;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
@@ -9,7 +11,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;
|
||||
@@ -50,6 +54,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<String, String> env) {}
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
public Optional<RunSettings> 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<String, String> 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();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user