feat(start): give each instance its own Docker resource namespace and base URL (#31)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-08 21:44:17 -05:00
1 parent 788eb470fb
commit bf9ee4037b
14 files changed
+310 -8

No files matched your search

+3 -1
View File
@@ -124,7 +124,9 @@ An instance is a profile: its container name is its identity, its port is the on
- Local state about one running instance (certificates, generated vendor-CLI config) lives under `InstanceState.dir(product, container)`, which is `~/.floci/<product>/<container>/`. 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). - Local state about one running instance (certificates, generated vendor-CLI config) lives under `InstanceState.dir(product, container)`, which is `~/.floci/<product>/<container>/`. 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. - 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. - 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. - `StartCommand.resourceNamespace()` passes the emulator's `<PREFIX>_DOCKER_RESOURCE_NAMESPACE`: explicit `--namespace`/profile `namespace` (verbatim), else `ProductProfile.resourceNamespace(container)`: nothing for the default container, otherwise the container name minus the `<defaultContainer>-` prefix (the emulator adds `floci-<cloud>-` itself, so keeping it would stutter). It scopes the child containers each emulator launches and its orphan sweeps; never derive one for the default container (it would rename existing users' child containers).
- On a non-default `--port`, `start` also passes `<PREFIX>_BASE_URL`, the endpoint with that port (`http://localhost:<port>` by default): every emulator builds returned URLs (SQS `QueueUrl`, OCI invoke endpoint) from it, and its default names the product port.
- `config profile create` takes `--container --port --persist --services --image --namespace` (and `--endpoint`); it reads only flags the user typed (`ParseResult.hasMatchedOption`), never values the profile provider or `FLOCI_*` env vars applied.
### Self-update ### Self-update
+26 -2
View File
@@ -345,21 +345,38 @@ floci start --services s3,dynamodb # enable specific services
floci start --persist ./data # persist state to a host directory floci start --persist ./data # persist state to a host directory
floci start --pull always # always pull the latest image floci start --pull always # always pull the latest image
floci start --detach # return immediately, don't wait floci start --detach # return immediately, don't wait
floci start --namespace team-b # scope the containers it launches (see below)
# GCP # GCP
floci gcp start # default port 4588 floci gcp start # default port 4588
floci gcp start --persist ./data # persist state to a host directory floci gcp start --persist ./data # persist state to a host directory
floci gcp start --namespace team-b # scope the containers it launches
# Azure # Azure
floci az start # default port 4577 floci az start # default port 4577
floci az start --port 4578 # custom host port floci az start --port 4578 # custom host port
floci az start --persist ./data # persist state to a host directory floci az start --persist ./data # persist state to a host directory
floci az start --namespace team-b # scope the containers it launches
# OCI # OCI
floci oci start # default port 4599 floci oci start # default port 4599
floci oci start --persist ./data # persist state to a host directory floci oci start --persist ./data # persist state to a host directory
floci oci start --namespace team-b # scope the containers it launches
``` ```
`--namespace` sets the emulator's Docker resource namespace (`FLOCI_DOCKER_RESOURCE_NAMESPACE`,
`FLOCI_GCP_…`, `FLOCI_AZ_…`, `FLOCI_OCI_…`). The emulator puts it in the names and the
`floci_namespace` label of the containers and volumes it launches (Lambda, ECS, RDS, Cloud Run,
Service Bus, ...) and only cleans up leftovers in its own namespace. When `--container` is not the
product default, the namespace is derived from it, without the default-container prefix the
emulator already adds (`floci-gcp-b` → `b`, so children are `floci-gcp-b-…`; `team-b` stays
`team-b`). The default container gets none.
On a `--port` other than the product default, `start` also sets the emulator's base URL
(`FLOCI_BASE_URL`, `FLOCI_GCP_BASE_URL`, ...) to the endpoint with that port (`http://localhost:<port>`
unless `--endpoint` names another host), so URLs it returns
(SQS `QueueUrl`, presigned URLs, the OCI functions invoke endpoint) point at that instance.
#### Docker daemon resolution (Podman, rootless, remote contexts) #### Docker daemon resolution (Podman, rootless, remote contexts)
The Floci container needs access to a Docker-compatible daemon (for Lambda, EC2, The Floci container needs access to a Docker-compatible daemon (for Lambda, EC2,
@@ -632,7 +649,7 @@ 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 default-product aws|gcp|az|oci # set the default product (persisted to ~/.floci/config.yaml)
floci config profile list # list saved profiles: container, port, data dir floci config profile list # list saved profiles: container, port, data dir
floci config profile create <name> # create a new profile with the tree's defaults floci config profile create <name> # create a new profile with the tree's defaults
floci config profile create <name> --container <c> --port <p> --persist <dir> --services <csv> --image <img> floci config profile create <name> --container <c> --port <p> --persist <dir> --services <csv> --image <img> --namespace <ns>
floci config profile show <name> # show a profile floci config profile show <name> # show a profile
floci config profile delete <name> # delete a profile floci config profile delete <name> # delete a profile
floci config validate -f docker-compose.yml # validate a Compose file floci config validate -f docker-compose.yml # validate a Compose file
@@ -652,6 +669,7 @@ image: floci/floci:enforced
port: 4599 port: 4599
persistDir: /tmp/floci-persist persistDir: /tmp/floci-persist
services: s3,lambda services: s3,lambda
namespace: team-probe
output: json output: json
``` ```
@@ -667,6 +685,7 @@ have that flag:
| `port` | `--port` | `start`, `restart` | | `port` | `--port` | `start`, `restart` |
| `persistDir` | `--persist` | `start`, `restart` | | `persistDir` | `--persist` | `start`, `restart` |
| `services` | `--services` | `start`, `restart` | | `services` | `--services` | `start`, `restart` |
| `namespace` | `--namespace` | `start`, `restart` |
Resolution order, highest first: Resolution order, highest first:
@@ -697,9 +716,14 @@ container recreation. Every command (`status`, `logs`, `env`, `doctor`, `stop`,
instance through its container, so passing the same `--profile` is all it takes. Any local state 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/<product>/<container>/`. the CLI keeps about an instance lives in `~/.floci/<product>/<container>/`.
Each instance's emulator also gets its own Docker resource namespace, derived from the container
name unless the profile sets `namespace`. That keeps the containers each instance launches (Lambda functions,
ECS tasks, Cloud Run jobs, Service Bus sidecars, ...) apart, so starting one instance never
cleans up another's. `floci config show --profile <name>` prints the namespace it will use.
Leave `endpoint` at the product default: the CLI reads the real host port from the running 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, container. `config profile create` warns when a new profile reuses another profile's container,
or its port on the same image. or its port or resource namespace on the same image.
```sh ```sh
# AWS # AWS
@@ -36,6 +36,21 @@ public record ProductProfile(
return "aws".equals(name) ? "floci" : "floci " + name; return "aws".equals(name) ? "floci" : "floci " + name;
} }
/**
* The Docker resource namespace an instance in {@code container} gets when none is set: none
* for the default container, so its child containers keep their names; otherwise the container
* name without the default-container prefix. The emulator already prefixes child names with
* {@code floci-<cloud>-}, so {@code floci-gcp-b} becomes {@code b}, not
* {@code floci-gcp-floci-gcp-b-...}.
*/
public String resourceNamespace(String container) {
if (container == null || container.equals(defaultContainer)) return null;
String prefix = defaultContainer + "-";
return container.startsWith(prefix) && container.length() > prefix.length()
? container.substring(prefix.length())
: container;
}
/** GitHub repository of the product's emulator server, for issue-tracker hints. */ /** GitHub repository of the product's emulator server, for issue-tracker hints. */
public String serverRepo() { public String serverRepo() {
return "https://github.com/floci-io/" + ("aws".equals(name) ? "floci" : "floci-" + name); return "https://github.com/floci-io/" + ("aws".equals(name) ? "floci" : "floci-" + name);
@@ -45,6 +45,11 @@ public class RestartCommand implements Callable<Integer> {
// container stopped, and the values must not be re-read from a file that could change // container stopped, and the values must not be re-read from a file that could change
// during the stop plus the one second wait below. // during the stop plus the one second wait below.
StartCommand start = buildStartCommand(); StartCommand start = buildStartCommand();
String invalid = start.validationError();
if (invalid != null) {
printer.error(invalid);
return 2;
}
StopCommand stop = new StopCommand(profile); StopCommand stop = new StopCommand(profile);
stop.global = global; stop.global = global;
@@ -16,6 +16,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.regex.Pattern;
@Command( @Command(
name = "start", name = "start",
@@ -55,6 +56,12 @@ public class StartCommand implements Callable<Integer> {
@Option(names = {"--image"}, description = "Image reference to use (default: ${DEFAULT-VALUE})", paramLabel = "<ref>") @Option(names = {"--image"}, description = "Image reference to use (default: ${DEFAULT-VALUE})", paramLabel = "<ref>")
String image; String image;
@Option(names = {"--namespace"}, description = "Docker resource namespace for the containers this instance launches (default: derived from --container; none for the default container)", paramLabel = "<name>")
String namespace;
// Docker's own name rule: the emulators put the namespace inside child container names.
private static final Pattern NAMESPACE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]*");
@Option(names = {"--pull"}, description = "Image pull policy: always, missing, never", defaultValue = "missing", paramLabel = "always|missing|never") @Option(names = {"--pull"}, description = "Image pull policy: always, missing, never", defaultValue = "missing", paramLabel = "always|missing|never")
String pull; String pull;
@@ -96,6 +103,35 @@ public class StartCommand implements Callable<Integer> {
public String services() { return services; } public String services() { return services; }
/**
* The resource namespace this instance passes to the emulator, which scopes the child
* containers and volumes it launches (Lambda, ECS, Cloud Run, Service Bus, ...) and its
* startup orphan sweeps. Without it two instances of one emulator remove each other's
* children. An explicit {@code --namespace} wins; otherwise it is derived from the container
* ({@link ProductProfile#resourceNamespace(String)}).
*/
/**
* Why these settings cannot start, or {@code null}. Checked before anything touches Docker,
* and by {@code restart} before it stops the running container, so a bad profile value never
* leaves an instance stopped.
*/
public String validationError() {
if (namespace != null && !namespace.isBlank() && !NAMESPACE.matcher(namespace).matches()) {
return "Invalid namespace '" + namespace + "'.\nUse letters, digits, '_', '.' and '-', starting with a letter or digit.";
}
return null;
}
public String resourceNamespace() {
return resourceNamespaceFor(global.container);
}
/** {@link #resourceNamespace()} for an instance in {@code container}, which a flag may have overridden. */
public String resourceNamespaceFor(String container) {
if (namespace != null && !namespace.isBlank()) return namespace;
return profile.resourceNamespace(container);
}
/** /**
* The {@code docker run} arguments this invocation would use. Extracted from {@link #call()} * The {@code docker run} arguments this invocation would use. Extracted from {@link #call()}
* as a test seam so the persistence mount can be pinned without starting a container; * as a test seam so the persistence mount can be pinned without starting a container;
@@ -116,6 +152,17 @@ public class StartCommand implements Callable<Integer> {
if (services != null && !services.isBlank()) { if (services != null && !services.isBlank()) {
args.addAll(List.of("-e", profile.envVar("SERVICES") + "=" + services)); args.addAll(List.of("-e", profile.envVar("SERVICES") + "=" + services));
} }
// URLs the emulator hands back (SQS QueueUrl, presigned URLs, the OCI invoke endpoint)
// are built from its base URL, which defaults to localhost and the product port. On any
// other host port they would point at whichever instance owns the default one; the host
// comes from the endpoint, so a remote Docker host is named too.
if (port != profile.defaultPort()) {
args.addAll(List.of("-e", profile.envVar("BASE_URL") + "=" + withPort(global.endpoint, port)));
}
String ns = resourceNamespace();
if (ns != null) {
args.addAll(List.of("-e", profile.envVar("DOCKER_RESOURCE_NAMESPACE") + "=" + ns));
}
new TreeMap<>(profile.startEnv()).forEach((suffix, value) -> new TreeMap<>(profile.startEnv()).forEach((suffix, value) ->
args.addAll(List.of("-e", profile.envVar(suffix) + "=" + value))); args.addAll(List.of("-e", profile.envVar(suffix) + "=" + value)));
args.add(image); args.add(image);
@@ -138,6 +185,12 @@ public class StartCommand implements Callable<Integer> {
Printer printer = global.printer(); Printer printer = global.printer();
DockerClient docker = new DockerClient(); DockerClient docker = new DockerClient();
String invalid = validationError();
if (invalid != null) {
printer.error(invalid);
return 2;
}
// Verify docker is available // Verify docker is available
if (!DockerClient.isInstalled()) { if (!DockerClient.isInstalled()) {
printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/"); printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/");
@@ -68,6 +68,9 @@ public class ConfigProfileCommand implements Callable<Integer> {
@Option(names = {"--services"}, description = "create: comma-separated services to enable", paramLabel = "<csv>") @Option(names = {"--services"}, description = "create: comma-separated services to enable", paramLabel = "<csv>")
String services; String services;
@Option(names = {"--namespace"}, description = "create: Docker resource namespace for the containers this instance launches (default: derived from --container)", paramLabel = "<name>")
String namespace;
@Spec @Spec
CommandSpec spec; CommandSpec spec;
@@ -104,6 +107,7 @@ public class ConfigProfileCommand implements Callable<Integer> {
row.put("image", p.image); row.put("image", p.image);
row.put("persistDir", p.persistDir); row.put("persistDir", p.persistDir);
row.put("services", p.services); row.put("services", p.services);
row.put("namespace", p.namespace);
out.add(row); out.add(row);
} }
printer.structured(out); printer.structured(out);
@@ -143,6 +147,7 @@ public class ConfigProfileCommand implements Callable<Integer> {
if (p.port != null) printer.println(" port: " + p.port); if (p.port != null) printer.println(" port: " + p.port);
if (p.persistDir != null) printer.println(" persistDir: " + p.persistDir); if (p.persistDir != null) printer.println(" persistDir: " + p.persistDir);
if (p.services != null) printer.println(" services: " + p.services); if (p.services != null) printer.println(" services: " + p.services);
if (p.namespace != null) printer.println(" namespace: " + p.namespace);
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {
printer.error("Could not read profile: " + e.getMessage()); printer.error("Could not read profile: " + e.getMessage());
@@ -171,8 +176,9 @@ public class ConfigProfileCommand implements Callable<Integer> {
if (typed("--image")) p.image = image; if (typed("--image")) p.image = image;
if (typed("--persist")) p.persistDir = persistDir; if (typed("--persist")) p.persistDir = persistDir;
if (typed("--services")) p.services = services; if (typed("--services")) p.services = services;
if (typed("--namespace")) p.namespace = namespace;
for (String warning : collisions(store.list(), p)) { for (String warning : collisions(profile, store.list(), p)) {
printer.warn(warning); printer.warn(warning);
} }
store.save(p); store.save(p);
@@ -191,25 +197,38 @@ public class ConfigProfileCommand implements Callable<Integer> {
/** /**
* Two profiles that share a container are the same instance, and two that share a port on the * 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), * same image cannot run at once. Two of one emulator that share a resource namespace remove
* each other's child containers. All are legitimate (one instance, used at different times),
* so they are warnings, not errors. * so they are warnings, not errors.
*/ */
static List<String> collisions(List<Profile> existing, Profile created) { static List<String> collisions(ProductProfile product, List<Profile> existing, Profile created) {
List<String> warnings = new ArrayList<>(); List<String> warnings = new ArrayList<>();
for (Profile other : existing) { for (Profile other : existing) {
if (other.name == null || other.name.equals(created.name)) continue; if (other.name == null || other.name.equals(created.name)) continue;
if (created.container != null && created.container.equals(other.container)) { if (created.container != null && created.container.equals(other.container)) {
warnings.add("Profile '" + other.name + "' already uses container '" + created.container + "'.\n" warnings.add("Profile '" + other.name + "' already uses container '" + created.container + "'.\n"
+ "Pick another --container, or start only one of them at a time."); + "Pick another --container, or start only one of them at a time.");
} else if (created.port != null && created.port.equals(other.port) continue; // one instance: its port and namespace are the same by definition
&& repository(created.image).equals(repository(other.image))) { }
boolean sameEmulator = repository(created.image).equals(repository(other.image));
if (sameEmulator && created.port != null && created.port.equals(other.port)) {
warnings.add("Profile '" + other.name + "' already uses port " + created.port + ".\n" warnings.add("Profile '" + other.name + "' already uses port " + created.port + ".\n"
+ "Pick another --port, or start only one of them at a time."); + "Pick another --port, or start only one of them at a time.");
} }
// Reported separately: a new port alone does not stop shared child containers.
String ns = sameEmulator ? namespaceOf(product, created) : null;
if (ns != null && ns.equals(namespaceOf(product, other))) {
warnings.add("Profile '" + other.name + "' already uses resource namespace '" + ns + "'.\n"
+ "Pass --namespace to give this instance its own.");
}
} }
return warnings; return warnings;
} }
private static String namespaceOf(ProductProfile product, Profile p) {
return p.namespace != null && !p.namespace.isBlank() ? p.namespace : product.resourceNamespace(p.container);
}
// floci/floci-az:latest -> floci/floci-az, so two tags of one emulator still collide on a port. // floci/floci-az:latest -> floci/floci-az, so two tags of one emulator still collide on a port.
private static String repository(String image) { private static String repository(String image) {
if (image == null) return ""; if (image == null) return "";
@@ -94,6 +94,10 @@ public class ConfigShowCommand implements Callable<Integer> {
if (p.port != null) data.put("port", resolved.port()); if (p.port != null) data.put("port", resolved.port());
if (p.persistDir != null) data.put("persistDir", resolved.persistDir()); if (p.persistDir != null) data.put("persistDir", resolved.persistDir());
if (p.services != null) data.put("services", resolved.services()); if (p.services != null) data.put("services", resolved.services());
// Effective, not declared: a profile with its own container gets a namespace unasked, and
// the container in effect (a --container flag beats the profile) is the one it comes from.
String namespace = resolved.resourceNamespaceFor(global.container);
if (namespace != null) data.put("namespace", namespace);
} }
private static String label(String key) { private static String label(String key) {
@@ -12,6 +12,7 @@ public class Profile {
public Integer port; public Integer port;
public String persistDir; public String persistDir;
public String services; public String services;
public String namespace;
public String output; public String output;
public Profile() {} public Profile() {}
@@ -27,6 +27,7 @@ public final class ProfileDefaults {
case "--port" -> profile.port == null ? null : String.valueOf(profile.port); case "--port" -> profile.port == null ? null : String.valueOf(profile.port);
case "--persist" -> profile.persistDir; case "--persist" -> profile.persistDir;
case "--services" -> profile.services; case "--services" -> profile.services;
case "--namespace" -> profile.namespace;
case "--output" -> profile.output; case "--output" -> profile.output;
default -> null; default -> null;
}; };
@@ -158,6 +158,38 @@ class ConfigCommandsTest {
assertEquals(14578, b.port); assertEquals(14578, b.port);
assertEquals("floci-az", b.container); assertEquals("floci-az", b.container);
assertNull(b.persistDir); assertNull(b.persistDir);
assertNull(b.namespace);
}
@Test
void createStoresATypedNamespace() throws Exception {
assertEquals(0, profileCmd(ProductProfile.GCP, "create", "ns",
"--container", "floci-gcp-b", "--namespace", "team-b").exit());
assertEquals("team-b", store().get("ns").orElseThrow().namespace);
}
@Test
void showReportsTheNamespaceAProfilesContainerImplies() throws Exception {
writeProfile("b", "container: floci-b\n");
writeProfile("plain", "port: 4599\n");
assertTrue(runShow(ProductProfile.AWS, "--profile", "b", "-o", "json")
.contains("\"namespace\" : \"b\""));
assertFalse(runShow(ProductProfile.AWS, "--profile", "plain", "-o", "json")
.contains("namespace"));
}
@Test
void createWarnsWhenTwoInstancesOfOneEmulatorWouldShareANamespace() throws Exception {
writeProfile("a", "container: floci-gcp-b\nport: 14588\nimage: floci/floci-gcp:latest\n");
Run same = profileCmd(ProductProfile.GCP, "create", "c", "--container", "b", "--port", "14589");
assertTrue(same.err().contains("resource namespace 'b'"), same.err());
Run own = profileCmd(ProductProfile.GCP, "create", "d", "--container", "b", "--port", "14590",
"--namespace", "team-d");
assertFalse(own.err().contains("resource namespace"), own.err());
} }
@Test @Test
@@ -184,6 +216,25 @@ class ConfigCommandsTest {
assertFalse(otherProduct.err().contains("already uses"), otherProduct.err()); assertFalse(otherProduct.err().contains("already uses"), otherProduct.err());
} }
@Test
void showDerivesTheNamespaceFromTheContainerInEffect() throws Exception {
writeProfile("b", "container: floci-b\n");
String out = runShow(ProductProfile.AWS, "--profile", "b", "--container", "floci-custom", "-o", "json");
assertTrue(out.contains("\"namespace\" : \"custom\""), out);
}
@Test
void aSharedNamespaceIsReportedEvenWhenThePortAlsoCollides() throws Exception {
writeProfile("a", "container: floci-gcp-b\nport: 14588\nimage: floci/floci-gcp:latest\n");
Run r = profileCmd(ProductProfile.GCP, "create", "c", "--container", "b", "--port", "14588");
assertTrue(r.err().contains("already uses port 14588"), r.err());
assertTrue(r.err().contains("already uses resource namespace 'b'"), r.err());
}
@Test @Test
void aDigestPinnedImageStillCollidesWithATagOfTheSameRepository() throws Exception { void aDigestPinnedImageStillCollidesWithATagOfTheSameRepository() throws Exception {
writeProfile("a", "container: floci-az-a\nport: 14577\nimage: floci/floci-az:latest\n"); writeProfile("a", "container: floci-az-a\nport: 14577\nimage: floci/floci-az:latest\n");
@@ -64,4 +64,16 @@ class ProductProfileTest {
assertEquals("floci oci", ProductProfile.OCI.commandPrefix()); assertEquals("floci oci", ProductProfile.OCI.commandPrefix());
assertEquals(Map.of(), ProductProfile.OCI.startEnv()); assertEquals(Map.of(), ProductProfile.OCI.startEnv());
} }
@Test
void resourceNamespaceDropsTheDefaultContainerPrefix() {
assertNull(ProductProfile.AWS.resourceNamespace("floci"));
assertNull(ProductProfile.GCP.resourceNamespace("floci-gcp"));
assertEquals("b", ProductProfile.AWS.resourceNamespace("floci-b"));
assertEquals("b", ProductProfile.GCP.resourceNamespace("floci-gcp-b"));
assertEquals("b", ProductProfile.AZ.resourceNamespace("floci-az-b"));
assertEquals("b", ProductProfile.OCI.resourceNamespace("floci-oci-b"));
assertEquals("team-b", ProductProfile.GCP.resourceNamespace("team-b"));
assertEquals("floci-gcp-", ProductProfile.GCP.resourceNamespace("floci-gcp-"));
}
} }
@@ -22,6 +22,7 @@ class ProfileDefaultsTest {
p.persistDir = "/tmp/floci-persist-test"; p.persistDir = "/tmp/floci-persist-test";
p.services = "s3,lambda"; p.services = "s3,lambda";
p.output = "json"; p.output = "json";
p.namespace = "team-b";
return p; return p;
} }
@@ -34,6 +35,7 @@ class ProfileDefaultsTest {
"--persist, /tmp/floci-persist-test", "--persist, /tmp/floci-persist-test",
"--services, 's3,lambda'", "--services, 's3,lambda'",
"--output, json", "--output, json",
"--namespace, team-b",
}) })
void mapsEveryProfileField(String option, String expected) { void mapsEveryProfileField(String option, String expected) {
assertEquals(expected, ProfileDefaults.valueFor(fullProfile(), option), option); assertEquals(expected, ProfileDefaults.valueFor(fullProfile(), option), option);
@@ -43,6 +45,7 @@ class ProfileDefaultsTest {
@ValueSource(strings = { @ValueSource(strings = {
"--service", // wait/logs/env filter — NOT the profile's 'services' "--service", // wait/logs/env filter — NOT the profile's 'services'
"--profile-name", // the OCI CLI profile written by 'floci oci setup' "--profile-name", // the OCI CLI profile written by 'floci oci setup'
"--namespace-name",
"--global", // 'floci az setup' target, not a profile field "--global", // 'floci az setup' target, not a profile field
"--reset", "--reset",
"--tenant", "--tenant",
@@ -7,7 +7,9 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import picocli.CommandLine; import picocli.CommandLine;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
@@ -56,6 +58,7 @@ class RestartCommandTest {
"-v", "/tmp/floci-persist-test:/app/data", "-v", "/tmp/floci-persist-test:/app/data",
"-e", "FLOCI_STORAGE_MODE=persistent", "-e", "FLOCI_STORAGE_MODE=persistent",
"-e", "FLOCI_SERVICES=s3,lambda", "-e", "FLOCI_SERVICES=s3,lambda",
"-e", "FLOCI_BASE_URL=http://localhost:4599",
"floci/floci:enforced"), args); "floci/floci:enforced"), args);
} }
@@ -76,6 +79,16 @@ class RestartCommandTest {
assertFalse(args.stream().anyMatch(a -> a.contains("${env:")), args.toString()); assertFalse(args.stream().anyMatch(a -> a.contains("${env:")), args.toString());
} }
@Test
void carriesTheProfileNamespaceIntoTheStartItRuns() throws Exception {
writeProfile("ns", "container: floci-oci-b\nnamespace: team-b\n");
List<String> args = parse(ProductProfile.OCI, "--profile", "ns")
.buildStartCommand().dockerRunArgs(SOCKET);
assertTrue(args.contains("FLOCI_OCI_DOCKER_RESOURCE_NAMESPACE=team-b"), args.toString());
}
@Test @Test
void withoutAProfileItStillUsesTheProductDefaults() { void withoutAProfileItStillUsesTheProductDefaults() {
List<String> args = parse(ProductProfile.GCP).buildStartCommand().dockerRunArgs(SOCKET); List<String> args = parse(ProductProfile.GCP).buildStartCommand().dockerRunArgs(SOCKET);
@@ -97,4 +110,19 @@ class RestartCommandTest {
"-e", "FLOCI_OCI_STORAGE_MODE=persistent", "-e", "FLOCI_OCI_STORAGE_MODE=persistent",
"floci/floci-oci:latest"), args); "floci/floci-oci:latest"), args);
} }
/** A namespace start would reject must fail restart before it stops anything. */
@Test
void anInvalidProfileNamespaceFailsBeforeTheStop() throws Exception {
writeProfile("bad", "container: floci-bad\nnamespace: bad/name\n");
RestartCommand restart = parse(ProductProfile.AWS, "--profile", "bad");
PrintStream err = System.err;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
try {
assertEquals(2, restart.call());
} finally {
System.setErr(err);
}
}
} }
@@ -7,7 +7,9 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import picocli.CommandLine.ParseResult; import picocli.CommandLine.ParseResult;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
@@ -54,6 +56,8 @@ class StartCommandArgsTest {
"-v", "/tmp/floci-persist-test:/app/data", "-v", "/tmp/floci-persist-test:/app/data",
"-e", "FLOCI_STORAGE_MODE=persistent", "-e", "FLOCI_STORAGE_MODE=persistent",
"-e", "FLOCI_SERVICES=s3,lambda", "-e", "FLOCI_SERVICES=s3,lambda",
"-e", "FLOCI_BASE_URL=http://localhost:4599",
"-e", "FLOCI_DOCKER_RESOURCE_NAMESPACE=probe",
"floci/floci:enforced"), "floci/floci:enforced"),
parse("start", "--profile", "probe").dockerRunArgs(SOCKET)); parse("start", "--profile", "probe").dockerRunArgs(SOCKET));
} }
@@ -107,6 +111,86 @@ class StartCommandArgsTest {
} }
} }
/**
* Two instances of one emulator must not share a resource namespace, or each one's startup
* sweep removes the other's Lambda/ECS/Cloud Run children. The default instance passes none,
* so its child container names stay what they were.
*/
@Test
void theDefaultContainerPassesNoResourceNamespace() {
for (String tree : new String[]{"aws", "gcp", "az", "oci"}) {
assertFalse(parse(tree, "start").dockerRunArgs(SOCKET).stream()
.anyMatch(a -> a.contains("RESOURCE_NAMESPACE")), tree);
}
}
@Test
void aNonDefaultContainerNamesItsOwnNamespaceInEveryTree() {
// The emulator prefixes child names with floci-<cloud>- itself, so the default-container
// prefix is dropped: floci-gcp-b -> b, not floci-gcp-floci-gcp-b-...
assertTrue(parse("start", "--container", "floci-b").dockerRunArgs(SOCKET)
.contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=b"));
assertTrue(parse("gcp", "start", "--container", "floci-gcp-b").dockerRunArgs(SOCKET)
.contains("FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE=b"));
assertTrue(parse("az", "start", "--container", "floci-az-b").dockerRunArgs(SOCKET)
.contains("FLOCI_AZ_DOCKER_RESOURCE_NAMESPACE=b"));
assertTrue(parse("oci", "start", "--container", "team-oci").dockerRunArgs(SOCKET)
.contains("FLOCI_OCI_DOCKER_RESOURCE_NAMESPACE=team-oci"));
}
@Test
void anExplicitNamespaceBeatsTheContainerName() {
assertTrue(parse("start", "--container", "floci-b", "--namespace", "team-b")
.dockerRunArgs(SOCKET).contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=team-b"));
assertTrue(parse("start", "--namespace", "team-a")
.dockerRunArgs(SOCKET).contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=team-a"));
}
@Test
void theProfileNamespaceAppliesAndTheFlagStillWins() throws Exception {
writeProfile("probe", "container: floci-probe\nnamespace: from-profile\n");
assertTrue(parse("start", "--container", "floci-probe", "--namespace", "floci-probe")
.dockerRunArgs(SOCKET).contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=floci-probe"),
"an explicit namespace is passed verbatim");
assertTrue(parse("start", "--profile", "probe").dockerRunArgs(SOCKET)
.contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=from-profile"));
assertTrue(parse("start", "--profile", "probe", "--namespace", "from-flag").dockerRunArgs(SOCKET)
.contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=from-flag"));
}
@Test
void anInvalidNamespaceIsRejectedBeforeDockerIsTouched() {
StartCommand start = parse("start", "--namespace", "bad/name");
PrintStream err = System.err;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
try {
assertEquals(2, start.call());
} finally {
System.setErr(err);
}
}
/** Response URLs (SQS QueueUrl, OCI invoke endpoint) must name the port this instance owns. */
@Test
void aNonDefaultPortMovesTheBaseUrlWithIt() {
assertTrue(parse("start", "--port", "14566").dockerRunArgs(SOCKET)
.contains("FLOCI_BASE_URL=http://localhost:14566"));
assertTrue(parse("oci", "start", "--port", "14599").dockerRunArgs(SOCKET)
.contains("FLOCI_OCI_BASE_URL=http://localhost:14599"));
for (String tree : new String[]{"aws", "gcp", "az", "oci"}) {
assertFalse(parse(tree, "start").dockerRunArgs(SOCKET).stream()
.anyMatch(a -> a.contains("BASE_URL")), tree);
}
}
/** Returned URLs must reach the emulator, so a remote endpoint's host is kept. */
@Test
void theBaseUrlKeepsTheEndpointsHost() {
assertTrue(parse("start", "--endpoint", "http://floci.internal:4566", "--port", "14566")
.dockerRunArgs(SOCKET).contains("FLOCI_BASE_URL=http://floci.internal:14566"));
}
@Test @Test
void readinessPollKeepsTheHostFromTheEndpointWhenSwappingThePort() { void readinessPollKeepsTheHostFromTheEndpointWhenSwappingThePort() {
assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599)); assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599));