fix(ecs): pull task images at launch so a moved tag reaches the next task (#4583)

* fix(ecs): pull task images at launch so a moved tag reaches the next task

Floci resolved an image reference to an image id the first time it saw it and
reused that id for the life of the process, so a rebuilt :latest pushed to the
registry never reached a new task, even through a new task definition revision
and a forced deployment, and nothing reported the mismatch.

ECS now pulls every container image when a task starts, before creating any of
its containers, following the agent's ECS_IMAGE_PULL_BEHAVIOR (configurable as
floci.services.ecs.image-pull-behavior, default "default": pull, and fall back
to the cached image when the pull fails). The cached image is whatever the
local tag names at launch rather than a remembered id. Each container reports
the manifest digest it runs as containers[].imageDigest.

* fix(ecs): create task containers from the image id their pull resolved to

An overlapping RunTask could pull the same moved tag between this task's pull
and its container creation, so the container was created from whatever the
shared tag cache named by then while reporting the digest this task pulled.
resolveForLaunch now returns the resolved image id with its digest, and ECS
builds each container from that id, so the image a task runs and the digest it
reports always come from the same pull.

The pull also now uses the reference the container is created from, including
floci.docker.image-registry-base, instead of the unprefixed name.

* fix(ecs): launch image ids without a pull and report the digest the pull resolved

A bare sha256 image id under always, or on the first once launch, went to the
registry as if it were a repository reference and failed the task although the
image was local. resolveForLaunch now runs an image id as it is, like
ensureImageExists.

The reported digest took the first RepoDigests entry for the repository, which
is not necessarily the manifest the tag resolved to when the image holds more
than one (an index and a platform manifest). It now comes from the Digest line
the daemon streams for the pull, kept while the tag still names that image; a
cached image falls back to its repo digest only when there is exactly one.

The shared test config uses prefer-cached so the other ECS Docker suites stop
adding a registry round trip per launch; the image pull integration test pins
default in its own profile. ContainerBuilder imports are back in order.

* fix(ecs): report a pull's digest only for the launch that pulled

The digest a pull reported was kept per reference and reused while the tag
still named the same image id, but on the classic image store an id is the
config digest and several manifests can share it, so an outside pull could move
the tag to another manifest and leave the reused digest stale. Only the launch
that pulled now uses the streamed digest. A cached launch uses the image's
repo digest for the repository when there is one, or the one equal to the id
(the containerd store names an image by its manifest), and otherwise none.

Also sorts the ContainerLifecycleManager imports.

* fix(ecs): pull the image-pull test's busybox and registry from Docker Hub

EcsImagePullDockerIntegrationTest pulled both images through the
public.ecr.aws/docker/library mirror, whose anonymous quota is shared per
runner IP; shard 3 failed on toomanyrequests: Data limit exceeded. Take
them from TestImages like the other Docker-backed tests, pinning the
registry image there, and prefetch both for the shard that runs the class.

* test(ecs): name the registry readiness probe's tolerated exception expected
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-30 22:14:50 -04:00
1 parent bc42cee767
commit d73e33fe4b
26 files changed
+1051 -28

No files matched your search

