Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(lambda): bound on-demand container shutdown (#6299)

Andre Kurait4a0650467a13
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index dc5ac781dd..c56aba835b 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -252,6 +252,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s
| `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` | `1000` | How often (ms) the SQS and Kinesis event source pollers check for new messages |
| `FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS` | `60` | Wait before the first retry of a failed asynchronous invocation (seconds); the second waits twice this, `0` retries back to back |
| `FLOCI_SERVICES_LAMBDA_CONTAINER_IDLE_TIMEOUT_SECONDS` | `300` | Seconds of inactivity before an idle Lambda container is removed |
+| `FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS` | `15` | Shared shutdown drain budget for Lambda containers; 1 through 300 seconds, invalid values fail initialization |
| `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION` | `max(4, cpus)` | Maximum idle (warm) containers kept per function; a container released beyond this is stopped |
| `FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL` | `0` | Maximum idle (warm) containers kept across all functions. Beyond it, the least-recently-used idle container of any function is stopped to make room for the one just released. `0` leaves the total unbounded; a negative value is ignored with a warning. See [Bounding warm containers](../services/lambda.md#bounding-warm-containers) |
| `FLOCI_SERVICES_LAMBDA_REGION_CONCURRENCY_LIMIT` | `1000` | Maximum concurrent Lambda invocations across all functions in a region |
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index 4f2545cdb7..b652f000e4 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -448,6 +448,26 @@ A layer ARN outside the caller's partition is refused whatever that setting says
isolated, so no resource policy can ever make such a layer readable, and `GetLayerVersionByArn`
rejects one outright with `InvalidParameterValueException: Invalid layer version ...`.
+## Container shutdown
+
+Shutdown drains on-demand containers concurrently within one
+`floci.services.lambda.container-drain-timeout-seconds` budget. The default is 15 seconds;
+set `FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS` when a larger fleet needs more
+time for Docker to finish removing stopped containers. Supported values are 1 through 300;
+invalid values fail initialization. The parent process's stop grace must exceed this
+budget. The destruction hook does not start another drain budget. Failed removals remain
+owned for a later retirement or reset retry; a completed removal is not repeated.
+A launch that outlasts the deadline is reported as incomplete cleanup. Its invocation is
+refused, and any returned container remains owned for a later cleanup retry; the deadline
+does not guarantee cancellation of an unresponsive container launcher.
+If an invocation finishes after the shutdown deadline, releasing its still-owned
+container starts a separate bounded cleanup attempt. This does not extend the
+initial shutdown wait.
+
+When using `floci-cli`, set `floci stop --timeout <seconds>` above the configured
+drain budget. The CLI currently defaults to 10 seconds, including for `floci restart`.
+For a longer drain, explicitly stop with the larger timeout and then start Floci.
+
## Not Implemented
These AWS Lambda operations have no handler in Floci. Calls will return `404` or an error:
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 0a6e1ed0e4..5e73ae33ea 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -2988,6 +2988,15 @@ public interface EmulatorConfig {
@WithDefault("300")
int containerIdleTimeoutSeconds();
+ /**
+ * One shutdown drain budget shared by on-demand Lambda containers.
+ * Values outside 1 through 300 seconds fail initialization.
+ *
+ * Env var: FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS
+ */
+ @WithDefault("15")
+ int containerDrainTimeoutSeconds();
+
/**
* Maximum idle (warm) containers kept per function. A container released when the
* function already holds this many idle ones is stopped instead of pooled.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index 6cc40f387f..fe0f1064c4 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -541,15 +541,19 @@ public class ContainerLifecycleManager {
* only once the container is gone; when removal fails it is left open for the retry.
*/
public void stopAndRemoveStrict(String containerId, Closeable logStream) {
- withTeardownSlot(() -> stopAndRemoveStrictAdmitted(containerId, logStream));
+ stopAndRemoveStrict(containerId, logStream, 5);
}
- private void stopAndRemoveStrictAdmitted(String containerId, Closeable logStream) {
+ public void stopAndRemoveStrict(String containerId, Closeable logStream, int stopTimeoutSeconds) {
+ withTeardownSlot(() -> stopAndRemoveStrictAdmitted(containerId, logStream, stopTimeoutSeconds));
+ }
+
+ private void stopAndRemoveStrictAdmitted(String containerId, Closeable logStream, int stopTimeoutSeconds) {
LOG.infov("Stopping container {0}", containerId);
Exception stopFailure = null;
try {
- dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
+ dockerClient.stopContainerCmd(containerId).withTimeout(stopTimeoutSeconds).exec();
} catch (NotFoundException e) {
LOG.debugv("Container {0} not found (already removed)", containerId);
closeLogStreamIfPresent(logStream);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java
index e96452d5a7..2f106c06c6 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/WarmPool.java
@@ -1,12 +1,15 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.ContainerTeardowns;
+import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
import io.github.hectorvent.floci.services.lambda.launcher.LambdaRuntimeLauncher;
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -21,7 +24,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -39,7 +44,8 @@ import java.util.concurrent.TimeUnit;
* after the invocation completes.
*/
@ApplicationScoped
-public class WarmPool implements ContainerTeardown {
+@Startup
+public class WarmPool implements ContainerTeardown, Resettable {
private static final Logger LOG = Logger.getLogger(WarmPool.class);
@@ -50,8 +56,13 @@ public class WarmPool implements ContainerTeardown {
private final Clock clock;
private final int maxPoolSizePerFunction;
private final int maxIdleTotal;
+ private final long drainTimeoutNanos;
private final ConcurrentHashMap<String, PoolState> poolStates = new ConcurrentHashMap<>();
private final ConcurrentHashMap<ContainerHandle, Lease> activeLeases = new ConcurrentHashMap<>();
+ private final Set<ContainerHandle> owned = ConcurrentHashMap.newKeySet();
+ private final Set<ContainerHandle> pendingTeardown = ConcurrentHashMap.newKeySet();
+ private final ConcurrentHashMap<ContainerHandle, CountDownLatch> stoppingHandles = new ConcurrentHashMap<>();
+ private LifecycleState lifecycleState = new LifecycleState();
/**
* Serialises the return-to-pool step of {@link #release} so the global idle count is
* checked and grown atomically. Lock order is this lock, then the releasing function's
@@ -62,6 +73,12 @@ public class WarmPool implements ContainerTeardown {
private final ScheduledExecutorService evictionScheduler = Executors.newSingleThreadScheduledExecutor(
r -> { Thread t = new Thread(r, "warm-pool-evictor"); t.setDaemon(true); return t; });
+ private static final class LifecycleState {
+ private boolean stopped;
+ private int activeLaunches;
+ private long deadlineNanos;
+ }
+
private static final class PoolState {
private final Map<String, ArrayDeque<ContainerHandle>> idleByEnvironment = new HashMap<>();
private final Map<String, Long> epochByEnvironment = new HashMap<>();
@@ -81,6 +98,7 @@ public class WarmPool implements ContainerTeardown {
this.clock = clock;
this.maxPoolSizePerFunction = resolveMaxPerFunction(config);
this.maxIdleTotal = resolveMaxTotal(config);
+ this.drainTimeoutNanos = TimeUnit.SECONDS.toNanos(resolveDrainTimeout(config));
}
/** Package-private constructor for testing (empty pool, no containers to drain). */
@@ -90,6 +108,16 @@ public class WarmPool implements ContainerTeardown {
this.clock = Clock.systemUTC();
this.maxPoolSizePerFunction = DEFAULT_MAX_POOL_SIZE;
this.maxIdleTotal = 0;
+ this.drainTimeoutNanos = TimeUnit.SECONDS.toNanos(15);
+ }
+
+ static int resolveDrainTimeout(EmulatorConfig config) {
+ int seconds = config.services().lambda().containerDrainTimeoutSeconds();
+ if (seconds < 1 || seconds > 300) {
+ throw new IllegalArgumentException("floci.services.lambda.container-drain-timeout-seconds "
+ + "must be between 1 and 300 seconds; received " + seconds);
+ }
+ return seconds;
}
static int resolveMaxPerFunction(EmulatorConfig config) {
@@ -123,11 +151,10 @@ public class WarmPool implements ContainerTeardown {
}
int idleTimeout = config.services().lambda().containerIdleTimeoutSeconds();
+ long checkInterval = idleTimeout > 0 ? Math.min(30, idleTimeout / 2 + 1) : 30;
+ evictionScheduler.scheduleAtFixedRate(this::evictIdleContainers,
+ checkInterval, checkInterval, TimeUnit.SECONDS);
if (!config.services().lambda().ephemeral() && idleTimeout > 0) {
- // Check for idle containers every 30 seconds (or half the timeout, whichever is less)
- long checkInterval = Math.min(30, idleTimeout / 2 + 1);
- evictionScheduler.scheduleAtFixedRate(this::evictIdleContainers,
- checkInterval, checkInterval, TimeUnit.SECONDS);
LOG.infov("Warm pool idle eviction enabled: timeout={0}s, check interval={1}s",
idleTimeout, checkInterval);
} else if (config.services().lambda().ephemeral()) {
@@ -144,13 +171,41 @@ public class WarmPool implements ContainerTeardown {
*/
@Override
public void stopManagedContainers() {
- drainAll();
+ LifecycleState shutdownState;
+ List<ContainerHandle> knownHandles;
+ synchronized (capLock) {
+ shutdownState = lifecycleState;
+ if (shutdownState.stopped) {
+ return;
+ }
+ shutdownState.stopped = true;
+ shutdownState.deadlineNanos = System.nanoTime() + drainTimeoutNanos;
+ for (String functionName : new ArrayList<>(poolStates.keySet())) {
+ detachFunction(functionName);
+ }
+ knownHandles = new ArrayList<>(owned);
+ pendingTeardown.addAll(knownHandles);
+ pendingTeardown.removeIf(handle -> !owned.contains(handle));
+ }
+ drainAll(shutdownState, knownHandles);
}
@PreDestroy
void shutdown() {
evictionScheduler.shutdownNow();
- drainAll();
+ stopManagedContainers();
+ }
+
+ @Override
+ public void clear() {
+ // Removal failures remain owned across reset so the next drain can retry them.
+ }
+
+ @Override
+ public void afterReset() {
+ synchronized (capLock) {
+ lifecycleState = new LifecycleState();
+ }
}
/**
@@ -159,6 +214,11 @@ public class WarmPool implements ContainerTeardown {
* Otherwise returns a warm container from the pool, or cold-starts a new one.
*/
public ContainerHandle acquire(LambdaFunction fn) {
+ LifecycleState admission;
+ synchronized (capLock) {
+ admission = lifecycleState;
+ requireCurrentAdmission(admission);
+ }
boolean ephemeral = config != null && config.services().lambda().ephemeral();
ContainerHandle handle = null;
PoolState poolState = null;
@@ -166,24 +226,26 @@ public class WarmPool implements ContainerTeardown {
String environmentKey = executionEnvironmentKey(fn);
if (!ephemeral) {
- poolState = poolStates.computeIfAbsent(fn.getFunctionName(), ignored -> new PoolState());
- synchronized (poolState) {
- leaseEpoch = poolState.epochByEnvironment.computeIfAbsent(environmentKey, ignored -> 0L);
+ synchronized (capLock) {
+ requireCurrentAdmission(admission);
+ poolState = poolStates.computeIfAbsent(fn.getFunctionName(), ignored -> new PoolState());
+ synchronized (poolState) {
+ leaseEpoch = poolState.epochByEnvironment.computeIfAbsent(environmentKey, ignored -> 0L);
+ }
}
- // Skip pooled handles whose container died out-of-band — otherwise the
- // caller would wait the full Lambda function timeout.
+ // Probe outside the locks, then recheck this acquisition's lifecycle before leasing.
while (true) {
ContainerHandle candidate;
- synchronized (poolState) {
- ArrayDeque<ContainerHandle> idle = poolState.idleByEnvironment.get(environmentKey);
- candidate = idle == null ? null : idle.pollFirst();
+ synchronized (capLock) {
+ requireCurrentAdmission(admission);
+ synchronized (poolState) {
+ ArrayDeque<ContainerHandle> idle = poolState.idleByEnvironment.get(environmentKey);
+ candidate = idle == null ? null : idle.pollFirst();
+ }
}
if (candidate == null) {
break;
}
- // A container whose extension reported a fatal error is still *running*, so the
- // liveness probe alone would hand it back out. Skip it for the same reason a dead
- // one is skipped: it can no longer serve invocations correctly.
if (candidate.isFaulted()) {
LOG.infov("Discarding pooled container {0} for function {1}: an extension reported a fatal error",
candidate.getContainerId(), fn.getFunctionName());
@@ -200,18 +262,58 @@ public class WarmPool implements ContainerTeardown {
}
}
- if (handle == null) {
- LOG.debugv(ephemeral ? "Ephemeral start for function: {0}" : "Cold start for function: {0}",
- fn.getFunctionName());
- handle = lambdaRuntimeLauncher.launch(fn);
- } else {
- LOG.debugv("Reusing warm container for function: {0}", fn.getFunctionName());
+ boolean launching = handle == null;
+ if (launching) {
+ synchronized (capLock) {
+ requireCurrentAdmission(admission);
+ admission.activeLaunches++;
+ }
}
- if (!ephemeral) {
- activeLeases.put(handle, new Lease(poolState, leaseEpoch, environmentKey));
+ try {
+ if (launching) {
+ LOG.debugv(ephemeral ? "Ephemeral start for function: {0}" : "Cold start for function: {0}",
+ fn.getFunctionName());
+ handle = lambdaRuntimeLauncher.launch(fn);
+ owned.add(handle);
+ } else {
+ LOG.debugv("Reusing warm container for function: {0}", fn.getFunctionName());
+ }
+ boolean rejected;
+ synchronized (capLock) {
+ rejected = admission.stopped || admission != lifecycleState;
+ if (!rejected && !ephemeral) {
+ activeLeases.put(handle, new Lease(poolState, leaseEpoch, environmentKey));
+ }
+ if (!rejected) {
+ handle.setState(ContainerState.BUSY);
+ }
+ }
+ if (rejected) {
+ long now = System.nanoTime();
+ long cleanupDeadline = admission.deadlineNanos > now
+ ? admission.deadlineNanos : now + drainTimeoutNanos;
+ stopInParallel(List.of(handle), cleanupDeadline);
+ if (owned.contains(handle)) {
+ LOG.warnv("Lambda acquisition crossed shutdown; container {0} remains owned for cleanup",
+ handle.getContainerId());
+ }
+ throw new AwsException("ResourceConflictException", "Lambda executor is stopping", 409);
+ }
+ return handle;
+ } finally {
+ if (launching) {
+ synchronized (capLock) {
+ admission.activeLaunches--;
+ capLock.notifyAll();
+ }
+ }
+ }
+ }
+
+ private void requireCurrentAdmission(LifecycleState admission) {
+ if (admission.stopped || admission != lifecycleState) {
+ throw new AwsException("ResourceConflictException", "Lambda executor is stopping", 409);
}
- handle.setState(ContainerState.BUSY);
- return handle;
}
/**
@@ -221,6 +323,9 @@ public class WarmPool implements ContainerTeardown {
*/
public void release(ContainerHandle handle) {
Lease lease = activeLeases.remove(handle);
+ if (!owned.contains(handle)) {
+ return;
+ }
boolean ephemeral = config != null && config.services().lambda().ephemeral();
// An extension reporting an init/exit error is fatal to the execution environment in real
// AWS. RuntimeApiServer already refuses new work at that point; the container is torn down
@@ -251,7 +356,7 @@ public class WarmPool implements ContainerTeardown {
List<ContainerHandle> evicted = List.of();
synchronized (capLock) {
synchronized (lease.poolState()) {
- stale = lease.epoch() != lease.poolState().epochByEnvironment
+ stale = lifecycleState.stopped || lease.epoch() != lease.poolState().epochByEnvironment
.getOrDefault(lease.environmentKey(), 0L);
returned = !stale && idleSize(lease.poolState()) < maxPoolSizePerFunction;
if (returned) {
@@ -366,7 +471,13 @@ public class WarmPool implements ContainerTeardown {
* Called on function deletion and emulator shutdown.
*/
public void drainFunction(String functionName) {
- stopInParallel(detachFunction(functionName));
+ List<ContainerHandle> handles = detachFunction(functionName);
+ for (ContainerHandle handle : pendingTeardown) {
+ if (owned.contains(handle) && handle.getFunctionName().equals(functionName) && !handles.contains(handle)) {
+ handles.add(handle);
+ }
+ }
+ stopInParallel(handles);
}
private List<ContainerHandle> detachFunction(String functionName) {
@@ -383,22 +494,69 @@ public class WarmPool implements ContainerTeardown {
}
private void stopInParallel(List<ContainerHandle> handles) {
- ContainerTeardowns.stopInParallel(handles, this::stopQuietly, LOG);
+ long deadline;
+ synchronized (capLock) {
+ deadline = lifecycleState.stopped ? lifecycleState.deadlineNanos
+ : System.nanoTime() + drainTimeoutNanos;
+ }
+ stopInParallel(handles, deadline);
}
- private void drainAll() {
- List<ContainerHandle> toStop = new ArrayList<>();
- for (String functionName : new ArrayList<>(poolStates.keySet())) {
- toStop.addAll(detachFunction(functionName));
+ private void stopInParallel(List<ContainerHandle> handles, long deadline) {
+ for (ContainerHandle handle : handles) {
+ if (owned.contains(handle)) {
+ pendingTeardown.add(handle);
+ if (!owned.contains(handle)) {
+ pendingTeardown.remove(handle);
+ }
+ }
}
- stopInParallel(toStop);
+ ContainerTeardowns.stopInParallel(handles, handle -> stopOwnedHandle(handle, deadline), LOG, deadline);
}
- private void evictIdleContainers() {
- if (config == null) {
- return;
+ private void drainAll(LifecycleState shutdownState, List<ContainerHandle> knownHandles) {
+ List<Runnable> drains = new ArrayList<>();
+ for (ContainerHandle handle : knownHandles) {
+ drains.add(() -> stopOwnedHandle(handle, shutdownState.deadlineNanos));
+ }
+ drains.add(() -> awaitLaunches(shutdownState));
+ ContainerTeardowns.stopInParallel(drains, Runnable::run, LOG, shutdownState.deadlineNanos);
+ if (!owned.isEmpty()) {
+ LOG.warnv("Shutdown drain ended with {0} on-demand Lambda environment(s) still owned", owned.size());
+ }
+ }
+
+ private void awaitLaunches(LifecycleState shutdownState) {
+ synchronized (capLock) {
+ try {
+ long remaining;
+ while (shutdownState.activeLaunches > 0
+ && (remaining = shutdownState.deadlineNanos - System.nanoTime()) > 0) {
+ TimeUnit.NANOSECONDS.timedWait(capLock, remaining);
+ }
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ if (shutdownState.activeLaunches > 0) {
+ LOG.warnv("Shutdown deadline reached with {0} Lambda launch(es) still pending",
+ shutdownState.activeLaunches);
+ }
+ }
+ }
+
+ void evictIdleContainers() {
+ synchronized (capLock) {
+ if (config == null || lifecycleState.stopped) {
+ return;
+ }
+ }
+ for (ContainerHandle handle : new ArrayList<>(pendingTeardown)) {
+ stopQuietly(handle);
}
long idleTimeoutMs = config.services().lambda().containerIdleTimeoutSeconds() * 1000L;
+ if (idleTimeoutMs <= 0 || config.services().lambda().ephemeral()) {
+ return;
+ }
long now = clock.millis();
for (Map.Entry<String, PoolState> entry : poolStates.entrySet()) {
@@ -446,10 +604,45 @@ public class WarmPool implements ContainerTeardown {
}
private void stopQuietly(ContainerHandle handle) {
+ boolean shutdown;
+ long deadline;
+ synchronized (capLock) {
+ shutdown = lifecycleState.stopped;
+ deadline = lifecycleState.deadlineNanos;
+ }
+ if (shutdown) {
+ long now = System.nanoTime();
+ stopInParallel(List.of(handle), deadline > now ? deadline : now + drainTimeoutNanos);
+ } else {
+ stopOwnedHandle(handle, System.nanoTime());
+ }
+ }
+
+ private void stopOwnedHandle(ContainerHandle handle, long deadlineNanos) {
+ CountDownLatch completion = new CountDownLatch(1);
+ CountDownLatch existing = stoppingHandles.putIfAbsent(handle, completion);
+ if (existing != null) {
+ try {
+ existing.await(Math.max(0, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS);
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ return;
+ }
try {
+ if (!owned.contains(handle)) {
+ return;
+ }
+ pendingTeardown.add(handle);
lambdaRuntimeLauncher.stop(handle);
+ owned.remove(handle);
+ pendingTeardown.remove(handle);
+ activeLeases.remove(handle);
} catch (Exception e) {
- LOG.warnv("Error stopping container {0}: {1}", handle.getContainerId(), e.getMessage());
+ LOG.warnv(e, "Error stopping container {0}", handle.getContainerId());
+ } finally {
+ stoppingHandles.remove(handle, completion);
+ completion.countDown();
}
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
index ccbeb27362..ddcf3094b3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
@@ -617,8 +617,13 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
// extension shutdown work — only that we will not preempt PID 1 for at least
// that long if it happens to be slow.
int stopTimeoutSeconds = server.hasRegisteredExtensions() ? 2 : 1;
- lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream(),
- stopTimeoutSeconds);
+ try {
+ lifecycleManager.stopAndRemoveStrict(handle.getContainerId(), handle.getLogStream(),
+ stopTimeoutSeconds);
+ } finally {
+ executionRoleCredentials.unregister(
+ handle.getExecutionRoleSessionAccountId(), handle.getExecutionRoleAccessKeyId());
+ }
// Only now close the runtime API socket. Any pollers that were still parked when
// the container exited get terminated by their end of the connection closing;
@@ -633,16 +638,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
LOG.warnv(e, "RuntimeApiServer did not close cleanly for container {0}",
handle.getContainerId());
} finally {
- try {
- runtimeApiServerFactory.release(server);
- } finally {
- // The session is only reachable while the container is alive, so it is retired
- // here rather than on the launch path's failure branch alone. Runs even if the
- // release above throws, otherwise a failed release strands the registration and
- // its credentials stay authorizable for the rest of the process lifetime.
- executionRoleCredentials.unregister(
- handle.getExecutionRoleSessionAccountId(), handle.getExecutionRoleAccessKeyId());
- }
+ runtimeApiServerFactory.release(server);
}
}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 2b7cb321ce..9052ef1e0e 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -430,6 +430,7 @@ floci:
poll-interval-ms: 1000
async-retry-delay-seconds: 60 # FLOCI_SERVICES_LAMBDA_ASYNC_RETRY_DELAY_SECONDS - a failed Event invocation waits this before its first retry and twice this before its second (AWS: 1 min, then 2); 0 retries back to back
container-idle-timeout-seconds: 300
+ container-drain-timeout-seconds: 15 # FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS - shared shutdown budget for on-demand Lambda containers
# warm-pool-max-per-function: # FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_PER_FUNCTION - idle containers kept per function (default max(4, cpus))
warm-pool-max-total: 0 # FLOCI_SERVICES_LAMBDA_WARM_POOL_MAX_TOTAL - idle containers kept across all functions, LRU evicted beyond it; 0 = unbounded
region-concurrency-limit: 1000
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
index be18805f46..b98ac93832 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
@@ -207,6 +207,20 @@ class ContainerLifecycleManagerVolumeTest {
manager.stopAndRemoveStrict("container-id", () -> operations.add("logs"));
assertEquals(List.of("stop", "remove", "logs"), operations);
+ verify(stop).withTimeout(5);
+ }
+
+ @Test
+ void strictContainerCleanupUsesTheCallersStopTimeout() {
+ StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
+ RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
+ when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
+ when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
+
+ manager.stopAndRemoveStrict("container-id", null, 2);
+
+ verify(stop).withTimeout(2);
+ verify(remove).exec();
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java
index 702b0eb965..c5dab6102b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/WarmPoolTest.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.lambda.launcher.ContainerHandle;
import io.github.hectorvent.floci.services.lambda.launcher.LambdaRuntimeLauncher;
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
@@ -8,6 +9,8 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -20,6 +23,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -27,12 +31,16 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -53,6 +61,11 @@ class WarmPoolTest {
}
private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal) {
+ return buildPool(maxPerFunction, maxTotal, 15);
+ }
+
+ private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal,
+ int drainSeconds) {
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
when(config.services()).thenReturn(services);
@@ -61,6 +74,7 @@ class WarmPoolTest {
when(lambda.containerIdleTimeoutSeconds()).thenReturn(0);
when(lambda.warmPoolMaxPerFunction()).thenReturn(maxPerFunction);
when(lambda.warmPoolMaxTotal()).thenReturn(maxTotal);
+ when(lambda.containerDrainTimeoutSeconds()).thenReturn(drainSeconds);
return new WarmPool(containerLauncher, config, clock);
}
@@ -124,6 +138,396 @@ class WarmPoolTest {
pool.shutdown();
}
+ @Test
+ void failedRemovalRemainsOwnedAndRetriesWithoutRetiringCompletedHandlesTwice() {
+ WarmPool pool = buildPool();
+ pool.init();
+ ContainerHandle handle = new ContainerHandle("cid-retry", "retry-fn", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(handle);
+ pool.release(pool.acquire(function("retry-fn")));
+ doThrow(new IllegalStateException("Docker removal failed")).doNothing().when(containerLauncher).stop(handle);
+
+ pool.drainFunction("retry-fn");
+ verify(containerLauncher, times(1)).stop(handle);
+ pool.drainFunction("retry-fn");
+ verify(containerLauncher, times(2)).stop(handle);
+ pool.drainFunction("retry-fn");
+ pool.release(handle);
+ pool.shutdown();
+ verify(containerLauncher, times(2)).stop(handle);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void shutdownStopsBusyHandlesAndResetAcceptsNewInvocations(boolean ephemeral) {
+ WarmPool pool = buildPool();
+ when(config.services().lambda().ephemeral()).thenReturn(ephemeral);
+ ContainerHandle busy = new ContainerHandle("busy", "fn", null, ContainerState.WARM);
+ ContainerHandle current = new ContainerHandle("current", "fn", null, ContainerState.WARM);
+ LambdaFunction fn = function("fn");
+ when(containerLauncher.launch(any())).thenReturn(busy, current);
+ try {
+ pool.init();
+ assertSame(busy, pool.acquire(fn));
+
+ pool.stopManagedContainers();
+
+ verify(containerLauncher).stop(busy);
+ AwsException failure = assertThrows(AwsException.class, () -> pool.acquire(fn));
+ assertEquals("ResourceConflictException", failure.getErrorCode());
+ assertEquals(409, failure.getHttpStatus());
+ pool.release(busy);
+ verify(containerLauncher, times(1)).stop(busy);
+ pool.afterReset();
+ assertSame(current, pool.acquire(fn));
+ } finally {
+ pool.shutdown();
+ }
+ verify(containerLauncher, times(1)).stop(busy);
+ verify(containerLauncher, times(1)).stop(current);
+ }
+
+ @Test
+ void shutdownDeadlineCancelsConcurrentRemovalsAndResetRetainsThemForRetry() throws Exception {
+ WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ ContainerHandle first = new ContainerHandle("first", "first", null, ContainerState.WARM);
+ ContainerHandle second = new ContainerHandle("second", "second", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(first, second);
+ CountDownLatch bothStarted = new CountDownLatch(2);
+ CountDownLatch release = new CountDownLatch(1);
+ CountDownLatch bothInterrupted = new CountDownLatch(2);
+ doAnswer(invocation -> {
+ bothStarted.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException interrupted) {
+ bothInterrupted.countDown();
+ throw interrupted;
+ }
+ return null;
+ }).when(containerLauncher).stop(any());
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ pool.init();
+ pool.release(pool.acquire(function("first")));
+ pool.release(pool.acquire(function("second")));
+ Future<?> drain = executor.submit(pool::stopManagedContainers);
+ assertTrue(bothStarted.await(3, TimeUnit.SECONDS));
+ drain.get(3, TimeUnit.SECONDS);
+ assertTrue(bothInterrupted.await(3, TimeUnit.SECONDS));
+ pool.stopManagedContainers();
+ verify(containerLauncher, times(1)).stop(first);
+ verify(containerLauncher, times(1)).stop(second);
+
+ pool.afterReset();
+ doNothing().when(containerLauncher).stop(any());
+ // Cancellation can return before workers finish releasing their teardown ownership.
+ await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> {
+ pool.evictIdleContainers();
+ verify(containerLauncher, times(2)).stop(first);
+ verify(containerLauncher, times(2)).stop(second);
+ });
+ } finally {
+ release.countDown();
+ executor.shutdownNow();
+ pool.shutdown();
+ }
+ verify(containerLauncher, times(2)).stop(first);
+ verify(containerLauncher, times(2)).stop(second);
+ }
+
+ @Test
+ void releaseAfterShutdownDeadlineRetriesFailedRemoval() throws Exception {
+ WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ LambdaFunction fn = function("late-release");
+ ContainerHandle busy = new ContainerHandle("busy", "late-release", null, ContainerState.WARM);
+ ContainerHandle slow = new ContainerHandle("slow", "late-release", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(busy, slow);
+ doThrow(new IllegalStateException("Removal failed")).doNothing().when(containerLauncher).stop(busy);
+ CountDownLatch slowStopStarted = new CountDownLatch(1);
+ CountDownLatch releaseSlowStop = new CountDownLatch(1);
+ doAnswer(invocation -> {
+ slowStopStarted.countDown();
+ releaseSlowStop.await();
+ return null;
+ }).when(containerLauncher).stop(slow);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ pool.init();
+ assertSame(busy, pool.acquire(fn));
+ assertSame(slow, pool.acquire(fn));
+ Future<?> shutdown = executor.submit(pool::stopManagedContainers);
+ assertTrue(slowStopStarted.await(3, TimeUnit.SECONDS));
+ shutdown.get(3, TimeUnit.SECONDS);
+ verify(containerLauncher, times(1)).stop(busy);
+
+ pool.release(busy);
+
+ verify(containerLauncher, times(2)).stop(busy);
+ pool.release(busy);
+ verify(containerLauncher, times(2)).stop(busy);
+ } finally {
+ releaseSlowStop.countDown();
+ executor.shutdownNow();
+ doNothing().when(containerLauncher).stop(slow);
+ pool.afterReset();
+ pool.shutdown();
+ }
+ }
+
+ @Test
+ void failedCapEvictionRetriesEvenWhenIdleEvictionIsDisabled() {
+ WarmPool pool = buildPool(Optional.of(1), 1);
+ ContainerHandle first = new ContainerHandle("retry-first", "first", null, ContainerState.WARM);
+ ContainerHandle second = new ContainerHandle("retry-second", "second", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(first, second);
+ doThrow(new IllegalStateException("Docker removal failed")).doNothing().when(containerLauncher).stop(first);
+ try {
+ pool.init();
+ pool.release(pool.acquire(function("first")));
+ nextMillisecond();
+ pool.release(pool.acquire(function("second")));
+ verify(containerLauncher, times(1)).stop(first);
+
+ pool.evictIdleContainers();
+ verify(containerLauncher, times(2)).stop(first);
+ pool.evictIdleContainers();
+ verify(containerLauncher, times(2)).stop(first);
+ verify(containerLauncher, never()).stop(second);
+ } finally {
+ pool.shutdown();
+ }
+ verify(containerLauncher, times(2)).stop(first);
+ verify(containerLauncher, times(1)).stop(second);
+ }
+
+ @Test
+ void functionDrainUsesConfiguredBudgetAndMaintenanceRetriesCanceledRemoval() throws Exception {
+ WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ ContainerHandle handle = new ContainerHandle("bounded-drain", "bounded", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(handle);
+ AtomicInteger attempts = new AtomicInteger();
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ doAnswer(call -> {
+ if (attempts.incrementAndGet() == 1) {
+ entered.countDown();
+ release.await();
+ }
+ return null;
+ }).when(containerLauncher).stop(handle);
+ try (ExecutorService tasks = Executors.newSingleThreadExecutor()) {
+ pool.init();
+ pool.release(pool.acquire(function("bounded")));
+ Future<?> drain = tasks.submit(() -> pool.drainFunction("bounded"));
+ try {
+ assertTrue(entered.await(2, TimeUnit.SECONDS));
+ drain.get(3, TimeUnit.SECONDS);
+ assertEquals(1, attempts.get());
+ } finally {
+ release.countDown();
+ }
+ await().atMost(Duration.ofSeconds(3)).until(() -> {
+ pool.evictIdleContainers();
+ return attempts.get() == 2;
+ });
+ } finally {
+ release.countDown();
+ pool.shutdown();
+ }
+ verify(containerLauncher, times(2)).stop(handle);
+ }
+
+ @Test
+ void warmHandleRemovedDuringLivenessProbeIsNotOwnedAgain() throws Exception {
+ WarmPool pool = buildPool();
+ pool.init();
+ LambdaFunction fn = function("reuse-race-fn");
+ ContainerHandle handle = new ContainerHandle("cid-reuse-race", "reuse-race-fn", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(handle);
+ pool.release(pool.acquire(fn));
+ CountDownLatch probeStarted = new CountDownLatch(1);
+ CountDownLatch finishProbe = new CountDownLatch(1);
+ when(containerLauncher.isAlive(handle)).thenAnswer(invocation -> {
+ probeStarted.countDown();
+ assertTrue(finishProbe.await(5, TimeUnit.SECONDS));
+ return true;
+ });
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ Future<ContainerHandle> acquire = executor.submit(() -> pool.acquire(fn));
+ assertTrue(probeStarted.await(3, TimeUnit.SECONDS));
+ pool.stopManagedContainers();
+ verify(containerLauncher, times(1)).stop(handle);
+ finishProbe.countDown();
+ assertThrows(ExecutionException.class, () -> acquire.get(3, TimeUnit.SECONDS));
+ pool.release(handle);
+ pool.shutdown();
+ verify(containerLauncher, times(1)).stop(handle);
+ } finally {
+ finishProbe.countDown();
+ executor.shutdownNow();
+ pool.shutdown();
+ }
+ }
+
+ @Test
+ void knownWarmHandleStopsWhileColdLaunchRemainsBlocked() throws Exception {
+ WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ pool.init();
+ ContainerHandle warm = new ContainerHandle("cid-known", "known-fn", null, ContainerState.WARM);
+ ContainerHandle late = new ContainerHandle("cid-blocked", "blocked-fn", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(warm);
+ pool.release(pool.acquire(function("known-fn")));
+ CountDownLatch launchStarted = new CountDownLatch(1);
+ CountDownLatch finishLaunch = new CountDownLatch(1);
+ CountDownLatch warmStopped = new CountDownLatch(1);
+ when(containerLauncher.launch(any())).thenAnswer(invocation -> {
+ launchStarted.countDown();
+ assertTrue(finishLaunch.await(5, TimeUnit.SECONDS));
+ return late;
+ });
+ doAnswer(invocation -> {
+ warmStopped.countDown();
+ return null;
+ }).when(containerLauncher).stop(warm);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<ContainerHandle> acquire = executor.submit(() -> pool.acquire(function("blocked-fn")));
+ assertTrue(launchStarted.await(3, TimeUnit.SECONDS));
+ Future<?> drain = executor.submit(pool::stopManagedContainers);
+ assertTrue(warmStopped.await(500, TimeUnit.MILLISECONDS),
+ "Known containers must retire before waiting for a blocked launch");
+ drain.get(3, TimeUnit.SECONDS);
+ finishLaunch.countDown();
+ assertThrows(ExecutionException.class, () -> acquire.get(3, TimeUnit.SECONDS));
+ verify(containerLauncher, times(1)).stop(warm);
+ verify(containerLauncher, times(1)).stop(late);
+ pool.afterReset();
+ pool.drainFunction("blocked-fn");
+ verify(containerLauncher, times(1)).stop(late);
+ } finally {
+ finishLaunch.countDown();
+ executor.shutdownNow();
+ pool.shutdown();
+ }
+ }
+
+ @Test
+ void oldColdLaunchCannotAcquireAfterResetReopensPool() throws Exception {
+ WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ pool.init();
+ LambdaFunction fn = function("reset-fn");
+ ContainerHandle old = new ContainerHandle("cid-old-launch", "reset-fn", null, ContainerState.WARM);
+ ContainerHandle current = new ContainerHandle("cid-new-launch", "reset-fn", null, ContainerState.WARM);
+ CountDownLatch launchStarted = new CountDownLatch(1);
+ CountDownLatch finishLaunch = new CountDownLatch(1);
+ when(containerLauncher.launch(any())).thenAnswer(invocation -> {
+ launchStarted.countDown();
+ assertTrue(finishLaunch.await(5, TimeUnit.SECONDS));
+ return old;
+ }).thenReturn(current);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ Future<ContainerHandle> acquire = executor.submit(() -> pool.acquire(fn));
+ assertTrue(launchStarted.await(3, TimeUnit.SECONDS));
+ pool.stopManagedContainers();
+ pool.afterReset();
+ assertSame(current, pool.acquire(fn));
+ pool.release(current);
+ finishLaunch.countDown();
+ assertThrows(ExecutionException.class, () -> acquire.get(3, TimeUnit.SECONDS));
+ verify(containerLauncher, times(1)).stop(old);
+ verify(containerLauncher, never()).stop(current);
+ when(containerLauncher.isAlive(current)).thenReturn(true);
+ assertSame(current, pool.acquire(fn));
+ pool.drainFunction("reset-fn");
+ verify(containerLauncher, times(1)).stop(old);
+ verify(containerLauncher, never()).stop(current);
+ pool.release(current);
+ verify(containerLauncher, times(1)).stop(current);
+ } finally {
+ finishLaunch.countDown();
+ executor.shutdownNow();
+ pool.shutdown();
+ }
+ }
+
+ @Test
+ void oldLivenessProbeCannotAcquireAfterResetReopensPool() throws Exception {
+ WarmPool pool = buildPool();
+ pool.init();
+ LambdaFunction fn = function("reset-probe-fn");
+ ContainerHandle old = new ContainerHandle("cid-old-probe", "reset-probe-fn", null, ContainerState.WARM);
+ ContainerHandle current = new ContainerHandle("cid-new-probe", "reset-probe-fn", null, ContainerState.WARM);
+ when(containerLauncher.launch(any())).thenReturn(old, current);
+ pool.release(pool.acquire(fn));
+ CountDownLatch probeStarted = new CountDownLatch(1);
+ CountDownLatch finishProbe = new CountDownLatch(1);
+ when(containerLauncher.isAlive(old)).thenAnswer(invocation -> {
+ probeStarted.countDown();
+ assertTrue(finishProbe.await(5, TimeUnit.SECONDS));
+ return true;
+ });
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ Future<ContainerHandle> acquire = executor.submit(() -> pool.acquire(fn));
+ assertTrue(probeStarted.await(3, TimeUnit.SECONDS));
+ pool.stopManagedContainers();
+ pool.afterReset();
+ assertSame(current, pool.acquire(fn));
+ pool.release(current);
+ finishProbe.countDown();
+ assertThrows(ExecutionException.class, () -> acquire.get(3, TimeUnit.SECONDS));
+ verify(containerLauncher, times(1)).stop(old);
+ verify(containerLauncher, never()).stop(current);
+ when(containerLauncher.isAlive(current)).thenReturn(true);
+ assertSame(current, pool.acquire(fn));
+ } finally {
+ finishProbe.countDown();
+ executor.shutdownNow();
+ pool.shutdown();
+ }
+ verify(containerLauncher, times(1)).stop(old);
+ verify(containerLauncher, times(1)).stop(current);
+ }
+
+ @Test
+ void launchBeyondShutdownDeadlineIsRefusedAndStopped() throws Exception {
+ WarmPool pool = buildPool(Optional.empty(), 0, 1);
+ pool.init();
+ LambdaFunction fn = function("late-fn");
+ ContainerHandle handle = new ContainerHandle("cid-late", "late-fn", null, ContainerState.WARM);
+ CountDownLatch launched = new CountDownLatch(1);
+ CountDownLatch finishLaunch = new CountDownLatch(1);
+ when(containerLauncher.launch(any())).thenAnswer(invocation -> {
+ launched.countDown();
+ assertTrue(finishLaunch.await(5, TimeUnit.SECONDS));
+ return handle;
+ });
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<ContainerHandle> acquire = executor.submit(() -> pool.acquire(fn));
+ assertTrue(launched.await(3, TimeUnit.SECONDS));
+ Future<?> drain = executor.submit(pool::stopManagedContainers);
+ drain.get(3, TimeUnit.SECONDS);
+ verify(containerLauncher, never()).stop(handle);
+ finishLaunch.countDown();
+ ExecutionException failure = assertThrows(ExecutionException.class,
+ () -> acquire.get(3, TimeUnit.SECONDS));
+ assertTrue(failure.getCause().getMessage().contains("Lambda executor is stopping"));
+ verify(containerLauncher, times(1)).stop(handle);
+ pool.afterReset();
+ pool.drainFunction("late-fn");
+ pool.drainFunction("late-fn");
+ verify(containerLauncher, times(1)).stop(handle);
+ } finally {
+ finishLaunch.countDown();
+ executor.shutdownNow();
+ pool.shutdown();
+ }
+ }
+
@Test
void stopManagedContainersDoesNotLetOneFunctionOccupyEveryWorker() throws Exception {
WarmPool pool = buildPool(Optional.of(17), 0);
@@ -767,6 +1171,24 @@ class WarmPoolTest {
pool.shutdown();
}
+ @Test
+ void drainTimeoutPreservesTheDefaultAndAcceptsOnlyBoundedOverrides() {
+ EmulatorConfig emulatorConfig = buildConfig(Optional.empty());
+ EmulatorConfig.LambdaServiceConfig lambda = emulatorConfig.services().lambda();
+ for (int seconds : new int[]{1, 15, 60, 300}) {
+ when(lambda.containerDrainTimeoutSeconds()).thenReturn(seconds);
+ assertEquals(seconds, WarmPool.resolveDrainTimeout(emulatorConfig));
+ }
+ for (int seconds : new int[]{0, -1, 301, Integer.MAX_VALUE}) {
+ when(lambda.containerDrainTimeoutSeconds()).thenReturn(seconds);
+ IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
+ () -> WarmPool.resolveDrainTimeout(emulatorConfig));
+ assertTrue(failure.getMessage().contains("must be between 1 and 300"));
+ assertThrows(IllegalArgumentException.class,
+ () -> new WarmPool(containerLauncher, emulatorConfig, clock));
+ }
+ }
+
@Test
void resolveMaxPerFunction_fallsBackToDerivedDefaultBelowOne() {
int derived = Math.max(4, Runtime.getRuntime().availableProcessors());
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
index ef314965cb..b605250c14 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
@@ -1026,6 +1026,46 @@ class ContainerLauncherTest {
verify(executionRoleCredentials).unregister("222233334444", "ASIASTOPSESSION");
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void stopRevokesCredentialsOnFailureAndRetainsRuntimeUntilRemovalSucceeds(boolean extensions) throws Exception {
+ Path codePath = Files.createDirectory(tempDir.resolve("role-session-stop-retry"));
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("role-session-stop-retry-fn");
+ fn.setAccountId("222233334444");
+ fn.setRuntime("nodejs20.x");
+ fn.setHandler("index.handler");
+ fn.setCodeLocalPath(codePath.toString());
+ when(executionRoleCredentials.forFunction(fn)).thenReturn(Optional.of(
+ new SessionCreds("ASIARETRYSESSION", "role-secret", "role-token")));
+ when(runtimeApiServer.hasRegisteredExtensions()).thenReturn(extensions);
+ ContainerHandle handle = launcher.launch(fn);
+ int timeout = extensions ? 2 : 1;
+ IllegalStateException failure = new IllegalStateException("Docker removal failed");
+ doThrow(failure).doNothing().when(lifecycleManager)
+ .stopAndRemoveStrict("container-123", null, timeout);
+
+ assertSame(failure, assertThrows(IllegalStateException.class, () -> launcher.stop(handle)));
+
+ verify(runtimeApiServer).quiesce();
+ verify(runtimeApiServer, never()).close();
+ verify(runtimeApiServerFactory, never()).release(runtimeApiServer);
+ verify(executionRoleCredentials).unregister("222233334444", "ASIARETRYSESSION");
+
+ launcher.stop(handle);
+
+ InOrder order = inOrder(lifecycleManager, runtimeApiServer, runtimeApiServerFactory,
+ executionRoleCredentials);
+ order.verify(runtimeApiServer).quiesce();
+ order.verify(lifecycleManager).stopAndRemoveStrict("container-123", null, timeout);
+ order.verify(executionRoleCredentials).unregister("222233334444", "ASIARETRYSESSION");
+ order.verify(runtimeApiServer).quiesce();
+ order.verify(lifecycleManager).stopAndRemoveStrict("container-123", null, timeout);
+ order.verify(executionRoleCredentials).unregister("222233334444", "ASIARETRYSESSION");
+ order.verify(runtimeApiServer).close();
+ order.verify(runtimeApiServerFactory).release(runtimeApiServer);
+ }
+
@Test
void launchFailureUnregistersExecutionRoleSession() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("role-session-failure"));
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 3a19e2ba5e..72c376bbf9 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -157,6 +157,7 @@ floci:
enabled: true
lambda:
enabled: true
+ container-drain-timeout-seconds: 15
docker-flags: ""
honour-architectures: false
zip-max-entries: 100000