mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(lambda): initialize provisioned concurrency environments (#6320)
Initialize and route qualifier-owned provisioned environments without invoking handlers during initialization. Keep configuration outcomes committed while failed removal remains owned for retry, and bound cleanup after late invocation release. Preserve on-demand spillover and the separate alias-retargeting stage. Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
f60cf120c6
commit
238d16e541
15 files changed
+2061
-248
No files matched your search
+61
-38
@@ -5,36 +5,6 @@
|
||||
|
||||
Floci Lambda runs your function code locally inside real Docker containers - close enough as AWS Lambda does (using Firecracker micro VM).
|
||||
|
||||
## Provisioned concurrency configuration
|
||||
|
||||
`PutProvisionedConcurrencyConfig`, `GetProvisionedConcurrencyConfig`, and
|
||||
`DeleteProvisionedConcurrencyConfig` use the AWS REST JSON route
|
||||
`/2019-09-30/functions/{FunctionName}/provisioned-concurrency?Qualifier=...`.
|
||||
They accept published versions and aliases pointing to published versions.
|
||||
Function names, partial ARNs, and full ARNs resolve in the named account and request region.
|
||||
IAM checks use the qualified function resource and the operation's own action.
|
||||
|
||||
This stage implements the control plane only. Put returns HTTP 202 and stores the desired
|
||||
count. Get reports `IN_PROGRESS` with zero allocated and available environments. No runtime
|
||||
is initialized, no handler is invoked, and ordinary invocation routing is unchanged. Runtime
|
||||
initialization and routing are separate follow-up work; `READY` is not simulated.
|
||||
|
||||
Requested counts share the existing `warm-pool-max-per-function` and `warm-pool-max-total`
|
||||
local limits, and cannot exceed the function's reserved concurrency. These local limits are
|
||||
not AWS account-quota emulation. A version and an alias targeting it cannot both have a
|
||||
configuration. Weighted aliases, hot-reload functions, and durable functions are not eligible
|
||||
for Put. Put requires the non-ephemeral Docker executor. Get and Delete still address an
|
||||
existing configuration if an alias later becomes
|
||||
weighted. An alias with a configuration cannot move to `$LATEST` or to a version already
|
||||
configured directly or through another alias. Description-only changes and unconfigured aliases
|
||||
remain allowed.
|
||||
|
||||
Deleting a version, alias, or function removes its corresponding configurations. Delete is
|
||||
idempotent for an existing target without a configuration; an absent target returns
|
||||
`ResourceNotFoundException`. Desired configuration uses the Lambda storage mode through
|
||||
`StorageFactory` and is restored after restart. Reset removes it. Storage failures propagate
|
||||
before the in-memory configuration is replaced or removed, so callers can retry.
|
||||
|
||||
## Supported Operations
|
||||
|
||||
| Operation | Description |
|
||||
@@ -79,9 +49,9 @@ before the in-memory configuration is replaced or removed, so callers can retry.
|
||||
| `PutFunctionConcurrency` | Set reserved concurrent executions |
|
||||
| `GetFunctionConcurrency` | Get reserved concurrent executions |
|
||||
| `DeleteFunctionConcurrency` | Clear reserved concurrent executions |
|
||||
| `PutProvisionedConcurrencyConfig` | Store requested capacity for a version or alias |
|
||||
| `GetProvisionedConcurrencyConfig` | Read requested capacity and configuration status |
|
||||
| `DeleteProvisionedConcurrencyConfig` | Remove requested capacity |
|
||||
| `PutProvisionedConcurrencyConfig` | Initialize Docker environments for a published version or simple alias |
|
||||
| `GetProvisionedConcurrencyConfig` | Read the allocation's actual initialization status and capacity |
|
||||
| `DeleteProvisionedConcurrencyConfig` | Remove an allocation and stop its environments |
|
||||
| `GetAccountSettings` | Account limits plus usage derived from the caller's stored functions |
|
||||
| `PutFunctionEventInvokeConfig` | Set the asynchronous invocation settings of a function, version or alias (retries, event age, destinations) |
|
||||
| `UpdateFunctionEventInvokeConfig` | Change some of those settings, leaving the rest as they are |
|
||||
@@ -405,8 +375,7 @@ disabled fails with Lambda's error as the resource status reason.
|
||||
applies independently to each region. `PutFunctionConcurrency` validates
|
||||
that the requested value leaves at least
|
||||
`floci.services.lambda.unreserved-concurrency-min` (default 100) available
|
||||
for unreserved functions in that region. Provisioned-concurrency requests
|
||||
must fit within any reserved concurrency configured for the function.
|
||||
for unreserved functions in that region.
|
||||
|
||||
Reducing or clearing a function's reserved value does not kill
|
||||
invocations that are already in flight. This matches AWS, which
|
||||
@@ -483,9 +452,62 @@ 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
|
||||
## Provisioned concurrency
|
||||
|
||||
Shutdown drains on-demand containers concurrently within one
|
||||
Put, Get and Delete use `/2019-09-30/functions/{FunctionName}/provisioned-concurrency`
|
||||
with a required `Qualifier` query parameter. Put accepts a positive integer
|
||||
`ProvisionedConcurrentExecutions` and returns HTTP 202 with `IN_PROGRESS`. An existing
|
||||
function without a configuration returns `ProvisionedConcurrencyConfigNotFoundException`
|
||||
from Get.
|
||||
|
||||
An alias and its resolved published version cannot both have configurations. Different
|
||||
aliases of the same provisioned version also conflict; other versions remain independent.
|
||||
`LastModified` uses Lambda's UTC `+0000` form.
|
||||
|
||||
Each environment runs the real function initialization. `READY` requires the runtime and
|
||||
every discovered extension to send their first Runtime API `Next` request. Provisioning
|
||||
does not enqueue a handler event. Initialization failures become `FAILED`; the initialization
|
||||
deadline is the greater of 130 seconds and the configured function timeout. A later ordinary
|
||||
Invoke for that exact alias or version uses an available initialized environment, with
|
||||
on-demand spillover when all its environments are busy. Other aliases, versions, accounts
|
||||
and regions do not borrow that allocation.
|
||||
|
||||
Layer initialization uses the stored function's account and partition, including background
|
||||
workers without a request context. An unresolved configured layer or missing layer directory
|
||||
fails provisioned initialization; it is never silently omitted from a `READY` environment.
|
||||
Cross-account layer sharing remains unsupported.
|
||||
|
||||
With IAM enforcement enabled, these operations authorize the function owner and qualifier
|
||||
against the caller's identity policy and the owner's function policy. A cross-account grant
|
||||
for Get does not authorize Put, Delete, or another qualifier.
|
||||
|
||||
Provisioned environments are separate from ordinary idle eviction. Desired configurations
|
||||
are persisted; restarting Floci initializes new processes before reporting `READY`.
|
||||
Deleting the configuration, alias or function removes the owned environments. If an
|
||||
alias changes its version, this stage marks its old allocation `FAILED` and retires its
|
||||
environments. Invocations use on-demand capacity until a new Put initializes the new
|
||||
version. Automatic alias retargeting is a separate follow-up. The requested quota is
|
||||
retained until configuration replacement or deletion. An invalid replacement Put preserves
|
||||
the existing healthy allocation. An alias with a configuration cannot move to `$LATEST`
|
||||
or to a version targeted by another configuration; remove the conflicting configuration
|
||||
first. Get and Delete remain available if the alias gains
|
||||
unsupported weighted routing.
|
||||
|
||||
This implementation supports the non-ephemeral Docker executor with immutable published
|
||||
versions and simple aliases. It refuses `$LATEST`, weighted aliases, hot reload, durable
|
||||
functions and other executors. Allocations share the configured `warm-pool-max-per-function`
|
||||
ceiling across a function's qualifiers, and the optional `warm-pool-max-total` ceiling across
|
||||
provisioned allocations. A function's reserved concurrency is also a ceiling. These local
|
||||
resource bounds do not implement AWS's complete regional provisioned-concurrency quota
|
||||
accounting, automatic scaling, or weighted-alias allocation. Provisioned runtimes receive
|
||||
their numeric `AWS_LAMBDA_FUNCTION_VERSION` and
|
||||
`AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency`.
|
||||
|
||||
Configuration replacement and deletion remain committed if environment removal fails.
|
||||
Failed removals retain ownership and are retried while Floci is running; they continue
|
||||
to count against local container limits until cleanup succeeds.
|
||||
|
||||
Shutdown drains provisioned and 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;
|
||||
@@ -495,6 +517,7 @@ 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.
|
||||
@@ -508,7 +531,7 @@ For a longer drain, explicitly stop with the larger timeout and then start Floci
|
||||
These AWS Lambda operations have no handler in Floci. Calls will return `404` or an error:
|
||||
|
||||
- Layer permissions (`AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`)
|
||||
- `ListProvisionedConcurrencyConfigs`
|
||||
- Listing provisioned concurrency (`ListProvisionedConcurrencyConfigs`)
|
||||
- `InvokeWithResponseStream`
|
||||
- Code signing enforcement. A configuration is created, read, updated, deleted and listed, and
|
||||
nothing verifies a signature against it, so it never gates a deployment. Attaching one to a
|
||||
|
||||
@@ -3004,7 +3004,7 @@ public interface EmulatorConfig {
|
||||
int containerIdleTimeoutSeconds();
|
||||
|
||||
/**
|
||||
* One shutdown drain budget shared by on-demand Lambda containers.
|
||||
* One shutdown drain budget shared by provisioned and on-demand Lambda containers.
|
||||
* Values outside 1 through 300 seconds fail initialization.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS
|
||||
|
||||
@@ -233,7 +233,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
}
|
||||
|
||||
try {
|
||||
return executeSync(fn, payload, requestId, clientContext);
|
||||
return executeSync(fn, payload, requestId, clientContext, invokedQualifier);
|
||||
} finally {
|
||||
permit.close();
|
||||
}
|
||||
@@ -289,7 +289,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
}
|
||||
InvokeResult result;
|
||||
try (permit) {
|
||||
result = executeSync(event.fn(), event.payload(), event.requestId(), null);
|
||||
result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Error in async Lambda execution for {0}: {1}", event.fn().getFunctionName(), e.getMessage());
|
||||
// Stops retrying, as upstream did: routes the previous attempt's result, or UnknownError when
|
||||
@@ -347,10 +347,13 @@ public class LambdaExecutorService implements Resettable {
|
||||
}
|
||||
|
||||
private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId,
|
||||
String clientContext) {
|
||||
String clientContext, String invokedQualifier) {
|
||||
ContainerHandle handle;
|
||||
try {
|
||||
handle = warmPool.acquire(fn);
|
||||
handle = warmPool.acquireProvisioned(fn, invokedQualifier);
|
||||
if (handle == null) {
|
||||
handle = warmPool.acquire(fn);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to acquire container for function {0}: {1}", fn.getFunctionName(), e.getMessage());
|
||||
return new InvokeResult(200, "Unhandled",
|
||||
|
||||
+525
-47
@@ -4,41 +4,72 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardowns;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
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.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Stores desired capacity. Runtime allocation is introduced by the next stage. */
|
||||
/**
|
||||
* Owns initialized environments separately from the on-demand idle pool.
|
||||
* Persisted requests never imply readiness: every new process must finish real initialization.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ProvisionedConcurrencyPool implements Resettable {
|
||||
private static final Logger LOG = Logger.getLogger(ProvisionedConcurrencyPool.class);
|
||||
private static final DateTimeFormatter LAST_MODIFIED =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZone(ZoneOffset.UTC);
|
||||
private final Object lock = new Object();
|
||||
private final LambdaRuntimeLauncher launcher;
|
||||
private final LambdaFunctionStore functions;
|
||||
private final LambdaAliasStore aliases;
|
||||
private final StorageBackend<String, Configuration> storage;
|
||||
private final Clock clock;
|
||||
private final int maxPerFunction;
|
||||
private final int maxTotal;
|
||||
private final boolean supported;
|
||||
private final Map<String, Configuration> configurations = new HashMap<>();
|
||||
private final boolean ephemeral;
|
||||
private final long drainTimeoutNanos;
|
||||
private final Map<String, Allocation> allocations = new HashMap<>();
|
||||
private final Map<ContainerHandle, Allocation> leases = new HashMap<>();
|
||||
private final Map<ContainerHandle, Configuration> owned = new HashMap<>();
|
||||
private final Set<Allocation> launchingAllocations = new HashSet<>();
|
||||
private final Set<ContainerHandle> pendingTeardown = new HashSet<>();
|
||||
private final Map<ContainerHandle, CountDownLatch> stopping = new HashMap<>();
|
||||
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
|
||||
Thread.ofPlatform().daemon().name("lambda-provisioned-concurrency").factory());
|
||||
private boolean stopped;
|
||||
private int activeLaunches;
|
||||
private long shutdownDeadlineNanos;
|
||||
|
||||
@RegisterForReflection
|
||||
public record Configuration(String account, String region, String name, String functionArn,
|
||||
@@ -52,32 +83,47 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
public record Status(int requested, int allocated, int available, String status,
|
||||
String reason, String lastModified) {}
|
||||
|
||||
private static final class Allocation {
|
||||
final Configuration configuration;
|
||||
final Set<ContainerHandle> handles = new HashSet<>();
|
||||
final ArrayDeque<ContainerHandle> idle = new ArrayDeque<>();
|
||||
int launching;
|
||||
String status = "IN_PROGRESS";
|
||||
String reason;
|
||||
|
||||
Allocation(Configuration configuration) {
|
||||
this.configuration = configuration;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class TargetUnavailableException extends RuntimeException {
|
||||
TargetUnavailableException() {
|
||||
super("The configured function version or alias is no longer available");
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
public ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
|
||||
StorageFactory storageFactory, EmulatorConfig config, Clock clock) {
|
||||
this(functions, aliases, storageFactory.create("lambda",
|
||||
public ProvisionedConcurrencyPool(LambdaRuntimeLauncher launcher, LambdaFunctionStore functions,
|
||||
LambdaAliasStore aliases, StorageFactory storageFactory,
|
||||
EmulatorConfig config, Clock clock) {
|
||||
this(launcher, functions, aliases, storageFactory.create("lambda",
|
||||
"lambda-provisioned-concurrency.json", new TypeReference<>() {}),
|
||||
clock, WarmPool.resolveMaxPerFunction(config), WarmPool.resolveMaxTotal(config),
|
||||
!config.services().lambda().ephemeral()
|
||||
&& "docker".equalsIgnoreCase(config.services().lambda().executor().trim()));
|
||||
config.services().lambda().ephemeral(), WarmPool.resolveDrainTimeout(config));
|
||||
}
|
||||
|
||||
ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
|
||||
StorageBackend<String, Configuration> storage,
|
||||
Clock clock, int maxPerFunction, int maxTotal) {
|
||||
this(functions, aliases, storage, clock, maxPerFunction, maxTotal, true);
|
||||
}
|
||||
|
||||
ProvisionedConcurrencyPool(LambdaFunctionStore functions, LambdaAliasStore aliases,
|
||||
StorageBackend<String, Configuration> storage,
|
||||
Clock clock, int maxPerFunction, int maxTotal, boolean supported) {
|
||||
this.supported = supported;
|
||||
ProvisionedConcurrencyPool(LambdaRuntimeLauncher launcher, LambdaFunctionStore functions,
|
||||
LambdaAliasStore aliases, StorageBackend<String, Configuration> storage,
|
||||
Clock clock, int maxPerFunction, int maxTotal, boolean ephemeral, int drainSeconds) {
|
||||
this.launcher = launcher;
|
||||
this.functions = functions;
|
||||
this.aliases = aliases;
|
||||
this.storage = storage;
|
||||
this.clock = clock;
|
||||
this.maxPerFunction = maxPerFunction;
|
||||
this.maxTotal = maxTotal;
|
||||
this.ephemeral = ephemeral;
|
||||
this.drainTimeoutNanos = TimeUnit.SECONDS.toNanos(drainSeconds);
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -86,9 +132,16 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
List<Configuration> stored = storage instanceof AccountAwareStorageBackend<Configuration> aware
|
||||
? aware.scanAllAccounts() : storage.scan(ignored -> true);
|
||||
for (Configuration configuration : stored) {
|
||||
configurations.put(configuration.key(), configuration);
|
||||
allocations.put(configuration.key(), new Allocation(configuration));
|
||||
}
|
||||
}
|
||||
scheduler.scheduleWithFixedDelay(() -> {
|
||||
try {
|
||||
reconcileSafely();
|
||||
} catch (RuntimeException failure) {
|
||||
LOG.errorv(failure, "Provisioned concurrency reconciliation failed");
|
||||
}
|
||||
}, 0, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public Status put(String region, String name, String qualifier, int count, String account) {
|
||||
@@ -106,27 +159,35 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
|
||||
private Status put(Configuration target) {
|
||||
int count = target.requested();
|
||||
if (!supported) {
|
||||
if (ephemeral || !launcher.supportsProvisionedConcurrency()) {
|
||||
throw invalid("Provisioned concurrency requires the non-ephemeral Docker Lambda executor");
|
||||
}
|
||||
LambdaFunction fn = functions.getForAccount(target.account(), target.region(), target.name(), target.version())
|
||||
.orElseThrow(() -> missing("Function no longer exists"));
|
||||
LambdaFunction fn = currentFunction(target);
|
||||
if (fn.isHotReload() || fn.isDurable()) {
|
||||
throw invalid("Provisioned concurrency is not supported for hot-reload or durable functions");
|
||||
}
|
||||
List<ContainerHandle> retired = List.of();
|
||||
Status result;
|
||||
synchronized (lock) {
|
||||
Configuration previous = configurations.get(target.key());
|
||||
if (stopped) {
|
||||
throw new AwsException("ResourceConflictException", "Lambda executor is stopping", 409);
|
||||
}
|
||||
if (hasPendingTeardown(target)) {
|
||||
throw new AwsException("ResourceConflictException",
|
||||
"The previous provisioned allocation is still being removed", 409);
|
||||
}
|
||||
Allocation previous = allocations.get(target.key());
|
||||
long otherFunction = 0;
|
||||
long otherTotal = 0;
|
||||
boolean versionConflict = false;
|
||||
for (Configuration entry : configurations.values()) {
|
||||
for (Allocation entry : allocations.values()) {
|
||||
if (entry == previous) {
|
||||
continue;
|
||||
}
|
||||
otherTotal += entry.requested();
|
||||
if (target.functionArn().equals(entry.functionArn())) {
|
||||
versionConflict |= target.version().equals(pointedVersion(entry));
|
||||
otherFunction += entry.requested();
|
||||
otherTotal += entry.configuration.requested();
|
||||
if (target.functionArn().equals(entry.configuration.functionArn())) {
|
||||
versionConflict |= target.version().equals(pointedVersion(entry.configuration));
|
||||
otherFunction += entry.configuration.requested();
|
||||
}
|
||||
}
|
||||
if (otherFunction + count > maxPerFunction
|
||||
@@ -146,24 +207,33 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
: "Alias can't be used for Provisioned Concurrency configuration "
|
||||
+ "on an already Provisioned version", 409);
|
||||
}
|
||||
if (previous != null && sameTarget(previous, target) && previous.requested() == count) {
|
||||
if (previous != null && sameTarget(previous.configuration, target)
|
||||
&& previous.configuration.requested() == count && !"FAILED".equals(previous.status)) {
|
||||
return status(previous);
|
||||
}
|
||||
write(target);
|
||||
configurations.put(target.key(), target);
|
||||
return status(target);
|
||||
Allocation next = new Allocation(target);
|
||||
allocations.put(target.key(), next);
|
||||
if (previous != null) {
|
||||
retired = retire(previous);
|
||||
}
|
||||
result = status(next);
|
||||
}
|
||||
stop(retired);
|
||||
reconcile();
|
||||
return result;
|
||||
}
|
||||
|
||||
public Status get(String region, String name, String qualifier, String account) {
|
||||
Target target = resolveTarget(region, name, qualifier, account);
|
||||
reconcile();
|
||||
synchronized (lock) {
|
||||
Configuration configuration = configurations.get(target.key());
|
||||
if (configuration == null) {
|
||||
Allocation allocation = allocations.get(target.key());
|
||||
if (allocation == null) {
|
||||
throw new AwsException("ProvisionedConcurrencyConfigNotFoundException",
|
||||
"No Provisioned Concurrency Config found for this function", 404);
|
||||
}
|
||||
return status(configuration);
|
||||
return status(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +245,71 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns null when the matching allocation has no idle capacity: on-demand execution may spill over. */
|
||||
ContainerHandle acquire(LambdaFunction fn, String qualifier) {
|
||||
if (qualifier == null) {
|
||||
return null;
|
||||
}
|
||||
String baseArn = baseArn(fn);
|
||||
List<ContainerHandle> discarded = new ArrayList<>();
|
||||
ContainerHandle selected = null;
|
||||
synchronized (lock) {
|
||||
Allocation allocation = allocations.get(baseArn + ":" + qualifier);
|
||||
if (allocation == null || !allocation.configuration.version().equals(fn.getVersion())) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
currentFunction(allocation.configuration);
|
||||
} catch (TargetUnavailableException changed) {
|
||||
return null;
|
||||
}
|
||||
while (!allocation.idle.isEmpty()) {
|
||||
ContainerHandle candidate = allocation.idle.removeFirst();
|
||||
if (healthy(candidate) && current(allocation)) {
|
||||
selected = candidate;
|
||||
leases.put(candidate, allocation);
|
||||
candidate.setState(ContainerState.BUSY);
|
||||
break;
|
||||
}
|
||||
allocation.handles.remove(candidate);
|
||||
pendingTeardown.add(candidate);
|
||||
discarded.add(candidate);
|
||||
}
|
||||
}
|
||||
stop(discarded);
|
||||
return selected;
|
||||
}
|
||||
|
||||
boolean release(ContainerHandle handle, boolean failed) {
|
||||
boolean retire;
|
||||
synchronized (lock) {
|
||||
Allocation allocation = leases.remove(handle);
|
||||
if (allocation == null) {
|
||||
return false;
|
||||
}
|
||||
retire = failed || !current(allocation) || !healthy(handle);
|
||||
if (retire) {
|
||||
allocation.handles.remove(handle);
|
||||
pendingTeardown.add(handle);
|
||||
} else {
|
||||
handle.setState(ContainerState.WARM);
|
||||
allocation.idle.addLast(handle);
|
||||
}
|
||||
}
|
||||
if (retire) {
|
||||
boolean shutdownDrain;
|
||||
long deadline;
|
||||
synchronized (lock) {
|
||||
shutdownDrain = stopped;
|
||||
long now = System.nanoTime();
|
||||
deadline = stopped && shutdownDeadlineNanos > now
|
||||
? shutdownDeadlineNanos : now + drainTimeoutNanos;
|
||||
}
|
||||
stop(List.of(handle), shutdownDrain, deadline);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void deleteFunction(LambdaFunction fn) {
|
||||
deleteMatching(baseArn(fn), null);
|
||||
}
|
||||
@@ -188,9 +323,9 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
return;
|
||||
}
|
||||
synchronized (lock) {
|
||||
long requested = configurations.values().stream()
|
||||
.filter(entry -> entry.functionArn().equals(baseArn(fn)))
|
||||
.mapToLong(entry -> entry.requested()).sum();
|
||||
long requested = allocations.values().stream()
|
||||
.filter(entry -> entry.configuration.functionArn().equals(baseArn(fn)))
|
||||
.mapToLong(entry -> entry.configuration.requested()).sum();
|
||||
if (requested > reserved) {
|
||||
throw invalid("Reserved concurrency cannot be lower than provisioned concurrency");
|
||||
}
|
||||
@@ -198,19 +333,96 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
}
|
||||
|
||||
private void deleteMatching(String functionArn, String qualifier) {
|
||||
List<ContainerHandle> retired = new ArrayList<>();
|
||||
synchronized (lock) {
|
||||
for (Configuration value : new ArrayList<>(configurations.values())) {
|
||||
for (Allocation entry : new ArrayList<>(allocations.values())) {
|
||||
Configuration value = entry.configuration;
|
||||
if (value.functionArn().equals(functionArn)
|
||||
&& (qualifier == null || qualifier.equals(value.qualifier()))) {
|
||||
erase(value);
|
||||
configurations.remove(value.key());
|
||||
allocations.remove(value.key());
|
||||
retired.addAll(retire(entry));
|
||||
}
|
||||
}
|
||||
for (ContainerHandle handle : pendingTeardown) {
|
||||
Configuration value = owned.get(handle);
|
||||
if (value.functionArn().equals(functionArn)
|
||||
&& (qualifier == null || qualifier.equals(value.qualifier()))) {
|
||||
retired.add(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
stop(retired);
|
||||
}
|
||||
|
||||
private Status status(Configuration configuration) {
|
||||
return new Status(configuration.requested(), 0, 0, "IN_PROGRESS", null, configuration.lastModified());
|
||||
private boolean hasPendingTeardown(Configuration configuration) {
|
||||
return pendingTeardown.stream().anyMatch(handle ->
|
||||
configuration.key().equals(owned.get(handle).key()));
|
||||
}
|
||||
|
||||
void reconcileSafely() {
|
||||
List<ContainerHandle> retry;
|
||||
synchronized (lock) {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
retry = new ArrayList<>(pendingTeardown);
|
||||
}
|
||||
stop(retry);
|
||||
reconcile();
|
||||
}
|
||||
|
||||
void reconcile() {
|
||||
List<ContainerHandle> retired = new ArrayList<>();
|
||||
synchronized (lock) {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
for (Allocation allocation : new ArrayList<>(allocations.values())) {
|
||||
if ("FAILED".equals(allocation.status)) {
|
||||
continue;
|
||||
}
|
||||
LambdaFunction fn;
|
||||
try {
|
||||
fn = currentFunction(allocation.configuration);
|
||||
} catch (TargetUnavailableException failure) {
|
||||
allocation.status = "FAILED";
|
||||
allocation.reason = "The configured function version or alias is no longer available";
|
||||
retired.addAll(retire(allocation));
|
||||
continue;
|
||||
}
|
||||
for (ContainerHandle handle : new ArrayList<>(allocation.idle)) {
|
||||
if (!healthy(handle)) {
|
||||
allocation.idle.remove(handle);
|
||||
allocation.handles.remove(handle);
|
||||
pendingTeardown.add(handle);
|
||||
retired.add(handle);
|
||||
}
|
||||
}
|
||||
if (hasPendingTeardown(allocation.configuration)) {
|
||||
continue;
|
||||
}
|
||||
int missing = allocation.configuration.requested()
|
||||
- allocation.handles.size() - allocation.launching;
|
||||
missing = Math.min(missing, availableCapacity(allocation.configuration));
|
||||
if (missing > 0) {
|
||||
allocation.status = "IN_PROGRESS";
|
||||
for (int i = 0; i < missing; i++) {
|
||||
allocation.launching++;
|
||||
launchingAllocations.add(allocation);
|
||||
activeLaunches++;
|
||||
try {
|
||||
workers.execute(() -> initialize(allocation, fn));
|
||||
} catch (RejectedExecutionException failure) {
|
||||
finishedLaunching(allocation);
|
||||
activeLaunches--;
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stop(retired);
|
||||
}
|
||||
|
||||
private String pointedVersion(Configuration configuration) {
|
||||
@@ -225,22 +437,212 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
void validateAliasUpdate(LambdaFunction fn, String qualifier, String version) {
|
||||
synchronized (lock) {
|
||||
String functionArn = baseArn(fn);
|
||||
if (!configurations.containsKey(functionArn + ":" + qualifier)) {
|
||||
if (!allocations.containsKey(functionArn + ":" + qualifier)) {
|
||||
return;
|
||||
}
|
||||
if ("$LATEST".equals(version)) {
|
||||
throw invalid("Provisioned Concurrency Configs cannot be applied to unpublished function versions.");
|
||||
}
|
||||
if (version != null && version.matches("[0-9]+") && configurations.values().stream()
|
||||
.anyMatch(entry -> functionArn.equals(entry.functionArn())
|
||||
&& !qualifier.equals(entry.qualifier())
|
||||
&& version.equals(pointedVersion(entry)))) {
|
||||
if (version != null && version.matches("[0-9]+") && allocations.values().stream()
|
||||
.anyMatch(entry -> functionArn.equals(entry.configuration.functionArn())
|
||||
&& !qualifier.equals(entry.configuration.qualifier())
|
||||
&& version.equals(pointedVersion(entry.configuration)))) {
|
||||
throw new AwsException("ResourceConflictException",
|
||||
"Alias can't be used for Provisioned Concurrency configuration on an already Provisioned version", 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int availableCapacity(Configuration configuration) {
|
||||
long functionOwned = owned.values().stream()
|
||||
.filter(value -> value.functionArn().equals(configuration.functionArn())).count();
|
||||
long functionLaunching = launchingAllocations.stream()
|
||||
.filter(value -> value.configuration.functionArn().equals(configuration.functionArn()))
|
||||
.mapToLong(value -> value.launching).sum();
|
||||
long available = maxPerFunction - functionOwned - functionLaunching;
|
||||
if (maxTotal > 0) {
|
||||
long launching = launchingAllocations.stream().mapToLong(value -> value.launching).sum();
|
||||
available = Math.min(available, maxTotal - owned.size() - launching);
|
||||
}
|
||||
return (int) Math.max(0, available);
|
||||
}
|
||||
|
||||
private void finishedLaunching(Allocation allocation) {
|
||||
allocation.launching--;
|
||||
if (allocation.launching == 0) {
|
||||
launchingAllocations.remove(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
private void initialize(Allocation allocation, LambdaFunction fn) {
|
||||
ContainerHandle handle = null;
|
||||
boolean retained = false;
|
||||
List<ContainerHandle> retired = List.of();
|
||||
try {
|
||||
handle = launcher.launchProvisioned(fn);
|
||||
synchronized (lock) {
|
||||
owned.put(handle, allocation.configuration);
|
||||
finishedLaunching(allocation);
|
||||
if (!current(allocation)) {
|
||||
return;
|
||||
}
|
||||
allocation.handles.add(handle);
|
||||
}
|
||||
long timeoutMs = Math.max(130, fn.getTimeout()) * 1000L;
|
||||
handle.getRuntimeApiServer().awaitInitialization(timeoutMs);
|
||||
synchronized (lock) {
|
||||
currentFunction(allocation.configuration);
|
||||
if (current(allocation) && healthy(handle)) {
|
||||
allocation.idle.addLast(handle);
|
||||
retained = true;
|
||||
if (allocation.handles.size() == allocation.configuration.requested()
|
||||
&& allocation.handles.stream().allMatch(this::healthy)) {
|
||||
allocation.status = "READY";
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
synchronized (lock) {
|
||||
if (handle == null) {
|
||||
finishedLaunching(allocation);
|
||||
}
|
||||
if (current(allocation)) {
|
||||
allocation.status = "FAILED";
|
||||
allocation.reason = "Execution environment initialization failed: "
|
||||
+ failure.getClass().getSimpleName()
|
||||
+ (failure.getMessage() == null ? "" : ": " + failure.getMessage());
|
||||
retired = retire(allocation);
|
||||
}
|
||||
}
|
||||
LOG.warnv(failure, "Provisioned Lambda initialization failed");
|
||||
if (failure instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
} finally {
|
||||
Set<ContainerHandle> toStop = new HashSet<>(retired);
|
||||
if (!retained && handle != null) {
|
||||
synchronized (lock) {
|
||||
allocation.handles.remove(handle);
|
||||
allocation.idle.remove(handle);
|
||||
}
|
||||
toStop.add(handle);
|
||||
}
|
||||
boolean shutdownDrain;
|
||||
long deadline;
|
||||
synchronized (lock) {
|
||||
shutdownDrain = stopped;
|
||||
long now = System.nanoTime();
|
||||
deadline = stopped && shutdownDeadlineNanos > now
|
||||
? shutdownDeadlineNanos : now + drainTimeoutNanos;
|
||||
}
|
||||
try {
|
||||
stop(new ArrayList<>(toStop), shutdownDrain, deadline);
|
||||
} finally {
|
||||
synchronized (lock) {
|
||||
activeLaunches--;
|
||||
lock.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Status status(Allocation allocation) {
|
||||
int healthy = (int) allocation.handles.stream().filter(this::healthy).count();
|
||||
int available = (int) allocation.idle.stream().filter(this::healthy).count();
|
||||
String state = allocation.status;
|
||||
if ("READY".equals(state) && healthy != allocation.configuration.requested()) {
|
||||
state = "IN_PROGRESS";
|
||||
}
|
||||
return new Status(allocation.configuration.requested(), healthy, available, state,
|
||||
allocation.reason, allocation.configuration.lastModified());
|
||||
}
|
||||
|
||||
private boolean healthy(ContainerHandle handle) {
|
||||
return handle.getState() != ContainerState.STOPPED
|
||||
&& handle.getRuntimeApiServer().isInitialized();
|
||||
}
|
||||
|
||||
private boolean current(Allocation allocation) {
|
||||
return !stopped && allocations.get(allocation.configuration.key()) == allocation
|
||||
&& !"FAILED".equals(allocation.status);
|
||||
}
|
||||
|
||||
private List<ContainerHandle> retire(Allocation allocation) {
|
||||
List<ContainerHandle> result = allocation.handles.stream()
|
||||
.filter(handle -> !leases.containsKey(handle)).toList();
|
||||
allocation.handles.clear();
|
||||
allocation.idle.clear();
|
||||
pendingTeardown.addAll(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void stop(List<ContainerHandle> handles) {
|
||||
stop(handles, false);
|
||||
}
|
||||
|
||||
private void stop(List<ContainerHandle> handles, boolean shutdownDrain) {
|
||||
stop(handles, shutdownDrain, System.nanoTime() + drainTimeoutNanos);
|
||||
}
|
||||
|
||||
private void stop(List<ContainerHandle> handles, boolean shutdownDrain, long deadlineNanos) {
|
||||
handles = handles.stream().distinct().toList();
|
||||
synchronized (lock) {
|
||||
for (ContainerHandle handle : handles) {
|
||||
if (owned.containsKey(handle)) {
|
||||
pendingTeardown.add(handle);
|
||||
handle.setState(ContainerState.STOPPED);
|
||||
}
|
||||
}
|
||||
if (stopped && !shutdownDrain) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
ContainerTeardowns.stopInParallel(handles, handle -> stop(handle, shutdownDrain, deadlineNanos),
|
||||
LOG, deadlineNanos);
|
||||
}
|
||||
|
||||
private void stop(ContainerHandle handle, boolean shutdownDrain, long deadlineNanos) {
|
||||
CountDownLatch completion;
|
||||
boolean alreadyStopping;
|
||||
synchronized (lock) {
|
||||
if (!owned.containsKey(handle) || (stopped && !shutdownDrain)) {
|
||||
return;
|
||||
}
|
||||
completion = stopping.get(handle);
|
||||
alreadyStopping = completion != null;
|
||||
if (!alreadyStopping) {
|
||||
completion = new CountDownLatch(1);
|
||||
stopping.put(handle, completion);
|
||||
}
|
||||
}
|
||||
if (alreadyStopping) {
|
||||
// An admitted retry owns this stop. Shutdown joins it within the same bounded
|
||||
// drain instead of returning while it runs, or issuing another Docker stop.
|
||||
if (shutdownDrain) {
|
||||
try {
|
||||
completion.await(Math.max(0, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
launcher.stop(handle);
|
||||
synchronized (lock) {
|
||||
pendingTeardown.remove(handle);
|
||||
owned.remove(handle);
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
LOG.warnv(failure, "Could not stop provisioned Lambda environment {0}", handle.getContainerId());
|
||||
} finally {
|
||||
synchronized (lock) {
|
||||
stopping.remove(handle);
|
||||
}
|
||||
completion.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
private record Target(String account, String region, String name, String functionArn,
|
||||
String qualifier, LambdaAlias alias) {
|
||||
String key() {
|
||||
@@ -298,6 +700,25 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
return new Target(account, region, ref.name(), baseArn(latest), qualifier, alias);
|
||||
}
|
||||
|
||||
private LambdaFunction currentFunction(Configuration configuration) {
|
||||
functions.getForAccount(configuration.account(), configuration.region(), configuration.name())
|
||||
.orElseThrow(TargetUnavailableException::new);
|
||||
if (!configuration.qualifier().matches("[0-9]+")) {
|
||||
LambdaAlias alias = aliases.getForAccount(configuration.account(), configuration.region(),
|
||||
configuration.name(), configuration.qualifier()).orElseThrow(TargetUnavailableException::new);
|
||||
if (!configuration.version().equals(alias.getFunctionVersion())
|
||||
|| (alias.getRoutingConfig() != null && !alias.getRoutingConfig().isEmpty())) {
|
||||
throw new TargetUnavailableException();
|
||||
}
|
||||
}
|
||||
LambdaFunction fn = functions.getForAccount(configuration.account(), configuration.region(),
|
||||
configuration.name(), configuration.version()).orElseThrow(TargetUnavailableException::new);
|
||||
if (!Objects.equals(configuration.revision(), fn.getRevisionId())) {
|
||||
throw new TargetUnavailableException();
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
|
||||
private static boolean sameTarget(Configuration first, Configuration second) {
|
||||
return first.key().equals(second.key()) && first.version().equals(second.version())
|
||||
&& Objects.equals(first.revision(), second.revision());
|
||||
@@ -327,9 +748,66 @@ public class ProvisionedConcurrencyPool implements Resettable {
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
stopManagedContainers();
|
||||
synchronized (lock) {
|
||||
storage.clear();
|
||||
configurations.clear();
|
||||
stopped = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void stopManagedContainers() {
|
||||
stopManagedContainers(System.nanoTime() + drainTimeoutNanos);
|
||||
}
|
||||
|
||||
void stopManagedContainers(long deadlineNanos) {
|
||||
List<ContainerHandle> retired;
|
||||
synchronized (lock) {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
stopped = true;
|
||||
shutdownDeadlineNanos = deadlineNanos;
|
||||
allocations.values().forEach(this::retire);
|
||||
allocations.clear();
|
||||
retired = new ArrayList<>(owned.keySet());
|
||||
}
|
||||
stop(retired, true, deadlineNanos);
|
||||
synchronized (lock) {
|
||||
try {
|
||||
long remaining;
|
||||
while (activeLaunches > 0 && (remaining = deadlineNanos - System.nanoTime()) > 0) {
|
||||
TimeUnit.NANOSECONDS.timedWait(lock, remaining);
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
if (activeLaunches > 0) {
|
||||
LOG.warnv("Shutdown deadline reached with {0} provisioned Lambda launch(es) still pending",
|
||||
activeLaunches);
|
||||
}
|
||||
}
|
||||
synchronized (lock) {
|
||||
if (!owned.isEmpty()) {
|
||||
LOG.warnv("Shutdown drain ended with {0} provisioned Lambda environment(s) still owned",
|
||||
owned.size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void shutdown() {
|
||||
stopManagedContainers();
|
||||
closeExecutors();
|
||||
}
|
||||
|
||||
void closeExecutors() {
|
||||
scheduler.shutdownNow();
|
||||
workers.shutdownNow();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterReset() {
|
||||
synchronized (lock) {
|
||||
stopped = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -95,8 +95,8 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
@Inject
|
||||
public WarmPool(LambdaRuntimeLauncher lambdaRuntimeLauncher, EmulatorConfig config, Clock clock,
|
||||
ProvisionedConcurrencyPool provisioned) {
|
||||
this.provisioned = provisioned;
|
||||
this.lambdaRuntimeLauncher = lambdaRuntimeLauncher;
|
||||
this.provisioned = provisioned;
|
||||
this.config = config;
|
||||
this.clock = clock;
|
||||
this.maxPoolSizePerFunction = resolveMaxPerFunction(config);
|
||||
@@ -195,13 +195,24 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
pendingTeardown.addAll(knownHandles);
|
||||
pendingTeardown.removeIf(handle -> !owned.contains(handle));
|
||||
}
|
||||
drainAll(shutdownState, knownHandles);
|
||||
List<Runnable> drains = new ArrayList<>();
|
||||
if (provisioned != null) {
|
||||
drains.add(() -> provisioned.stopManagedContainers(shutdownState.deadlineNanos));
|
||||
}
|
||||
drains.add(() -> drainAll(shutdownState, knownHandles));
|
||||
ContainerTeardowns.stopInParallel(drains, Runnable::run, LOG, shutdownState.deadlineNanos);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
evictionScheduler.shutdownNow();
|
||||
stopManagedContainers();
|
||||
try {
|
||||
stopManagedContainers();
|
||||
} finally {
|
||||
if (provisioned != null) {
|
||||
provisioned.closeExecutors();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -330,6 +341,9 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
* Otherwise it is returned to the warm pool.
|
||||
*/
|
||||
public void release(ContainerHandle handle) {
|
||||
if (provisioned != null && provisioned.release(handle, false)) {
|
||||
return;
|
||||
}
|
||||
Lease lease = activeLeases.remove(handle);
|
||||
if (!owned.contains(handle)) {
|
||||
return;
|
||||
@@ -449,12 +463,19 @@ public class WarmPool implements ContainerTeardown, Resettable {
|
||||
* stop is needed — no pool bookkeeping required.
|
||||
*/
|
||||
public void destroyHandle(ContainerHandle handle) {
|
||||
if (provisioned != null && provisioned.release(handle, true)) {
|
||||
return;
|
||||
}
|
||||
activeLeases.remove(handle);
|
||||
LOG.debugv("Destroying timed-out container {0} for function {1}",
|
||||
handle.getContainerId(), handle.getFunctionName());
|
||||
stopQuietly(handle);
|
||||
}
|
||||
|
||||
ContainerHandle acquireProvisioned(LambdaFunction fn, String qualifier) {
|
||||
return provisioned == null ? null : provisioned.acquire(fn, qualifier);
|
||||
}
|
||||
|
||||
void deleteProvisionedFunction(LambdaFunction fn) {
|
||||
if (provisioned != null) {
|
||||
provisioned.deleteFunction(fn);
|
||||
|
||||
+37
-5
@@ -153,6 +153,20 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
public ContainerHandle launch(LambdaFunction fn) {
|
||||
return launch(fn, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsProvisionedConcurrency() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContainerHandle launchProvisioned(LambdaFunction fn) {
|
||||
return launch(fn, true);
|
||||
}
|
||||
|
||||
private ContainerHandle launch(LambdaFunction fn, boolean provisioned) {
|
||||
LOG.infov("Launching container for function: {0}", fn.getFunctionName());
|
||||
|
||||
// For Zip functions, verify code exists before allocating any resources.
|
||||
@@ -266,6 +280,10 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
|
||||
env.removeIf(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION="));
|
||||
env.add("AWS_LAMBDA_FUNCTION_VERSION=" + fn.getVersion());
|
||||
if (provisioned) {
|
||||
env.removeIf(value -> value.startsWith("AWS_LAMBDA_INITIALIZATION_TYPE="));
|
||||
env.add("AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency");
|
||||
}
|
||||
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
@@ -391,6 +409,11 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
for (String layerArn : fn.getLayers()) {
|
||||
LambdaLayerVersion layer = layerService.resolveLayerByArnForAccount(
|
||||
layerArn, lambdaAccountId, lambdaRegion);
|
||||
if (provisioned && (layer == null || layer.getCodeLocalPath() == null
|
||||
|| !Files.isDirectory(Path.of(layer.getCodeLocalPath())))) {
|
||||
throw new IllegalStateException("Configured layer is unavailable for provisioned initialization: "
|
||||
+ layerArn);
|
||||
}
|
||||
if (layer != null && layer.getCodeLocalPath() != null) {
|
||||
Path layerPath = Path.of(layer.getCodeLocalPath());
|
||||
if (Files.exists(layerPath)) {
|
||||
@@ -432,7 +455,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
// (e.g. aws-lambda-web-adapter) never start without this. Best-effort: an extension
|
||||
// launch failure shouldn't fail the whole container launch, since a function with no
|
||||
// extensions is the common case and this must be a no-op for it.
|
||||
launchExtensions(dockerClient, containerId, fn.getFunctionName(), runtimeApiServer, logDestination);
|
||||
launchExtensions(dockerClient, containerId, fn.getFunctionName(), runtimeApiServer, logDestination, provisioned);
|
||||
|
||||
// Init-readiness barrier: the execs above are detached, so without waiting here the caller
|
||||
// could enqueue the first invocation before an extension is ready to receive it — the
|
||||
@@ -441,7 +464,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
// /extension/event/next rather than its register call. A no-extensions function (the
|
||||
// common case) does not wait at all; a timeout is non-fatal, since a container that serves
|
||||
// invocations without a slow extension is strictly better than failing the launch.
|
||||
awaitExtensionReadiness(runtimeApiServer, fn.getFunctionName());
|
||||
if (!provisioned) {
|
||||
awaitExtensionReadiness(runtimeApiServer, fn.getFunctionName());
|
||||
}
|
||||
|
||||
ContainerHandle handle = new ContainerHandle(
|
||||
containerId, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM, fn.isHotReload(),
|
||||
@@ -1372,8 +1397,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
private void launchExtensions(DockerClient dockerClient, String containerId, String functionName,
|
||||
RuntimeApiServer runtimeApiServer, LogDestination logDestination) {
|
||||
List<String> extensionNames = listExtensionBinaries(dockerClient, containerId, functionName);
|
||||
RuntimeApiServer runtimeApiServer, LogDestination logDestination, boolean strict) {
|
||||
List<String> extensionNames = listExtensionBinaries(dockerClient, containerId, functionName, strict);
|
||||
// Arm the readiness barrier before starting any extension process, so the latch already
|
||||
// exists when the first one starts polling /extension/event/next — otherwise a
|
||||
// fast-starting extension could become ready before there is anything to count it down.
|
||||
@@ -1402,6 +1427,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
LOG.infov("Launched extension {0} for function {1} (container {2})",
|
||||
name, functionName, containerId);
|
||||
} catch (Exception e) {
|
||||
if (strict) {
|
||||
throw new IllegalStateException("Could not launch a provisioned Lambda extension", e);
|
||||
}
|
||||
LOG.warnv(e, "Failed to launch extension {0} for function {1}; continuing without it",
|
||||
name, functionName);
|
||||
}
|
||||
@@ -1442,7 +1470,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
* those utilities present, which would silently look like "no extensions" to a shell-based probe.
|
||||
* The archive API only talks to the Docker daemon, so it works regardless of the image contents.
|
||||
*/
|
||||
private List<String> listExtensionBinaries(DockerClient dockerClient, String containerId, String functionName) {
|
||||
private List<String> listExtensionBinaries(DockerClient dockerClient, String containerId,
|
||||
String functionName, boolean strict) {
|
||||
try (InputStream tarStream = dockerClient.copyArchiveFromContainerCmd(containerId, EXTENSIONS_DIR).exec();
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(tarStream)) {
|
||||
|
||||
@@ -1469,6 +1498,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
} catch (NotFoundException e) {
|
||||
return List.of();
|
||||
} catch (Exception e) {
|
||||
if (strict) {
|
||||
throw new IllegalStateException("Could not discover provisioned Lambda extensions", e);
|
||||
}
|
||||
LOG.debugv("Could not list {0} for function {1} ({2}); assuming no extensions",
|
||||
EXTENSIONS_DIR, functionName, e.getMessage());
|
||||
return List.of();
|
||||
|
||||
+8
@@ -12,6 +12,14 @@ public interface LambdaRuntimeLauncher {
|
||||
|
||||
ContainerHandle launch(LambdaFunction fn);
|
||||
|
||||
default boolean supportsProvisionedConcurrency() {
|
||||
return false;
|
||||
}
|
||||
|
||||
default ContainerHandle launchProvisioned(LambdaFunction fn) {
|
||||
throw new UnsupportedOperationException("Provisioned concurrency is not supported by this Lambda executor");
|
||||
}
|
||||
|
||||
void stop(ContainerHandle handle);
|
||||
|
||||
boolean isAlive(ContainerHandle handle);
|
||||
|
||||
+4
@@ -59,6 +59,10 @@ public class RegisteredExtension {
|
||||
return waitingContext != null;
|
||||
}
|
||||
|
||||
public boolean hasReceivedFirstNext() {
|
||||
return firstNextReceived;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that this extension has issued its first {@code /extension/event/next}, which is
|
||||
* what AWS treats as the extension being init-ready (registering alone only obtains an
|
||||
|
||||
+40
-1
@@ -24,6 +24,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@@ -111,6 +112,8 @@ public class RuntimeApiServer {
|
||||
// Guards stopped, pendingQueue, waitingContexts, extensions, closeFuture, and every
|
||||
// RegisteredExtension's pendingEvents/waitingContext. See class doc for the discipline.
|
||||
private final Object lock = new Object();
|
||||
private final CompletableFuture<Void> initialization = new CompletableFuture<>();
|
||||
private boolean runtimeNextReceived;
|
||||
|
||||
// Invocations queued before a /next poller arrived. Guarded by lock.
|
||||
private final ArrayDeque<PendingInvocation> pendingQueue = new ArrayDeque<>();
|
||||
@@ -290,6 +293,32 @@ public class RuntimeApiServer {
|
||||
return faulted;
|
||||
}
|
||||
|
||||
/** Waits for runtime and extension initialization, without enqueuing an invocation. */
|
||||
public void awaitInitialization(long timeoutMs) throws Exception {
|
||||
initialization.get(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
synchronized (lock) {
|
||||
if (stopped || faulted) {
|
||||
throw new IllegalStateException("Lambda execution environment is no longer ready");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isInitialized() {
|
||||
synchronized (lock) {
|
||||
return initialization.isDone() && !initialization.isCompletedExceptionally() && !stopped && !faulted;
|
||||
}
|
||||
}
|
||||
|
||||
private void completeInitializationIfReady() {
|
||||
synchronized (lock) {
|
||||
CountDownLatch latch = extensionsReady;
|
||||
if (runtimeNextReceived && !stopped && !faulted && latch != null && latch.getCount() == 0
|
||||
&& extensions.values().stream().allMatch(RegisteredExtension::hasReceivedFirstNext)) {
|
||||
initialization.complete(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Declares how many extension binaries were launched for this container, arming the
|
||||
* init-readiness barrier that {@link #awaitExtensionsReady(long)} waits on.
|
||||
@@ -299,7 +328,10 @@ public class RuntimeApiServer {
|
||||
* no {@code /opt/extensions} directory) leaves the barrier permanently open.
|
||||
*/
|
||||
public void expectExtensions(int count) {
|
||||
extensionsReady = new CountDownLatch(Math.max(0, count));
|
||||
synchronized (lock) {
|
||||
extensionsReady = new CountDownLatch(Math.max(0, count));
|
||||
completeInitializationIfReady();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -363,6 +395,8 @@ public class RuntimeApiServer {
|
||||
// AWS Lambda tears an environment down.
|
||||
waitingContexts.add(ctx);
|
||||
} else {
|
||||
runtimeNextReceived = true;
|
||||
completeInitializationIfReady();
|
||||
toDispatch = pendingQueue.poll();
|
||||
if (toDispatch == null) {
|
||||
waitingContexts.add(ctx);
|
||||
@@ -525,6 +559,7 @@ public class RuntimeApiServer {
|
||||
if (readyLatch != null) {
|
||||
readyLatch.countDown();
|
||||
}
|
||||
completeInitializationIfReady();
|
||||
if (unknownExtension) {
|
||||
ctx.response().setStatusCode(403)
|
||||
.putHeader("Content-Type", "application/json")
|
||||
@@ -606,6 +641,7 @@ public class RuntimeApiServer {
|
||||
return;
|
||||
}
|
||||
stopped = true;
|
||||
initialization.completeExceptionally(new IllegalStateException("Lambda execution environment stopped"));
|
||||
extensionWritesFlushed = writesFuture;
|
||||
|
||||
ExtensionEvent shutdownEvent = ExtensionEvent.shutdown(System.currentTimeMillis() + 2000, "SPINDOWN");
|
||||
@@ -911,6 +947,7 @@ public class RuntimeApiServer {
|
||||
List<PendingInvocation> stranded;
|
||||
synchronized (lock) {
|
||||
faulted = true;
|
||||
initialization.completeExceptionally(new IllegalStateException("Lambda runtime initialization failed"));
|
||||
// Retained for a possible later enqueue(): the invocation that triggered this cold
|
||||
// start may not exist yet (see fatalRuntimeErrorPayload's doc), in which case
|
||||
// `stranded` below is empty and this is the only place the real error survives.
|
||||
@@ -1037,6 +1074,7 @@ public class RuntimeApiServer {
|
||||
return;
|
||||
}
|
||||
faulted = true;
|
||||
initialization.completeExceptionally(new IllegalStateException("Lambda runtime exited: " + exitCode));
|
||||
// Retained for a possible later enqueue(): the invocation that would have hit this
|
||||
// container may not exist yet (see fatalRuntimeErrorPayload's doc), so this generic,
|
||||
// requestId-free payload is built here rather than only per-stranded-invocation below.
|
||||
@@ -1105,6 +1143,7 @@ public class RuntimeApiServer {
|
||||
// Set under the lock alongside the unregistration so both land as one atomic
|
||||
// change.
|
||||
faulted = true;
|
||||
initialization.completeExceptionally(new IllegalStateException("Lambda extension initialization failed"));
|
||||
|
||||
// Anything already queued or parked would otherwise wait forever, since the guards
|
||||
// in enqueue()/NEXT_PATH now refuse to move work through a condemned environment.
|
||||
|
||||
@@ -439,7 +439,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
|
||||
container-drain-timeout-seconds: 15 # FLOCI_SERVICES_LAMBDA_CONTAINER_DRAIN_TIMEOUT_SECONDS - shared shutdown budget for both Lambda pools
|
||||
# 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
|
||||
|
||||
+7
-1
@@ -464,7 +464,7 @@ class SamTransformIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void samAutoPublishAliasKeepsPublishedConfiguration() {
|
||||
void samAutoPublishAliasKeepsPublishedConfigurationAndQualifiesForProvisionedConcurrency() {
|
||||
String stackName = "sam-published-config-stack";
|
||||
String function = "sam-published-config-func";
|
||||
stacksToDelete.add(stackName);
|
||||
@@ -503,6 +503,12 @@ class SamTransformIntegrationTest {
|
||||
.when().get("/2015-03-31/functions/" + function + "/configuration")
|
||||
.then().statusCode(200).body("Version", equalTo("1"))
|
||||
.body("MemorySize", equalTo(128)).body("Environment.Variables.MARKER", equalTo("original"));
|
||||
|
||||
// No allocation exists, but the generated alias is an eligible immutable target.
|
||||
given().queryParam("Qualifier", "production")
|
||||
.when().get("/2019-09-30/functions/" + function + "/provisioned-concurrency")
|
||||
.then().statusCode(404)
|
||||
.body("__type", equalTo("ProvisionedConcurrencyConfigNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1007
-137
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
@@ -38,6 +39,7 @@ 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.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
@@ -61,11 +63,11 @@ class WarmPoolTest {
|
||||
}
|
||||
|
||||
private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal) {
|
||||
return buildPool(maxPerFunction, maxTotal, 15);
|
||||
return buildPool(maxPerFunction, maxTotal, null, 15);
|
||||
}
|
||||
|
||||
private WarmPool buildPool(Optional<Integer> maxPerFunction, int maxTotal,
|
||||
int drainSeconds) {
|
||||
ProvisionedConcurrencyPool provisioned, int drainSeconds) {
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.LambdaServiceConfig lambda = mock(EmulatorConfig.LambdaServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
@@ -75,7 +77,7 @@ class WarmPoolTest {
|
||||
when(lambda.warmPoolMaxPerFunction()).thenReturn(maxPerFunction);
|
||||
when(lambda.warmPoolMaxTotal()).thenReturn(maxTotal);
|
||||
when(lambda.containerDrainTimeoutSeconds()).thenReturn(drainSeconds);
|
||||
return new WarmPool(containerLauncher, config, clock);
|
||||
return new WarmPool(containerLauncher, config, clock, provisioned);
|
||||
}
|
||||
|
||||
private static LambdaFunction function(String name) {
|
||||
@@ -189,7 +191,7 @@ class WarmPoolTest {
|
||||
|
||||
@Test
|
||||
void shutdownDeadlineCancelsConcurrentRemovalsAndResetRetainsThemForRetry() throws Exception {
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, 1);
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, null, 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);
|
||||
@@ -238,7 +240,7 @@ class WarmPoolTest {
|
||||
|
||||
@Test
|
||||
void releaseAfterShutdownDeadlineRetriesFailedRemoval() throws Exception {
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, 1);
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, null, 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);
|
||||
@@ -303,7 +305,7 @@ class WarmPoolTest {
|
||||
|
||||
@Test
|
||||
void functionDrainUsesConfiguredBudgetAndMaintenanceRetriesCanceledRemoval() throws Exception {
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, 1);
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
|
||||
ContainerHandle handle = new ContainerHandle("bounded-drain", "bounded", null, ContainerState.WARM);
|
||||
when(containerLauncher.launch(any())).thenReturn(handle);
|
||||
AtomicInteger attempts = new AtomicInteger();
|
||||
@@ -338,6 +340,68 @@ class WarmPoolTest {
|
||||
verify(containerLauncher, times(2)).stop(handle);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bothPoolsUseOneConfiguredDeadlineAndCanceledRemovalRemainsRetryable() throws Exception {
|
||||
ProvisionedConcurrencyPool provisioned = mock(ProvisionedConcurrencyPool.class);
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, provisioned, 1);
|
||||
pool.init();
|
||||
ContainerHandle handle = new ContainerHandle("cid-canceled", "cancel-fn", null, ContainerState.WARM);
|
||||
when(containerLauncher.launch(any())).thenReturn(handle);
|
||||
LambdaFunction fn = function("cancel-fn");
|
||||
pool.release(pool.acquire(fn));
|
||||
CountDownLatch bothStarted = new CountDownLatch(2);
|
||||
CountDownLatch bothInterrupted = new CountDownLatch(2);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicLong provisionedDeadline = new AtomicLong();
|
||||
doAnswer(invocation -> {
|
||||
provisionedDeadline.set(invocation.getArgument(0));
|
||||
bothStarted.countDown();
|
||||
try {
|
||||
release.await();
|
||||
} catch (InterruptedException interrupted) {
|
||||
bothInterrupted.countDown();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return null;
|
||||
}).when(provisioned).stopManagedContainers(anyLong());
|
||||
doAnswer(invocation -> {
|
||||
bothStarted.countDown();
|
||||
try {
|
||||
release.await();
|
||||
} catch (InterruptedException interrupted) {
|
||||
bothInterrupted.countDown();
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(interrupted);
|
||||
}
|
||||
return null;
|
||||
}).when(containerLauncher).stop(handle);
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
long before = System.nanoTime();
|
||||
Future<?> drain = executor.submit(pool::stopManagedContainers);
|
||||
try {
|
||||
assertTrue(bothStarted.await(3, TimeUnit.SECONDS),
|
||||
"Both pools must start draining before either pool finishes");
|
||||
drain.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(bothInterrupted.await(3, TimeUnit.SECONDS));
|
||||
assertTrue(provisionedDeadline.get() >= before + TimeUnit.SECONDS.toNanos(1));
|
||||
assertTrue(provisionedDeadline.get() <= System.nanoTime());
|
||||
assertThrows(RuntimeException.class, () -> pool.acquire(fn));
|
||||
pool.shutdown();
|
||||
verify(containerLauncher, times(1)).stop(handle);
|
||||
verify(provisioned, times(1)).stopManagedContainers(anyLong());
|
||||
|
||||
pool.afterReset();
|
||||
doNothing().when(containerLauncher).stop(handle);
|
||||
pool.drainFunction("cancel-fn");
|
||||
pool.drainFunction("cancel-fn");
|
||||
verify(containerLauncher, times(2)).stop(handle);
|
||||
} finally {
|
||||
release.countDown();
|
||||
executor.shutdownNow();
|
||||
pool.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void warmHandleRemovedDuringLivenessProbeIsNotOwnedAgain() throws Exception {
|
||||
WarmPool pool = buildPool();
|
||||
@@ -373,7 +437,7 @@ class WarmPoolTest {
|
||||
|
||||
@Test
|
||||
void knownWarmHandleStopsWhileColdLaunchRemainsBlocked() throws Exception {
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, 1);
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, null, 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);
|
||||
@@ -415,7 +479,7 @@ class WarmPoolTest {
|
||||
|
||||
@Test
|
||||
void oldColdLaunchCannotAcquireAfterResetReopensPool() throws Exception {
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, 1);
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
|
||||
pool.init();
|
||||
LambdaFunction fn = function("reset-fn");
|
||||
ContainerHandle old = new ContainerHandle("cid-old-launch", "reset-fn", null, ContainerState.WARM);
|
||||
@@ -494,7 +558,7 @@ class WarmPoolTest {
|
||||
|
||||
@Test
|
||||
void launchBeyondShutdownDeadlineIsRefusedAndStopped() throws Exception {
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, 1);
|
||||
WarmPool pool = buildPool(Optional.empty(), 0, null, 1);
|
||||
pool.init();
|
||||
LambdaFunction fn = function("late-fn");
|
||||
ContainerHandle handle = new ContainerHandle("cid-late", "late-fn", null, ContainerState.WARM);
|
||||
|
||||
+126
-1
@@ -89,6 +89,7 @@ class ContainerLauncherTest {
|
||||
@Mock RuntimeApiServer runtimeApiServer;
|
||||
@Mock DockerClient dockerClient;
|
||||
@Mock LambdaExecutionRoleCredentials executionRoleCredentials;
|
||||
@Mock LambdaLayerService layerService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
@@ -144,7 +145,7 @@ class ContainerLauncherTest {
|
||||
LaunchedContainerAwsEnv awsEnv = new LaunchedContainerAwsEnv(reachableEndpoint);
|
||||
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,
|
||||
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
|
||||
mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv,
|
||||
layerService, awsEnv,
|
||||
executionRoleCredentials);
|
||||
|
||||
when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
|
||||
@@ -661,6 +662,16 @@ class ContainerLauncherTest {
|
||||
verify(lifecycleManager, never()).createAndStart(any());
|
||||
}
|
||||
|
||||
private static LambdaFunction imageFunction() {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("image-function");
|
||||
fn.setAccountId("222233334444");
|
||||
fn.setFunctionArn("arn:aws:lambda:us-east-1:222233334444:function:image-function");
|
||||
fn.setPackageType("Image");
|
||||
fn.setImageUri("unit-lambda:latest");
|
||||
return fn;
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFunction_injectsDefaultAwsCredentials() throws Exception {
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("creds-defaults"));
|
||||
@@ -682,6 +693,120 @@ class ContainerLauncherTest {
|
||||
"AWS_SESSION_TOKEN should be injected when awsConfigPath is absent");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"$LATEST", "1", "7"})
|
||||
void onDemandLaunchUsesTheSelectedVersion(String version) {
|
||||
LambdaFunction fn = imageFunction();
|
||||
fn.setVersion(version);
|
||||
fn.setEnvironment(Map.of("AWS_LAMBDA_FUNCTION_VERSION", "user-override"));
|
||||
|
||||
launcher.launch(fn);
|
||||
|
||||
assertEquals(List.of("AWS_LAMBDA_FUNCTION_VERSION=" + version),
|
||||
captureRealContainerSpec().env().stream()
|
||||
.filter(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION=")).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionedLaunchUsesTheImmutableVersionAndPlatformInitializationType() throws Exception {
|
||||
stubExtensionDiscovery("example-extension");
|
||||
when(logStreamer.execLogCallbackForAccount(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new ResultCallback.Adapter<>());
|
||||
LambdaFunction fn = imageFunction();
|
||||
fn.setVersion("7");
|
||||
fn.setEnvironment(Map.of("AWS_LAMBDA_INITIALIZATION_TYPE", "on-demand",
|
||||
"AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"));
|
||||
launcher.launchProvisioned(fn);
|
||||
List<String> env = captureRealContainerSpec().env();
|
||||
assertEquals(List.of("AWS_LAMBDA_FUNCTION_VERSION=7"),
|
||||
env.stream().filter(value -> value.startsWith("AWS_LAMBDA_FUNCTION_VERSION=")).toList());
|
||||
assertEquals(List.of("AWS_LAMBDA_INITIALIZATION_TYPE=provisioned-concurrency"),
|
||||
env.stream().filter(value -> value.startsWith("AWS_LAMBDA_INITIALIZATION_TYPE=")).toList());
|
||||
verify(runtimeApiServer).expectExtensions(1);
|
||||
verify(runtimeApiServer, never()).awaitExtensionsReady(anyLong());
|
||||
verify(runtimeApiServer, never()).enqueue(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionedLaunchRefusesFailedExtensionDiscoveryAndCleansTheCreatedRuntime() {
|
||||
LambdaFunction fn = imageFunction();
|
||||
fn.setVersion("1");
|
||||
CopyArchiveFromContainerCmd archive = mock(CopyArchiveFromContainerCmd.class);
|
||||
when(dockerClient.copyArchiveFromContainerCmd("container-123", "/opt/extensions")).thenReturn(archive);
|
||||
when(archive.exec()).thenThrow(new IllegalStateException("controlled archive failure"));
|
||||
assertThrows(RuntimeException.class, () -> launcher.launchProvisioned(fn));
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
verify(runtimeApiServer, never()).expectExtensions(0);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void provisionedLaunchCopiesTheStoredAccountsLayerWithoutAmbientLookup(boolean legacyAccount) throws Exception {
|
||||
LambdaFunction fn = imageFunction();
|
||||
fn.setAccountId(legacyAccount ? null : "123456789012");
|
||||
fn.setFunctionArn("arn:aws:lambda:eu-west-1:123456789012:function:layer-function");
|
||||
fn.setVersion("1");
|
||||
String arn = "arn:aws:lambda:eu-west-1:123456789012:layer:owned:1";
|
||||
fn.setLayers(List.of(arn));
|
||||
Path layerPath = Files.createDirectory(tempDir.resolve("owned-layer"));
|
||||
Files.writeString(layerPath.resolve("dependency.txt"), "owned");
|
||||
LambdaLayerVersion layer = new LambdaLayerVersion();
|
||||
layer.setCodeLocalPath(layerPath.toString());
|
||||
when(layerService.resolveLayerByArnForAccount(arn, "123456789012", "eu-west-1")).thenReturn(layer);
|
||||
stubExtensionDiscovery();
|
||||
|
||||
launcher.launchProvisioned(fn);
|
||||
|
||||
assertTrue(capturedRemotePaths.contains("/opt"));
|
||||
verify(layerService, never()).resolveLayerByArn(anyString());
|
||||
verify(lifecycleManager).startCreated(eq("container-123"), any());
|
||||
verify(runtimeApiServer).expectExtensions(0);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("unavailableLayerPaths")
|
||||
void provisionedLaunchRefusesMissingLayerInputsAndCleansBeforeStart(String pathKind) throws Exception {
|
||||
LambdaFunction fn = imageFunction();
|
||||
fn.setAccountId("123456789012");
|
||||
fn.setFunctionArn("arn:aws:lambda:us-east-1:123456789012:function:missing-layer");
|
||||
fn.setVersion("1");
|
||||
String arn = "arn:aws:lambda:us-east-1:123456789012:layer:missing:1";
|
||||
fn.setLayers(List.of(arn));
|
||||
if (!"unresolved".equals(pathKind)) {
|
||||
LambdaLayerVersion layer = new LambdaLayerVersion();
|
||||
if ("absent".equals(pathKind)) {
|
||||
layer.setCodeLocalPath(tempDir.resolve("absent").toString());
|
||||
} else if ("regular-file".equals(pathKind)) {
|
||||
layer.setCodeLocalPath(Files.writeString(tempDir.resolve("not-a-directory"), "data").toString());
|
||||
}
|
||||
when(layerService.resolveLayerByArnForAccount(eq(arn), eq("123456789012"), anyString()))
|
||||
.thenReturn(layer);
|
||||
}
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||
() -> launcher.launchProvisioned(fn));
|
||||
assertTrue(error.getMessage().startsWith("Configured layer is unavailable for provisioned initialization:"));
|
||||
verify(lifecycleManager, never()).startCreated(anyString(), any());
|
||||
verify(lifecycleManager).stopAndRemove("container-123", null);
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
verify(runtimeApiServer, never()).expectExtensions(anyInt());
|
||||
verify(runtimeApiServer, never()).enqueue(any());
|
||||
}
|
||||
|
||||
private static Stream<String> unavailableLayerPaths() {
|
||||
return Stream.of("unresolved", "null-path", "absent", "regular-file");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryLaunchRetainsItsUnresolvedLayerBehavior() {
|
||||
LambdaFunction fn = imageFunction();
|
||||
String arn = "arn:aws:lambda:us-east-1:123456789012:layer:missing:1";
|
||||
fn.setLayers(List.of(arn));
|
||||
launcher.launch(fn);
|
||||
verify(layerService).resolveLayerByArnForAccount(arn, "222233334444", "us-east-1");
|
||||
verify(layerService, never()).resolveLayerByArn(anyString());
|
||||
verify(lifecycleManager).startCreated(eq("container-123"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFunction_injectsOwningAccountAsAccessKeyAndFallsBackForTheRest() throws Exception {
|
||||
// The access key identifies the container's owning account to AccountResolver, so it is
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package io.github.hectorvent.floci.services.lambda.runtime;
|
||||
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@Timeout(15)
|
||||
class RuntimeInitializationTest {
|
||||
private Vertx vertx;
|
||||
private RuntimeApiServer server;
|
||||
private HttpClient client;
|
||||
private String base;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
int port;
|
||||
try (ServerSocket socket = new ServerSocket(0)) {
|
||||
port = socket.getLocalPort();
|
||||
}
|
||||
base = "http://127.0.0.1:" + port;
|
||||
server = new RuntimeApiServer(vertx, port);
|
||||
server.start().get(5, TimeUnit.SECONDS);
|
||||
client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
server.stop().get(5, TimeUnit.SECONDS);
|
||||
client.shutdownNow();
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private CompletableFuture<HttpResponse<String>> next() {
|
||||
return client.sendAsync(HttpRequest.newBuilder(URI.create(base + "/2018-06-01/runtime/invocation/next"))
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private String register(String name) throws Exception {
|
||||
HttpResponse<String> response = client.send(
|
||||
HttpRequest.newBuilder(URI.create(base + "/2020-01-01/extension/register"))
|
||||
.header("Lambda-Extension-Name", name).header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{\"events\":[\"INVOKE\",\"SHUTDOWN\"]}")).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, response.statusCode());
|
||||
return response.headers().firstValue("Lambda-Extension-Identifier").orElseThrow();
|
||||
}
|
||||
|
||||
private CompletableFuture<HttpResponse<String>> extensionNext(String id) {
|
||||
return client.sendAsync(HttpRequest.newBuilder(URI.create(base + "/2020-01-01/extension/event/next"))
|
||||
.header("Lambda-Extension-Identifier", id).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void initializationNeedsRuntimeNextAndDoesNotProduceAnInvocation() throws Exception {
|
||||
server.expectExtensions(0);
|
||||
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
|
||||
CompletableFuture<HttpResponse<String>> pending = next();
|
||||
server.awaitInitialization(2000);
|
||||
assertTrue(server.isInitialized());
|
||||
assertFalse(pending.isDone(), "No handler event was enqueued by initialization");
|
||||
}
|
||||
|
||||
@Test
|
||||
void runtimeNextBeforeExtensionDiscoveryCannotCompleteInitialization() throws Exception {
|
||||
CompletableFuture<HttpResponse<String>> pending = next();
|
||||
await().atMost(Duration.ofSeconds(2)).until(() -> server.waitingContextsSize() == 1);
|
||||
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
|
||||
server.expectExtensions(1);
|
||||
String extension = register("example-extension");
|
||||
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
|
||||
extensionNext(extension);
|
||||
server.awaitInitialization(2000);
|
||||
assertFalse(pending.isDone());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyExtensionAndTheRuntimeMustFinishInit() throws Exception {
|
||||
server.expectExtensions(2);
|
||||
String first = register("first-extension");
|
||||
String second = register("second-extension");
|
||||
extensionNext(first);
|
||||
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
|
||||
CompletableFuture<HttpResponse<String>> pending = next();
|
||||
assertThrows(TimeoutException.class, () -> server.awaitInitialization(20));
|
||||
extensionNext(second);
|
||||
server.awaitInitialization(2000);
|
||||
assertFalse(pending.isDone());
|
||||
}
|
||||
|
||||
@Test
|
||||
void initErrorFailsTheBarrierWithoutAnInvocation() throws Exception {
|
||||
server.expectExtensions(0);
|
||||
HttpResponse<String> response = client.send(
|
||||
HttpRequest.newBuilder(URI.create(base + "/2018-06-01/runtime/init/error"))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(
|
||||
new JsonObject().put("errorMessage", "controlled import failure").encode())).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(202, response.statusCode());
|
||||
assertThrows(ExecutionException.class, () -> server.awaitInitialization(100));
|
||||
assertFalse(server.isInitialized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processExitFailsTheBarrierAndCannotBeMadeReadyByALateNext() throws Exception {
|
||||
server.expectExtensions(0);
|
||||
server.handleRuntimeProcessExited(1);
|
||||
assertThrows(ExecutionException.class, () -> server.awaitInitialization(100));
|
||||
assertEquals(204, next().get(2, TimeUnit.SECONDS).statusCode());
|
||||
assertFalse(server.isInitialized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopInvalidatesCompletedReadiness() throws Exception {
|
||||
server.expectExtensions(0);
|
||||
next();
|
||||
server.awaitInitialization(2000);
|
||||
server.quiesce();
|
||||
assertFalse(server.isInitialized());
|
||||
assertThrows(IllegalStateException.class, () -> server.awaitInitialization(100));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user