@@ -315,6 +315,15 @@ class ContainerBuilderTest {
assertEquals("ghcr.io/floci-io/mirror/floci/ami-ubuntu:24.04-arm64", spec.image());
}
@Test
void imageRegistryBaseLeavesAnImageIdAlone() {
TestFixture fixture = new TestFixture();
when(fixture.docker.imageRegistryBase()).thenReturn(Optional.of("ghcr.io/floci-io/mirror"));
String imageId = "sha256:" + "a".repeat(64);
assertEquals(imageId, fixture.builder.newContainer(imageId).build().image());
}
private static class TestFixture {
final EmulatorConfig config = mock(EmulatorConfig.class);
final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
@@ -0,0 +1,233 @@
package io.github.hectorvent.floci.services.ecs;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.PushResponseItem;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.testing.TestImages;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* The scenario from a CI rebuild: a service's image tag is moved in its registry while the Docker
* host still holds the old image under that tag. The next task has to run the image the registry
* names now, as the ECS agent's default pull behaviour does, and report that image's digest.
*/
@QuarkusTest
@TestProfile(EcsImagePullDockerIntegrationTest.DockerEcsProfile.class)
class EcsImagePullDockerIntegrationTest {
private static final String REGION = "us-east-1";
private static final String MANIFEST_TYPES = String.join(",",
"application/vnd.oci.image.index.v1+json",
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.docker.distribution.manifest.v2+json");
/**
* Real containers, security-group enforcement back to its shipped default of off, and the
* shipped pull behaviour, which the shared test config swaps for prefer-cached.
*/
public static final class DockerEcsProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.ecs.mock", "false",
"floci.network.security-group-enforcement.enabled", "false",
"floci.services.ecs.image-pull-behavior", "default");
}
}
@Inject
EcsService ecsService;
@Inject
DockerClient dockerClient;
private String registryContainerId;
private final List<String> images = new ArrayList<>();
private final List<String> taskArns = new ArrayList<>();
private String clusterName;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for the ECS image pull test");
}
@AfterEach
void cleanUp() {
for (String taskArn : taskArns) {
ecsService.stopTask(clusterName, taskArn, "test teardown", REGION);
}
for (String image : images) {
try {
dockerClient.removeImageCmd(image).withForce(true).exec();
} catch (NotFoundException expected) {
// Removing one tag of an image can take the others with it.
}
}
if (registryContainerId != null) {
dockerClient.removeContainerCmd(registryContainerId).withForce(true).exec();
}
}
@Test
void aTaskRunsTheImageItsTagWasMovedToInTheRegistry() throws Exception {
String registry = startRegistry();
String repository = "floci-ecs-pull-" + UUID.randomUUID().toString().substring(0, 8);
String image = registry + "/" + repository + ":latest";
images.add(image);
pull(TestImages.BUSYBOX);
dockerClient.tagImageCmd(TestImages.BUSYBOX, registry + "/" + repository, "latest").exec();
push(registry + "/" + repository);
String firstDigest = registryDigest(registry, repository);
clusterName = "pull-" + UUID.randomUUID().toString().substring(0, 8);
ecsService.createCluster(clusterName, REGION);
TaskDefinition taskDef = registerTaskDefinition(image);
EcsTask first = runTask(taskDef);
assertEquals(firstDigest, first.getContainers().getFirst().getImageDigest());
String firstImageId = containerImageId(first);
// A rebuild pushed under the same tag, while the Docker host keeps the old image under it.
String rebuilt = commitChangedImage(image);
images.add(rebuilt);
dockerClient.tagImageCmd(rebuilt, registry + "/" + repository, "latest").exec();
push(registry + "/" + repository);
String rebuiltDigest = registryDigest(registry, repository);
assertNotEquals(firstDigest, rebuiltDigest, "the rebuild must have moved the tag in the registry");
dockerClient.tagImageCmd(firstImageId, registry + "/" + repository, "latest").exec();
EcsTask second = runTask(taskDef);
assertEquals(rebuiltDigest, second.getContainers().getFirst().getImageDigest(),
"the task must report the digest the registry's tag names now");
assertNotEquals(firstImageId, containerImageId(second),
"the task must run the rebuilt image, not the one the Docker host held under the tag");
}
private EcsTask runTask(TaskDefinition taskDef) {
EcsTask task = ecsService.runTask(clusterName, taskDef.getTaskDefinitionArn(), 1,
null, null, null, null, null, REGION).getFirst();
taskArns.add(task.getTaskArn());
EcsTask described = ecsService.describeTasks(clusterName, List.of(task.getTaskArn()), REGION).getFirst();
assertEquals("RUNNING", described.getLastStatus(), "the container must be up: " + described.getStoppedReason());
return described;
}
private TaskDefinition registerTaskDefinition(String image) {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage(image);
app.setCommand(List.of("sleep", "120"));
return ecsService.registerTaskDefinition("pull-" + UUID.randomUUID().toString().substring(0, 8),
List.of(app), NetworkMode.bridge, null, null, null, null, null, REGION);
}
private String containerImageId(EcsTask task) {
return dockerClient.inspectContainerCmd(task.getContainers().getFirst().getRuntimeId()).exec().getImageId();
}
private String commitChangedImage(String image) {
CreateContainerResponse container = dockerClient.createContainerCmd(image).withCmd("true").exec();
try {
return dockerClient.commitCmd(container.getId())
.withLabels(Map.of("floci.test.build", UUID.randomUUID().toString()))
.exec();
} finally {
dockerClient.removeContainerCmd(container.getId()).withForce(true).exec();
}
}
private String startRegistry() throws InterruptedException {
pull(TestImages.REGISTRY);
ExposedPort registryPort = ExposedPort.tcp(5000);
registryContainerId = dockerClient.createContainerCmd(TestImages.REGISTRY)
.withExposedPorts(registryPort)
.withHostConfig(HostConfig.newHostConfig().withPortBindings(new PortBinding(
Ports.Binding.bindIp("127.0.0.1"), registryPort)))
.exec()
.getId();
dockerClient.startContainerCmd(registryContainerId).exec();
Ports.Binding binding = dockerClient.inspectContainerCmd(registryContainerId).exec()
.getNetworkSettings().getPorts().getBindings().get(registryPort)[0];
String registry = "localhost:" + binding.getHostPortSpec();
HttpClient http = HttpClient.newHttpClient();
for (int attempt = 0; attempt < 50; attempt++) {
try {
HttpResponse<Void> response = http.send(
HttpRequest.newBuilder(URI.create("http://" + registry + "/v2/")).build(),
HttpResponse.BodyHandlers.discarding());
if (response.statusCode() == 200) {
return registry;
}
} catch (IOException expected) {
// Safe to retry: the registry takes a moment to bind after the container starts.
}
Thread.sleep(100);
}
throw new IllegalStateException("registry at " + registry + " never answered");
}
/** The digest the registry serves for the tag, which is what a pull of it resolves to. */
private static String registryDigest(String registry, String repository) throws Exception {
HttpResponse<Void> response = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create("http://" + registry + "/v2/" + repository + "/manifests/latest"))
.method("HEAD", HttpRequest.BodyPublishers.noBody())
.header("Accept", MANIFEST_TYPES)
.build(),
HttpResponse.BodyHandlers.discarding());
assertEquals(200, response.statusCode());
return response.headers().firstValue("Docker-Content-Digest").orElseThrow();
}
private void pull(String image) throws InterruptedException {
dockerClient.pullImageCmd(image).exec(new PullImageResultCallback()).awaitCompletion(5, TimeUnit.MINUTES);
}
private void push(String repository) throws InterruptedException {
dockerClient.pushImageCmd(repository).withTag("latest")
.exec(new ResultCallback.Adapter<PushResponseItem>())
.awaitCompletion(2, TimeUnit.MINUTES);
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (RuntimeException e) {
return false;
}
}
}
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -60,8 +61,11 @@ class EcsContainerManagerAwsBaselineTest {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -61,8 +62,11 @@ class EcsContainerManagerEcrRewriteTest {
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
@@ -71,8 +72,11 @@ class EcsContainerManagerFirelensTest {
when(builder.build()).thenReturn(new ContainerSpec("image"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("app-id", Map.of()));
when(lifecycleManager.create(any())).thenReturn("router-id");
when(lifecycleManager.startCreated(anyString(), any())).thenReturn(new ContainerInfo("router-id", Map.of()));
@@ -0,0 +1,160 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A task pulls its images at launch, as the ECS agent does under {@code ECS_IMAGE_PULL_BEHAVIOR},
* so a tag moved in its registry is what the next task runs, and each container reports the
* digest of the image it runs.
*/
class EcsContainerManagerImagePullTest {
private static final String APP_IMAGE = "registry.example:5000/app:latest";
private static final String SIDECAR_IMAGE = "sidecar:latest";
private static final String APP_IMAGE_ID = "sha256:" + "a".repeat(64);
private static final String SIDECAR_IMAGE_ID = "sha256:" + "b".repeat(64);
private ContainerBuilder containerBuilder;
private ContainerLifecycleManager lifecycleManager;
private EcsContainerManager manager;
@BeforeEach
void setUp() {
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().imagePullBehavior()).thenReturn(ImagePullBehavior.ALWAYS);
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(any(), any())).thenReturn(List.of());
EcrRegistryManager ecrRegistryManager = mock(EcrRegistryManager.class);
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
manager = new EcsContainerManager(containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config, mock(RegionResolver.class), awsEnv,
mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class));
}
@Test
void everyImageIsPulledWithTheConfiguredBehaviourBeforeAnyContainerIsCreated() {
when(lifecycleManager.resolveImageForLaunch(APP_IMAGE, ImagePullBehavior.ALWAYS))
.thenReturn(new LaunchImage(APP_IMAGE_ID, "sha256:new-manifest"));
when(lifecycleManager.resolveImageForLaunch(SIDECAR_IMAGE, ImagePullBehavior.ALWAYS))
.thenReturn(new LaunchImage(SIDECAR_IMAGE_ID, null));
EcsTask task = task();
manager.startTask(task, taskDefinition(), List.of(), "us-east-1");
InOrder order = inOrder(lifecycleManager);
order.verify(lifecycleManager).resolveImageForLaunch(APP_IMAGE, ImagePullBehavior.ALWAYS);
order.verify(lifecycleManager).resolveImageForLaunch(SIDECAR_IMAGE, ImagePullBehavior.ALWAYS);
order.verify(lifecycleManager).createAndStart(any());
List<Container> containers = task.getContainers();
assertEquals("sha256:new-manifest", containers.get(0).getImageDigest());
assertNull(containers.get(1).getImageDigest(), "a locally built image has no manifest digest");
assertEquals(APP_IMAGE, containers.get(0).getImage());
}
@Test
void everyContainerIsCreatedFromTheImageIdItsPullResolvedTo() {
when(lifecycleManager.resolveImageForLaunch(APP_IMAGE, ImagePullBehavior.ALWAYS))
.thenReturn(new LaunchImage(APP_IMAGE_ID, "sha256:new-manifest"));
when(lifecycleManager.resolveImageForLaunch(SIDECAR_IMAGE, ImagePullBehavior.ALWAYS))
.thenReturn(new LaunchImage(SIDECAR_IMAGE_ID, null));
manager.startTask(task(), taskDefinition(), List.of(), "us-east-1");
verify(containerBuilder).newContainer(APP_IMAGE_ID);
verify(containerBuilder).newContainer(SIDECAR_IMAGE_ID);
verify(containerBuilder, never()).newContainer(APP_IMAGE);
verify(containerBuilder, never()).newContainer(SIDECAR_IMAGE);
}
@Test
void theImagePulledIsTheOneTheConfiguredRegistryBaseNames() {
when(containerBuilder.resolveImage(anyString()))
.thenAnswer(invocation -> "mirror.example/" + invocation.getArgument(0));
when(lifecycleManager.resolveImageForLaunch(anyString(), any()))
.thenReturn(new LaunchImage(APP_IMAGE_ID, null));
manager.startTask(task(), taskDefinition(), List.of(), "us-east-1");
verify(lifecycleManager).resolveImageForLaunch("mirror.example/" + APP_IMAGE, ImagePullBehavior.ALWAYS);
verify(lifecycleManager).resolveImageForLaunch("mirror.example/" + SIDECAR_IMAGE, ImagePullBehavior.ALWAYS);
}
@Test
void aFailedPullLeavesNoContainerCreated() {
when(lifecycleManager.resolveImageForLaunch(APP_IMAGE, ImagePullBehavior.ALWAYS))
.thenReturn(new LaunchImage(APP_IMAGE_ID, "sha256:new-manifest"));
when(lifecycleManager.resolveImageForLaunch(SIDECAR_IMAGE, ImagePullBehavior.ALWAYS))
.thenThrow(new NotFoundException("pull access denied for sidecar"));
assertThrows(NotFoundException.class,
() -> manager.startTask(task(), taskDefinition(), List.of(), "us-east-1"));
verify(lifecycleManager, never()).createAndStart(any());
}
private static TaskDefinition taskDefinition() {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage(APP_IMAGE);
ContainerDefinition sidecar = new ContainerDefinition();
sidecar.setName("sidecar");
sidecar.setImage(SIDECAR_IMAGE);
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("app-service");
taskDef.setContainerDefinitions(List.of(app, sidecar));
return taskDef;
}
private static EcsTask task() {
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
return task;
}
}
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -59,8 +60,11 @@ class EcsContainerManagerOverridesTest {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -76,8 +77,11 @@ class EcsContainerManagerPortMappingsTest {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("docker-id", Map.of()));
// resolveNetworkBindings() inspects the container after launch; deep stubs
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
import io.github.hectorvent.floci.services.ecs.model.Secret;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
@@ -53,8 +54,11 @@ class EcsContainerManagerSecretsTest {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -66,8 +67,11 @@ class EcsContainerManagerSecurityGroupTest {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -68,9 +69,12 @@ class EcsContainerManagerTaskRoleCredentialsTest {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of(NETWORK));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
@@ -184,6 +188,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void revokesCredentialsEvenWhenAContainerCouldNotBeRemoved() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
// Docker refuses the removal, so the task's containers never all come off.
@@ -227,6 +233,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void keepsAddressesReservedWhenAContainerCouldNotBeRemoved() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.removeContainerCmd("docker-id")).thenThrow(new IllegalStateException("in use"));
@@ -249,6 +257,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void keepsAddressesReservedWhenCleanupCannotRemoveAContainer() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
// The reconciler's cleanup path is the other way a task's containers come off, and Docker
// can refuse a removal here just as it can on the stop path.
@@ -274,6 +284,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void keepsAddressesReservedWhenAFailedLaunchCannotRemoveAContainer() {
ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class);
when(failing.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
// The first container starts and the second does not, so the launch unwinds with one
// container already up and holding an address.
when(failing.createAndStart(any()))
@@ -349,6 +361,8 @@ class EcsContainerManagerTaskRoleCredentialsTest {
@Test
void revokesCredentialsWhenTheLaunchFailsPartWayThrough() {
ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class);
when(failing.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(failing.createAndStart(any())).thenThrow(new IllegalStateException("no daemon"));
EcsContainerManager failingManager = new EcsContainerManager(containerBuilder, failing,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.VolumeFrom;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -61,6 +62,7 @@ class EcsContainerManagerVolumesFromTest {
@BeforeEach
void setUp() {
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
sourceBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
appBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer("sidecar:latest")).thenReturn(sourceBuilder);
@@ -69,6 +71,8 @@ class EcsContainerManagerVolumesFromTest {
when(appBuilder.build()).thenReturn(mock(ContainerSpec.class));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("source-id", Map.of()))
.thenReturn(new ContainerInfo("app-id", Map.of()));
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
import io.github.hectorvent.floci.services.ecs.model.MountPoint;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.Volume;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
@@ -65,8 +66,11 @@ class EcsContainerManagerVolumesTest {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerInfo("docker-id", Map.of()));
@@ -12,10 +12,16 @@ 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 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.services.lambda.launcher.ImageCacheService.LaunchImage;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -24,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -34,6 +41,9 @@ import static org.mockito.Mockito.when;
class ImageCacheServiceTest {
private static final String IMAGE = "public.ecr.aws/docker/library/alpine:latest";
private static final String REGISTRY_REPO = "registry.example:5000/app";
private static final String REGISTRY_IMAGE = REGISTRY_REPO + ":latest";
private static final String LOCAL_IMAGE = "app-local:latest";
@Test
void pullsImageWhenInspectionReportsNotFound() throws Exception {
@@ -383,6 +393,290 @@ class ImageCacheServiceTest {
assertEquals(1, calls.get());
}
@Test
void defaultPullBehaviourRunsTheImageAMovedTagNamesNow() {
FakeDaemon daemon = new FakeDaemon();
daemon.registry.put(REGISTRY_IMAGE, image("sha256:old", REGISTRY_REPO + "@sha256:old-manifest"));
ImageCacheService service = newService(daemon.client);
assertEquals("sha256:old", service.ensureImageExists(REGISTRY_IMAGE));
daemon.registry.put(REGISTRY_IMAGE, image("sha256:new", REGISTRY_REPO + "@sha256:new-manifest"));
assertEquals(new LaunchImage("sha256:new", "sha256:new-manifest"),
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.DEFAULT));
assertEquals("sha256:new", service.ensureImageExists(REGISTRY_IMAGE));
assertEquals(2, daemon.pulls.get());
}
@Test
void defaultPullBehaviourRunsTheCachedImageWhenThePullFails() {
FakeDaemon daemon = new FakeDaemon();
daemon.store(LOCAL_IMAGE, image("sha256:built"));
ImageCacheService service = newService(daemon.client);
assertEquals(new LaunchImage("sha256:built", null),
service.resolveForLaunch(LOCAL_IMAGE, ImagePullBehavior.DEFAULT));
assertEquals("sha256:built", service.ensureImageExists(LOCAL_IMAGE));
assertEquals(1, daemon.pulls.get());
}
@Test
void defaultPullBehaviourFailsWhenThePullFailsAndNothingIsCached() {
FakeDaemon daemon = new FakeDaemon();
assertThrows(NotFoundException.class,
() -> newService(daemon.client).resolveForLaunch(LOCAL_IMAGE, ImagePullBehavior.DEFAULT));
}
@Test
void alwaysPullBehaviourFailsWhenThePullFailsEvenWithACachedImage() {
FakeDaemon daemon = new FakeDaemon();
daemon.store(LOCAL_IMAGE, image("sha256:built"));
assertThrows(NotFoundException.class,
() -> newService(daemon.client).resolveForLaunch(LOCAL_IMAGE, ImagePullBehavior.ALWAYS));
}
@Test
void preferCachedPullBehaviourFollowsTheLocalTagWithoutPulling() {
FakeDaemon daemon = new FakeDaemon();
daemon.store(REGISTRY_IMAGE, image("sha256:old", REGISTRY_REPO + "@sha256:old-manifest"));
ImageCacheService service = newService(daemon.client);
assertEquals("sha256:old", service.ensureImageExists(REGISTRY_IMAGE));
daemon.store(REGISTRY_IMAGE, image("sha256:new", REGISTRY_REPO + "@sha256:new-manifest"));
assertEquals(new LaunchImage("sha256:new", "sha256:new-manifest"),
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.PREFER_CACHED));
assertEquals("sha256:new", service.ensureImageExists(REGISTRY_IMAGE));
assertEquals(0, daemon.pulls.get());
}
@Test
void preferCachedPullBehaviourPullsWhenNothingIsCached() {
FakeDaemon daemon = new FakeDaemon();
daemon.registry.put(REGISTRY_IMAGE, image("sha256:new", REGISTRY_REPO + "@sha256:new-manifest"));
assertEquals(new LaunchImage("sha256:new", "sha256:new-manifest"),
newService(daemon.client).resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.PREFER_CACHED));
assertEquals(1, daemon.pulls.get());
}
@Test
void oncePullBehaviourPullsOnlyTheFirstLaunch() {
FakeDaemon daemon = new FakeDaemon();
daemon.store(REGISTRY_IMAGE, image("sha256:stale"));
daemon.registry.put(REGISTRY_IMAGE, image("sha256:old", REGISTRY_REPO + "@sha256:old-manifest"));
ImageCacheService service = newService(daemon.client);
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.ONCE);
daemon.registry.put(REGISTRY_IMAGE, image("sha256:new", REGISTRY_REPO + "@sha256:new-manifest"));
assertEquals(new LaunchImage("sha256:old", "sha256:old-manifest"),
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.ONCE));
assertEquals("sha256:old", service.ensureImageExists(REGISTRY_IMAGE));
assertEquals(1, daemon.pulls.get());
}
@Test
void aLaunchKeepsTheImageItResolvedWhenAnOverlappingLaunchMovesTheTag() {
String oldId = "sha256:" + "a".repeat(64);
String newId = "sha256:" + "b".repeat(64);
FakeDaemon daemon = new FakeDaemon();
daemon.registry.put(REGISTRY_IMAGE, image(oldId, REGISTRY_REPO + "@sha256:old-manifest"));
ImageCacheService service = newService(daemon.client);
LaunchImage first = service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.DEFAULT);
daemon.registry.put(REGISTRY_IMAGE, image(newId, REGISTRY_REPO + "@sha256:new-manifest"));
LaunchImage second = service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.DEFAULT);
assertEquals(new LaunchImage(oldId, "sha256:old-manifest"), first);
assertEquals(new LaunchImage(newId, "sha256:new-manifest"), second);
assertEquals(oldId, service.ensureImageExists(first.imageId()),
"the first launch's container is created from the image its own pull resolved to");
assertEquals(newId, service.ensureImageExists(second.imageId()));
assertEquals(2, daemon.pulls.get());
}
@Test
void anImageIdThatIsGoneFailsWithoutAPull() {
FakeDaemon daemon = new FakeDaemon();
assertThrows(DockerClientException.class,
() -> newService(daemon.client).ensureImageExists("sha256:" + "c".repeat(64)));
assertEquals(0, daemon.pulls.get());
}
@Test
void anImageIdLaunchesWithoutAPullUnderEveryBehaviour() {
String imageId = "sha256:" + "d".repeat(64);
FakeDaemon daemon = new FakeDaemon();
daemon.store(LOCAL_IMAGE, image(imageId));
ImageCacheService service = newService(daemon.client);
for (ImagePullBehavior behavior : ImagePullBehavior.values()) {
assertEquals(new LaunchImage(imageId, null), service.resolveForLaunch(imageId, behavior));
}
assertEquals(0, daemon.pulls.get());
}
@Test
void anImageIdThatIsGoneFailsALaunchWithoutAPull() {
FakeDaemon daemon = new FakeDaemon();
assertThrows(DockerClientException.class, () -> newService(daemon.client)
.resolveForLaunch("sha256:" + "e".repeat(64), ImagePullBehavior.ALWAYS));
assertEquals(0, daemon.pulls.get());
}
@Test
void aLaunchReportsTheDigestItsPullResolvedTheTagTo() {
FakeDaemon daemon = new FakeDaemon();
daemon.registry.put(REGISTRY_IMAGE, image("sha256:config",
REGISTRY_REPO + "@sha256:platform-manifest", REGISTRY_REPO + "@sha256:index"));
daemon.registryDigests.put(REGISTRY_IMAGE, "sha256:index");
assertEquals(new LaunchImage("sha256:config", "sha256:index"),
newService(daemon.client).resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.DEFAULT));
}
@Test
void aCachedLaunchReportsNoDigestWhenAnOutsidePullMovedTheTagToAnotherManifestOfTheSameImage() {
FakeDaemon daemon = new FakeDaemon();
daemon.registry.put(REGISTRY_IMAGE, image("sha256:config", REGISTRY_REPO + "@sha256:first-manifest"));
daemon.registryDigests.put(REGISTRY_IMAGE, "sha256:first-manifest");
ImageCacheService service = newService(daemon.client);
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.DEFAULT);
// A docker pull outside Floci moves the tag to a second manifest of the same image config,
// which the classic image store keeps under the same image id.
daemon.store(REGISTRY_IMAGE, image("sha256:config",
REGISTRY_REPO + "@sha256:first-manifest", REGISTRY_REPO + "@sha256:second-manifest"));
assertEquals(new LaunchImage("sha256:config", null),
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.PREFER_CACHED));
}
@Test
void aCachedLaunchReportsTheDigestTheContainerdStoreNamesTheImageBy() {
FakeDaemon daemon = new FakeDaemon();
daemon.store(REGISTRY_IMAGE, image("sha256:index",
REGISTRY_REPO + "@sha256:platform-manifest", REGISTRY_REPO + "@sha256:index"));
assertEquals(new LaunchImage("sha256:index", "sha256:index"),
newService(daemon.client).resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.PREFER_CACHED));
}
@Test
void aCachedLaunchDoesNotReportTheDigestOfAnImageTheTagNoLongerNames() {
FakeDaemon daemon = new FakeDaemon();
daemon.registry.put(REGISTRY_IMAGE, image("sha256:old", REGISTRY_REPO + "@sha256:old-manifest"));
daemon.registryDigests.put(REGISTRY_IMAGE, "sha256:old-manifest");
ImageCacheService service = newService(daemon.client);
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.DEFAULT);
daemon.store(REGISTRY_IMAGE, image("sha256:rebuilt"));
assertEquals(new LaunchImage("sha256:rebuilt", null),
service.resolveForLaunch(REGISTRY_IMAGE, ImagePullBehavior.PREFER_CACHED));
}
@Test
void manifestDigestIsEmptyWhenTheRepositoryHasSeveralDigests() {
InspectImageResponse image = image("sha256:id",
REGISTRY_REPO + "@sha256:platform-manifest", REGISTRY_REPO + "@sha256:index");
assertEquals(Optional.empty(), ImageCacheService.manifestDigest(REGISTRY_IMAGE, image));
}
@Test
void manifestDigestIsTheRepoDigestOfTheRepositoryTheReferenceNames() {
InspectImageResponse pulled = image("sha256:id",
"mirror.example:5000/app@sha256:mirror-manifest", REGISTRY_REPO + "@sha256:manifest");
assertEquals(Optional.of("sha256:manifest"), ImageCacheService.manifestDigest(REGISTRY_IMAGE, pulled));
}
@Test
void manifestDigestMatchesDockerHubRepositoriesWrittenInFull() {
InspectImageResponse pulled = image("sha256:id", "alpine@sha256:manifest");
assertEquals(Optional.of("sha256:manifest"),
ImageCacheService.manifestDigest("docker.io/library/alpine:3.20", pulled));
}
@Test
void manifestDigestOfADigestReferenceIsThatDigest() {
assertEquals(Optional.of("sha256:pinned"),
ImageCacheService.manifestDigest(REGISTRY_REPO + "@sha256:pinned", image("sha256:id")));
}
@Test
void manifestDigestIsEmptyForALocallyBuiltImage() {
assertEquals(Optional.empty(), ImageCacheService.manifestDigest(LOCAL_IMAGE, image("sha256:built")));
}
private static InspectImageResponse image(String id, String... repoDigests) {
return new InspectImageResponse()
.withId(id)
.withOs("linux")
.withArch("amd64")
.withRepoDigests(List.of(repoDigests));
}
/**
* A daemon whose local images and registry are plain maps, so a test can move a tag in either
* place and watch which image the next launch resolves to.
*/
private static final class FakeDaemon {
final DockerClient client = mock(DockerClient.class);
final Map<String, InspectImageResponse> local = new HashMap<>();
final Map<String, InspectImageResponse> registry = new HashMap<>();
final Map<String, String> registryDigests = new HashMap<>();
final AtomicInteger pulls = new AtomicInteger();
FakeDaemon() {
when(client.inspectImageCmd(anyString())).thenAnswer(invocation -> {
String reference = invocation.getArgument(0);
InspectImageCmd inspect = mock(InspectImageCmd.class);
when(inspect.exec()).thenAnswer(ignored -> {
InspectImageResponse image = local.get(reference);
if (image == null) {
throw new NotFoundException("No such image: " + reference);
}
return image;
});
return inspect;
});
when(client.pullImageCmd(anyString())).thenAnswer(invocation -> {
String reference = invocation.getArgument(0);
PullImageCmd pull = mock(PullImageCmd.class);
when(pull.withAuthConfig(any())).thenReturn(pull);
when(pull.exec(any(PullImageResultCallback.class))).thenAnswer(execution -> {
pulls.incrementAndGet();
InspectImageResponse image = registry.get(reference);
if (image == null) {
throw new NotFoundException("manifest unknown: " + reference);
}
store(reference, image);
String digest = registryDigests.get(reference);
if (digest != null) {
PullResponseItem status = mock(PullResponseItem.class);
when(status.getStatus()).thenReturn("Digest: " + digest);
execution.<PullImageResultCallback>getArgument(0).onNext(status);
}
return mock(PullImageResultCallback.class);
});
return pull;
});
}
void store(String tag, InspectImageResponse image) {
local.put(tag, image);
local.put(image.getId(), image);
}
}
private static ImageCacheService newService(DockerClient dockerClient) {
InfoCmd infoCmd = mock(InfoCmd.class);
when(dockerClient.infoCmd()).thenReturn(infoCmd);
@@ -30,6 +30,9 @@ public final class TestImages {
/** The same image AWS publishes at {@code public.ecr.aws/aws-observability/aws-for-fluent-bit:3}. */
public static final String FLUENT_BIT = "amazon/aws-for-fluent-bit:3";
/** The tag {@code floci.services.ecr.registry-image} ships with. */
public static final String REGISTRY = "registry:2";
private TestImages() {
}
}