fix(ecs): reconcile task lifecycle when container exits naturally (#1078)

* fix(ecs): reconcile task lifecycle when container exits naturally

ECS tasks stayed in RUNNING indefinitely after the underlying Docker
container exited, causing `aws ecs wait tasks-stopped` to hang forever
and exitCode to remain null. Fixes #889.

The 5-second reconciler now also polls running task handles. When all
containers for a task have exited, it atomically claims the handle
(guarding against a concurrent explicit stopTask), closes log streams,
removes the Docker containers, and transitions the task to STOPPED with
stoppedAt and per-container exitCode populated.

Explicit stopTask is also fixed: it now calls stopTaskAndCollectExitCodes
to capture exit codes before the container record is removed, and
propagates them to the ECS container model. An idempotency guard prevents
double-decrement of runningTasksCount when stopTask is called on a task
already transitioned by the reconciler.

cleanupStoppedTask is used by the reconciler to avoid re-inspecting
containers whose exit codes were already collected in the inspection pass.

* fix(ecs): capture exit code after stop, not before

stopTaskAndCollectExitCodes inspected containers before stopping them,
so getExitCodeIfStopped returned null for still-running containers and
the exit code was lost once stopAndRemove deleted the record.

Split the operation into two phases: stop all containers first, then
inspect exit codes, then remove. Containers already exited skip the
stop call silently.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-05-29 02:14:23 -05:00
1 parent b1a3822206
commit 0655be9d23
3 files changed
+405 -6

No files matched your search

@@ -30,6 +30,7 @@ import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -92,7 +93,7 @@ public class EcsService {
@PostConstruct
void init() {
reconciler.scheduleAtFixedRate(this::reconcileServices, 5, 5, TimeUnit.SECONDS);
reconciler.scheduleAtFixedRate(this::reconcile, 5, 5, TimeUnit.SECONDS);
}
@PreDestroy
@@ -316,21 +317,32 @@ public class EcsService {
public EcsTask stopTask(String clusterRef, String taskRef, String reason, String region) {
EcsTask task = resolveTaskOrThrow(taskRef, region);
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
return task;
}
task.setDesiredStatus(TaskStatus.STOPPED.name());
task.setLastStatus(TaskStatus.STOPPING.name());
task.setStoppedReason(reason != null ? reason : "Stopped by user");
deregisterTaskFromLoadBalancers(task, region);
Map<String, Integer> exitCodes = Map.of();
if (dockerMode) {
EcsTaskHandle handle = taskHandles.remove(task.getTaskArn());
containerManager.stopTask(handle);
exitCodes = containerManager.stopTaskAndCollectExitCodes(handle);
}
task.setLastStatus(TaskStatus.STOPPED.name());
task.setStoppedAt(Instant.now());
if (task.getContainers() != null) {
task.getContainers().forEach(c -> c.setLastStatus("STOPPED"));
final Map<String, Integer> codes = exitCodes;
task.getContainers().forEach(c -> {
c.setLastStatus("STOPPED");
Integer code = codes.get(c.getName());
if (code != null) {
c.setExitCode(code);
}
});
}
EcsCluster cluster = resolveClusterByArn(task.getClusterArn());
@@ -1000,6 +1012,75 @@ public class EcsService {
// ── Service Reconciliation ────────────────────────────────────────────────
void reconcile() {
reconcileTasks();
reconcileServices();
}
private void reconcileTasks() {
for (String taskArn : taskHandles.keySet()) {
try {
reconcileTask(taskArn);
} catch (Exception e) {
LOG.debugv("Error reconciling ECS task {0}: {1}", taskArn, e.getMessage());
}
}
}
private void reconcileTask(String taskArn) {
EcsTask task = tasks.get(taskArn);
if (task == null || !TaskStatus.RUNNING.name().equals(task.getLastStatus())) {
return;
}
EcsTaskHandle handle = taskHandles.get(taskArn);
if (handle == null) {
return;
}
// Inspect every container; abort if any are still running.
Map<String, Integer> exitCodes = new LinkedHashMap<>();
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
Integer code = containerManager.getExitCodeIfStopped(entry.getValue());
if (code == null) {
return;
}
exitCodes.put(entry.getKey(), code);
}
// All containers have exited. Atomically claim the handle to avoid
// racing with an explicit stopTask() call.
EcsTaskHandle claimed = taskHandles.remove(taskArn);
if (claimed == null) {
return;
}
// Close log streams and remove the stopped Docker containers without re-inspecting.
containerManager.cleanupStoppedTask(claimed);
if (task.getContainers() != null) {
task.getContainers().forEach(c -> {
c.setLastStatus("STOPPED");
Integer code = exitCodes.get(c.getName());
if (code != null) {
c.setExitCode(code);
}
});
}
task.setLastStatus(TaskStatus.STOPPED.name());
task.setDesiredStatus(TaskStatus.STOPPED.name());
task.setStoppedAt(Instant.now());
task.setStoppedReason("Essential container in task exited");
EcsCluster cluster = resolveClusterByArn(task.getClusterArn());
if (cluster != null && cluster.getRunningTasksCount() > 0) {
cluster.setRunningTasksCount(cluster.getRunningTasksCount() - 1);
}
LOG.infov("ECS task {0} reconciled to STOPPED (all containers exited)", taskArn);
}
void reconcileServices() {
for (Map.Entry<String, EcsServiceModel> entry : services.entrySet()) {
try {
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ExposedPort;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -145,11 +146,39 @@ public class EcsContainerManager {
* Stops and removes all Docker containers for a task.
*/
public void stopTask(EcsTaskHandle handle) {
stopTaskAndCollectExitCodes(handle);
}
/**
* Closes log streams and removes already-stopped containers without re-inspecting exit codes.
* Use this from the reconciler when exit codes have already been collected.
*/
public void cleanupStoppedTask(EcsTaskHandle handle) {
if (handle == null) {
return;
}
for (Closeable logStream : handle.getLogStreams()) {
try {
logStream.close();
} catch (Exception ignored) {
}
}
for (String dockerId : handle.getContainerIds().values()) {
lifecycleManager.stopAndRemove(dockerId, null);
}
}
/**
* Stops all containers, captures their exit codes, then removes them.
* Stop happens before inspect so the exit code reflects the actual stop
* signal (e.g. 137 for SIGKILL), not a stale pre-stop value.
*/
public Map<String, Integer> stopTaskAndCollectExitCodes(EcsTaskHandle handle) {
Map<String, Integer> exitCodes = new LinkedHashMap<>();
if (handle == null) {
return exitCodes;
}
// Close all log streams first
for (Closeable logStream : handle.getLogStreams()) {
try {
logStream.close();
@@ -157,9 +186,49 @@ public class EcsContainerManager {
}
}
// Stop and remove all containers
// Phase 1: stop all containers (no-op for those already exited).
for (String dockerId : handle.getContainerIds().values()) {
try {
lifecycleManager.getDockerClient().stopContainerCmd(dockerId).withTimeout(5).exec();
} catch (NotFoundException ignored) {
} catch (Exception e) {
LOG.warnv("Error stopping ECS container {0}: {1}", dockerId, e.getMessage());
}
}
// Phase 2: inspect exit codes, then remove.
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
lifecycleManager.stopAndRemove(entry.getValue(), null);
String name = entry.getKey();
String dockerId = entry.getValue();
exitCodes.put(name, getExitCodeIfStopped(dockerId));
try {
lifecycleManager.getDockerClient().removeContainerCmd(dockerId).withForce(true).exec();
} catch (NotFoundException ignored) {
} catch (Exception e) {
LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage());
}
}
return exitCodes;
}
/**
* Returns the exit code of a container that has already stopped, or {@code null}
* if the container is still running or its state cannot be determined.
* A missing container (externally removed) is treated as a clean exit (code 0).
*/
public Integer getExitCodeIfStopped(String dockerId) {
try {
var inspect = lifecycleManager.getDockerClient().inspectContainerCmd(dockerId).exec();
if (Boolean.TRUE.equals(inspect.getState().getRunning())) {
return null;
}
Long code = inspect.getState().getExitCodeLong();
return code != null ? code.intValue() : null;
} catch (NotFoundException e) {
return 0;
} catch (Exception e) {
LOG.debugv("Could not inspect container {0}: {1}", dockerId, e.getMessage());
return null;
}
}