fix(ecs): roll a load-balanced service healthy-first and drain the old task before stopping it (#8256)

* fix(ecs): keep a load-balanced service task running while its targets drain
* fix(ecs): stop a replaced task only once its replacement's targets are healthy
* fix(ecs): drain a load-balanced task as DEACTIVATING and hold a deployment on unhealthy replacements
This commit is contained in:
Maxence LEFEBVRE authored and GitHub committed 2026-11-14 11:16:52 -04:00
1 parent 16cb752444
commit a56739ca30
6 files changed
+270 -34

No files matched your search

@@ -4,12 +4,15 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ecs.container.EcsContainerManager;
import io.floci.aws.services.ecs.container.EcsTaskHandle;
import io.floci.aws.services.ecs.exec.EcsExecSessionRegistry;
import io.floci.aws.services.ecs.model.Container;
import io.floci.aws.services.ecs.model.ContainerDefinition;
import io.floci.aws.services.ecs.model.EcsLoadBalancer;
import io.floci.aws.services.ecs.model.EcsTask;
import io.floci.aws.services.ecs.model.LaunchType;
import io.floci.aws.services.ecs.model.TaskStatus;
import io.floci.aws.testing.InMemoryStorageFactory;
import io.floci.aws.testing.MutableClock;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -61,6 +64,8 @@ class EcsGracefulStopConcurrencyServiceTest {
private final EcsContainerManager containerManager = mock(EcsContainerManager.class);
private final EcsEventPublisher eventPublisher = mock(EcsEventPublisher.class);
private final EcsLoadBalancerRegistrar lbRegistrar = mock(EcsLoadBalancerRegistrar.class);
private final MutableClock clock = new MutableClock();
private final List<EcsService> services = new ArrayList<>();
/** The task whose stop blocks until {@link #releaseSlowStop}; every other task stops at once. */
private final AtomicReference<String> slowTaskArn = new AtomicReference<>();
@@ -335,6 +340,63 @@ class EcsGracefulStopConcurrencyServiceTest {
assertEquals(2, stops.get());
}
@Test
void aTaskBehindALoadBalancerStaysDeactivatingUntilItsTargetsHaveDrained() throws Exception {
Duration deregistrationDelay = Duration.ofSeconds(300);
when(lbRegistrar.deregisterTask(any(), any(), anyString())).thenReturn(deregistrationDelay);
when(lbRegistrar.targetsHealthy(any())).thenReturn(true);
EcsService service = newService();
createService(service, "drained", 1, List.of(loadBalancer("drained")));
tick(service);
EcsTask old = onlyRunningTask(service, "drained");
service.updateService(CLUSTER, "drained", null, null, null, null, true, REGION);
tick(service);
tick(service);
verify(lbRegistrar).deregisterTask(argThat(task -> old.getTaskArn().equals(task.getTaskArn())), any(),
eq(REGION));
assertEquals("DEACTIVATING", lastStatus(service, old));
clock.advance(deregistrationDelay.minusSeconds(1));
tick(service);
assertEquals("DEACTIVATING", lastStatus(service, old));
verify(containerManager, never()).stopTaskAndCollectExitCodes(handleOf(old));
clock.advance(Duration.ofSeconds(1));
tick(service);
await().atMost(TICK_BUDGET).until(() -> "STOPPED".equals(lastStatus(service, old)));
verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handleOf(old));
}
@Test
void aRollingDeploymentStopsTheOldTaskOnlyOnceItsReplacementsTargetsAreHealthy() throws Exception {
AtomicReference<String> healthyTaskArn = new AtomicReference<>();
when(lbRegistrar.targetsHealthy(any())).thenAnswer(invocation ->
invocation.<EcsTask>getArgument(0).getTaskArn().equals(healthyTaskArn.get()));
EcsService service = newService();
createService(service, "checked", 1, List.of(loadBalancer("checked")));
tick(service);
EcsTask old = onlyRunningTask(service, "checked");
service.updateService(CLUSTER, "checked", null, null, null, null, true, REGION);
tick(service);
EcsTask replacement = runningTasks(service, "checked").stream()
.filter(task -> !task.getTaskArn().equals(old.getTaskArn()))
.findFirst().orElseThrow();
tick(service);
tick(service);
assertEquals("RUNNING", lastStatus(service, old), "the replacement's targets are still in initial health");
verify(lbRegistrar, never()).deregisterTask(argThat(task -> old.getTaskArn().equals(task.getTaskArn())),
any(), anyString());
healthyTaskArn.set(replacement.getTaskArn());
tick(service);
verify(lbRegistrar).deregisterTask(argThat(task -> old.getTaskArn().equals(task.getTaskArn())), any(),
eq(REGION));
await().atMost(TICK_BUDGET).until(() -> "STOPPED".equals(lastStatus(service, old)));
assertEquals("RUNNING", lastStatus(service, replacement));
}
// ── helpers ──────────────────────────────────────────────────────────────
/** One full reconcile tick, on a thread of its own, so a tick stuck behind a stop fails rather than hangs. */
@@ -360,7 +422,8 @@ class EcsGracefulStopConcurrencyServiceTest {
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), containerManager,
config, mock(EcsLoadBalancerRegistrar.class), new InMemoryStorageFactory("000000000000"), eventPublisher);
config, lbRegistrar, new InMemoryStorageFactory("000000000000"), eventPublisher,
new EcsExecSessionRegistry(), null, null, clock);
service.initializeStorage();
service.createCluster(CLUSTER, REGION);
services.add(service);
@@ -368,12 +431,26 @@ class EcsGracefulStopConcurrencyServiceTest {
}
private static void createService(EcsService service, String name, int desiredCount) {
createService(service, name, desiredCount, List.of());
}
private static void createService(EcsService service, String name, int desiredCount,
List<EcsLoadBalancer> loadBalancers) {
ContainerDefinition container = new ContainerDefinition();
container.setName("app");
container.setImage(name + ":1");
service.registerTaskDefinition(name, List.of(container), null, null, null,
null, null, List.of(), REGION);
service.createService(CLUSTER, name, name, desiredCount, LaunchType.FARGATE, List.of(), null, REGION);
service.createService(CLUSTER, name, name, desiredCount, LaunchType.FARGATE, loadBalancers, null, REGION);
}
private static EcsLoadBalancer loadBalancer(String targetGroupName) {
EcsLoadBalancer loadBalancer = new EcsLoadBalancer();
loadBalancer.setTargetGroupArn("arn:aws:elasticloadbalancing:" + REGION
+ ":000000000000:targetgroup/" + targetGroupName + "/0123456789abcdef");
loadBalancer.setContainerName("app");
loadBalancer.setContainerPort(8080);
return loadBalancer;
}
private static EcsTaskHandle handleOf(EcsTask task) {
@@ -16,17 +16,20 @@ import io.quarkus.test.junit.mockito.InjectSpy;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.time.Duration;
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.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;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
/**
* Component test for {@link EcsLoadBalancerRegistrar}: drives the register/deregister
@@ -96,6 +99,60 @@ class EcsLoadBalancerRegistrarTest {
"target should be deregistered");
}
@Test
void deregisterTaskReportsTheLongestDeregistrationDelayOfItsTargetGroups() {
String defaultTg = createTargetGroup("reg-tg-drain-default");
String shortTg = createTargetGroup("reg-tg-drain-short");
elbV2Service.modifyTargetGroupAttributes(REGION, shortTg, Map.of("deregistration_delay.timeout_seconds", "3"));
EcsTask task = taskWithContainer("web", 8080, 34600);
registrar.registerTask(task, serviceWithLb(shortTg, "web", 8080), REGION);
assertEquals(Duration.ofSeconds(3), registrar.deregisterTask(task, serviceWithLb(shortTg, "web", 8080), REGION));
EcsServiceModel both = serviceWithLb(shortTg, "web", 8080);
EcsLoadBalancer second = new EcsLoadBalancer();
second.setTargetGroupArn(defaultTg);
second.setContainerName("web");
second.setContainerPort(8080);
both.setLoadBalancers(List.of(both.getLoadBalancers().getFirst(), second));
registrar.registerTask(task, both, REGION);
assertEquals(Duration.ofSeconds(300), registrar.deregisterTask(task, both, REGION));
assertEquals(Duration.ZERO, registrar.deregisterTask(task, both, REGION), "nothing left to deregister");
}
@Test
void targetsHealthyIsFalseUntilEveryRecordedTargetPassesItsHealthCheck() {
String tgArn = createTargetGroup("reg-tg-health");
EcsTask task = taskWithContainer("web", 8080, 34700);
EcsTask unregistered = taskWithContainer("web", 8080, 34701);
registrar.registerTask(task, serviceWithLb(tgArn, "web", 8080), REGION);
assertTrue(registrar.targetsHealthy(unregistered), "a task that registered nothing has nothing to wait for");
assertFalse(registrar.targetsHealthy(task), "a freshly registered target is still in initial health");
TargetHealth healthy = new TargetHealth();
healthy.setState("healthy");
doReturn(List.of(healthy)).when(elbV2Service).describeTargetHealth(eq(REGION), eq(tgArn), any());
assertTrue(registrar.targetsHealthy(task));
}
@Test
void targetsHealthyIsFalseWhenTheTargetsFailedToRegisterOrTheirHealthCannotBeRead() {
String tgArn = createTargetGroup("reg-tg-health-unknown");
EcsTask failed = taskWithContainer("web", 8080, 34800);
doThrow(new IllegalStateException("registration refused"))
.when(elbV2Service).registerTargets(eq(REGION), eq(tgArn), any());
registrar.registerTask(failed, serviceWithLb(tgArn, "web", 8080), REGION);
assertFalse(registrar.targetsHealthy(failed), "a target that never registered never turns healthy");
String readTg = createTargetGroup("reg-tg-health-unread");
EcsTask unread = taskWithContainer("web", 8080, 34801);
registrar.registerTask(unread, serviceWithLb(readTg, "web", 8080), REGION);
doThrow(new IllegalStateException("health unavailable"))
.when(elbV2Service).describeTargetHealth(eq(REGION), eq(readTg), any());
assertFalse(registrar.targetsHealthy(unread));
}
@Test
void awsvpcInContainerShapedBindingRegistersContainerPort() {
// In-container mode, awsvpc tasks are expose-only: resolveNetworkBindings