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

@@ -36,6 +36,21 @@ public record ProductProfile(
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. */
public String serverRepo() {
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
// during the stop plus the one second wait below.
StartCommand start = buildStartCommand();
String invalid = start.validationError();
if (invalid != null) {
printer.error(invalid);
return 2;
}
StopCommand stop = new StopCommand(profile);
stop.global = global;
@@ -16,6 +16,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
@Command(
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>")
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")
String pull;
@@ -96,6 +103,35 @@ public class StartCommand implements Callable<Integer> {
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()}
* 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()) {
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) ->
args.addAll(List.of("-e", profile.envVar(suffix) + "=" + value)));
args.add(image);
@@ -138,6 +185,12 @@ public class StartCommand implements Callable<Integer> {
Printer printer = global.printer();
DockerClient docker = new DockerClient();
String invalid = validationError();
if (invalid != null) {
printer.error(invalid);
return 2;
}
// Verify docker is available
if (!DockerClient.isInstalled()) {
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>")
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
CommandSpec spec;
@@ -104,6 +107,7 @@ public class ConfigProfileCommand implements Callable<Integer> {
row.put("image", p.image);
row.put("persistDir", p.persistDir);
row.put("services", p.services);
row.put("namespace", p.namespace);
out.add(row);
}
printer.structured(out);
@@ -143,6 +147,7 @@ public class ConfigProfileCommand implements Callable<Integer> {
if (p.port != null) printer.println(" port: " + p.port);
if (p.persistDir != null) printer.println(" persistDir: " + p.persistDir);
if (p.services != null) printer.println(" services: " + p.services);
if (p.namespace != null) printer.println(" namespace: " + p.namespace);
return 0;
} catch (IOException e) {
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("--persist")) p.persistDir = persistDir;
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);
}
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
* 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.
*/
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<>();
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))) {
continue; // one instance: its port and namespace are the same by definition
}
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"
+ "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;
}
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.
private static String repository(String image) {
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.persistDir != null) data.put("persistDir", resolved.persistDir());
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) {
@@ -12,6 +12,7 @@ public class Profile {
public Integer port;
public String persistDir;
public String services;
public String namespace;
public String output;
public Profile() {}
@@ -27,6 +27,7 @@ public final class ProfileDefaults {
case "--port" -> profile.port == null ? null : String.valueOf(profile.port);
case "--persist" -> profile.persistDir;
case "--services" -> profile.services;
case "--namespace" -> profile.namespace;
case "--output" -> profile.output;
default -> null;
};