fix(ecs): quiesce task producers before container teardown (#8214)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-15 14:46:26 -04:00
1 parent 07ef865dfa
commit 42ead66324
11 files changed
+296 -25

No files matched your search

+5
View File
@@ -513,6 +513,11 @@ held in memory. The service scheduler starts at boot, so within a few seconds of
persisted service is brought back to its `desiredCount`, re-registering load balancer targets
and Cloud Map instances as its tasks start, without waiting for an ECS request.
Before shared container teardown, Floci pauses ECS reconciliation and waits for its current
pass to finish. It also interrupts and waits for background task launches before other services
retire their credentials or networking. A state reset starts fresh executors after the old tasks
have been drained.
#### Service deployments
An `ACTIVE` service reports exactly one `PRIMARY` entry in `services[].deployments`,
@@ -23,6 +23,10 @@ package io.floci.aws.core.common;
*/
public interface ContainerTeardown {
/** Prevents new work before any service starts draining its containers. */
default void beginTeardown() {
}
void stopManagedContainers();
/**
@@ -26,11 +26,27 @@ public final class ContainerTeardowns {
}
public static void stopAll(Instance<ContainerTeardown> teardowns, Logger log) {
stopPrepared(prepareAll(teardowns, log), log);
}
public static List<ContainerTeardown> prepareAll(Instance<ContainerTeardown> teardowns, Logger log) {
List<ContainerTeardown> ordered = new ArrayList<>();
for (ContainerTeardown teardown : teardowns) {
ordered.add(teardown);
}
ordered.sort(Comparator.comparingInt(ContainerTeardown::teardownOrder));
for (ContainerTeardown teardown : ordered) {
try {
teardown.beginTeardown();
} catch (Exception e) {
log.warnv(e, "Container teardown preparation failed for {0}; producers may still be active during best-effort cleanup",
teardown.getClass().getSimpleName());
}
}
return List.copyOf(ordered);
}
public static void stopPrepared(List<ContainerTeardown> ordered, Logger log) {
for (ContainerTeardown teardown : ordered) {
try {
teardown.stopManagedContainers();
@@ -58,6 +58,7 @@ import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
@@ -420,6 +421,7 @@ public class EmulatorLifecycle {
runCleanup("Kinesis poller", kinesisPoller::shutdown);
runCleanup("Redshift zero-ETL consumer", redshiftZeroEtlConsumer::shutdown);
runCleanup("storage flush", storageFactory::flushAll);
List<ContainerTeardown> prepared = ContainerTeardowns.prepareAll(containerTeardowns, LOG);
runCleanup("EC2 metadata server", () -> {
if (isMetadataServerNeeded()) {
ec2MetadataServer.stop();
@@ -447,7 +449,7 @@ public class EmulatorLifecycle {
// Centralized teardown for process-bound containers (Lambda warm pool, ECS tasks,
// EC2 instances, in-flight build/job containers). Runs before shutdownAll() so any
// state written while stopping is captured by the final flush.
ContainerTeardowns.stopAll(containerTeardowns, LOG);
ContainerTeardowns.stopPrepared(prepared, LOG);
runCleanup("DynamoDB backend", dynamoDbRuntime::stop);
runCleanup("storage shutdown", storageFactory::shutdownAll);
@@ -31,7 +31,7 @@ import java.util.Optional;
* {@link ReposiliteSidecarClient#ensureRepository}), not to its own container.
*
* <p>Implements {@link ContainerTeardown} rather than observing {@code ShutdownEvent} directly:
* {@code ContainerTeardowns.stopAll} already runs every implementation both at process shutdown
* {@code ContainerTeardowns} already drains every implementation both at process shutdown
* and on {@code /state/reset}/{@code /state/nuke}, so a reset now actually stops the managed
* container instead of leaving it running with every {@code CodeArtifactRepository} record that
* named it gone.
@@ -113,6 +113,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
@@ -154,6 +155,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
private static final int TASK_STOP_CONCURRENCY = 8;
/** How long a container teardown waits for the launches it interrupted to land their tasks. */
private static final long LAUNCHER_SHUTDOWN_SECONDS = 30;
private static final long RECONCILER_SHUTDOWN_SECONDS = 2;
// 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;
@@ -161,7 +163,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// interrupts and shuts it down, and afterReset() replaces it, as with the task stopper.
private volatile ExecutorService taskLauncher;
private final Object reconcilerLock = new Object();
private final Object reconciliationPassLock = new Object();
private final ReentrantLock reconciliationPassLock = new ReentrantLock();
// False until a previous run's task containers are confirmed gone; no task starts before.
private volatile boolean leftoverContainersRemoved = true;
private volatile boolean leftoverTaskVolumesRemoved;
@@ -463,22 +465,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
stopManagedContainers();
}
/**
* Stops the Docker containers of all still-running tasks on emulator shutdown and on a
* 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()}. The task launcher is then
* interrupted and its launches awaited, so each lands its task before the sweep below. 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.
*/
/** Stops task producers before any owner retires shared credentials or networking. */
@Override
public void stopManagedContainers() {
ScheduledExecutorService current = reconciler;
current.shutdownNow();
public void beginTeardown() {
reconciler.shutdownNow();
try {
current.awaitTermination(2, TimeUnit.SECONDS);
if (reconciliationPassLock.tryLock(RECONCILER_SHUTDOWN_SECONDS, TimeUnit.SECONDS)) {
reconciliationPassLock.unlock();
} else {
LOG.warnv("ECS reconciliation still running after {0} seconds of teardown; "
+ "shared resources will retire before the pass finishes", RECONCILER_SHUTDOWN_SECONDS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
@@ -493,6 +490,21 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* Stops the Docker containers of all still-running tasks on emulator shutdown and on a
* 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 given a bounded wait, so cooperative passes land before this teardown and the final
* storage flush. A reset brings it back in {@link #afterReset()}. The task launcher is then
* interrupted and its launches awaited, so each lands its task before the sweep below. 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() {
beginTeardown();
drainTaskStopper();
for (String taskArn : new ArrayList<>(taskHandles.keySet())) {
if (taskStops.containsKey(taskArn)) {
@@ -5379,7 +5391,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// ── Service Reconciliation ────────────────────────────────────────────────
void reconcile() {
synchronized (reconciliationPassLock) {
reconciliationPassLock.lock();
try {
if (reconciler.isShutdown()) {
return;
}
try {
retryPreviousRunTaskVolumes();
} catch (Exception e) {
@@ -5400,6 +5416,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
});
}
} finally {
reconciliationPassLock.unlock();
}
}
@@ -5884,7 +5902,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
void reconcileServices() {
synchronized (reconciliationPassLock) {
reconciliationPassLock.lock();
try {
if (reconciler.isShutdown()) {
return;
}
for (Map.Entry<String, EcsServiceModel> entry : services.entrySet()) {
try {
reconcileService(entry.getKey(), entry.getValue());
@@ -5897,6 +5919,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
LOG.warnv(e, "Could not publish Container Insights task counts for ECS service {0}", entry.getKey());
}
}
} finally {
reconciliationPassLock.unlock();
}
}
@@ -25,6 +25,46 @@ class ContainerTeardownsTest {
private static final Logger LOG = Logger.getLogger(ContainerTeardownsTest.class);
@Test
void preparesEveryServiceBeforeTheFirstDrain() {
assertPreparesBeforeDraining(false);
}
@Test
void failedPreparationStillPreparesAndDrainsEveryService() {
assertPreparesBeforeDraining(true);
}
private static void assertPreparesBeforeDraining(boolean failPreparation) {
List<String> phases = new ArrayList<>();
ContainerTeardown first = teardown("first", phases, failPreparation);
ContainerTeardown second = teardown("second", phases, false);
@SuppressWarnings("unchecked")
Instance<ContainerTeardown> teardowns = mock(Instance.class);
when(teardowns.iterator()).thenAnswer(ignored -> List.of(first, second).iterator());
ContainerTeardowns.stopAll(teardowns, LOG);
assertEquals(List.of("prepare-first", "prepare-second", "stop-first", "stop-second"), phases);
}
private static ContainerTeardown teardown(String name, List<String> phases, boolean failPreparation) {
return new ContainerTeardown() {
@Override
public void beginTeardown() {
phases.add("prepare-" + name);
if (failPreparation) {
throw new IllegalStateException("injected preparation failure");
}
}
@Override
public void stopManagedContainers() {
phases.add("stop-" + name);
}
};
}
@Test
void stopAllRunsATeardownWhoseContainersOthersUseAfterTheirs() {
List<String> stopped = new ArrayList<>();
@@ -192,6 +192,27 @@ class EmulatorLifecycleTest {
.thenReturn(Collections.emptyIterator());
}
@Test
void preparesContainerOwnersBeforeRetiringSharedCredentials() {
ContainerTeardown first = Mockito.mock(ContainerTeardown.class);
ContainerTeardown second = Mockito.mock(ContainerTeardown.class);
when(containerTeardowns.iterator()).thenReturn(List.of(first, second).iterator());
when(ecsTaskRoleCredentialsConfig.enabled()).thenReturn(true);
emulatorLifecycle.onStop(new ShutdownEvent());
InOrder order = Mockito.inOrder(first, second, storageFactory, ecsTaskRoleCredentialsServer);
order.verify(storageFactory).flushAll();
order.verify(first).beginTeardown();
order.verify(second).beginTeardown();
order.verify(ecsTaskRoleCredentialsServer).stop();
order.verify(first).stopManagedContainers();
order.verify(second).stopManagedContainers();
order.verify(storageFactory).shutdownAll();
verify(first).beginTeardown();
verify(second).beginTeardown();
}
private void stubStorageConfig() {
when(config.storage()).thenReturn(storageConfig);
when(storageConfig.mode()).thenReturn("in-memory");
@@ -13,12 +13,14 @@ 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 io.floci.aws.testing.ThreadStates;
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.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@@ -397,6 +399,148 @@ class EcsGracefulStopConcurrencyServiceTest {
assertEquals("RUNNING", lastStatus(service, replacement));
}
@Test
void teardownPreparationPausesReconciliationUntilReset() throws Exception {
EcsService service = newService();
createService(service, "draining", 1);
tick(service);
EcsTask original = onlyRunningTask(service, "draining");
service.beginTeardown();
assertTrue(service.isReconcilerShutdown(), "preparation stops the scheduler before other owners drain");
service.updateService(CLUSTER, "draining", null, 2, null, REGION);
tick(service);
service.reconcileServices();
verify(containerManager, times(1)).startTask(any(), any(), any(), anyString());
service.stopManagedContainers();
verify(containerManager).stopTask(handleOf(original));
service.clear();
service.afterReset();
tick(service);
assertEquals(2, runningTasks(service, "draining").size(), "reset resumes the desired service count");
}
@Test
void preparationInterruptsTheScheduledPullBeforeWaitingForItsPass() throws Exception {
EcsService service = newService(true);
CountDownLatch pullEntered = new CountDownLatch(1);
CountDownLatch releasePull = new CountDownLatch(1);
CountDownLatch interrupted = new CountDownLatch(1);
doAnswer(invocation -> {
pullEntered.countDown();
try {
releasePull.await();
} catch (InterruptedException e) {
interrupted.countDown();
Thread.currentThread().interrupt();
throw new IllegalStateException("image pull interrupted", e);
}
throw new IllegalStateException("test released the pull without interruption");
}).when(containerManager).startTask(any(), any(), any(), anyString());
createService(service, "scheduled-pull", 1);
FutureTask<Void> preparation = new FutureTask<>(service::beginTeardown, null);
Thread thread = new Thread(preparation, "test-ecs-scheduled-pull-teardown");
thread.setDaemon(true);
try {
assertTrue(pullEntered.await(10, TimeUnit.SECONDS), "the real scheduler must enter its pull");
thread.start();
preparation.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS);
assertEquals(0, interrupted.getCount(), "preparation interrupts the scheduler's inline pull");
List<EcsTask> tasks = allTasks(service, "scheduled-pull");
assertEquals(1, tasks.size());
assertEquals("STOPPED", tasks.getFirst().getLastStatus());
assertEquals("TaskFailedToStart", tasks.getFirst().getStopCode());
verify(containerManager, never()).stopTask(any());
} finally {
releasePull.countDown();
if (thread.getState() != Thread.State.NEW) {
preparation.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS);
}
}
}
@Test
void preparationReturnsWhileTheScheduledPullIgnoresInterruption() throws Exception {
EcsService service = newService(true);
CountDownLatch pullEntered = new CountDownLatch(1);
CountDownLatch interrupted = new CountDownLatch(1);
CountDownLatch releasePull = new CountDownLatch(1);
CountDownLatch pullFinished = new CountDownLatch(1);
doAnswer(invocation -> {
pullEntered.countDown();
try {
boolean released = false;
while (!released) {
try {
released = releasePull.await(10, TimeUnit.SECONDS);
assertTrue(released, "test must release the uncooperative pull");
} catch (InterruptedException e) {
interrupted.countDown();
}
}
throw new IllegalStateException("test released the uncooperative pull");
} finally {
pullFinished.countDown();
}
}).when(containerManager).startTask(any(), any(), any(), anyString());
createService(service, "uncooperative-pull", 1);
FutureTask<Void> preparation = new FutureTask<>(service::beginTeardown, null);
Thread thread = new Thread(preparation, "test-ecs-uncooperative-pull-teardown");
thread.setDaemon(true);
try {
assertTrue(pullEntered.await(10, TimeUnit.SECONDS), "the real scheduler must enter its pull");
thread.start();
assertTrue(interrupted.await(5, TimeUnit.SECONDS), "preparation must interrupt the pull");
preparation.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS);
assertEquals(1, pullFinished.getCount(), "preparation returns while the pull is still blocked");
assertTrue(service.isReconcilerShutdown());
} finally {
releasePull.countDown();
assertTrue(pullFinished.await(5, TimeUnit.SECONDS), "the test pull must finish");
if (thread.getState() != Thread.State.NEW) {
preparation.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS);
}
}
}
@Test
void teardownPreparationWaitsForTaskLaunchBeforeStoppingContainers() throws Exception {
EcsService service = newService();
createService(service, "launching", 1);
CountDownLatch launchEntered = new CountDownLatch(1);
CountDownLatch releaseLaunch = new CountDownLatch(1);
doAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
launchEntered.countDown();
assertTrue(releaseLaunch.await(30, TimeUnit.SECONDS), "test must release the in-flight launch");
Container container = new Container();
container.setName("app");
container.setRuntimeId("launching-container");
task.setContainers(List.of(container));
return new EcsTaskHandle(task.getTaskArn(), Map.of("app", container.getRuntimeId()), Map.of());
}).when(containerManager).startTask(any(), any(), any(), anyString());
FutureTask<Void> launch = startTick(service);
FutureTask<Void> preparation = new FutureTask<>(service::beginTeardown, null);
Thread preparationThread = new Thread(preparation, "test-ecs-teardown-preparation");
preparationThread.setDaemon(true);
try {
assertTrue(launchEntered.await(5, TimeUnit.SECONDS), "the task launch must be in flight");
preparationThread.start();
Thread.State state = ThreadStates.awaitState(preparationThread,
EnumSet.of(Thread.State.TIMED_WAITING, Thread.State.TERMINATED), TICK_BUDGET,
"teardown preparation");
assertEquals(Thread.State.TIMED_WAITING, state, "preparation must wait for the admitted task launch");
} finally {
releaseLaunch.countDown();
}
launch.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS);
preparation.get(TICK_BUDGET.toMillis(), TimeUnit.MILLISECONDS);
EcsTask launched = onlyRunningTask(service, "launching");
service.stopManagedContainers();
verify(containerManager).stopTask(handleOf(launched));
}
// ── helpers ──────────────────────────────────────────────────────────────
/** One full reconcile tick, on a thread of its own, so a tick stuck behind a stop fails rather than hangs. */
@@ -418,13 +562,21 @@ class EcsGracefulStopConcurrencyServiceTest {
}
private EcsService newService() {
return newService(false);
}
private EcsService newService(boolean scheduleReconciliation) {
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, lbRegistrar, new InMemoryStorageFactory("000000000000"), eventPublisher,
new EcsExecSessionRegistry(), null, null, clock);
service.initializeStorage();
if (scheduleReconciliation) {
service.init();
} else {
service.initializeStorage();
}
service.createCluster(CLUSTER, REGION);
services.add(service);
return service;
@@ -73,8 +73,8 @@ class EcsReconciliationConcurrencyServiceTest {
assertTrue(entered.await(5, TimeUnit.SECONDS), "first pass must reach service storage");
secondThread.start();
await().atMost(Duration.ofSeconds(5)).until(() ->
secondThread.getState() == Thread.State.BLOCKED || second.isDone());
assertEquals(Thread.State.BLOCKED, secondThread.getState(),
secondThread.getState() == Thread.State.WAITING || second.isDone());
assertEquals(Thread.State.WAITING, secondThread.getState(),
"a direct pass must wait for the running pass instead of reconciling the same deficit");
} finally {
release.countDown();
@@ -21,6 +21,8 @@ import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Duration;
import java.util.ArrayList;
@@ -315,8 +317,9 @@ class EcsRunTaskAsyncLaunchServiceTest {
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
}
@Test
void teardownInterruptsAPullAndAfterResetLaunchesAgain() throws Exception {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void teardownInterruptsAPullAndAfterResetLaunchesAgain(boolean prepareOnly) throws Exception {
doAnswer(invocation -> {
startEntered.countDown();
try {
@@ -333,7 +336,11 @@ class EcsRunTaskAsyncLaunchServiceTest {
EcsTask response = run(service, "teardown");
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
assertTimeoutPreemptively(LAUNCH_BUDGET, service::stopManagedContainers);
assertTimeoutPreemptively(LAUNCH_BUDGET,
prepareOnly ? service::beginTeardown : service::stopManagedContainers);
if (prepareOnly) {
verify(containerManager, never()).stopTask(any());
}
EcsTask stopped = describe(service, response);
assertEquals("STOPPED", stopped.getLastStatus());