Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ecs): roll a DAEMON service's tasks when its task definition changes (#4766)
Allen Sanbornc43269e0adad
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.javaindex c93b119c77..ad43263723 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java@@ -3978,20 +3978,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabif (cluster == null) {return 0;}- Stream<EcsTask> running = tasks.values().stream()- .filter(t -> ownedBy(t, svc, cluster))- .filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus()));-- // reconcileDaemonService does not replace a DAEMON service's tasks when its task- // definition changes, so the stale ones are the only ones there will ever be; counting- // them keeps main's behaviour. Scope this like REPLICA once DAEMON services roll.- if (SCHEDULING_DAEMON.equals(svc.getSchedulingStrategy())) {- return running.count();- }-String currentDeploymentId = deploymentId(svc);String taskDefinitionArn = resolvedTaskDefinitionArn(svc, serviceRegion(svc));- return running+ return tasks.values().stream()+ .filter(t -> ownedBy(t, svc, cluster))+ .filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus())).filter(t -> !isStaleForDeployment(t, currentDeploymentId, taskDefinitionArn)).count();}@@ -4508,14 +4499,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab.map(ContainerInstance::getContainerInstanceArn).collect(Collectors.toSet());+ String currentDeploymentId = deploymentId(svc);+ String currentTaskDefinitionArn = pinnedTaskDefinitionArn(svc, key, region);+// Every task that still occupies its instance: RUNNING, PENDING (Docker start in// flight) and STOPPING (teardown in flight, possibly stranded). Only STOPPED frees the// slot — otherwise a stranded STOPPING task would get a duplicate next to it.- // RUNNING tasks are preferred as the instance's daemon when there are several.+ // RUNNING tasks are preferred as the instance's daemon when there are several, and+ // among those the ones on the current deployment.List<EcsTask> liveTasks = tasks.values().stream().filter(t -> ownedBy(t, svc, cluster)).filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus()))- .sorted(Comparator.comparingInt(t -> daemonTaskRank(t.getLastStatus())))+ .sorted(Comparator.<EcsTask>comparingInt(t -> daemonTaskRank(t.getLastStatus()))+ .thenComparing(t -> isStaleForDeployment(t, currentDeploymentId,+ currentTaskDefinitionArn) ? 1 : 0)).toList();Set<String> covered = new HashSet<>();@@ -4523,6 +4520,23 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettabfor (EcsTask t : liveTasks) {String instanceArn = t.getContainerInstanceArn();boolean keep = instanceArn != null && activeArns.contains(instanceArn) && covered.add(instanceArn);+ if (keep && isStaleForDeployment(t, currentDeploymentId, currentTaskDefinitionArn)) {+ // 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);+ } catch (Exception e) {+ LOG.warnv("Service reconciler failed to stop daemon task {0}: {1}",+ t.getTaskArn(), e.getMessage());+ }+ }+ if (TaskStatus.STOPPED.name().equals(t.getLastStatus())) {+ covered.remove(instanceArn);+ }+ continue;+ }if (keep) {if (TaskStatus.RUNNING.name().equals(t.getLastStatus())) {running++;diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.javaindex cbb7543cd8..2dc5e9d2ff 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java@@ -8,12 +8,17 @@ 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.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.TaskDefinition;import org.junit.jupiter.api.Test;+import java.util.ArrayList;+import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -22,6 +27,8 @@ import java.util.stream.Collectors;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.junit.jupiter.api.Assertions.fail;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.RETURNS_DEEP_STUBS;@@ -127,6 +134,139 @@ class EcsServiceDaemonSchedulingTest {assertEquals(a.getContainerInstanceArn(), running.getFirst().getContainerInstanceArn());}+ @Test+ void taskDefinitionChangeReplacesTheDaemonTaskOnEveryInstance() {+ EcsService service = newMockModeService();+ service.createCluster("daemon-roll", REGION);+ ContainerInstance a = service.registerContainerInstance("daemon-roll", null, List.of(), REGION);+ ContainerInstance b = service.registerContainerInstance("daemon-roll", null, List.of(), REGION);+ registerTaskDef(service);+ service.createService("daemon-roll", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,+ List.of(), null, null, "DAEMON", null, null, REGION);+ service.reconcileServices();+ Set<String> oldTasks = taskArns(runningTasks(service));++ String revision2 = registerTaskDef(service).getTaskDefinitionArn();+ service.updateService("daemon-roll", "daemon-svc", "daemon-fam:2", null, null, REGION);+ service.reconcileServices();++ assertConvergedOn(service, "daemon-roll", revision2, Set.of(a, b));+ List<EcsTask> running = runningTasks(service);+ assertTrue(Collections.disjoint(oldTasks, taskArns(running)), "every old-revision task is replaced");+ for (EcsTask old : service.describeTasks(null, List.copyOf(oldTasks), REGION)) {+ assertEquals("STOPPED", old.getLastStatus());+ assertEquals("ServiceSchedulerInitiated", old.getStopCode());+ }++ // Converged: further ticks leave it alone.+ service.reconcileServices();+ assertEquals(taskArns(running), taskArns(runningTasks(service)));+ }++ @Test+ void forceNewDeploymentReplacesTheDaemonTaskOnEveryInstance() {+ EcsService service = newMockModeService();+ service.createCluster("daemon-force", REGION);+ ContainerInstance a = service.registerContainerInstance("daemon-force", null, List.of(), REGION);+ ContainerInstance b = service.registerContainerInstance("daemon-force", null, List.of(), REGION);+ String revision1 = registerTaskDef(service).getTaskDefinitionArn();+ service.createService("daemon-force", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,+ List.of(), null, null, "DAEMON", null, null, REGION);+ service.reconcileServices();+ Set<String> oldTasks = taskArns(runningTasks(service));++ service.updateService("daemon-force", "daemon-svc", null, null, null, null, true, REGION);+ service.reconcileServices();++ assertConvergedOn(service, "daemon-force", revision1, Set.of(a, b));+ assertTrue(Collections.disjoint(oldTasks, taskArns(runningTasks(service))),+ "a forced deployment replaces tasks even on the same revision");+ }++ @Test+ void unchangedDaemonServiceDoesNotChurnItsTasks() {+ EcsService service = newMockModeService();+ service.createCluster("daemon-steady", REGION);+ service.registerContainerInstance("daemon-steady", null, List.of(), REGION);+ service.registerContainerInstance("daemon-steady", null, List.of(), REGION);+ registerTaskDef(service);+ service.createService("daemon-steady", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,+ List.of(), null, null, "DAEMON", null, null, REGION);+ service.reconcileServices();+ Set<String> first = taskArns(runningTasks(service));++ service.reconcileServices();+ service.reconcileServices();+ service.reconcileServices();++ assertEquals(first, taskArns(allTasks(service)), "no task stopped or started once converged");+ }++ @Test+ void staleDaemonTaskStuckStoppingDelaysItsReplacement() {+ // AWS caps a DAEMON service's maximumPercent at 100: the old task has to be gone before its+ // replacement starts on that instance. A Docker teardown that fails leaves it STOPPING.+ EcsService service = newDockerModeServiceWhoseStopsFail();+ service.createCluster("daemon-slow", REGION);+ ContainerInstance a = service.registerContainerInstance("daemon-slow", null, List.of(), REGION);+ registerTaskDef(service);+ service.createService("daemon-slow", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,+ List.of(), null, null, "DAEMON", null, null, REGION);+ service.reconcileServices();+ EcsTask old = runningTasks(service).getFirst();++ String revision2 = registerTaskDef(service).getTaskDefinitionArn();+ service.updateService("daemon-slow", "daemon-svc", "daemon-fam:2", null, null, REGION);+ service.reconcileServices();++ assertEquals("STOPPING", old.getLastStatus());+ assertEquals(List.of(old.getTaskArn()), List.copyOf(taskArns(allTasks(service))),+ "no replacement next to a daemon task still stopping");++ old.setLastStatus("STOPPED");+ service.reconcileServices();+ assertConvergedOn(service, "daemon-slow", revision2, Set.of(a));+ }++ @Test+ void currentDaemonTaskWinsItsInstanceOverAStaleOneThatWillNotStop() {+ // Map order decides which of two RUNNING tasks is seen first; build until the stale one is.+ for (int attempt = 0; attempt < 50; attempt++) {+ EcsService service = newDockerModeServiceWhoseStopsFail();+ service.createCluster("daemon-pair", REGION);+ ContainerInstance a = service.registerContainerInstance("daemon-pair", null, List.of(), REGION);+ registerTaskDef(service);+ service.createService("daemon-pair", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,+ List.of(), null, null, "DAEMON", null, null, REGION);+ service.reconcileServices();+ EcsTask stale = runningTasks(service).getFirst();++ registerTaskDef(service);+ service.updateService("daemon-pair", "daemon-svc", "daemon-fam:2", null, null, REGION);+ ContainerInstance b = service.registerContainerInstance("daemon-pair", null, List.of(), REGION);+ service.reconcileServices();+ EcsTask current = runningTasks(service).getFirst();+ assertEquals(b.getContainerInstanceArn(), current.getContainerInstanceArn());++ // Both RUNNING on instance a.+ stale.setLastStatus("RUNNING");+ stale.setDesiredStatus("RUNNING");+ current.setContainerInstanceArn(a.getContainerInstanceArn());+ service.updateContainerInstancesState("daemon-pair", List.of(b.getContainerInstanceArn()), "DRAINING", REGION);+ if (!service.listTasks(null, null, null, null, REGION).getFirst().equals(stale.getTaskArn())) {+ continue;+ }++ service.reconcileServices();+ assertEquals("RUNNING", current.getLastStatus(), "the current task keeps the instance");+ assertEquals("STOPPING", stale.getLastStatus());+ assertEquals(1, service.describeServices("daemon-pair", List.of("daemon-svc"), REGION)+ .getFirst().getRunningCount());+ return;+ }+ fail("never built the stale-first ordering");+ }+@Testvoid daemonIsRejectedForFargateAndForNonEcsDeploymentControllers() {EcsService service = newMockModeService();@@ -142,17 +282,62 @@ class EcsServiceDaemonSchedulingTest {assertEquals("InvalidParameterException", external.getErrorCode());}+ /** Exactly one live task per instance, each RUNNING the given revision on the current deployment. */+ private static void assertConvergedOn(EcsService service, String cluster, String taskDefinitionArn,+ Set<ContainerInstance> instances) {+ List<EcsTask> live = allTasks(service).stream()+ .filter(t -> !"STOPPED".equals(t.getLastStatus()))+ .toList();+ assertEquals(instances.stream().map(ContainerInstance::getContainerInstanceArn).collect(Collectors.toSet()),+ live.stream().map(EcsTask::getContainerInstanceArn).collect(Collectors.toSet()));+ assertEquals(instances.size(), live.size(), "one daemon task per instance");+ EcsServiceModel svc = service.describeServices(cluster, List.of("daemon-svc"), REGION).getFirst();+ for (EcsTask t : live) {+ assertEquals("RUNNING", t.getLastStatus());+ assertEquals(taskDefinitionArn, t.getTaskDefinitionArn());+ assertEquals(svc.getDeploymentId(), t.getDeploymentId());+ }+ assertEquals(taskDefinitionArn, svc.getTaskDefinition());+ assertEquals(instances.size(), svc.getRunningCount());+ }++ private static List<EcsTask> allTasks(EcsService service) {+ List<String> arns = new ArrayList<>(service.listTasks(null, null, null, null, REGION));+ arns.addAll(service.listTasks(null, null, "STOPPED", null, REGION));+ return service.describeTasks(null, arns, REGION);+ }++ private static Set<String> taskArns(List<EcsTask> tasks) {+ return tasks.stream().map(EcsTask::getTaskArn).collect(Collectors.toSet());+ }+private static List<EcsTask> runningTasks(EcsService service) {return service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION).stream().filter(t -> "RUNNING".equals(t.getLastStatus())).toList();}- private static void registerTaskDef(EcsService service) {+ private static TaskDefinition registerTaskDef(EcsService service) {ContainerDefinition cd = new ContainerDefinition();cd.setName("agent");cd.setImage("agent:1");- service.registerTaskDefinition("daemon-fam", List.of(cd), null, null, null, null, null, List.of(), REGION);+ return service.registerTaskDefinition("daemon-fam", List.of(cd), null, null, null, null, null, List.of(), REGION);+ }++ private static EcsService newDockerModeServiceWhoseStopsFail() {+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);+ when(config.services().ecs().mock()).thenReturn(false);+ when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");+ EcsContainerManager containerManager = mock(EcsContainerManager.class);+ when(containerManager.removeLeftoverContainers()).thenReturn(true);+ when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(inv ->+ new EcsTaskHandle(inv.<EcsTask>getArgument(0).getTaskArn(), Map.of("agent", "cid"), Map.of()));+ when(containerManager.stopTaskAndCollectExitCodes(any()))+ .thenThrow(new RuntimeException("docker unavailable"));+ EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), containerManager,+ config, mock(EcsLoadBalancerRegistrar.class), new InMemoryStorageFactory(), null);+ service.initializeStorage();+ return service;}private static EcsService newMockModeService() {diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentStatusTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentStatusTest.javaindex 34ae2a8c22..caeec61339 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentStatusTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentStatusTest.java@@ -21,6 +21,7 @@ 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.assertNull;@@ -268,12 +269,12 @@ class EcsServiceDeploymentStatusTest {}/**- * A DAEMON service still finishes its deployment after a task-definition change. DAEMON- * services do not roll yet, so the old revision's task is still the one running; the last- * assertions fail once they do, which is when the DAEMON case in the count should go.+ * A DAEMON service's deployment is not done until its task has rolled to the new revision.+ * Before the reconciler has replaced the old task, counting it would report COMPLETED and+ * settle the new deployment SUCCESSFUL, which is terminal, while only the old revision runs.*/@Test- void aDaemonServiceStillFinishesItsDeploymentAfterATaskDefinitionChange() {+ void aDaemonServiceFinishesItsDeploymentOnlyOnceItsTaskHasRolled() {EcsService service = newMockModeService();service.createCluster("ddmn-cluster", REGION);service.registerContainerInstance("ddmn-cluster", null, List.of(), REGION);@@ -282,23 +283,36 @@ class EcsServiceDeploymentStatusTest {List.of(), null, null, "DAEMON", null, null, REGION);service.reconcileServices();service.reconcileServices();+ assertEquals(rev1.getTaskDefinitionArn(), runningTasks(service).getFirst().getTaskDefinitionArn(),+ "precondition: the old revision's task is up");TaskDefinition rev2 = registerTaskDef(service, "ddmn-fam", "app:2");String rolled = service.updateService("ddmn-cluster", "ddmn-svc","ddmn-fam:" + rev2.getRevision(), null, null, REGION).getDeploymentId();++ EcsServiceModel svc = service.serviceByArn(+ service.describeServices("ddmn-cluster", List.of("ddmn-svc"), REGION)+ .getFirst().getServiceArn());+ assertEquals("IN_PROGRESS", service.deploymentsFor(svc).getFirst().getRolloutState(),+ "only the old revision's task is running");+ assertEquals("IN_PROGRESS",+ deploymentOf(service, "ddmn-svc", "ddmn-cluster", rolled).getStatus(),+ "a deployment settled now could never move again");+ assertTrue(service.eventsFor(svc).isEmpty(),+ "no steady-state event before the task has rolled");+service.reconcileServices();service.reconcileServices();- ServiceDeployment record = deploymentOf(service, "ddmn-svc", "ddmn-cluster", rolled);- assertEquals("SUCCESSFUL", record.getStatus(),- "a DAEMON deployment must still finish, or a steady-state wait hangs for ever");- assertNotNull(record.getFinishedAt());-List<EcsTask> live = runningTasks(service);assertEquals(1, live.size(), "one task per container instance");- assertEquals(rev1.getTaskDefinitionArn(), live.getFirst().getTaskDefinitionArn(),- "DAEMON does not roll on a task-definition change; the count is honest about that");- assertNotEquals(rev2.getTaskDefinitionArn(), live.getFirst().getTaskDefinitionArn());+ assertEquals(rev2.getTaskDefinitionArn(), live.getFirst().getTaskDefinitionArn(),+ "the task rolled to the new revision");+ assertEquals("COMPLETED", service.deploymentsFor(svc).getFirst().getRolloutState());+ ServiceDeployment record = deploymentOf(service, "ddmn-svc", "ddmn-cluster", rolled);+ assertEquals("SUCCESSFUL", record.getStatus());+ assertNotNull(record.getFinishedAt());+ assertFalse(service.eventsFor(svc).isEmpty(), "steady state once the task has rolled");}/**