fix(docker): rebuild local helpers for daemon platform and recipe (#7222)

* fix(docker): rebuild local helpers for daemon platform and recipe

Preserve the complete retained helper platform and recipe feature from fork #301 on current main. Rebuild foreign-platform or stale-recipe helpers, explicitly pull the native base, and retain the isolated Docker regression and existing workload launch-platform API.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(docker): isolate helper platform and reuse checks

Give foreign-platform fixtures the current recipe label and count real Docker build requests so cached image IDs cannot mask an unnecessary rebuild.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
Signed-off-by: Andre Kurait <akurait@amazon.com>

* test: share cached helper image fixtures

Reuse one cached-image stub and recipe hashing helper across helper-image and ECS proxy fixtures. Gate native helper execution on the shared Docker availability probe instead of an opt-in property. Preserve platform and actual build-count assertions. Addresses upstream review 5729804211.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test: restore shared base image after helper platform checks

Preserve the original base image tag through successful, skipped and failed helper-platform fixtures. Keep the requested Docker availability gate and the existing native-build and cache-reuse assertions.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-01 16:08:16 -04:00
1 parent 3c5e8936f2
commit 7bae152c69
11 files changed
+436 -62

No files matched your search

@@ -0,0 +1,42 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.model.Info;
import java.util.Locale;
/** Platform selection shared by native helper builds and workload image resolution. */
public final class DockerPlatform {
private DockerPlatform() {}
public static String daemon(DockerClient dockerClient) {
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);
};
return os.toLowerCase(Locale.ROOT) + "/" + normalizedArchitecture;
}
public static boolean matches(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());
}
}
@@ -2,7 +2,9 @@ package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.BuildImageResultCallback;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.core.common.Digests;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
@@ -10,10 +12,11 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
/**
* Builds a Floci-recipe helper image in the workload daemon the first time something needs it,
* Builds a Floci-recipe helper image for the workload daemon's platform when needed,
* instead of trying to pull an image that only exists as a Dockerfile checked into Floci itself.
* Security-group enforcement is the caller today; this exists as a shared utility because a second
* one is coming (an ECS task-role credentials proxy needs the same image), and the alternative was
@@ -22,6 +25,8 @@ import java.util.Set;
*/
public final class LocallyBuiltHelperImage {
static final String RECIPE_LABEL = "io.floci.helper.recipe-sha256";
private LocallyBuiltHelperImage() {
}
@@ -39,17 +44,23 @@ public final class LocallyBuiltHelperImage {
return;
}
String image = containerBuilder.resolveImage(configuredImage);
try {
dockerClient.inspectImageCmd(image).exec();
return;
} catch (NotFoundException missing) {
// Build the versioned Floci recipe in the daemon used for workloads.
}
String platform = DockerPlatform.daemon(dockerClient);
try (InputStream dockerfile = LocallyBuiltHelperImage.class.getResourceAsStream(dockerfileResourcePath)) {
if (dockerfile == null) {
throw new IllegalStateException("Floci helper Dockerfile is missing: " + dockerfileResourcePath);
}
byte[] content = dockerfile.readAllBytes();
String recipe = Digests.sha256Hex(content);
try {
InspectImageResponse cached = dockerClient.inspectImageCmd(image).exec();
if (DockerPlatform.matches(cached, platform) && cached.getConfig() != null
&& cached.getConfig().getLabels() != null
&& recipe.equals(cached.getConfig().getLabels().get(RECIPE_LABEL))) {
return;
}
} catch (NotFoundException missing) {
// Build the current Floci recipe in the daemon used for workloads.
}
ByteArrayOutputStream archive = new ByteArrayOutputStream(content.length + 1024);
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) {
TarArchiveEntry entry = new TarArchiveEntry("Dockerfile");
@@ -60,7 +71,8 @@ public final class LocallyBuiltHelperImage {
}
try (BuildImageResultCallback callback = new BuildImageResultCallback()) {
String built = dockerClient.buildImageCmd(new ByteArrayInputStream(archive.toByteArray()))
.withTags(Set.of(image)).exec(callback).awaitImageId();
.withTags(Set.of(image)).withPlatform(platform).withPull(true)
.withLabels(Map.of(RECIPE_LABEL, recipe)).exec(callback).awaitImageId();
if (built == null || built.isBlank()) {
throw new IllegalStateException("Docker did not build the Floci helper image: " + image);
}
@@ -8,18 +8,17 @@ import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.InternalServerErrorException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.Info;
import com.github.dockerjava.api.model.PullResponseItem;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.docker.DockerClientProducer;
import io.github.hectorvent.floci.core.common.docker.DockerPlatform;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -83,7 +82,7 @@ public class ImageCacheService {
return resolvedImage;
}
InspectImageResponse localImage = inspectLocalImage(imageUri);
if (matchesPlatform(localImage, requestedPlatform)) {
if (DockerPlatform.matches(localImage, requestedPlatform)) {
resolvedImage = resolvedImageReference(imageUri, localImage);
resolvedImages.put(imageKey, resolvedImage);
LOG.infov("Image already present locally, skipping pull: {0}", imageUri);
@@ -178,7 +177,7 @@ public class ImageCacheService {
private InspectImageResponse cachedImage(ImageKey imageKey) {
InspectImageResponse local = inspectLocalImage(imageKey.imageUri());
return matchesPlatform(local, imageKey.platform()) ? local : null;
return DockerPlatform.matches(local, imageKey.platform()) ? local : null;
}
/**
@@ -344,38 +343,11 @@ public class ImageCacheService {
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;
resolvedPlatform = DockerPlatform.daemon(dockerClient);
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());
}
/**
* Resolves the reference the container is created from. Inspecting the image cannot confirm
* the platform on Docker 29, whose containerd image store is the default: for an image whose
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.core.common.docker;
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.model.ContainerConfig;
import io.github.hectorvent.floci.core.common.Digests;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Map;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Cached helper images with explicit platform and recipe metadata for Docker client fixtures. */
public final class CachedImageStubs {
private CachedImageStubs() {
}
public static void image(DockerClient docker, String reference, String os, String architecture, String recipe) {
InspectImageResponse image = mock(InspectImageResponse.class);
when(image.getOs()).thenReturn(os);
when(image.getArch()).thenReturn(architecture);
when(image.getConfig()).thenReturn(new ContainerConfig().withLabels(recipe == null
? Map.of() : Map.of(LocallyBuiltHelperImage.RECIPE_LABEL, recipe)));
InspectImageCmd inspect = mock(InspectImageCmd.class);
when(inspect.exec()).thenReturn(image);
when(docker.inspectImageCmd(reference)).thenReturn(inspect);
}
public static String recipe(String dockerfile) {
try (InputStream stream = CachedImageStubs.class.getResourceAsStream(dockerfile)) {
if (stream == null) {
throw new IllegalArgumentException("Missing fixture Dockerfile: " + dockerfile);
}
return Digests.sha256Hex(stream.readAllBytes());
} catch (IOException failure) {
throw new UncheckedIOException("Cannot read fixture Dockerfile: " + dockerfile, failure);
}
}
}
@@ -0,0 +1,93 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.smallrye.config.SmallRyeConfigBuilder;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** Builds and reuses a native helper when the configured Docker daemon answers. */
class LocallyBuiltHelperImageDockerIntegrationTest {
private static final String BASE = "busybox:1.37.0";
@Test
void helperBuildReplacesForeignHelperAndBaseWithNativeExecutableImage() throws Exception {
EmulatorConfig config = new SmallRyeConfigBuilder().withMapping(EmulatorConfig.class)
.build().getConfigMapping(EmulatorConfig.class);
try (DockerClient docker = spy(new DockerClientProducer(config).dockerClient())) {
Assumptions.assumeTrue(DockerAvailability.answers(docker), "Docker daemon is unavailable");
String nativePlatform = DockerPlatform.daemon(docker);
Assumptions.assumeTrue(nativePlatform.equals("linux/amd64") || nativePlatform.equals("linux/arm64"));
String foreignPlatform = nativePlatform.equals("linux/amd64") ? "linux/arm64" : "linux/amd64";
try (PreservedImageTag base = new PreservedImageTag(docker, "busybox", "1.37.0")) {
try (PullImageResultCallback pulled = new PullImageResultCallback()) {
assertTrue(docker.pullImageCmd(BASE).withPlatform(foreignPlatform).exec(pulled)
.awaitCompletion(120, TimeUnit.SECONDS));
}
String tag = UUID.randomUUID().toString();
String repository = "floci/helper-platform-test";
String helper = repository + ":" + tag;
String containerId = null;
docker.tagImageCmd(BASE, repository, tag).exec();
try {
Assumptions.assumeTrue(DockerPlatform.matches(docker.inspectImageCmd(helper).exec(), foreignPlatform),
"This daemon does not expose the cached foreign image platform");
ContainerBuilder builder = new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class));
LocallyBuiltHelperImage.ensureBuilt(docker, builder, helper, helper,
"/docker/native-platform-helper.Dockerfile");
assertTrue(DockerPlatform.matches(docker.inspectImageCmd(helper).exec(), nativePlatform));
String builtImage = docker.inspectImageCmd(helper).exec().getId();
LocallyBuiltHelperImage.ensureBuilt(docker, builder, helper, helper,
"/docker/native-platform-helper.Dockerfile");
assertEquals(builtImage, docker.inspectImageCmd(helper).exec().getId());
verify(docker, times(1)).buildImageCmd(any(InputStream.class));
containerId = docker.createContainerCmd(helper).exec().getId();
docker.startContainerCmd(containerId).exec();
try (WaitContainerResultCallback exited = new WaitContainerResultCallback()) {
assertEquals(0, docker.waitContainerCmd(containerId).exec(exited)
.awaitStatusCode(30, TimeUnit.SECONDS));
}
StringBuilder output = new StringBuilder();
try (ResultCallback.Adapter<Frame> logs = new ResultCallback.Adapter<>() {
@Override
public void onNext(Frame frame) {
output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
}) {
assertTrue(docker.logContainerCmd(containerId).withStdOut(true).withStdErr(true)
.exec(logs).awaitCompletion(30, TimeUnit.SECONDS));
}
assertEquals(nativePlatform.equals("linux/amd64") ? "x86_64" : "aarch64",
output.toString().trim());
} finally {
if (containerId != null) {
docker.removeContainerCmd(containerId).withForce(true).exec();
}
docker.removeImageCmd(helper).withForce(true).exec();
}
}
}
}
}
@@ -3,13 +3,17 @@ package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.BuildImageCmd;
import com.github.dockerjava.api.command.BuildImageResultCallback;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.InspectImageCmd;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Info;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.InputStream;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -21,12 +25,8 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Covers the decisions this helper makes before it ever touches a Dockerfile: that a caller pointed
* at something other than Floci's own default is left to pull that image itself, that an image
* already in the daemon is not rebuilt, and that a build which produces no image id fails instead
* of reporting success. All are branches the callers depend on and none needs a real daemon, so
* they are pinned here rather than only through the EC2 security-group path, which uses the default
* image and is skipped without Docker.
* Covers custom image selection, reuse of the current recipe on the correct platform, stale-cache
* rebuilding and failure when a build produces no image. Real Docker coverage lives separately.
*/
class LocallyBuiltHelperImageTest {
@@ -35,11 +35,16 @@ class LocallyBuiltHelperImageTest {
private DockerClient dockerClient;
private ContainerBuilder containerBuilder;
private Info daemon;
@BeforeEach
void setUp() {
dockerClient = mock(DockerClient.class);
containerBuilder = mock(ContainerBuilder.class);
daemon = new Info().withArchitecture("x86_64").withOsType("linux");
InfoCmd info = mock(InfoCmd.class);
when(info.exec()).thenReturn(daemon);
when(dockerClient.infoCmd()).thenReturn(info);
}
@Test
@@ -54,11 +59,9 @@ class LocallyBuiltHelperImageTest {
}
@Test
void buildsNothingWhenTheImageIsAlreadyInTheDaemon() {
void buildsNothingWhenTheImageHasTheCurrentRecipeAndPlatform() throws Exception {
stubResolvedImage();
InspectImageCmd inspectCmd = mock(InspectImageCmd.class);
when(dockerClient.inspectImageCmd(DEFAULT_IMAGE)).thenReturn(inspectCmd);
when(inspectCmd.exec()).thenReturn(mock(InspectImageResponse.class));
CachedImageStubs.image(dockerClient, DEFAULT_IMAGE, "linux", "amd64", recipe());
LocallyBuiltHelperImage.ensureBuilt(dockerClient, containerBuilder,
DEFAULT_IMAGE, DEFAULT_IMAGE, DOCKERFILE);
@@ -67,14 +70,45 @@ class LocallyBuiltHelperImageTest {
}
@Test
void buildsFromTheDockerfileWhenTheImageIsMissing() {
void buildsFromTheDockerfileWhenTheImageIsMissing() throws Exception {
stubMissingImage();
stubBuildReturning("sha256:built");
BuildImageCmd build = stubBuildReturning("sha256:built");
LocallyBuiltHelperImage.ensureBuilt(dockerClient, containerBuilder,
DEFAULT_IMAGE, DEFAULT_IMAGE, DOCKERFILE);
verify(dockerClient).buildImageCmd(any(InputStream.class));
verify(build).withPlatform("linux/amd64");
verify(build).withLabels(Map.of(LocallyBuiltHelperImage.RECIPE_LABEL, recipe()));
verify(build).withPull(true);
}
@ParameterizedTest
@CsvSource({"missing", "old-recipe"})
void replacesNativeHelperFromAnOlderRecipe(String previous) {
stubResolvedImage();
CachedImageStubs.image(dockerClient, DEFAULT_IMAGE, "linux", "amd64",
"missing".equals(previous) ? null : previous);
BuildImageCmd build = stubBuildReturning("sha256:rebuilt");
LocallyBuiltHelperImage.ensureBuilt(dockerClient, containerBuilder,
DEFAULT_IMAGE, DEFAULT_IMAGE, DOCKERFILE);
verify(build).withPlatform("linux/amd64");
}
@ParameterizedTest
@CsvSource({"x86_64,arm64,linux/amd64", "aarch64,amd64,linux/arm64"})
void replacesForeignCachedHelperWithTheDaemonPlatform(String host, String cached, String expected) throws Exception {
daemon.withArchitecture(host);
stubResolvedImage();
CachedImageStubs.image(dockerClient, DEFAULT_IMAGE, "linux", cached, recipe());
BuildImageCmd build = stubBuildReturning("sha256:rebuilt");
LocallyBuiltHelperImage.ensureBuilt(dockerClient, containerBuilder,
DEFAULT_IMAGE, DEFAULT_IMAGE, DOCKERFILE);
verify(build).withPlatform(expected);
}
@Test
@@ -105,6 +139,10 @@ class LocallyBuiltHelperImageTest {
when(containerBuilder.resolveImage(DEFAULT_IMAGE)).thenReturn(DEFAULT_IMAGE);
}
private static String recipe() {
return CachedImageStubs.recipe(DOCKERFILE);
}
private void stubMissingImage() {
stubResolvedImage();
InspectImageCmd inspectCmd = mock(InspectImageCmd.class);
@@ -116,11 +154,12 @@ class LocallyBuiltHelperImageTest {
* Returns a stub callback rather than the one the helper passes in: awaiting the real
* {@link BuildImageResultCallback} would block, since no daemon ever feeds it events.
*/
private void stubBuildReturning(String imageId) {
private BuildImageCmd stubBuildReturning(String imageId) {
BuildImageCmd buildCmd = mock(BuildImageCmd.class, RETURNS_SELF);
when(dockerClient.buildImageCmd(any(InputStream.class))).thenReturn(buildCmd);
BuildImageResultCallback result = mock(BuildImageResultCallback.class);
when(result.awaitImageId()).thenReturn(imageId);
when(buildCmd.exec(any())).thenReturn(result);
return buildCmd;
}
}
@@ -0,0 +1,49 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import java.util.UUID;
/** Keeps an existing image reachable while a fixture replaces its tag. */
final class PreservedImageTag implements AutoCloseable {
private final DockerClient docker;
private final String repository;
private final String tag;
private final String backup;
PreservedImageTag(DockerClient docker, String repository, String tag) {
this.docker = docker;
this.repository = repository;
this.tag = tag;
String originalId;
try {
originalId = docker.inspectImageCmd(repository + ":" + tag).exec().getId();
} catch (NotFoundException expected) {
// An initially absent tag must be absent again after the fixture.
originalId = null;
}
if (originalId == null) {
backup = null;
} else {
String backupTag = UUID.randomUUID().toString();
docker.tagImageCmd(originalId, "floci/helper-base-backup", backupTag).exec();
backup = "floci/helper-base-backup:" + backupTag;
}
}
@Override
public void close() {
if (backup != null) {
docker.tagImageCmd(backup, repository, tag).exec();
// Retain the recovery tag if restoration throws.
docker.removeImageCmd(backup).exec();
} else {
try {
docker.removeImageCmd(repository + ":" + tag).exec();
} catch (NotFoundException expected) {
// A failed pull may never have created the initially absent tag.
}
}
}
}
@@ -0,0 +1,114 @@
package io.github.hectorvent.floci.core.common.docker;
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.RemoveImageCmd;
import com.github.dockerjava.api.command.TagImageCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.opentest4j.TestAbortedException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class PreservedImageTagTest {
private DockerClient docker;
private InspectImageCmd inspect;
private TagImageCmd tag;
private RemoveImageCmd remove;
@BeforeEach
void setUp() {
docker = mock(DockerClient.class);
inspect = mock(InspectImageCmd.class);
InspectImageResponse image = mock(InspectImageResponse.class);
tag = mock(TagImageCmd.class);
remove = mock(RemoveImageCmd.class);
when(docker.inspectImageCmd("busybox:1.37.0")).thenReturn(inspect);
when(inspect.exec()).thenReturn(image);
when(image.getId()).thenReturn("original-image");
when(docker.tagImageCmd(anyString(), anyString(), anyString())).thenReturn(tag);
when(docker.removeImageCmd(anyString())).thenReturn(remove);
}
@ParameterizedTest
@ValueSource(strings = {"success", "skip", "pull-failure", "build-failure"})
void restoresOriginalImageForEveryExit(String exit) {
RuntimeException failure = "skip".equals(exit)
? new TestAbortedException("unsupported fixture")
: new IllegalStateException(exit);
if ("success".equals(exit)) {
try (PreservedImageTag saved = new PreservedImageTag(docker, "busybox", "1.37.0")) {
verify(docker).inspectImageCmd("busybox:1.37.0");
}
} else {
assertSame(failure, assertThrows(RuntimeException.class, () -> {
try (PreservedImageTag saved = new PreservedImageTag(docker, "busybox", "1.37.0")) {
throw failure;
}
}));
}
ArgumentCaptor<String> backupTag = ArgumentCaptor.forClass(String.class);
InOrder order = inOrder(docker, tag, remove);
order.verify(docker).tagImageCmd(eq("original-image"), eq("floci/helper-base-backup"), backupTag.capture());
order.verify(tag).exec();
String backup = "floci/helper-base-backup:" + backupTag.getValue();
order.verify(docker).tagImageCmd(backup, "busybox", "1.37.0");
order.verify(tag).exec();
order.verify(docker).removeImageCmd(backup);
order.verify(remove).exec();
}
@Test
void removesTagThatWasInitiallyAbsent() {
when(inspect.exec()).thenThrow(new NotFoundException("absent"));
try (PreservedImageTag saved = new PreservedImageTag(docker, "busybox", "1.37.0")) {
verify(docker).inspectImageCmd("busybox:1.37.0");
}
verify(docker).removeImageCmd("busybox:1.37.0");
verify(remove).exec();
verify(docker, never()).tagImageCmd(anyString(), anyString(), anyString());
}
@Test
void absentTagAfterFailedPullIsAlreadyClean() {
when(inspect.exec()).thenThrow(new NotFoundException("absent"));
doThrow(new NotFoundException("pull never created tag")).when(remove).exec();
assertDoesNotThrow(() -> {
try (PreservedImageTag saved = new PreservedImageTag(docker, "busybox", "1.37.0")) {
verify(docker).inspectImageCmd("busybox:1.37.0");
}
});
}
@Test
void snapshotFailureDoesNotMutateTags() {
IllegalStateException failure = new IllegalStateException("inspect failed");
when(inspect.exec()).thenThrow(failure);
assertSame(failure, assertThrows(IllegalStateException.class,
() -> new PreservedImageTag(docker, "busybox", "1.37.0")));
verify(docker, never()).tagImageCmd(anyString(), anyString(), anyString());
verify(docker, never()).removeImageCmd(anyString());
}
@Test
void restorationFailureRetainsBackupAndIsSuppressedByPrimaryFailure() {
IllegalStateException restore = new IllegalStateException("restore failed");
IllegalStateException primary = new IllegalStateException("build failed");
doNothing().doThrow(restore).when(tag).exec();
assertSame(primary, assertThrows(IllegalStateException.class, () -> {
try (PreservedImageTag saved = new PreservedImageTag(docker, "busybox", "1.37.0")) {
throw primary;
}
}));
assertArrayEquals(new Throwable[]{restore}, primary.getSuppressed());
verify(docker, never()).removeImageCmd(anyString());
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.ec2;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Info;
@@ -36,14 +37,18 @@ class SecurityGroupFirewallManagerTest {
void helperCarriesTheResolverAndHostsItsWorkloadsUse() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.network().securityGroupEnforcement().enabled()).thenReturn(true);
when(config.network().securityGroupEnforcement().helperImage()).thenReturn("floci/network-helper:local");
when(config.network().securityGroupEnforcement().helperImage()).thenReturn("example/network-helper:test");
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
when(config.docker().imageRegistryBase()).thenReturn(Optional.empty());
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
Info linux = mock(Info.class);
when(linux.getOsType()).thenReturn("linux");
when(linux.getArchitecture()).thenReturn("amd64");
when(dockerClient.infoCmd().exec()).thenReturn(linux);
when(dockerClient.inspectImageCmd(anyString()).exec()).thenReturn(null);
InspectImageResponse image = mock(InspectImageResponse.class);
when(image.getOs()).thenReturn("linux");
when(image.getArch()).thenReturn("amd64");
when(dockerClient.inspectImageCmd(anyString()).exec()).thenReturn(image);
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
when(dockerHostResolver.isLinuxHost()).thenReturn(true);
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
@@ -1,14 +1,15 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse.ContainerState;
import com.github.dockerjava.api.command.InspectImageCmd;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.CachedImageStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
@@ -52,6 +53,9 @@ class EcsCredentialsProxyTest {
@BeforeEach
void setUp() {
dockerClient = mock(DockerClient.class);
InfoCmd info = mock(InfoCmd.class);
when(dockerClient.infoCmd()).thenReturn(info);
when(info.exec()).thenReturn(new Info().withArchitecture("x86_64").withOsType("linux"));
containerBuilder = mock(ContainerBuilder.class);
lifecycleManager = mock(ContainerLifecycleManager.class);
dockerHostResolver = mock(DockerHostResolver.class);
@@ -248,10 +252,8 @@ class EcsCredentialsProxyTest {
when(config.services().ecs().taskRoleCredentials().proxyImage()).thenReturn("floci/network-helper:local");
when(containerBuilder.resolveImage("floci/network-helper:local")).thenReturn("floci/network-helper:local");
stubNoStaleContainerByName();
InspectImageCmd inspectImageCmd =
mock(InspectImageCmd.class);
when(dockerClient.inspectImageCmd(any())).thenReturn(inspectImageCmd);
when(inspectImageCmd.exec()).thenReturn(mock(InspectImageResponse.class));
CachedImageStubs.image(dockerClient, "floci/network-helper:local", "linux", "amd64",
CachedImageStubs.recipe("/docker/network-helper.Dockerfile"));
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo(containerId, Map.of()));
InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class);
@@ -0,0 +1,2 @@
FROM busybox:1.37.0
CMD ["uname", "-m"]