mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
6130fe9568
commit
6be18ea1ee
15 files changed
+680
-51
No files matched your search
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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: ""
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+15
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
+180
@@ -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;
|
||||
}
|
||||
}
|
||||
+137
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user