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

@@ -31,6 +31,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -66,6 +67,8 @@ class ContainerLifecycleManagerLabelsTest {
void setUp() {
lenient().when(config.docker()).thenReturn(dockerConfig);
lenient().when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty());
lenient().when(imageCacheService.ensureImageExists(any()))
.thenAnswer(invocation -> invocation.getArgument(0));
}
@Test
@@ -77,6 +80,7 @@ class ContainerLifecycleManagerLabelsTest {
assertEquals(
Map.of("floci", "true", "floci_emulator", "floci-aws"),
capturedLabels(createCmd));
verify(imageCacheService).ensureImageExists("busybox:stable");
}
@Test
@@ -103,6 +107,31 @@ class ContainerLifecycleManagerLabelsTest {
capturedLabels(createCmd));
}
@Test
void createUsesRequestedDockerPlatform() {
when(imageCacheService.ensureImageExists("busybox:stable", "linux/arm64"))
.thenReturn("sha256:arm64");
CreateContainerCmd createCmd = stubCreateContainer("sha256:arm64");
manager().create(new ContainerSpec("busybox:stable"), "linux/arm64");
verify(imageCacheService).ensureImageExists("busybox:stable", "linux/arm64");
verify(dockerClient).createContainerCmd("sha256:arm64");
verify(createCmd).withPlatform("linux/arm64");
}
@Test
void createUsesResolvedImageForDaemonDefaultPlatform() {
when(imageCacheService.ensureImageExists("busybox:stable"))
.thenReturn("sha256:native");
CreateContainerCmd createCmd = stubCreateContainer("sha256:native");
manager().create(new ContainerSpec("busybox:stable"));
verify(dockerClient).createContainerCmd("sha256:native");
verify(createCmd, never()).withPlatform(any());
}
@Test
void createIncludesNamespaceLabelWhenConfigured() {
when(dockerConfig.resourceNamespace()).thenReturn(Optional.of("run-one"));
@@ -169,8 +198,12 @@ class ContainerLifecycleManagerLabelsTest {
}
private CreateContainerCmd stubCreateContainer() {
return stubCreateContainer("busybox:stable");
}
private CreateContainerCmd stubCreateContainer(String image) {
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
when(dockerClient.createContainerCmd(image)).thenReturn(createCmd);
CreateContainerResponse response = mock(CreateContainerResponse.class);
when(response.getId()).thenReturn("container-id");
when(createCmd.exec()).thenReturn(response);
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Locale;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class ContainerPlatformDockerIntegrationTest {
private static final Logger LOG = Logger.getLogger(ContainerPlatformDockerIntegrationTest.class);
private static final String IMAGE = "public.ecr.aws/docker/library/busybox:1.36";
@Inject
DockerClient dockerClient;
@Inject
ContainerBuilder containerBuilder;
@Inject
ContainerLifecycleManager lifecycleManager;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(),
"Docker daemon must be available for container platform integration tests");
}
@Test
void createUsesRequestedForeignPlatformImage() {
String hostArchitecture = dockerClient.infoCmd().exec().getArchitecture()
.toLowerCase(Locale.ROOT);
boolean armHost = hostArchitecture.equals("arm64") || hostArchitecture.equals("aarch64");
String requestedArchitecture = armHost ? "amd64" : "arm64";
String platform = "linux/" + requestedArchitecture;
ContainerSpec spec = containerBuilder.newContainer(IMAGE)
.withName("floci-platform-test-" + UUID.randomUUID())
.build();
String containerId = null;
try {
containerId = lifecycleManager.create(spec, platform);
String imageId = dockerClient.inspectContainerCmd(containerId).exec().getImageId();
assertEquals(requestedArchitecture,
dockerClient.inspectImageCmd(imageId).exec().getArch());
} finally {
if (containerId != null) {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
}
}
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (Exception e) {
LOG.warn("Docker daemon is not available for the container platform integration test", e);
return false;
}
}
}
@@ -591,6 +591,125 @@ class LambdaServiceTest {
assertEquals(List.of("x86_64"), service.getFunction(REGION, "arch-fn").getArchitectures());
}
@Test
void createFunctionRejectsUnsupportedArchitectureWithoutPersistingFunction() {
Map<String, Object> request = baseRequest("unsupported-create-architecture");
request.put("Architectures", List.of("sparc"));
AwsException error = assertThrows(AwsException.class,
() -> service.createFunction(REGION, request));
assertUnsupportedArchitecture(error);
assertTrue(service.listFunctions(REGION).isEmpty());
}
@Test
void createFunctionRejectsMultipleArchitecturesWithoutPersistingFunction() {
Map<String, Object> request = baseRequest("multiple-create-architectures");
request.put("Architectures", List.of("arm64", "x86_64"));
AwsException error = assertThrows(AwsException.class,
() -> service.createFunction(REGION, request));
assertEquals("InvalidParameterValueException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("1 validation error detected: Value '[arm64, x86_64]' at 'architectures' "
+ "failed to satisfy constraint: Member must have length less than or equal to 1",
error.getMessage());
assertTrue(service.listFunctions(REGION).isEmpty());
}
@Test
void createFunctionRejectsEmptyArchitecturesWithoutPersistingFunction() {
Map<String, Object> request = baseRequest("empty-create-architectures");
request.put("Architectures", List.of());
AwsException error = assertThrows(AwsException.class,
() -> service.createFunction(REGION, request));
assertEquals("InvalidParameterValueException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("1 validation error detected: Value '[]' at 'architectures' "
+ "failed to satisfy constraint: Member must have length greater than or equal to 1",
error.getMessage());
assertTrue(service.listFunctions(REGION).isEmpty());
}
@Test
void createFunctionRejectsScalarArchitecturesWithoutPersistingFunction() {
Map<String, Object> request = baseRequest("scalar-create-architectures");
request.put("Architectures", "arm64");
AwsException error = assertThrows(AwsException.class,
() -> service.createFunction(REGION, request));
assertMalformedArchitectures(error, "arm64");
assertTrue(service.listFunctions(REGION).isEmpty());
}
@Test
void updateFunctionCodeRejectsUnsupportedArchitectureBeforeMutation() {
service.createFunction(REGION, baseRequest("unsupported-code-architecture"));
AwsException error = assertThrows(AwsException.class,
() -> service.updateFunctionCode(REGION, "unsupported-code-architecture",
Map.of("ImageUri", "example.invalid/changed:latest",
"Architectures", List.of("sparc"))));
assertUnsupportedArchitecture(error);
LambdaFunction unchanged = service.getFunction(REGION, "unsupported-code-architecture");
assertNull(unchanged.getImageUri());
assertNull(unchanged.getArchitectures());
}
@Test
void updateFunctionCodeRejectsObjectArchitecturesBeforeMutation() {
service.createFunction(REGION, baseRequest("object-code-architectures"));
String revisionId = service.getFunction(REGION, "object-code-architectures").getRevisionId();
Map<String, String> malformedArchitectures = Map.of("Architecture", "arm64");
AwsException error = assertThrows(AwsException.class,
() -> service.updateFunctionCode(REGION, "object-code-architectures",
Map.of("ImageUri", "example.invalid/changed:latest",
"Architectures", malformedArchitectures)));
assertMalformedArchitectures(error, malformedArchitectures);
LambdaFunction unchanged = service.getFunction(REGION, "object-code-architectures");
assertNull(unchanged.getImageUri());
assertNull(unchanged.getArchitectures());
assertEquals(revisionId, unchanged.getRevisionId());
}
@Test
void updateFunctionConfigurationRejectsUnsupportedArchitectureBeforeMutation() {
service.createFunction(REGION, baseRequest("unsupported-config-architecture"));
AwsException error = assertThrows(AwsException.class,
() -> service.updateFunctionConfiguration(REGION, "unsupported-config-architecture",
Map.of("Description", "changed", "Architectures", List.of("sparc"))));
assertUnsupportedArchitecture(error);
LambdaFunction unchanged = service.getFunction(REGION, "unsupported-config-architecture");
assertNull(unchanged.getDescription());
assertNull(unchanged.getArchitectures());
}
@Test
void updateFunctionConfigurationRejectsScalarArchitecturesBeforeMutation() {
service.createFunction(REGION, baseRequest("scalar-config-architectures"));
String revisionId = service.getFunction(REGION, "scalar-config-architectures").getRevisionId();
AwsException error = assertThrows(AwsException.class,
() -> service.updateFunctionConfiguration(REGION, "scalar-config-architectures",
Map.of("Description", "changed", "Architectures", 64)));
assertMalformedArchitectures(error, 64);
LambdaFunction unchanged = service.getFunction(REGION, "scalar-config-architectures");
assertNull(unchanged.getDescription());
assertNull(unchanged.getArchitectures());
assertEquals(revisionId, unchanged.getRevisionId());
}
@Test
void updateFunctionCodeWithoutArchitecturesKeepsExisting() {
Map<String, Object> req = baseRequest("arch-keep-fn");
@@ -601,6 +720,22 @@ class LambdaServiceTest {
assertEquals(List.of("arm64"), updated.getArchitectures());
}
private static void assertUnsupportedArchitecture(AwsException error) {
assertEquals("InvalidParameterValueException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("1 validation error detected: Value 'sparc' at 'architectures.1.member' "
+ "failed to satisfy constraint: Member must satisfy enum value set: [x86_64, arm64]",
error.getMessage());
}
private static void assertMalformedArchitectures(AwsException error, Object value) {
assertEquals("InvalidParameterValueException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("1 validation error detected: Value '" + value + "' at 'architectures' "
+ "failed to satisfy constraint: Member must be a list",
error.getMessage());
}
@Test
void rehydrateConcurrency_restoresReservedFromStore() {
// Simulate a persisted state: functions already live in the store
@@ -33,6 +33,8 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
@@ -50,11 +52,13 @@ import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
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;
@@ -146,6 +150,7 @@ class ContainerLauncherTest {
// lenient: the failure-path test (populate fails before any container is created) never
// reaches these, but every success-path test does — they must not trip strict-stubs.
lenient().when(lifecycleManager.create(any())).thenReturn("container-123");
lenient().when(lifecycleManager.create(any(), anyString())).thenReturn("container-123");
ContainerLifecycleManager.ContainerInfo info =
new ContainerLifecycleManager.ContainerInfo("container-123", Map.of());
lenient().when(lifecycleManager.startCreated(eq("container-123"), any())).thenReturn(info);
@@ -204,6 +209,13 @@ class ContainerLauncherTest {
.orElseGet(() -> specs.get(specs.size() - 1));
}
private String captureRealContainerPlatform() {
ArgumentCaptor<String> platformCaptor = ArgumentCaptor.forClass(String.class);
verify(lifecycleManager, atLeastOnce()).create(any(ContainerSpec.class), platformCaptor.capture());
List<String> platforms = platformCaptor.getAllValues();
return platforms.get(platforms.size() - 1);
}
/** Returns the read-only {@code /var/task} volume mount on the spec, or null if absent. */
private static Mount varTaskVolumeMount(ContainerSpec spec) {
if (spec.mounts() == null) {
@@ -215,6 +227,137 @@ class ContainerLauncherTest {
.orElse(null);
}
@Test
void launchFunction_usesArm64DockerPlatformWhenArchitectureHonouringIsEnabled() throws Exception {
EmulatorConfig.LambdaServiceConfig lambda = config.services().lambda();
when(lambda.honourArchitectures()).thenReturn(true);
Path codePath = Files.createDirectory(tempDir.resolve("arm64-code"));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("arm64-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
fn.setArchitectures(List.of("arm64"));
launcher.launch(fn);
assertEquals("linux/arm64", captureRealContainerPlatform());
}
@Test
void launchFunction_usesAmd64DockerPlatformForX86Architecture() throws Exception {
EmulatorConfig.LambdaServiceConfig lambda = config.services().lambda();
when(lambda.honourArchitectures()).thenReturn(true);
Path codePath = Files.createDirectory(tempDir.resolve("x86-code"));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("x86-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
fn.setArchitectures(List.of("x86_64"));
launcher.launch(fn);
assertEquals("linux/amd64", captureRealContainerPlatform());
}
@Test
void launchFunction_usesAmd64DockerPlatformWhenArchitectureIsOmitted() throws Exception {
EmulatorConfig.LambdaServiceConfig lambda = config.services().lambda();
when(lambda.honourArchitectures()).thenReturn(true);
Path codePath = Files.createDirectory(tempDir.resolve("default-architecture-code"));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("default-architecture-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
launcher.launch(fn);
assertEquals("linux/amd64", captureRealContainerPlatform());
}
@Test
void launchFunction_keepsDaemonDefaultPlatformWhenArchitectureHonouringIsDisabled() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("native-platform-code"));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("native-platform-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
fn.setArchitectures(List.of("arm64"));
launcher.launch(fn);
captureRealContainerSpec();
verify(lifecycleManager, never()).create(any(ContainerSpec.class), anyString());
}
@ParameterizedTest
@MethodSource("invalidPersistedArchitectures")
void launchFunction_rejectsInvalidPersistedArchitecturesBeforeCreatingContainer(
List<String> architectures) throws Exception {
EmulatorConfig.LambdaServiceConfig lambda = config.services().lambda();
when(lambda.honourArchitectures()).thenReturn(true);
Path codePath = Files.createDirectory(tempDir.resolve("legacy-invalid-architecture-code"));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("legacy-invalid-architecture-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
fn.setArchitectures(architectures);
IllegalStateException exception = assertThrows(IllegalStateException.class,
() -> launcher.launch(fn));
assertEquals("Invalid persisted architectures " + architectures
+ " for function 'legacy-invalid-architecture-fn'", exception.getMessage());
verify(lifecycleManager, never()).create(any(ContainerSpec.class));
verify(lifecycleManager, never()).create(any(ContainerSpec.class), anyString());
assertSame(architectures, fn.getArchitectures());
}
private static Stream<List<String>> invalidPersistedArchitectures() {
return Stream.of(
List.of(),
List.of("riscv64"),
List.of("arm64", "x86_64"));
}
@Test
void launchFunction_usesArm64DockerPlatformForCodeVolumeHelper() throws Exception {
EmulatorConfig.LambdaServiceConfig lambda = config.services().lambda();
when(lambda.honourArchitectures()).thenReturn(true);
Path codePath = Files.createDirectory(tempDir.resolve("large-arm64-code"));
Files.write(codePath.resolve("bundle.bin"), new byte[8 * 1024]);
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("large-arm64-fn");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setCodeLocalPath(codePath.toString());
fn.setCodeSha256("large-arm64-code-sha");
fn.setArchitectures(List.of("arm64"));
long originalThreshold = ContainerLauncher.CODE_VOLUME_MIN_BYTES;
try {
ContainerLauncher.CODE_VOLUME_MIN_BYTES = 4 * 1024;
launcher.launch(fn);
} finally {
ContainerLauncher.CODE_VOLUME_MIN_BYTES = originalThreshold;
}
ArgumentCaptor<String> platformCaptor = ArgumentCaptor.forClass(String.class);
verify(lifecycleManager, times(2)).create(any(ContainerSpec.class), platformCaptor.capture());
assertTrue(platformCaptor.getAllValues().stream()
.allMatch("linux/arm64"::equals));
}
@Test
void launchFunction_labelsContainerWithResourceIdentity() throws Exception {
Path codePath = Files.createDirectory(tempDir.resolve("code"));
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectImageCmd;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.PullImageCmd;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.exception.DockerClientException;
@@ -9,6 +11,7 @@ import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.exception.InternalServerErrorException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.exception.UnauthorizedException;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import org.junit.jupiter.api.Test;
@@ -21,8 +24,10 @@ 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.nullable;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -37,7 +42,11 @@ class ImageCacheServiceTest {
PullImageCmd pullImage = mock(PullImageCmd.class);
PullImageResultCallback callback = mock(PullImageResultCallback.class);
when(dockerClient.inspectImageCmd(IMAGE)).thenReturn(inspectImage);
when(inspectImage.exec()).thenThrow(new NotFoundException("image not found"));
when(inspectImage.exec()).thenThrow(new NotFoundException("image not found"))
.thenReturn(new InspectImageResponse()
.withId("sha256:native")
.withOs("linux")
.withArch("amd64"));
when(dockerClient.pullImageCmd(IMAGE)).thenReturn(pullImage);
when(pullImage.withAuthConfig(any())).thenReturn(pullImage);
when(pullImage.exec(any(PullImageResultCallback.class))).thenReturn(callback);
@@ -45,6 +54,7 @@ class ImageCacheServiceTest {
newService(dockerClient).ensureImageExists(IMAGE);
verify(pullImage).exec(any(PullImageResultCallback.class));
verify(pullImage, never()).withPlatform(nullable(String.class));
verify(callback).awaitCompletion(5, TimeUnit.MINUTES);
}
@@ -63,6 +73,139 @@ class ImageCacheServiceTest {
verify(dockerClient, never()).pullImageCmd(IMAGE);
}
@Test
void pullsRequestedPlatformWhenLocalImageArchitectureDoesNotMatch() throws Exception {
DockerClient dockerClient = mock(DockerClient.class);
InspectImageCmd inspectImage = mock(InspectImageCmd.class);
PullImageCmd pullImage = mock(PullImageCmd.class);
PullImageResultCallback callback = mock(PullImageResultCallback.class);
when(dockerClient.inspectImageCmd(IMAGE)).thenReturn(inspectImage);
when(inspectImage.exec()).thenReturn(
new InspectImageResponse().withOs("linux").withArch("amd64"),
new InspectImageResponse().withId("sha256:arm64").withOs("linux").withArch("arm64"));
when(dockerClient.pullImageCmd(IMAGE)).thenReturn(pullImage);
when(pullImage.withAuthConfig(any())).thenReturn(pullImage);
when(pullImage.withPlatform("linux/arm64")).thenReturn(pullImage);
when(pullImage.exec(any(PullImageResultCallback.class))).thenReturn(callback);
String resolvedImage = newService(dockerClient)
.ensureImageExists(IMAGE, "linux/arm64");
assertEquals("sha256:arm64", resolvedImage);
verify(pullImage).withPlatform("linux/arm64");
verify(callback).awaitCompletion(5, TimeUnit.MINUTES);
}
@Test
void skipsPullWhenLocalImageMatchesRequestedPlatform() {
DockerClient dockerClient = mock(DockerClient.class);
InspectImageCmd inspectImage = mock(InspectImageCmd.class);
when(dockerClient.inspectImageCmd(IMAGE)).thenReturn(inspectImage);
when(inspectImage.exec()).thenReturn(new InspectImageResponse()
.withId("sha256:arm64")
.withOs("linux")
.withArch("arm64"));
String resolvedImage = newService(dockerClient)
.ensureImageExists(IMAGE, "linux/arm64");
assertEquals("sha256:arm64", resolvedImage);
verify(dockerClient, never()).pullImageCmd(IMAGE);
}
@Test
void keepsDifferentPlatformsAsSeparateCacheRequests() {
DockerClient dockerClient = mock(DockerClient.class);
InspectImageCmd inspectImage = mock(InspectImageCmd.class);
PullImageCmd pullImage = mock(PullImageCmd.class);
PullImageResultCallback callback = mock(PullImageResultCallback.class);
when(dockerClient.inspectImageCmd(IMAGE)).thenReturn(inspectImage);
when(inspectImage.exec()).thenReturn(
new InspectImageResponse().withOs("linux").withArch("amd64"),
new InspectImageResponse().withId("sha256:arm64").withOs("linux").withArch("arm64"),
new InspectImageResponse().withOs("linux").withArch("arm64"),
new InspectImageResponse().withId("sha256:amd64").withOs("linux").withArch("amd64"));
when(dockerClient.pullImageCmd(IMAGE)).thenReturn(pullImage);
when(pullImage.withAuthConfig(any())).thenReturn(pullImage);
when(pullImage.withPlatform("linux/arm64")).thenReturn(pullImage);
when(pullImage.withPlatform("linux/amd64")).thenReturn(pullImage);
when(pullImage.exec(any(PullImageResultCallback.class))).thenReturn(callback);
ImageCacheService service = newService(dockerClient);
String armImage = service.ensureImageExists(IMAGE, "linux/arm64");
String amdImage = service.ensureImageExists(IMAGE, "linux/amd64");
assertEquals("sha256:arm64", armImage);
assertEquals("sha256:amd64", amdImage);
verify(pullImage).withPlatform("linux/arm64");
verify(pullImage).withPlatform("linux/amd64");
}
@Test
void restoresDaemonDefaultImageAfterPlatformSpecificPull() throws Exception {
DockerClient dockerClient = mock(DockerClient.class);
InspectImageCmd inspectImage = mock(InspectImageCmd.class);
PullImageCmd pullImage = mock(PullImageCmd.class);
PullImageResultCallback callback = mock(PullImageResultCallback.class);
when(dockerClient.inspectImageCmd(IMAGE)).thenReturn(inspectImage);
when(inspectImage.exec()).thenThrow(new NotFoundException("image not found"))
.thenReturn(new InspectImageResponse()
.withId("sha256:arm64")
.withOs("linux")
.withArch("arm64"),
new InspectImageResponse()
.withId("sha256:arm64")
.withOs("linux")
.withArch("arm64"),
new InspectImageResponse()
.withId("sha256:amd64")
.withOs("linux")
.withArch("amd64"));
when(dockerClient.pullImageCmd(IMAGE)).thenReturn(pullImage);
when(pullImage.withAuthConfig(any())).thenReturn(pullImage);
when(pullImage.withPlatform("linux/arm64")).thenReturn(pullImage);
when(pullImage.exec(any(PullImageResultCallback.class))).thenReturn(callback);
ImageCacheService service = newService(dockerClient);
service.ensureImageExists(IMAGE, "linux/arm64");
service.ensureImageExists(IMAGE);
verify(pullImage, times(2)).exec(any(PullImageResultCallback.class));
verify(pullImage).withPlatform("linux/arm64");
}
@Test
void repullsPlatformImageWhenCachedImageWasRemoved() throws Exception {
DockerClient dockerClient = mock(DockerClient.class);
InspectImageCmd inspectImage = mock(InspectImageCmd.class);
InspectImageCmd inspectCachedImage = mock(InspectImageCmd.class);
PullImageCmd pullImage = mock(PullImageCmd.class);
PullImageResultCallback callback = mock(PullImageResultCallback.class);
when(dockerClient.inspectImageCmd(IMAGE)).thenReturn(inspectImage);
when(dockerClient.inspectImageCmd("sha256:arm64-old")).thenReturn(inspectCachedImage);
when(inspectImage.exec()).thenReturn(
new InspectImageResponse()
.withId("sha256:arm64-old")
.withOs("linux")
.withArch("arm64"),
new InspectImageResponse().withOs("linux").withArch("amd64"),
new InspectImageResponse()
.withId("sha256:arm64-new")
.withOs("linux")
.withArch("arm64"));
when(inspectCachedImage.exec()).thenThrow(new NotFoundException("image was removed"));
when(dockerClient.pullImageCmd(IMAGE)).thenReturn(pullImage);
when(pullImage.withAuthConfig(any())).thenReturn(pullImage);
when(pullImage.withPlatform("linux/arm64")).thenReturn(pullImage);
when(pullImage.exec(any(PullImageResultCallback.class))).thenReturn(callback);
ImageCacheService service = newService(dockerClient);
assertEquals("sha256:arm64-old", service.ensureImageExists(IMAGE, "linux/arm64"));
assertEquals("sha256:arm64-new", service.ensureImageExists(IMAGE, "linux/arm64"));
verify(pullImage).exec(any(PullImageResultCallback.class));
}
@Test
void succeedsOnFirstAttempt() throws Exception {
AtomicInteger calls = new AtomicInteger();
@@ -163,6 +306,9 @@ class ImageCacheServiceTest {
}
private static ImageCacheService newService(DockerClient dockerClient) {
InfoCmd infoCmd = mock(InfoCmd.class);
when(dockerClient.infoCmd()).thenReturn(infoCmd);
when(infoCmd.exec()).thenReturn(new Info().withOsType("linux").withArchitecture("amd64"));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.DockerConfig dockerConfig = mock(EmulatorConfig.DockerConfig.class);
when(config.docker()).thenReturn(dockerConfig);