diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 7dae9a7d1a..ceb5501e0a 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -614,6 +614,7 @@ Configuration resource reads and `ListFunctionsByCodeSigningConfig` return |---|---|---| | `FLOCI_SERVICES_LAMBDA_ENABLED` | `true` | Enable or disable the service | | `FLOCI_SERVICES_LAMBDA_EPHEMERAL` | `false` | Remove containers after each invocation | +| `FLOCI_SERVICES_LAMBDA_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | Reclaim owned Docker containers from previous runs at startup and retry incomplete cleanup on cold starts; disable when deployments share the same owner identity | | `FLOCI_SERVICES_LAMBDA_HONOUR_ARCHITECTURES` | `false` | Select each function's declared architecture for Docker image pulls and containers | | `FLOCI_SERVICES_LAMBDA_DEFAULT_MEMORY_MB` | `128` | Default function memory (MB) | | `FLOCI_SERVICES_LAMBDA_DEFAULT_TIMEOUT_SECONDS` | `3` | Default function timeout (seconds) | @@ -682,6 +683,21 @@ Configuration resource reads and `ListFunctionsByCodeSigningConfig` return finishes or fails. It runs no Lambda code; actual execution environments retain their normal shutdown and extension-drain behavior. +!!! note "Cleanup after an unclean Docker shutdown" + At startup, Floci removes running and exited Lambda containers left by a previous run, + including temporary code-copy helpers. Cleanup is scoped to the Docker resource namespace + and Floci API port, and preserves containers from the current run and named code volumes. + If Docker is unavailable or removal fails, the next cold start retries cleanup. + + This applies to containers created with ownership and run labels. Containers from older + versions without those labels are left alone because their deployment cannot be identified + safely. Use distinct `FLOCI_DOCKER_RESOURCE_NAMESPACE` values for deployments sharing a daemon. + + If two deployments must share the same namespace and API port, set + `FLOCI_SERVICES_LAMBDA_RECONCILE_CONTAINERS_ON_STARTUP=false` to disable both startup cleanup + and cold-start retries. Cleanup is enabled by default. Each distinct Docker listing or removal + failure warns once; repeated failures log at DEBUG until cleanup recovers. + !!! note "Bounding warm containers" After an invocation the container stays warm so the next call skips the cold start, and is reaped only after `container-idle-timeout-seconds` of inactivity. Each function keeps up to diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index a3982dfc80..7fb233d947 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -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}. diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerReconciler.java b/src/main/java/io/floci/aws/core/common/docker/ContainerReconciler.java new file mode 100644 index 0000000000..7df92629e3 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerReconciler.java @@ -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 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 filter, Predicate isLeftover) { + if (!filter.containsKey(ContainerStorageHelper.SERVICE_LABEL) + || !filter.containsKey(ContainerStorageHelper.OWNER_LABEL)) { + throw new IllegalArgumentException("Container reconciliation requires service and owner labels"); + } + List 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 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; + } +} diff --git a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java index 1ae5809630..7fb9216a30 100644 --- a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java @@ -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 leftoverRemovalFailuresReported = ConcurrentHashMap.newKeySet(); + private final ContainerReconciler containerReconciler; private volatile boolean leftoverTaskVolumeListFailureReported; private final Set 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 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 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. */ diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java index 46b590ccbd..872941a358 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java @@ -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 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 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 diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaContainerReconciler.java b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaContainerReconciler.java new file mode 100644 index 0000000000..0d8747db0c --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaContainerReconciler.java @@ -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 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); + }); + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducer.java b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducer.java index 2f00651e7d..2763448fbc 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducer.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducer.java @@ -38,6 +38,14 @@ public class LambdaRuntimeLauncherProducer { } } + void reconcileDockerContainers(@Observes StartupEvent event, EmulatorConfig config, + Instance docker) { + if (config.services().lambda().enabled() && config.services().lambda().reconcileContainersOnStartup() + && requireValidExecutor(config).equals("docker")) { + docker.get().removeLeftoverContainers(); + } + } + @Produces @ApplicationScoped LambdaRuntimeLauncher launcher(EmulatorConfig config, diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d7d1904997..a14a1b4aaa 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -442,6 +442,7 @@ floci: enabled: true lambda: enabled: true + reconcile-containers-on-startup: true # FLOCI_SERVICES_LAMBDA_RECONCILE_CONTAINERS_ON_STARTUP ephemeral: false # Extra Docker create flags for Lambda containers, for example: --env KEY=VALUE --volume /host:/container:ro docker-flags: "" diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerReconcilerTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerReconcilerTest.java new file mode 100644 index 0000000000..20214dbcb7 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerReconcilerTest.java @@ -0,0 +1,94 @@ +package io.floci.aws.core.common.docker; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.model.Container; +import io.floci.aws.testutil.LogCapture; +import org.jboss.logging.Logger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ContainerReconcilerTest { + + private static final Map FILTER = Map.of( + ContainerStorageHelper.SERVICE_LABEL, "ecs", ContainerStorageHelper.OWNER_LABEL, "alpha/4566"); + private ContainerLifecycleManager lifecycle; + private ListContainersCmd list; + private ContainerReconciler reconciler; + + @BeforeEach + void setUp() { + lifecycle = mock(ContainerLifecycleManager.class); + DockerClient client = mock(DockerClient.class); + list = mock(ListContainersCmd.class, RETURNS_SELF); + when(lifecycle.getDockerClient()).thenReturn(client); + when(client.listContainersCmd()).thenReturn(list); + reconciler = new ContainerReconciler(lifecycle, Logger.getLogger(ContainerReconcilerTest.class)); + } + + @Test + void listingWarnsOnceAndReportsAgainAfterRecovery() { + RuntimeException failure = new IllegalStateException("offline", new IllegalStateException("daemon refused")); + when(list.exec()).thenThrow(failure); + List records = LogCapture.capture(ContainerReconcilerTest.class, () -> { + assertFalse(reconciler.reconcile(FILTER, container -> true)); + assertFalse(reconciler.reconcile(FILTER, container -> true)); + doReturn(List.of()).when(list).exec(); + assertTrue(reconciler.reconcile(FILTER, container -> true)); + doThrow(failure).when(list).exec(); + assertFalse(reconciler.reconcile(FILTER, container -> true)); + }); + assertEquals(List.of(Level.WARNING.intValue(), Level.FINE.intValue(), Level.WARNING.intValue()), + records.stream().map(record -> record.getLevel().intValue()).toList()); + assertTrue(records.stream().allMatch(record -> record.getThrown() == failure)); + verify(lifecycle, never()).removeIfExistsStrict(anyString(), anyBoolean()); + } + + @Test + void removalWarnsOncePerContainerAndReportsAgainAfterSuccessfulRemoval() { + Container alpha = container("alpha"); + Container beta = container("beta"); + when(list.exec()).thenReturn(List.of(alpha, beta)); + RuntimeException failure = new IllegalStateException("busy", new IllegalStateException("daemon refused")); + doThrow(failure).when(lifecycle).removeIfExistsStrict(anyString(), eq(true)); + List records = LogCapture.capture(ContainerReconcilerTest.class, () -> { + assertFalse(reconciler.reconcile(FILTER, container -> true)); + assertFalse(reconciler.reconcile(FILTER, container -> true)); + doNothing().when(lifecycle).removeIfExistsStrict("alpha", true); + assertFalse(reconciler.reconcile(FILTER, container -> true)); + doThrow(failure).when(lifecycle).removeIfExistsStrict("alpha", true); + assertFalse(reconciler.reconcile(FILTER, container -> true)); + }); + List failures = records.stream().filter(record -> record.getThrown() != null).toList(); + assertEquals(List.of(Level.WARNING.intValue(), Level.WARNING.intValue(), Level.FINE.intValue(), + Level.FINE.intValue(), Level.FINE.intValue(), Level.WARNING.intValue(), Level.FINE.intValue()), + failures.stream().map(record -> record.getLevel().intValue()).toList()); + assertTrue(failures.stream().allMatch(record -> record.getThrown() == failure)); + verify(lifecycle, times(4)).removeIfExistsStrict("alpha", true); + verify(lifecycle, times(4)).removeIfExistsStrict("beta", true); + } + + @Test + void filtersMustIdentifyBothServiceAndOwner() { + assertThrows(IllegalArgumentException.class, () -> reconciler.reconcile(Map.of("io.floci.service", "ecs"), + container -> true)); + assertThrows(IllegalArgumentException.class, () -> reconciler.reconcile(Map.of("io.floci.owner", "alpha/4566"), + container -> true)); + verifyNoInteractions(lifecycle); + } + + private static Container container(String id) { + Container container = mock(Container.class); + when(container.getId()).thenReturn(id); + when(container.getLabels()).thenReturn(FILTER); + return container; + } +} diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java index afbe8c28d2..ce313ea22e 100644 --- a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerLifecycleTest.java @@ -267,6 +267,21 @@ class EcsContainerManagerLifecycleTest { verify(lifecycleManager, never()).removeIfExistsStrict(anyString(), eq(true)); } + @Test + void removeLeftoverContainersStillReclaimsOwnedLegacyContainersWithoutRunLabels() { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + Container unmarked = leftover("unmarked", Map.of("io.floci.service", "ecs", "io.floci.owner", "alpha/4566")); + Container foreign = leftover("foreign", Map.of("io.floci.service", "ecs", "io.floci.owner", "beta/4566")); + Container otherService = leftover("other-service", Map.of("io.floci.service", "lambda", + "io.floci.owner", "alpha/4566")); + stubLeftoverListing(lifecycle, Map.of("unmarked", unmarked, "foreign", foreign, + "other-service", otherService), Map.of()); + assertTrue(manager(lifecycle, namespacedConfig()).removeLeftoverContainers("current")); + verify(lifecycle).removeIfExistsStrict("unmarked", true); + verify(lifecycle, never()).removeIfExistsStrict("foreign", true); + verify(lifecycle, never()).removeIfExistsStrict("other-service", true); + } + @Test void previousRunVolumesAreRemovedAfterContainersAndFailedRemovalIsRetried() { ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java index 8dfae991bc..1b08ccb6e1 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java @@ -7,6 +7,7 @@ import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; import com.github.dockerjava.api.command.ExecCreateCmd; import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.command.ExecStartCmd; +import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.AccessMode; import com.github.dockerjava.api.model.Frame; @@ -80,6 +81,7 @@ import java.util.stream.Stream; import static io.floci.aws.testing.DockerDaemonVersionFixtures.stubDaemonVersion; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -127,6 +129,7 @@ class ContainerLauncherTest { when(config.services()).thenReturn(services); when(services.lambda()).thenReturn(lambda); + lenient().when(lambda.reconcileContainersOnStartup()).thenReturn(true); when(lambda.dockerNetwork()).thenReturn(Optional.empty()); lenient().when(lambda.extraHosts()).thenReturn(Optional.empty()); lenient().when(lambda.awsConfigPath()).thenReturn(Optional.empty()); @@ -174,6 +177,9 @@ class ContainerLauncherTest { new ContainerLifecycleManager.ContainerInfo("container-123", Map.of()); lenient().when(lifecycleManager.startCreated(eq("container-123"), any())).thenReturn(info); lenient().when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + ListContainersCmd inventory = mock(ListContainersCmd.class, RETURNS_SELF); + lenient().when(dockerClient.listContainersCmd()).thenReturn(inventory); + lenient().when(inventory.exec()).thenReturn(List.of()); // Stub the Docker copy chain so code and bootstrap archive copies // don't throw when the mock DockerClient is used. Each invocation @@ -604,10 +610,41 @@ class ContainerLauncherTest { verify(lifecycleManager, times(2)).create(any(ContainerSpec.class), platformCaptor.capture()); assertTrue(platformCaptor.getAllValues().stream() .allMatch("linux/arm64"::equals)); + ArgumentCaptor specs = ArgumentCaptor.forClass(ContainerSpec.class); + verify(lifecycleManager, times(2)).create(specs.capture(), anyString()); + for (ContainerSpec spec : specs.getAllValues()) { + assertEquals("4566", spec.labels().get("io.floci.owner")); + assertEquals("lambda", spec.labels().get("io.floci.service")); + assertNotNull(spec.labels().get("io.floci.lambda.run")); + } + assertEquals(specs.getAllValues().getFirst().labels().get("io.floci.lambda.run"), + specs.getAllValues().getLast().labels().get("io.floci.lambda.run")); } - @Test - void launchFunction_labelsContainerWithResourceIdentity() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void coldStartRetriesAFailedStartupSweepOnlyWhenEnabled(boolean enabled) throws Exception { + when(config.services().lambda().reconcileContainersOnStartup()).thenReturn(enabled); + ListContainersCmd inventory = dockerClient.listContainersCmd(); + lenient().when(inventory.exec()).thenThrow(new IllegalStateException("daemon unavailable")) + .thenReturn(List.of()); + launcher.removeLeftoverContainers(); + + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName("retry-cleanup"); + fn.setRuntime("nodejs20.x"); + fn.setHandler("index.handler"); + fn.setCodeLocalPath(Files.createDirectory(tempDir.resolve("code")).toString()); + launcher.launch(fn); + launcher.removeLeftoverContainers(); + + verify(inventory, times(enabled ? 3 : 0)).exec(); + } + + @ParameterizedTest + @ValueSource(strings = {"", "--label io.floci.owner=foreign --label io.floci.lambda.run=forged --label io.floci.service=ecs"}) + void launchFunction_labelsContainerWithResourceIdentity(String flags) throws Exception { + when(config.services().lambda().dockerFlags()).thenReturn(Optional.of(flags)); Path codePath = Files.createDirectory(tempDir.resolve("code")); LambdaFunction fn = new LambdaFunction(); @@ -620,12 +657,17 @@ class ContainerLauncherTest { launcher.launch(fn); ContainerSpec spec = captureRealContainerSpec(); + assertEquals("4566", spec.labels().get("io.floci.owner")); + assertNotNull(spec.labels().get("io.floci.lambda.run")); + assertNotEquals("forged", spec.labels().get("io.floci.lambda.run")); assertEquals(Map.of( "io.floci", "aws", "io.floci.service", "lambda", "io.floci.resource-id", "standard-fn", "io.floci.account", "222222222222", - "io.floci.region", "us-west-2"), + "io.floci.region", "us-west-2", + "io.floci.owner", "4566", + "io.floci.lambda.run", spec.labels().get("io.floci.lambda.run")), spec.labels()); } diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/LambdaContainerReconcilerTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/LambdaContainerReconcilerTest.java new file mode 100644 index 0000000000..1f831512cb --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/launcher/LambdaContainerReconcilerTest.java @@ -0,0 +1,180 @@ +package io.floci.aws.services.lambda.launcher; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.model.Container; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.testutil.LogCapture; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.*; + +class LambdaContainerReconcilerTest { + + private ContainerLifecycleManager lifecycle; + private ListContainersCmd list; + private EmulatorConfig config; + private LambdaContainerReconciler reconciler; + + @BeforeEach + void setUp() { + config = mock(EmulatorConfig.class); + EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class); + when(config.docker()).thenReturn(docker); + when(docker.resourceNamespace()).thenReturn(Optional.of("deployment-a")); + when(config.port()).thenReturn(4566); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class); + when(config.services()).thenReturn(services); + when(services.lambda()).thenReturn(lambda); + when(lambda.reconcileContainersOnStartup()).thenReturn(true); + lifecycle = mock(ContainerLifecycleManager.class); + DockerClient client = mock(DockerClient.class); + list = mock(ListContainersCmd.class, RETURNS_SELF); + when(lifecycle.getDockerClient()).thenReturn(client); + when(client.listContainersCmd()).thenReturn(list); + when(list.exec()).thenReturn(List.of()); + reconciler = new LambdaContainerReconciler(config, lifecycle); + } + + @Test + void labelsIdentifyTheDeploymentAndDistinguishRuns() { + Map labels = reconciler.ownershipLabels(); + assertEquals("deployment-a/4566", labels.get(ContainerStorageHelper.OWNER_LABEL)); + assertEquals("lambda", labels.get(ContainerStorageHelper.SERVICE_LABEL)); + assertNotEquals(labels.get(LambdaContainerReconciler.RUN_LABEL), + new LambdaContainerReconciler(config, lifecycle).ownershipLabels().get(LambdaContainerReconciler.RUN_LABEL)); + } + + @Test + void removesOnlyOwnedMarkedLambdaContainersFromPreviousRuns() { + Container old = container("old", Map.of()); + Container current = container("current", reconciler.ownershipLabels()); + Container sibling = container("sibling", Map.of(ContainerStorageHelper.OWNER_LABEL, "deployment-b/4566")); + Container otherPort = container("other-port", Map.of(ContainerStorageHelper.OWNER_LABEL, "deployment-a/4567")); + Container otherService = container("ecs", Map.of(ContainerStorageHelper.SERVICE_LABEL, "ecs")); + Container unowned = container("unowned", Map.of()); + unowned.getLabels().remove(ContainerStorageHelper.OWNER_LABEL); + Container unmarked = container("unmarked", Map.of()); + unmarked.getLabels().remove(LambdaContainerReconciler.RUN_LABEL); + Container contradictory = container("conflict", Map.of("floci_owner_port", "deployment-b/4566")); + Container legacyOwner = container("legacy-owner", Map.of("floci_owner_port", "deployment-a/4566")); + legacyOwner.getLabels().remove(ContainerStorageHelper.OWNER_LABEL); + when(list.exec()).thenReturn(List.of(old, current, sibling, otherPort, otherService, unowned, unmarked, + contradictory, legacyOwner)); + + reconciler.reconcile(); + reconciler.reconcile(); + + verify(lifecycle).removeIfExistsStrict("old", true); + verify(lifecycle).removeIfExistsStrict("legacy-owner", true); + verify(lifecycle, times(2)).getDockerClient(); + verifyNoMoreInteractions(lifecycle); + verify(list, times(2)).withShowAll(true); + verify(list).withLabelFilter(Map.of(ContainerStorageHelper.SERVICE_LABEL, "lambda", + ContainerStorageHelper.OWNER_LABEL, "deployment-a/4566")); + verify(list).withLabelFilter(Map.of(ContainerStorageHelper.SERVICE_LABEL, "lambda", + "floci_owner_port", "deployment-a/4566")); + } + + @Test + void failedInventoryIsRetriedWithoutRemovingAnythingFromAPartialList() { + Container old = container("old", Map.of()); + when(list.exec()).thenReturn(List.of(old)).thenThrow(new IllegalStateException("daemon unavailable")) + .thenReturn(List.of(old)); + reconciler.reconcile(); + verify(lifecycle, never()).removeIfExistsStrict(anyString(), anyBoolean()); + reconciler.reconcile(); + verify(lifecycle).removeIfExistsStrict("old", true); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void nullInventoryIsNotTreatedAsAnEmptySuccessfulSweep(boolean secondQuery) { + Container old = container("old", Map.of()); + if (secondQuery) { + when(list.exec()).thenReturn(List.of(old)).thenReturn(null).thenReturn(List.of(old)); + } else { + when(list.exec()).thenReturn(null).thenReturn(List.of(old)); + } + reconciler.reconcile(); + verify(lifecycle, never()).removeIfExistsStrict(anyString(), anyBoolean()); + reconciler.reconcile(); + verify(lifecycle).removeIfExistsStrict("old", true); + } + + @Test + void removalFailureDoesNotSkipOtherContainersAndIsRetried() { + List containers = List.of(container("first", Map.of()), container("second", Map.of()), + container("current", reconciler.ownershipLabels())); + when(list.exec()).thenReturn(containers); + doThrow(new IllegalStateException("busy")).doNothing().when(lifecycle).removeIfExistsStrict("first", true); + reconciler.reconcile(); + verify(lifecycle).removeIfExistsStrict("second", true); + reconciler.reconcile(); + verify(lifecycle, times(2)).removeIfExistsStrict("first", true); + verify(lifecycle, never()).removeIfExistsStrict("current", true); + } + + @Test + void disabledCleanupNeverInventoriesOrRemovesAnotherRunsContainers() { + when(config.services().lambda().reconcileContainersOnStartup()).thenReturn(false); + reconciler.reconcile(); + verifyNoInteractions(lifecycle); + } + + @Test + void repeatedInventoryFailureWarnsOnceAndRetainsItsCause() { + RuntimeException failure = new IllegalStateException("offline", new IllegalStateException("daemon refused")); + when(list.exec()).thenThrow(failure); + List records = LogCapture.capture(LambdaContainerReconciler.class, () -> { + reconciler.reconcile(); + reconciler.reconcile(); + }); + assertEquals(List.of(Level.WARNING.intValue(), Level.FINE.intValue()), + records.stream().map(record -> record.getLevel().intValue()).toList()); + assertSame(failure, records.getFirst().getThrown()); + } + + @Test + void repeatedRemovalFailureWarnsOnceAndRetainsItsCause() { + Container old = container("old", Map.of()); + when(list.exec()).thenReturn(List.of(old)); + RuntimeException failure = new IllegalStateException("busy", new IllegalStateException("daemon refused")); + doThrow(failure).when(lifecycle).removeIfExistsStrict("old", true); + List records = LogCapture.capture(LambdaContainerReconciler.class, () -> { + reconciler.reconcile(); + reconciler.reconcile(); + }); + assertEquals(List.of(Level.WARNING.intValue(), Level.FINE.intValue()), + records.stream().map(record -> record.getLevel().intValue()).toList()); + assertSame(failure, records.getFirst().getThrown()); + } + + private static Container container(String id, Map overrides) { + Container container = mock(Container.class); + Map labels = new HashMap<>(Map.of( + ContainerStorageHelper.SERVICE_LABEL, "lambda", + ContainerStorageHelper.OWNER_LABEL, "deployment-a/4566", + LambdaContainerReconciler.RUN_LABEL, "previous-run")); + labels.putAll(overrides); + when(container.getId()).thenReturn(id); + when(container.getLabels()).thenReturn(labels); + return container; + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/LambdaLeftoverContainersDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/LambdaLeftoverContainersDockerIntegrationTest.java new file mode 100644 index 0000000000..4d2d5b139c --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/launcher/LambdaLeftoverContainersDockerIntegrationTest.java @@ -0,0 +1,137 @@ +package io.floci.aws.services.lambda.launcher; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.core.command.WaitContainerResultCallback; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.services.lambda.model.LambdaFunction; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.TestImages; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestProfile(LambdaLeftoverContainersDockerIntegrationTest.LeftoversProfile.class) +class LambdaLeftoverContainersDockerIntegrationTest { + + @Inject + DockerClient docker; + @Inject + ContainerBuilder builder; + @Inject + ContainerLifecycleManager lifecycle; + @Inject + ContainerLauncher launcher; + @Inject + EmulatorConfig config; + @TempDir + Path code; + + @BeforeEach + void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), + "Docker daemon must be available for the Lambda leftover container test"); + } + + @Test + void nextRunRemovesRunningAndExitedLeftoversWithoutRemovingOtherOwnersOrNamedVolumes() throws Exception { + Files.writeString(code.resolve("index.js"), "exports.handler = async () => 'ok';"); + LambdaFunction function = new LambdaFunction(); + function.setFunctionName("leftover-" + UUID.randomUUID()); + function.setFunctionArn("arn:aws:lambda:us-east-1:000000000000:function:" + function.getFunctionName()); + function.setAccountId("000000000000"); + function.setRuntime("nodejs20.x"); + function.setHandler("index.handler"); + function.setCodeLocalPath(code.toString()); + + List fixtures = new ArrayList<>(); + String volume = "floci-lambda-leftover-test-" + UUID.randomUUID(); + ContainerHandle runtime = null; + docker.createVolumeCmd().withName(volume).exec(); + try { + runtime = launcher.launch(function); + Map labels = docker.inspectContainerCmd(runtime.getContainerId()).exec() + .getConfig().getLabels(); + assertEquals(ContainerStorageHelper.ownerIdentity(config), labels.get(ContainerStorageHelper.OWNER_LABEL)); + LambdaContainerReconciler nextRun = new LambdaContainerReconciler(config, lifecycle); + assertNotEquals(nextRun.ownershipLabels().get(LambdaContainerReconciler.RUN_LABEL), + labels.get(LambdaContainerReconciler.RUN_LABEL)); + + String exited = lifecycle.create(builder.newContainer(TestImages.BUSYBOX) + .withCmd(List.of("sh", "-c", "exit 1")) + .withLabels(labels).withNamedVolume(volume, "/code").build()); + fixtures.add(exited); + docker.startContainerCmd(exited).exec(); + assertEquals(1, docker.waitContainerCmd(exited).exec(new WaitContainerResultCallback()) + .awaitStatusCode(20, TimeUnit.SECONDS)); + String current = fixture(nextRun.ownershipLabels(), fixtures); + String sibling = fixture(Map.of(ContainerStorageHelper.SERVICE_LABEL, "lambda", + ContainerStorageHelper.OWNER_LABEL, "another-deployment/4566", + LambdaContainerReconciler.RUN_LABEL, "previous-run"), fixtures); + String unowned = fixture(Map.of(ContainerStorageHelper.SERVICE_LABEL, "lambda"), fixtures); + + nextRun.reconcile(); + + assertFalse(exists(runtime.getContainerId()), "a previous run's running runtime must go"); + assertFalse(exists(exited), "a previous run's Exited(1) helper must go"); + assertTrue(exists(current), "a runtime from the current run must stay"); + assertTrue(exists(sibling), "another deployment's container must stay"); + assertTrue(exists(unowned), "a legacy container without proven ownership must stay"); + assertEquals(volume, docker.inspectVolumeCmd(volume).exec().getName(), "named code volumes must stay"); + } finally { + if (runtime != null) { + launcher.stop(runtime); + } + for (String id : fixtures) { + lifecycle.removeIfExistsStrict(id, true); + } + docker.removeVolumeCmd(volume).exec(); + } + } + + private String fixture(Map labels, List fixtures) { + String id = lifecycle.create(builder.newContainer(TestImages.BUSYBOX) + .withCmd(List.of("sleep", "120")).withLabels(labels).build()); + fixtures.add(id); + return id; + } + + private boolean exists(String id) { + try { + docker.inspectContainerCmd(id).exec(); + return true; + } catch (NotFoundException expected) { + return false; // The sweep removed this exact test container. + } + } + + public static final class LeftoversProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.docker.resource-namespace", "lambda-leftovers-7731", + "floci.services.lambda.executor", "docker"); + } + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducerTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducerTest.java index dfb5d1d281..6fff84fa2c 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducerTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/LambdaRuntimeLauncherProducerTest.java @@ -39,6 +39,7 @@ class LambdaRuntimeLauncherProducerTest { lambda = mock(EmulatorConfig.LambdaServiceConfig.class); when(config.services()).thenReturn(services); when(services.lambda()).thenReturn(lambda); + when(lambda.reconcileContainersOnStartup()).thenReturn(true); when(dockerInstance.get()).thenReturn(containerLauncher); when(kubernetesInstance.get()).thenReturn(kubernetesPodLauncher); } @@ -92,4 +93,36 @@ class LambdaRuntimeLauncherProducerTest { .doesNotThrowAnyException(); verify(kubernetesPodLauncher).initializeClient(); } + + @Test + void startupReconcilesOnlyTheEnabledDockerExecutor() { + when(lambda.enabled()).thenReturn(true); + when(lambda.executor()).thenReturn("docker"); + producer.reconcileDockerContainers(new StartupEvent(), config, dockerInstance); + verify(containerLauncher).removeLeftoverContainers(); + verify(kubernetesInstance, never()).get(); + } + + @Test + void kubernetesStartupDoesNotInstantiateDocker() { + when(lambda.enabled()).thenReturn(true); + when(lambda.executor()).thenReturn("kubernetes"); + producer.reconcileDockerContainers(new StartupEvent(), config, dockerInstance); + verify(dockerInstance, never()).get(); + } + + @Test + void disabledLambdaDoesNotInstantiateDockerForCleanup() { + producer.reconcileDockerContainers(new StartupEvent(), config, dockerInstance); + verify(dockerInstance, never()).get(); + } + + @Test + void disabledReconciliationDoesNotInstantiateDockerForCleanup() { + when(lambda.enabled()).thenReturn(true); + when(lambda.executor()).thenReturn("docker"); + when(lambda.reconcileContainersOnStartup()).thenReturn(false); + producer.reconcileDockerContainers(new StartupEvent(), config, dockerInstance); + verify(dockerInstance, never()).get(); + } } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index cad28ec314..a3a6fbd6b7 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -155,6 +155,7 @@ floci: enabled: true lambda: enabled: true + reconcile-containers-on-startup: true container-drain-timeout-seconds: 15 docker-flags: "" honour-architectures: false