Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ecr): prefer locally present images over the loopback registry rewrite (#3022)

Kurt McAlpine23728e0b7596
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` (`<account>.dkr.ecr.<region>.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 `<account>/<region>/<repoName>`, 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 `<account>.dkr.ecr.<region>.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 `<account>.dkr.ecr.<region>.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 <account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag> .`) 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 `<base>/<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag>`.
## 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.<region>.localhost`; `path` = `localhost:<port>/<account>/<region>/<repo>` |
+| `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 `<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag>` 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 <ImageUri> .`) and no push is needed. With `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set, tag it as `<base>/<ImageUri>` 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<String> 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);