diff --git a/docs/services/ecs.md b/docs/services/ecs.md index c1ae12d21b..e7b8e46d45 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -329,8 +329,13 @@ applied without rolling anything. An update replaces only the members it names: array clears a member the way AWS clears it. When a service replaces or stops a task in Docker mode, the task remains `STOPPING` until its -containers are removed. A failed Docker removal is retried on later reconciliation ticks, so the -task is not reported as `STOPPED` while its container may still be serving. +containers are removed. The service scheduler runs these Docker stops in the background, up to +eight at a time, so a container waiting out its `stopTimeout` does not hold up the reconciliation +of other tasks and services; a `DAEMON` replacement still starts only once the task it replaces +is `STOPPED`. A failed Docker removal is retried on later reconciliation ticks, so the task is not +reported as `STOPPED` while its container may still be serving. `StopTask` answers once its stop +has landed, and on a task the scheduler is already stopping it waits for that stop rather than +starting a second one. Every `awsvpc` task gets a real ENI in the subnet it asked for, in Docker and in mock mode alike, and reports it as an `attachments` entry with its `networkInterfaceId`, `privateIPv4Address` and 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.java index 8f4e09e65d..c8bb22aacf 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 @@ -100,12 +100,17 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.LongPredicate; import java.util.function.Predicate; @@ -136,6 +141,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab private final String baseUrl; // Replaced by afterReset() after a state reset, whose container teardown shuts this scheduler down. private volatile ScheduledExecutorService reconciler = newReconciler(); + /** + * Docker stops the task stopper runs at once. Each holds its thread for the containers' whole + * {@code stopTimeout}, up to two minutes a container, so this bounds that work without making + * unrelated services take turns behind one slow task. + */ + private static final int TASK_STOP_CONCURRENCY = 8; + // Runs the service scheduler's Docker stops (see stopInBackground). A container teardown drains + // and shuts it down, and afterReset() replaces it, as with the reconciler. + private volatile ExecutorService taskStopper = newTaskStopper(); private final Object reconcilerLock = new Object(); private final Object reconciliationPassLock = new Object(); // False until a previous run's task containers are confirmed gone; no task starts before. @@ -153,6 +167,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab private final Map tasks = new ConcurrentHashMap<>(); // taskArn → EcsTaskHandle (running containers or pending resource cleanup) private final Map taskHandles = new ConcurrentHashMap<>(); + // taskArn → the Docker stop the task stopper is running for that task, until the stop has landed. + private final Map> taskStops = new ConcurrentHashMap<>(); private final Set shutdownCleanupTasks = ConcurrentHashMap.newKeySet(); // region::clusterName/serviceName → EcsServiceModel private Map services = new ConcurrentHashMap<>(); @@ -341,6 +357,22 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab r -> { Thread t = new Thread(r, "ecs-reconciler"); t.setDaemon(true); return t; }); } + /** + * Its threads exist only while there is something to stop. The queue is unbounded, but + * {@link #taskStops} admits one stop per task, so it never holds more stops than there are tasks. + */ + private static ExecutorService newTaskStopper() { + AtomicInteger threads = new AtomicInteger(); + ThreadPoolExecutor stopper = new ThreadPoolExecutor(TASK_STOP_CONCURRENCY, TASK_STOP_CONCURRENCY, + 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> { + Thread t = new Thread(r, "ecs-task-stopper-" + threads.incrementAndGet()); + t.setDaemon(true); + return t; + }); + stopper.allowCoreThreadTimeOut(true); + return stopper; + } + void initializeStorage() { if (storageFactory == null) { return; // keeps non-CDI unit tests working @@ -401,8 +433,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab * state reset. Task state is transient (memory-only), so without this the containers * outlive the process as orphans. The reconciler is shut down first, and any in-flight * tick awaited, so it cannot restart drained tasks between this teardown and the final - * storage flush. A reset brings it back in {@link #afterReset()}. Handles are claimed - * atomically to avoid racing an explicit StopTask. + * storage flush. A reset brings it back in {@link #afterReset()}. The stops the task stopper + * already has are let finish, since each owns its task's handle until it lands. The remaining + * handles are claimed atomically to avoid racing an explicit StopTask. */ @Override public void stopManagedContainers() { @@ -413,7 +446,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + drainTaskStopper(); for (String taskArn : new ArrayList<>(taskHandles.keySet())) { + if (taskStops.containsKey(taskArn)) { + // Only after an interrupted drain: stopping its containers beside that stop would race it. + LOG.warnv("Leaving ECS task {0} to the stop still running for it", taskArn); + continue; + } EcsTaskHandle claimed = taskHandles.remove(taskArn); if (claimed == null) { continue; @@ -444,6 +483,23 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } } + /** + * Lets every stop handed to the task stopper finish, queued ones included, and land its task + * as usual, rather than stopping the same containers again beside it. The stopper takes no new + * stop until {@link #afterReset()} replaces it. The wait is no longer than stopping those tasks + * here would have taken: each stop is bounded by its containers' stop timeouts and Docker's API + * timeout, and they run side by side. + */ + private void drainTaskStopper() { + ExecutorService current = taskStopper; + current.shutdown(); + try { + current.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + @Override public void clear() { // The stores hold the ECS state and afterReset() restarts the reconciler. The reset also @@ -454,14 +510,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab /** * Runs at the end of every state reset, never on shutdown. The reset's teardown stopped the - * reconciler, so without a new one no service would be reconciled again until the emulator - * restarted. This hook rather than {@code clear()} because the controller runs it even when - * the storage wipe or another service's {@code clear()} threw, and a failed reset must not - * leave ECS without a reconciler for good. + * reconciler and the task stopper, so without new ones no service would be reconciled again, + * nor any of its tasks stopped, until the emulator restarted. This hook rather than + * {@code clear()} because the controller runs it even when the storage wipe or another + * service's {@code clear()} threw, and a failed reset must not leave ECS without a reconciler + * for good. The stopper comes back first, so the new reconciler's first tick has one. */ @Override public void afterReset() { synchronized (reconcilerLock) { + if (taskStopper.isShutdown()) { + taskStopper = newTaskStopper(); + } if (reconciler.isShutdown()) { ScheduledExecutorService replacement = newReconciler(); scheduleReconciliation(replacement); @@ -1575,7 +1635,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab synchronized (task) { taskHandles.put(taskArn, handle); markTaskRunning(task); - cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); + adjustRunningTasksCount(cluster, 1); LOG.infov("Started ECS task (docker): {0}", taskArn); stopRequested = TaskStatus.STOPPED.name().equals(task.getDesiredStatus()); if (!stopRequested) { @@ -1616,7 +1676,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } else { task.setContainers(mockContainers(task, taskDef, region)); markTaskRunning(task); - cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); + adjustRunningTasksCount(cluster, 1); LOG.infov("Started ECS task (mock): {0}", taskArn); if (eventPublisher != null) { eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region); @@ -1678,6 +1738,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab task.bumpVersion(); } + /** + * Moves a cluster's running task count by {@code delta}, never below zero, and says whether it + * moved. Launches, the reconciler and the task stopper's threads all change it, so it is read + * and written under the cluster's monitor rather than one update overwriting another. + */ + private static boolean adjustRunningTasksCount(EcsCluster cluster, int delta) { + synchronized (cluster) { + int count = Math.max(0, cluster.getRunningTasksCount() + delta); + boolean moved = count != cluster.getRunningTasksCount(); + cluster.setRunningTasksCount(count); + return moved; + } + } + /** * Launches one task on behalf of a service, stamping it with the service's ARN so later * reconciliation can recognize it as service-owned without trusting the caller-settable @@ -1981,20 +2055,44 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab */ private EcsTask stopTask(String clusterRef, String taskRef, String reason, String stopCode, String region) { EcsTask task = resolveTaskOrThrow(taskRef, region); + while (true) { + CompletableFuture running; + synchronized (task) { + running = taskStops.get(task.getTaskArn()); + if (running == null) { + return stopTaskLocked(task, reason, stopCode, region, false); + } + } + // The service scheduler is already stopping it. Waiting for that stop, outside the + // monitor it lands under, answers as a stop queued behind another always has: with the + // task STOPPED, or by retrying a stop that failed. A stop that failed can be retried by + // a tick before this thread takes the monitor back, so that retry is waited for too. + running.join(); + } + } + + /** A stop the service scheduler decides on, whose Docker side runs in the background. */ + private void stopServiceTask(EcsTask task, String reason, String region) { synchronized (task) { - return stopTaskLocked(task, reason, stopCode, region); + stopTaskLocked(task, reason, STOP_CODE_SERVICE_SCHEDULER_INITIATED, region, true); } } 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); + stopTaskLocked(task, reason, STOP_CODE_SERVICE_SCHEDULER_INITIATED, region, true); } } } - private EcsTask stopTaskLocked(EcsTask task, String reason, String stopCode, String region) { + /** + * @param inBackground run the Docker stop on the task stopper and return with the task still + * STOPPING, as the reconciler must (see {@link #stopInBackground}); otherwise + * run it on this thread and return once it has landed, as StopTask does + */ + private EcsTask stopTaskLocked(EcsTask task, String reason, String stopCode, String region, + boolean inBackground) { if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) { return task; } @@ -2009,50 +2107,126 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab deregisterTaskFromServiceDiscovery(task, region); } - Map exitCodes = Map.of(); - Map finishedAt = Map.of(); - if (dockerMode) { - EcsTaskHandle handle = taskHandles.get(task.getTaskArn()); - if (handle == null) { - handle = recoverTaskHandle(task, region); - if (handle == null) { - LOG.warnv("Cannot stop ECS task {0}: no Docker container IDs are available", task.getTaskArn()); - return task; - } - } - try { - exitCodes = containerManager.stopTaskAndCollectExitCodes(handle); - } catch (Exception e) { - LOG.warnv(e, "Could not stop ECS task {0}; retrying on the next reconciliation tick", - task.getTaskArn()); - return task; - } - if (exitCodes.size() != handle.getContainerIds().size() - || !handle.allContainersRemoved()) { - LOG.warnv("ECS task {0} still has containers pending removal; retrying on the next reconciliation tick", - task.getTaskArn()); - return task; - } - taskHandles.remove(task.getTaskArn(), handle); - retainPendingCleanupHandle(task.getTaskArn(), handle); - finishedAt = handle.getFinishedAt(); + if (!dockerMode) { + markTaskStopped(task, Map.of(), Map.of(), region); + return task; } + if (taskStops.containsKey(task.getTaskArn())) { + return task; // the stop already running for it lands it + } + EcsTaskHandle handle = taskHandles.get(task.getTaskArn()); + if (handle == null) { + handle = recoverTaskHandle(task, region); + if (handle == null) { + LOG.warnv("Cannot stop ECS task {0}: no Docker container IDs are available", task.getTaskArn()); + return task; + } + } + if (inBackground) { + stopInBackground(task, handle, region); + return task; + } + Map exitCodes; + try { + exitCodes = containerManager.stopTaskAndCollectExitCodes(handle); + } catch (Exception e) { + LOG.warnv(e, "Could not stop ECS task {0}; retrying on the next reconciliation tick", + task.getTaskArn()); + return task; + } + landDockerStop(task, handle, exitCodes, region); + return task; + } + /** + * Hands a task's Docker stop to the task stopper. The stop waits out each container's + * {@code stopTimeout}, up to two minutes a container; run on the reconciler thread, it held up + * every other task and service for that long, one slow task after another. The task is + * already STOPPING and deregistered; the stop lands it STOPPED once Docker is done, or leaves + * it STOPPING for a later tick to retry, as a failed stop always has. {@link #taskStops} keeps + * the ticks in between from starting it again. Called holding the task's monitor, which the + * stop takes only to land: nothing holds it while Docker works. + */ + private void stopInBackground(EcsTask task, EcsTaskHandle handle, String region) { + String taskArn = task.getTaskArn(); + String accountId = taskAccountId(taskArn); + CompletableFuture stop = new CompletableFuture<>(); + // Recorded before it can run, so its own removal below always comes after this. + taskStops.put(taskArn, stop); + try { + taskStopper.execute(() -> { + try { + // A stopper thread has no request context, and account-aware storage reads the + // account from it. + RequestScopes.runAs(accountId, () -> runBackgroundStop(task, handle, region)); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not finish stopping ECS task {0}: {1}", taskArn, e.getMessage()); + } finally { + taskStops.remove(taskArn, stop); + stop.complete(null); + } + }); + } catch (RejectedExecutionException e) { + // Only while a container teardown has the stopper shut down. The task keeps its handle, + // so that teardown, or the first tick after a reset, stops it instead. + taskStops.remove(taskArn, stop); + stop.complete(null); + LOG.debugv("ECS task stopper is shut down, leaving task {0} STOPPING: {1}", taskArn, e.getMessage()); + } + } + + /** The task stopper's half of {@link #stopInBackground}: the Docker stop, then its landing. */ + private void runBackgroundStop(EcsTask task, EcsTaskHandle handle, String region) { + Map exitCodes; + try { + exitCodes = containerManager.stopTaskAndCollectExitCodes(handle); + } catch (Exception e) { + LOG.warnv(e, "Could not stop ECS task {0}; retrying on the next reconciliation tick", + task.getTaskArn()); + return; + } + synchronized (task) { + // Nothing else takes a task out of STOPPING while its stop runs here; checked all the + // same, so a stop can never land a task twice. + if (TaskStatus.STOPPING.name().equals(task.getLastStatus())) { + landDockerStop(task, handle, exitCodes, region); + } + } + } + + /** + * Lands a Docker stop that came back: STOPPED once every container is gone, still STOPPING + * otherwise, for a later reconciliation tick to retry. Called holding the task's monitor. + */ + private void landDockerStop(EcsTask task, EcsTaskHandle handle, Map exitCodes, + String region) { + if (exitCodes.size() != handle.getContainerIds().size() + || !handle.allContainersRemoved()) { + LOG.warnv("ECS task {0} still has containers pending removal; retrying on the next reconciliation tick", + task.getTaskArn()); + return; + } + taskHandles.remove(task.getTaskArn(), handle); + retainPendingCleanupHandle(task.getTaskArn(), handle); + markTaskStopped(task, exitCodes, handle.getFinishedAt(), region); + } + + /** The STOPPED half of a stop, with what Docker reported about each container. */ + private void markTaskStopped(EcsTask task, Map exitCodes, Map finishedAt, + String region) { task.setLastStatus(TaskStatus.STOPPED.name()); task.setStoppedAt(Instant.now()); task.setExecutionStoppedAt(Instant.now()); task.bumpVersion(); containerManager.releaseTaskNetwork(task, region); if (task.getContainers() != null) { - final Map codes = exitCodes; - final Map finishTimes = finishedAt; task.getContainers().forEach(c -> { c.setLastStatus("STOPPED"); - Integer code = codes.get(c.getName()); + Integer code = exitCodes.get(c.getName()); if (code != null) { c.setExitCode(code); } - Instant finished = finishTimes.get(c.getName()); + Instant finished = finishedAt.get(c.getName()); if (finished != null) { c.setFinishedAt(finished); } @@ -2060,8 +2234,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } EcsCluster cluster = resolveClusterByArn(task.getClusterArn()); - if (cluster != null && cluster.getRunningTasksCount() > 0) { - cluster.setRunningTasksCount(cluster.getRunningTasksCount() - 1); + if (cluster != null && adjustRunningTasksCount(cluster, -1)) { persistCluster(region, cluster); } @@ -2069,7 +2242,6 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab if (eventPublisher != null) { eventPublisher.emitTaskLadder(task, TaskStatus.RUNNING, TaskStatus.STOPPED, region); } - return task; } /** Registers a freshly-started task's containers as ELBv2 targets if its service is load-balanced. */ @@ -5004,7 +5176,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab private void reconcileTaskLocked(String taskArn, EcsTask task) { if (TaskStatus.STOPPING.name().equals(task.getLastStatus())) { - stopTask(task.getClusterArn(), taskArn, task.getStoppedReason(), task.getStopCode(), taskRegion(task)); + // 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); return; } @@ -5075,8 +5249,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab task.bumpVersion(); EcsCluster cluster = resolveClusterByArn(task.getClusterArn()); - if (cluster != null && cluster.getRunningTasksCount() > 0) { - cluster.setRunningTasksCount(cluster.getRunningTasksCount() - 1); + if (cluster != null) { + adjustRunningTasksCount(cluster, -1); } LOG.infov("ECS task {0} reconciled to STOPPED (all containers exited)", taskArn); @@ -5271,10 +5445,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab continue; // teardown already in flight } try { - stopTask(clusterName, t.getTaskArn(), instanceArn == null || !activeArns.contains(instanceArn) + stopServiceTask(t, instanceArn == null || !activeArns.contains(instanceArn) ? "Daemon task's container instance is no longer active" - : "Daemon service already has a task on this container instance", - STOP_CODE_SERVICE_SCHEDULER_INITIATED, region); + : "Daemon service already has a task on this container instance", region); } catch (Exception e) { LOG.warnv("Service reconciler failed to stop daemon task {0}: {1}", t.getTaskArn(), e.getMessage()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsBackgroundTaskStopIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsBackgroundTaskStopIntegrationTest.java new file mode 100644 index 0000000000..921de12ec5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsBackgroundTaskStopIntegrationTest.java @@ -0,0 +1,119 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.github.hectorvent.floci.core.common.RequestScopes; +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.Container; +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.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +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 java.util.concurrent.atomic.AtomicReference; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +/** + * The service scheduler's Docker stops run on the task stopper's own threads, which have no + * request context, and account-aware storage reads the account from that context. Only a running + * Arc container has one, so this runs in Quarkus, in Docker mode over a container manager that + * stops nothing for real: a stop that landed in the wrong account would leave the task's own + * cluster still counting it. + */ +@QuarkusTest +@TestProfile(EcsBackgroundTaskStopIntegrationTest.DockerModeProfile.class) +class EcsBackgroundTaskStopIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "111122223333"; + + /** Docker mode, with no sweep of a previous run's containers, which the mock would refuse. */ + public static final class DockerModeProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ecs.mock", "false", + "floci.services.ecs.reconcile-containers-on-startup", "false"); + } + } + + @Inject + EcsService ecsService; + + @InjectMock + EcsContainerManager containerManager; + + @Test + void aServiceTaskStoppedInTheBackgroundLandsInItsOwnAccount() { + AtomicReference stoppedOn = new AtomicReference<>(); + when(containerManager.getExitCodeIfStopped(anyString())).thenReturn(null); + when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> { + EcsTask task = invocation.getArgument(0); + Container container = new Container(); + container.setName("app"); + container.setRuntimeId("docker-" + Integer.toHexString(task.getTaskArn().hashCode())); + task.setContainers(List.of(container)); + return new EcsTaskHandle(task.getTaskArn(), Map.of("app", container.getRuntimeId()), Map.of()); + }); + when(containerManager.stopTaskAndCollectExitCodes(any())).thenAnswer(invocation -> { + stoppedOn.set(Thread.currentThread().getName()); + EcsTaskHandle handle = invocation.getArgument(0); + handle.getContainerIds().keySet().forEach(handle::recordContainerRemoved); + return Map.of("app", 137); + }); + String suffix = UUID.randomUUID().toString().substring(0, 8); + String cluster = "stopper-" + suffix; + String service = "stopper-svc-" + suffix; + RequestScopes.runAs(ACCOUNT, () -> { + ecsService.createCluster(cluster, REGION); + ContainerDefinition app = new ContainerDefinition(); + app.setName("app"); + app.setImage("app:1"); + ecsService.registerTaskDefinition(service, List.of(app), null, null, null, + null, null, List.of(), REGION); + ecsService.createService(cluster, service, service, 1, LaunchType.FARGATE, List.of(), null, REGION); + }); + + ecsService.reconcile(); + EcsTask task = RequestScopes.callAs(ACCOUNT, () -> { + List running = ecsService.describeTasks(cluster, + ecsService.listTasks(cluster, null, null, service, REGION), REGION); + assertEquals(1, running.size(), "the service's task must be running"); + return running.getFirst(); + }); + assertEquals(1, runningTasksCount(cluster)); + + RequestScopes.runAs(ACCOUNT, () -> ecsService.updateService(cluster, service, null, 0, null, REGION)); + ecsService.reconcile(); + // A stop lands whole under the task's monitor, so a STOPPED read there sees its exit codes + // and cluster count too. + await().atMost(Duration.ofSeconds(10)).until(() -> { + synchronized (task) { + return "STOPPED".equals(task.getLastStatus()); + } + }); + + assertTrue(stoppedOn.get().startsWith("ecs-task-stopper-"), "stopped on " + stoppedOn.get()); + assertEquals(137, task.getContainers().getFirst().getExitCode()); + assertEquals(0, runningTasksCount(cluster), "the stop must land in the task's own account"); + RequestScopes.runAs(ACCOUNT, () -> ecsService.deleteService(cluster, service, true, REGION)); + } + + private int runningTasksCount(String cluster) { + return RequestScopes.callAs(ACCOUNT, () -> + ecsService.describeClusters(List.of(cluster), REGION).getFirst().getRunningTasksCount()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsGracefulStopConcurrencyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsGracefulStopConcurrencyServiceTest.java new file mode 100644 index 0000000000..eb0ead13d8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsGracefulStopConcurrencyServiceTest.java @@ -0,0 +1,413 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +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.Container; +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.TaskStatus; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doAnswer; +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 task's graceful stop waits out its containers' {@code stopTimeout}, up to two minutes a + * container. The service scheduler used to wait for it on the single reconciler thread, so one + * slow stop held up every other task and service, and several ran one after another (#6619). + * These run the reconciler in Docker mode against a container manager whose stop of one chosen + * task blocks until the test lets it finish, the way a container that ignores SIGTERM holds its + * stop until the timeout kills it. + */ +class EcsGracefulStopConcurrencyServiceTest { + + private static final String REGION = "us-east-1"; + private static final String CLUSTER = "stop-cluster"; + /** Far longer than a tick takes here, and far shorter than the stop the tests hold open. */ + private static final Duration TICK_BUDGET = Duration.ofSeconds(5); + + private final EcsContainerManager containerManager = mock(EcsContainerManager.class); + private final EcsEventPublisher eventPublisher = mock(EcsEventPublisher.class); + private final List services = new ArrayList<>(); + /** The task whose stop blocks until {@link #releaseSlowStop}; every other task stops at once. */ + private final AtomicReference slowTaskArn = new AtomicReference<>(); + private final CountDownLatch slowStopEntered = new CountDownLatch(1); + private final CountDownLatch releaseSlowStop = new CountDownLatch(1); + /** The task whose next {@link #stopFailures} stops throw, as a stop does when Docker is unreachable. */ + private final AtomicReference failingTaskArn = new AtomicReference<>(); + private final AtomicInteger stopFailures = new AtomicInteger(); + + @BeforeEach + void stubContainers() { + // Mockito answers 0 for an Integer, which reads as "every container exited". + when(containerManager.getExitCodeIfStopped(anyString())).thenReturn(null); + when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> { + EcsTask task = invocation.getArgument(0); + Container container = new Container(); + container.setName("app"); + container.setRuntimeId("docker-" + Integer.toHexString(task.getTaskArn().hashCode())); + task.setContainers(List.of(container)); + return new EcsTaskHandle(task.getTaskArn(), Map.of("app", container.getRuntimeId()), Map.of()); + }); + when(containerManager.stopTaskAndCollectExitCodes(any())).thenAnswer(invocation -> { + EcsTaskHandle handle = invocation.getArgument(0); + if (handle.getTaskArn().equals(failingTaskArn.get()) && stopFailures.getAndDecrement() > 0) { + throw new IllegalStateException("Cannot connect to the Docker daemon"); + } + int exitCode = 0; + if (handle.getTaskArn().equals(slowTaskArn.get())) { + slowStopEntered.countDown(); + // A container that ignores SIGTERM goes only when its stopTimeout runs out, as SIGKILL. + releaseSlowStop.await(30, TimeUnit.SECONDS); + exitCode = 137; + } + handle.getContainerIds().keySet().forEach(handle::recordContainerRemoved); + return Map.of("app", exitCode); + }); + } + + @AfterEach + void releaseStopsAndTearDown() { + releaseSlowStop.countDown(); + services.forEach(EcsService::stopManagedContainers); + } + + @Test + void anUnrelatedServiceRollsOutWhileAnotherTaskWaitsOutItsStopTimeout() throws Exception { + EcsService service = newService(); + createService(service, "slow", 1); + createService(service, "fast", 1); + tick(service); + EcsTask slowOld = onlyRunningTask(service, "slow"); + EcsTask fastOld = onlyRunningTask(service, "fast"); + slowTaskArn.set(slowOld.getTaskArn()); + + // The slow service rolls: its replacement starts, then the next tick drains the old task, + // whose container takes its whole stopTimeout to go. + service.updateService(CLUSTER, "slow", null, null, null, null, true, REGION); + tick(service); + FutureTask drain = startTick(service); + try { + assertTrue(slowStopEntered.await(5, TimeUnit.SECONDS), "the slow task's stop never started"); + + // Meanwhile an unrelated service rolls all the way through. + service.updateService(CLUSTER, "fast", null, null, null, null, true, REGION); + tick(service); + tick(service); + await().atMost(TICK_BUDGET).until(() -> "STOPPED".equals(lastStatus(service, fastOld))); + assertNotEquals(fastOld.getTaskArn(), onlyRunningTask(service, "fast").getTaskArn()); + + assertEquals("STOPPING", lastStatus(service, slowOld), "the slow task is still in its grace period"); + drain.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS); + } finally { + releaseSlowStop.countDown(); + } + await().atMost(TICK_BUDGET).until(() -> "STOPPED".equals(lastStatus(service, slowOld))); + } + + @Test + void ticksDuringASlowStopNeitherRepeatItNorLandItTwice() throws Exception { + EcsService service = newService(); + createService(service, "slow", 1); + tick(service); + EcsTask old = onlyRunningTask(service, "slow"); + slowTaskArn.set(old.getTaskArn()); + service.updateService(CLUSTER, "slow", null, null, null, null, true, REGION); + tick(service); + EcsTask replacement = runningTasks(service, "slow").stream() + .filter(task -> !task.getTaskArn().equals(old.getTaskArn())) + .findFirst().orElseThrow(); + + try { + tick(service); + assertTrue(slowStopEntered.await(5, TimeUnit.SECONDS), "the slow task's stop never started"); + tick(service); + tick(service); + tick(service); + verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handleOf(old)); + assertEquals("STOPPING", lastStatus(service, old)); + } finally { + releaseSlowStop.countDown(); + } + await().atMost(TICK_BUDGET).until(() -> "STOPPED".equals(lastStatus(service, old))); + tick(service); + tick(service); + + EcsTask stopped = describe(service, old); + assertEquals(137, stopped.getContainers().getFirst().getExitCode()); + assertEquals(EcsService.STOP_CODE_SERVICE_SCHEDULER_INITIATED, stopped.getStopCode()); + verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handleOf(old)); + verify(eventPublisher, times(1)).emitTaskLadder(argThat(task -> old.getTaskArn().equals(task.getTaskArn())), + eq(TaskStatus.RUNNING), eq(TaskStatus.STOPPED), eq(REGION)); + assertEquals(List.of(replacement.getTaskArn()), + runningTasks(service, "slow").stream().map(EcsTask::getTaskArn).toList()); + assertEquals(2, allTasks(service, "slow").size(), "a slow stop starts no second replacement"); + assertEquals(1, service.describeClusters(List.of(CLUSTER), REGION).getFirst().getRunningTasksCount()); + } + + @Test + void aStopThatFailsIsRetriedOnALaterTick() throws Exception { + EcsService service = newService(); + createService(service, "flaky", 1); + tick(service); + EcsTask task = onlyRunningTask(service, "flaky"); + failingTaskArn.set(task.getTaskArn()); + stopFailures.set(1); + + service.updateService(CLUSTER, "flaky", null, 0, null, REGION); + tick(service); + await().atMost(TICK_BUDGET).untilAsserted(() -> + verify(containerManager).stopTaskAndCollectExitCodes(handleOf(task))); + assertEquals("STOPPING", lastStatus(service, task), "a stop that failed leaves the task STOPPING"); + + await().atMost(TICK_BUDGET).until(() -> { + tick(service); + return "STOPPED".equals(lastStatus(service, task)); + }); + verify(containerManager, times(2)).stopTaskAndCollectExitCodes(handleOf(task)); + } + + @Test + void teardownLetsAStopAlreadyRunningFinishInsteadOfStoppingTheTaskAgain() throws Exception { + EcsService service = newService(); + createService(service, "slow", 1); + tick(service); + EcsTask old = onlyRunningTask(service, "slow"); + slowTaskArn.set(old.getTaskArn()); + service.updateService(CLUSTER, "slow", null, null, null, null, true, REGION); + tick(service); + EcsTask replacement = runningTasks(service, "slow").stream() + .filter(task -> !task.getTaskArn().equals(old.getTaskArn())) + .findFirst().orElseThrow(); + + FutureTask drain = startTick(service); + FutureTask teardown; + try { + assertTrue(slowStopEntered.await(5, TimeUnit.SECONDS), "the slow task's stop never started"); + // A reset or shutdown arrives while that container is still in its grace period. + teardown = new FutureTask<>(service::stopManagedContainers, null); + Thread teardownThread = new Thread(teardown, "test-ecs-teardown"); + teardownThread.setDaemon(true); + teardownThread.start(); + assertThrows(TimeoutException.class, () -> teardown.get(500, TimeUnit.MILLISECONDS), + "the teardown waits for the stop already running"); + } finally { + releaseSlowStop.countDown(); + } + teardown.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS); + drain.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS); + + assertEquals("STOPPED", lastStatus(service, old)); + assertEquals(137, describe(service, old).getContainers().getFirst().getExitCode()); + verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handleOf(old)); + verify(containerManager, never()).stopTask(handleOf(old)); + verify(containerManager, times(1)).stopTask(handleOf(replacement)); + } + + @Test + void aResetBringsTheTaskStopperBackWithTheReconciler() throws Exception { + EcsService service = newService(); + createService(service, "after-reset", 1); + tick(service); + EcsTask task = onlyRunningTask(service, "after-reset"); + + service.stopManagedContainers(); + service.afterReset(); + service.updateService(CLUSTER, "after-reset", null, 0, null, REGION); + tick(service); + + await().atMost(TICK_BUDGET).until(() -> "STOPPED".equals(lastStatus(service, task))); + } + + @Test + void stopTaskWaitsForTheStopTheSchedulerAlreadyStarted() throws Exception { + EcsService service = newService(); + createService(service, "slow", 1); + tick(service); + EcsTask task = onlyRunningTask(service, "slow"); + slowTaskArn.set(task.getTaskArn()); + service.updateService(CLUSTER, "slow", null, 0, null, REGION); + + FutureTask scaleIn = startTick(service); + CompletableFuture userStop; + try { + assertTrue(slowStopEntered.await(5, TimeUnit.SECONDS), "the scale-in stop never started"); + userStop = CompletableFuture.supplyAsync(() -> + service.stopTask(CLUSTER, task.getTaskArn(), "user stop", REGION)); + assertThrows(TimeoutException.class, () -> userStop.get(500, TimeUnit.MILLISECONDS), + "StopTask answers once the stop already running has landed"); + } finally { + releaseSlowStop.countDown(); + } + + EcsTask stopped = userStop.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS); + scaleIn.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS); + assertEquals("STOPPED", stopped.getLastStatus()); + assertEquals(EcsService.STOP_CODE_SERVICE_SCHEDULER_INITIATED, stopped.getStopCode()); + verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handleOf(task)); + } + + @Test + void stopTaskWaitsForATickRetryOfAStopThatFailedWhileItWaited() throws Exception { + EcsService service = newService(); + createService(service, "flaky", 1); + tick(service); + EcsTask task = onlyRunningTask(service, "flaky"); + CountDownLatch firstStopEntered = new CountDownLatch(1); + CountDownLatch failFirstStop = new CountDownLatch(1); + CountDownLatch retryEntered = new CountDownLatch(1); + CountDownLatch releaseRetry = new CountDownLatch(1); + AtomicInteger stops = new AtomicInteger(); + doAnswer(invocation -> { + EcsTaskHandle handle = invocation.getArgument(0); + if (stops.incrementAndGet() == 1) { + firstStopEntered.countDown(); + failFirstStop.await(30, TimeUnit.SECONDS); + throw new IllegalStateException("Cannot connect to the Docker daemon"); + } + retryEntered.countDown(); + releaseRetry.await(30, TimeUnit.SECONDS); + handle.getContainerIds().keySet().forEach(handle::recordContainerRemoved); + return Map.of("app", 137); + }).when(containerManager).stopTaskAndCollectExitCodes(handleOf(task)); + service.updateService(CLUSTER, "flaky", null, 0, null, REGION); + + tick(service); + CompletableFuture userStop; + try { + assertTrue(firstStopEntered.await(5, TimeUnit.SECONDS), "the scale-in stop never started"); + userStop = CompletableFuture.supplyAsync(() -> + service.stopTask(CLUSTER, task.getTaskArn(), "user stop", REGION)); + assertThrows(TimeoutException.class, () -> userStop.get(500, TimeUnit.MILLISECONDS), + "StopTask waits for the stop already running"); + // Holding the task's monitor while the first stop fails lets a tick retry it before + // StopTask, woken by the failure, can take the monitor back. + synchronized (task) { + failFirstStop.countDown(); + for (int i = 0; i < 100 && !retryEntered.await(50, TimeUnit.MILLISECONDS); i++) { + service.reconcile(); + } + assertEquals(0, retryEntered.getCount(), "no tick retried the failed stop"); + } + assertThrows(TimeoutException.class, () -> userStop.get(500, TimeUnit.MILLISECONDS), + "StopTask answers once the retry has landed, not while it runs"); + } finally { + failFirstStop.countDown(); + releaseRetry.countDown(); + } + + EcsTask stopped = userStop.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS); + assertEquals("STOPPED", stopped.getLastStatus()); + assertEquals(137, stopped.getContainers().getFirst().getExitCode()); + assertEquals(2, stops.get()); + } + + // ── helpers ────────────────────────────────────────────────────────────── + + /** One full reconcile tick, on a thread of its own, so a tick stuck behind a stop fails rather than hangs. */ + private static void tick(EcsService service) throws Exception { + FutureTask pass = startTick(service); + try { + pass.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + fail("a reconcile tick waited for another task's graceful stop"); + } + } + + private static FutureTask startTick(EcsService service) { + FutureTask pass = new FutureTask<>(service::reconcile, null); + Thread thread = new Thread(pass, "test-ecs-reconcile-tick"); + thread.setDaemon(true); + thread.start(); + return pass; + } + + private EcsService newService() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + 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); + service.initializeStorage(); + service.createCluster(CLUSTER, REGION); + services.add(service); + return service; + } + + private static void createService(EcsService service, String name, int desiredCount) { + 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); + } + + private static EcsTaskHandle handleOf(EcsTask task) { + return argThat(handle -> handle != null && task.getTaskArn().equals(handle.getTaskArn())); + } + + private static EcsTask onlyRunningTask(EcsService service, String serviceName) { + List running = runningTasks(service, serviceName); + assertEquals(1, running.size(), "running tasks of " + serviceName); + return running.getFirst(); + } + + private static List runningTasks(EcsService service, String serviceName) { + return tasks(service, serviceName, "RUNNING").stream() + .filter(task -> "RUNNING".equals(task.getLastStatus())) + .toList(); + } + + private static List allTasks(EcsService service, String serviceName) { + List all = new ArrayList<>(tasks(service, serviceName, "RUNNING")); + all.addAll(tasks(service, serviceName, "STOPPED")); + return all; + } + + private static List tasks(EcsService service, String serviceName, String desiredStatus) { + return service.describeTasks(CLUSTER, + service.listTasks(CLUSTER, null, desiredStatus, serviceName, REGION), REGION); + } + + private static EcsTask describe(EcsService service, EcsTask task) { + return service.describeTasks(CLUSTER, List.of(task.getTaskArn()), REGION).getFirst(); + } + + private static String lastStatus(EcsService service, EcsTask task) { + return describe(service, task).getLastStatus(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java index 132a814f53..b0d43cbe19 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDeploymentCircuitBreakerTest.java @@ -23,12 +23,14 @@ import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest; import org.junit.jupiter.api.Test; +import java.time.Duration; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -381,6 +383,9 @@ class EcsServiceDeploymentCircuitBreakerTest { "rollback remains active while a task from its failed revision is still draining"); assertEquals(2, runningTasks(service).size()); + // The drained task's Docker stop runs off the reconciler thread; the rollback ends once it lands. + await().atMost(Duration.ofSeconds(5)).until(() -> stoppedTasks(service).stream() + .noneMatch(task -> "STOPPING".equals(task.getLastStatus()))); service.reconcile(); service.reconcileServices(); assertEquals("ROLLBACK_SUCCESSFUL", deploymentOf(service, "cb-drain", failedId).getStatus()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java index 0baa89c38a..10970b8d06 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.Closeable; +import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,6 +30,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; @@ -369,8 +371,10 @@ class EcsServiceTeardownTest { service.stopTask(null, taskArn, null, REGION); assertEquals("STOPPING", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus()); + // The tick's retry runs off the reconciler thread and lands the task once Docker is done. service.reconcile(); - assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus()); + await().atMost(Duration.ofSeconds(5)).until(() -> + "STOPPED".equals(service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus())); verify(containerManager, times(2)).stopTaskAndCollectExitCodes(handle); }