mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(lambda): support EFS file system configs (#2053)
* feat(lambda): support EFS file system configs * fix(lambda): prevent stale and shared EFS mounts * fix(lambda): isolate warm pools by version * test(dynamodb): retain Quarkus port for cleanup * fix(lambda): scope warm pool invalidation by environment --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
1 parent
ea74b979ae
commit
e1f389f61b
18 files changed
+991
-46
No files matched your search
+42
@@ -63,6 +63,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFileSystemConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
@@ -1584,6 +1585,8 @@ public class CloudFormationResourceProvisioner {
|
||||
configRequest.put("DeadLetterConfig", resolveMapOrDefault(props, "DeadLetterConfig", engine,
|
||||
mapWithNullValue("TargetArn")));
|
||||
configRequest.put("VpcConfig", resolveMapOrDefault(props, "VpcConfig", engine, Map.of()));
|
||||
configRequest.put("FileSystemConfigs",
|
||||
resolveObjectListOrEmpty(props, "FileSystemConfigs", engine));
|
||||
putResolvedMapIfPresent(configRequest, props, "ImageConfig", "ImageConfig", engine);
|
||||
|
||||
createRequest.putAll(configRequest);
|
||||
@@ -1787,6 +1790,12 @@ public class CloudFormationResourceProvisioner {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
case "FileSystemConfigs" -> {
|
||||
if (!Objects.equals(normalizeForCompare(fileSystemConfigs(fn)),
|
||||
normalizeForCompare(desired))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
case "ImageConfig" -> {
|
||||
if (imageConfigurationChanged(fn, desired)) return true;
|
||||
}
|
||||
@@ -1816,6 +1825,22 @@ public class CloudFormationResourceProvisioner {
|
||||
&& !Objects.equals(fn.getImageConfigWorkingDirectory(), mapString(map, "WorkingDirectory"));
|
||||
}
|
||||
|
||||
private static List<Map<String, String>> fileSystemConfigs(LambdaFunction fn) {
|
||||
if (fn.getFileSystemConfigs() == null) {
|
||||
return List.of();
|
||||
}
|
||||
return fn.getFileSystemConfigs().stream()
|
||||
.map(CloudFormationResourceProvisioner::fileSystemConfig)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static Map<String, String> fileSystemConfig(LambdaFileSystemConfig config) {
|
||||
Map<String, String> value = new LinkedHashMap<>();
|
||||
value.put("Arn", config.getArn());
|
||||
value.put("LocalMountPath", config.getLocalMountPath());
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String sha256Base64(String zipFileBase64) {
|
||||
byte[] zipBytes = Base64.getDecoder().decode(zipFileBase64);
|
||||
try {
|
||||
@@ -1915,6 +1940,23 @@ public class CloudFormationResourceProvisioner {
|
||||
return values;
|
||||
}
|
||||
|
||||
private List<Object> resolveObjectListOrEmpty(JsonNode props, String source,
|
||||
CloudFormationTemplateEngine engine) {
|
||||
if (props == null || !props.has(source) || props.get(source).isNull()) {
|
||||
return List.of();
|
||||
}
|
||||
JsonNode resolved = engine.resolveNode(props.get(source));
|
||||
if (resolved == null) {
|
||||
return List.of();
|
||||
}
|
||||
if (!resolved.isArray()) {
|
||||
throw new AwsException("ValidationError", source + " must be a list", 400);
|
||||
}
|
||||
List<Object> values = new ArrayList<>();
|
||||
resolved.forEach(value -> values.add(jsonNodeToValue(value)));
|
||||
return values;
|
||||
}
|
||||
|
||||
private Map<String, Object> resolveMapOrDefault(JsonNode props, String source,
|
||||
CloudFormationTemplateEngine engine,
|
||||
Map<String, Object> defaultValue) {
|
||||
|
||||
+2
@@ -443,6 +443,8 @@ class SamTransformProcessor {
|
||||
copyIfPresent(properties, "Architectures", lambdaProps);
|
||||
copyIfPresent(properties, "ReservedConcurrentExecutions", lambdaProps);
|
||||
copyIfPresent(properties, "EphemeralStorage", lambdaProps);
|
||||
copyIfPresent(properties, "VpcConfig", lambdaProps);
|
||||
copyIfPresent(properties, "FileSystemConfigs", lambdaProps);
|
||||
|
||||
JsonNode tracing = properties.path("Tracing");
|
||||
if (!tracing.isMissingNode()) {
|
||||
|
||||
@@ -626,6 +626,13 @@ public class LambdaController {
|
||||
node.put("KMSKeyArn", fn.getKmsKeyArn());
|
||||
}
|
||||
|
||||
if (fn.getFileSystemConfigs() != null && !fn.getFileSystemConfigs().isEmpty()) {
|
||||
ArrayNode fileSystems = node.putArray("FileSystemConfigs");
|
||||
fn.getFileSystemConfigs().forEach(fileSystem -> fileSystems.addObject()
|
||||
.put("Arn", fileSystem.getArn())
|
||||
.put("LocalMountPath", fileSystem.getLocalMountPath()));
|
||||
}
|
||||
|
||||
// Environment — always present (SDK expects it even when empty)
|
||||
ObjectNode envNode = node.putObject("Environment");
|
||||
if (fn.getEnvironment() != null && !fn.getEnvironment().isEmpty()) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfi
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFileSystemConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaUrlConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.model.ScalingConfig;
|
||||
@@ -40,6 +41,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Business logic for Lambda function management and invocation.
|
||||
@@ -48,6 +50,11 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
public class LambdaService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaService.class);
|
||||
private static final Pattern EFS_ACCESS_POINT_ARN = Pattern.compile(
|
||||
"^arn:aws[a-zA-Z-]*:elasticfilesystem:(?:eusc-)?[a-z]{2}"
|
||||
+ "(?:(?:-gov)|(?:-iso(?:b)?))?-[a-z]+-\\d:"
|
||||
+ "\\d{12}:access-point/fsap-[a-f0-9]{17}$");
|
||||
private static final Pattern FILE_SYSTEM_LOCAL_MOUNT_PATH = Pattern.compile("^/mnt/[A-Za-z0-9._-]+$");
|
||||
|
||||
private final LambdaFunctionStore functionStore;
|
||||
private final LambdaExecutorService executorService;
|
||||
@@ -327,6 +334,11 @@ public class LambdaService {
|
||||
fn.setVpcConfig(vpc);
|
||||
}
|
||||
|
||||
List<LambdaFileSystemConfig> fileSystemConfigs =
|
||||
parseFileSystemConfigs(request.get("FileSystemConfigs"));
|
||||
validateFileSystemVpcConfig(fileSystemConfigs, fn.getVpcConfig());
|
||||
fn.setFileSystemConfigs(fileSystemConfigs);
|
||||
|
||||
// ImageConfig (PackageType=Image overrides)
|
||||
if (request.get("ImageConfig") instanceof Map<?, ?> ic) {
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -441,7 +453,7 @@ public class LambdaService {
|
||||
fn.setRevisionId(UUID.randomUUID().toString());
|
||||
|
||||
// Drain warm containers — they have stale code mounted
|
||||
warmPool.drainFunction(functionName);
|
||||
warmPool.drainEnvironment(fn);
|
||||
|
||||
functionStore.save(region, fn);
|
||||
LOG.infov("Updated code for function: {0}", functionName);
|
||||
@@ -451,6 +463,20 @@ public class LambdaService {
|
||||
public LambdaFunction updateFunctionConfiguration(String region, String functionName, Map<String, Object> request) {
|
||||
LambdaFunction fn = getFunction(region, functionName);
|
||||
|
||||
Map<String, Object> requestedVpcConfig = fn.getVpcConfig();
|
||||
if (request.get("VpcConfig") instanceof Map<?, ?>) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> vpc = (Map<String, Object>) request.get("VpcConfig");
|
||||
requestedVpcConfig = new java.util.HashMap<>(vpc);
|
||||
}
|
||||
List<LambdaFileSystemConfig> requestedFileSystemConfigs = fn.getFileSystemConfigs();
|
||||
if (request.containsKey("FileSystemConfigs")) {
|
||||
requestedFileSystemConfigs = parseFileSystemConfigs(request.get("FileSystemConfigs"));
|
||||
}
|
||||
if (request.containsKey("VpcConfig") || request.containsKey("FileSystemConfigs")) {
|
||||
validateFileSystemVpcConfig(requestedFileSystemConfigs, requestedVpcConfig);
|
||||
}
|
||||
|
||||
if (request.containsKey("Description")) {
|
||||
fn.setDescription((String) request.get("Description"));
|
||||
}
|
||||
@@ -531,12 +557,14 @@ public class LambdaService {
|
||||
|
||||
if (request.containsKey("VpcConfig")) {
|
||||
if (request.get("VpcConfig") instanceof Map<?, ?>) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> vpc = (Map<String, Object>) request.get("VpcConfig");
|
||||
fn.setVpcConfig(vpc);
|
||||
fn.setVpcConfig(requestedVpcConfig);
|
||||
}
|
||||
}
|
||||
|
||||
if (request.containsKey("FileSystemConfigs")) {
|
||||
fn.setFileSystemConfigs(requestedFileSystemConfigs);
|
||||
}
|
||||
|
||||
if (request.containsKey("ImageConfig")) {
|
||||
if (request.get("ImageConfig") instanceof Map<?, ?> ic) {
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -562,7 +590,7 @@ public class LambdaService {
|
||||
fn.setRevisionId(UUID.randomUUID().toString());
|
||||
|
||||
// Drain warm containers so the next invocation picks up the new configuration
|
||||
warmPool.drainFunction(functionName);
|
||||
warmPool.drainEnvironment(fn);
|
||||
|
||||
functionStore.save(region, fn);
|
||||
LOG.infov("Updated configuration for function: {0}", functionName);
|
||||
@@ -944,6 +972,10 @@ public class LambdaService {
|
||||
snapshot.setState(fn.getState());
|
||||
snapshot.setCodeSizeBytes(fn.getCodeSizeBytes());
|
||||
snapshot.setEnvironment(fn.getEnvironment());
|
||||
snapshot.setVpcConfig(fn.getVpcConfig() == null
|
||||
? null
|
||||
: new java.util.HashMap<>(fn.getVpcConfig()));
|
||||
snapshot.setFileSystemConfigs(new ArrayList<>(fn.getFileSystemConfigs()));
|
||||
snapshot.setLastModified(System.currentTimeMillis());
|
||||
snapshot.setRevisionId(UUID.randomUUID().toString());
|
||||
|
||||
@@ -952,6 +984,64 @@ public class LambdaService {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static List<LambdaFileSystemConfig> parseFileSystemConfigs(Object value) {
|
||||
if (value == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
if (!(value instanceof List<?> configs)) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"FileSystemConfigs must be a list", 400);
|
||||
}
|
||||
if (configs.size() > 1) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"A Lambda function supports at most one file system configuration", 400);
|
||||
}
|
||||
|
||||
List<LambdaFileSystemConfig> parsed = new ArrayList<>();
|
||||
for (Object rawConfig : configs) {
|
||||
if (!(rawConfig instanceof Map<?, ?> config)) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Each FileSystemConfigs entry must be an object", 400);
|
||||
}
|
||||
Object arnValue = config.get("Arn");
|
||||
Object mountPathValue = config.get("LocalMountPath");
|
||||
String arn = arnValue instanceof String string ? string : null;
|
||||
String localMountPath = mountPathValue instanceof String string ? string : null;
|
||||
if (arn == null || arn.isBlank() || arn.length() > 256) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"File system Arn must be 1 to 256 characters", 400);
|
||||
}
|
||||
if (!EFS_ACCESS_POINT_ARN.matcher(arn).matches()) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"File system Arn must identify an EFS access point", 400);
|
||||
}
|
||||
if (localMountPath == null || localMountPath.isBlank() || localMountPath.length() > 160
|
||||
|| !FILE_SYSTEM_LOCAL_MOUNT_PATH.matcher(localMountPath).matches()) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"LocalMountPath must be a directory directly under /mnt", 400);
|
||||
}
|
||||
parsed.add(new LambdaFileSystemConfig(arn, localMountPath));
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private static void validateFileSystemVpcConfig(List<LambdaFileSystemConfig> fileSystemConfigs,
|
||||
Map<String, Object> vpcConfig) {
|
||||
if (fileSystemConfigs == null || fileSystemConfigs.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (!hasValues(vpcConfig, "SubnetIds") || !hasValues(vpcConfig, "SecurityGroupIds")) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"EFS file system access requires VpcConfig with subnets and security groups", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasValues(Map<String, Object> config, String key) {
|
||||
return config != null
|
||||
&& config.get(key) instanceof List<?> values
|
||||
&& !values.isEmpty();
|
||||
}
|
||||
|
||||
public List<LambdaFunction> listVersionsByFunction(String region, String functionName) {
|
||||
LambdaFunction fn = getFunction(region, functionName); // verify function exists
|
||||
return functionStore.listVersions(region, fn.getFunctionName());
|
||||
|
||||
@@ -14,7 +14,9 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -41,10 +43,19 @@ public class WarmPool implements ContainerTeardown {
|
||||
private final ContainerLauncher containerLauncher;
|
||||
private final EmulatorConfig config;
|
||||
private final int maxPoolSizePerFunction;
|
||||
private final ConcurrentHashMap<String, ArrayDeque<ContainerHandle>> pool = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, PoolState> poolStates = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<ContainerHandle, Lease> activeLeases = new ConcurrentHashMap<>();
|
||||
private final ScheduledExecutorService evictionScheduler = Executors.newSingleThreadScheduledExecutor(
|
||||
r -> { Thread t = new Thread(r, "warm-pool-evictor"); t.setDaemon(true); return t; });
|
||||
|
||||
private static final class PoolState {
|
||||
private final Map<String, ArrayDeque<ContainerHandle>> idleByEnvironment = new HashMap<>();
|
||||
private final Map<String, Long> epochByEnvironment = new HashMap<>();
|
||||
}
|
||||
|
||||
private record Lease(PoolState poolState, long epoch, String environmentKey) {
|
||||
}
|
||||
|
||||
@Inject
|
||||
public WarmPool(ContainerLauncher containerLauncher, EmulatorConfig config) {
|
||||
this.containerLauncher = containerLauncher;
|
||||
@@ -104,15 +115,22 @@ public class WarmPool implements ContainerTeardown {
|
||||
public ContainerHandle acquire(LambdaFunction fn) {
|
||||
boolean ephemeral = config != null && config.services().lambda().ephemeral();
|
||||
ContainerHandle handle = null;
|
||||
PoolState poolState = null;
|
||||
long leaseEpoch = 0;
|
||||
String environmentKey = executionEnvironmentKey(fn);
|
||||
|
||||
if (!ephemeral) {
|
||||
ArrayDeque<ContainerHandle> queue = pool.computeIfAbsent(fn.getFunctionName(), k -> new ArrayDeque<>());
|
||||
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.
|
||||
while (true) {
|
||||
ContainerHandle candidate;
|
||||
synchronized (queue) {
|
||||
candidate = queue.pollFirst();
|
||||
synchronized (poolState) {
|
||||
ArrayDeque<ContainerHandle> idle = poolState.idleByEnvironment.get(environmentKey);
|
||||
candidate = idle == null ? null : idle.pollFirst();
|
||||
}
|
||||
if (candidate == null) {
|
||||
break;
|
||||
@@ -143,6 +161,9 @@ public class WarmPool implements ContainerTeardown {
|
||||
} else {
|
||||
LOG.debugv("Reusing warm container for function: {0}", fn.getFunctionName());
|
||||
}
|
||||
if (!ephemeral) {
|
||||
activeLeases.put(handle, new Lease(poolState, leaseEpoch, environmentKey));
|
||||
}
|
||||
handle.setState(ContainerState.BUSY);
|
||||
return handle;
|
||||
}
|
||||
@@ -153,6 +174,7 @@ public class WarmPool implements ContainerTeardown {
|
||||
* Otherwise it is returned to the warm pool.
|
||||
*/
|
||||
public void release(ContainerHandle handle) {
|
||||
Lease lease = activeLeases.remove(handle);
|
||||
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
|
||||
@@ -171,17 +193,32 @@ public class WarmPool implements ContainerTeardown {
|
||||
return;
|
||||
}
|
||||
|
||||
handle.setState(ContainerState.WARM);
|
||||
handle.touchLastUsed();
|
||||
ArrayDeque<ContainerHandle> queue = pool.computeIfAbsent(handle.getFunctionName(), k -> new ArrayDeque<>());
|
||||
if (lease == null) {
|
||||
LOG.warnv("Container {0} for function {1} has no active warm-pool lease; stopping it",
|
||||
handle.getContainerId(), handle.getFunctionName());
|
||||
stopQuietly(handle);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean stale;
|
||||
boolean returned;
|
||||
synchronized (queue) {
|
||||
returned = queue.size() < maxPoolSizePerFunction;
|
||||
synchronized (lease.poolState()) {
|
||||
stale = lease.epoch() != lease.poolState().epochByEnvironment
|
||||
.getOrDefault(lease.environmentKey(), 0L);
|
||||
returned = !stale && idleSize(lease.poolState()) < maxPoolSizePerFunction;
|
||||
if (returned) {
|
||||
queue.addFirst(handle);
|
||||
handle.setState(ContainerState.WARM);
|
||||
handle.touchLastUsed();
|
||||
lease.poolState().idleByEnvironment
|
||||
.computeIfAbsent(lease.environmentKey(), ignored -> new ArrayDeque<>())
|
||||
.addFirst(handle);
|
||||
}
|
||||
}
|
||||
if (returned) {
|
||||
if (stale) {
|
||||
LOG.debugv("Pool was invalidated while container {0} was busy; stopping it",
|
||||
handle.getContainerId());
|
||||
stopQuietly(handle);
|
||||
} else if (returned) {
|
||||
LOG.debugv("Released container back to pool for function: {0}", handle.getFunctionName());
|
||||
} else {
|
||||
LOG.debugv("Pool full for function {0}, stopping excess container", handle.getFunctionName());
|
||||
@@ -196,7 +233,7 @@ public class WarmPool implements ContainerTeardown {
|
||||
public void pushCodeUpdate(LambdaFunction fn) {
|
||||
LOG.infov("Reactive S3 Sync: invalidating warm pool for function {0} to pick up new code",
|
||||
fn.getFunctionName());
|
||||
drainFunction(fn.getFunctionName());
|
||||
drainEnvironment(fn);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -205,31 +242,52 @@ public class WarmPool implements ContainerTeardown {
|
||||
* stop is needed — no pool bookkeeping required.
|
||||
*/
|
||||
public void destroyHandle(ContainerHandle handle) {
|
||||
activeLeases.remove(handle);
|
||||
LOG.debugv("Destroying timed-out container {0} for function {1}",
|
||||
handle.getContainerId(), handle.getFunctionName());
|
||||
stopQuietly(handle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops and removes all warm containers for the given function.
|
||||
* Called on function delete or code update.
|
||||
* Stops and removes warm containers for one immutable execution environment, such as
|
||||
* {@code $LATEST}. Published versions keep their independently keyed warm containers.
|
||||
*/
|
||||
public void drainEnvironment(LambdaFunction fn) {
|
||||
String functionName = fn.getFunctionName();
|
||||
String environmentKey = executionEnvironmentKey(fn);
|
||||
PoolState poolState = poolStates.computeIfAbsent(functionName, ignored -> new PoolState());
|
||||
List<ContainerHandle> toStop;
|
||||
synchronized (poolState) {
|
||||
poolState.epochByEnvironment.merge(environmentKey, 1L, Long::sum);
|
||||
ArrayDeque<ContainerHandle> idle = poolState.idleByEnvironment.remove(environmentKey);
|
||||
toStop = idle == null ? List.of() : new ArrayList<>(idle);
|
||||
}
|
||||
LOG.infov("Draining {0} container(s) for Lambda environment: {1}",
|
||||
toStop.size(), environmentKey);
|
||||
stopInParallel(toStop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops and removes all warm containers for every environment of the given function.
|
||||
* Called on function deletion and emulator shutdown.
|
||||
*/
|
||||
public void drainFunction(String functionName) {
|
||||
ArrayDeque<ContainerHandle> queue = pool.remove(functionName);
|
||||
if (queue == null) {
|
||||
return;
|
||||
}
|
||||
PoolState poolState = poolStates.computeIfAbsent(functionName, ignored -> new PoolState());
|
||||
List<ContainerHandle> toStop;
|
||||
synchronized (queue) {
|
||||
toStop = new ArrayList<>(queue);
|
||||
queue.clear();
|
||||
synchronized (poolState) {
|
||||
poolState.epochByEnvironment.replaceAll((ignored, epoch) -> epoch + 1);
|
||||
toStop = new ArrayList<>();
|
||||
poolState.idleByEnvironment.values().forEach(toStop::addAll);
|
||||
poolState.idleByEnvironment.clear();
|
||||
}
|
||||
LOG.infov("Draining {0} container(s) for function: {1}", toStop.size(), functionName);
|
||||
stopInParallel(toStop);
|
||||
}
|
||||
|
||||
private void stopInParallel(List<ContainerHandle> handles) {
|
||||
if (handles.isEmpty()) return;
|
||||
if (handles.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int parallelism = Math.min(handles.size(), 16);
|
||||
ExecutorService pool = Executors.newFixedThreadPool(parallelism,
|
||||
r -> { Thread t = new Thread(r, "warm-pool-drainer"); t.setDaemon(true); return t; });
|
||||
@@ -251,34 +309,38 @@ public class WarmPool implements ContainerTeardown {
|
||||
}
|
||||
|
||||
private void drainAll() {
|
||||
for (String functionName : new ArrayList<>(pool.keySet())) {
|
||||
for (String functionName : new ArrayList<>(poolStates.keySet())) {
|
||||
drainFunction(functionName);
|
||||
}
|
||||
}
|
||||
|
||||
private void evictIdleContainers() {
|
||||
if (config == null) return;
|
||||
if (config == null) {
|
||||
return;
|
||||
}
|
||||
long idleTimeoutMs = config.services().lambda().containerIdleTimeoutSeconds() * 1000L;
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
for (var entry : pool.entrySet()) {
|
||||
for (var entry : poolStates.entrySet()) {
|
||||
String functionName = entry.getKey();
|
||||
ArrayDeque<ContainerHandle> queue = entry.getValue();
|
||||
PoolState poolState = entry.getValue();
|
||||
List<ContainerHandle> toEvict = new ArrayList<>();
|
||||
|
||||
synchronized (queue) {
|
||||
queue.removeIf(handle -> {
|
||||
if (handle.getState() == ContainerState.WARM
|
||||
&& (now - handle.getLastUsedMs()) >= idleTimeoutMs) {
|
||||
toEvict.add(handle);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
synchronized (poolState) {
|
||||
for (ArrayDeque<ContainerHandle> idle : poolState.idleByEnvironment.values()) {
|
||||
idle.removeIf(handle -> {
|
||||
if (handle.getState() == ContainerState.WARM
|
||||
&& (now - handle.getLastUsedMs()) >= idleTimeoutMs) {
|
||||
toEvict.add(handle);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
poolState.idleByEnvironment.values().removeIf(ArrayDeque::isEmpty);
|
||||
}
|
||||
|
||||
// Re-check that the queue is still registered to avoid double-stop with drainFunction.
|
||||
if (!toEvict.isEmpty() && pool.get(functionName) == queue) {
|
||||
if (!toEvict.isEmpty()) {
|
||||
LOG.infov("Evicting {0} idle container(s) for function: {1}", toEvict.size(), functionName);
|
||||
for (ContainerHandle handle : toEvict) {
|
||||
stopQuietly(handle);
|
||||
@@ -287,6 +349,22 @@ public class WarmPool implements ContainerTeardown {
|
||||
}
|
||||
}
|
||||
|
||||
private static String executionEnvironmentKey(LambdaFunction fn) {
|
||||
String functionArn = fn.getFunctionArn();
|
||||
if (functionArn != null && !functionArn.isBlank()) {
|
||||
return functionArn;
|
||||
}
|
||||
return fn.getFunctionName() + ":" + fn.getVersion();
|
||||
}
|
||||
|
||||
private static int idleSize(PoolState poolState) {
|
||||
int size = 0;
|
||||
for (ArrayDeque<ContainerHandle> idle : poolState.idleByEnvironment.values()) {
|
||||
size += idle.size();
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
private void stopQuietly(ContainerHandle handle) {
|
||||
try {
|
||||
containerLauncher.stop(handle);
|
||||
|
||||
+42
@@ -32,13 +32,17 @@ import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@@ -274,6 +278,25 @@ public class ContainerLauncher {
|
||||
// enough that a shared volume's helper round-trip would only add cold-start latency.
|
||||
}
|
||||
|
||||
if (fn.getFileSystemConfigs() != null && !fn.getFileSystemConfigs().isEmpty()) {
|
||||
var efsCfg = config.storage().efs();
|
||||
fn.getFileSystemConfigs().forEach(fileSystem -> {
|
||||
String volumeName = efsVolumeName(fileSystem.getArn());
|
||||
lifecycleManager.ensureSharedVolume(volumeName,
|
||||
efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(),
|
||||
efsCfg.initImage());
|
||||
specBuilder.withNamedVolume(volumeName, fileSystem.getLocalMountPath(), false);
|
||||
});
|
||||
efsCfg.mountUser().ifPresent(user -> {
|
||||
if (!user.matches("^\\d+(:\\d+)?$")) {
|
||||
throw new IllegalArgumentException(
|
||||
"floci.storage.efs.mount-user must be \"uid\" or \"uid:gid\": " + user);
|
||||
}
|
||||
specBuilder.withUser(user);
|
||||
});
|
||||
efsCfg.mountGroupAdd().ifPresent(gid -> specBuilder.withGroupAdd(String.valueOf(gid)));
|
||||
}
|
||||
|
||||
// For Image package type use ImageConfig.Command/EntryPoint/WorkingDirectory if set, otherwise fall back to Handler (Zip-style)
|
||||
if ("Image".equals(fn.getPackageType())) {
|
||||
if (fn.getImageConfigEntryPoint() != null && !fn.getImageConfigEntryPoint().isEmpty()) {
|
||||
@@ -766,6 +789,25 @@ public class ContainerLauncher {
|
||||
return "floci-code-" + fname + "-" + h;
|
||||
}
|
||||
|
||||
static String efsVolumeName(String accessPointArn) {
|
||||
int separator = Math.max(accessPointArn.lastIndexOf('/'), accessPointArn.lastIndexOf(':'));
|
||||
String resourceId = separator >= 0 ? accessPointArn.substring(separator + 1) : accessPointArn;
|
||||
if (resourceId.isBlank()) {
|
||||
throw new IllegalArgumentException("File system access point ARN must include a resource id");
|
||||
}
|
||||
return "floci-efs-" + resourceId + "-" + sha256Hex(accessPointArn);
|
||||
}
|
||||
|
||||
private static String sha256Hex(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is required but not available", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Buffer for the tar-streaming pipe. The default {@link java.io.PipedInputStream} buffer is
|
||||
* only 1KB, which forces a writer/reader thread hand-off (wait/notify) every 1KB. Streaming a
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package io.github.hectorvent.floci.services.lambda.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public class LambdaFileSystemConfig {
|
||||
|
||||
private String arn;
|
||||
private String localMountPath;
|
||||
|
||||
public LambdaFileSystemConfig() {
|
||||
}
|
||||
|
||||
public LambdaFileSystemConfig(String arn, String localMountPath) {
|
||||
this.arn = arn;
|
||||
this.localMountPath = localMountPath;
|
||||
}
|
||||
|
||||
public String getArn() {
|
||||
return arn;
|
||||
}
|
||||
|
||||
public void setArn(String arn) {
|
||||
this.arn = arn;
|
||||
}
|
||||
|
||||
public String getLocalMountPath() {
|
||||
return localMountPath;
|
||||
}
|
||||
|
||||
public void setLocalMountPath(String localMountPath) {
|
||||
this.localMountPath = localMountPath;
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ public class LambdaFunction {
|
||||
private List<String> layers = new ArrayList<>();
|
||||
private String kmsKeyArn;
|
||||
private Map<String, Object> vpcConfig;
|
||||
private List<LambdaFileSystemConfig> fileSystemConfigs = new ArrayList<>();
|
||||
private String codeSha256;
|
||||
|
||||
/** Non-null only for hot-reload functions. Holds the Docker-host path bind-mounted into /var/task. */
|
||||
@@ -168,6 +169,11 @@ public class LambdaFunction {
|
||||
public Map<String, Object> getVpcConfig() { return vpcConfig; }
|
||||
public void setVpcConfig(Map<String, Object> vpcConfig) { this.vpcConfig = vpcConfig; }
|
||||
|
||||
public List<LambdaFileSystemConfig> getFileSystemConfigs() { return fileSystemConfigs; }
|
||||
public void setFileSystemConfigs(List<LambdaFileSystemConfig> fileSystemConfigs) {
|
||||
this.fileSystemConfigs = fileSystemConfigs == null ? new ArrayList<>() : new ArrayList<>(fileSystemConfigs);
|
||||
}
|
||||
|
||||
public String getCodeSha256() { return codeSha256; }
|
||||
public void setCodeSha256(String codeSha256) { this.codeSha256 = codeSha256; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user