diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardown.java b/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardown.java
new file mode 100644
index 0000000000..2d5e0211e7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ContainerTeardown.java
@@ -0,0 +1,19 @@
+package io.github.hectorvent.floci.core.common;
+
+/**
+ * Implemented by services that launch Docker containers whose lifetime is bound to the
+ * emulator process (Lambda warm pool, ECS tasks, EC2 instances, in-flight build/job
+ * containers). {@code EmulatorLifecycle.onStop} invokes every implementation during the
+ * ShutdownEvent phase — before {@code StorageFactory.shutdownAll()} — so teardown runs at
+ * a deterministic point and state changes made while stopping are still captured by the
+ * final flush. A {@code @PreDestroy} alone is not sufficient for that: bean destruction
+ * runs after the ShutdownEvent observers, when the storage flush schedulers are already
+ * stopped.
+ *
+ *
Implementations must be idempotent; they may also be invoked from {@code @PreDestroy}
+ * as a fallback.
+ */
+public interface ContainerTeardown {
+
+ void stopManagedContainers();
+}
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
index 498835fc87..5c1cb5f51c 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
@@ -83,6 +84,7 @@ public class EmulatorLifecycle {
private final FlociUiManager flociUiManager;
private final InitLifecycleState initLifecycleState;
private final SchemaCreationWorker schemaCreationWorker;
+ private final jakarta.enterprise.inject.Instance containerTeardowns;
@Inject
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
@@ -108,7 +110,8 @@ public class EmulatorLifecycle {
EcrRegistryManager ecrRegistryManager,
FlociUiManager flociUiManager,
InitLifecycleState initLifecycleState,
- SchemaCreationWorker schemaCreationWorker) {
+ SchemaCreationWorker schemaCreationWorker,
+ jakarta.enterprise.inject.Instance containerTeardowns) {
this.storageFactory = storageFactory;
this.serviceRegistry = serviceRegistry;
this.config = config;
@@ -134,6 +137,7 @@ public class EmulatorLifecycle {
this.flociUiManager = flociUiManager;
this.initLifecycleState = initLifecycleState;
this.schemaCreationWorker = schemaCreationWorker;
+ this.containerTeardowns = containerTeardowns;
}
void onStart(@Observes StartupEvent ignored) {
@@ -264,6 +268,17 @@ public class EmulatorLifecycle {
rabbitMqManager.stopAll();
ecrRegistryManager.shutdown();
flociUiManager.shutdown();
+ // 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.
+ for (ContainerTeardown teardown : containerTeardowns) {
+ try {
+ teardown.stopManagedContainers();
+ } catch (Exception e) {
+ LOG.warnv("Container teardown failed for {0}: {1}",
+ teardown.getClass().getSimpleName(), e.getMessage());
+ }
+ }
storageFactory.shutdownAll();
LOG.info("=== AWS Local Emulator Stopped ===");
diff --git a/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java b/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java
index d5b62cddc2..838b23b4dc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.batch;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
@@ -22,13 +23,19 @@ import java.io.Closeable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
-public class BatchDockerRunner {
+public class BatchDockerRunner implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(BatchDockerRunner.class);
private static final String LOG_GROUP = "/aws/batch/job";
+ // Containers of jobs currently inside run(); drained on emulator shutdown so a
+ // SIGTERM mid-job does not orphan the container.
+ private final ConcurrentHashMap inFlightContainers = new ConcurrentHashMap<>();
+
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
@@ -76,27 +83,59 @@ public class BatchDockerRunner {
ContainerSpec spec = builder.build();
containerId = lifecycleManager.createAndStart(spec).containerId();
+ inFlightContainers.put(job.getJobId(), containerId);
logHandle = logStreamer.attach(containerId, LOG_GROUP, logStreamName, job.getRegion(),
"batch:" + job.getJobName() + ":" + job.getJobId());
Integer exitCode = waitForExit(containerId, timeout(job));
long stoppedAt = System.currentTimeMillis();
+ releaseAndStop(job.getJobId(), containerId, logHandle);
if (exitCode == null) {
- lifecycleManager.stopAndRemove(containerId, logHandle);
return new BatchRunResult(137, "Job timed out", logStreamName, startedAt, stoppedAt, true);
}
- lifecycleManager.stopAndRemove(containerId, logHandle);
return new BatchRunResult(exitCode, exitCode == 0 ? null : "Container exited with code " + exitCode,
logStreamName, startedAt, stoppedAt, false);
} catch (Exception e) {
LOG.warnv("Batch Docker job {0} failed: {1}", job.getJobId(), e.getMessage());
if (containerId != null) {
- lifecycleManager.stopAndRemove(containerId, logHandle);
+ releaseAndStop(job.getJobId(), containerId, logHandle);
}
return failed(startedAt, logStreamName, e.getMessage());
}
}
+ // Whoever wins the map removal owns the stop — stopManagedContainers() may have
+ // claimed the container first during shutdown, but the log stream is still ours.
+ private void releaseAndStop(String jobId, String containerId, Closeable logHandle) {
+ if (inFlightContainers.remove(jobId, containerId)) {
+ lifecycleManager.stopAndRemove(containerId, logHandle);
+ } else if (logHandle != null) {
+ try {
+ logHandle.close();
+ } catch (Exception e) {
+ LOG.debugv("Error closing log stream for job {0}: {1}", jobId, e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Stops the containers of jobs still inside {@link #run} on emulator shutdown;
+ * without this a SIGTERM mid-job orphans the container.
+ */
+ @Override
+ public void stopManagedContainers() {
+ for (Map.Entry entry : new ConcurrentHashMap<>(inFlightContainers).entrySet()) {
+ if (inFlightContainers.remove(entry.getKey(), entry.getValue())) {
+ try {
+ lifecycleManager.stopAndRemove(entry.getValue(), null);
+ } catch (Exception e) {
+ LOG.warnv("Failed to stop Batch container for job {0} on shutdown: {1}",
+ entry.getKey(), e.getMessage());
+ }
+ }
+ }
+ }
+
private BatchRunResult failed(long startedAt, String logStreamName, String reason) {
return new BatchRunResult(1, reason, logStreamName, startedAt, System.currentTimeMillis(), false);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java
index e75072ffdc..1547f6ad1e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
@@ -54,7 +55,7 @@ import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
@ApplicationScoped
-public class CodeBuildRunner {
+public class CodeBuildRunner implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(CodeBuildRunner.class);
@@ -95,6 +96,25 @@ public class CodeBuildRunner {
this.regionResolver = regionResolver;
}
+ /**
+ * Stops the containers of all in-flight builds on emulator shutdown; without this
+ * they outlive the process as orphans. Build state is transient, so there is no
+ * persisted status to update.
+ */
+ @Override
+ public void stopManagedContainers() {
+ for (Map.Entry entry : new LinkedHashMap<>(runningContainers).entrySet()) {
+ if (runningContainers.remove(entry.getKey(), entry.getValue())) {
+ try {
+ lifecycleManager.stopAndRemove(entry.getValue(), null);
+ } catch (Exception e) {
+ LOG.warnv("Failed to stop CodeBuild container for build {0} on shutdown: {1}",
+ entry.getKey(), e.getMessage());
+ }
+ }
+ }
+ }
+
public void startBuild(String region, Build build, Project project, String buildspecOverride) {
AtomicBoolean stopFlag = new AtomicBoolean(false);
stopFlags.put(build.getId(), stopFlag);
@@ -349,11 +369,10 @@ public class CodeBuildRunner {
}
} finally {
stopFlags.remove(buildId);
- if (containerId != null) {
- runningContainers.remove(buildId);
- if (logHandle != null) {
- try { logHandle.close(); } catch (Exception ignored) {}
- }
+ if (logHandle != null) {
+ try { logHandle.close(); } catch (Exception ignored) {}
+ }
+ if (containerId != null && runningContainers.remove(buildId, containerId)) {
lifecycleManager.stopAndRemove(containerId, null);
}
if (workspace != null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
index 7d06f71302..f8812cd0b1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
@@ -239,6 +239,27 @@ public class Ec2ContainerManager {
});
}
+ /**
+ * Synchronous stop for emulator shutdown: tears down the port-forward sidecars and
+ * stops the container with a short timeout so N instances cannot exhaust the SIGTERM
+ * grace window. Unlike {@link #stop}, runs on the caller's thread (the async executor
+ * would be abandoned mid-flight during shutdown) and leaves state handling to the caller.
+ */
+ public void stopForShutdown(Instance instance) {
+ String containerId = instance.getDockerContainerId();
+ if (containerId == null) {
+ return;
+ }
+ portForwardManager.unpublishAll(instance);
+ try {
+ dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
+ } catch (NotFoundException e) {
+ // already gone
+ } catch (Exception e) {
+ LOG.warnv("Error stopping EC2 container {0} on shutdown: {1}", containerId, e.getMessage());
+ }
+ }
+
/**
* Gracefully stops a running container (30 second timeout then SIGKILL).
* Updates instance state through stopping → stopped.
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index 99f8b28aa4..a80c0d0547 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -27,6 +27,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.model.Address;
@@ -77,7 +78,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
-public class Ec2Service {
+public class Ec2Service implements ContainerTeardown {
private static final Logger LOG = Logger.getLogger(Ec2Service.class);
private static final DateTimeFormatter ISO_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
@@ -902,6 +903,34 @@ public class Ec2Service {
return result;
}
+ /**
+ * Stops the Docker containers of running instances on emulator shutdown. Without this
+ * they outlive the process as orphans. Instances flip to {@code stopped} — the container
+ * really is stopped, and the id is kept so StartInstances can revive it after a restart.
+ * Runs during the ShutdownEvent phase, so the state change is captured by the final flush.
+ */
+ @Override
+ public void stopManagedContainers() {
+ if (config.services().ec2().mock()) {
+ return;
+ }
+ for (String storeKey : Set.copyOf(instances.keys())) {
+ Instance inst = instances.get(storeKey).orElse(null);
+ if (inst == null || inst.getDockerContainerId() == null
+ || inst.getState() == null || !"running".equals(inst.getState().getName())) {
+ continue;
+ }
+ try {
+ containerManager.stopForShutdown(inst);
+ inst.setState(InstanceState.stopped());
+ instances.put(storeKey, inst);
+ } catch (Exception e) {
+ LOG.warnv("Failed to stop EC2 instance container {0} on shutdown: {1}",
+ inst.getDockerContainerId(), e.getMessage());
+ }
+ }
+ }
+
public List