fix(ecs): release stale task containers and registrations, and evict ones that would misroute a reused address (#4513)

* fix(ecs): release a previous run's task containers and registrations at startup

Task state is memory-only, so a restarted Floci knows no task and the
service scheduler starts a replacement for each service. A run that ended
without a graceful shutdown left its task containers serving beside those
replacements, and even a graceful one left their load balancer targets and
Cloud Map instances registered, so a dead task's target followed its
address to whichever container Docker handed it to next.

At startup, before the scheduler runs, ECS now removes the containers this
Floci owns (task containers now carry the floci_owner_port label EC2 and
the security-group helpers already use), deregisters the IP targets in each
service's target groups, and deregisters the Cloud Map instances its tasks
registered. The owner identity is computed by one shared helper.

* fix(ecs): release only the registrations ECS recorded, and retry failed container removal

The startup sweep recognised a previous run's load balancer targets by
their address shape and its Cloud Map instances by their ECS attributes,
so it also removed a target or instance registered by hand into the same
target group or Cloud Map service. Both registrars now persist each
registration they make, keyed by task ARN, drop the record on
deregistration, and at startup release exactly what was recorded.

Removing a leftover container now uses strict removal, and the result
says whether every leftover is gone. Until it is, each reconciliation
tick retries the sweep and starts no service task. The sweep only
considers containers created before this process started, so a retry
never touches a task this run launched.

* fix(ecs): tell a previous run's containers apart by run label, and record registrations before making them

The startup sweep kept every container created in the same second this process started, so a run killed within that second left an orphan the sweep reported as gone. Containers now carry a per-process floci.ecs-run label, also stamped on security-group helpers, and the sweep keeps only the current run's.

Target and Cloud Map registrations are now written to the ledger before they are made, so a process killed in between still leaves a record for the next run to release.

* fix(ecs): leave a target already in its group to whoever registered it

ELBv2 registration is idempotent, so a task whose address and port matched a target registered by hand adopted it: the ledger recorded it, and a task stop or the startup release then removed it. The registrar now skips and never records a target that is already registered.

* fix(ecs): deregister only the targets a task recorded when it stops

A task whose targets were all already in their groups records nothing, and its stop fell back to deregistering the targets its containers resolve to, removing the ones registered by hand. Every task this process knows went through the recording registrar, so the fallback now serves only a task without an ARN, which cannot be recorded.

* fix(ecs): retry the leftover sweep only when a service needs a task, and warn once

With Docker unreachable, the boot sweep failed and every 5 second tick then
logged two WARNs forever, even with no service to run. The retry now runs only
where a service is about to start a task, and both the sweep failure and the
blocked-launch message are WARNs the first time and DEBUG after.

* fix(ecs): log a repeated blocked service launch at DEBUG

* fix(ecs): retry the leftover sweep before RunTask and StartTask launches too

A task started through RunTask or StartTask no longer bypasses a failed sweep:
the common launch path retries it and stops the task with TaskFailedToStart
while a previous run's containers remain. Sweep failures are tracked per kind,
a failed listing and each container that would not go, so a new failure is
still a WARN after an earlier one cleared.

* fix(ecs): evict unrecorded registrations at a starting task's address, and adopt its own target

A target already in its group when a task started was skipped and never recorded, so a registration no task recorded, as one a Floci version without the ledger made, survived every task stop and restart. When a task of the same service came up on its address it left it in place, and when another service's task took the address the target or Cloud Map instance routed the first service's traffic to it.

A target at the task's own address and port is now recorded as the task's, so its stop deregisters it, as ECS does on AWS. When a task starts, every target and Cloud Map instance at one of its addresses that no live task recorded is deregistered from the target groups and Cloud Map services the region's ECS services name, with a warning. A loopback address matches only on the task's host ports.

* fix(ecs): evict only registrations that actually point at a starting task

The eviction matched every unrecorded target at any of a task's addresses on any port, including its ENI address. ECS registers no target at the ENI address, and an ENI address is unique only within its VPC, so an IP target for something in another VPC could be removed; a target on a port the task does not publish sends it nothing either.

Targets are now matched only at a container's Docker address on the ports its bindings declare. Cloud Map instances still match a container address on any port, since a DNS answer carries none, and match the ENI address only in a namespace of the task's own VPC.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-28 23:25:48 -05:00
1 parent 0232d5d224
commit 451a30f98e
16 files changed
+1369 -39

No files matched your search

@@ -0,0 +1,143 @@
package io.github.hectorvent.floci.services.ecs;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A Floci that ends without a graceful shutdown leaves its task containers running, and the next
* run knows no task, since task state is memory-only. Those containers must go at startup, or the
* service scheduler starts a second task beside each one. The sweep recognises them by the owner
* label a task container is created with, so a container of another Floci sharing the daemon stays,
* and tells this run's containers from a previous run's by the run label rather than by time.
*/
@QuarkusTest
@TestProfile(EcsServiceDiscoveryDockerIntegrationTest.DockerEcsProfile.class)
class EcsLeftoverContainersDockerIntegrationTest {
private static final String REGION = "us-east-1";
private static final String BUSYBOX_IMAGE = "public.ecr.aws/docker/library/busybox:latest";
@Inject
EcsService ecsService;
@Inject
EcsContainerManager containerManager;
@Inject
EmulatorConfig config;
@Inject
DockerClient dockerClient;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(),
"Docker daemon must be available for the ECS leftover container test");
}
@Test
void theStartupSweepRemovesTaskContainersAndKeepsAnotherFlocisContainers() {
String clusterName = unique("leftover-cluster");
ecsService.createCluster(clusterName, REGION);
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage(BUSYBOX_IMAGE);
app.setCommand(List.of("sleep", "120"));
TaskDefinition taskDef = ecsService.registerTaskDefinition(unique("leftover-td"), List.of(app),
NetworkMode.bridge, null, null, null, null, null, REGION);
EcsTask task = ecsService.runTask(clusterName, taskDef.getTaskDefinitionArn(), 1, LaunchType.EC2, null, null,
null, null, REGION).getFirst();
String foreignId = null;
String previousRunId = null;
try {
String taskContainerId = task.getContainers().getFirst().getDockerId();
assertNotNull(taskContainerId, "the task must have started a container: " + task.getStoppedReason());
assertEquals(ContainerStorageHelper.ownerIdentity(config), labels(taskContainerId)
.get(ContainerStorageHelper.OWNER_LABEL), "a task container must carry its owner");
foreignId = createEcsContainer(Map.of(ContainerStorageHelper.OWNER_LABEL, "another-floci/4566"));
// Created a moment ago, as by a run killed within the second this one started.
previousRunId = createEcsContainer(Map.of(ContainerStorageHelper.OWNER_LABEL,
ContainerStorageHelper.ownerIdentity(config), EcsContainerManager.RUN_LABEL, "a-previous-run"));
assertTrue(containerManager.removeLeftoverContainers(), "the sweep must succeed");
assertTrue(exists(taskContainerId), "a task container this run started must stay");
assertFalse(exists(previousRunId), "a previous run's container must be removed however recent");
assertTrue(containerManager.removeLeftoverContainers("the-next-run"), "the sweep must succeed");
assertFalse(exists(taskContainerId), "the leftover task container must be removed");
assertTrue(exists(foreignId), "another Floci's container must stay");
} finally {
ecsService.stopTask(clusterName, task.getTaskArn(), "test teardown", REGION);
for (String containerId : new String[] {foreignId, previousRunId}) {
if (containerId != null && exists(containerId)) {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
}
}
}
}
/** An ECS container carrying {@code ownership}, as another Floci or another run creates. */
private String createEcsContainer(Map<String, String> ownership) {
Map<String, String> labels = new HashMap<>(ownership);
labels.put("io.floci.service", "ecs");
CreateContainerResponse created = dockerClient.createContainerCmd(BUSYBOX_IMAGE)
.withName(unique("floci-other-ecs"))
.withCmd("sleep", "120")
.withLabels(labels)
.exec();
return created.getId();
}
private Map<String, String> labels(String containerId) {
return dockerClient.inspectContainerCmd(containerId).exec().getConfig().getLabels();
}
private boolean exists(String containerId) {
try {
dockerClient.inspectContainerCmd(containerId).exec();
return true;
} catch (NotFoundException e) {
return false;
}
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (RuntimeException e) {
return false;
}
}
private static String unique(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
}
}
@@ -4,19 +4,27 @@ import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.EcsTaskAddress;
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
import io.github.hectorvent.floci.services.elbv2.model.TargetHealth;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
/**
* Component test for {@link EcsLoadBalancerRegistrar}: drives the register/deregister
@@ -31,7 +39,7 @@ class EcsLoadBalancerRegistrarTest {
@Inject
EcsLoadBalancerRegistrar registrar;
@Inject
@InjectSpy
ElbV2Service elbV2Service;
private String createTargetGroup(String name) {
@@ -47,7 +55,7 @@ class EcsLoadBalancerRegistrarTest {
container.setNetworkBindings(List.of(
new NetworkBinding("0.0.0.0", containerPort, hostPort, "tcp")));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:" + REGION + ":000000000000:task/c/regtest");
task.setTaskArn("arn:aws:ecs:" + REGION + ":000000000000:task/c/" + UUID.randomUUID());
task.setGroup("regtest-svc");
task.setContainers(List.of(container));
return task;
@@ -125,4 +133,153 @@ class EcsLoadBalancerRegistrarTest {
assertTrue(elbV2Service.describeTargetHealth(REGION, tgArn, null).isEmpty(),
"no network binding for the declared containerPort -> no target");
}
@Test
void releaseRecordedTargetsKeepsATargetRegisteredByHand() {
String tgArn = createTargetGroup("reg-tg-stale");
registrar.registerTask(taskWithContainer("web", 8080, 34567), serviceWithLb(tgArn, "web", 8080), REGION);
elbV2Service.registerTargets(REGION, tgArn, List.of(target("172.18.0.7", 8080)));
registrar.releaseRecordedTargets();
List<TargetHealth> health = elbV2Service.describeTargetHealth(REGION, tgArn, null);
assertEquals(1, health.size(), "only the target registered by hand should survive");
assertEquals("172.18.0.7", health.get(0).getTarget().getId());
}
@Test
void deregisterTaskRemovesTheTargetItRecordedEvenAfterTheBindingChanged() {
String tgArn = createTargetGroup("reg-tg-recorded");
EcsTask task = taskWithContainer("web", 8080, 35000);
EcsServiceModel svc = serviceWithLb(tgArn, "web", 8080);
registrar.registerTask(task, svc, REGION);
task.getContainers().getFirst().setNetworkBindings(List.of(
new NetworkBinding("0.0.0.0", 8080, 36000, "tcp")));
registrar.deregisterTask(task, svc, REGION);
assertTrue(elbV2Service.describeTargetHealth(REGION, tgArn, null).isEmpty(),
"the recorded target should be deregistered");
}
@Test
void releaseRecordedTargetsToleratesADeletedTargetGroup() {
String tgArn = createTargetGroup("reg-tg-gone");
EcsTask task = taskWithContainer("web", 8080, 37000);
registrar.registerTask(task, serviceWithLb(tgArn, "web", 8080), REGION);
elbV2Service.deleteTargetGroup(REGION, tgArn);
registrar.releaseRecordedTargets();
}
@Test
void releaseRecordedTargetsReleasesATargetWhoseRegistrationWasCutShort() {
String tgArn = createTargetGroup("reg-tg-killed");
doAnswer(invocation -> {
invocation.callRealMethod();
throw new ProcessKilled();
}).when(elbV2Service).registerTargets(eq(REGION), eq(tgArn), any());
assertThrows(ProcessKilled.class, () -> registrar.registerTask(
taskWithContainer("web", 8080, 38000), serviceWithLb(tgArn, "web", 8080), REGION));
registrar.releaseRecordedTargets();
assertTrue(elbV2Service.describeTargetHealth(REGION, tgArn, null).isEmpty(),
"a target registered just before the process died should be released");
}
@Test
void aTargetAlreadyAtTheTasksAddressIsAdoptedAndRemovedWhenTheTaskStops() {
// Left by a task of a run that kept no record: the next task to take the address adopts it.
String tgArn = createTargetGroup("reg-tg-preexisting");
elbV2Service.registerTargets(REGION, tgArn, List.of(target("127.0.0.1", 39000)));
EcsTask task = taskWithContainer("web", 8080, 39000);
EcsServiceModel svc = serviceWithLb(tgArn, "web", 8080);
registrar.registerTask(task, svc, REGION);
assertEquals(1, elbV2Service.describeTargetHealth(REGION, tgArn, null).size());
registrar.deregisterTask(task, svc, REGION);
assertTrue(elbV2Service.describeTargetHealth(REGION, tgArn, null).isEmpty(),
"the target at the stopped task's address should be deregistered");
}
@Test
void evictUnrecordedTargetsRemovesAStaleTargetAtTheTasksAddressFromEveryGroup() {
String alphaTg = createTargetGroup("reg-tg-evict-alpha");
String betaTg = createTargetGroup("reg-tg-evict-beta");
elbV2Service.registerTargets(REGION, alphaTg, List.of(target("172.19.0.4", 8080), target("172.19.0.3", 8080)));
elbV2Service.registerTargets(REGION, betaTg, List.of(target("172.19.0.4", 8080)));
EcsTask betaTask = taskWithContainer("web", 8080, 8080);
registrar.evictUnrecordedTargets(betaTask, List.of(alphaTg, betaTg),
List.of(new EcsTaskAddress("172.19.0.4", 8080)), REGION);
List<TargetHealth> alpha = elbV2Service.describeTargetHealth(REGION, alphaTg, null);
assertEquals(1, alpha.size(), "only the target at another address should stay in alpha's group");
assertEquals("172.19.0.3", alpha.get(0).getTarget().getId());
assertTrue(elbV2Service.describeTargetHealth(REGION, betaTg, null).isEmpty(),
"a target at the task's address and port should be evicted");
}
@Test
void evictUnrecordedTargetsKeepsATargetOnAPortTheTaskDoesNotServe() {
String tgArn = createTargetGroup("reg-tg-evict-port");
elbV2Service.registerTargets(REGION, tgArn, List.of(target("172.19.0.5", 8080), target("172.19.0.5", 9000)));
registrar.evictUnrecordedTargets(taskWithContainer("web", 8080, 8080), List.of(tgArn),
List.of(new EcsTaskAddress("172.19.0.5", 8080)), REGION);
List<TargetHealth> health = elbV2Service.describeTargetHealth(REGION, tgArn, null);
assertEquals(1, health.size(), "the target on a port the task does not serve should stay");
assertEquals(9000, health.get(0).getTarget().getPort());
}
@Test
void evictUnrecordedTargetsKeepsATargetALiveTaskRecorded() {
String tgArn = createTargetGroup("reg-tg-evict-recorded");
EcsTask owner = taskWithContainer("web", 8080, 40000);
registrar.registerTask(owner, serviceWithLb(tgArn, "web", 8080), REGION);
EcsTask other = taskWithContainer("web", 8080, 40000);
registrar.evictUnrecordedTargets(other, List.of(tgArn),
List.of(EcsTaskAddress.of("127.0.0.1", 40000)), REGION);
assertEquals(1, elbV2Service.describeTargetHealth(REGION, tgArn, null).size(),
"a target a live task recorded should stay");
registrar.deregisterTask(owner, serviceWithLb(tgArn, "web", 8080), REGION);
}
@Test
void evictUnrecordedTargetsMatchesALoopbackAddressOnlyByItsHostPort() {
String tgArn = createTargetGroup("reg-tg-evict-loopback");
elbV2Service.registerTargets(REGION, tgArn, List.of(target("127.0.0.1", 41000), target("127.0.0.1", 41001)));
registrar.evictUnrecordedTargets(taskWithContainer("web", 8080, 41000), List.of(tgArn),
List.of(EcsTaskAddress.of("127.0.0.1", 41000)), REGION);
List<TargetHealth> health = elbV2Service.describeTargetHealth(REGION, tgArn, null);
assertEquals(1, health.size(), "the loopback target on another host port should stay");
assertEquals(41001, health.get(0).getTarget().getPort());
}
@Test
void evictUnrecordedTargetsToleratesADeletedTargetGroup() {
String tgArn = createTargetGroup("reg-tg-evict-gone");
elbV2Service.deleteTargetGroup(REGION, tgArn);
registrar.evictUnrecordedTargets(taskWithContainer("web", 8080, 42000), List.of(tgArn),
List.of(new EcsTaskAddress("172.19.0.9", 8080)), REGION);
}
/** Stands in for the process dying between the registration and anything after it. */
private static final class ProcessKilled extends Error {
}
private static TargetDescription target(String id, int port) {
TargetDescription td = new TargetDescription();
td.setId(id);
td.setPort(port);
return td;
}
}
@@ -7,8 +7,10 @@ import io.github.hectorvent.floci.services.cloudmap.model.Service;
import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.EcsTaskAddress;
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
@@ -17,7 +19,11 @@ import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
/**
* Component test for {@link EcsServiceDiscoveryRegistrar}: drives register/deregister directly
@@ -33,7 +39,7 @@ class EcsServiceDiscoveryRegistrarTest {
@Inject
EcsServiceDiscoveryRegistrar registrar;
@Inject
@InjectSpy
CloudMapService cloudMapService;
@Test
@@ -139,6 +145,105 @@ class EcsServiceDiscoveryRegistrarTest {
assertTrue(!registrar.hasRegistries(svc));
}
@Test
void releaseRecordedInstancesKeepsInstancesRegisteredByHand() {
String namespace = uniqueName("svcdisc") + ".internal";
Service cloudMapSvc = createDnsService(namespace, "web");
EcsServiceModel web = serviceWithRegistry(cloudMapSvc.getArn(), "web", 8080);
web.setServiceName("web-svc");
registrar.registerTask(taskInCluster("172.31.0.11", "payments"), web, REGION);
registrar.registerTask(taskInCluster("172.31.0.12", "payments"), web, REGION);
cloudMapService.registerInstance(cloudMapSvc.getId(), "registered-by-hand", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.15",
"ECS_SERVICE_NAME", "web-svc", "ECS_CLUSTER_NAME", "payments"), REGION);
registrar.releaseRecordedInstances();
List<String> remaining = cloudMapService.listInstances(cloudMapSvc.getId()).stream()
.map(Instance::getInstanceId)
.toList();
assertEquals(List.of("registered-by-hand"), remaining);
}
@Test
void releaseRecordedInstancesReleasesAnInstanceWhoseRegistrationWasCutShort() {
String namespace = uniqueName("svcdisc") + ".internal";
Service cloudMapSvc = createDnsService(namespace, "killed");
doAnswer(invocation -> {
invocation.callRealMethod();
throw new ProcessKilled();
}).when(cloudMapService).registerInstance(eq(cloudMapSvc.getId()), any(), any(), any(), any());
assertThrows(ProcessKilled.class, () -> registrar.registerTask(task("172.31.0.13", "killed", 8080, 8080),
serviceWithRegistry(cloudMapSvc.getArn(), "killed", 8080), REGION));
registrar.releaseRecordedInstances();
assertTrue(cloudMapService.listInstances(cloudMapSvc.getId()).isEmpty(),
"an instance registered just before the process died should be released");
}
@Test
void evictUnrecordedInstancesRemovesAStaleInstanceAtTheTasksAddress() {
String namespace = uniqueName("svcdisc") + ".internal";
Service auth = createDnsService(namespace, "auth");
Service document = cloudMapService.createService("document", auth.getNamespaceId(),
null, null, null, null, null, null, Map.of(), REGION);
// Left by an auth task of a run that kept no record; the address now belongs to a document task.
cloudMapService.registerInstance(auth.getId(), "bdf778f0", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.21"), REGION);
cloudMapService.registerInstance(auth.getId(), "elsewhere", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.17"), REGION);
EcsTask documentTask = task("172.31.0.21", "document", 8080, 8080);
registrar.registerTask(documentTask, serviceWithRegistry(document.getArn(), "document", 8080), REGION);
registrar.evictUnrecordedInstances(documentTask, List.of(auth.getId(), document.getId()),
List.of(new EcsTaskAddress("172.31.0.21", null)), REGION);
assertEquals(List.of("elsewhere"), cloudMapService.listInstances(auth.getId()).stream()
.map(Instance::getInstanceId).toList());
assertEquals(1, cloudMapService.listInstances(document.getId()).size(),
"the task's own recorded instance should stay");
assertEquals(List.of("172.31.0.17"), cloudMapService.resolveDnsName("auth." + namespace));
}
@Test
void evictUnrecordedInstancesMatchesALoopbackAddressOnlyByItsPort() {
String namespace = uniqueName("svcdisc") + ".internal";
Service cloudMapSvc = createDnsService(namespace, "api");
cloudMapService.registerInstance(cloudMapSvc.getId(), "stale", null,
Map.of("AWS_INSTANCE_IPV4", "127.0.0.1", "AWS_INSTANCE_PORT", "32768"), REGION);
cloudMapService.registerInstance(cloudMapSvc.getId(), "other-port", null,
Map.of("AWS_INSTANCE_IPV4", "127.0.0.1", "AWS_INSTANCE_PORT", "32769"), REGION);
registrar.evictUnrecordedInstances(task(null, "api", 8080, 32768), List.of(cloudMapSvc.getId()),
List.of(EcsTaskAddress.of("127.0.0.1", 32768)), REGION);
assertEquals(List.of("other-port"), cloudMapService.listInstances(cloudMapSvc.getId()).stream()
.map(Instance::getInstanceId).toList());
}
@Test
void evictUnrecordedInstancesMatchesAnEniAddressOnlyInItsOwnVpc() {
String namespace = uniqueName("svcdisc") + ".internal";
Service cloudMapSvc = createDnsService(namespace, "api");
cloudMapService.registerInstance(cloudMapSvc.getId(), "by-hand", null,
Map.of("AWS_INSTANCE_IPV4", "10.0.1.5"), REGION);
registrar.evictUnrecordedInstances(task("10.0.1.5", "api", 8080, 8080), List.of(cloudMapSvc.getId()),
List.of(new EcsTaskAddress("10.0.1.5", null, "vpc-elsewhere")), REGION);
assertEquals(List.of("by-hand"), cloudMapService.listInstances(cloudMapSvc.getId()).stream()
.map(Instance::getInstanceId).toList(), "an instance in another VPC's namespace should stay");
registrar.evictUnrecordedInstances(task("10.0.1.5", "api", 8080, 8080), List.of(cloudMapSvc.getId()),
List.of(new EcsTaskAddress("10.0.1.5", null, "vpc-svcdisc")), REGION);
assertTrue(cloudMapService.listInstances(cloudMapSvc.getId()).isEmpty(),
"an instance at the task's ENI address in its own VPC should be evicted");
}
/** Stands in for the process dying between the registration and anything after it. */
private static final class ProcessKilled extends Error {
}
private Service createDnsService(String namespaceName, String serviceName) {
Operation operation = cloudMapService.createPrivateDnsNamespace(
namespaceName, "vpc-svcdisc", null, null, Map.of(), REGION);
@@ -168,6 +273,12 @@ class EcsServiceDiscoveryRegistrarTest {
return task;
}
private EcsTask taskInCluster(String privateIpAddress, String clusterName) {
EcsTask task = task(privateIpAddress, "web", 8080, 8080);
task.setClusterArn("arn:aws:ecs:" + REGION + ":000000000000:cluster/" + clusterName);
return task;
}
private static String uniqueName(String prefix) {
return prefix + UUID.randomUUID().toString().substring(0, 8);
}
@@ -0,0 +1,248 @@
package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;
import io.github.hectorvent.floci.services.ecs.exec.EcsExecSessionRegistry;
import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.EcsTaskAddress;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A restarted Floci knows no task, since task state is memory-only, so what the previous run's
* tasks left behind has to go before the scheduler starts their replacements: containers a run
* without a graceful shutdown left serving, and the load balancer targets and Cloud Map instances
* that even a graceful one leaves registered.
*/
class EcsServiceRestartLeftoversTest {
private static final String REGION = "us-east-1";
private static final String TARGET_GROUP_ARN =
"arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/0123456789abcdef";
@Test
void releasesTheRegistrationsThePreviousRunRecorded() {
EcsLoadBalancerRegistrar lbRegistrar = mock(EcsLoadBalancerRegistrar.class);
EcsServiceDiscoveryRegistrar discoveryRegistrar = mock(EcsServiceDiscoveryRegistrar.class);
service(new SharedStorageFactory(), true, mock(EcsContainerManager.class),
lbRegistrar, discoveryRegistrar).releasePreviousRunLeftovers();
verify(lbRegistrar).releaseRecordedTargets();
verify(discoveryRegistrar).releaseRecordedInstances();
}
@Test
void theSchedulerWaitsUntilThePreviousRunsContainersAreRemoved() {
SharedStorageFactory storage = new SharedStorageFactory();
persistServiceWithLoadBalancer(storage);
EcsContainerManager containerManager = mock(EcsContainerManager.class);
when(containerManager.removeLeftoverContainers()).thenReturn(false, false, true);
EcsService restarted = service(storage, false, containerManager,
mock(EcsLoadBalancerRegistrar.class), null);
restarted.releasePreviousRunLeftovers();
restarted.reconcile();
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
restarted.reconcile();
restarted.reconcile();
verify(containerManager, times(3)).removeLeftoverContainers();
}
@Test
void theSweepIsNotRetriedWhileNoServiceNeedsATask() {
EcsContainerManager containerManager = mock(EcsContainerManager.class);
when(containerManager.removeLeftoverContainers()).thenReturn(false);
EcsService restarted = service(new SharedStorageFactory(), false, containerManager,
mock(EcsLoadBalancerRegistrar.class), null);
restarted.releasePreviousRunLeftovers();
restarted.reconcile();
restarted.reconcile();
verify(containerManager).removeLeftoverContainers();
}
@Test
void runTaskRetriesTheSweepAndStartsNothingBesideAPreviousRunsContainers() {
EcsContainerManager containerManager = mock(EcsContainerManager.class);
when(containerManager.removeLeftoverContainers()).thenReturn(false, false, true);
EcsService restarted = service(new SharedStorageFactory(), false, containerManager,
mock(EcsLoadBalancerRegistrar.class), null);
restarted.createCluster("app-cluster", Map.of(), REGION);
ContainerDefinition container = new ContainerDefinition();
container.setName("web");
container.setImage("nginx:alpine");
restarted.registerTaskDefinition("web", List.of(container), NetworkMode.bridge, null, null,
null, null, List.of(), REGION);
restarted.releasePreviousRunLeftovers();
EcsTask blocked = restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null,
null, null, REGION).getFirst();
assertEquals("STOPPED", blocked.getLastStatus());
assertThat(blocked.getStoppedReason(), containsString("previous run"));
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION);
verify(containerManager, times(3)).removeLeftoverContainers();
verify(containerManager).startTask(any(), any(), any(), anyString());
}
@Test
void dockerModeRemovesTheContainersAPreviousRunLeft() {
EcsContainerManager containerManager = mock(EcsContainerManager.class);
service(new SharedStorageFactory(), false, containerManager,
mock(EcsLoadBalancerRegistrar.class), null).releasePreviousRunLeftovers();
verify(containerManager).removeLeftoverContainers();
}
@Test
void mockModeHasNoContainersToRemove() {
EcsContainerManager containerManager = mock(EcsContainerManager.class);
service(new SharedStorageFactory(), true, containerManager,
mock(EcsLoadBalancerRegistrar.class), null).releasePreviousRunLeftovers();
verify(containerManager, never()).removeLeftoverContainers();
}
@Test
void startupReleasesLeftoversBeforeTheSchedulerRuns() {
EcsContainerManager containerManager = mock(EcsContainerManager.class);
EcsService service = service(new SharedStorageFactory(), false, containerManager,
mock(EcsLoadBalancerRegistrar.class), null);
service.init();
try {
verify(containerManager).removeLeftoverContainers();
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
} finally {
service.stopManagedContainers();
}
}
@Test
void aStartingTaskEvictsTheUnrecordedRegistrationsAtItsAddress() {
EcsContainerManager containerManager = mock(EcsContainerManager.class);
when(containerManager.removeLeftoverContainers()).thenReturn(true);
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
Container container = new Container();
container.setName("web");
container.setNetworkBindings(List.of(new NetworkBinding("0.0.0.0", 80, 80, "tcp")));
task.setContainers(List.of(container));
task.setPrivateIpAddress("10.0.1.5");
return new EcsTaskHandle(task.getTaskArn(), Map.of("web", "docker-id"), Map.of());
});
when(containerManager.resolveContainerHost(any())).thenReturn("172.19.0.4");
when(containerManager.taskVpcId(any(), anyString())).thenReturn("vpc-app");
EcsLoadBalancerRegistrar lbRegistrar = mock(EcsLoadBalancerRegistrar.class);
EcsServiceDiscoveryRegistrar discoveryRegistrar = mock(EcsServiceDiscoveryRegistrar.class);
when(discoveryRegistrar.cloudMapServiceIds(any())).thenReturn(List.of("srv-alpha"));
EcsService ecs = service(new SharedStorageFactory(), false, containerManager, lbRegistrar,
discoveryRegistrar);
ecs.releasePreviousRunLeftovers();
ecs.createCluster("app-cluster", Map.of(), REGION);
ContainerDefinition definition = new ContainerDefinition();
definition.setName("web");
definition.setImage("nginx:alpine");
ecs.registerTaskDefinition("web", List.of(definition), NetworkMode.bridge, null, null,
null, null, List.of(), REGION);
EcsLoadBalancer lb = new EcsLoadBalancer();
lb.setTargetGroupArn(TARGET_GROUP_ARN);
lb.setContainerName("web");
lb.setContainerPort(80);
ecs.createService("app-cluster", "alpha", "web", 0, LaunchType.EC2, List.of(lb), null, REGION);
// A task of no service at all: any container can take the address a stale entry points at.
EcsTask task = ecs.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION)
.getFirst();
assertEquals("RUNNING", task.getLastStatus());
// A target only on the ports the container serves, and never at the VPC-scoped ENI address.
verify(lbRegistrar).evictUnrecordedTargets(task, Set.of(TARGET_GROUP_ARN),
Set.of(new EcsTaskAddress("172.19.0.4", 80)), REGION);
verify(discoveryRegistrar).evictUnrecordedInstances(task, Set.of("srv-alpha"),
Set.of(new EcsTaskAddress("10.0.1.5", null, "vpc-app"), new EcsTaskAddress("172.19.0.4", null)),
REGION);
}
private static void persistServiceWithLoadBalancer(StorageFactory storage) {
EcsService first = service(storage, true, mock(EcsContainerManager.class),
mock(EcsLoadBalancerRegistrar.class), null);
first.createCluster("app-cluster", Map.of(), REGION);
ContainerDefinition container = new ContainerDefinition();
container.setName("web");
container.setImage("nginx:alpine");
first.registerTaskDefinition("web", List.of(container), NetworkMode.bridge, null, null,
null, null, List.of(), REGION);
EcsLoadBalancer lb = new EcsLoadBalancer();
lb.setTargetGroupArn(TARGET_GROUP_ARN);
lb.setContainerName("web");
lb.setContainerPort(80);
first.createService("app-cluster", "web-svc", "web", 1, LaunchType.EC2, List.of(lb), null, REGION);
}
private static EcsService service(StorageFactory storage, boolean mockMode,
EcsContainerManager containerManager,
EcsLoadBalancerRegistrar lbRegistrar,
EcsServiceDiscoveryRegistrar discoveryRegistrar) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(mockMode);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), containerManager,
config, lbRegistrar, storage, null, new EcsExecSessionRegistry(), discoveryRegistrar);
service.initializeStorage();
return service;
}
private static final class SharedStorageFactory extends StorageFactory {
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
private SharedStorageFactory() {
super(null, null);
}
@Override
@SuppressWarnings("unchecked")
public <V> AccountAwareStorageBackend<V> create(String serviceName,
String fileName,
TypeReference<Map<String, V>> typeReference) {
return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,
ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
}
}
}
@@ -98,7 +98,7 @@ class EcsContainerManagerSecurityGroupTest {
void awsvpcTaskWithFirewallJoinsHelperNamespaceAndSkipsHostPorts() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
@@ -149,7 +149,7 @@ class EcsContainerManagerSecurityGroupTest {
void stopTaskUnregistersEniAndReleasingTheTaskNetworkDeletesIt() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
@@ -185,7 +185,7 @@ class EcsContainerManagerSecurityGroupTest {
void firelensRouterAndAppBothJoinTheHelperNamespace() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
@@ -233,7 +233,7 @@ class EcsContainerManagerSecurityGroupTest {
verify(builder, times(2)).withNetworkMode("container:helper-id");
verify(builder, times(2)).withLabels(Map.of("floci.security-group-workload", "true"));
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any());
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any());
verify(lifecycleManager).create(any());
verify(lifecycleManager).startCreated(eq("router-id"), any());
verify(lifecycleManager).createAndStart(any());