Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ecr): explain unavailable registry responses (#6752)
Aniket Shuklac37e0aaba947
diff --git a/docs/services/ecr.md b/docs/services/ecr.mdindex 39e8cc889c..e1330c7005 100644--- a/docs/services/ecr.md+++ b/docs/services/ecr.md@@ -93,6 +93,7 @@ the optional `filter` fields.| `FLOCI_SERVICES_ECR_REGISTRY_MAX_PORT` | `5199` | Last private loopback port for the backing registry || `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_DOCKER_NETWORK` | Inherit Floci's container network | Docker network shared by Floci and the backing registry when running in Docker || `FLOCI_SERVICES_ECR_URI_STYLE` | `hostname` | `hostname` = `*.dkr.ecr.<region>.localhost`; `path` = `localhost:<port>/<account>/<region>/<repo>` || `FLOCI_SERVICES_ECR_TLS_URI` | `false` | Report `localhost.floci.io` registry addresses and an HTTPS login endpoint when global `FLOCI_TLS_ENABLED` is also `true` || `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 |@@ -285,6 +286,15 @@ The following ECR features are **not** implemented. Stored values for policies a**`docker login` fails with TLS errors.** When TLS URI advertising is enabled, Docker must trust the Floci CA independently of the AWS CLI, and the server certificate must cover the returned registry hostname. Follow the trust steps above; setting only `AWS_CA_BUNDLE` is insufficient. Default loopback URIs remain usable over HTTP without additional Docker trust configuration.+**Registry requests return `503 Service Unavailable`.** Floci could not start or connect to its+backing registry. Errors detected by Floci include a Distribution `errors` array with a network configuration+hint. Check Docker availability and the registry container's health. When Floci itself runs in+Docker, attach Floci and its registry to the same user-defined network. Docker's default `bridge`+does not resolve container names, which Floci uses to reach the registry. Create a network with+`docker network create floci-net`, start Floci with `--network floci-net`, and set+`FLOCI_SERVICES_ECR_DOCKER_NETWORK=floci-net` if selecting the registry network explicitly.+See [Docker's bridge network documentation](https://docs.docker.com/engine/network/drivers/bridge/).+**Disk not reclaimed after deleting images.** `BatchDeleteImage` removes manifests but blobs remain on disk until garbage collection runs. Trigger it with `curl -X POST http://localhost:4566/_floci/ecr/gc`. The endpoint runs `registry garbage-collect` inside the backing container and returns the reclaimed blob list. The operation is serialized — ECR API calls block for its duration (typically a few seconds).**`*.localhost` does not resolve to loopback on this platform.** Set `floci.services.ecr.uri-style: path` to fall back to `localhost:<port>/<account>/<region>/<repo>` URIs.diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.java b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.javaindex aaf9cf0c35..22e71c1da6 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.java@@ -129,7 +129,7 @@ public class EcrRegistryDataPlane {if (result.failed()) {context.request().resume();exchange.end();- context.response().setStatusCode(503).end();+ registryUnavailable(context);} else if (result.result()) {context.request().resume();exchange.end();@@ -158,7 +158,7 @@ public class EcrRegistryDataPlane {if (upstreamRequest.failed()) {context.request().resume();exchange.end();- failUnlessGone(context, 503);+ registryUnavailable(context);return;}HttpClientRequest clientReq = upstreamRequest.result();@@ -180,6 +180,16 @@ public class EcrRegistryDataPlane {});}+ private static void registryUnavailable(RoutingContext context) {+ if (!context.response().ended() && !context.response().closed()) {+ String message = "ECR registry is unavailable. Check Docker and registry connectivity. "+ + "When running Floci in Docker, use a user-defined network shared with the registry "+ + "(FLOCI_SERVICES_ECR_DOCKER_NETWORK).";+ context.response().putHeader("Docker-Distribution-API-Version", "registry/2.0");+ registryError(context, 503, "UNAVAILABLE", message);+ }+ }+/** Answers {@code status} unless the response is already written or its client went away. */private static void failUnlessGone(RoutingContext context, int status) {if (!context.response().ended() && !context.response().closed()) {@@ -228,14 +238,14 @@ public class EcrRegistryDataPlane {String message = String.format("The image tag %s already exists in the %s repository and cannot be overwritten because the tag is immutable.",tag, repository);- String body = new JsonObject()- .put("errors", new JsonArray().add(new JsonObject()- .put("code", "TAG_INVALID")- .put("message", message)))- .encode();- context.response().setStatusCode(400)+ registryError(context, 400, "TAG_INVALID", message);+ }++ private static void registryError(RoutingContext context, int status, String code, String message) {+ context.response().setStatusCode(status).putHeader("Content-Type", "application/json")- .end(body);+ .end(new JsonObject().put("errors", new JsonArray().add(new JsonObject()+ .put("code", code).put("message", message))).encode());}private void release(String immutableTag) {diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.javaindex ea0e0b34cc..7ef77a349c 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecr.registry;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.services.ecr.EcrService;+import io.github.hectorvent.floci.testutil.FreePorts;import io.vertx.core.Future;import io.vertx.core.Vertx;import io.vertx.core.buffer.Buffer;@@ -21,6 +22,9 @@ import io.vertx.ext.web.Router;import org.junit.jupiter.api.AfterEach;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 org.junit.jupiter.params.provider.ValueSource;import org.mockito.Mockito;import java.util.ArrayList;@@ -551,6 +555,67 @@ class EcrRegistryDataPlaneTest {}}+ @ParameterizedTest+ @CsvSource({"true,GET,/v2/", "false,GET,/v2/",+ "true,PUT,/v2/platform/api/manifests/latest", "false,PUT,/v2/platform/api/manifests/latest"})+ void unavailableRegistryExplainsTheNetworkRequirement(boolean startupFailure, String method, String path)+ throws Exception {+ EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);+ HttpServer dataPlane = dataPlane(manager, false, null);+ when(manager.httpClient()).thenReturn(new RegistryHttpClient(+ "http://127.0.0.1:" + FreePorts.loopbackIpv4Port()));+ if (startupFailure) {+ Mockito.doThrow(new IllegalStateException("internal-startup-detail")).when(manager).ensureStarted();+ }+ RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.valueOf(method), path);+ assertEquals(503, response.status());+ assertEquals("application/json", response.contentType());+ assertEquals("registry/2.0", response.apiVersion());+ assertFalse(response.body().isBlank());+ JsonArray errors = new JsonObject(response.body()).getJsonArray("errors");+ assertNotNull(errors);+ assertEquals(1, errors.size());+ JsonObject error = errors.getJsonObject(0);+ assertEquals("UNAVAILABLE", error.getString("code"));+ String message = error.getString("message");+ assertTrue(message.contains("registry"));+ assertTrue(message.contains("user-defined network"));+ assertTrue(message.contains("FLOCI_SERVICES_ECR_DOCKER_NETWORK"));+ assertFalse(response.body().contains("internal-startup-detail"));+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void headFailuresKeepRegistryHeadersWithoutSendingABody(boolean startupFailure) throws Exception {+ EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);+ HttpServer dataPlane = dataPlane(manager, false, null);+ when(manager.httpClient()).thenReturn(new RegistryHttpClient(+ "http://127.0.0.1:" + FreePorts.loopbackIpv4Port()));+ if (startupFailure) {+ Mockito.doThrow(new IllegalStateException("internal-startup-detail")).when(manager).ensureStarted();+ }+ RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.HEAD, "/v2/platform/api/manifests/latest");+ assertEquals(503, response.status());+ assertEquals("application/json", response.contentType());+ assertEquals("registry/2.0", response.apiVersion());+ assertTrue(response.body().isEmpty());+ }++ @Test+ void upstreamErrorResponsesPassThroughUnchanged() throws Exception {+ HttpServer registry = vertx.createHttpServer().requestHandler(request -> request.response()+ .setStatusCode(503).putHeader("Content-Type", "text/plain").end("registry temporarily busy"))+ .listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);+ EcrRegistryManager manager = Mockito.mock(EcrRegistryManager.class);+ when(manager.httpClient()).thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.actualPort()));+ HttpServer dataPlane = dataPlane(manager, false, null);+ RegistryResponse response = request(dataPlane.actualPort(), HttpMethod.GET, "/v2/");+ assertEquals(503, response.status());+ assertEquals("text/plain", response.contentType());+ assertEquals("registry temporarily busy", response.body());+ assertNull(response.apiVersion());+ }+/*** A data plane in front of {@code registry}, on plain HTTP that a client can speak HTTP/1.1 or,* with prior knowledge, HTTP/2 to. Repository {@code platform/api} of account 000000000000 in@@ -562,12 +627,17 @@ class EcrRegistryDataPlaneTest {private HttpServer dataPlane(HttpServer registry, boolean immutableTags, CountDownLatch tagReleased) throws Exception {EcrRegistryManager registryManager = Mockito.mock(EcrRegistryManager.class);+ when(registryManager.httpClient())+ .thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.actualPort()));+ return dataPlane(registryManager, immutableTags, tagReleased);+ }++ private HttpServer dataPlane(EcrRegistryManager registryManager, boolean immutableTags,+ CountDownLatch tagReleased) throws Exception {EcrService ecrService = Mockito.mock(EcrService.class);EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);when(config.services().ecr().enabled()).thenReturn(true);when(config.services().ecr().uriStyle()).thenReturn("hostname");- when(registryManager.httpClient())- .thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.actualPort()));when(ecrService.isImageTagImmutable("platform/api", "000000000000", "us-east-1")).thenReturn(immutableTags);// The tag lock lives in EcrService, so the mock holds a real one.@@ -617,4 +687,16 @@ class EcrRegistryDataPlaneTest {.map(body -> new ManifestResponse(response.statusCode(), body.toString()))).toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);}++ private RegistryResponse request(int port, HttpMethod method, String path) throws Exception {+ return vertx.createHttpClient().request(new RequestOptions().setHost("127.0.0.1").setPort(port)+ .setMethod(method).setURI(path))+ .compose(request -> request.putHeader("Host", "000000000000.dkr.ecr.us-east-1.localhost:4566").send())+ .compose(response -> response.body().map(body -> new RegistryResponse(response.statusCode(),+ response.getHeader("Content-Type"), response.getHeader("Docker-Distribution-API-Version"),+ body.toString())))+ .toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);+ }++ private record RegistryResponse(int status, String contentType, String apiVersion, String body) {}}