Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ec2): reclaim instance containers orphaned by a hard restart (#3031)
Allen Sanborn94b9665c3224
diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex c810eff8b0..269348d637 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -675,6 +675,7 @@ State is reported settled rather than transitional, as elsewhere in this service| `FLOCI_SERVICES_EC2_MOCK` | `false` | Skip Docker; instances jump directly to final state (useful for tests) || `FLOCI_SERVICES_EC2_AWS_FAITHFUL_PRIVATE_IP` | `false` | Report the CFN/subnet-allocated private IP instead of the container bridge IP; routing and IMDS are unaffected || `FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE` | auto-detect | Whether an instance's container IP is reachable from the machines consuming Floci's API (Terraform, Terratest, your shell). When it is, DescribeInstances and DescribeAddresses report the container IP, so port 22 really is port 22; when it is not, they report `127.0.0.1` and reachability goes through the published high host ports. Detected by a throwaway TCP connect; set explicitly when Floci itself runs as a container |+| `FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | On startup, remove instance containers this Floci left on the daemon whose record did not survive the restart or came back terminated; stopped instances are never swept |## Requirementsdiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex a2d63931c6..3f91080ed6 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -2095,6 +2095,18 @@ public interface EmulatorConfig {*/Optional<Boolean> containerIpsRoutable();+ /**+ * 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+ * came back already terminated. Stopped instances are never swept — their containers are+ * exactly what StartInstances revives.+ *+ * Env var: FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP+ */+ @WithDefault("true")+ boolean reconcileContainersOnStartup();+/** Port on the Floci host for the IMDS HTTP server (169.254.169.254 equivalent). */@WithDefault("9169")int imdsPort();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.javaindex 7e891d964c..ab74e3b681 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@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManagerimport com.github.dockerjava.api.DockerClient;import com.github.dockerjava.api.exception.NotFoundException;import com.github.dockerjava.api.async.ResultCallback;+import com.github.dockerjava.api.model.Container;import com.github.dockerjava.api.model.ContainerNetwork;import com.github.dockerjava.api.model.Frame;import com.github.dockerjava.api.model.Mount;@@ -44,6 +45,7 @@ import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;+import java.util.function.BiPredicate;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.zip.GZIPInputStream;@@ -90,6 +92,35 @@ public class Ec2ContainerManager {* serialize concurrent decompressions deterministically. Always null in production. */static volatile Runnable userDataDecompressionTestHook;+ /**+ * 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+ * 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 = "floci_owner_port";++ /**+ * Identity of the Floci deployment that owns a container, for scoping the startup sweep.+ * The API port alone collides when two independently namespaced Flocis share a Docker daemon+ * on the same internal port, and each would then reap the other's live containers. Composing+ * the documented resource namespace in front of it separates exactly those deployments; an+ * unnamespaced single Floci keeps the bare port it already stamped.+ */+ private String ownerIdentity() {+ String ns = config.docker() == null || config.docker().resourceNamespace() == null+ ? "" : config.docker().resourceNamespace().orElse("");+ return ns.isBlank() ? String.valueOf(config.port()) : ns + "/" + config.port();+ }+ static final String LABEL_SERVICE = "io.floci.service";+ 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 int containerBridgeIpAttempts = 30;static long containerBridgeIpPollMillis = 500;@@ -366,6 +397,9 @@ public class Ec2ContainerManager {.withLogRotation().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()))// 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(true)@@ -633,6 +667,62 @@ public class Ec2ContainerManager {return containerId != null && !containerId.isBlank() && lifecycleManager.isContainerRunning(containerId);}+ /**+ * Removes EC2 instance containers this Floci left behind on a previous run.+ *+ * <p>{@link #terminate} removes the container asynchronously after flipping the record to+ * {@code shutting-down}, and {@code launch} persists the container id only once Docker has+ * created it. A process killed across either edge — SIGKILL, OOM, {@code docker kill} — leaves+ * a container on the daemon that no surviving record refers to, so nothing on the next run+ * would ever collect it. {@code Ec2Service.stopManagedContainers} only covers the graceful+ * ShutdownEvent path, and {@code restoreMetadataRegistration} deliberately skips records in+ * {@code terminated}/{@code shutting-down}, so neither reaches these.+ *+ * <p><strong>Stopped instances are not orphans.</strong> Floci stops every running container+ * on shutdown and keeps the id so StartInstances can revive it; those records come back as+ * {@code stopped} and {@code stillDeclared} keeps them. Only containers with no surviving+ * record, or whose record is already terminated/shutting-down, are removed.+ *+ * @param stillDeclared answers whether (region, instanceId) is still a live instance record+ * @return the number of containers removed+ */+ public int reconcileOrphanedContainers(BiPredicate<String, String> stillDeclared) {+ if (!config.services().ec2().reconcileContainersOnStartup()) {+ return 0;+ }+ String owner = ownerIdentity();+ int removed = 0;+ try {+ List<Container> containers = dockerClient.listContainersCmd()+ .withShowAll(true)+ .withLabelFilter(Map.of(LABEL_SERVICE, SERVICE_VALUE))+ .exec();+ for (Container container : containers) {+ Map<String, String> labels = container.getLabels() == null ? Map.of() : container.getLabels();+ if (!owner.equals(labels.get(LABEL_OWNER_PORT))) {+ continue;+ }+ String instanceId = labels.get(LABEL_RESOURCE_ID);+ String region = labels.get(LABEL_REGION);+ if (instanceId != null && !instanceId.isBlank()+ && region != null && !region.isBlank()+ && stillDeclared.test(region, instanceId)) {+ continue;+ }+ lifecycleManager.removeIfExists(container.getId());+ removed++;+ LOG.infov("Reconciled orphaned EC2 container {0} (instance {1}) left by a previous run",+ container.getId(), String.valueOf(instanceId));+ }+ } catch (Exception e) {+ LOG.warnv("Could not reconcile orphaned EC2 containers: {0}", e.getMessage());+ }+ if (removed > 0) {+ LOG.infov("Removed {0} orphaned EC2 container(s)", String.valueOf(removed));+ }+ return removed;+ }+boolean restoreMetadataRegistration(Instance instance) {if (instance == null || instance.getDockerContainerId() == null) {return false;diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex e2212c2b08..d093c9269f 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -414,6 +414,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {if (restored > 0) {LOG.infov("Restored IMDS metadata registration for {0} EC2 container(s)", restored);}++ // Runs after the restore loop, so anything legitimately revived above is already+ // accounted for and only genuine leftovers are left to collect.+ containerManager.reconcileOrphanedContainers(this::instanceContainerStillWanted);+ }++ /**+ * Whether a container labelled for (region, instanceId) still backs a live instance record.+ * False means the record is gone or already terminated, so the container is an orphan.+ */+ private boolean instanceContainerStillWanted(String region, String instanceId) {+ Instance instance = findAnyInstance(key(region, instanceId)).orElse(null);+ if (instance == null) {+ return false;+ }+ String state = instance.getState() == null ? null : instance.getState().getName();+ return !"terminated".equals(state) && !"shutting-down".equals(state);}private static boolean needsMetadataRegistration(Instance instance) {@@ -5404,6 +5421,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {return vpcs.keys().stream().anyMatch(k -> k.endsWith(suffix));}+ /**+ * An instance record from whichever account owns it. The startup sweep runs from+ * {@code @PostConstruct}, outside any request, where an account-aware backend resolves to the+ * default account: a record owned by another account would read as absent and its live+ * container would be destroyed. Read-only, so a cross-account hit stays in its own partition.+ */+ private Optional<Instance> findAnyInstance(String storageKey) {+ if (instances instanceof AccountAwareStorageBackend<?> rawAccountAware) {+ @SuppressWarnings("unchecked")+ AccountAwareStorageBackend<Instance> accountAware = (AccountAwareStorageBackend<Instance>) rawAccountAware;+ return accountAware.findAnyAccount(storageKey);+ }+ return instances.get(storageKey);+ }+private Optional<AccountAwareStorageBackend.OwnedEntry<Vpc>> findAnyVpcEntry(String region, String vpcId) {if (vpcs instanceof AccountAwareStorageBackend<?> rawAccountAware) {@SuppressWarnings("unchecked")diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 4ff684ae8e..ce96b52888 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -431,6 +431,10 @@ floci:ec2:enabled: trueimds-port: 9169+ # Sweep EC2 containers left on the daemon by a previous run that died mid-launch or+ # mid-terminate (SIGKILL, OOM, docker kill), which no surviving record refers to.+ # Scoped to this deployment's own containers; stopped instances are never swept.+ reconcile-containers-on-startup: truessh-port-range-start: 2200ssh-port-range-end: 2299publish-security-group-ports: truediff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.javaindex d7e3b1d6e0..ae511c0dd4 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@@ -10,6 +10,8 @@ import com.github.dockerjava.api.command.InspectContainerCmd;import com.github.dockerjava.api.command.InspectContainerResponse;import com.github.dockerjava.api.command.InspectExecCmd;import com.github.dockerjava.api.command.InspectExecResponse;+import com.github.dockerjava.api.command.ListContainersCmd;+import com.github.dockerjava.api.model.Container;import com.github.dockerjava.api.model.ContainerNetwork;import com.github.dockerjava.api.model.Frame;import com.github.dockerjava.api.model.StreamType;@@ -35,6 +37,7 @@ import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;@@ -965,7 +968,137 @@ class Ec2ContainerManagerTest {regionResolver,mock(ContainerNetworkReachability.class));return new LaunchHarness(manager, lifecycleManager, dockerClient, metadataServer, logStreamer, builder,- portAllocator, portForwardManager, new CopyOnWriteArrayList<>());+ portAllocator, portForwardManager, config, new CopyOnWriteArrayList<>());+ }++ // ── startup reconciliation of EC2 containers orphaned by a previous run ──────++ @Test+ void launchStampsTheOwnerPortLabelOnTheInstanceContainer() throws Exception {+ Ec2ContainerManager.containerBridgeIpAttempts = 1;+ Ec2ContainerManager.containerBridgeIpPollMillis = 1;+ LaunchHarness harness = launchHarness();+ when(harness.config.port()).thenReturn(4680);+ InspectContainerCmd inspect = mock(InspectContainerCmd.class);+ InspectContainerResponse withIp = inspectResponse("172.18.0.12");+ when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);+ when(inspect.exec()).thenReturn(withIp);+ harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));+ Instance instance = instance("i-owned");++ harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");++ 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"));+ }++ @Test+ void reconcileOrphanedContainersRemovesOnlyThisProcessesUnrecordedContainers() {+ LaunchHarness harness = reconcileHarness(true, 4680);+ stubContainerListing(harness.dockerClient,+ labelled("c-orphan", "4680", "us-east-1", "i-orphan"),+ labelled("c-live", "4680", "us-east-1", "i-live"),+ labelled("c-sibling", "4620", "us-east-1", "i-sibling"));++ // Only i-live still has a record. i-sibling belongs to the Floci on :4620 sharing this+ // daemon and must not be touched, however orphaned it looks from here.+ int removed = harness.manager.reconcileOrphanedContainers(+ (region, instanceId) -> "i-live".equals(instanceId));++ verify(harness.lifecycleManager, never()).removeIfExists("c-sibling");+ verify(harness.lifecycleManager, never()).removeIfExists("c-live");+ verify(harness.lifecycleManager).removeIfExists("c-orphan");+ assertEquals(1, removed);+ }++ @Test+ void reconcileOrphanedContainersLeavesStoppedInstancesAlone() {+ LaunchHarness harness = reconcileHarness(true, 4680);+ stubContainerListing(harness.dockerClient, labelled("c-stopped", "4680", "us-east-1", "i-stopped"));++ // Floci stops every running container on shutdown and keeps the id; the record comes+ // back as `stopped`, which stillDeclared answers true for. Sweeping these would break+ // stop/start across a restart.+ int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> true);++ verify(harness.lifecycleManager, never()).removeIfExists(anyString());+ assertEquals(0, removed);+ }++ @Test+ void reconcileOrphanedContainersIgnoresContainersPredatingTheOwnerLabel() {+ LaunchHarness harness = reconcileHarness(true, 4680);+ Container unowned = mock(Container.class);+ when(unowned.getLabels()).thenReturn(Map.of(+ Ec2ContainerManager.LABEL_SERVICE, Ec2ContainerManager.SERVICE_VALUE,+ Ec2ContainerManager.LABEL_REGION, "us-east-1",+ Ec2ContainerManager.LABEL_RESOURCE_ID, "i-legacy"));+ stubContainerListing(harness.dockerClient, unowned);++ int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false);++ verify(harness.lifecycleManager, never()).removeIfExists(anyString());+ assertEquals(0, removed);+ }++ @Test+ void reconcileOrphanedContainersSparesAnotherNamespacesContainerOnTheSamePort() {+ // Two Flocis can share a daemon on the same internal port and are separated only by the+ // resource namespace. Keying ownership on the port alone made each reap the other's live+ // containers; the owner label carries the namespace so a sibling's container is not ours.+ LaunchHarness harness = reconcileHarness(true, 4566, "alpha");+ stubContainerListing(harness.dockerClient,+ labelled("c-ours", "alpha/4566", "us-east-1", "i-ours"),+ labelled("c-sibling", "beta/4566", "us-east-1", "i-sibling"));++ int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false);++ assertEquals(1, removed);+ verify(harness.lifecycleManager).removeIfExists("c-ours");+ verify(harness.lifecycleManager, never()).removeIfExists("c-sibling");+ }++ @Test+ void reconcileOrphanedContainersDoesNothingWhenDisabled() {+ LaunchHarness harness = reconcileHarness(false, 4680);++ assertEquals(0, harness.manager.reconcileOrphanedContainers((region, instanceId) -> false));++ verify(harness.dockerClient, never()).listContainersCmd();+ }++ private static Container labelled(String containerId, String ownerPort, String region, String instanceId) {+ Container container = mock(Container.class);+ when(container.getId()).thenReturn(containerId);+ when(container.getLabels()).thenReturn(Map.of(+ Ec2ContainerManager.LABEL_SERVICE, Ec2ContainerManager.SERVICE_VALUE,+ Ec2ContainerManager.LABEL_OWNER_PORT, ownerPort,+ Ec2ContainerManager.LABEL_REGION, region,+ Ec2ContainerManager.LABEL_RESOURCE_ID, instanceId));+ return container;+ }++ private static void stubContainerListing(DockerClient dockerClient, Container... containers) {+ ListContainersCmd listCmd = mock(ListContainersCmd.class, withSettings().defaultAnswer(RETURNS_SELF));+ when(dockerClient.listContainersCmd()).thenReturn(listCmd);+ when(listCmd.exec()).thenReturn(new ArrayList<>(Arrays.asList(containers)));+ }++ private static LaunchHarness reconcileHarness(boolean reconcileEnabled, int ownerPort) {+ LaunchHarness harness = launchHarness();+ when(harness.config.port()).thenReturn(ownerPort);+ when(harness.config.services().ec2().reconcileContainersOnStartup()).thenReturn(reconcileEnabled);+ return harness;+ }++ private static LaunchHarness reconcileHarness(boolean reconcileEnabled, int ownerPort, String namespace) {+ LaunchHarness harness = reconcileHarness(reconcileEnabled, ownerPort);+ EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);+ when(docker.resourceNamespace()).thenReturn(Optional.ofNullable(namespace));+ when(harness.config.docker()).thenReturn(docker);+ return harness;}/**@@ -1075,6 +1208,7 @@ class Ec2ContainerManagerTest {ContainerBuilder.Builder builder,PortAllocator portAllocator,Ec2PortForwardManager portForwardManager,+ EmulatorConfig config,List<String[]> executedCommands) {void stubSuccessfulExecs(CountDownLatch userDataStarted, CountDownLatch finishUserData) throws Exception {AtomicReference<String[]> currentCommand = new AtomicReference<>();