From 788eb470fb2d51b0d2b6743a060e709d9970c34d Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 8 Oct 2026 21:34:15 -0500 Subject: [PATCH] feat(config): create profiles for instances that run side by side (#30) --- AGENTS.md | 10 ++ README.md | 47 +++++++- .../commands/config/ConfigProfileCommand.java | 111 +++++++++++++++++- .../io/floci/cli/unit/ConfigCommandsTest.java | 111 ++++++++++++++++++ 4 files changed, 274 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ebe5b9a..669b85f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,6 +116,16 @@ Rules when touching this: - Commands that build another command programmatically (`RestartCommand` → `StartCommand`) are never parsed by picocli, so they must carry the profile across by hand. - Use `FlociCli.buildCommandLine(ProfileStore)` in tests — `new CommandLine(new FlociCli())` has none of the wiring. +### Multiple instances + +An instance is a profile: its container name is its identity, its port is the only thing that must differ, and its persist dir keeps its state. Rules: + +- Commands find their instance through the container (`GlobalOptions.resolvedEndpoint`); never persist an endpoint as instance identity. +- Local state about one running instance (certificates, generated vendor-CLI config) lives under `InstanceState.dir(product, container)`, which is `~/.floci///`. Never a fixed per-product path: a second instance would overwrite the first. `floci az setup` is the reference (its az cloud is also named after the container). +- Hints that tell the user to re-run a command append `global.instanceSelector()` so they select the same instance again. +- Instance-independent state (the OCI CLI profile from `floci oci setup`) may stay shared. +- `config profile create` takes `--container --port --persist --services --image` (and `--endpoint`); it reads only flags the user typed (`ParseResult.hasMatchedOption`), never values the profile provider or `FLOCI_*` env vars applied. + ### Self-update `UpdateCommand` (`floci update`) downloads the release binary for the current platform, verifies its sha256 against the release's `sha256sums.txt`, and atomically replaces the running binary (staged in the same directory, `ATOMIC_MOVE`). It refuses to update Homebrew-managed installs. `--check` exits 0 when up to date, 1 when an update is available. `ReleaseChannel` builds the GitHub release asset URLs. diff --git a/README.md b/README.md index 13bb82f..4dc9cca 100644 --- a/README.md +++ b/README.md @@ -630,8 +630,9 @@ floci services -o json ```sh floci config show # show active configuration floci config default-product aws|gcp|az|oci # set the default product (persisted to ~/.floci/config.yaml) -floci config profile list # list saved profiles -floci config profile create # create a new profile +floci config profile list # list saved profiles: container, port, data dir +floci config profile create # create a new profile with the tree's defaults +floci config profile create --container --port

--persist

--services --image floci config profile show # show a profile floci config profile delete # delete a profile floci config validate -f docker-compose.yml # validate a Compose file @@ -688,6 +689,48 @@ expect. > restart. A plain `floci restart` has no `--persist` flag of its own and still falls back to the > defaults. +#### Running several instances side by side + +An instance is a profile. Its **container name** is its identity, its **port** is the only thing +that must differ from the other instances, and its **persist dir** keeps its state across +container recreation. Every command (`status`, `logs`, `env`, `doctor`, `stop`, ...) finds the +instance through its container, so passing the same `--profile` is all it takes. Any local state +the CLI keeps about an instance lives in `~/.floci///`. + +Leave `endpoint` at the product default: the CLI reads the real host port from the running +container. `config profile create` warns when a new profile reuses another profile's container, +or its port on the same image. + +```sh +# AWS +floci config profile create aws-a --container floci-a --port 4566 --persist ~/.floci/data/aws-a +floci config profile create aws-b --container floci-b --port 14566 --persist ~/.floci/data/aws-b +floci start --profile aws-a && floci start --profile aws-b +eval $(floci env --profile aws-b) # AWS_ENDPOINT_URL points at :14566 + +# GCP +floci gcp config profile create gcp-b --container floci-gcp-b --port 14588 --persist ~/.floci/data/gcp-b +floci gcp start --profile gcp-b +eval $(floci gcp env --profile gcp-b) + +# Azure: setup is per instance too (its own certificate, az cloud and login) +floci az config profile create az-b --container floci-az-b --port 14577 --persist ~/.floci/data/az-b +floci az start --profile az-b +floci az setup --profile az-b +eval $(floci az env --profile az-b) # plain az now talks to floci-az-b only + +# OCI: 'floci oci setup' is shared, the endpoint is per instance +floci oci config profile create oci-b --container floci-oci-b --port 14599 --persist ~/.floci/data/oci-b +floci oci start --profile oci-b +eval $(floci oci env --profile oci-b) + +floci config profile list # one row per instance +floci stop --profile aws-b # stop one, the others keep running +``` + +Without `--persist` an instance starts empty each time its container is recreated. For floci-az +it also gets a new certificate, which `floci az env` reports so you can re-run `floci az setup`. + ### `floci snapshot` Save and restore named snapshots of Floci AWS state. diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java index a600ecc..9f1cfec 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -5,11 +5,17 @@ import io.floci.cli.ProductProfile; import io.floci.cli.config.Profile; import io.floci.cli.config.ProfileStore; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import picocli.CommandLine.Model.CommandSpec; import java.io.IOException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.Callable; @Command( @@ -48,6 +54,23 @@ public class ConfigProfileCommand implements Callable { @Parameters(index = "1", description = "Profile name (required for show, create, delete)", arity = "0..1", paramLabel = "") String name; + // create only. With --container they describe one instance, so several profiles can run the + // same emulator side by side; unset ones keep the defaults of the tree create runs under. + @Option(names = {"--port"}, description = "create: host port for this instance", paramLabel = "") + Integer port; + + @Option(names = {"--image"}, description = "create: Docker image for this instance", paramLabel = "") + String image; + + @Option(names = {"--persist"}, description = "create: host directory that keeps this instance's state", paramLabel = "") + String persistDir; + + @Option(names = {"--services"}, description = "create: comma-separated services to enable", paramLabel = "") + String services; + + @Spec + CommandSpec spec; + @Override public Integer call() { Printer printer = global.printer(); @@ -66,14 +89,39 @@ public class ConfigProfileCommand implements Callable { private int listProfiles(Printer printer, ProfileStore store) { try { - List profiles = store.list(); + List profiles = store.list().stream() + .sorted(Comparator.comparing(p -> String.valueOf(p.name))) + .toList(); + // Structured output first: an empty store is still a valid, parseable empty list. + if (printer.format() != OutputFormat.text) { + List> out = new ArrayList<>(); + for (Profile p : profiles) { + Map row = new LinkedHashMap<>(); + row.put("name", p.name); + row.put("container", p.container); + row.put("port", p.port); + row.put("endpoint", p.endpoint); + row.put("image", p.image); + row.put("persistDir", p.persistDir); + row.put("services", p.services); + out.add(row); + } + printer.structured(out); + return 0; + } if (profiles.isEmpty()) { printer.println(Ansi.gray("No profiles found. Create one with: " + profile.commandPrefix() + " config profile create ")); return 0; } + // One row per instance: the container and port are what tell two instances apart. printer.println(Ansi.bold("Profiles:")); + int width = profiles.stream().mapToInt(p -> String.valueOf(p.name).length()).max().orElse(0); for (Profile p : profiles) { - printer.println(" " + p.name + Ansi.gray(" " + (p.endpoint != null ? p.endpoint : ""))); + StringBuilder row = new StringBuilder(" ").append(pad(String.valueOf(p.name), width)); + if (p.container != null) row.append(" ").append(p.container); + if (p.port != null) row.append(Ansi.gray(" :" + p.port)); + if (p.persistDir != null) row.append(Ansi.gray(" " + p.persistDir)); + printer.println(row.toString()); } return 0; } catch (IOException e) { @@ -109,10 +157,27 @@ public class ConfigProfileCommand implements Callable { printer.error("Profile '" + name + "' already exists. Delete it first or edit " + store.profileFile(name)); return 1; } + if (port != null && (port < 1 || port > 65535)) { + printer.error("--port must be between 1 and 65535, but was " + port + ".\n" + + "Pick a free port, for example " + (profile.defaultPort() + 10000) + "."); + return 1; + } Profile p = new Profile(profile, name); + // Only flags the user typed: the mixin's own values may come from FLOCI_* env vars, and + // a provider-applied --profile, neither of which should be baked into a new file. + if (typed("--container")) p.container = global.container; + if (typed("--endpoint")) p.endpoint = global.endpoint; + if (typed("--port")) p.port = port; + if (typed("--image")) p.image = image; + if (typed("--persist")) p.persistDir = persistDir; + if (typed("--services")) p.services = services; + + for (String warning : collisions(store.list(), p)) { + printer.warn(warning); + } store.save(p); printer.println(Ansi.green("Created") + " profile '" + name + "' at " + store.profileFile(name)); - printer.println(Ansi.gray("Edit the file to customize endpoint, container, image, etc.")); + printer.println(Ansi.gray("Start it with: " + profile.commandPrefix() + " start --profile " + name)); return 0; } catch (IOException e) { printer.error("Could not create profile: " + e.getMessage()); @@ -120,6 +185,46 @@ public class ConfigProfileCommand implements Callable { } } + private boolean typed(String option) { + return spec.commandLine().getParseResult().hasMatchedOption(option); + } + + /** + * Two profiles that share a container are the same instance, and two that share a port on the + * same image cannot run at once. Both are legitimate (one instance, used at different times), + * so they are warnings, not errors. + */ + static List collisions(List existing, Profile created) { + List warnings = new ArrayList<>(); + for (Profile other : existing) { + if (other.name == null || other.name.equals(created.name)) continue; + if (created.container != null && created.container.equals(other.container)) { + warnings.add("Profile '" + other.name + "' already uses container '" + created.container + "'.\n" + + "Pick another --container, or start only one of them at a time."); + } else if (created.port != null && created.port.equals(other.port) + && repository(created.image).equals(repository(other.image))) { + warnings.add("Profile '" + other.name + "' already uses port " + created.port + ".\n" + + "Pick another --port, or start only one of them at a time."); + } + } + return warnings; + } + + // floci/floci-az:latest -> floci/floci-az, so two tags of one emulator still collide on a port. + private static String repository(String image) { + if (image == null) return ""; + // A digest (repo@sha256:...) carries a colon of its own; drop it before looking for a tag. + int digest = image.indexOf('@'); + if (digest >= 0) image = image.substring(0, digest); + int slash = image.lastIndexOf('/'); + int colon = image.lastIndexOf(':'); + return colon > slash ? image.substring(0, colon) : image; + } + + private static String pad(String s, int width) { + return s.length() >= width ? s : s + " ".repeat(width - s.length()); + } + private int deleteProfile(Printer printer, ProfileStore store) { if (name == null) { printer.error("Profile name required."); return 1; } try { diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index e8164a7..d505d0d 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -106,4 +106,115 @@ class ConfigCommandsTest { assertEquals("floci/floci-gcp:latest", created.image); assertEquals(4588, created.port); } + + private record Run(int exit, String out, String err) {} + + private Run profileCmd(ProductProfile product, String... args) { + CommandLine cmd = new CommandLine(new ConfigProfileCommand(product, store())) + .setCaseInsensitiveEnumValuesAllowed(true) + .setDefaultValueProvider(new ProfileDefaultValueProvider(store())); + 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 { + int exit = cmd.execute(args); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void createTakesTheInstanceFlagsInEveryTree() throws Exception { + for (ProductProfile product : new ProductProfile[]{ProductProfile.AWS, ProductProfile.GCP, + ProductProfile.AZ, ProductProfile.OCI}) { + String name = "inst-" + product.name(); + assertEquals(0, profileCmd(product, "create", name, + "--container", "floci-" + product.name() + "-b", "--port", "14000", + "--persist", "/data/" + product.name(), "--services", "x,y").exit()); + + Profile p = store().get(name).orElseThrow(); + assertEquals("floci-" + product.name() + "-b", p.container); + assertEquals(14000, p.port); + assertEquals("/data/" + product.name(), p.persistDir); + assertEquals("x,y", p.services); + // Untyped flags keep the defaults of the tree create ran under. + assertEquals(product.defaultEndpoint(), p.endpoint); + assertEquals(product.defaultImageRef(), p.image); + } + } + + @Test + void createIgnoresAnotherProfilesValuesAndTakesOnlyTypedFlags() throws Exception { + writeProfile("a", "container: floci-az-a\nport: 14577\npersistDir: /data/a\n"); + + assertEquals(0, profileCmd(ProductProfile.AZ, "create", "b", "--profile", "a", "--port", "14578").exit()); + + Profile b = store().get("b").orElseThrow(); + assertEquals(14578, b.port); + assertEquals("floci-az", b.container); + assertNull(b.persistDir); + } + + @Test + void createRefusesAPortOutOfRange() throws Exception { + Run r = profileCmd(ProductProfile.AZ, "create", "bad", "--port", "70000"); + + assertEquals(1, r.exit()); + assertTrue(store().get("bad").isEmpty()); + } + + @Test + void createWarnsWhenAnotherProfileClaimsTheSameContainerOrPort() throws Exception { + writeProfile("a", "container: floci-az-a\nport: 14577\nimage: floci/floci-az:latest\n"); + + Run sameContainer = profileCmd(ProductProfile.AZ, "create", "b", "--container", "floci-az-a", "--port", "14999"); + assertEquals(0, sameContainer.exit()); + assertTrue(sameContainer.err().contains("Profile 'a' already uses container 'floci-az-a'"), sameContainer.err()); + + Run samePort = profileCmd(ProductProfile.AZ, "create", "c", "--container", "floci-az-c", "--port", "14577"); + assertTrue(samePort.err().contains("Profile 'a' already uses port 14577"), samePort.err()); + + // Another emulator on the same port is not this instance's concern. + Run otherProduct = profileCmd(ProductProfile.GCP, "create", "d", "--container", "floci-gcp-d", "--port", "14577"); + assertFalse(otherProduct.err().contains("already uses"), otherProduct.err()); + } + + @Test + void aDigestPinnedImageStillCollidesWithATagOfTheSameRepository() throws Exception { + writeProfile("a", "container: floci-az-a\nport: 14577\nimage: floci/floci-az:latest\n"); + + Run pinned = profileCmd(ProductProfile.AZ, "create", "b", "--container", "floci-az-b", "--port", "14577", + "--image", "floci/floci-az@sha256:0123456789abcdef"); + + assertTrue(pinned.err().contains("Profile 'a' already uses port 14577"), pinned.err()); + } + + @Test + void listAsJsonIsAnEmptyArrayWhenThereAreNoProfiles() { + Run r = profileCmd(ProductProfile.AWS, "list", "-o", "json"); + + assertEquals(0, r.exit()); + assertEquals("[ ]", r.out().strip()); + } + + @Test + void listShowsEachInstancesContainerPortAndDataDir() throws Exception { + writeProfile("b", "container: floci-az-b\nport: 14578\n"); + writeProfile("a", "container: floci-az-a\nport: 14577\npersistDir: /data/a\n"); + + String text = profileCmd(ProductProfile.AZ, "list", "--no-color").out(); + assertTrue(text.indexOf("floci-az-a") < text.indexOf("floci-az-b"), "sorted by name: " + text); + assertTrue(text.contains("floci-az-a") && text.contains(":14577") && text.contains("/data/a"), text); + assertTrue(text.contains("floci-az-b") && text.contains(":14578"), text); + + String json = profileCmd(ProductProfile.AZ, "list", "-o", "json").out(); + assertTrue(json.trim().startsWith("["), json); + assertTrue(json.contains("\"container\" : \"floci-az-b\""), json); + assertTrue(json.contains("\"port\" : 14577"), json); + } }