Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(docker): give internal Docker labels io.floci.* names and keep the old keys as aliases (#4871)

Hector Ventura24c655050f6a
diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md
index fd886665ad..44c3ac9389 100644
--- a/docs/configuration/docker.md
+++ b/docs/configuration/docker.md
@@ -175,7 +175,7 @@ services:
Extra labels are a list of key/value entries rather than a map so that label keys containing dots, colons, or uppercase characters survive the environment-variable naming convention.
!!! note
- Entries using one of the reserved keys (`floci`, `floci_emulator`, `floci_namespace`) are ignored with a warning — user configuration can never break Floci's own container discovery and volume pruning.
+ Entries using one of the reserved keys (`floci`, `floci_emulator`, `floci_namespace`, or any key listed under [Internal Labels](#internal-labels), new or legacy) are ignored with a warning: user configuration can never break Floci's own container discovery and volume pruning, or fake the owner or identity a cleanup path trusts.
### Resource Identity Labels
@@ -189,7 +189,28 @@ A container backing an emulated AWS resource also carries labels tying it back t
| `io.floci.account` | the resolved account id | The AWS account the resource belongs to |
| `io.floci.region` | the resolved region | The AWS region the resource belongs to |
-This makes `docker ps --filter label=io.floci.resource-id=orders-db-primary` resolve a specific emulated resource to its backing container directly, without inferring it from names or creation order. Applied to RDS, DocDB, ElastiCache (Redis/Valkey and Memcached), MemoryDB, Neptune, MSK, OpenSearch, ECS, EKS, AmazonMQ, MWAA, Kinesis Data Analytics (Flink), Batch, CodeBuild, Lambda, and EC2. ECR's backing registry container carries every label except `io.floci.resource-id`, since it is a shared singleton with no single resource identifier.
+This makes `docker ps --filter label=io.floci.resource-id=orders-db-primary` resolve a specific emulated resource to its backing container directly, without inferring it from names or creation order. Applied to RDS, DocDB, ElastiCache (Redis/Valkey and Memcached), MemoryDB, Neptune, MSK, OpenSearch, ECS, EKS, AmazonMQ, MWAA, Kinesis Data Analytics (Flink), Batch, CodeBuild, Lambda, and EC2. ECR's backing registry container carries every label except `io.floci.resource-id`, since it is a shared singleton with no single resource identifier. The EventBridge Pipes Kafka bridge carries only `io.floci` and `io.floci.service=pipes`, since one bridge serves every pipe reading the same cluster. The Docker networks backing EC2 VPCs carry `io.floci`, `io.floci.service=ec2`, `io.floci.resource-id` (the VPC id) and `io.floci.region`.
+
+The same key set is used by Floci's GCP, Azure and OCI emulators, each with its own scope keys in place of `io.floci.account` and `io.floci.region` (see the [floci-gcp](https://floci.io/floci-gcp/), [floci-az](https://floci.io/floci-az/) and [floci-oci](https://floci.io/floci-oci/) documentation).
+
+### Internal Labels
+
+Floci also stamps bookkeeping labels it reads back itself: which Floci deployment owns a container or network, which process run created an ECS container, and which containers belong to the security-group sandbox. Each key Floci used before it adopted the `io.floci.*` namespace is still written next to its new key with the same value, and read when the new key is missing, so resources created by an earlier version keep being found. *Legacy: still written, prefer the new key.*
+
+| Label | Legacy alias | On | Value |
+|---|---|---|---|
+| `io.floci.owner` | `floci_owner_port` | ECS task containers, ECS credentials proxies, EC2 instance containers, security-group helpers | The owning deployment: `<namespace>/<port>`, or the bare API port without a resource namespace |
+| `io.floci.owner` | `floci_vpc_owner_port` | EC2 VPC networks | As above |
+| `io.floci.ecs.run` | `floci.ecs-run` | ECS task containers and their security-group helpers | The process run that created the container |
+| `io.floci.ecs.credentials-proxy` | `floci.ecs-task-role-credentials-proxy` | ECS credentials proxies | `true` |
+| `io.floci.security-group.helper` | `floci.security-group-helper` | Security-group helpers | `true` |
+| `io.floci.security-group.workload` | `floci.security-group-workload` | Workloads inside a security-group helper's network namespace | `true` |
+| `io.floci.component` | `floci.component` | The EventBridge Pipes Kafka bridge | `pipes-kafka-rest-bridge` |
+| `io.floci.service=ec2` and `io.floci.component=vpc-network` | `floci_component=ec2-vpc` | EC2 VPC networks | |
+| `io.floci.resource-id` | `floci_vpc_id` | EC2 VPC networks | The VPC id |
+| `io.floci.region` | `floci_vpc_region` | EC2 VPC networks | The VPC's region |
+
+Startup cleanup acts on an object only when every owner key it carries, new or legacy, names this deployment. An object whose new and legacy labels disagree was relabelled outside Floci and is left alone with a warning.
## Docker Network
diff --git a/docs/services/ecs.md b/docs/services/ecs.md
index b6a08ec0cb..f0b6287c85 100644
--- a/docs/services/ecs.md
+++ b/docs/services/ecs.md
@@ -522,9 +522,11 @@ nothing manages:
- In Docker mode, every ECS container a previous run of this Floci left on the daemon is
removed. A graceful shutdown already stops them; this covers a run that ended without one
(SIGKILL, OOM, a stop timeout that expired mid-drain). Containers are recognised by the
- `floci_owner_port` label (the resource namespace and API port), so the containers of another
+ `io.floci.owner` label (the resource namespace and API port), so the containers of another
Floci sharing the daemon stay, and are told apart from the current run's by a per-process
- `floci.ecs-run` label rather than by creation time. Containers created by a Floci version without that label are
+ `io.floci.ecs.run` label rather than by creation time. Both are also written under their legacy
+ names, `floci_owner_port` and `floci.ecs-run`, which are still read for containers an earlier
+ version created (see [Internal Labels](../configuration/docker.md#internal-labels)). Containers created by a Floci version without that label are
not recognised and must be removed by hand once. If Docker cannot list or remove one, the
ECS starts no task until it is gone, retrying the removal before each launch: a service's
replacement on a reconciliation tick, or a `RunTask` or `StartTask` call, whose task then stops
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index dcb71e2082..b7281b5ce9 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -2112,7 +2112,7 @@ public interface EmulatorConfig {
/**
* When true, Floci removes on startup, in Docker mode, every ECS container a previous run
- * of <em>this same</em> Floci left on the daemon (matched by the {@code floci_owner_port}
+ * of <em>this same</em> Floci left on the daemon (matched by the {@code io.floci.owner}
* label), task-role credentials proxies included, before the service scheduler starts
* replacement tasks. Turn it off when two Floci instances share a daemon with the same
* port and no resource namespace, so one does not remove the other's containers.
@@ -2965,7 +2965,7 @@ public interface EmulatorConfig {
/**
* When true, Floci removes on startup any EC2 instance container left on the Docker
* daemon by a previous run of <em>this same</em> Floci (matched by the
- * {@code floci_owner_port} label) whose instance record did not survive the restart, or
+ * {@code io.floci.owner} label) whose instance record did not survive the restart, or
* came back already terminated. Stopped instances are never swept — their containers are
* exactly what StartInstances revives.
*
@@ -3064,8 +3064,8 @@ public interface EmulatorConfig {
/**
* When true, VPC networks left behind by a previous run of this same Floci instance are
- * removed at startup. Scoped by the emulator's API port, so instances sharing a Docker
- * daemon never reconcile each other's networks.
+ * removed at startup. Scoped by the emulator's resource namespace and API port, so
+ * instances sharing a Docker daemon never reconcile each other's networks.
*/
@WithDefault("true")
boolean reconcileOnStartup();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index 1ae57ceb43..99b024b5ab 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -497,14 +497,15 @@ public class ContainerLifecycleManager {
/**
* Default emulator labels overlaid with the spec's labels; a per-spec label
- * wins on key conflicts.
+ * wins on key conflicts. Each new key with a legacy alias also gets that alias, with the
+ * same value (see {@link ContainerStorageHelper#CONTAINER_LABEL_ALIASES}).
*/
private Map<String, String> mergedLabels(Map<String, String> specLabels) {
Map<String, String> labels = ContainerStorageHelper.defaultLabels(config);
if (specLabels != null) {
labels.putAll(specLabels);
}
- return labels;
+ return ContainerStorageHelper.CONTAINER_LABEL_ALIASES.withLegacyAliases(labels);
}
/**
@@ -973,12 +974,14 @@ public class ContainerLifecycleManager {
if (spec.privileged()) {
hostConfig.withPrivileged(true);
}
- if (spec.labels() != null && "true".equals(spec.labels().get("floci.security-group-workload"))) {
+ if ("true".equals(ContainerStorageHelper.labelValue(
+ spec.labels(), ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL))) {
hostConfig.withCapDrop(Capability.NET_ADMIN, Capability.NET_RAW);
}
// The firewall helper only has to program nftables in the namespace it already owns,
// which needs CAP_NET_ADMIN and nothing else that privileged mode would also grant.
- if (spec.labels() != null && "true".equals(spec.labels().get("floci.security-group-helper"))) {
+ if ("true".equals(ContainerStorageHelper.labelValue(
+ spec.labels(), ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL))) {
hostConfig.withCapAdd(Capability.NET_ADMIN);
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java
index f9e3eba1c4..115a5f00c8 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java
@@ -6,8 +6,14 @@ import org.jboss.logging.Logger;
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.LinkedHashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
/**
* Central helper for child-container volume management across RDS, OpenSearch, MSK, and ECR.
@@ -35,8 +41,49 @@ public final class ContainerStorageHelper {
/** {@link #NAME_PREFIX} with its separator, the literal prefix of every name produced here. */
static final String CONTAINER_PREFIX = NAME_PREFIX + "-";
+
+ public static final String SERVICE_LABEL = "io.floci.service";
+ public static final String RESOURCE_ID_LABEL = "io.floci.resource-id";
+ public static final String ACCOUNT_LABEL = "io.floci.account";
+ public static final String REGION_LABEL = "io.floci.region";
/** The label carrying {@link #ownerIdentity(EmulatorConfig)}. */
- public static final String OWNER_LABEL = "floci_owner_port";
+ public static final String OWNER_LABEL = "io.floci.owner";
+ /** Names a Floci-internal part that backs no single emulated resource on its own. */
+ public static final String COMPONENT_LABEL = "io.floci.component";
+ /** The Floci process run that created an ECS container. */
+ public static final String ECS_RUN_LABEL = "io.floci.ecs.run";
+ /** Marks the proxy holding the ECS container-credentials address on a network. */
+ public static final String ECS_CREDENTIALS_PROXY_LABEL = "io.floci.ecs.credentials-proxy";
+ /** Marks the helper that owns a protected workload's network namespace and firewall. */
+ public static final String SECURITY_GROUP_HELPER_LABEL = "io.floci.security-group.helper";
+ /** Marks a workload running inside a security-group helper's network namespace. */
+ public static final String SECURITY_GROUP_WORKLOAD_LABEL = "io.floci.security-group.workload";
+
+ /**
+ * The labels Floci wrote on containers before it took the {@code io.floci.*} namespace, each
+ * mapped from the key that replaced it. The legacy key is still written next to its new key
+ * with the same value, because containers outlive the process that labelled them and users
+ * may filter on the old key. This table is the only place a legacy container key is spelled.
+ */
+ public static final LabelAliases CONTAINER_LABEL_ALIASES = new LabelAliases(
+ Map.of(OWNER_LABEL, "floci_owner_port",
+ ECS_RUN_LABEL, "floci.ecs-run",
+ ECS_CREDENTIALS_PROXY_LABEL, "floci.ecs-task-role-credentials-proxy",
+ SECURITY_GROUP_HELPER_LABEL, "floci.security-group-helper",
+ SECURITY_GROUP_WORKLOAD_LABEL, "floci.security-group-workload",
+ COMPONENT_LABEL, "floci.component"),
+ List.of());
+
+ /**
+ * {@link #CONTAINER_LABEL_ALIASES} for the Docker networks backing VPCs. The same new key can
+ * have a different legacy key here: a network's owner was {@code floci_vpc_owner_port}.
+ */
+ public static final LabelAliases NETWORK_LABEL_ALIASES = new LabelAliases(
+ Map.of(OWNER_LABEL, "floci_vpc_owner_port",
+ RESOURCE_ID_LABEL, "floci_vpc_id",
+ REGION_LABEL, "floci_vpc_region"),
+ List.of(new LabelAliases.Composite(
+ Map.of(SERVICE_LABEL, "ec2", COMPONENT_LABEL, "vpc-network"), "floci_component", "ec2-vpc")));
/**
* The prefix this emulator used before it took the shared {@code floci-<cloud>-} convention.
@@ -132,10 +179,18 @@ public final class ContainerStorageHelper {
* drive container/volume discovery and pruning (e.g.
* {@code docker volume prune --filter label=floci=true}); {@code floci_namespace} scopes
* resources when multiple Floci processes share one daemon. Extra labels using these keys
- * are ignored so user configuration can never break cleanup.
+ * are ignored so user configuration can never break cleanup. Every key in
+ * {@link #CONTAINER_LABEL_ALIASES} and {@link #NETWORK_LABEL_ALIASES}, new and legacy, is
+ * reserved too, so a user label can never fake an owner or identity a cleanup path trusts.
*/
- private static final java.util.Set<String> RESERVED_LABEL_KEYS =
- java.util.Set.of("floci", "floci_emulator", "floci_namespace");
+ private static final Set<String> RESERVED_LABEL_KEYS = reservedLabelKeys();
+
+ private static Set<String> reservedLabelKeys() {
+ Set<String> keys = new LinkedHashSet<>(List.of("floci", "floci_emulator", "floci_namespace"));
+ keys.addAll(CONTAINER_LABEL_ALIASES.keys());
+ keys.addAll(NETWORK_LABEL_ALIASES.keys());
+ return Set.copyOf(keys);
+ }
/**
* Labels applied to every emulator-created container and volume:
@@ -179,13 +234,18 @@ public final class ContainerStorageHelper {
String service, String resourceId, String accountId, String region) {
Map<String, String> labels = new LinkedHashMap<>();
labels.put("io.floci", CLOUD);
- putIfNotBlank(labels, "io.floci.service", service);
- putIfNotBlank(labels, "io.floci.resource-id", resourceId);
- putIfNotBlank(labels, "io.floci.account", accountId);
- putIfNotBlank(labels, "io.floci.region", region);
+ putIfNotBlank(labels, SERVICE_LABEL, service);
+ putIfNotBlank(labels, RESOURCE_ID_LABEL, resourceId);
+ putIfNotBlank(labels, ACCOUNT_LABEL, accountId);
+ putIfNotBlank(labels, REGION_LABEL, region);
return labels;
}
+ /** {@link LabelAliases#labelValue} for a container's labels. */
+ public static String labelValue(Map<String, String> labels, String key) {
+ return CONTAINER_LABEL_ALIASES.labelValue(labels, key);
+ }
+
/**
* Identity of the Floci deployment that owns a container, stamped as {@link #OWNER_LABEL} so a
* startup sweep collects only its own leftovers. The API port alone collides when two
@@ -336,4 +396,172 @@ public final class ContainerStorageHelper {
LOG.errorv("Failed to create data directory {0}: {1}", hostDataPath, e.getMessage());
}
}
+
+ /**
+ * One kind of Docker object's legacy label keys, each mapped from the {@code io.floci.*} key
+ * that replaced it. Writers set only the new key and pass the labels through
+ * {@link #withLegacyAliases}; readers go through {@link #labelValue}, {@link #matches} and
+ * {@link #consistent}; a Docker-side label filter goes through {@link #listByLabels}, since a
+ * filter is an AND and cannot ask for "new key or legacy key".
+ */
+ public static final class LabelAliases {
+
+ /**
+ * A legacy key whose single value stood for several new labels at once, such as
+ * {@code floci_component=ec2-vpc} for {@code io.floci.service=ec2} plus
+ * {@code io.floci.component=vpc-network}.
+ */
+ record Composite(Map<String, String> labels, String legacyKey, String legacyValue) {}
+
+ private final Map<String, String> legacyByKey;
+ private final List<Composite> composites;
+
+ LabelAliases(Map<String, String> legacyByKey, List<Composite> composites) {
+ this.legacyByKey = Map.copyOf(legacyByKey);
+ this.composites = List.copyOf(composites);
+ }
+
+ /** Every key this table names, new and legacy. */
+ public Set<String> keys() {
+ Set<String> keys = new LinkedHashSet<>();
+ legacyByKey.forEach((key, legacy) -> {
+ keys.add(key);
+ keys.add(legacy);
+ });
+ for (Composite composite : composites) {
+ keys.addAll(composite.labels().keySet());
+ keys.add(composite.legacyKey());
+ }
+ return keys;
+ }
+
+ /** {@code labels} plus the legacy alias of each new key present, carrying the same value. */
+ public Map<String, String> withLegacyAliases(Map<String, String> labels) {
+ Map<String, String> aliased = new LinkedHashMap<>(labels);
+ legacyByKey.forEach((key, legacy) -> {
+ String value = labels.get(key);
+ if (value != null) {
+ aliased.put(legacy, value);
+ }
+ });
+ for (Composite composite : composites) {
+ if (containsAll(labels, composite.labels())) {
+ aliased.put(composite.legacyKey(), composite.legacyValue());
+ }
+ }
+ return aliased;
+ }
+
+ /** The value under {@code key}, or under its legacy alias when {@code key} is absent. */
+ public String labelValue(Map<String, String> labels, String key) {
+ if (labels == null) {
+ return null;
+ }
+ String value = labels.get(key);
+ return value != null ? value : legacyValue(labels, key);
+ }
+
+ /**
+ * Whether {@code labels} carry {@code expected} under {@code key}, for a decision that
+ * removes or trusts the object: at least one of the key and its legacy alias is present,
+ * and every one present equals {@code expected}. An object whose new and legacy values
+ * disagree never matches.
+ */
+ public boolean matches(Map<String, String> labels, String key, String expected) {
+ if (labels == null) {
+ return false;
+ }
+ String value = labels.get(key);
+ String legacy = legacyValue(labels, key);
+ if (value == null && legacy == null) {
+ return false;
+ }
+ return (value == null || value.equals(expected)) && (legacy == null || legacy.equals(expected));
+ }
+
+ /**
+ * False, with a warning, when any new key and its legacy alias are both present with
+ * different values. Floci always writes the two together, so a disagreement means
+ * something outside Floci relabelled the object, which a destructive path then leaves alone.
+ */
+ public boolean consistent(String objectId, Map<String, String> labels) {
+ if (labels == null) {
+ return true;
+ }
+ Set<String> keys = new LinkedHashSet<>(legacyByKey.keySet());
+ composites.forEach(composite -> keys.addAll(composite.labels().keySet()));
+ for (String key : keys) {
+ String value = labels.get(key);
+ String legacy = legacyValue(labels, key);
+ if (value != null && legacy != null && !value.equals(legacy)) {
+ LOG.warnv("Leaving Docker object {0} alone: label {1}={2} disagrees with its legacy alias ({3})",
+ objectId, key, value, legacy);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * The label filters that find an object labelled with {@code filter}: the filter itself
+ * and, when any of its keys has a legacy alias, the same filter spelled with the legacy keys.
+ */
+ public List<Map<String, String>> labelFilters(Map<String, String> filter) {
+ Map<String, String> legacy = new LinkedHashMap<>(filter);
+ for (Composite composite : composites) {
+ if (containsAll(filter, composite.labels())) {
+ composite.labels().keySet().forEach(legacy::remove);
+ legacy.put(composite.legacyKey(), composite.legacyValue());
+ }
+ }
+ filter.forEach((key, value) -> {
+ String legacyKey = legacyByKey.get(key);
+ if (legacyKey != null) {
+ legacy.remove(key);
+ legacy.put(legacyKey, value);
+ }
+ });
+ return legacy.equals(filter) ? List.of(filter) : List.of(filter, legacy);
+ }
+
+ /**
+ * Runs {@code query} once per filter of {@link #labelFilters} and merges the results by
+ * object id, so an object labelled with the new keys, the legacy keys or both is listed once.
+ */
+ public <T> List<T> listByLabels(Map<String, String> filter, Function<Map<String, String>, List<T>> query,
+ Function<T, String> idOf) {
+ Map<String, T> byId = new LinkedHashMap<>();
+ for (Map<String, String> variant : labelFilters(filter)) {
+ List<T> found = query.apply(variant);
+ if (found != null) {
+ found.forEach(object -> byId.putIfAbsent(idOf.apply(object), object));
+ }
+ }
+ return new ArrayList<>(byId.values());
+ }
+
+ /** The value under {@code key}'s legacy alias, or null when it has none or the label is absent. */
+ public String legacyValue(Map<String, String> labels, String key) {
+ String legacyKey = legacyByKey.get(key);
+ if (legacyKey != null) {
+ return labels.get(legacyKey);
+ }
+ for (Composite composite : composites) {
+ if (composite.labels().containsKey(key) && labels.containsKey(composite.legacyKey())) {
+ String legacy = labels.get(composite.legacyKey());
+ return composite.legacyValue().equals(legacy) ? composite.labels().get(key) : legacy;
+ }
+ }
+ return null;
+ }
+
+ private static boolean containsAll(Map<String, String> labels, Map<String, String> expected) {
+ for (Map.Entry<String, String> entry : expected.entrySet()) {
+ if (!Objects.equals(labels.get(entry.getKey()), entry.getValue())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
index 8679095119..25ec90a183 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
@@ -107,16 +107,18 @@ public class Ec2ContainerManager {
};
/**
- * Label identifying the Floci process that created an EC2 instance container, by its API
- * port. {@link #reconcileOrphanedContainers} lists on the existing {@code io.floci.service=ec2}
- * identity label (see {@link ContainerStorageHelper#resourceIdentityLabels}) and then keeps
- * only containers carrying <em>this</em> process's owner port: several emulators can share one
+ * Label identifying the Floci deployment that created an EC2 instance container, by its
+ * resource namespace and API port. {@link #reconcileOrphanedContainers} lists on the existing
+ * {@code io.floci.service=ec2} identity label (see
+ * {@link ContainerStorageHelper#resourceIdentityLabels}) and then keeps
+ * only containers carrying <em>this</em> deployment's owner: several emulators can share one
* Docker daemon, and an unscoped sweep would reap a sibling's live instances.
* {@code floci_namespace} is the documented scoping mechanism for that, but it is absent
* unless a resource namespace is configured, so it cannot scope the default configuration.
* Containers created before this label existed carry no owner and are therefore never swept.
*/
- static final String LABEL_OWNER_PORT = ContainerStorageHelper.OWNER_LABEL;
+ static final String LABEL_OWNER = ContainerStorageHelper.OWNER_LABEL;
+ private static final ContainerStorageHelper.LabelAliases ALIASES = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
/**
* Identity of the Floci deployment that owns a container, for scoping the startup sweep.
@@ -128,10 +130,10 @@ public class Ec2ContainerManager {
private String ownerIdentity() {
return ContainerStorageHelper.ownerIdentity(config);
}
- static final String LABEL_SERVICE = "io.floci.service";
+ static final String LABEL_SERVICE = ContainerStorageHelper.SERVICE_LABEL;
static final String SERVICE_VALUE = "ec2";
- static final String LABEL_RESOURCE_ID = "io.floci.resource-id";
- static final String LABEL_REGION = "io.floci.region";
+ static final String LABEL_RESOURCE_ID = ContainerStorageHelper.RESOURCE_ID_LABEL;
+ static final String LABEL_REGION = ContainerStorageHelper.REGION_LABEL;
static int containerBridgeIpAttempts = 30;
static long containerBridgeIpPollMillis = 500;
@@ -187,10 +189,11 @@ public class Ec2ContainerManager {
String helperId = mode.substring("container:".length());
InspectContainerResponse helper = dockerClient.inspectContainerCmd(helperId).exec();
Map<String, String> labels = helper.getConfig().getLabels();
- if (!"true".equals(labels.get("floci.security-group-helper"))
+ if (!ALIASES.consistent(helperId, labels)
+ || !ALIASES.matches(labels, ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true")
|| !"ec2".equals(labels.get(LABEL_SERVICE))
|| !instance.getInstanceId().equals(labels.get(LABEL_RESOURCE_ID))
- || !ownerIdentity().equals(labels.get(LABEL_OWNER_PORT))) {
+ || !ALIASES.matches(labels, LABEL_OWNER, ownerIdentity())) {
throw new IllegalStateException("EC2 workload network namespace is not Floci protected");
}
String address = helper.getNetworkSettings().getNetworks().values().stream()
@@ -694,8 +697,8 @@ public class Ec2ContainerManager {
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ec2", instanceId, regionResolver.getAccountId(), region))
// Which Floci owns this container, so the startup reconciler cannot reap a
- // sibling emulator's live instances off a shared daemon. See LABEL_OWNER_PORT.
- .withLabels(Map.of(LABEL_OWNER_PORT, ownerIdentity()))
+ // sibling emulator's live instances off a shared daemon. See LABEL_OWNER.
+ .withLabels(Map.of(LABEL_OWNER, ownerIdentity()))
// EC2 instances expose IMDS on 169.254.169.254. Floci needs network administration
// privileges in the local container to attach that link-local address.
.withPrivileged(namespace == null)
@@ -715,7 +718,7 @@ public class Ec2ContainerManager {
specBuilder.withPortBinding(22, sshHostPort);
} else {
specBuilder.withNetworkMode("container:" + namespace.helperId());
- specBuilder.withLabels(Map.of("floci.security-group-workload", "true"));
+ specBuilder.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true"));
}
if (image.systemd()) {
specBuilder
@@ -1071,7 +1074,7 @@ public class Ec2ContainerManager {
.exec();
for (Container container : containers) {
Map<String, String> labels = container.getLabels() == null ? Map.of() : container.getLabels();
- if (!owner.equals(labels.get(LABEL_OWNER_PORT))) {
+ if (!ALIASES.consistent(container.getId(), labels) || !ALIASES.matches(labels, LABEL_OWNER, owner)) {
continue;
}
String instanceId = labels.get(LABEL_RESOURCE_ID);
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManager.java
index ed0ef2d1b7..e4b40a3fe5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManager.java
@@ -68,17 +68,20 @@ public class SecurityGroupFirewallManager {
}
try {
String owner = ContainerStorageHelper.ownerIdentity(config);
- dockerClient.listContainersCmd().withShowAll(true)
- .withLabelFilter(Map.of("floci.security-group-helper", "true"))
- .exec().stream()
- .filter(container -> owner.equals(container.getLabels().get(ContainerStorageHelper.OWNER_LABEL)))
+ ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
+ aliases.listByLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true"),
+ filter -> dockerClient.listContainersCmd().withShowAll(true)
+ .withLabelFilter(filter).exec(),
+ Container::getId).stream()
+ .filter(container -> aliases.consistent(container.getId(), container.getLabels())
+ && aliases.matches(container.getLabels(), ContainerStorageHelper.OWNER_LABEL, owner))
.forEach(container -> {
if ("running".equals(container.getState())) {
quarantine(container.getId());
} else {
stopNamespaceWorkloads(container.getId());
}
- if ("ecs".equals(container.getLabels().get("io.floci.service"))) {
+ if ("ecs".equals(container.getLabels().get(ContainerStorageHelper.SERVICE_LABEL))) {
removeNamespaceWorkloads(container.getId());
lifecycleManager.removeIfExists(container.getId());
}
@@ -121,7 +124,7 @@ public class SecurityGroupFirewallManager {
.withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of("exec sleep 2147483647"))
.withLabels(ContainerStorageHelper.resourceIdentityLabels(service, resourceId, accountId, region))
- .withLabels(Map.of("floci.security-group-helper", "true",
+ .withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true",
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
if (portBindings != null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java
index 9ab43a3855..e244415fee 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java
@@ -18,6 +18,7 @@ import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -88,17 +89,17 @@ public class VpcNetworkManager {
private static final Logger LOG = Logger.getLogger(VpcNetworkManager.class);
- /** Marks a Docker network as a Floci VPC network, for discovery and orphan reconciliation. */
- public static final String LABEL_COMPONENT = "floci_component";
- public static final String COMPONENT_VALUE = "ec2-vpc";
- public static final String LABEL_VPC_ID = "floci_vpc_id";
- public static final String LABEL_VPC_REGION = "floci_vpc_region";
/**
- * The API port of the Floci process that created the network. Several Floci instances
- * routinely share one Docker daemon, and reconciliation deletes things; scoping it by
- * owner is what stops one instance's startup from tearing down another's live networks.
+ * With {@code io.floci.service=ec2}, marks a Docker network as a Floci VPC network, for
+ * discovery and orphan reconciliation. The network also carries the VPC id and region as its
+ * resource identity, and {@link ContainerStorageHelper#OWNER_LABEL}: several Floci instances
+ * routinely share one Docker daemon, and reconciliation deletes things; scoping it by owner is
+ * what stops one instance's startup from tearing down another's live networks.
*/
- public static final String LABEL_OWNER_PORT = "floci_vpc_owner_port";
+ public static final String COMPONENT_VALUE = "vpc-network";
+ public static final String SERVICE_VALUE = "ec2";
+ private static final ContainerStorageHelper.LabelAliases ALIASES = ContainerStorageHelper.NETWORK_LABEL_ALIASES;
+ private static final String NAMESPACE_LABEL = "floci_namespace";
/**
* Instance addresses start here inside each subnet slice. AWS reserves the first four
@@ -736,13 +737,31 @@ public class VpcNetworkManager {
return subnets;
}
+ /**
+ * Whether a VPC network belongs to this deployment. A network created before the owner label
+ * took the resource namespace carries only the legacy {@code floci_vpc_owner_port} key, holding
+ * the bare API port that every deployment on that port wrote; such a network is this
+ * deployment's when its {@code floci_namespace} label also names this deployment's namespace
+ * (none when unset), which is the same identity {@link ContainerStorageHelper#ownerIdentity}
+ * encodes for networks created since.
+ */
+ private boolean ownedByThisDeployment(Map<String, String> labels) {
+ if (labels.containsKey(ContainerStorageHelper.OWNER_LABEL)) {
+ return ALIASES.matches(labels, ContainerStorageHelper.OWNER_LABEL,
+ ContainerStorageHelper.ownerIdentity(config));
+ }
+ String legacyOwner = ALIASES.legacyValue(labels, ContainerStorageHelper.OWNER_LABEL);
+ return String.valueOf(config.port()).equals(legacyOwner)
+ && Objects.equals(labels.get(NAMESPACE_LABEL),
+ ContainerStorageHelper.defaultLabels(config).get(NAMESPACE_LABEL));
+ }
+
private Map<String, String> networkLabels(VpcBinding vpc) {
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.defaultLabels(config));
- labels.put(LABEL_COMPONENT, COMPONENT_VALUE);
- labels.put(LABEL_VPC_ID, vpc.vpcId);
- labels.put(LABEL_VPC_REGION, vpc.region);
- labels.put(LABEL_OWNER_PORT, String.valueOf(config.port()));
- return labels;
+ labels.putAll(ContainerStorageHelper.resourceIdentityLabels(SERVICE_VALUE, vpc.vpcId, null, vpc.region));
+ labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT_VALUE);
+ labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
+ return ALIASES.withLegacyAliases(labels);
}
// ─── Teardown ────────────────────────────────────────────────────────────
@@ -798,8 +817,9 @@ public class VpcNetworkManager {
* mode in this project, and one that looks like a genuine collision, so it would silently
* push every VPC into the fallback pool.
*
- * <p>Only networks labelled with this process's own API port are considered. Several Floci
- * instances share a daemon here; scoping by owner is what makes the deletion safe.
+ * <p>Only networks labelled with this deployment's own owner identity (resource namespace and
+ * API port) are considered. Several Floci instances share a daemon here; scoping by owner is
+ * what makes the deletion safe.
*
* @param stillDeclared answers whether (region, vpcId) exists in the restored state
*/
@@ -807,18 +827,24 @@ public class VpcNetworkManager {
if (!enabled() || !config.services().ec2().vpcNetworks().reconcileOnStartup()) {
return;
}
- String owner = String.valueOf(config.port());
int removed = 0;
try {
- for (Network network : dockerClient.listNetworksCmd()
- .withFilter("label", List.of(LABEL_COMPONENT + "=" + COMPONENT_VALUE))
- .exec()) {
+ List<Network> networks = ALIASES.listByLabels(
+ Map.of(ContainerStorageHelper.SERVICE_LABEL, SERVICE_VALUE,
+ ContainerStorageHelper.COMPONENT_LABEL, COMPONENT_VALUE),
+ filter -> dockerClient.listNetworksCmd()
+ .withFilter("label", filter.entrySet().stream()
+ .map(entry -> entry.getKey() + "=" + entry.getValue())
+ .toList())
+ .exec(),
+ Network::getId);
+ for (Network network : networks) {
Map<String, String> labels = network.getLabels() == null ? Map.of() : network.getLabels();
- if (!owner.equals(labels.get(LABEL_OWNER_PORT))) {
+ if (!ALIASES.consistent(network.getName(), labels) || !ownedByThisDeployment(labels)) {
continue;
}
- String vpcId = labels.get(LABEL_VPC_ID);
- String region = labels.get(LABEL_VPC_REGION);
+ String vpcId = ALIASES.labelValue(labels, ContainerStorageHelper.RESOURCE_ID_LABEL);
+ String region = ALIASES.labelValue(labels, ContainerStorageHelper.REGION_LABEL);
if (vpcId != null && region != null && stillDeclared.test(region, vpcId)) {
continue;
}
@@ -918,12 +944,11 @@ public class VpcNetworkManager {
*/
private Set<Cidr4> dockerNetworkSubnets(String ownVpcId) {
Set<Cidr4> taken = new java.util.LinkedHashSet<>();
- String owner = String.valueOf(config.port());
try {
for (Network network : dockerClient.listNetworksCmd().exec()) {
Map<String, String> labels = network.getLabels() == null ? Map.of() : network.getLabels();
- if (ownVpcId != null && ownVpcId.equals(labels.get(LABEL_VPC_ID))
- && owner.equals(labels.get(LABEL_OWNER_PORT))) {
+ if (ownVpcId != null && ALIASES.matches(labels, ContainerStorageHelper.RESOURCE_ID_LABEL, ownVpcId)
+ && ownedByThisDeployment(labels)) {
continue;
}
if (network.getIpam() == null || network.getIpam().getConfig() == null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
index 1e8861ac20..9fd5774b15 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
@@ -96,7 +96,7 @@ public class EcsContainerManager {
private static final String ATTACHMENT_DELETED = "DELETED";
/** The label naming the Floci process that created a container, set by {@link #ownerLabels()}. */
- public static final String RUN_LABEL = "floci.ecs-run";
+ public static final String RUN_LABEL = ContainerStorageHelper.ECS_RUN_LABEL;
/** EC2 error codes the task ENI path can raise, none of which RunTask declares. */
private static final Set<String> EC2_NETWORK_LOOKUP_FAILURES =
@@ -339,7 +339,7 @@ public class EcsContainerManager {
.withLabels(ownerLabels());
if (protectedNetwork != null) {
specBuilder.withNetworkMode("container:" + protectedNetwork.namespace().helperId());
- specBuilder.withLabels(Map.of("floci.security-group-workload", "true"));
+ specBuilder.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true"));
}
// Its own address in the credential endpoint's range, so this container has a
// connected route to 169.254.170.2 at all. One per container, not per task: each
@@ -1115,14 +1115,18 @@ public class EcsContainerManager {
/** {@link #removeLeftoverContainers()} keeping only the containers of run {@code currentRunId}. */
public boolean removeLeftoverContainers(String currentRunId) {
String owner = ContainerStorageHelper.ownerIdentity(config);
+ ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
List<com.github.dockerjava.api.model.Container> containers;
try {
// Docker's container summary, not the ECS model Container this class imports.
- containers = lifecycleManager.getDockerClient()
- .listContainersCmd()
- .withShowAll(true)
- .withLabelFilter(Map.of("io.floci.service", "ecs", ContainerStorageHelper.OWNER_LABEL, owner))
- .exec();
+ containers = aliases.listByLabels(
+ Map.of(ContainerStorageHelper.SERVICE_LABEL, "ecs", ContainerStorageHelper.OWNER_LABEL, owner),
+ filter -> lifecycleManager.getDockerClient()
+ .listContainersCmd()
+ .withShowAll(true)
+ .withLabelFilter(filter)
+ .exec(),
+ com.github.dockerjava.api.model.Container::getId);
} catch (Exception e) {
LOG.logv(leftoverListFailureReported ? Logger.Level.DEBUG : Logger.Level.WARN,
"Could not list the ECS containers a previous run left behind: {0}", e.getMessage());
@@ -1132,7 +1136,10 @@ public class EcsContainerManager {
leftoverListFailureReported = false;
boolean allRemoved = true;
for (com.github.dockerjava.api.model.Container container : containers) {
- if (container.getLabels() != null && currentRunId.equals(container.getLabels().get(RUN_LABEL))) {
+ Map<String, String> labels = container.getLabels();
+ if (!aliases.consistent(container.getId(), labels)
+ || !aliases.matches(labels, ContainerStorageHelper.OWNER_LABEL, owner)
+ || currentRunId.equals(aliases.labelValue(labels, RUN_LABEL))) {
continue;
}
try {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java
index 3b861f9ce9..11c97338fa 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java
@@ -40,7 +40,8 @@ public class EcsCredentialsProxy implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(EcsCredentialsProxy.class);
private static final String CREDENTIALS_ADDRESS = "169.254.170.2";
- private static final String OWNS_NETWORK_LABEL = "floci.ecs-task-role-credentials-proxy";
+ private static final String OWNS_NETWORK_LABEL = ContainerStorageHelper.ECS_CREDENTIALS_PROXY_LABEL;
+ private static final ContainerStorageHelper.LabelAliases ALIASES = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
private static final int VERIFY_ATTEMPTS = 30;
private static final long VERIFY_INTERVAL_MILLIS = 200;
private static final int EXEC_TIMEOUT_SECONDS = 10;
@@ -70,7 +71,7 @@ public class EcsCredentialsProxy implements ContainerTeardown {
* credential routing depend on which one wins ARP. Remove any surviving one this exact process
* owned before minting new ones.
*
- * <p>Scoped to this instance's own {@code floci_owner_port}, the same convention {@code
+ * <p>Scoped to this instance's own {@code io.floci.owner}, the same convention {@code
* SecurityGroupFirewallManager} uses: several Floci processes can share one Docker daemon, and
* a label match alone would let one instance's restart tear down another's still-running,
* still-in-use proxy.
@@ -85,10 +86,12 @@ public class EcsCredentialsProxy implements ContainerTeardown {
return;
}
try {
- dockerClient.listContainersCmd().withShowAll(true)
- .withLabelFilter(Map.of(OWNS_NETWORK_LABEL, "true"))
- .exec().stream()
- .filter(container -> owner().equals(container.getLabels().get(ContainerStorageHelper.OWNER_LABEL)))
+ ALIASES.listByLabels(Map.of(OWNS_NETWORK_LABEL, "true"),
+ filter -> dockerClient.listContainersCmd().withShowAll(true)
+ .withLabelFilter(filter).exec(),
+ Container::getId).stream()
+ .filter(container -> ALIASES.consistent(container.getId(), container.getLabels())
+ && ALIASES.matches(container.getLabels(), ContainerStorageHelper.OWNER_LABEL, owner()))
.forEach(container -> lifecycleManager.removeIfExists(container.getId()));
} catch (Exception e) {
LOG.warnv("Could not reap surviving ECS credentials proxy containers: {0}", e.getMessage());
@@ -189,8 +192,8 @@ public class EcsCredentialsProxy implements ContainerTeardown {
/**
* Removes a container by this exact name only when it is safe to: it must actually be one of
- * this label's proxy containers, and it must be either unowned (predates the {@code
- * floci_owner_port} convention) or owned by this same Floci instance. A same-named proxy
+ * this label's proxy containers, and it must be either unowned (predates the owner label
+ * convention) or owned by this same Floci instance. A same-named proxy
* belonging to a different instance sharing this daemon is left alone; removing it would
* interrupt that instance's tasks mid-flight, which a name collision here does not justify.
*/
@@ -203,9 +206,12 @@ public class EcsCredentialsProxy implements ContainerTeardown {
continue;
}
Map<String, String> labels = candidate.getLabels();
- boolean isOurProxy = labels != null && "true".equals(labels.get(OWNS_NETWORK_LABEL));
- String candidateOwner = labels == null ? null : labels.get(ContainerStorageHelper.OWNER_LABEL);
- if (isOurProxy && (candidateOwner == null || owner().equals(candidateOwner))) {
+ if (!ALIASES.consistent(candidate.getId(), labels)) {
+ continue;
+ }
+ boolean isOurProxy = ALIASES.matches(labels, OWNS_NETWORK_LABEL, "true");
+ boolean unowned = ALIASES.labelValue(labels, ContainerStorageHelper.OWNER_LABEL) == null;
+ if (isOurProxy && (unowned || ALIASES.matches(labels, ContainerStorageHelper.OWNER_LABEL, owner()))) {
lifecycleManager.removeIfExists(candidate.getId());
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java b/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java
index 3054d6bc78..b706c537ba 100644
--- a/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java
@@ -111,7 +111,10 @@ class KarapaceManager {
// is the REST Proxy's own dedicated process, config-driven entirely by KARAPACE_* env.
.withEntrypoint(List.of("/venv/bin/karapace_rest_proxy"))
.withEnv(env)
- .withLabels(Map.of("floci.component", "pipes-kafka-rest-bridge"));
+ // Shared by every Pipe reading this bootstrap target, in any account or region,
+ // so the identity names the service only.
+ .withLabels(ContainerStorageHelper.resourceIdentityLabels("pipes", null, null, null))
+ .withLabels(Map.of(ContainerStorageHelper.COMPONENT_LABEL, "pipes-kafka-rest-bridge"));
int hostPort = 0;
if (!containerDetector.isRunningInContainer()) {
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java
index 5a94444b36..746851b2f7 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java
@@ -103,10 +103,39 @@ class ContainerLifecycleManagerLabelsTest {
capturedLabels(createCmd));
}
+ @Test
+ void createWritesTheLegacyAliasOfEachNewKeyWithTheSameValue() {
+ CreateContainerCmd createCmd = stubCreateContainer();
+ ContainerSpec spec = specWithLabels(Map.of(
+ ContainerStorageHelper.OWNER_LABEL, "alpha/4566",
+ ContainerStorageHelper.ECS_RUN_LABEL, "run-1"));
+
+ manager().create(spec);
+
+ assertEquals(
+ Map.of("floci", "true", "floci_emulator", "floci-aws",
+ "io.floci.owner", "alpha/4566", "floci_owner_port", "alpha/4566",
+ "io.floci.ecs.run", "run-1", "floci.ecs-run", "run-1"),
+ capturedLabels(createCmd));
+ }
+
@Test
void protectedWorkloadCannotAdministerOrSpoofItsNetwork() {
CreateContainerCmd createCmd = stubCreateContainer();
+ manager().create(specWithLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true")));
+
+ ArgumentCaptor<HostConfig> hostConfig = ArgumentCaptor.forClass(HostConfig.class);
+ verify(createCmd).withHostConfig(hostConfig.capture());
+ List<Capability> dropped = List.of(hostConfig.getValue().getCapDrop());
+ assertTrue(dropped.contains(Capability.NET_ADMIN));
+ assertTrue(dropped.contains(Capability.NET_RAW));
+ }
+
+ @Test
+ void protectedWorkloadSpecWithOnlyTheLegacyLabelStillDropsNetworkAdministration() {
+ CreateContainerCmd createCmd = stubCreateContainer();
+
manager().create(specWithLabels(Map.of("floci.security-group-workload", "true")));
ArgumentCaptor<HostConfig> hostConfig = ArgumentCaptor.forClass(HostConfig.class);
@@ -128,6 +157,17 @@ class ContainerLifecycleManagerLabelsTest {
assertNotEquals(Boolean.TRUE, hostConfig.getValue().getPrivileged());
}
+ @Test
+ void firewallHelperSpecWithTheNewLabelGetsNetAdmin() {
+ CreateContainerCmd createCmd = stubCreateContainer();
+
+ manager().create(specWithLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true")));
+
+ ArgumentCaptor<HostConfig> hostConfig = ArgumentCaptor.forClass(HostConfig.class);
+ verify(createCmd).withHostConfig(hostConfig.capture());
+ assertEquals(List.of(Capability.NET_ADMIN), List.of(hostConfig.getValue().getCapAdd()));
+ }
+
@Test
void specLabelWinsOverDefaultOnKeyConflict() {
CreateContainerCmd createCmd = stubCreateContainer();
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelperTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelperTest.java
index 7002e977c0..5ae4995042 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelperTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelperTest.java
@@ -4,10 +4,14 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -106,7 +110,7 @@ class ContainerStorageHelperTest {
void extraLabelsAreMergedIntoDefaultLabels() {
// A dotted key — exactly the shape that motivates list-of-entries config over a Map,
// whose env-var naming convention cannot express such keys.
- EmulatorConfig config = config("", java.util.List.of(
+ EmulatorConfig config = config("", List.of(
label("com.example.project", "my-project"),
label("environment", "dev")));
@@ -120,7 +124,7 @@ class ContainerStorageHelperTest {
void extraLabelsCannotOverrideReservedKeys() {
// The reserved labels drive container/volume discovery and pruning; a user label must
// never be able to break `docker volume prune --filter label=floci=true` cleanup.
- EmulatorConfig config = config(" run/one ", java.util.List.of(
+ EmulatorConfig config = config(" run/one ", List.of(
label("floci", "false"),
label("floci_emulator", "spoofed"),
label("floci_namespace", "spoofed"),
@@ -134,7 +138,7 @@ class ContainerStorageHelperTest {
@Test
void blankExtraLabelKeysAreIgnored() {
- EmulatorConfig config = config("", java.util.List.of(
+ EmulatorConfig config = config("", List.of(
label(" ", "dropped"),
label(null, "dropped"),
label("kept", null)));
@@ -164,6 +168,170 @@ class ContainerStorageHelperTest {
ContainerStorageHelper.resourceIdentityLabels("ecr", null, "", " "));
}
+ @Test
+ void extraLabelsCannotSetAnAliasedKeyNewOrLegacy() {
+ // A cleanup path trusts the owner and identity labels; a user label must never fake one.
+ EmulatorConfig config = config("", List.of(
+ label("io.floci.owner", "spoofed"),
+ label("floci_owner_port", "spoofed"),
+ label("io.floci.ecs.run", "spoofed"),
+ label("floci.ecs-run", "spoofed"),
+ label("floci.security-group-helper", "true"),
+ label("io.floci.component", "spoofed"),
+ label("floci_vpc_owner_port", "spoofed"),
+ label("floci_vpc_id", "spoofed"),
+ label("io.floci.resource-id", "spoofed"),
+ label("floci_component", "ec2-vpc"),
+ label("kept", "yes")));
+
+ assertEquals(
+ Map.of("floci", "true", "floci_emulator", "floci-aws", "kept", "yes"),
+ ContainerStorageHelper.defaultLabels(config));
+ }
+
+ @Test
+ void ownerIdentityPrefixesTheResourceNamespaceToThePort() {
+ EmulatorConfig plain = config("");
+ when(plain.port()).thenReturn(4566);
+ EmulatorConfig namespaced = config("alpha");
+ when(namespaced.port()).thenReturn(4566);
+
+ assertEquals("4566", ContainerStorageHelper.ownerIdentity(plain));
+ assertEquals("alpha/4566", ContainerStorageHelper.ownerIdentity(namespaced));
+ }
+
+ @Test
+ void containerAliasesWriteEachLegacyKeyWithTheNewKeysValue() {
+ Map<String, String> labels = ContainerStorageHelper.CONTAINER_LABEL_ALIASES.withLegacyAliases(Map.of(
+ "io.floci.owner", "alpha/4566",
+ "io.floci.ecs.run", "run-1",
+ "io.floci.ecs.credentials-proxy", "true",
+ "io.floci.security-group.helper", "true",
+ "io.floci.security-group.workload", "true",
+ "io.floci.component", "pipes-kafka-rest-bridge",
+ "io.floci.service", "ecs"));
+
+ assertEquals("alpha/4566", labels.get("floci_owner_port"));
+ assertEquals("run-1", labels.get("floci.ecs-run"));
+ assertEquals("true", labels.get("floci.ecs-task-role-credentials-proxy"));
+ assertEquals("true", labels.get("floci.security-group-helper"));
+ assertEquals("true", labels.get("floci.security-group-workload"));
+ assertEquals("pipes-kafka-rest-bridge", labels.get("floci.component"));
+ assertEquals("alpha/4566", labels.get("io.floci.owner"), "the new key stays");
+ assertEquals("ecs", labels.get("io.floci.service"));
+ assertEquals(13, labels.size(), "a key without an alias gains nothing");
+ }
+
+ @Test
+ void networkAliasesUseTheirOwnLegacyKeysAndTheComposite() {
+ Map<String, String> labels = ContainerStorageHelper.NETWORK_LABEL_ALIASES.withLegacyAliases(Map.of(
+ "io.floci.owner", "alpha/4566",
+ "io.floci.resource-id", "vpc-1",
+ "io.floci.region", "us-east-1",
+ "io.floci.service", "ec2",
+ "io.floci.component", "vpc-network"));
+
+ assertEquals("alpha/4566", labels.get("floci_vpc_owner_port"));
+ assertFalse(labels.containsKey("floci_owner_port"), "the container alias of the owner is not a network's");
+ assertEquals("vpc-1", labels.get("floci_vpc_id"));
+ assertEquals("us-east-1", labels.get("floci_vpc_region"));
+ assertEquals("ec2-vpc", labels.get("floci_component"));
+ }
+
+ @Test
+ void theCompositeAliasNeedsEveryOneOfItsNewLabels() {
+ Map<String, String> labels = ContainerStorageHelper.NETWORK_LABEL_ALIASES.withLegacyAliases(Map.of(
+ "io.floci.service", "ec2", "io.floci.component", "something-else"));
+
+ assertFalse(labels.containsKey("floci_component"));
+ }
+
+ @Test
+ void labelValuePrefersTheNewKeyAndFallsBackToTheLegacyOne() {
+ ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
+
+ assertEquals("4566", aliases.labelValue(Map.of("io.floci.owner", "4566"), "io.floci.owner"));
+ assertEquals("4566", aliases.labelValue(Map.of("floci_owner_port", "4566"), "io.floci.owner"));
+ assertEquals("4566", aliases.labelValue(
+ Map.of("io.floci.owner", "4566", "floci_owner_port", "4566"), "io.floci.owner"));
+ assertEquals("4566", aliases.labelValue(
+ Map.of("io.floci.owner", "4566", "floci_owner_port", "4567"), "io.floci.owner"));
+ assertNull(aliases.labelValue(Map.of(), "io.floci.owner"));
+ assertNull(aliases.labelValue(null, "io.floci.owner"));
+ assertEquals("run-1", ContainerStorageHelper.labelValue(Map.of("floci.ecs-run", "run-1"), "io.floci.ecs.run"));
+ }
+
+ @Test
+ void labelValueReadsTheCompositeBackIntoEachOfItsNewKeys() {
+ ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.NETWORK_LABEL_ALIASES;
+ Map<String, String> legacy = Map.of("floci_component", "ec2-vpc", "floci_vpc_id", "vpc-1");
+
+ assertEquals("ec2", aliases.labelValue(legacy, "io.floci.service"));
+ assertEquals("vpc-network", aliases.labelValue(legacy, "io.floci.component"));
+ assertEquals("vpc-1", aliases.labelValue(legacy, "io.floci.resource-id"));
+ }
+
+ @Test
+ void matchesRequiresEveryOwnerKeyPresentToAgree() {
+ ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
+
+ assertTrue(aliases.matches(Map.of("io.floci.owner", "4566"), "io.floci.owner", "4566"));
+ assertTrue(aliases.matches(Map.of("floci_owner_port", "4566"), "io.floci.owner", "4566"));
+ assertTrue(aliases.matches(
+ Map.of("io.floci.owner", "4566", "floci_owner_port", "4566"), "io.floci.owner", "4566"));
+ assertFalse(aliases.matches(
+ Map.of("io.floci.owner", "4566", "floci_owner_port", "4567"), "io.floci.owner", "4566"));
+ assertFalse(aliases.matches(
+ Map.of("io.floci.owner", "4567", "floci_owner_port", "4566"), "io.floci.owner", "4566"));
+ assertFalse(aliases.matches(Map.of(), "io.floci.owner", "4566"), "an unowned object matches nobody");
+ }
+
+ @Test
+ void consistentRejectsAnObjectWhoseNewAndLegacyLabelsDisagree() {
+ ContainerStorageHelper.LabelAliases containers = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
+ ContainerStorageHelper.LabelAliases networks = ContainerStorageHelper.NETWORK_LABEL_ALIASES;
+
+ assertTrue(containers.consistent("c", Map.of("io.floci.owner", "4566")));
+ assertTrue(containers.consistent("c", Map.of("floci_owner_port", "4566")));
+ assertTrue(containers.consistent("c", Map.of("io.floci.owner", "4566", "floci_owner_port", "4566")));
+ assertFalse(containers.consistent("c", Map.of("io.floci.owner", "4566", "floci_owner_port", "4567")));
+ assertFalse(containers.consistent("c", Map.of("io.floci.ecs.run", "a", "floci.ecs-run", "b")));
+ assertTrue(networks.consistent("n", Map.of(
+ "io.floci.service", "ec2", "io.floci.component", "vpc-network", "floci_component", "ec2-vpc")));
+ assertFalse(networks.consistent("n", Map.of("io.floci.component", "other", "floci_component", "ec2-vpc")));
+ assertFalse(networks.consistent("n", Map.of("io.floci.resource-id", "vpc-1", "floci_vpc_id", "vpc-2")));
+ }
+
+ @Test
+ void labelFiltersSpellTheSameFilterWithTheLegacyKeys() {
+ assertEquals(
+ List.of(Map.of("io.floci.service", "ecs", "io.floci.owner", "4566"),
+ Map.of("io.floci.service", "ecs", "floci_owner_port", "4566")),
+ ContainerStorageHelper.CONTAINER_LABEL_ALIASES.labelFilters(
+ Map.of("io.floci.service", "ecs", "io.floci.owner", "4566")));
+ assertEquals(
+ List.of(Map.of("io.floci.service", "ec2", "io.floci.component", "vpc-network"),
+ Map.of("floci_component", "ec2-vpc")),
+ ContainerStorageHelper.NETWORK_LABEL_ALIASES.labelFilters(
+ Map.of("io.floci.service", "ec2", "io.floci.component", "vpc-network")));
+ assertEquals(
+ List.of(Map.of("io.floci.service", "ec2")),
+ ContainerStorageHelper.CONTAINER_LABEL_ALIASES.labelFilters(Map.of("io.floci.service", "ec2")),
+ "a filter with no aliased key is queried once");
+ }
+
+ @Test
+ void listByLabelsQueriesEachKeySetAndListsEveryObjectOnce() {
+ Map<Map<String, String>, List<String>> daemon = Map.of(
+ Map.of("io.floci.owner", "4566"), List.of("new-only", "both"),
+ Map.of("floci_owner_port", "4566"), List.of("legacy-only", "both"));
+
+ List<String> found = ContainerStorageHelper.CONTAINER_LABEL_ALIASES.listByLabels(
+ Map.of("io.floci.owner", "4566"), daemon::get, id -> id);
+
+ assertEquals(List.of("new-only", "both", "legacy-only"), found);
+ }
+
private static EmulatorConfig.DockerConfig.LabelEntry label(String key, String value) {
return new EmulatorConfig.DockerConfig.LabelEntry() {
@Override
@@ -179,7 +347,7 @@ class ContainerStorageHelperTest {
}
private static EmulatorConfig config(String namespace) {
- return config(namespace, java.util.List.of());
+ return config(namespace, List.of());
}
private static EmulatorConfig config(
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java
index 545515a79c..53aaa785c5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java
@@ -45,6 +45,7 @@ import java.io.Closeable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -342,6 +343,63 @@ class Ec2ContainerManagerTest {
@Test
void startOfAProtectedInstanceReusesTheHelperTransportAddress() throws Exception {
+ Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
+ Instance instance = startProtectedInstance(metadataServer, Map.of(
+ "floci.security-group-helper", "true",
+ "io.floci.service", "ec2",
+ "io.floci.resource-id", "i-protected",
+ "floci_owner_port", "4566"));
+
+ awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5));
+ verify(metadataServer, timeout(2000)).registerContainer("172.17.0.7", "i-protected", instance);
+ assertEquals("172.17.0.7", instance.getContainerBridgeIp(),
+ "StartInstances must keep addressing the instance through its protected namespace");
+ }
+
+ @Test
+ void startOfAProtectedInstanceAcceptsAHelperLabelledWithTheNewKeys() throws Exception {
+ Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
+ Instance instance = startProtectedInstance(metadataServer, Map.of(
+ "io.floci.security-group.helper", "true",
+ "io.floci.service", "ec2",
+ "io.floci.resource-id", "i-protected",
+ "io.floci.owner", "4566"));
+
+ awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5));
+ verify(metadataServer, timeout(2000)).registerContainer("172.17.0.7", "i-protected", instance);
+ }
+
+ @Test
+ void startOfAProtectedInstanceAcceptsAHelperWhoseNewAndLegacyKeysAgree() throws Exception {
+ Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
+ Instance instance = startProtectedInstance(metadataServer, Map.of(
+ "io.floci.security-group.helper", "true",
+ "floci.security-group-helper", "true",
+ "io.floci.service", "ec2",
+ "io.floci.resource-id", "i-protected",
+ "io.floci.owner", "4566",
+ "floci_owner_port", "4566"));
+
+ awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5));
+ verify(metadataServer, timeout(2000)).registerContainer("172.17.0.7", "i-protected", instance);
+ }
+
+ @Test
+ void startOfAProtectedInstanceRefusesAHelperWhoseNewAndLegacyOwnersDisagree() throws Exception {
+ Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
+ Instance instance = startProtectedInstance(metadataServer, Map.of(
+ "io.floci.security-group.helper", "true",
+ "floci.security-group-helper", "true",
+ "io.floci.service", "ec2",
+ "io.floci.resource-id", "i-protected",
+ "io.floci.owner", "4566",
+ "floci_owner_port", "4567"));
+
+ awaitUntil(() -> "stopped".equals(instance.getState().getName()), Duration.ofSeconds(5));
+ verify(metadataServer, never()).registerContainer(anyString(), anyString(), any());
+ }
+
+ private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map<String, String> helperLabels) {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
@@ -360,11 +418,7 @@ class Ec2ContainerManagerTest {
InspectContainerResponse helper = mock(InspectContainerResponse.class);
ContainerConfig helperConfig = mock(ContainerConfig.class);
- when(helperConfig.getLabels()).thenReturn(Map.of(
- "floci.security-group-helper", "true",
- "io.floci.service", "ec2",
- "io.floci.resource-id", "i-protected",
- "floci_owner_port", "4566"));
+ when(helperConfig.getLabels()).thenReturn(helperLabels);
when(helper.getConfig()).thenReturn(helperConfig);
NetworkSettings helperNetworks = mock(NetworkSettings.class);
when(helperNetworks.getNetworks())
@@ -378,7 +432,6 @@ class Ec2ContainerManagerTest {
when(config.port()).thenReturn(4566);
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
- Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = new Ec2ContainerManager(
mock(ContainerBuilder.class),
lifecycleManager,
@@ -401,11 +454,7 @@ class Ec2ContainerManagerTest {
instance.setDockerContainerId(TEST_CONTAINER_ID);
manager.start(instance);
- awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5));
-
- verify(metadataServer, timeout(2000)).registerContainer("172.17.0.7", "i-protected", instance);
- assertEquals("172.17.0.7", instance.getContainerBridgeIp(),
- "StartInstances must keep addressing the instance through its protected namespace");
+ return instance;
}
private static Ec2ContainerManager managerWith(ContainerLifecycleManager lifecycleManager,
@@ -1618,7 +1667,7 @@ class Ec2ContainerManagerTest {
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
// Without this label the reconciler cannot tell one emulator's containers from another's
// on a shared Docker daemon, so it could only ever be unsafe or a no-op.
- verify(harness.builder).withLabels(Map.of(Ec2ContainerManager.LABEL_OWNER_PORT, "4680"));
+ verify(harness.builder).withLabels(Map.of(Ec2ContainerManager.LABEL_OWNER, "4680"));
}
@Test
@@ -1687,6 +1736,46 @@ class Ec2ContainerManagerTest {
verify(harness.lifecycleManager, never()).removeIfExists("c-sibling");
}
+ @Test
+ void reconcileOrphanedContainersFindsOwnersUnderTheLegacyKeyOrBoth() {
+ LaunchHarness harness = reconcileHarness(true, 4680);
+ stubContainerListing(harness.dockerClient,
+ withOwners("c-legacy", Map.of("floci_owner_port", "4680"), "i-legacy"),
+ withOwners("c-both", Map.of("io.floci.owner", "4680", "floci_owner_port", "4680"), "i-both"),
+ withOwners("c-legacy-sibling", Map.of("floci_owner_port", "4620"), "i-sibling"));
+
+ int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false);
+
+ assertEquals(2, removed);
+ verify(harness.lifecycleManager).removeIfExists("c-legacy");
+ verify(harness.lifecycleManager).removeIfExists("c-both");
+ verify(harness.lifecycleManager, never()).removeIfExists("c-legacy-sibling");
+ }
+
+ @Test
+ void reconcileOrphanedContainersLeavesAContainerWhoseOwnersDisagreeAlone() {
+ LaunchHarness harness = reconcileHarness(true, 4680);
+ stubContainerListing(harness.dockerClient,
+ withOwners("c-new-ours", Map.of("io.floci.owner", "4680", "floci_owner_port", "4620"), "i-1"),
+ withOwners("c-legacy-ours", Map.of("io.floci.owner", "4620", "floci_owner_port", "4680"), "i-2"));
+
+ int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false);
+
+ assertEquals(0, removed);
+ verify(harness.lifecycleManager, never()).removeIfExists(anyString());
+ }
+
+ private static Container withOwners(String containerId, Map<String, String> owners, String instanceId) {
+ Map<String, String> labels = new HashMap<>(owners);
+ labels.put(Ec2ContainerManager.LABEL_SERVICE, Ec2ContainerManager.SERVICE_VALUE);
+ labels.put(Ec2ContainerManager.LABEL_REGION, "us-east-1");
+ labels.put(Ec2ContainerManager.LABEL_RESOURCE_ID, instanceId);
+ Container container = mock(Container.class);
+ when(container.getId()).thenReturn(containerId);
+ when(container.getLabels()).thenReturn(labels);
+ return container;
+ }
+
@Test
void reconcileOrphanedContainersDoesNothingWhenDisabled() {
LaunchHarness harness = reconcileHarness(false, 4680);
@@ -1701,7 +1790,7 @@ class Ec2ContainerManagerTest {
when(container.getId()).thenReturn(containerId);
when(container.getLabels()).thenReturn(Map.of(
Ec2ContainerManager.LABEL_SERVICE, Ec2ContainerManager.SERVICE_VALUE,
- Ec2ContainerManager.LABEL_OWNER_PORT, ownerPort,
+ Ec2ContainerManager.LABEL_OWNER, ownerPort,
Ec2ContainerManager.LABEL_REGION, region,
Ec2ContainerManager.LABEL_RESOURCE_ID, instanceId));
return container;
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManagerTest.java
index 8386a196da..2e89ffd89e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/SecurityGroupFirewallManagerTest.java
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.ec2;
import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.ListContainersCmd;
+import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
@@ -11,6 +13,7 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -21,7 +24,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -73,4 +78,51 @@ class SecurityGroupFirewallManagerTest {
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
assertEquals(List.of(), manager.vpcResolvers());
}
+ @Test
+ void survivingEcsHelpersAreFoundUnderTheNewAndLegacyLabelsAndRemovedOnlyWhenTheirOwnersAgree() {
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.network().securityGroupEnforcement().enabled()).thenReturn(true);
+ when(config.port()).thenReturn(4566);
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ DockerClient dockerClient = mock(DockerClient.class);
+ ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
+ when(dockerClient.listContainersCmd()).thenReturn(listCmd);
+ when(listCmd.exec()).thenReturn(List.of());
+ ListContainersCmd byNewKeys = mock(ListContainersCmd.class);
+ ListContainersCmd byLegacyKeys = mock(ListContainersCmd.class);
+ when(listCmd.withLabelFilter(Map.of("io.floci.security-group.helper", "true"))).thenReturn(byNewKeys);
+ when(listCmd.withLabelFilter(Map.of("floci.security-group-helper", "true"))).thenReturn(byLegacyKeys);
+ Container newOnly = exitedEcsHelper("new-only",
+ Map.of("io.floci.security-group.helper", "true", "io.floci.owner", "4566"));
+ Container legacyOnly = exitedEcsHelper("legacy-only",
+ Map.of("floci.security-group-helper", "true", "floci_owner_port", "4566"));
+ Container both = exitedEcsHelper("both", Map.of(
+ "io.floci.security-group.helper", "true", "io.floci.owner", "4566",
+ "floci.security-group-helper", "true", "floci_owner_port", "4566"));
+ Container disagreeing = exitedEcsHelper("disagreeing", Map.of(
+ "io.floci.security-group.helper", "true", "io.floci.owner", "4566",
+ "floci.security-group-helper", "true", "floci_owner_port", "4567"));
+ when(byNewKeys.exec()).thenReturn(List.of(newOnly, both, disagreeing));
+ when(byLegacyKeys.exec()).thenReturn(List.of(legacyOnly, both, disagreeing));
+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
+ SecurityGroupFirewallManager manager = new SecurityGroupFirewallManager(dockerClient,
+ mock(ContainerBuilder.class), lifecycleManager, config, mock(EmbeddedDnsServer.class));
+
+ manager.quarantineSurvivingNamespaces();
+
+ verify(lifecycleManager).removeIfExists("new-only");
+ verify(lifecycleManager).removeIfExists("legacy-only");
+ verify(lifecycleManager).removeIfExists("both");
+ verify(lifecycleManager, never()).removeIfExists("disagreeing");
+ }
+
+ private static Container exitedEcsHelper(String id, Map<String, String> ownerLabels) {
+ Map<String, String> labels = new HashMap<>(ownerLabels);
+ labels.put("io.floci.service", "ecs");
+ Container container = mock(Container.class);
+ when(container.getId()).thenReturn(id);
+ when(container.getState()).thenReturn("exited");
+ when(container.getLabels()).thenReturn(labels);
+ return container;
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java
index c2aecab6ee..5ecdd38d23 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java
@@ -21,6 +21,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -28,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
@@ -519,12 +521,185 @@ class VpcNetworkManagerTest {
assertEquals("10.0.0.0/16", manager.effectiveVpcCidr(REGION, "vpc-1").orElseThrow());
}
+ @Test
+ void createdNetworkCarriesTheIdentityLabelsAndTheirLegacyAliases() {
+ manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
+ manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
+ String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
+
+ manager.attach(REGION, "vpc-1", "subnet-a", "container-1", address);
+
+ Map<String, String> expected = new LinkedHashMap<>();
+ expected.put("floci", "true");
+ expected.put("floci_emulator", "floci-aws");
+ expected.put("io.floci", "aws");
+ expected.put("io.floci.service", "ec2");
+ expected.put("io.floci.resource-id", "vpc-1");
+ expected.put("io.floci.region", REGION);
+ expected.put("io.floci.component", "vpc-network");
+ expected.put("io.floci.owner", "4650");
+ expected.put("floci_component", "ec2-vpc");
+ expected.put("floci_vpc_id", "vpc-1");
+ expected.put("floci_vpc_region", REGION);
+ expected.put("floci_vpc_owner_port", "4650");
+ assertEquals(expected, createdNetworkLabels());
+ }
+
+ @Test
+ void aNamespacedEmulatorOwnsItsNetworksByNamespaceAndPort() {
+ when(config.docker().resourceNamespace()).thenReturn(Optional.of("alpha"));
+ manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
+ manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
+ String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
+
+ manager.attach(REGION, "vpc-1", "subnet-a", "container-1", address);
+
+ Map<String, String> labels = createdNetworkLabels();
+ assertEquals("alpha/4650", labels.get("io.floci.owner"));
+ assertEquals("alpha/4650", labels.get("floci_vpc_owner_port"));
+ }
+
+ /** The labels a namespaced or plain Floci wrote on a VPC network before the io.floci.owner key. */
+ private static Map<String, String> preUpgradeLabels(String vpcId, String namespace) {
+ Map<String, String> labels = new LinkedHashMap<>();
+ labels.put("floci", "true");
+ if (namespace != null) {
+ labels.put("floci_namespace", namespace);
+ }
+ labels.put("floci_component", "ec2-vpc");
+ labels.put("floci_vpc_id", vpcId);
+ labels.put("floci_vpc_region", REGION);
+ labels.put("floci_vpc_owner_port", "4650");
+ return labels;
+ }
+
+ @Test
+ void aPreUpgradeNetworkOfThisNamespacedEmulatorIsNotReadAsACollision() {
+ when(config.docker().resourceNamespace()).thenReturn(Optional.of("alpha"));
+ existingNetwork(manager.networkName(REGION, "vpc-1"), "10.0.0.0/16", preUpgradeLabels("vpc-1", "alpha"));
+
+ manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
+
+ assertFalse(manager.isSubstituted(REGION, "vpc-1"),
+ "a network this namespace created before the owner label took the namespace is still its own");
+ assertEquals("10.0.0.0/16", manager.effectiveVpcCidr(REGION, "vpc-1").orElseThrow());
+ }
+
+ @Test
+ void reconcileRemovesAPreUpgradeOrphanOnlyWhenItsNamespaceIsThisEmulators() {
+ when(config.docker().resourceNamespace()).thenReturn(Optional.of("alpha"));
+ existingNetwork("floci-aws-alpha-vpc-4650-us-east-1-vpc-dead", "10.7.0.0/16",
+ preUpgradeLabels("vpc-dead", "alpha"));
+ existingNetwork("floci-aws-beta-vpc-4650-us-east-1-vpc-beta", "10.8.0.0/16",
+ preUpgradeLabels("vpc-beta", "beta"));
+ existingNetwork("floci-aws-vpc-4650-us-east-1-vpc-plain", "10.9.0.0/16",
+ preUpgradeLabels("vpc-plain", null));
+
+ manager.reconcileOrphans((region, vpcId) -> false);
+
+ assertEquals(List.of("floci-aws-alpha-vpc-4650-us-east-1-vpc-dead"), removedNetworks,
+ "the bare port in the legacy owner key is shared by every deployment on it, so only the "
+ + "namespace label decides which pre-upgrade network is this emulator's");
+ }
+
+ @Test
+ void reconcileQueriesTheNewAndLegacyKeySetsAndRemovesOrphansUnderEither() {
+ existingNetwork("vpc-new", "10.7.0.0/16", newLabels("vpc-new", "4650"));
+ existingNetwork("vpc-legacy", "10.8.0.0/16", ourLabels("vpc-legacy", "4650"));
+ existingNetwork("vpc-both", "10.9.0.0/16", bothLabels("vpc-both", "4650"));
+
+ manager.reconcileOrphans((region, vpcId) -> false);
+
+ assertEquals(List.of("vpc-new", "vpc-legacy", "vpc-both"), removedNetworks,
+ "each network is removed once, however many of the queries list it");
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<String>> filters = ArgumentCaptor.forClass(List.class);
+ verify(docker.listNetworksCmd(), times(2)).withFilter(eq("label"),
+ filters.capture());
+ assertEquals(List.of(Set.of("io.floci.service=ec2", "io.floci.component=vpc-network"),
+ Set.of("floci_component=ec2-vpc")),
+ filters.getAllValues().stream().map(Set::copyOf).toList());
+ }
+
+ @Test
+ void reconcileLeavesANetworkWhoseNewAndLegacyLabelsDisagreeAlone() {
+ Map<String, String> ownerDisagrees = bothLabels("vpc-1", "4650");
+ ownerDisagrees.put("floci_vpc_owner_port", "4620");
+ existingNetwork("owner-disagrees", "10.7.0.0/16", ownerDisagrees);
+ Map<String, String> vpcDisagrees = bothLabels("vpc-dead", "4650");
+ vpcDisagrees.put("floci_vpc_id", "vpc-live");
+ existingNetwork("vpc-disagrees", "10.8.0.0/16", vpcDisagrees);
+
+ manager.reconcileOrphans((region, vpcId) -> "vpc-live".equals(vpcId));
+
+ assertTrue(removedNetworks.isEmpty());
+ }
+
+ @Test
+ void twoNamespacedEmulatorsOnTheSamePortNeverReconcileEachOthersNetworks() {
+ when(config.docker().resourceNamespace()).thenReturn(Optional.of("alpha"));
+ existingNetwork("alpha-dead", "10.7.0.0/16", bothLabels("vpc-a", "alpha/4650"));
+ existingNetwork("beta-live", "10.8.0.0/16", bothLabels("vpc-b", "beta/4650"));
+ // Written by a namespaced emulator before owners carried the namespace: a bare port no
+ // longer names this deployment, so it is left alone rather than deleted.
+ existingNetwork("bare-port", "10.9.0.0/16", ourLabels("vpc-c", "4650"));
+
+ manager.reconcileOrphans((region, vpcId) -> false);
+
+ assertEquals(List.of("alpha-dead"), removedNetworks);
+ }
+
+ @Test
+ void anotherNamespacesNetworkForTheSameVpcIdIsStillACollision() {
+ when(config.docker().resourceNamespace()).thenReturn(Optional.of("alpha"));
+ existingNetwork("beta-vpc-1", "10.0.0.0/16", bothLabels("vpc-1", "beta/4650"));
+
+ manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
+
+ assertTrue(manager.isSubstituted(REGION, "vpc-1"),
+ "a sibling deployment's live network holds that range; it is not this VPC's own");
+ }
+
+ @Test
+ void aSurvivingNamespacedNetworkForTheSameVpcIsNotReadAsACollision() {
+ when(config.docker().resourceNamespace()).thenReturn(Optional.of("alpha"));
+ existingNetwork("alpha-vpc-1", "10.0.0.0/16", newLabels("vpc-1", "alpha/4650"));
+
+ manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
+
+ assertFalse(manager.isSubstituted(REGION, "vpc-1"));
+ }
+
+ private Map<String, String> createdNetworkLabels() {
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, String>> labels = ArgumentCaptor.forClass(Map.class);
+ verify(docker.createNetworkCmd()).withLabels(labels.capture());
+ return labels.getValue();
+ }
+
+ /** What a network created before the {@code io.floci.*} keys carries. */
private static Map<String, String> ourLabels(String vpcId, String ownerPort) {
Map<String, String> labels = new LinkedHashMap<>();
- labels.put(VpcNetworkManager.LABEL_COMPONENT, VpcNetworkManager.COMPONENT_VALUE);
- labels.put(VpcNetworkManager.LABEL_VPC_ID, vpcId);
- labels.put(VpcNetworkManager.LABEL_VPC_REGION, REGION);
- labels.put(VpcNetworkManager.LABEL_OWNER_PORT, ownerPort);
+ labels.put("floci_component", "ec2-vpc");
+ labels.put("floci_vpc_id", vpcId);
+ labels.put("floci_vpc_region", REGION);
+ labels.put("floci_vpc_owner_port", ownerPort);
+ return labels;
+ }
+
+ private static Map<String, String> newLabels(String vpcId, String owner) {
+ Map<String, String> labels = new LinkedHashMap<>();
+ labels.put("io.floci.service", "ec2");
+ labels.put("io.floci.component", "vpc-network");
+ labels.put("io.floci.resource-id", vpcId);
+ labels.put("io.floci.region", REGION);
+ labels.put("io.floci.owner", owner);
+ return labels;
+ }
+
+ private static Map<String, String> bothLabels(String vpcId, String owner) {
+ Map<String, String> labels = newLabels(vpcId, owner);
+ labels.putAll(ourLabels(vpcId, owner));
return labels;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java
index 0c7bf57e9f..8890790825 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java
@@ -1,8 +1,10 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
+import com.github.dockerjava.api.model.Container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -18,13 +20,18 @@ import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
+import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
@@ -204,10 +211,92 @@ class EcsContainerManagerLifecycleTest {
assertFalse(handle.getLogStreamsByContainerId().containsKey("stopped-id"));
}
+ @Test
+ void removeLeftoverContainersFindsOwnLeftoversUnderTheNewAndLegacyLabels() {
+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
+ Map<String, Container> newKeys = Map.of(
+ "new-only", leftover("new-only", Map.of(
+ "io.floci.service", "ecs", "io.floci.owner", "alpha/4566", "io.floci.ecs.run", "old-run")),
+ "both", leftover("both", Map.of(
+ "io.floci.service", "ecs", "io.floci.owner", "alpha/4566", "io.floci.ecs.run", "old-run",
+ "floci_owner_port", "alpha/4566", "floci.ecs-run", "old-run")),
+ "current-run", leftover("current-run", Map.of(
+ "io.floci.service", "ecs", "io.floci.owner", "alpha/4566", "io.floci.ecs.run", "current")));
+ Map<String, Container> legacyKeys = Map.of(
+ "legacy-only", leftover("legacy-only", Map.of(
+ "io.floci.service", "ecs", "floci_owner_port", "alpha/4566", "floci.ecs-run", "old-run")),
+ "both", newKeys.get("both"),
+ "legacy-current-run", leftover("legacy-current-run", Map.of(
+ "io.floci.service", "ecs", "floci_owner_port", "alpha/4566", "floci.ecs-run", "current")));
+ stubLeftoverListing(lifecycleManager, newKeys, legacyKeys);
+
+ assertTrue(manager(lifecycleManager, namespacedConfig()).removeLeftoverContainers("current"));
+
+ verify(lifecycleManager).removeIfExistsStrict("new-only");
+ verify(lifecycleManager).removeIfExistsStrict("legacy-only");
+ verify(lifecycleManager).removeIfExistsStrict("both");
+ verify(lifecycleManager, never()).removeIfExistsStrict("current-run");
+ verify(lifecycleManager, never()).removeIfExistsStrict("legacy-current-run");
+ }
+
+ @Test
+ void removeLeftoverContainersLeavesAContainerWhoseNewAndLegacyLabelsDisagreeAlone() {
+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
+ // Relabelled outside Floci: one owner key names a sibling deployment, or the run keys
+ // disagree on whether the container is the current run's. Neither is removed.
+ Map<String, Container> newKeys = Map.of(
+ "owner-disagrees", leftover("owner-disagrees", Map.of(
+ "io.floci.service", "ecs", "io.floci.owner", "alpha/4566", "io.floci.ecs.run", "old-run",
+ "floci_owner_port", "beta/4566", "floci.ecs-run", "old-run")),
+ "run-disagrees", leftover("run-disagrees", Map.of(
+ "io.floci.service", "ecs", "io.floci.owner", "alpha/4566", "io.floci.ecs.run", "current",
+ "floci_owner_port", "alpha/4566", "floci.ecs-run", "old-run")));
+ Map<String, Container> legacyKeys = Map.of("run-disagrees", newKeys.get("run-disagrees"));
+ stubLeftoverListing(lifecycleManager, newKeys, legacyKeys);
+
+ assertTrue(manager(lifecycleManager, namespacedConfig()).removeLeftoverContainers("current"));
+
+ verify(lifecycleManager, never()).removeIfExistsStrict(anyString());
+ }
+
+ private static void stubLeftoverListing(ContainerLifecycleManager lifecycleManager,
+ Map<String, Container> newKeys, Map<String, Container> legacyKeys) {
+ DockerClient dockerClient = mock(DockerClient.class);
+ when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
+ ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
+ when(dockerClient.listContainersCmd()).thenReturn(listCmd);
+ ListContainersCmd byNewKeys = mock(ListContainersCmd.class);
+ ListContainersCmd byLegacyKeys = mock(ListContainersCmd.class);
+ when(listCmd.withLabelFilter(Map.of("io.floci.service", "ecs", "io.floci.owner", "alpha/4566")))
+ .thenReturn(byNewKeys);
+ when(listCmd.withLabelFilter(Map.of("io.floci.service", "ecs", "floci_owner_port", "alpha/4566")))
+ .thenReturn(byLegacyKeys);
+ when(byNewKeys.exec()).thenReturn(List.copyOf(newKeys.values()));
+ when(byLegacyKeys.exec()).thenReturn(List.copyOf(legacyKeys.values()));
+ }
+
+ private static Container leftover(String id, Map<String, String> labels) {
+ Container container = mock(Container.class);
+ when(container.getId()).thenReturn(id);
+ when(container.getLabels()).thenReturn(labels);
+ return container;
+ }
+
+ private static EmulatorConfig namespacedConfig() {
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.port()).thenReturn(4566);
+ when(config.docker().resourceNamespace()).thenReturn(Optional.of("alpha"));
+ return config;
+ }
+
private static EcsContainerManager manager(ContainerLifecycleManager lifecycleManager) {
+ return manager(lifecycleManager, mock(EmulatorConfig.class));
+ }
+
+ private static EcsContainerManager manager(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) {
return new EcsContainerManager(
mock(ContainerBuilder.class), lifecycleManager, mock(ContainerLogStreamer.class),
- mock(ContainerDetector.class), mock(EmulatorConfig.class), mock(RegionResolver.class),
+ mock(ContainerDetector.class), config, mock(RegionResolver.class),
mock(LaunchedContainerAwsEnv.class), mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
mock(EcrRegistryManager.class), mock(HostVolumePolicy.class));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java
index 89472740d3..31b162e1bd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java
@@ -122,7 +122,7 @@ class EcsContainerManagerSecurityGroupTest {
List.of(), "us-east-1");
verify(builder).withNetworkMode("container:helper-id");
- verify(builder).withLabels(Map.of("floci.security-group-workload", "true"));
+ verify(builder).withLabels(Map.of("io.floci.security-group.workload", "true"));
verify(builder, never()).withPortBinding(anyInt(), anyInt());
verify(builder, never()).withDynamicPort(anyInt());
verify(builder, never()).withExposedPort(anyInt());
@@ -144,7 +144,7 @@ class EcsContainerManagerSecurityGroupTest {
List.of(), "us-east-1");
verify(builder, never()).withNetworkMode(anyString());
- verify(builder, never()).withLabels(Map.of("floci.security-group-workload", "true"));
+ verify(builder, never()).withLabels(Map.of("io.floci.security-group.workload", "true"));
verify(ec2Service, never()).createNetworkInterface(any(), any(), any(), any(), any(), any(), any());
verify(builder).withDynamicPort(80);
}
@@ -235,7 +235,7 @@ class EcsContainerManagerSecurityGroupTest {
manager.startTask(awsvpcTask(), taskDef, List.of(), "us-east-1");
verify(builder, times(2)).withNetworkMode("container:helper-id");
- verify(builder, times(2)).withLabels(Map.of("floci.security-group-workload", "true"));
+ verify(builder, times(2)).withLabels(Map.of("io.floci.security-group.workload", "true"));
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any());
verify(lifecycleManager).create(any());
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyDockerIntegrationTest.java
index a6ba86c78e..28be6829a0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyDockerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyDockerIntegrationTest.java
@@ -144,7 +144,7 @@ class EcsCredentialsProxyDockerIntegrationTest {
dockerClient, containerBuilder, lifecycleManager, dockerHostResolver, config);
proxy.ensureProxyOn(network);
proxyContainerId = dockerClient.listContainersCmd()
- .withLabelFilter(Map.of("floci.ecs-task-role-credentials-proxy", "true"))
+ .withLabelFilter(Map.of(ContainerStorageHelper.ECS_CREDENTIALS_PROXY_LABEL, "true"))
.withNetworkFilter(List.of(networkId))
.exec().get(0).getId();
@@ -213,7 +213,7 @@ class EcsCredentialsProxyDockerIntegrationTest {
ContainerSpec staleSpec = containerBuilder.newContainer("floci/network-helper:local")
.withName(name)
.withDockerNetwork(Optional.of(network))
- .withLabels(Map.of("floci.ecs-task-role-credentials-proxy", "true"))
+ .withLabels(Map.of(ContainerStorageHelper.ECS_CREDENTIALS_PROXY_LABEL, "true"))
.build();
String staleId = lifecycleManager.createAndStart(staleSpec).containerId();
dockerClient.stopContainerCmd(staleId).withTimeout(1).exec();
@@ -228,7 +228,7 @@ class EcsCredentialsProxyDockerIntegrationTest {
try {
proxy.ensureProxyOn(network);
proxyContainerId = dockerClient.listContainersCmd()
- .withLabelFilter(Map.of("floci.ecs-task-role-credentials-proxy", "true"))
+ .withLabelFilter(Map.of(ContainerStorageHelper.ECS_CREDENTIALS_PROXY_LABEL, "true"))
.withNetworkFilter(List.of(networkId))
.exec().get(0).getId();
assertEquals("running", dockerClient.inspectContainerCmd(proxyContainerId)
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
index 41af460195..fb3efecb04 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
@@ -182,6 +182,47 @@ class EcsCredentialsProxyTest {
verify(lifecycleManager, never()).removeIfExists("other-instance-proxy");
}
+ @Test
+ void removesAStaleContainerThisSameInstanceOwnsUnderTheNewLabels() {
+ stubSuccessfulLaunch("proxy-1");
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ when(config.port()).thenReturn(4566);
+ stubStaleContainerByName("stale-own", Map.of(
+ "io.floci.ecs.credentials-proxy", "true", "io.floci.owner", "4566"));
+
+ proxy.ensureProxyOn("floci-net");
+
+ verify(lifecycleManager).removeIfExists("stale-own");
+ }
+
+ @Test
+ void removesAStaleContainerWhoseNewAndLegacyLabelsAgree() {
+ stubSuccessfulLaunch("proxy-1");
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ when(config.port()).thenReturn(4566);
+ stubStaleContainerByName("stale-own", Map.of(
+ "io.floci.ecs.credentials-proxy", "true", "io.floci.owner", "4566",
+ "floci.ecs-task-role-credentials-proxy", "true", "floci_owner_port", "4566"));
+
+ proxy.ensureProxyOn("floci-net");
+
+ verify(lifecycleManager).removeIfExists("stale-own");
+ }
+
+ @Test
+ void leavesAStaleContainerWhoseNewAndLegacyOwnersDisagreeAlone() {
+ stubSuccessfulLaunch("proxy-1");
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ when(config.port()).thenReturn(4566);
+ stubStaleContainerByName("relabelled", Map.of(
+ "io.floci.ecs.credentials-proxy", "true", "io.floci.owner", "4566",
+ "floci.ecs-task-role-credentials-proxy", "true", "floci_owner_port", "4567"));
+
+ proxy.ensureProxyOn("floci-net");
+
+ verify(lifecycleManager, never()).removeIfExists("relabelled");
+ }
+
@Test
void leavesAnUnrelatedSameNamedContainerAlone() {
stubSuccessfulLaunch("proxy-1");
@@ -245,6 +286,47 @@ class EcsCredentialsProxyTest {
verify(lifecycleManager, never()).removeIfExists("other-instance-proxy");
}
+ @Test
+ void reapSurvivingProxiesQueriesTheNewAndLegacyLabelsAndRemovesOnlyAgreeingOwnLeftovers() {
+ when(config.services().ecs().reconcileContainersOnStartup()).thenReturn(true);
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ when(config.port()).thenReturn(4566);
+ ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
+ ListContainersCmd newKeys = mock(ListContainersCmd.class);
+ ListContainersCmd legacyKeys = mock(ListContainersCmd.class);
+ when(dockerClient.listContainersCmd()).thenReturn(listCmd);
+ when(listCmd.withLabelFilter(Map.of("io.floci.ecs.credentials-proxy", "true"))).thenReturn(newKeys);
+ when(listCmd.withLabelFilter(Map.of("floci.ecs-task-role-credentials-proxy", "true")))
+ .thenReturn(legacyKeys);
+ Container newOnly = proxyContainer("new-only",
+ Map.of("io.floci.ecs.credentials-proxy", "true", "io.floci.owner", "4566"));
+ Container legacyOnly = proxyContainer("legacy-only",
+ Map.of("floci.ecs-task-role-credentials-proxy", "true", "floci_owner_port", "4566"));
+ Container both = proxyContainer("both", Map.of(
+ "io.floci.ecs.credentials-proxy", "true", "io.floci.owner", "4566",
+ "floci.ecs-task-role-credentials-proxy", "true", "floci_owner_port", "4566"));
+ // Relabelled outside Floci: the legacy owner names another instance, so it is left alone.
+ Container disagreeing = proxyContainer("disagreeing", Map.of(
+ "io.floci.ecs.credentials-proxy", "true", "io.floci.owner", "4566",
+ "floci.ecs-task-role-credentials-proxy", "true", "floci_owner_port", "4567"));
+ when(newKeys.exec()).thenReturn(List.of(newOnly, both, disagreeing));
+ when(legacyKeys.exec()).thenReturn(List.of(legacyOnly, both, disagreeing));
+
+ proxy.reapSurvivingProxies();
+
+ verify(lifecycleManager).removeIfExists("new-only");
+ verify(lifecycleManager).removeIfExists("legacy-only");
+ verify(lifecycleManager).removeIfExists("both");
+ verify(lifecycleManager, never()).removeIfExists("disagreeing");
+ }
+
+ private static Container proxyContainer(String id, Map<String, String> labels) {
+ Container container = mock(Container.class);
+ when(container.getId()).thenReturn(id);
+ when(container.getLabels()).thenReturn(labels);
+ return container;
+ }
+
@Test
void reapSurvivingProxiesLeavesProxiesAloneWhenStartupReconciliationIsOff() {
when(config.services().ecs().reconcileContainersOnStartup()).thenReturn(false);
diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java
index 909ccb6bba..c3b811afcf 100644
--- a/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java
@@ -118,6 +118,25 @@ class KarapaceManagerTest {
assertEquals(Integer.valueOf(hostPort), spec.portBindings().get(REST_PORT));
}
+ @Test
+ void bridgeContainerCarriesThePipesIdentityAndItsComponent() throws Exception {
+ int hostPort = startFakeRestServer();
+ when(containerDetector.isRunningInContainer()).thenReturn(false);
+ when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort);
+ when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("container-1",
+ Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))));
+
+ manager.ensureStarted("broker-1:9092");
+
+ ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
+ verify(lifecycleManager).createAndStart(specCaptor.capture());
+ // The legacy floci.component alias is added where every container is created, not here.
+ assertEquals(
+ Map.of("io.floci", "aws", "io.floci.service", "pipes",
+ "io.floci.component", "pipes-kafka-rest-bridge"),
+ specCaptor.getValue().labels());
+ }
+
@Test
void ensureStartedReusesTheSameContainerForTheSameTarget() throws Exception {
int hostPort = startFakeRestServer();