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

+7
View File
@@ -541,6 +541,13 @@ Known differences from AWS:
and rolls the running tasks: a replacement on the new deployment normally starts first, then
the task from the previous deployment is drained one reconciler tick later. The
`deployments` list still reports a single `PRIMARY` throughout.
- A rolling deployment of a service with `loadBalancers` stops a stale task only once every
replacement's targets report `healthy`. A replacement that never turns healthy holds the
deployment.
- A stale or scaled-in task of a service with `loadBalancers` stays `DEACTIVATING`, its
containers still running, for the longest `deregistration_delay.timeout_seconds` of its target
groups (300 seconds by default), then turns `STOPPING` on the next reconciler tick. A `StopTask`
call does not wait. The target leaves its target group at once rather than reporting `draining`.
- `updatedAt` starts at `createdAt` and advances when the deployment status changes.
- `deploymentConfiguration` is stored and reported as given. The deployment circuit breaker
counts tasks that fail to start and moves a deployment through `STOP_REQUESTED` to `STOPPED`,
@@ -19,8 +19,10 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -88,11 +90,8 @@ public class EcsLoadBalancerRegistrar {
if (taskArn == null || registered.size() == planned.size()) {
return;
}
if (registered.isEmpty()) {
ledger.delete(taskArn);
} else {
ledger.put(taskArn, new EcsRegisteredTargets(region, List.copyOf(registered)));
}
// An empty record, rather than none, tells targetsHealthy the task has targets that never registered.
ledger.put(taskArn, new EcsRegisteredTargets(region, List.copyOf(registered)));
}
/**
@@ -100,17 +99,53 @@ public class EcsLoadBalancerRegistrar {
* with no record registered nothing, as when none of its containers had a reachable binding.
* Only a task without an ARN, which {@link #registerTask} cannot record, falls back to the
* targets its containers resolve to now.
*
* @return how long the deregistered targets drain: the longest
* {@code deregistration_delay.timeout_seconds} of their target groups, during which
* AWS keeps the task running for the requests already in flight
*/
public void deregisterTask(EcsTask task, EcsServiceModel svc, String region) {
public Duration deregisterTask(EcsTask task, EcsServiceModel svc, String region) {
List<Duration> drains = new ArrayList<>();
if (task.getTaskArn() == null) {
forEachTarget(task, svc, (tgArn, td) -> deregister(region, tgArn, td));
return;
forEachTarget(task, svc, (tgArn, td) -> drains.add(deregister(region, tgArn, td)));
} else {
Optional<EcsRegisteredTargets> recorded = ledger.get(task.getTaskArn());
if (recorded.isPresent()) {
drains.addAll(deregister(recorded.get()));
ledger.delete(task.getTaskArn());
}
}
Optional<EcsRegisteredTargets> recorded = ledger.get(task.getTaskArn());
if (recorded.isPresent()) {
deregister(recorded.get());
ledger.delete(task.getTaskArn());
return drains.stream().max(Comparator.naturalOrder()).orElse(Duration.ZERO);
}
/**
* Whether every target {@link #registerTask} recorded for the task reports {@code healthy}. A
* task with no load-balanced container has nothing to wait for; one whose targets failed to
* register, or whose health cannot be read, is not healthy yet.
*/
public boolean targetsHealthy(EcsTask task) {
Optional<EcsRegisteredTargets> recorded = task.getTaskArn() == null
? Optional.empty() : ledger.get(task.getTaskArn());
if (recorded.isEmpty()) {
return true;
}
List<EcsRegisteredTargets.Target> targets = recorded.get().targets();
if (targets == null || targets.isEmpty()) {
return false;
}
for (EcsRegisteredTargets.Target target : targets) {
try {
List<TargetHealth> health = elbV2Service.describeTargetHealth(recorded.get().region(),
target.targetGroupArn(), List.of(target.toDescription()));
if (health.isEmpty() || health.stream().anyMatch(th -> !"healthy".equals(th.getState()))) {
return false;
}
} catch (Exception e) {
LOG.warnv("Could not read the health of {0}: {1}", target.targetGroupArn(), e.getMessage());
return false;
}
}
return true;
}
/**
@@ -175,22 +210,36 @@ public class EcsLoadBalancerRegistrar {
}
}
private void deregister(EcsRegisteredTargets recorded) {
private List<Duration> deregister(EcsRegisteredTargets recorded) {
List<Duration> drains = new ArrayList<>();
if (recorded.targets() == null) {
return;
return drains;
}
for (EcsRegisteredTargets.Target target : recorded.targets()) {
deregister(recorded.region(), target.targetGroupArn(), target.toDescription());
drains.add(deregister(recorded.region(), target.targetGroupArn(), target.toDescription()));
}
return drains;
}
private void deregister(String region, String tgArn, TargetDescription td) {
/** @return the target group's deregistration delay, or zero when the target could not be deregistered */
private Duration deregister(String region, String tgArn, TargetDescription td) {
try {
elbV2Service.deregisterTargets(region, tgArn, List.of(td));
LOG.infov("Deregistered ECS task target {0}:{1} from target group {2}",
td.getId(), td.getPort(), tgArn);
} catch (Exception e) {
LOG.warnv("Could not deregister ECS target from {0}: {1}", tgArn, e.getMessage());
return Duration.ZERO;
}
String delay = null;
try {
delay = elbV2Service.describeTargetGroupAttributes(region, tgArn)
.get("deregistration_delay.timeout_seconds");
return delay == null ? Duration.ZERO : Duration.ofSeconds(Long.parseLong(delay));
} catch (Exception e) {
LOG.warnv("Not draining target group {0}: could not read its deregistration delay {1}: {2}",
tgArn, delay, e.getMessage());
return Duration.ZERO;
}
}
@@ -290,7 +290,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
execSessions, discoveryRegistrar, cloudWatchMetricsService, Clock.systemUTC());
}
/** With the clock for Container Insights samples and task protection deadlines. */
/** With the clock for Container Insights samples, task protection deadlines and target drains. */
EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,
EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar,
StorageFactory storageFactory, EcsEventPublisher eventPublisher,
@@ -2255,15 +2255,29 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
task.bumpVersion();
return task;
}
if (!TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
boolean deactivating = TaskStatus.DEACTIVATING.name().equals(task.getLastStatus());
if (!deactivating && !TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
task.setDesiredStatus(TaskStatus.STOPPED.name());
task.setLastStatus(TaskStatus.STOPPING.name());
task.setStoppingAt(Instant.now());
task.setStoppedReason(reason != null ? reason : "Stopped by user");
task.setStopCode(stopCode);
task.bumpVersion();
deregisterTaskFromLoadBalancers(task, region);
Duration drain = deregisterTaskFromLoadBalancers(task, region);
deregisterTaskFromServiceDiscovery(task, region);
if (inBackground && !drain.isZero()) {
// As on AWS, the task stays DEACTIVATING, serving its in-flight requests, until its
// targets have drained; the first reconciliation tick after that stops it.
task.setLastStatus(TaskStatus.DEACTIVATING.name());
task.setTargetsDrainedAt(clock.instant().plus(drain));
task.bumpVersion();
return task;
}
} else if (deactivating && inBackground && task.getTargetsDrainedAt() != null
&& clock.instant().isBefore(task.getTargetsDrainedAt())) {
return task; // StopTask does not wait for the drain
}
if (!TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
task.setLastStatus(TaskStatus.STOPPING.name());
task.setStoppingAt(Instant.now());
task.bumpVersion();
}
if (!dockerMode) {
@@ -2537,21 +2551,26 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
.orElse(null);
}
/** Deregisters a stopping task's containers from any ELBv2 target groups its service declared. */
private void deregisterTaskFromLoadBalancers(EcsTask task, String region) {
/**
* Deregisters a stopping task's containers from any ELBv2 target groups its service declared.
*
* @return how long those targets drain, as {@link EcsLoadBalancerRegistrar#deregisterTask} reports
*/
private Duration deregisterTaskFromLoadBalancers(EcsTask task, String region) {
// Gated on dockerMode for symmetry with the register hook (inside launchTasks'
// dockerMode branch): mock-mode tasks have no containers and never registered.
if (!dockerMode || task.getOwningServiceArn() == null) {
return;
return Duration.ZERO;
}
EcsCluster cluster = resolveClusterByArn(task.getClusterArn());
if (cluster == null) {
return;
return Duration.ZERO;
}
EcsServiceModel svc = owningService(task, cluster);
if (svc != null && !svc.getLoadBalancers().isEmpty()) {
lbRegistrar.deregisterTask(task, svc, region);
return lbRegistrar.deregisterTask(task, svc, region);
}
return Duration.ZERO;
}
/** Deregisters a stopping task from the Cloud Map services it actually joined. */
@@ -2884,6 +2903,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
}
/**
* Whether a task's load balancer targets pass their health checks, as ECS waits for before it
* stops the task a rolling deployment replaces. As on AWS, a replacement that never turns
* healthy holds the deployment.
*/
private boolean loadBalancerTargetsHealthy(EcsTask task, EcsServiceModel svc) {
if (!dockerMode || lbRegistrar == null || svc.getLoadBalancers().isEmpty()) {
return true;
}
return lbRegistrar.targetsHealthy(task);
}
private boolean eligibleForServiceStop(EcsTask task) {
return !isProtectedTask(task);
}
@@ -5370,7 +5401,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
private void reconcileTaskLocked(String taskArn, EcsTask task) {
if (TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
if (TaskStatus.STOPPING.name().equals(task.getLastStatus())
|| TaskStatus.DEACTIVATING.name().equals(task.getLastStatus())) {
// Never stopTask(...), which waits for a stop already running: that stop lands under
// this task's monitor, held here.
stopTaskLocked(task, task.getStoppedReason(), task.getStopCode(), taskRegion(task), true);
@@ -5950,11 +5982,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
}
} else if (running > svc.getDesiredCount()) {
// Drain stale tasks first: once their replacements are RUNNING this is the second
// half of the rolling deployment. Protected stale tasks cannot displace the
// desired number of current-revision tasks.
// Drain stale tasks first: once their replacements are RUNNING, and healthy behind
// the service's load balancers, this is the second half of the rolling deployment.
// Protected stale tasks cannot displace the desired number of current-revision tasks.
int currentToStop = Math.max(0, (int) current - svc.getDesiredCount());
Stream.concat(staleTasks.stream().filter(this::eligibleForServiceStop),
boolean replacementsHealthy = runningTasks.stream()
.filter(t -> !staleTasks.contains(t))
.allMatch(t -> loadBalancerTargetsHealthy(t, svc));
Stream.concat(staleTasks.stream()
.filter(t -> replacementsHealthy)
.filter(this::eligibleForServiceStop),
runningTasks.stream()
.filter(t -> !staleTasks.contains(t))
.filter(this::eligibleForServiceStop)
@@ -61,6 +61,11 @@ public class EcsTask {
private Instant pullStoppedAt;
private Instant executionStoppedAt;
private Instant stoppingAt;
/**
* When the load balancer targets of this DEACTIVATING task finish draining, the earliest the
* service scheduler stops its containers. Internal: never serialized.
*/
private Instant targetsDrainedAt;
private EphemeralStorage ephemeralStorage;
private boolean enableExecuteCommand;
private TaskOverride overrides;
@@ -118,6 +123,7 @@ public class EcsTask {
this.pullStoppedAt = other.pullStoppedAt;
this.executionStoppedAt = other.executionStoppedAt;
this.stoppingAt = other.stoppingAt;
this.targetsDrainedAt = other.targetsDrainedAt;
this.ephemeralStorage = other.ephemeralStorage;
this.enableExecuteCommand = other.enableExecuteCommand;
this.overrides = other.overrides;
@@ -257,6 +263,9 @@ public class EcsTask {
public Instant getStoppingAt() { return stoppingAt; }
public void setStoppingAt(Instant stoppingAt) { this.stoppingAt = stoppingAt; }
public Instant getTargetsDrainedAt() { return targetsDrainedAt; }
public void setTargetsDrainedAt(Instant targetsDrainedAt) { this.targetsDrainedAt = targetsDrainedAt; }
public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; }
public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { this.ephemeralStorage = ephemeralStorage; }
@@ -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