mirror of
https://github.com/floci-io/floci.git
synced 2026-11-28 16:11:48 -05:00
fix(ecs): retry teardown of redeployed task containers (#4280)
* fix(ecs): retry teardown of redeployed task containers * test(ecs): wait for explicit task stop in SDK compatibility test * fix(ecs): serialize teardown and align stop compatibility test * test(ecs): observe blocked concurrent stop without delay * fix(ecs): preserve unknown exits and serialize startup transition
This commit is contained in:
1 parent
ecc4b1a569
commit
76cc27f2f1
7 files changed
+552
-36
No files matched your search
@@ -1290,13 +1290,22 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
task.setPullStartedAt(Instant.now());
|
||||
EcsTaskHandle handle = containerManager.startTask(task, taskDef, containerOverrides, region);
|
||||
task.setPullStoppedAt(Instant.now());
|
||||
taskHandles.put(taskArn, handle);
|
||||
markTaskRunning(task);
|
||||
cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1);
|
||||
LOG.infov("Started ECS task (docker): {0}", taskArn);
|
||||
registerTaskWithLoadBalancers(task, cluster, region);
|
||||
if (eventPublisher != null) {
|
||||
eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region);
|
||||
boolean stopRequested;
|
||||
synchronized (task) {
|
||||
taskHandles.put(taskArn, handle);
|
||||
markTaskRunning(task);
|
||||
cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1);
|
||||
LOG.infov("Started ECS task (docker): {0}", taskArn);
|
||||
stopRequested = TaskStatus.STOPPED.name().equals(task.getDesiredStatus());
|
||||
if (!stopRequested) {
|
||||
registerTaskWithLoadBalancers(task, cluster, region);
|
||||
}
|
||||
if (eventPublisher != null) {
|
||||
eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region);
|
||||
}
|
||||
}
|
||||
if (stopRequested) {
|
||||
stopTask(cluster.getClusterName(), taskArn, task.getStoppedReason(), task.getStopCode(), region);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage());
|
||||
@@ -1659,30 +1668,52 @@ 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);
|
||||
synchronized (task) {
|
||||
return stopTaskLocked(task, reason, stopCode, region);
|
||||
}
|
||||
}
|
||||
|
||||
private EcsTask stopTaskLocked(EcsTask task, String reason, String stopCode, String region) {
|
||||
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
|
||||
return task;
|
||||
}
|
||||
task.setDesiredStatus(TaskStatus.STOPPED.name());
|
||||
task.setLastStatus(TaskStatus.STOPPING.name());
|
||||
task.setStoppingAt(Instant.now());
|
||||
task.setStoppedReason(reason != null ? reason : "Stopped by user");
|
||||
task.setStopCode(stopCode);
|
||||
task.bumpVersion();
|
||||
|
||||
deregisterTaskFromLoadBalancers(task, region);
|
||||
if (!TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
task.setDesiredStatus(TaskStatus.STOPPED.name());
|
||||
task.setLastStatus(TaskStatus.STOPPING.name());
|
||||
task.setStoppingAt(Instant.now());
|
||||
task.setStoppedReason(reason != null ? reason : "Stopped by user");
|
||||
task.setStopCode(stopCode);
|
||||
task.bumpVersion();
|
||||
deregisterTaskFromLoadBalancers(task, region);
|
||||
}
|
||||
|
||||
Map<String, Integer> exitCodes = Map.of();
|
||||
Map<String, Instant> finishedAt = Map.of();
|
||||
if (dockerMode) {
|
||||
EcsTaskHandle handle = taskHandles.remove(task.getTaskArn());
|
||||
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);
|
||||
} finally {
|
||||
retainUnresolvedLogHandle(task.getTaskArn(), handle);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Could not stop ECS task {0}; retrying on the next reconciliation tick",
|
||||
task.getTaskArn());
|
||||
return task;
|
||||
}
|
||||
if (handle != null) {
|
||||
finishedAt = handle.getFinishedAt();
|
||||
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);
|
||||
retainUnresolvedLogHandle(task.getTaskArn(), handle);
|
||||
finishedAt = handle.getFinishedAt();
|
||||
}
|
||||
|
||||
task.setLastStatus(TaskStatus.STOPPED.name());
|
||||
@@ -3900,6 +3931,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (task) {
|
||||
reconcileTaskLocked(taskArn, task);
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileTaskLocked(String taskArn, EcsTask task) {
|
||||
if (TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
stopTask(task.getClusterArn(), taskArn, task.getStoppedReason(), task.getStopCode(), taskRegion(task));
|
||||
return;
|
||||
}
|
||||
|
||||
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
|
||||
reconcileStoppedTask(taskArn);
|
||||
@@ -4045,6 +4086,37 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
private EcsTaskHandle recoverTaskHandle(EcsTask task, String region) {
|
||||
if (task.getContainers() == null || task.getContainers().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> containerIds = new LinkedHashMap<>();
|
||||
for (Container container : task.getContainers()) {
|
||||
String dockerId = container.getDockerId() != null
|
||||
? container.getDockerId() : container.getRuntimeId();
|
||||
if (dockerId == null) {
|
||||
return null;
|
||||
}
|
||||
containerIds.put(container.getName(), dockerId);
|
||||
}
|
||||
Map<String, Integer> stopTimeouts = new LinkedHashMap<>();
|
||||
try {
|
||||
TaskDefinition definition = resolveTaskDefinitionOrThrow(task.getTaskDefinitionArn(), region);
|
||||
for (ContainerDefinition container : definition.getContainerDefinitions()) {
|
||||
if (container.getStopTimeout() != null) {
|
||||
stopTimeouts.put(container.getName(), container.getStopTimeout());
|
||||
}
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv(e, "Could not load task definition for {0}; using the default container stop timeout",
|
||||
task.getTaskArn());
|
||||
}
|
||||
EcsTaskHandle recovered = new EcsTaskHandle(task.getTaskArn(), containerIds, Map.of(),
|
||||
null, task.getNetworkInterfaceId(), region, stopTimeouts);
|
||||
EcsTaskHandle existing = taskHandles.putIfAbsent(task.getTaskArn(), recovered);
|
||||
return existing != null ? existing : recovered;
|
||||
}
|
||||
|
||||
/**
|
||||
* DAEMON scheduling: exactly one task on each ACTIVE container instance of the cluster,
|
||||
* none anywhere else. {@code desiredCount} is derived from the instance count, as AWS
|
||||
|
||||
+20
-3
@@ -1110,6 +1110,9 @@ public class EcsContainerManager {
|
||||
// period its container definition asked for.
|
||||
Set<String> terminatedContainerIds = new HashSet<>();
|
||||
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
|
||||
if (handle.isContainerRemoved(entry.getKey())) {
|
||||
continue;
|
||||
}
|
||||
String dockerId = entry.getValue();
|
||||
try {
|
||||
lifecycleManager.getDockerClient().stopContainerCmd(dockerId)
|
||||
@@ -1126,24 +1129,38 @@ public class EcsContainerManager {
|
||||
// Phase 2: inspect exit codes, then remove.
|
||||
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
if (handle.isContainerRemoved(name)) {
|
||||
exitCodes.put(name, handle.getRecordedExitCode(name));
|
||||
continue;
|
||||
}
|
||||
String dockerId = entry.getValue();
|
||||
exitCodes.put(name, getExitCodeIfStopped(dockerId));
|
||||
Integer exitCode = handle.getRecordedExitCode(name);
|
||||
if (exitCode == null) {
|
||||
exitCode = getExitCodeIfStopped(dockerId);
|
||||
handle.recordExitCode(name, exitCode);
|
||||
}
|
||||
exitCodes.put(name, exitCode);
|
||||
// Read before the removal below, which is the last moment the daemon still knows it.
|
||||
handle.recordFinishedAt(name, getFinishedAtIfStopped(dockerId));
|
||||
try {
|
||||
lifecycleManager.getDockerClient().removeContainerCmd(dockerId).withForce(true).exec();
|
||||
terminatedContainerIds.add(dockerId);
|
||||
handle.recordContainerRemoved(name);
|
||||
} catch (NotFoundException ignored) {
|
||||
terminatedContainerIds.add(dockerId);
|
||||
handle.recordContainerRemoved(name);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage());
|
||||
exitCodes.put(name, null);
|
||||
}
|
||||
}
|
||||
// A force removal terminates Docker's follow-log transport even when the preceding stop failed.
|
||||
// Preserve handles for any container that still may be running after both operations failed.
|
||||
terminatedContainerIds.forEach(dockerId -> finalizeLogStream(handle, dockerId));
|
||||
cleanupProtectedNetwork(handle);
|
||||
removeFirelensVolume(handle);
|
||||
if (handle.allContainersRemoved()) {
|
||||
cleanupProtectedNetwork(handle);
|
||||
removeFirelensVolume(handle);
|
||||
}
|
||||
return exitCodes;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Holds the runtime Docker container IDs for a running ECS task.
|
||||
@@ -34,6 +36,10 @@ public class EcsTaskHandle {
|
||||
* removed, so the time has to be kept here for the caller that stamps the task's containers.
|
||||
*/
|
||||
private final Map<String, Instant> finishedAt = new LinkedHashMap<>();
|
||||
/** Exit codes read before Docker removes a container, retained across teardown retries. */
|
||||
private final Map<String, Integer> exitCodes = new LinkedHashMap<>();
|
||||
/** Container names confirmed removed, including those whose exit code was unavailable. */
|
||||
private final Set<String> removedContainers = new HashSet<>();
|
||||
|
||||
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
|
||||
Map<String, Closeable> logStreamsByContainerId) {
|
||||
@@ -85,6 +91,28 @@ public class EcsTaskHandle {
|
||||
return finishedAt;
|
||||
}
|
||||
|
||||
public Integer getRecordedExitCode(String containerName) {
|
||||
return exitCodes.get(containerName);
|
||||
}
|
||||
|
||||
public void recordExitCode(String containerName, Integer exitCode) {
|
||||
if (exitCode != null) {
|
||||
exitCodes.putIfAbsent(containerName, exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
public void recordContainerRemoved(String containerName) {
|
||||
removedContainers.add(containerName);
|
||||
}
|
||||
|
||||
public boolean isContainerRemoved(String containerName) {
|
||||
return removedContainers.contains(containerName);
|
||||
}
|
||||
|
||||
public boolean allContainersRemoved() {
|
||||
return removedContainers.containsAll(containerIds.keySet());
|
||||
}
|
||||
|
||||
/** Removes and returns the log stream that no longer needs task-level ownership. */
|
||||
public Closeable removeLogStream(String containerId) {
|
||||
return logStreamsByContainerId.remove(containerId);
|
||||
|
||||
Reference in new issue
Block a user