fix(lambda): honor configured function architecture (#2994)

* fix(lambda): honor configured function architecture

* fix(lambda): isolate Docker images by platform

* fix(lambda): reject unsupported architectures early

* fix(lambda): require one function architecture

Note: pre-existing full-suite flakes in EC2, Kinesis Analytics, and RDS Data passed in isolated reruns.

* fix(lambda): preserve legacy architecture fallback

* fix(lambda): reject malformed architecture fields

* fix(lambda): reject invalid persisted architectures
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-04 09:22:23 -04:00
1 parent ee24c77d02
commit 7fdd145c0c
14 files changed
+762 -49

No files matched your search

@@ -1861,6 +1861,16 @@ public interface EmulatorConfig {
@WithDefault("false")
boolean ephemeral();
/**
* When true, Docker Lambda containers use the platform declared by the function's
* Architectures value. Disabled by default because foreign-platform containers require
* host support such as binfmt_misc or QEMU.
*
* Env var: FLOCI_SERVICES_LAMBDA_HONOUR_ARCHITECTURES
*/
@WithDefault("false")
boolean honourArchitectures();
@WithDefault("300")
int containerIdleTimeoutSeconds();
@@ -102,15 +102,34 @@ public class ContainerLifecycleManager {
* @return the container ID
*/
public String create(ContainerSpec spec) {
LOG.debugv("Creating container from spec: image={0}, name={1}", spec.image(), spec.name());
String resolvedImage = imageCacheService.ensureImageExists(spec.image());
return create(spec, resolvedImage, null);
}
imageCacheService.ensureImageExists(spec.image());
/**
* Creates a container for a specific Docker platform.
*
* @param spec the container specification
* @param platform Docker platform, such as {@code linux/arm64}
* @return the container ID
*/
public String create(ContainerSpec spec, String platform) {
String resolvedImage = imageCacheService.ensureImageExists(spec.image(), platform);
return create(spec, resolvedImage, platform);
}
private String create(ContainerSpec spec, String resolvedImage, String platform) {
LOG.debugv("Creating container from spec: image={0}, name={1}", spec.image(), spec.name());
HostConfig hostConfig = buildHostConfig(spec);
CreateContainerCmd createCmd = dockerClient.createContainerCmd(spec.image())
CreateContainerCmd createCmd = dockerClient.createContainerCmd(resolvedImage)
.withHostConfig(hostConfig);
if (platform != null && !platform.isBlank()) {
createCmd.withPlatform(platform);
}
if (spec.name() != null) {
createCmd.withName(spec.name());
}
@@ -75,6 +75,7 @@ public class LambdaService implements ResourceProvider {
"arn:(aws[a-zA-Z-]*)?:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+");
private static final Pattern HANDLER_PATTERN = Pattern.compile("\\S+");
private static final int MAX_HANDLER_LENGTH = 128;
private static final List<String> FUNCTION_ARCHITECTURES = List.of("x86_64", "arm64");
private final LambdaFunctionStore functionStore;
private final LambdaExecutorService executorService;
@@ -338,6 +339,7 @@ public class LambdaService implements ResourceProvider {
throw new AwsException("ResourceConflictException",
"Function already exist: " + functionName, 409);
}
List<String> architectures = validateArchitectures(request.get("Architectures"));
LambdaFunction fn = new LambdaFunction();
fn.setAccountId(regionResolver.getAccountId());
@@ -368,10 +370,6 @@ public class LambdaService implements ResourceProvider {
Map<String, String> tags = (Map<String, String>) request.get("Tags");
if (tags != null) fn.setTags(tags);
// Architectures
@SuppressWarnings("unchecked")
List<String> architectures = request.get("Architectures") instanceof List
? (List<String>) request.get("Architectures") : null;
if (architectures != null && !architectures.isEmpty()) {
fn.setArchitectures(new ArrayList<>(architectures));
}
@@ -555,6 +553,7 @@ public class LambdaService implements ResourceProvider {
public LambdaFunction updateFunctionCode(String region, String functionName, Map<String, Object> request) {
LambdaFunction fn = getFunction(region, functionName);
functionName = fn.getFunctionName();
List<String> architectures = validateArchitectures(request.get("Architectures"));
String zipFileBase64 = (String) request.get("ZipFile");
String imageUri = (String) request.get("ImageUri");
@@ -577,13 +576,8 @@ public class LambdaService implements ResourceProvider {
}
}
if (request.containsKey("Architectures")) {
@SuppressWarnings("unchecked")
List<String> archs = request.get("Architectures") instanceof List
? (List<String>) request.get("Architectures") : null;
if (archs != null && !archs.isEmpty()) {
fn.setArchitectures(new ArrayList<>(archs));
}
if (architectures != null) {
fn.setArchitectures(new ArrayList<>(architectures));
}
fn.setLastModified(System.currentTimeMillis());
@@ -602,6 +596,7 @@ public class LambdaService implements ResourceProvider {
public LambdaFunction updateFunctionConfiguration(String region, String functionName, Map<String, Object> request) {
LambdaFunction fn = getFunction(region, functionName);
List<String> architectures = validateArchitectures(request.get("Architectures"));
// Validated before any field mutation below, not inline where Layers is applied further
// down - fn is the live object backing this store entry (InMemoryStorage#get returns the
@@ -680,13 +675,8 @@ public class LambdaService implements ResourceProvider {
}
}
if (request.containsKey("Architectures")) {
@SuppressWarnings("unchecked")
List<String> archs = request.get("Architectures") instanceof List
? (List<String>) request.get("Architectures") : null;
if (archs != null && !archs.isEmpty()) {
fn.setArchitectures(new ArrayList<>(archs));
}
if (architectures != null) {
fn.setArchitectures(new ArrayList<>(architectures));
}
if (request.containsKey("EphemeralStorage")) {
@@ -1515,6 +1505,41 @@ public class LambdaService implements ResourceProvider {
return parsed;
}
private static List<String> validateArchitectures(Object value) {
if (value == null) {
return null;
}
if (!(value instanceof List<?> architectures)) {
throw new AwsException("InvalidParameterValueException",
"1 validation error detected: Value '" + value + "' at 'architectures' "
+ "failed to satisfy constraint: Member must be a list",
400);
}
if (architectures.isEmpty()) {
throw new AwsException("InvalidParameterValueException",
"1 validation error detected: Value '[]' at 'architectures' "
+ "failed to satisfy constraint: Member must have length greater than or equal to 1",
400);
}
if (architectures.size() > 1) {
throw new AwsException("InvalidParameterValueException",
"1 validation error detected: Value '" + architectures + "' at 'architectures' "
+ "failed to satisfy constraint: Member must have length less than or equal to 1",
400);
}
Object architecture = architectures.getFirst();
if (!FUNCTION_ARCHITECTURES.contains(architecture)) {
throw new AwsException("InvalidParameterValueException",
"1 validation error detected: Value '" + architecture
+ "' at 'architectures.1.member' "
+ "failed to satisfy constraint: Member must satisfy enum value set: "
+ FUNCTION_ARCHITECTURES,
400);
}
return List.of((String) architecture);
}
private static void validateFileSystemVpcConfig(List<LambdaFileSystemConfig> fileSystemConfigs,
Map<String, Object> vpcConfig) {
if (fileSystemConfigs == null || fileSystemConfigs.isEmpty()) {
@@ -372,7 +372,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
// Create container without starting — provided.* runtimes exec
// /var/runtime/bootstrap on start, so code must be copied first.
containerId = lifecycleManager.create(spec);
containerId = createContainer(spec, fn);
LOG.infov("Created container {0} for function {1}", containerId, fn.getFunctionName());
// Docker now holds the real container-to-volume reference, which removeVolume's own in-use
// check protects from here on - release the in-flight marker that stood in for it before
@@ -515,6 +515,33 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
}
private static Optional<String> dockerPlatform(LambdaFunction fn) {
List<String> architectures = fn.getArchitectures();
if (architectures == null) {
return Optional.of("linux/amd64");
}
if (architectures.size() != 1) {
return Optional.empty();
}
return switch (architectures.getFirst()) {
case "arm64" -> Optional.of("linux/arm64");
case "x86_64" -> Optional.of("linux/amd64");
default -> Optional.empty();
};
}
private String createContainer(ContainerSpec spec, LambdaFunction fn) {
if (!config.services().lambda().honourArchitectures()) {
return lifecycleManager.create(spec);
}
Optional<String> platform = dockerPlatform(fn);
if (platform.isEmpty()) {
throw new IllegalStateException("Invalid persisted architectures "
+ fn.getArchitectures() + " for function '" + fn.getFunctionName() + "'");
}
return lifecycleManager.create(spec, platform.get());
}
public void stop(ContainerHandle handle) {
LOG.infov("Stopping container {0}", handle.getContainerId());
handle.setState(ContainerState.STOPPED);
@@ -876,19 +903,19 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
String shortId = java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 8);
// A minimal helper container (sleep) with the volume mounted read-write at /var/task; we
// tar-copy the code into it, then discard it — the data persists in the volume.
ContainerSpec helperSpec = containerBuilder.newContainer(image)
ContainerBuilder.Builder helperBuilder = containerBuilder.newContainer(image)
.withName(resolveContainerNamePrefix(config) + "-codevol-" + fn.getFunctionName() + "-" + shortId)
.withEnv(java.util.List.of())
.withEntrypoint(java.util.List.of("sleep"))
.withCmd(java.util.List.of("3600"))
.withNamedVolume(volName, TASK_DIR, false)
.build();
.withNamedVolume(volName, TASK_DIR, false);
ContainerSpec helperSpec = helperBuilder.build();
// Gate the heavy work (helper create + ~90MB tar copy) so a burst of first-time populates
// doesn't thrash the Docker daemon. Only populates are serialized — plain cold starts aren't.
acquirePopulatePermit(fn.getFunctionName());
String helperId = null;
try {
helperId = lifecycleManager.create(helperSpec);
helperId = createContainer(helperSpec, fn);
lifecycleManager.startCreated(helperId, helperSpec);
copyDirToContainerStrict(lifecycleManager.getDockerClient(), helperId,
Path.of(fn.getCodeLocalPath()), TASK_DIR, fn.getFunctionName());
@@ -1,22 +1,26 @@
package io.github.hectorvent.floci.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.PullImageCmd;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.InternalServerErrorException;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.Set;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* Ensures each Docker image is pulled only once.
* Ensures each Docker image is pulled only once per platform.
* Thread-safe using ConcurrentHashMap for double-checked locking per image.
*/
@ApplicationScoped
@@ -29,8 +33,9 @@ public class ImageCacheService {
private final DockerClient dockerClient;
private final List<EmulatorConfig.DockerConfig.RegistryCredential> registryCredentials;
private final Set<String> pulledImages = ConcurrentHashMap.newKeySet();
private final Map<ImageKey, String> resolvedImages = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
private volatile String daemonPlatform;
@Inject
public ImageCacheService(DockerClient dockerClient, EmulatorConfig config) {
@@ -38,29 +43,47 @@ public class ImageCacheService {
this.registryCredentials = config.docker().registryCredentials();
}
public void ensureImageExists(String imageUri) {
if (pulledImages.contains(imageUri)) {
return;
public String ensureImageExists(String imageUri) {
return ensureImageExists(imageUri, null);
}
public String ensureImageExists(String imageUri, String platform) {
boolean explicitPlatform = platform != null && !platform.isBlank();
String requestedPlatform = explicitPlatform ? platform.trim() : daemonPlatform();
ImageKey imageKey = new ImageKey(imageUri, requestedPlatform);
String resolvedImage = validResolvedImage(imageKey);
if (resolvedImage != null) {
return resolvedImage;
}
Object lock = locks.computeIfAbsent(imageUri, k -> new Object());
synchronized (lock) {
if (pulledImages.contains(imageUri)) {
return;
resolvedImage = validResolvedImage(imageKey);
if (resolvedImage != null) {
return resolvedImage;
}
if (isLocalImagePresent(imageUri)) {
pulledImages.add(imageUri);
InspectImageResponse localImage = inspectLocalImage(imageUri);
if (matchesPlatform(localImage, requestedPlatform)) {
resolvedImage = resolvedImageReference(imageUri, requestedPlatform, localImage);
resolvedImages.put(imageKey, resolvedImage);
LOG.infov("Image already present locally, skipping pull: {0}", imageUri);
return;
return resolvedImage;
}
LOG.infov("Pulling image: {0}", imageUri);
try {
runWithRetry(imageUri, MAX_PULL_ATTEMPTS, INITIAL_BACKOFF_MS,
() -> dockerClient.pullImageCmd(imageUri)
.withAuthConfig(resolveAuth(imageUri))
.exec(new PullImageResultCallback())
.awaitCompletion(5, TimeUnit.MINUTES));
pulledImages.add(imageUri);
runWithRetry(imageUri, MAX_PULL_ATTEMPTS, INITIAL_BACKOFF_MS, () -> {
PullImageCmd pullImage = dockerClient.pullImageCmd(imageUri)
.withAuthConfig(resolveAuth(imageUri));
if (explicitPlatform) {
pullImage.withPlatform(requestedPlatform);
}
pullImage.exec(new PullImageResultCallback())
.awaitCompletion(5, TimeUnit.MINUTES);
});
resolvedImage = resolvedImageReference(imageUri, requestedPlatform,
inspectLocalImage(imageUri));
resolvedImages.put(imageKey, resolvedImage);
LOG.infov("Image pulled successfully: {0}", imageUri);
return resolvedImage;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while pulling image: " + imageUri, e);
@@ -118,15 +141,78 @@ public class ImageCacheService {
void run() throws InterruptedException;
}
private boolean isLocalImagePresent(String imageUri) {
private InspectImageResponse inspectLocalImage(String imageUri) {
try {
dockerClient.inspectImageCmd(imageUri).exec();
return true;
return dockerClient.inspectImageCmd(imageUri).exec();
} catch (com.github.dockerjava.api.exception.NotFoundException e) {
return false;
return null;
}
}
private String validResolvedImage(ImageKey imageKey) {
String resolvedImage = resolvedImages.get(imageKey);
if (resolvedImage == null) {
return null;
}
if (inspectLocalImage(resolvedImage) != null) {
return resolvedImage;
}
resolvedImages.remove(imageKey, resolvedImage);
return null;
}
private String daemonPlatform() {
String resolvedPlatform = daemonPlatform;
if (resolvedPlatform != null) {
return resolvedPlatform;
}
Info info = dockerClient.infoCmd().exec();
String architecture = info.getArchitecture();
if (architecture == null || architecture.isBlank()) {
throw new DockerClientException("Docker did not report its architecture");
}
String os = info.getOsType();
if (os == null || os.isBlank()) {
os = "linux";
}
String normalizedArchitecture = switch (architecture.toLowerCase(Locale.ROOT)) {
case "aarch64" -> "arm64";
case "x86_64" -> "amd64";
default -> architecture.toLowerCase(Locale.ROOT);
};
resolvedPlatform = os.toLowerCase(Locale.ROOT) + "/" + normalizedArchitecture;
daemonPlatform = resolvedPlatform;
return resolvedPlatform;
}
private static boolean matchesPlatform(InspectImageResponse image, String platform) {
if (image == null) {
return false;
}
if (platform == null) {
return true;
}
String[] parts = platform.split("/", 2);
return parts.length == 2
&& parts[0].equals(image.getOs())
&& parts[1].equals(image.getArch());
}
private static String resolvedImageReference(String imageUri, String platform,
InspectImageResponse image) {
if (!matchesPlatform(image, platform)) {
throw new DockerClientException(
"Docker image does not match requested platform " + platform + ": " + imageUri);
}
String imageId = image.getId();
if (imageId == null || imageId.isBlank()) {
throw new DockerClientException("Docker did not report an image ID for: " + imageUri);
}
return imageId;
}
private record ImageKey(String imageUri, String platform) {}
private AuthConfig resolveAuth(String imageUri) {
String host = extractRegistryHost(imageUri);
for (EmulatorConfig.DockerConfig.RegistryCredential cred : registryCredentials) {