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

@@ -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();
}
}