mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(ecs): mount and clean up ephemeral task volumes (#5511)
* fix(ecs): mount and clean up ephemeral task volumes * fix(ecs): retry orphan volume cleanup independently * fix(ecs): quiet repeated orphan volume cleanup failures
This commit is contained in:
1 parent
f4c8237229
commit
760c38ef99
16 files changed
+1064
-40
No files matched your search
+11
-2
@@ -583,14 +583,23 @@ public class ContainerLifecycleManager {
|
||||
createVolumeIfAbsent(volumeName);
|
||||
}
|
||||
|
||||
/** Creates the named volume when it is missing; returns whether it was created. */
|
||||
/** Creates a volume with resource ownership labels for recoverable cleanup. */
|
||||
public void ensureVolume(String volumeName, Map<String, String> labels) {
|
||||
createVolumeIfAbsent(volumeName, labels);
|
||||
}
|
||||
|
||||
private boolean createVolumeIfAbsent(String volumeName) {
|
||||
return createVolumeIfAbsent(volumeName, Map.of());
|
||||
}
|
||||
|
||||
/** Creates the named volume when it is missing; returns whether it was created. */
|
||||
private boolean createVolumeIfAbsent(String volumeName, Map<String, String> labels) {
|
||||
if (volumeExists(volumeName)) {
|
||||
return false;
|
||||
}
|
||||
dockerClient.createVolumeCmd()
|
||||
.withName(volumeName)
|
||||
.withLabels(ContainerStorageHelper.defaultLabels(config))
|
||||
.withLabels(mergedLabels(labels))
|
||||
.exec();
|
||||
LOG.debugv("Created volume {0}", volumeName);
|
||||
return true;
|
||||
|
||||
@@ -1517,12 +1517,16 @@ public class EcsJsonHandler {
|
||||
private static final Set<String> VOLUME_CONSUMED = Set.of("name", "efsVolumeConfiguration");
|
||||
|
||||
private EfsVolumeConfiguration parseEfsVolumeConfiguration(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw new AwsException("InvalidParameterException", "EFS volume configuration must be an object.", 400);
|
||||
}
|
||||
String fileSystemId = node.path("fileSystemId").asText(null);
|
||||
if (fileSystemId == null) {
|
||||
return null;
|
||||
if (fileSystemId == null || fileSystemId.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"EFS volume configuration requires a fileSystemId.", 400);
|
||||
}
|
||||
Integer transitEncryptionPort = node.path("transitEncryptionPort").isNumber()
|
||||
? node.path("transitEncryptionPort").asInt() : null;
|
||||
|
||||
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsS
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
|
||||
import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;
|
||||
import io.github.hectorvent.floci.services.ecs.container.EcsTaskLaunchException;
|
||||
import io.github.hectorvent.floci.services.ecs.exec.EcsExecChannelHandler;
|
||||
import io.github.hectorvent.floci.services.ecs.exec.EcsExecSessionRegistry;
|
||||
import io.github.hectorvent.floci.services.ecs.exec.ExecSession;
|
||||
@@ -128,6 +129,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
private final Object reconcilerLock = new Object();
|
||||
// False until a previous run's task containers are confirmed gone; no task starts before.
|
||||
private volatile boolean leftoverContainersRemoved = true;
|
||||
private volatile boolean leftoverTaskVolumesRemoved;
|
||||
private volatile boolean leftoverContainersBlockReported;
|
||||
|
||||
// region::clusterName → EcsCluster
|
||||
@@ -138,8 +140,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
private Map<String, Integer> latestRevisions = new ConcurrentHashMap<>();
|
||||
// taskArn → EcsTask
|
||||
private final Map<String, EcsTask> tasks = new ConcurrentHashMap<>();
|
||||
// taskArn → EcsTaskHandle (running containers or unresolved log readers)
|
||||
// taskArn → EcsTaskHandle (running containers or pending resource cleanup)
|
||||
private final Map<String, EcsTaskHandle> taskHandles = new ConcurrentHashMap<>();
|
||||
private final Set<String> shutdownCleanupTasks = ConcurrentHashMap.newKeySet();
|
||||
// region::clusterName/serviceName → EcsServiceModel
|
||||
private Map<String, EcsServiceModel> services = new ConcurrentHashMap<>();
|
||||
private AccountAwareStorageBackend<EcsServiceModel> servicesStore;
|
||||
@@ -239,6 +242,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
this.containerManager = containerManager;
|
||||
this.dockerMode = !config.services().ecs().mock();
|
||||
this.sweepLeftoverContainers = dockerMode && config.services().ecs().reconcileContainersOnStartup();
|
||||
this.leftoverTaskVolumesRemoved = !sweepLeftoverContainers;
|
||||
this.baseUrl = config.effectiveBaseUrl();
|
||||
this.lbRegistrar = lbRegistrar;
|
||||
this.storageFactory = storageFactory;
|
||||
@@ -287,6 +291,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
void releasePreviousRunLeftovers() {
|
||||
if (sweepLeftoverContainers) {
|
||||
leftoverContainersRemoved = containerManager.removeLeftoverContainers();
|
||||
retryPreviousRunTaskVolumes();
|
||||
}
|
||||
if (lbRegistrar != null) {
|
||||
lbRegistrar.releaseRecordedTargets();
|
||||
@@ -384,8 +389,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
try {
|
||||
containerManager.stopTask(claimed);
|
||||
for (int attempt = 0; attempt < 2 && claimed.hasTaskVolumes(); attempt++) {
|
||||
containerManager.cleanupStoppedTask(claimed);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stop ECS task {0} on shutdown: {1}", taskArn, e.getMessage());
|
||||
} finally {
|
||||
if (claimed.hasTaskVolumes()) {
|
||||
taskHandles.put(taskArn, claimed);
|
||||
shutdownCleanupTasks.add(taskArn);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Task state is memory-only, so an ENI left behind here would outlive every task that
|
||||
@@ -1551,6 +1564,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
stopTask(cluster.getClusterName(), taskArn, task.getStoppedReason(), task.getStopCode(), region);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (e instanceof EcsTaskLaunchException failedLaunch) {
|
||||
retainPendingCleanupHandle(taskArn, failedLaunch.getHandle());
|
||||
}
|
||||
LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage());
|
||||
task.setLastStatus(TaskStatus.STOPPED.name());
|
||||
task.setDesiredStatus(TaskStatus.STOPPED.name());
|
||||
@@ -1983,7 +1999,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return task;
|
||||
}
|
||||
taskHandles.remove(task.getTaskArn(), handle);
|
||||
retainUnresolvedLogHandle(task.getTaskArn(), handle);
|
||||
retainPendingCleanupHandle(task.getTaskArn(), handle);
|
||||
finishedAt = handle.getFinishedAt();
|
||||
}
|
||||
|
||||
@@ -4716,6 +4732,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// ── Service Reconciliation ────────────────────────────────────────────────
|
||||
|
||||
void reconcile() {
|
||||
try {
|
||||
retryPreviousRunTaskVolumes();
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "ECS previous-run task volume cleanup failed: {0}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
reconcileTasks();
|
||||
} catch (Exception e) {
|
||||
@@ -4733,6 +4754,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
private void retryPreviousRunTaskVolumes() {
|
||||
if (sweepLeftoverContainers && leftoverContainersRemoved && !leftoverTaskVolumesRemoved) {
|
||||
leftoverTaskVolumesRemoved = containerManager.removeLeftoverTaskVolumes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a task may start: true once the containers a previous run left behind are gone,
|
||||
* retrying the sweep otherwise. It runs before every task launch, RunTask and StartTask
|
||||
@@ -4798,8 +4825,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
|
||||
private void reconcileTask(String taskArn) {
|
||||
if (shutdownCleanupTasks.contains(taskArn)) {
|
||||
reconcileStoppedTask(taskArn);
|
||||
return;
|
||||
}
|
||||
EcsTask task = tasks.get(taskArn);
|
||||
if (task == null) {
|
||||
reconcileStoppedTask(taskArn);
|
||||
return;
|
||||
}
|
||||
synchronized (task) {
|
||||
@@ -4854,6 +4886,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
// Close log streams and remove the stopped Docker containers without re-inspecting.
|
||||
containerManager.cleanupStoppedTask(claimed);
|
||||
retainPendingCleanupHandle(taskArn, claimed);
|
||||
|
||||
if (task.getContainers() != null) {
|
||||
task.getContainers().forEach(c -> {
|
||||
@@ -4961,14 +4994,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
containerManager.stopTaskAndCollectExitCodes(claimed);
|
||||
} finally {
|
||||
// A task can be reported STOPPED even if Docker rejected both teardown attempts.
|
||||
// Keep only the affected log readers and retry their teardown on later reconciliation ticks.
|
||||
retainUnresolvedLogHandle(taskArn, claimed);
|
||||
// Keep pending log readers and task volumes for later cleanup attempts.
|
||||
retainPendingCleanupHandle(taskArn, claimed);
|
||||
}
|
||||
}
|
||||
|
||||
private void retainUnresolvedLogHandle(String taskArn, EcsTaskHandle handle) {
|
||||
if (handle != null && handle.hasOpenLogStreams()) {
|
||||
private void retainPendingCleanupHandle(String taskArn, EcsTaskHandle handle) {
|
||||
if (handle != null && (handle.hasOpenLogStreams() || handle.hasTaskVolumes()
|
||||
|| !handle.allContainersRemoved())) {
|
||||
taskHandles.put(taskArn, handle);
|
||||
} else {
|
||||
shutdownCleanupTasks.remove(taskArn);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4986,8 +5022,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
containerIds.put(container.getName(), dockerId);
|
||||
}
|
||||
Map<String, Integer> stopTimeouts = new LinkedHashMap<>();
|
||||
Set<String> taskVolumeNames = Set.of();
|
||||
try {
|
||||
TaskDefinition definition = resolveTaskDefinitionOrThrow(task.getTaskDefinitionArn(), region);
|
||||
taskVolumeNames = containerManager.taskVolumeNames(task, definition);
|
||||
for (ContainerDefinition container : definition.getContainerDefinitions()) {
|
||||
if (container.getStopTimeout() != null) {
|
||||
stopTimeouts.put(container.getName(), container.getStopTimeout());
|
||||
@@ -4998,7 +5036,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
task.getTaskArn());
|
||||
}
|
||||
EcsTaskHandle recovered = new EcsTaskHandle(task.getTaskArn(), containerIds, Map.of(),
|
||||
null, task.getNetworkInterfaceId(), region, stopTimeouts);
|
||||
null, task.getNetworkInterfaceId(), region, stopTimeouts, taskVolumeNames);
|
||||
EcsTaskHandle existing = taskHandles.putIfAbsent(task.getTaskArn(), recovered);
|
||||
return existing != null ? existing : recovered;
|
||||
}
|
||||
|
||||
+138
-25
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.ecs.container;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.command.InspectVolumeResponse;
|
||||
import com.github.dockerjava.api.command.ListVolumesResponse;
|
||||
import com.github.dockerjava.api.command.StatsCmd;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
@@ -75,6 +77,7 @@ import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -144,6 +147,8 @@ public class EcsContainerManager {
|
||||
// A sweep failure is retried before each task launch; each distinct failure is a WARN once.
|
||||
private volatile boolean leftoverListFailureReported;
|
||||
private final Set<String> leftoverRemovalFailuresReported = ConcurrentHashMap.newKeySet();
|
||||
private volatile boolean leftoverTaskVolumeListFailureReported;
|
||||
private final Set<String> leftoverTaskVolumeRemovalFailuresReported = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Inject
|
||||
public EcsContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -230,15 +235,19 @@ public class EcsContainerManager {
|
||||
// name -> EFS configuration (materialised below as a shared local Docker volume).
|
||||
Map<String, String> volumeSourcePaths = new LinkedHashMap<>();
|
||||
Map<String, EfsVolumeConfiguration> efsVolumes = new LinkedHashMap<>();
|
||||
Map<String, String> ephemeralVolumes = new LinkedHashMap<>();
|
||||
Set<String> taskVolumeNames = new LinkedHashSet<>();
|
||||
if (taskDef.getVolumes() != null) {
|
||||
for (Volume v : taskDef.getVolumes()) {
|
||||
if (v.name() == null) {
|
||||
continue;
|
||||
}
|
||||
if (v.hostSourcePath() != null) {
|
||||
if (v.hostSourcePath() != null && !v.hostSourcePath().isBlank()) {
|
||||
volumeSourcePaths.put(v.name(), v.hostSourcePath());
|
||||
} else if (v.efs() != null) {
|
||||
efsVolumes.put(v.name(), v.efs());
|
||||
} else if (isEphemeralVolume(v)) {
|
||||
ephemeralVolumes.put(v.name(), taskVolumeName(task, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -299,6 +308,13 @@ public class EcsContainerManager {
|
||||
throw e;
|
||||
}
|
||||
|
||||
Map<String, Integer> stopTimeouts = new LinkedHashMap<>();
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
if (def.getStopTimeout() != null) {
|
||||
stopTimeouts.put(def.getName(), def.getStopTimeout());
|
||||
}
|
||||
}
|
||||
|
||||
String fluentHost = null;
|
||||
String networkModeName = taskDef.getNetworkMode() != null
|
||||
? taskDef.getNetworkMode().name()
|
||||
@@ -445,6 +461,7 @@ public class EcsContainerManager {
|
||||
}
|
||||
String sourcePath = volumeSourcePaths.get(mp.sourceVolume());
|
||||
EfsVolumeConfiguration efs = efsVolumes.get(mp.sourceVolume());
|
||||
String ephemeralVolume = ephemeralVolumes.get(mp.sourceVolume());
|
||||
if (sourcePath != null) {
|
||||
// Host volume: bind-mount an absolute path on the Docker host. Re-validate
|
||||
// here (not just at RegisterTaskDefinition time): this narrows the window
|
||||
@@ -460,6 +477,13 @@ public class EcsContainerManager {
|
||||
}
|
||||
} else if (efs != null) {
|
||||
mountEfsVolume(specBuilder, efs, mp);
|
||||
} else if (ephemeralVolume != null) {
|
||||
if (taskVolumeNames.add(ephemeralVolume)) {
|
||||
Map<String, String> labels = new LinkedHashMap<>(ownerLabels());
|
||||
labels.put(ContainerStorageHelper.SERVICE_LABEL, "ecs");
|
||||
lifecycleManager.ensureVolume(ephemeralVolume, labels);
|
||||
}
|
||||
specBuilder.withNamedVolume(ephemeralVolume, mp.containerPath(), mp.readOnly());
|
||||
} else {
|
||||
LOG.warnv("Skipping mountPoint with unresolved volume {0} on container {1}",
|
||||
mp.sourceVolume(), def.getName());
|
||||
@@ -497,6 +521,8 @@ public class EcsContainerManager {
|
||||
dockerId = info.containerId();
|
||||
}
|
||||
|
||||
containerIds.put(def.getName(), dockerId);
|
||||
|
||||
LOG.infov("Created ECS container {0} for task {1} container {2}", dockerId, taskId, def.getName());
|
||||
|
||||
// Resolve network bindings for ECS-specific model
|
||||
@@ -508,7 +534,6 @@ public class EcsContainerManager {
|
||||
metadataIdsByContainer.get(def.getName()));
|
||||
container.setImageDigest(imageDigestsByContainer.get(def.getName()));
|
||||
runtimeContainers.add(container);
|
||||
containerIds.put(def.getName(), dockerId);
|
||||
|
||||
// awsfirelens containers are shipped to Fluent Bit by Docker; don't also scrape json-file.
|
||||
// Only awslogs containers go to CloudWatch Logs; the others stay on the console.
|
||||
@@ -528,23 +553,16 @@ public class EcsContainerManager {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
boolean allRemoved = true;
|
||||
for (String dockerId : containerIds.values()) {
|
||||
if (!stopAndConfirmRemoved(dockerId)) {
|
||||
allRemoved = false;
|
||||
}
|
||||
}
|
||||
if (firelensVolumeName != null) {
|
||||
lifecycleManager.removeVolume(firelensVolumeName);
|
||||
}
|
||||
EcsTaskHandle partial = new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
|
||||
firelensVolumeName,
|
||||
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region,
|
||||
stopTimeouts, taskVolumeNames);
|
||||
cleanupStoppedTask(partial);
|
||||
if (protectedNetwork != null) {
|
||||
releaseTaskNetwork(task, region);
|
||||
}
|
||||
revokeTaskRoleCredentials(task.getTaskArn());
|
||||
// A container left behind by a failed removal is still on the network holding its
|
||||
// address, exactly as on the stop path.
|
||||
if (allRemoved) {
|
||||
releaseTaskLinkLocalAddresses(task.getTaskArn());
|
||||
if (!partial.allContainersRemoved() || partial.hasTaskVolumes() || partial.hasOpenLogStreams()) {
|
||||
throw new EcsTaskLaunchException(e, partial);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
@@ -577,16 +595,44 @@ public class EcsContainerManager {
|
||||
task.setDesiredStatus(TaskStatus.RUNNING.name());
|
||||
task.setStartedAt(Instant.now());
|
||||
|
||||
Map<String, Integer> stopTimeouts = new LinkedHashMap<>();
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
if (def.getStopTimeout() != null) {
|
||||
stopTimeouts.put(def.getName(), def.getStopTimeout());
|
||||
}
|
||||
}
|
||||
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
|
||||
firelensVolumeName,
|
||||
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region,
|
||||
stopTimeouts);
|
||||
stopTimeouts, taskVolumeNames);
|
||||
}
|
||||
|
||||
private String taskVolumeName(EcsTask task, Volume volume) {
|
||||
return ContainerStorageHelper.dockerName(config,
|
||||
"ecs-task-volume-" + Digests.sha256Hex(task.getTaskArn() + "|" + volume.name()));
|
||||
}
|
||||
|
||||
/** Reconstructs only task-owned volumes referenced by a container, without creating them. */
|
||||
public Set<String> taskVolumeNames(EcsTask task, TaskDefinition definition) {
|
||||
Set<String> referenced = new HashSet<>();
|
||||
for (ContainerDefinition container : definition.getContainerDefinitions()) {
|
||||
if (container.getMountPoints() != null) {
|
||||
container.getMountPoints().forEach(mount -> referenced.add(mount.sourceVolume()));
|
||||
}
|
||||
}
|
||||
Set<String> names = new LinkedHashSet<>();
|
||||
if (definition.getVolumes() != null) {
|
||||
for (Volume volume : definition.getVolumes()) {
|
||||
if (referenced.contains(volume.name()) && isEphemeralVolume(volume)) {
|
||||
names.add(taskVolumeName(task, volume));
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private static boolean isEphemeralVolume(Volume volume) {
|
||||
Map<String, Object> properties = volume.unparsed();
|
||||
return (volume.hostSourcePath() == null || volume.hostSourcePath().isBlank()) && volume.efs() == null
|
||||
&& (properties == null || (properties.get("efsVolumeConfiguration") == null
|
||||
&& properties.get("dockerVolumeConfiguration") == null
|
||||
&& properties.get("fsxWindowsFileServerVolumeConfiguration") == null
|
||||
&& properties.get("s3filesVolumeConfiguration") == null
|
||||
&& !Boolean.TRUE.equals(properties.get("configuredAtLaunch"))));
|
||||
}
|
||||
|
||||
/** A task-level {@code memory} is MiB as a plain number, or a {@code "1GB"}-style string. */
|
||||
@@ -1163,6 +1209,61 @@ public class EcsContainerManager {
|
||||
return allRemoved;
|
||||
}
|
||||
|
||||
/** Removes previous-run task volumes independently of the container launch gate. */
|
||||
public boolean removeLeftoverTaskVolumes() {
|
||||
return removeLeftoverTaskVolumes(runId);
|
||||
}
|
||||
|
||||
/** {@link #removeLeftoverTaskVolumes()} keeping volumes of {@code currentRunId}. */
|
||||
public boolean removeLeftoverTaskVolumes(String currentRunId) {
|
||||
String owner = ContainerStorageHelper.ownerIdentity(config);
|
||||
ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
|
||||
try {
|
||||
List<InspectVolumeResponse> volumes = aliases.listByLabels(
|
||||
Map.of(ContainerStorageHelper.SERVICE_LABEL, "ecs", ContainerStorageHelper.OWNER_LABEL, owner),
|
||||
filter -> {
|
||||
ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd()
|
||||
.withFilter("label", filter.entrySet().stream()
|
||||
.map(entry -> entry.getKey() + "=" + entry.getValue()).toList()).exec();
|
||||
if (response == null || response.getVolumes() == null) {
|
||||
throw new IllegalStateException("Docker returned no volume inventory");
|
||||
}
|
||||
return response.getVolumes();
|
||||
}, InspectVolumeResponse::getName);
|
||||
leftoverTaskVolumeListFailureReported = false;
|
||||
boolean allRemoved = true;
|
||||
for (InspectVolumeResponse volume : volumes) {
|
||||
Map<String, String> labels = volume.getLabels();
|
||||
String previousRun = aliases.labelValue(labels, RUN_LABEL);
|
||||
if (!aliases.consistent(volume.getName(), labels)
|
||||
|| !aliases.matches(labels, ContainerStorageHelper.SERVICE_LABEL, "ecs")
|
||||
|| !aliases.matches(labels, ContainerStorageHelper.OWNER_LABEL, owner)
|
||||
|| previousRun == null || currentRunId.equals(previousRun)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
lifecycleManager.removeVolumeStrict(volume.getName());
|
||||
leftoverTaskVolumeRemovalFailuresReported.remove(volume.getName());
|
||||
} catch (RuntimeException e) {
|
||||
allRemoved = false;
|
||||
Logger.Level level = leftoverTaskVolumeRemovalFailuresReported.add(volume.getName())
|
||||
? Logger.Level.WARN : Logger.Level.DEBUG;
|
||||
LOG.logv(level, "Could not remove ECS task volume {0} left by a previous run: {1}",
|
||||
volume.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
if (allRemoved) {
|
||||
leftoverTaskVolumeRemovalFailuresReported.clear();
|
||||
}
|
||||
return allRemoved;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.logv(leftoverTaskVolumeListFailureReported ? Logger.Level.DEBUG : Logger.Level.WARN,
|
||||
"Could not list ECS task volumes from a previous run: {0}", e.getMessage());
|
||||
leftoverTaskVolumeListFailureReported = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The ENI {@link #attachTaskNetwork} allocated for this task, or null if it is already gone. */
|
||||
private NetworkInterface existingTaskEni(EcsTask task, String region) {
|
||||
if (task.getNetworkInterfaceId() == null) {
|
||||
@@ -1274,8 +1375,10 @@ public class EcsContainerManager {
|
||||
return;
|
||||
}
|
||||
boolean allRemoved = true;
|
||||
for (String dockerId : handle.getContainerIds().values()) {
|
||||
if (!stopAndConfirmRemoved(dockerId)) {
|
||||
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
|
||||
if (stopAndConfirmRemoved(entry.getValue())) {
|
||||
handle.recordContainerRemoved(entry.getKey());
|
||||
} else {
|
||||
allRemoved = false;
|
||||
}
|
||||
}
|
||||
@@ -1285,6 +1388,7 @@ public class EcsContainerManager {
|
||||
removeFirelensVolume(handle);
|
||||
revokeTaskRoleCredentials(handle.getTaskArn());
|
||||
if (allRemoved) {
|
||||
removeTaskVolumes(handle);
|
||||
releaseTaskLinkLocalAddresses(handle.getTaskArn());
|
||||
}
|
||||
}
|
||||
@@ -1373,6 +1477,7 @@ public class EcsContainerManager {
|
||||
if (handle.allContainersRemoved()) {
|
||||
cleanupProtectedNetwork(handle);
|
||||
removeFirelensVolume(handle);
|
||||
removeTaskVolumes(handle);
|
||||
// Only now: a container that survived a failed removal still holds its address.
|
||||
releaseTaskLinkLocalAddresses(handle.getTaskArn());
|
||||
}
|
||||
@@ -1423,6 +1528,14 @@ public class EcsContainerManager {
|
||||
lifecycleManager.removeVolume(handle.getFirelensVolumeName());
|
||||
}
|
||||
|
||||
private void removeTaskVolumes(EcsTaskHandle handle) {
|
||||
for (String volumeName : handle.getTaskVolumeNames()) {
|
||||
if (lifecycleManager.removeVolume(volumeName)) {
|
||||
handle.recordTaskVolumeRemoved(volumeName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ContainerDefinition findFirelensRouter(List<ContainerDefinition> defs) {
|
||||
if (defs == null) {
|
||||
return null;
|
||||
|
||||
@@ -4,6 +4,7 @@ import java.io.Closeable;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -29,6 +30,7 @@ public class EcsTaskHandle {
|
||||
private final String firelensVolumeName;
|
||||
private final String networkInterfaceId;
|
||||
private final String region;
|
||||
private final Set<String> taskVolumeNames;
|
||||
/** Per-container {@code stopTimeout}, so teardown waits as long as the task definition asked. */
|
||||
private final Map<String, Integer> stopTimeouts;
|
||||
/**
|
||||
@@ -57,12 +59,21 @@ public class EcsTaskHandle {
|
||||
Map<String, Closeable> logStreamsByContainerId,
|
||||
String firelensVolumeName, String networkInterfaceId, String region,
|
||||
Map<String, Integer> stopTimeouts) {
|
||||
this(taskArn, containerIds, logStreamsByContainerId, firelensVolumeName,
|
||||
networkInterfaceId, region, stopTimeouts, Set.of());
|
||||
}
|
||||
|
||||
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
|
||||
Map<String, Closeable> logStreamsByContainerId,
|
||||
String firelensVolumeName, String networkInterfaceId, String region,
|
||||
Map<String, Integer> stopTimeouts, Set<String> taskVolumeNames) {
|
||||
this.taskArn = taskArn;
|
||||
this.containerIds = new LinkedHashMap<>(containerIds);
|
||||
this.logStreamsByContainerId = new LinkedHashMap<>(logStreamsByContainerId);
|
||||
this.firelensVolumeName = firelensVolumeName;
|
||||
this.networkInterfaceId = networkInterfaceId;
|
||||
this.region = region;
|
||||
this.taskVolumeNames = new LinkedHashSet<>(taskVolumeNames);
|
||||
this.stopTimeouts = new LinkedHashMap<>(stopTimeouts);
|
||||
}
|
||||
|
||||
@@ -72,6 +83,15 @@ public class EcsTaskHandle {
|
||||
public String getFirelensVolumeName() { return firelensVolumeName; }
|
||||
public String getNetworkInterfaceId() { return networkInterfaceId; }
|
||||
public String getRegion() { return region; }
|
||||
public Set<String> getTaskVolumeNames() { return Set.copyOf(taskVolumeNames); }
|
||||
|
||||
public void recordTaskVolumeRemoved(String volumeName) {
|
||||
taskVolumeNames.remove(volumeName);
|
||||
}
|
||||
|
||||
public boolean hasTaskVolumes() {
|
||||
return !taskVolumeNames.isEmpty();
|
||||
}
|
||||
|
||||
/** The container's {@code stopTimeout} in seconds, or {@link #DEFAULT_STOP_TIMEOUT_SECONDS}. */
|
||||
public int stopTimeoutFor(String containerName) {
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
/** A failed launch whose remaining resources still need teardown. */
|
||||
public class EcsTaskLaunchException extends AwsException {
|
||||
|
||||
private final EcsTaskHandle handle;
|
||||
|
||||
public EcsTaskLaunchException(Exception cause, EcsTaskHandle handle) {
|
||||
super(cause instanceof AwsException aws ? aws.getErrorCode() : "ClientException",
|
||||
cause.getMessage(), cause instanceof AwsException aws ? aws.getHttpStatus() : 400);
|
||||
initCause(cause);
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public EcsTaskHandle getHandle() {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,16 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A task-level volume in an ECS task definition. Two shapes are modelled:
|
||||
* A task-level volume in an ECS task definition. Three shapes are modelled:
|
||||
* <ul>
|
||||
* <li>A volume without a host source path or external configuration supplies ephemeral
|
||||
* storage shared by the containers in one task.</li>
|
||||
* <li>EC2-launch-type {@code host} volume: {@code {"name": ..., "host": {"sourcePath": ...}}};
|
||||
* {@code hostSourcePath} is the absolute path on the Docker host that the volume binds to.</li>
|
||||
* <li>{@code efsVolumeConfiguration} volume: {@code {"name": ..., "efsVolumeConfiguration": {...}}};
|
||||
* see {@link EfsVolumeConfiguration}.</li>
|
||||
* </ul>
|
||||
* The two are mutually exclusive. A container references the volume by {@code name} via a
|
||||
* The configurations are mutually exclusive. A container references the volume by {@code name} via a
|
||||
* {@link MountPoint}.
|
||||
*
|
||||
* <p>{@code unparsed} keeps the volume members Floci backs with nothing, which is the rest of
|
||||
|
||||
Reference in new issue
Block a user