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

@@ -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<String, String> 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<LogRecord> 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<LogRecord> 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<LogRecord> 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;
}
}
@@ -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);
@@ -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<ContainerSpec> 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());
}
@@ -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<String, String> 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<Container> 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<LogRecord> 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<LogRecord> 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<String, String> overrides) {
Container container = mock(Container.class);
Map<String, String> 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;
}
}
@@ -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<String> 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<String, String> 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<String, String> labels, List<String> 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<String, String> getConfigOverrides() {
return Map.of("floci.docker.resource-namespace", "lambda-leftovers-7731",
"floci.services.lambda.executor", "docker");
}
}
}
@@ -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();
}
}