From 23728e0b7596dabaf4aec1a9a0ca04c3a5d6e1c4 Mon Sep 17 00:00:00 2001 From: Kurt McAlpine Date: Sat, 5 Sep 2026 02:59:51 +1200 Subject: [PATCH] feat(ecr): prefer locally present images over the loopback registry rewrite (#3022) * feat(ecr): prefer locally present images over the loopback registry rewrite EcrRegistryManager.rewriteImageUri rewrote every AWS-shaped .dkr.ecr..amazonaws.com/: URI to Floci's loopback registry unconditionally, so a container image Lambda function (or ECS task) whose image was built locally and tagged with its real ECR URI could never run: the launcher started the registry:2 sidecar and tried to pull from it, failing with "failed to resolve reference ..." (Lambda.InitError) even though the daemon already held the image. The rewrite now first asks the Docker daemon whether the image exists under the URI as given; if it does, the URI is used unchanged and the registry container is not started. Images the daemon does not have keep the existing rewrite-and-pull path, so CDK DockerImageFunction flows are unaffected. floci.services.ecr.prefer-local-images (FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES, default true) restores the old behaviour when set to false. Verified with a provided.al2023 Go image tagged 000000000000.dkr.ecr.ap-southeast-2.amazonaws.com/e2e/hello-image:local: Invoke fails on 2.0.1 and succeeds with this change, both with Floci as a host process and inside a container sharing the host's docker.sock; an image absent from the daemon still takes the rewrite path. * fix(ecr): inspect the image reference ContainerBuilder launches when preferring local images With floci.docker.image-registry-base set, rewriteImageUri inspected the bare AWS-shaped URI while ContainerBuilder later prefixed it, so a locally present image was reported as found and then missed at launch. Resolve the image through ContainerBuilder before asking the daemon so both paths agree. --- .../configuration/advanced/application-yml.md | 1 + docs/configuration/environment-variables.md | 1 + docs/services/ecr.md | 4 +- docs/services/lambda.md | 4 + .../floci/config/EmulatorConfig.java | 7 ++ .../core/common/docker/ContainerBuilder.java | 2 +- .../ecr/registry/EcrRegistryManager.java | 26 +++++- src/main/resources/application.yml | 1 + .../ecr/registry/EcrRegistryManagerTest.java | 84 ++++++++++++++++++- 9 files changed, 126 insertions(+), 4 deletions(-) diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 2da1e30f99..763d6de196 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -275,6 +275,7 @@ floci: tls-enabled: false keep-running-on-shutdown: true uri-style: hostname # hostname | path + prefer-local-images: true ``` ### Initialization hooks diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 4bd72d6c19..a408ecebf8 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -396,6 +396,7 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_ECR_TLS_ENABLED` | `false` | Enable TLS for the ECR registry | | `FLOCI_SERVICES_ECR_KEEP_RUNNING_ON_SHUTDOWN` | `true` | Keep the ECR registry container running when Floci stops | | `FLOCI_SERVICES_ECR_URI_STYLE` | `hostname` | Repository URI style: `hostname` (`.dkr.ecr..localhost`) or `path` | +| `FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES` | `true` | Use an AWS-shaped ECR image URI as-is when the Docker daemon already has that image, instead of rewriting it to the loopback registry | | `FLOCI_SERVICES_ECR_DOCKER_NETWORK` | _(none)_ | Docker network for the ECR registry container | ### EKS (Elastic Kubernetes Service) diff --git a/docs/services/ecr.md b/docs/services/ecr.md index 9d143b6461..c75453f5fe 100644 --- a/docs/services/ecr.md +++ b/docs/services/ecr.md @@ -36,7 +36,8 @@ - **Manifest format negotiation.** `BatchGetImage` forwards the caller's `acceptedMediaTypes` as the upstream `Accept` header. Modern OCI manifests (`application/vnd.oci.image.manifest.v1+json`) and Docker v2 schema 2 are both supported. - **Cross-account / cross-region isolation.** Internally the registry namespaces repositories as `//`, so the same repository name in different accounts or regions cannot collide. - **Reconcile on first start.** When the registry container starts, Floci queries `GET /v2/_catalog` and recreates `Repository` metadata entries for any namespaces present in the registry but missing from local storage. This means image bytes are never orphaned across restarts. -- **Lambda integration.** Image-backed Lambda functions (`PackageType=Image`) reference the same loopback `repositoryUri`. Floci's Lambda runner rewrites real-AWS-shaped `.dkr.ecr..amazonaws.com/...` URIs to the loopback registry at pull time, so CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting. +- **Lambda and ECS integration.** Image-backed Lambda functions (`PackageType=Image`) and ECS task containers reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `.dkr.ecr..amazonaws.com/...` URIs to the loopback registry at pull time, so CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting. +- **Locally built images win.** An AWS-shaped URI that names an image already present on the Docker daemon is used as-is instead of being rewritten (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`, default `true`). Build the image under the exact URI your function or task definition declares (`docker build -t .dkr.ecr..amazonaws.com/: .`) and it runs without a push to the emulated registry, and without the registry container being started. The check uses the reference Floci would launch, so with `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set the image must be present as `/.dkr.ecr..amazonaws.com/:`. ## Configuration @@ -50,6 +51,7 @@ | `FLOCI_SERVICES_ECR_DATA_PATH` | `./data/ecr` | Bind-mount root for the registry data directory | | `FLOCI_SERVICES_ECR_KEEP_RUNNING_ON_SHUTDOWN` | `true` | Leave the registry container running so the next Floci start adopts it | | `FLOCI_SERVICES_ECR_URI_STYLE` | `hostname` | `hostname` = `*.dkr.ecr..localhost`; `path` = `localhost:///` | +| `FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES` | `true` | Use an AWS-shaped ECR image URI as-is when the Docker daemon already has that image, instead of rewriting it to the loopback registry | | `FLOCI_SERVICES_ECR_TLS_ENABLED` | `false` | Reserved for future ACM-backed TLS | ### Docker Compose port mapping diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 0da6006ef1..3c546c512a 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -658,6 +658,10 @@ When unset (default), Floci injects execution-role credentials for a known role. first time it happens. Give the function a role Floci knows, or set `aws-config-path`, to keep host credentials out of the container. +### Locally built images + +A container image function whose `ImageUri` names an image already present on the Docker daemon runs that image directly. This includes AWS-shaped `.dkr.ecr..amazonaws.com/:` URIs, which are otherwise rewritten to [Floci's emulated ECR registry](ecr.md) at pull time: build the image under the exact URI the function declares (`docker build -t .`) and no push is needed. With `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set, tag it as `/` instead, since that is the reference Floci launches. Set `FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES=false` to always resolve AWS-shaped URIs through the emulated registry. + ### Private registry authentication Container image functions (`"PackageType": "Image"`) that pull from private registries need Docker credentials. See [Docker Configuration → Private Registry Authentication](../configuration/docker.md#private-registry-authentication) for the full guide. diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index fb75657c8e..e23c9cb5fe 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1804,6 +1804,13 @@ public interface EmulatorConfig { @WithDefault("hostname") String uriStyle(); + /** + * When true, an AWS-shaped ECR image URI that names an image already present on the Docker + * daemon is used as-is instead of being rewritten to Floci's loopback registry. + */ + @WithDefault("true") + boolean preferLocalImages(); + Optional dockerNetwork(); } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java index 35fc343ae0..c600ae0ae7 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java @@ -65,7 +65,7 @@ public class ContainerBuilder { return new Builder(resolveImage(image), config, dockerHostResolver, embeddedDnsServer, currentContainerNetworkResolver); } - private String resolveImage(String image) { + public String resolveImage(String image) { return resolveImage(image, configuredImageRegistryBase(config)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java index bb471e0b0a..3f80d06a71 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java @@ -15,6 +15,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.command.InspectExecResponse; +import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.Frame; import jakarta.enterprise.context.ApplicationScoped; @@ -95,7 +96,10 @@ public class EcrRegistryManager { * starting the backing registry container on first use. Any image that doesn't * match the AWS ECR URI shape (e.g. a plain Docker Hub reference or an image * already pointing at Floci's registry) is returned unchanged, without starting - * the registry container. + * the registry container, as is an AWS-shaped URI naming an image the Docker + * daemon already has (under the reference {@link ContainerBuilder#resolveImage} + * launches, so {@code floci.docker.image-registry-base} is honoured) while + * {@code floci.services.ecr.prefer-local-images} is on. */ public String rewriteImageUri(String image) { if (image == null) { @@ -105,6 +109,13 @@ public class EcrRegistryManager { if (!m.matches()) { return image; } + if (config.services().ecr().preferLocalImages()) { + String resolved = containerBuilder.resolveImage(image); + if (isPresentOnDaemon(resolved)) { + LOG.infov("Using locally present image {0} as-is (not rewriting to the emulated ECR registry)", resolved); + return image; + } + } String account = m.group(1); String region = m.group(2); String repoAndTag = m.group(3); @@ -114,6 +125,19 @@ public class EcrRegistryManager { return rewritten; } + private boolean isPresentOnDaemon(String image) { + try { + lifecycleManager.getDockerClient().inspectImageCmd(image).exec(); + return true; + } catch (NotFoundException e) { + return false; + } catch (RuntimeException e) { + LOG.debugv("Could not inspect image {0} on the Docker daemon ({1}); rewriting to the emulated ECR registry", + image, e.getMessage()); + return false; + } + } + /** Returns the docker-pullable repository URI for the given account/region/name. */ public String getRepositoryUri(String accountId, String region, String repoName) { int port = effectivePort(); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 595ba91c0b..e9a324cfba 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -460,6 +460,7 @@ floci: tls-enabled: false keep-running-on-shutdown: true uri-style: hostname + prefer-local-images: true ui: enabled: true image: "floci/floci-ui:latest" diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java index 982c38d76b..5673b03f02 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java @@ -16,6 +16,10 @@ import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.command.ExecStartCmd; import com.github.dockerjava.api.command.InspectExecCmd; import com.github.dockerjava.api.command.InspectExecResponse; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.InspectImageResponse; +import com.github.dockerjava.api.exception.DockerClientException; +import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.Frame; import org.junit.jupiter.api.BeforeEach; @@ -46,6 +50,7 @@ class EcrRegistryManagerTest { private static final int BASE_PORT = 6100; private static final int MAX_PORT = 6101; // pool of exactly two ports private static final String REGISTRY_NAME = "floci-test-ecr-registry"; + private static final String AWS_ECR_IMAGE = "123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1"; private PortAllocator portAllocator; private ContainerLifecycleManager lifecycleManager; @@ -54,20 +59,29 @@ class EcrRegistryManagerTest { private EmulatorConfig.DockerConfig docker; private EmulatorConfig.EcrServiceConfig ecr; private EmulatorConfig.StorageConfig storage; + private ContainerBuilder containerBuilder; private ContainerBuilder.Builder builder; + private DockerClient dockerClient; + private InspectImageCmd inspectImage; private EcrRegistryManager manager; @BeforeEach void setUp() { portAllocator = new PortAllocator(); - ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + containerBuilder = Mockito.mock(ContainerBuilder.class); builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); + when(containerBuilder.resolveImage(anyString())).thenAnswer(inv -> inv.getArgument(0)); when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class)); lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); when(lifecycleManager.findByName(anyString())).thenReturn(Optional.empty()); + dockerClient = Mockito.mock(DockerClient.class); + inspectImage = Mockito.mock(InspectImageCmd.class); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + when(dockerClient.inspectImageCmd(anyString())).thenReturn(inspectImage); + Mockito.doThrow(new NotFoundException("No such image")).when(inspectImage).exec(); ContainerLogStreamer logStreamer = Mockito.mock(ContainerLogStreamer.class); containerDetector = Mockito.mock(ContainerDetector.class); @@ -91,6 +105,7 @@ class EcrRegistryManagerTest { when(ecr.registryBasePort()).thenReturn(BASE_PORT); when(ecr.registryMaxPort()).thenReturn(MAX_PORT); when(ecr.dockerNetwork()).thenReturn(Optional.empty()); + when(ecr.preferLocalImages()).thenReturn(true); manager = new EcrRegistryManager(containerBuilder, lifecycleManager, logStreamer, containerDetector, currentContainerNetworkResolver, portAllocator, config, regionResolver); @@ -211,6 +226,73 @@ class EcrRegistryManagerTest { assertNull(manager.rewriteImageUri(null)); } + @Test + void rewriteImageUri_imagePresentOnDaemon_returnsUnchangedWithoutStartingRegistry() { + Mockito.doReturn(new InspectImageResponse()).when(inspectImage).exec(); + + String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE); + + assertEquals(AWS_ECR_IMAGE, rewritten); + verify(dockerClient).inspectImageCmd(AWS_ECR_IMAGE); + verify(lifecycleManager, Mockito.never()).createAndStart(any()); + } + + @Test + void rewriteImageUri_imagePresentOnDaemon_preferLocalImagesOff_rewritesWithoutInspecting() { + when(ecr.preferLocalImages()).thenReturn(false); + Mockito.doReturn(new InspectImageResponse()).when(inspectImage).exec(); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + + String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE); + + assertEquals("123456789012.dkr.ecr.us-east-1.localhost:" + BASE_PORT + "/backend-user:1", rewritten); + verify(dockerClient, Mockito.never()).inspectImageCmd(anyString()); + } + + @Test + void rewriteImageUri_imageRegistryBaseConfigured_inspectsResolvedReference() { + String mirrored = "ghcr.io/floci-io/mirror/" + AWS_ECR_IMAGE; + when(containerBuilder.resolveImage(AWS_ECR_IMAGE)).thenReturn(mirrored); + Mockito.doReturn(new InspectImageResponse()).when(inspectImage).exec(); + + String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE); + + assertEquals(AWS_ECR_IMAGE, rewritten); + verify(dockerClient).inspectImageCmd(mirrored); + verify(dockerClient, Mockito.never()).inspectImageCmd(AWS_ECR_IMAGE); + verify(lifecycleManager, Mockito.never()).createAndStart(any()); + } + + @Test + void rewriteImageUri_imageRegistryBaseConfigured_unprefixedLocalImageDoesNotCount() { + String mirrored = "ghcr.io/floci-io/mirror/" + AWS_ECR_IMAGE; + when(containerBuilder.resolveImage(AWS_ECR_IMAGE)).thenReturn(mirrored); + InspectImageCmd inspectUnprefixed = Mockito.mock(InspectImageCmd.class); + Mockito.doReturn(new InspectImageResponse()).when(inspectUnprefixed).exec(); + when(dockerClient.inspectImageCmd(AWS_ECR_IMAGE)).thenReturn(inspectUnprefixed); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + + String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE); + + assertEquals("123456789012.dkr.ecr.us-east-1.localhost:" + BASE_PORT + "/backend-user:1", rewritten); + verify(dockerClient).inspectImageCmd(mirrored); + verify(lifecycleManager).createAndStart(any()); + } + + @Test + void rewriteImageUri_daemonInspectFails_rewritesToLocalRegistry() { + Mockito.doThrow(new DockerClientException("daemon unavailable")).when(inspectImage).exec(); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + + String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE); + + assertEquals("123456789012.dkr.ecr.us-east-1.localhost:" + BASE_PORT + "/backend-user:1", rewritten); + verify(lifecycleManager).createAndStart(any()); + } + @Test void pruneStorageRemovesTheRegistryAndVolumeWhenConfigured() { when(storage.pruneVolumesOnDelete()).thenReturn(true);