mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-23 06:00:47 -05:00
feat(config): validate Compose files by their structure, with -o json and three more checks (#61)
* feat(config): validate Compose files by their structure, with -o json and three more checks config validate now parses the Compose file and checks the emulator's own service: any host port mapped to the emulator port is accepted (5566:4566 was rejected), -o json and -o yaml report the findings, and it flags a read-only or file-bound data volume, a data volume without persistent storage mode (and the reverse), and an image tag older than the supported minimum. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * feat(config): check the socket target, TCP mappings and bind types, and report unparsable files as JSON The socket has to land at /var/run/docker.sock in the container, a UDP mapping no longer counts, a long-form bind with a bare name is checked as a path, an env_file makes the storage mode unknown, and a file that cannot be parsed still gets a structured report. Signed-off-by: Hector Ventura <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
4a9a9b5a4a
commit
6b06382516
5 files changed
+791
-32
No files matched your search
@@ -0,0 +1,267 @@
|
||||
package io.floci.cli.commands.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.doctor.checks.ImageVersionCheck;
|
||||
import io.floci.cli.update.Version;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What {@code config validate} finds in a Compose file. It reads the parsed document and looks
|
||||
* at the one service that runs the product's emulator, so a port or a volume on some other
|
||||
* service is never taken for the emulator's.
|
||||
*/
|
||||
public final class ComposeCheck {
|
||||
|
||||
/** The directory the emulator keeps its state in, inside the container. */
|
||||
static final String DATA_DIR = "/app/data";
|
||||
|
||||
private ComposeCheck() {}
|
||||
|
||||
/**
|
||||
* The findings for one file. {@code service} is the Compose service that was checked, or null
|
||||
* when none could be told apart as the emulator's.
|
||||
*/
|
||||
public record Report(String service, List<String> errors, List<String> warnings) {
|
||||
|
||||
public boolean valid() {
|
||||
return errors.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the emulator looks for the Docker socket, inside the container. */
|
||||
static final String DOCKER_SOCK = "/var/run/docker.sock";
|
||||
|
||||
/**
|
||||
* A volume entry, from either the short {@code src:dst[:mode]} or the long form. {@code bind}
|
||||
* is true when the source is a path on the host rather than a named volume.
|
||||
*/
|
||||
record Mount(String source, String target, boolean readOnly, boolean bind) {}
|
||||
|
||||
/**
|
||||
* @param baseDir the Compose file's directory, against which relative bind sources resolve
|
||||
*/
|
||||
public static Report analyze(JsonNode compose, ProductProfile profile, boolean dockerSockRequired,
|
||||
String dockerSockNeededFor, Path baseDir) {
|
||||
List<String> errors = new ArrayList<>();
|
||||
List<String> warnings = new ArrayList<>();
|
||||
JsonNode services = compose.path("services");
|
||||
if (!services.isObject() || services.isEmpty()) {
|
||||
errors.add("No services found: a Compose file needs a 'services' section with the "
|
||||
+ profile.displayName() + " service in it");
|
||||
return new Report(null, errors, warnings);
|
||||
}
|
||||
|
||||
String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1);
|
||||
Map.Entry<String, JsonNode> found = null;
|
||||
for (Map.Entry<String, JsonNode> service : services.properties()) {
|
||||
String repository = repositoryOf(service.getValue().path("image").asText(""));
|
||||
if (repository.equals(profile.image()) || repository.equals("docker.io/" + profile.image())
|
||||
|| repository.equals(ghcrImage)) {
|
||||
found = service;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found == null) {
|
||||
warnings.add(profile.displayName() + " image reference not detected — ensure your service uses "
|
||||
+ profile.image() + " or " + ghcrImage);
|
||||
// With one service there is no doubt which one is meant (a locally built image, a
|
||||
// mirror); with several, checking the wrong one would only mislead.
|
||||
if (services.size() != 1) {
|
||||
return new Report(null, errors, warnings);
|
||||
}
|
||||
found = services.properties().iterator().next();
|
||||
}
|
||||
|
||||
JsonNode service = found.getValue();
|
||||
List<Mount> mounts = mounts(service.path("volumes"));
|
||||
Map<String, String> environment = environment(service.path("environment"));
|
||||
int port = profile.defaultPort();
|
||||
|
||||
// The container side is what the emulator opens; the host side may be any socket (Podman's,
|
||||
// a rootless Docker's), so only the target is checked.
|
||||
if (mounts.stream().noneMatch(m -> DOCKER_SOCK.equals(stripTrailingSlash(m.target())))) {
|
||||
(dockerSockRequired ? errors : warnings)
|
||||
.add("Missing " + DOCKER_SOCK + " volume mount — required for " + dockerSockNeededFor);
|
||||
}
|
||||
|
||||
// With host networking the container's ports are the host's; there is nothing to map.
|
||||
if (!"host".equals(service.path("network_mode").asText("")) && !publishes(service.path("ports"), port)) {
|
||||
errors.add("No port mapping for " + port + " found — " + profile.displayName() + " listens on " + port
|
||||
+ " inside the container; map any host port to it, for example \"" + port + ":" + port + "\"");
|
||||
}
|
||||
|
||||
Mount data = mounts.stream().filter(m -> DATA_DIR.equals(stripTrailingSlash(m.target()))).findFirst().orElse(null);
|
||||
String storageVar = profile.envVar("STORAGE_MODE");
|
||||
String storageMode = environment.get(storageVar);
|
||||
// A value Compose will substitute (${MODE:-persistent}) cannot be judged from here, and
|
||||
// neither can one an env_file may set: the file is not read.
|
||||
boolean storageKnown = storageMode == null
|
||||
? service.path("env_file").isMissingNode() || service.path("env_file").isNull()
|
||||
: !storageMode.contains("${");
|
||||
if (data != null && storageKnown && !"persistent".equalsIgnoreCase(storageMode)) {
|
||||
warnings.add("A volume is mounted at " + DATA_DIR + " but " + storageVar + " is not 'persistent' — "
|
||||
+ "the emulator keeps its state in memory by default, so the volume stays empty");
|
||||
}
|
||||
if (data == null && "persistent".equalsIgnoreCase(storageMode)) {
|
||||
warnings.add(storageVar + " is 'persistent' but nothing is mounted at " + DATA_DIR
|
||||
+ " — the state is lost when the container is removed");
|
||||
}
|
||||
if (data != null) {
|
||||
if (data.readOnly()) {
|
||||
errors.add("The volume at " + DATA_DIR + " is mounted read-only — the emulator cannot save its state there");
|
||||
}
|
||||
String notADirectory = fileWhereADirectoryIsNeeded(data, baseDir);
|
||||
if (notADirectory != null) {
|
||||
errors.add("The volume at " + DATA_DIR + " is bound to " + notADirectory + ", which is a file, not a directory");
|
||||
}
|
||||
}
|
||||
|
||||
String tag = tagOf(service.path("image").asText(""));
|
||||
// The minimum is the AWS emulator's; the other emulators are versioned on their own lines.
|
||||
if ("aws".equals(profile.name()) && Version.isValid(tag)
|
||||
&& !ImageVersionCheck.meetsMinimum(tag, ImageVersionCheck.MIN_VERSION)) {
|
||||
warnings.add("Image tag " + tag + " is older than " + ImageVersionCheck.MIN_VERSION
|
||||
+ ", the oldest version this CLI supports — use a newer tag");
|
||||
}
|
||||
|
||||
return new Report(found.getKey(), errors, warnings);
|
||||
}
|
||||
|
||||
/** {@code registry/name:tag@digest} without its tag and digest. */
|
||||
public static String repositoryOf(String image) {
|
||||
String reference = image.strip();
|
||||
int digest = reference.indexOf('@');
|
||||
if (digest >= 0) reference = reference.substring(0, digest);
|
||||
int colon = reference.lastIndexOf(':');
|
||||
// A colon before the last slash is a registry port, not a tag.
|
||||
return colon > reference.lastIndexOf('/') ? reference.substring(0, colon) : reference;
|
||||
}
|
||||
|
||||
/** The tag of an image reference, or an empty string when it has none. */
|
||||
public static String tagOf(String image) {
|
||||
String reference = image.strip();
|
||||
int digest = reference.indexOf('@');
|
||||
if (digest >= 0) reference = reference.substring(0, digest);
|
||||
int colon = reference.lastIndexOf(':');
|
||||
return colon > reference.lastIndexOf('/') ? reference.substring(colon + 1) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether one of a service's {@code ports} entries reaches {@code port} inside the container,
|
||||
* whatever the host side is: {@code 4566}, {@code "4566:4566"}, {@code "5566:4566"},
|
||||
* {@code "127.0.0.1:5566:4566/tcp"}, a range that contains it, or the long form's {@code target}.
|
||||
*/
|
||||
public static boolean publishes(JsonNode ports, int port) {
|
||||
for (JsonNode entry : ports) {
|
||||
if (entry.isObject()) {
|
||||
if (entry.path("target").asInt(-1) == port && isTcp(entry.path("protocol").asText(""))) return true;
|
||||
continue;
|
||||
}
|
||||
String text = entry.asText("").strip();
|
||||
int slash = text.indexOf('/');
|
||||
String protocol = slash >= 0 ? text.substring(slash + 1) : "";
|
||||
if (slash >= 0) text = text.substring(0, slash);
|
||||
String container = text.substring(text.lastIndexOf(':') + 1);
|
||||
if (isTcp(protocol) && inRange(container, port)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The emulator's endpoint is HTTP: a UDP mapping of the same number does not reach it. An
|
||||
// entry without a protocol is TCP, as Compose reads it.
|
||||
private static boolean isTcp(String protocol) {
|
||||
return protocol.isBlank() || "tcp".equalsIgnoreCase(protocol.strip());
|
||||
}
|
||||
|
||||
private static boolean inRange(String spec, int port) {
|
||||
try {
|
||||
int dash = spec.indexOf('-');
|
||||
if (dash < 0) return Integer.parseInt(spec.strip()) == port;
|
||||
return Integer.parseInt(spec.substring(0, dash).strip()) <= port
|
||||
&& port <= Integer.parseInt(spec.substring(dash + 1).strip());
|
||||
} catch (NumberFormatException e) {
|
||||
return false; // a ${VARIABLE} or something else that is not a number
|
||||
}
|
||||
}
|
||||
|
||||
static List<Mount> mounts(JsonNode volumes) {
|
||||
List<Mount> mounts = new ArrayList<>();
|
||||
for (JsonNode entry : volumes) {
|
||||
if (entry.isObject()) {
|
||||
// In the long form the type says what the source is; a bind's is a host path
|
||||
// even when it is a bare name like 'data'.
|
||||
mounts.add(new Mount(entry.path("source").asText(""), entry.path("target").asText(""),
|
||||
entry.path("read_only").asBoolean(false), "bind".equals(entry.path("type").asText(""))));
|
||||
continue;
|
||||
}
|
||||
String text = entry.asText("");
|
||||
// A Windows source (C:\data:/app/data) has a colon of its own after the drive letter.
|
||||
int from = startsWithDrive(text) ? 2 : 0;
|
||||
int first = text.indexOf(':', from);
|
||||
if (first < 0) {
|
||||
mounts.add(new Mount("", text, false, false)); // an anonymous volume: only the container path
|
||||
continue;
|
||||
}
|
||||
String source = text.substring(0, first);
|
||||
String rest = text.substring(first + 1);
|
||||
int second = rest.indexOf(':');
|
||||
String target = second < 0 ? rest : rest.substring(0, second);
|
||||
String mode = second < 0 ? "" : rest.substring(second + 1);
|
||||
// In the short form a source is a host path when it looks like one; a bare name is a
|
||||
// named volume.
|
||||
boolean bind = source.startsWith("/") || source.startsWith(".") || source.startsWith("~")
|
||||
|| startsWithDrive(source);
|
||||
mounts.add(new Mount(source, target, List.of(mode.split(",")).contains("ro"), bind));
|
||||
}
|
||||
return mounts;
|
||||
}
|
||||
|
||||
private static boolean startsWithDrive(String text) {
|
||||
return text.length() > 2 && Character.isLetter(text.charAt(0)) && text.charAt(1) == ':'
|
||||
&& (text.charAt(2) == '\\' || text.charAt(2) == '/');
|
||||
}
|
||||
|
||||
/** A service's {@code environment}, from either the mapping or the {@code KEY=value} list form. */
|
||||
static Map<String, String> environment(JsonNode environment) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
if (environment.isObject()) {
|
||||
for (Map.Entry<String, JsonNode> entry : environment.properties()) {
|
||||
values.put(entry.getKey(), entry.getValue().asText(""));
|
||||
}
|
||||
} else {
|
||||
for (JsonNode entry : environment) {
|
||||
String text = entry.asText("");
|
||||
int equals = text.indexOf('=');
|
||||
if (equals > 0) values.put(text.substring(0, equals), text.substring(equals + 1));
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static String stripTrailingSlash(String path) {
|
||||
return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
|
||||
}
|
||||
|
||||
// Best effort: only a bind source that already exists on this machine can be looked at. A
|
||||
// named volume, a ${VARIABLE}, a home-relative path Compose expands itself, or a path that
|
||||
// is not there yet says nothing.
|
||||
private static String fileWhereADirectoryIsNeeded(Mount mount, Path baseDir) {
|
||||
if (!mount.bind() || mount.source().isBlank() || mount.source().contains("${") || mount.source().startsWith("~")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Path path = baseDir.resolve(mount.source()).normalize();
|
||||
return Files.isRegularFile(path) ? path.toString() : null;
|
||||
} catch (InvalidPathException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,22 @@
|
||||
package io.floci.cli.commands.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import io.floci.cli.GlobalOptions;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.output.Ansi;
|
||||
import io.floci.cli.output.OutputFormat;
|
||||
import io.floci.cli.output.Printer;
|
||||
import picocli.CommandLine.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Command(
|
||||
name = "validate",
|
||||
@@ -21,6 +25,8 @@ import java.util.regex.Pattern;
|
||||
)
|
||||
public class ConfigValidateCommand implements Callable<Integer> {
|
||||
|
||||
private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory());
|
||||
|
||||
protected final ProductProfile profile;
|
||||
private final boolean dockerSockRequired;
|
||||
private final String dockerSockNeededFor;
|
||||
@@ -61,50 +67,68 @@ public class ConfigValidateCommand implements Callable<Integer> {
|
||||
return 1;
|
||||
}
|
||||
|
||||
printer.println(Ansi.bold("Validating") + " " + composeFile);
|
||||
JsonNode compose = null;
|
||||
String unreadable = null;
|
||||
try {
|
||||
compose = YAML.readTree(content);
|
||||
if (compose == null || !compose.isObject()) {
|
||||
unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping";
|
||||
}
|
||||
} catch (IOException e) {
|
||||
String reason = e.getMessage() == null ? "unreadable" : e.getMessage().lines().findFirst().orElse("unreadable");
|
||||
unreadable = "Could not read " + composeFile + " as YAML: " + reason;
|
||||
}
|
||||
if (unreadable != null) {
|
||||
// Structured output always carries the report, so a script reading it gets 'valid: false'
|
||||
// and the reason rather than nothing.
|
||||
if (printer.format() != OutputFormat.text) {
|
||||
printer.structured(document(composeFile, new ComposeCheck.Report(null, List.of(unreadable), List.of())));
|
||||
} else {
|
||||
printer.error(unreadable, "Fix the file's syntax, or pass another with --file.");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
Path baseDir = composeFile.toAbsolutePath().getParent();
|
||||
ComposeCheck.Report report = ComposeCheck.analyze(compose, profile, dockerSockRequired, dockerSockNeededFor, baseDir);
|
||||
|
||||
if (printer.format() != OutputFormat.text) {
|
||||
printer.structured(document(composeFile, report));
|
||||
return report.valid() ? 0 : 1;
|
||||
}
|
||||
|
||||
printer.println(Ansi.bold("Validating") + " " + composeFile
|
||||
+ (report.service() == null ? "" : Ansi.gray(" (service: " + report.service() + ")")));
|
||||
printer.println("");
|
||||
|
||||
List<String> issues = new ArrayList<>();
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
// Check for docker.sock mount (an error where the product needs it for core services)
|
||||
if (!content.contains("/var/run/docker.sock")) {
|
||||
(dockerSockRequired ? issues : warnings)
|
||||
.add("Missing /var/run/docker.sock volume mount — required for " + dockerSockNeededFor);
|
||||
}
|
||||
|
||||
// Check port mapping
|
||||
int port = profile.defaultPort();
|
||||
if (!Pattern.compile(port + "\\s*:\\s*" + port).matcher(content).find()) {
|
||||
issues.add("Port mapping " + port + ":" + port + " not found — " + profile.displayName()
|
||||
+ " listens on " + port + " by default");
|
||||
}
|
||||
|
||||
// Check for the product image
|
||||
String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1);
|
||||
if (!content.contains(profile.image()) && !content.contains(ghcrImage)) {
|
||||
warnings.add(profile.displayName() + " image reference not detected — ensure your service uses "
|
||||
+ profile.image() + " or " + ghcrImage);
|
||||
}
|
||||
|
||||
for (String issue : issues) {
|
||||
for (String issue : report.errors()) {
|
||||
printer.println(" " + Ansi.red("✗") + " " + issue);
|
||||
}
|
||||
for (String warn : warnings) {
|
||||
for (String warn : report.warnings()) {
|
||||
printer.println(" " + Ansi.yellow("⚠") + " " + warn);
|
||||
}
|
||||
if (issues.isEmpty() && warnings.isEmpty()) {
|
||||
if (report.errors().isEmpty() && report.warnings().isEmpty()) {
|
||||
printer.println(" " + Ansi.green("✓") + " Compose file looks good");
|
||||
}
|
||||
|
||||
printer.println("");
|
||||
if (!issues.isEmpty()) {
|
||||
printer.println(issues.size() + " error(s) found.");
|
||||
if (!report.valid()) {
|
||||
printer.println(report.errors().size() + " error(s) found.");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static Map<String, Object> document(Path composeFile, ComposeCheck.Report report) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("file", composeFile.toString());
|
||||
out.put("service", report.service());
|
||||
out.put("valid", report.valid());
|
||||
out.put("errors", report.errors());
|
||||
out.put("warnings", report.warnings());
|
||||
return out;
|
||||
}
|
||||
|
||||
private Path resolveComposeFile() {
|
||||
if (file != null) return Path.of(file);
|
||||
for (String name : List.of("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml")) {
|
||||
|
||||
@@ -15,7 +15,8 @@ public class ImageVersionCheck implements Check {
|
||||
|
||||
private final String image;
|
||||
private final DockerClient docker;
|
||||
private static final String MIN_VERSION = "1.5.0";
|
||||
/** The oldest server version this CLI supports. */
|
||||
public static final String MIN_VERSION = "1.5.0";
|
||||
|
||||
public ImageVersionCheck() {
|
||||
this("floci/floci");
|
||||
|
||||
Reference in new issue
Block a user