fix(lambda): remove containers orphaned by previous runs (#7734)

Label runtime and code-copy containers with protected deployment and run identities. Reconcile previous runs at Docker startup and retry incomplete cleanup on cold starts, preserving current environments and named volumes.

Honor the Lambda reconciliation switch at startup and before cold starts. Share the owned-container sweep with ECS, retaining each service run policy and reporting persistent failures once until recovery.
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-11-08 18:16:48 -04:00
1 parent 6130fe9568
commit 6be18ea1ee
15 files changed
+680 -51

No files matched your search

@@ -3091,6 +3091,15 @@ public interface EmulatorConfig {
@WithDefault("true")
boolean enabled();
/**
* Remove previous-run Docker Lambda containers at startup and retry incomplete cleanup
* on cold starts. Disable when deployments share a daemon and the same owner identity.
*
* Env var: FLOCI_SERVICES_LAMBDA_RECONCILE_CONTAINERS_ON_STARTUP
*/
@WithDefault("true")
boolean reconcileContainersOnStartup();
/**
* Registry host (optionally with a path prefix) that Lambda runtime images are pulled
* from, e.g. {@code public.ecr.aws} produces {@code public.ecr.aws/lambda/python:3.12}.
@@ -0,0 +1,77 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.api.model.Container;
import org.jboss.logging.Logger;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
/** Removes owned Docker leftovers, retaining each caller's run-label eligibility policy. */
public final class ContainerReconciler {
private static final ContainerStorageHelper.LabelAliases ALIASES = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
private final ContainerLifecycleManager lifecycleManager;
private final Logger log;
private final Set<String> removalFailuresReported = new HashSet<>();
private boolean listFailureReported;
public ContainerReconciler(ContainerLifecycleManager lifecycleManager, Logger log) {
this.lifecycleManager = lifecycleManager;
this.log = log;
}
/**
* Returns whether every eligible leftover was removed. Filters must identify a service and
* owner; both current and legacy label spellings are inventoried before anything is removed.
* Each failed listing or removal warns once, then logs at DEBUG until it recovers.
*/
public synchronized boolean reconcile(Map<String, String> filter, Predicate<Container> isLeftover) {
if (!filter.containsKey(ContainerStorageHelper.SERVICE_LABEL)
|| !filter.containsKey(ContainerStorageHelper.OWNER_LABEL)) {
throw new IllegalArgumentException("Container reconciliation requires service and owner labels");
}
List<Container> containers;
try {
containers = ALIASES.listByLabels(filter,
labels -> Objects.requireNonNull(lifecycleManager.getDockerClient().listContainersCmd()
.withShowAll(true).withLabelFilter(labels).exec(), "Missing Docker container inventory"),
Container::getId);
} catch (RuntimeException failure) {
log.logv(listFailureReported ? Logger.Level.DEBUG : Logger.Level.WARN, failure,
"Could not list leftover containers matching {0}", filter);
listFailureReported = true;
return false;
}
listFailureReported = false;
boolean complete = true;
for (Container container : containers) {
Map<String, String> labels = container.getLabels();
if (!ALIASES.consistent(container.getId(), labels)
|| !filter.entrySet().stream().allMatch(entry -> ALIASES.matches(labels,
entry.getKey(), entry.getValue()))
|| !isLeftover.test(container)) {
continue;
}
try {
lifecycleManager.removeIfExistsStrict(container.getId(), true);
removalFailuresReported.remove(container.getId());
log.infov("Removed {0} container {1} left by a previous run",
filter.get(ContainerStorageHelper.SERVICE_LABEL), container.getId());
} catch (RuntimeException failure) {
complete = false;
Logger.Level level = removalFailuresReported.add(container.getId())
? Logger.Level.WARN : Logger.Level.DEBUG;
log.logv(level, failure, "Could not remove leftover container {0}", container.getId());
}
}
if (complete) {
removalFailuresReported.clear();
}
return complete;
}
}
@@ -24,6 +24,7 @@ import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerReconciler;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
@@ -150,9 +151,7 @@ public class EcsContainerManager {
private final EfsService efsService;
// Stamped as RUN_LABEL on every container this process creates, so a sweep can tell its own apart.
private final String runId = UUID.randomUUID().toString();
// 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 final ContainerReconciler containerReconciler;
private volatile boolean leftoverTaskVolumeListFailureReported;
private final Set<String> leftoverTaskVolumeRemovalFailuresReported = ConcurrentHashMap.newKeySet();
@@ -193,6 +192,7 @@ public class EcsContainerManager {
this.credentialsProxy = credentialsProxy;
this.linkLocalAddresses = linkLocalAddresses;
this.efsService = efsService;
this.containerReconciler = new ContainerReconciler(lifecycleManager, LOG);
}
public EcsContainerManager(ContainerBuilder containerBuilder,
@@ -1246,51 +1246,11 @@ public class EcsContainerManager {
/** {@link #removeLeftoverContainers()} keeping only the containers of run {@code currentRunId}. */
public boolean removeLeftoverContainers(String currentRunId) {
String owner = ContainerStorageHelper.ownerIdentity(config);
ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
List<com.github.dockerjava.api.model.Container> containers;
try {
// Docker's container summary, not the ECS model Container this class imports.
containers = aliases.listByLabels(
Map.of(ContainerStorageHelper.SERVICE_LABEL, "ecs", ContainerStorageHelper.OWNER_LABEL, owner),
filter -> lifecycleManager.getDockerClient()
.listContainersCmd()
.withShowAll(true)
.withLabelFilter(filter)
.exec(),
com.github.dockerjava.api.model.Container::getId);
} catch (Exception e) {
LOG.logv(leftoverListFailureReported ? Logger.Level.DEBUG : Logger.Level.WARN,
"Could not list the ECS containers a previous run left behind: {0}", e.getMessage());
leftoverListFailureReported = true;
return false;
}
leftoverListFailureReported = false;
boolean allRemoved = true;
for (com.github.dockerjava.api.model.Container container : containers) {
Map<String, String> labels = container.getLabels();
if (!aliases.consistent(container.getId(), labels)
|| !aliases.matches(labels, ContainerStorageHelper.OWNER_LABEL, owner)
|| currentRunId.equals(aliases.labelValue(labels, RUN_LABEL))) {
continue;
}
try {
lifecycleManager.removeIfExistsStrict(container.getId(), true);
leftoverRemovalFailuresReported.remove(container.getId());
LOG.infov("Removed ECS container {0} ({1}) left by a previous run", container.getId(),
container.getNames() == null ? "" : String.join(",", container.getNames()));
} catch (Exception e) {
allRemoved = false;
Logger.Level level = leftoverRemovalFailuresReported.add(container.getId())
? Logger.Level.WARN : Logger.Level.DEBUG;
LOG.logv(level, "Could not remove ECS container {0} left by a previous run: {1}",
container.getId(), e.getMessage());
}
}
if (allRemoved) {
leftoverRemovalFailuresReported.clear();
}
return allRemoved;
return containerReconciler.reconcile(
Map.of(ContainerStorageHelper.SERVICE_LABEL, "ecs",
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)),
container -> !currentRunId.equals(ContainerStorageHelper.CONTAINER_LABEL_ALIASES
.labelValue(container.getLabels(), RUN_LABEL)));
}
/** Removes previous-run task volumes independently of the container launch gate. */
@@ -127,6 +127,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
private final LaunchedContainerAwsEnv awsEnv;
private final LambdaExecutionRoleCredentials executionRoleCredentials;
private final Ec2Service ec2Service;
private final LambdaContainerReconciler containerReconciler;
/** The VPC address each VpcConfig function's container holds, returned once it is removed. */
private final Map<String, VpcLease> vpcLeases = new ConcurrentHashMap<>();
@@ -155,6 +156,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
this.awsEnv = awsEnv;
this.executionRoleCredentials = executionRoleCredentials;
this.ec2Service = ec2Service;
this.containerReconciler = new LambdaContainerReconciler(config, lifecycleManager);
this.populateSemaphore = new Semaphore(resolvePopulateConcurrency(config));
}
@@ -173,6 +175,10 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
return launch(fn, false);
}
public void removeLeftoverContainers() {
containerReconciler.reconcile();
}
@Override
public boolean supportsProvisionedConcurrency() {
return true;
@@ -209,6 +215,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
}
removeLeftoverContainers();
// Start Runtime API server first so container can connect on boot
RuntimeApiServer runtimeApiServer = runtimeApiServerFactory.create();
runtimeApiServer.setFunctionMetadata(fn.getFunctionName(), fn.getVersion(), fn.getHandler(),
@@ -306,6 +313,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
"lambda", fn.getFunctionName(), lambdaAccountId, lambdaRegion));
List<String> configuredExtraHosts = config.services().lambda().extraHosts().orElse(List.of());
applyDockerFlags(specBuilder, dockerFlags);
specBuilder.withLabels(containerReconciler.ownershipLabels());
specBuilder.withEmbeddedDns();
// A container image's runtime is its own, Java as likely as any.
@@ -1054,6 +1062,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
.withEnv(List.of())
.withEntrypoint(List.of("sleep"))
.withCmd(List.of("3600"))
.withLabels(containerReconciler.ownershipLabels())
.withNamedVolume(volName, TASK_DIR, false);
ContainerSpec helperSpec = helperBuilder.build();
// Gate the heavy work (helper create + ~90MB tar copy) so a burst of first-time populates
@@ -0,0 +1,47 @@
package io.floci.aws.services.lambda.launcher;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerReconciler;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import org.jboss.logging.Logger;
import java.util.Map;
import java.util.UUID;
/** Reclaims this deployment's Lambda environments, which cannot survive their Runtime API server. */
final class LambdaContainerReconciler {
static final String RUN_LABEL = "io.floci.lambda.run";
private static final Logger LOG = Logger.getLogger(LambdaContainerReconciler.class);
private static final ContainerStorageHelper.LabelAliases ALIASES = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
private final EmulatorConfig config;
private final ContainerReconciler containers;
private final String owner;
private final String runId = UUID.randomUUID().toString();
private boolean reconciled;
LambdaContainerReconciler(EmulatorConfig config, ContainerLifecycleManager lifecycleManager) {
this.config = config;
this.containers = new ContainerReconciler(lifecycleManager, LOG);
this.owner = ContainerStorageHelper.ownerIdentity(config);
}
Map<String, String> ownershipLabels() {
return Map.of(ContainerStorageHelper.SERVICE_LABEL, "lambda",
ContainerStorageHelper.OWNER_LABEL, owner, RUN_LABEL, runId);
}
synchronized void reconcile() {
if (reconciled || !config.services().lambda().reconcileContainersOnStartup()) {
return;
}
reconciled = containers.reconcile(
Map.of(ContainerStorageHelper.SERVICE_LABEL, "lambda", ContainerStorageHelper.OWNER_LABEL, owner),
container -> {
String previousRun = ALIASES.labelValue(container.getLabels(), RUN_LABEL);
return previousRun != null && !previousRun.isBlank() && !runId.equals(previousRun);
});
}
}
@@ -38,6 +38,14 @@ public class LambdaRuntimeLauncherProducer {
}
}
void reconcileDockerContainers(@Observes StartupEvent event, EmulatorConfig config,
Instance<ContainerLauncher> docker) {
if (config.services().lambda().enabled() && config.services().lambda().reconcileContainersOnStartup()
&& requireValidExecutor(config).equals("docker")) {
docker.get().removeLeftoverContainers();
}
}
@Produces
@ApplicationScoped
LambdaRuntimeLauncher launcher(EmulatorConfig config,