fix(ecs): respect task scale-in protection (#6906)

* fix(ecs): respect task scale-in protection

* fix(ecs): count protected daemon tasks

* fix(ecs): use injected clock for task protection expiry
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-29 14:42:22 -04:00
1 parent e37a415f24
commit 606ed3cf8b
2 files changed
+281 -26

No files matched your search

@@ -259,7 +259,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
execSessions, discoveryRegistrar, cloudWatchMetricsService, Clock.systemUTC());
}
/** With the clock that dates Container Insights samples, which a test pins. */
/** With the clock for Container Insights samples and task protection deadlines. */
EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,
EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar,
StorageFactory storageFactory, EcsEventPublisher eventPublisher,
@@ -1984,6 +1984,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
}
private void stopServiceTaskIfUnprotected(EcsTask task, String reason, String region) {
synchronized (task) {
if (!isTaskProtected(task, clock.instant())) {
stopTaskLocked(task, reason, STOP_CODE_SERVICE_SCHEDULER_INITIATED, region);
}
}
}
private EcsTask stopTaskLocked(EcsTask task, String reason, String stopCode, String region) {
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
return task;
@@ -2499,15 +2507,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
List<ProtectedTask> result = new ArrayList<>();
for (String ref : taskRefs) {
EcsTask task = resolveTaskOrThrow(ref, region);
task.setProtectionEnabled(protectionEnabled);
Instant expiration = null;
if (protectionEnabled && expiresInMinutes != null) {
expiration = Instant.now().plusSeconds(expiresInMinutes * 60L);
synchronized (task) {
task.setProtectionEnabled(protectionEnabled);
Instant expiration = protectionEnabled
? clock.instant().plusSeconds((expiresInMinutes == null ? 120L : expiresInMinutes) * 60L)
: null;
task.setProtectedUntil(expiration);
} else {
task.setProtectedUntil(null);
result.add(new ProtectedTask(task.getTaskArn(), protectionEnabled, expiration));
}
result.add(new ProtectedTask(task.getTaskArn(), protectionEnabled, expiration));
}
return result;
}
@@ -2516,11 +2523,38 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
List<ProtectedTask> result = new ArrayList<>();
for (String ref : taskRefs) {
EcsTask task = resolveTaskOrThrow(ref, region);
result.add(new ProtectedTask(task.getTaskArn(), task.isProtectionEnabled(), task.getProtectedUntil()));
synchronized (task) {
result.add(new ProtectedTask(task.getTaskArn(), isTaskProtected(task, clock.instant()),
task.getProtectedUntil()));
}
}
return result;
}
private static boolean isTaskProtected(EcsTask task, Instant now) {
if (!task.isProtectionEnabled()) {
return false;
}
Instant until = task.getProtectedUntil();
if (until == null || now.isBefore(until)) {
return true;
}
task.setProtectionEnabled(false);
task.setProtectedUntil(null);
task.bumpVersion();
return false;
}
private boolean isProtectedTask(EcsTask task) {
synchronized (task) {
return isTaskProtected(task, clock.instant());
}
}
private boolean eligibleForServiceStop(EcsTask task) {
return !isProtectedTask(task);
}
// ── Services ──────────────────────────────────────────────────────────────
public EcsServiceModel createService(String clusterRef, String serviceName, String taskDefinition,
@@ -4153,7 +4187,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// This deployment's own tasks: counting the ones still draining from the previous
// deployment would report a task-definition change COMPLETED as soon as it was made.
long running = runningOnCurrentDeployment(svc);
boolean converged = running >= svc.getDesiredCount();
boolean converged = running >= svc.getDesiredCount() && !hasProtectedStaleTask(svc);
boolean rollbackPending = latestServiceDeployment(svc.getServiceArn(), candidate ->
DEPLOYMENT_STATUS_ROLLBACK_IN_PROGRESS.equals(candidate.getStatus())) != null;
ServiceDeployment record = lockedCopyOf(deploymentRecordOf(svc));
@@ -4227,7 +4261,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
*/
public List<ServiceEvent> eventsFor(EcsServiceModel svc) {
if (svc == null || !"ACTIVE".equals(svc.getStatus())
|| runningOnCurrentDeployment(svc) < svc.getDesiredCount()) {
|| runningOnCurrentDeployment(svc) < svc.getDesiredCount()
|| hasProtectedStaleTask(svc)) {
return List.of();
}
String deploymentId = deploymentId(svc);
@@ -4283,6 +4318,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
.count();
}
private boolean hasProtectedStaleTask(EcsServiceModel svc) {
EcsCluster cluster = resolveClusterByArn(svc.getClusterArn());
if (cluster == null) {
return false;
}
String currentDeploymentId = deploymentId(svc);
String taskDefinitionArn = resolvedTaskDefinitionArn(svc, serviceRegion(svc));
return tasks.values().stream()
.filter(t -> ownedBy(t, svc, cluster))
.filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus()))
.filter(t -> isStaleForDeployment(t, currentDeploymentId, taskDefinitionArn))
.anyMatch(this::isProtectedTask);
}
/**
* The bare identifier inside the service's {@code ecs-svc/<id>} deployment id: what AWS
* calls the task set id, and what names the service revision that deployment targets.
@@ -4412,7 +4461,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
&& deployment.getTargetServiceRevisionArn().endsWith("/" + taskSetId(svc))
&& DEPLOYMENT_STATUS_IN_PROGRESS.equals(deployment.getStatus())
&& STATUS_ACTIVE.equals(svc.getStatus())
&& runningOnCurrentDeployment(svc) >= svc.getDesiredCount()) {
&& runningOnCurrentDeployment(svc) >= svc.getDesiredCount()
&& !hasProtectedStaleTask(svc)) {
Instant now = Instant.now();
deployment.setStatus(DEPLOYMENT_STATUS_SUCCESSFUL);
if (deployment.getAlarmNames() != null) {
@@ -5133,9 +5183,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// maximumPercent is 100 for DAEMON: the replacement starts once this is STOPPED.
if (!TaskStatus.STOPPING.name().equals(t.getLastStatus())) {
try {
stopTask(clusterName, t.getTaskArn(),
"Service deployment replaced task definition " + t.getTaskDefinitionArn(),
STOP_CODE_SERVICE_SCHEDULER_INITIATED, region);
stopServiceTaskIfUnprotected(t, "Service deployment replaced task definition "
+ t.getTaskDefinitionArn(), region);
} catch (Exception e) {
LOG.warnv("Service reconciler failed to stop daemon task {0}: {1}",
t.getTaskArn(), e.getMessage());
@@ -5143,6 +5192,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
if (TaskStatus.STOPPED.name().equals(t.getLastStatus())) {
covered.remove(instanceArn);
} else if (TaskStatus.RUNNING.name().equals(t.getLastStatus())) {
running++;
}
continue;
}
@@ -5393,7 +5444,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (eventPublisher != null) {
String deploymentId = currentDeploymentId;
boolean converged = current >= svc.getDesiredCount();
boolean converged = current >= svc.getDesiredCount() && !hasProtectedStaleTask(svc);
ServiceDeployment pendingFailure = latestServiceDeployment(svc.getServiceArn(), candidate ->
DEPLOYMENT_STATUS_ROLLBACK_IN_PROGRESS.equals(candidate.getStatus()));
if (converged && pendingFailure == null) {
@@ -5439,19 +5490,21 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
}
} else if (running > svc.getDesiredCount()) {
int toStop = (int) running - svc.getDesiredCount();
// Drain stale tasks first: once their replacements are RUNNING this is the second
// half of the rolling deployment, not a scale-in.
Stream.concat(staleTasks.stream(),
runningTasks.stream().filter(t -> !staleTasks.contains(t)))
.limit(toStop)
// 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),
runningTasks.stream()
.filter(t -> !staleTasks.contains(t))
.filter(this::eligibleForServiceStop)
.limit(currentToStop))
.forEach(t -> {
boolean stale = staleTasks.contains(t);
try {
stopTask(clusterName, t.getTaskArn(),
stale ? "Service deployment replaced task definition " + t.getTaskDefinitionArn()
: "Service scale-in",
STOP_CODE_SERVICE_SCHEDULER_INITIATED, region);
stopServiceTaskIfUnprotected(t,
stale ? "Service deployment replaced task definition "
+ t.getTaskDefinitionArn() : "Service scale-in", region);
} catch (Exception e) {
LOG.warnv("Service reconciler failed to stop task {0}: {1}",
t.getTaskArn(), e.getMessage());
@@ -7,22 +7,36 @@ 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.exec.EcsExecSessionRegistry;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
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.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.ProtectedTask;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.eq;
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;
/**
@@ -88,6 +102,182 @@ class EcsServiceTaskOwnershipTest {
"scale-in must not reach a task the service never launched");
}
@Test
void scaleInWaitsForProtectedTasksAndContinuesWhenProtectionIsRemoved() {
EcsService service = newMockModeService();
service.createCluster("protected-cluster", REGION);
registerTaskDef(service);
service.createService("protected-cluster", "worker", "own-fam", 2, LaunchType.FARGATE,
List.of(), null, REGION);
service.reconcileServices();
service.reconcileServices();
List<EcsTask> running = ownedTasks(service, "protected-cluster", "worker");
assertEquals(2, running.size());
List<String> arns = running.stream().map(EcsTask::getTaskArn).toList();
service.updateTaskProtection("protected-cluster", arns, true, 60, REGION);
service.updateService("protected-cluster", "worker", null, 0, null, REGION);
service.reconcileServices();
assertEquals(2, ownedTasks(service, "protected-cluster", "worker").size(),
"protected tasks stay running despite the lower desired count");
service.updateTaskProtection("protected-cluster", List.of(arns.getFirst()), false, null, REGION);
service.reconcileServices();
assertEquals("STOPPED", reload(service, running.getFirst()).getLastStatus());
assertEquals("RUNNING", reload(service, running.getLast()).getLastStatus());
service.updateTaskProtection("protected-cluster", List.of(arns.getLast()), false, null, REGION);
service.reconcileServices();
assertEquals(0, ownedTasks(service, "protected-cluster", "worker").size());
}
@Test
void replicaScaleInOnEc2RetainsProtectedTask() {
EcsService service = newMockModeService();
service.createCluster("ec2-protected", REGION);
service.registerContainerInstance("ec2-protected", null, List.of(), REGION);
service.registerContainerInstance("ec2-protected", null, List.of(), REGION);
registerTaskDef(service);
service.createService("ec2-protected", "worker", "own-fam", 2, LaunchType.EC2,
List.of(), null, REGION);
service.reconcileServices();
service.reconcileServices();
List<EcsTask> running = ownedTasks(service, "ec2-protected", "worker");
assertEquals(2, running.size());
EcsTask protectedTask = running.getFirst();
EcsTask otherTask = running.getLast();
service.updateTaskProtection("ec2-protected", List.of(protectedTask.getTaskArn()), true, 60, REGION);
service.updateService("ec2-protected", "worker", null, 1, null, REGION);
service.reconcileServices();
assertEquals("RUNNING", reload(service, protectedTask).getLastStatus());
assertEquals("STOPPED", reload(service, otherTask).getLastStatus());
assertEquals(1, ownedTasks(service, "ec2-protected", "worker").size());
}
@Test
void scaleInSkipsProtectedTaskAndStopsExpiredTaskOnNextTick() {
MutableClock clock = new MutableClock();
EcsService service = newMockModeService(clock);
service.createCluster("mixed-cluster", REGION);
registerTaskDef(service);
service.createService("mixed-cluster", "worker", "own-fam", 2, LaunchType.FARGATE,
List.of(), null, REGION);
service.reconcileServices();
service.reconcileServices();
List<EcsTask> running = ownedTasks(service, "mixed-cluster", "worker");
assertEquals(2, running.size());
EcsTask protectedTask = running.getFirst();
EcsTask unprotectedTask = running.getLast();
service.updateTaskProtection("mixed-cluster", List.of(protectedTask.getTaskArn()), true, 60, REGION);
service.updateService("mixed-cluster", "worker", null, 1, null, REGION);
service.reconcileServices();
assertEquals("RUNNING", reload(service, protectedTask).getLastStatus());
assertEquals("STOPPED", reload(service, unprotectedTask).getLastStatus());
clock.advance(Duration.ofMinutes(61));
service.updateService("mixed-cluster", "worker", null, 0, null, REGION);
service.reconcileServices();
assertEquals("STOPPED", reload(service, protectedTask).getLastStatus());
assertFalse(service.getTaskProtection("mixed-cluster",
List.of(protectedTask.getTaskArn()), REGION).getFirst().protectionEnabled());
}
@Test
void taskProtectionDefaultsToTwoHoursAndExplicitStopStillWorks() {
MutableClock clock = new MutableClock();
EcsService service = newMockModeService(clock);
service.createCluster("default-cluster", REGION);
registerTaskDef(service);
service.createService("default-cluster", "worker", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, REGION);
service.reconcileServices();
EcsTask task = ownedTasks(service, "default-cluster", "worker").getFirst();
clock.reset();
Instant before = clock.instant();
clock.reset();
ProtectedTask protection = service.updateTaskProtection("default-cluster", List.of(task.getTaskArn()),
true, null, REGION).getFirst();
assertTrue(protection.protectionEnabled());
assertEquals(before.plus(Duration.ofMinutes(120)), protection.expirationDate());
assertEquals(protection.expirationDate(), service.getTaskProtection("default-cluster",
List.of(task.getTaskArn()), REGION).getFirst().expirationDate());
service.stopTask("default-cluster", task.getTaskArn(), "requested by user", REGION);
assertEquals("STOPPED", reload(service, task).getLastStatus());
}
@Test
void deploymentWaitsToDrainProtectedOldRevision() {
EcsEventPublisher publisher = mock(EcsEventPublisher.class);
EcsService service = newMockModeService(publisher);
service.createCluster("rollout-cluster", REGION);
registerTaskDef(service);
service.createService("rollout-cluster", "worker", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, REGION);
service.reconcileServices();
EcsTask oldTask = ownedTasks(service, "rollout-cluster", "worker").getFirst();
clearInvocations(publisher);
service.updateTaskProtection("rollout-cluster", List.of(oldTask.getTaskArn()), true, 60, REGION);
registerTaskDef(service);
service.updateService("rollout-cluster", "worker", "own-fam:2", null, null, REGION);
service.reconcileServices();
service.reconcileServices();
assertEquals("RUNNING", reload(service, oldTask).getLastStatus(),
"deployment must leave the protected old revision running");
assertEquals(2, ownedTasks(service, "rollout-cluster", "worker").size());
EcsServiceModel svc = service.describeServices("rollout-cluster", List.of("worker"), REGION).getFirst();
assertEquals("IN_PROGRESS", service.listServiceDeploymentsDetailed("worker", "rollout-cluster",
null, REGION).getFirst().getStatus());
assertEquals("IN_PROGRESS", service.deploymentsFor(svc).getFirst().getRolloutState());
assertTrue(service.eventsFor(svc).isEmpty(), "protected old revision blocks steady state");
verify(publisher, never()).emitDeploymentStateChange(any(), eq("SERVICE_DEPLOYMENT_COMPLETED"),
any(), eq(REGION));
service.updateTaskProtection("rollout-cluster", List.of(oldTask.getTaskArn()), false, null, REGION);
service.reconcileServices();
assertEquals("STOPPED", reload(service, oldTask).getLastStatus());
assertEquals(1, ownedTasks(service, "rollout-cluster", "worker").size());
assertEquals("SUCCESSFUL", service.listServiceDeploymentsDetailed("worker", "rollout-cluster",
null, REGION).getFirst().getStatus());
assertEquals("COMPLETED", service.deploymentsFor(svc).getFirst().getRolloutState());
assertFalse(service.eventsFor(svc).isEmpty());
verify(publisher, times(1)).emitDeploymentStateChange(any(), eq("SERVICE_DEPLOYMENT_COMPLETED"),
any(), eq(REGION));
}
@Test
void daemonDeploymentWaitsForProtectedTask() {
EcsService service = newMockModeService();
service.createCluster("daemon-protected", REGION);
service.registerContainerInstance("daemon-protected", null, List.of(), REGION);
registerTaskDef(service);
service.createService("daemon-protected", "agent", "own-fam", 1, LaunchType.EC2,
List.of(), null, null, "DAEMON", null, null, REGION);
service.reconcileServices();
EcsTask oldTask = ownedTasks(service, "daemon-protected", "agent").getFirst();
service.updateTaskProtection("daemon-protected", List.of(oldTask.getTaskArn()), true, 60, REGION);
registerTaskDef(service);
service.updateService("daemon-protected", "agent", "own-fam:2", null, null, REGION);
service.reconcileServices();
assertEquals("RUNNING", reload(service, oldTask).getLastStatus());
assertEquals(1, ownedTasks(service, "daemon-protected", "agent").size());
assertEquals(1, service.describeServices("daemon-protected", List.of("agent"), REGION)
.getFirst().getRunningCount());
service.updateTaskProtection("daemon-protected", List.of(oldTask.getTaskArn()), false, null, REGION);
service.reconcileServices();
service.reconcileServices();
assertEquals("STOPPED", reload(service, oldTask).getLastStatus());
assertEquals(1, ownedTasks(service, "daemon-protected", "agent").size());
}
@Test
void daemonSchedulingIgnoresASpoofedGroupWhenCoveringInstances() {
EcsService service = newMockModeService();
@@ -240,6 +430,18 @@ class EcsServiceTaskOwnershipTest {
}
private static EcsService newMockModeService() {
return newMockModeService(null, Clock.systemUTC());
}
private static EcsService newMockModeService(EcsEventPublisher publisher) {
return newMockModeService(publisher, Clock.systemUTC());
}
private static EcsService newMockModeService(Clock clock) {
return newMockModeService(null, clock);
}
private static EcsService newMockModeService(EcsEventPublisher publisher, Clock clock) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(true);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
@@ -249,7 +451,7 @@ class EcsServiceTaskOwnershipTest {
config,
mock(EcsLoadBalancerRegistrar.class),
new InMemoryStorageFactory(),
null);
publisher, new EcsExecSessionRegistry(), null, null, clock);
service.initializeStorage();
return service;
}