fix(ecr): prevent registry request stalls during background garbage collection (#7437)

* fix(ecr): prevent registry request stalls during background garbage col…

fix(ecr): coordinate write admission and enforce exec termination durin…

Resolve race conditions between garbage collection and incoming write operations:

- Enforce container exec termination on await timeout or interruption using kernel-level `timeout -k 2` and process polling via `inspectExecCmd`.
- Keep write admission closed if exec process status is not definitively terminated.
- Implement atomic write admission tokens (`tryAcquireWriteAdmission`) under `writeAdmissionLock` to gate mutating requests (`POST`, `PUT`, `PATCH`, `DELETE`) with HTTP 503 while preserving non-blocking `GET` and `HEAD` requests.
- Decouple GC synchronization using a dedicated `gcLock` and drain active in-flight writes before initiating container exec.
- Add post-startup GC re-check in `EcrRegistryDataPlane.checkTagAndProxy()` prior to upstream proxying.
- Add unit tests `runGarbageCollectTimeoutWithExecStillRunningKeepsAdmissionClosed` and `garbageCollectionDuringStartupRefusesWritesAndPreservesReads`.

Closes #6150

fix(ecr): address review feedback on gc wait, tag claims, and registry…

Address code review feedback on ECR registry data plane and lifecycle management:

- Claim immutable tags prior to Exchange creation in EcrRegistryDataPlane to avoid tag release race on collisions
- Defer write admission release in Exchange.end() until client.close() completes
- Implement deadlock-free two-phase synchronization in EcrRegistryManager.runGarbageCollect() to preserve mutual exclusion with EcrService and storage pruning
- Ensure write admission is reopened if Docker exec start or inspection throws
- Introduce volatile ready flag set after ping and catalog reconcile to gate fast-path probes safely

fix(ecr): extract shared stub registry helper in EcrRegistryDataPlaneTe…

Refactor stub registry helper in EcrRegistryDataPlaneTest.

Closes #6150

* fix(ecr): guarantee poll delay in awaitTermination and add clock test s…

- Decouple Docker exec inspection from polling delay in EcrRegistryManager.awaitTermination into sequential try-catch blocks, guaranteeing a 200 ms pause on every iteration.
- Add Clock and Sleeper test seams with production defaults in EcrRegistryManager while preserving the 8-arg @Inject constructor for CDI.
- Update runGarbageCollectTimeoutWithExecStillRunningKeepsAdmissionClosed in EcrRegistryManagerTest to advance time via ManualClock, eliminating the 3 s real-time wait.
- Sign commit with GPG and remove attribution trailer from PR description.
This commit is contained in:
noy-solvin authored and GitHub committed 2026-11-08 18:04:34 -04:00
1 parent 01c84245a7
commit a1f5b9b21f
4 files changed
+513 -70

No files matched your search

@@ -825,6 +825,77 @@ class EcrRegistryDataPlaneTest {
assertNull(response.apiVersion());
}
@Test
void garbageCollectionAllowsReadsAndRefusesWrites() throws Exception {
StubRegistry stub = stubRegistry();
when(stub.manager().isGarbageCollecting()).thenReturn(true);
HttpServer dataPlane = dataPlane(stub.manager(), false, null);
try {
RegistryResponse readResponse = request(dataPlane.actualPort(), HttpMethod.GET, "/v2/");
assertEquals(200, readResponse.status());
assertEquals("{\"status\":\"ok\"}", readResponse.body());
RegistryResponse putResponse = request(dataPlane.actualPort(), HttpMethod.PUT, "/v2/platform/api/manifests/v1");
assertEquals(503, putResponse.status());
assertEquals("registry/2.0", putResponse.apiVersion());
JsonObject json = new JsonObject(putResponse.body());
JsonArray errors = json.getJsonArray("errors");
assertNotNull(errors);
assertEquals("UNAVAILABLE", errors.getJsonObject(0).getString("code"));
assertTrue(errors.getJsonObject(0).getString("message").contains("garbage collection"));
RegistryResponse postResponse = request(dataPlane.actualPort(), HttpMethod.POST, "/v2/platform/api/blobs/uploads/");
assertEquals(503, postResponse.status());
assertEquals("registry/2.0", postResponse.apiVersion());
} finally {
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
stub.registry().close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
@Test
void garbageCollectionDuringStartupRefusesWritesAndPreservesReads() throws Exception {
StubRegistry stub = stubRegistry();
AtomicBoolean gcActive = new AtomicBoolean(false);
when(stub.manager().isGarbageCollecting()).thenAnswer(inv -> gcActive.get());
Mockito.doAnswer(inv -> { gcActive.set(true); return null; }).when(stub.manager()).ensureStarted();
HttpServer dataPlane = dataPlane(stub.manager(), false, null);
try {
RegistryResponse postResponse = request(dataPlane.actualPort(), HttpMethod.POST, "/v2/platform/api/blobs/uploads/");
assertEquals(503, postResponse.status());
assertEquals("registry/2.0", postResponse.apiVersion());
RegistryResponse readResponse = request(dataPlane.actualPort(), HttpMethod.GET, "/v2/");
assertEquals(200, readResponse.status());
RegistryResponse headResponse = request(dataPlane.actualPort(), HttpMethod.HEAD, "/v2/");
assertEquals(200, headResponse.status());
} finally {
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
stub.registry().close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
// Issue #6150 / PR #7437: Shared helper to build stub registry and mock manager wiring
private StubRegistry stubRegistry() throws Exception {
HttpServer registry = vertx.createHttpServer().requestHandler(request -> {
if (request.method() == HttpMethod.GET || request.method() == HttpMethod.HEAD) {
request.response().setStatusCode(200).end("{\"status\":\"ok\"}");
} else {
request.response().setStatusCode(201).end();
}
}).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()));
when(manager.isStarted()).thenReturn(true);
return new StubRegistry(registry, manager);
}
private record StubRegistry(HttpServer registry, EcrRegistryManager manager) {}
/**
* 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
@@ -847,6 +918,8 @@ class EcrRegistryDataPlaneTest {
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.tryAcquireWriteAdmission())
.thenAnswer(inv -> !registryManager.isGarbageCollecting());
when(ecrService.isImageTagImmutable("platform/api", "000000000000", "us-east-1"))
.thenReturn(immutableTags);
// The tag lock lives in EcrService, so the mock holds a real one.
@@ -29,6 +29,7 @@ import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
import io.floci.aws.core.common.docker.HostBlindPortAllocator;
import io.floci.aws.core.common.docker.PortAllocator;
import io.floci.aws.testing.ManualClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -36,10 +37,15 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.Mockito;
import java.io.Closeable;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -48,6 +54,7 @@ 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.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
@@ -149,6 +156,36 @@ class EcrRegistryManagerTest {
"io.floci.region", "us-east-1"));
}
@Test
void ensureStartedDoesNotBlockWhenAlreadyRunning() throws Exception {
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
when(lifecycleManager.presenceOf("container-id")).thenReturn(ContainerPresence.RUNNING);
manager.ensureStarted();
assertTrue(manager.isStarted());
CountDownLatch lockAcquired = new CountDownLatch(1);
CountDownLatch finishLock = new CountDownLatch(1);
Thread holder = new Thread(() -> {
synchronized (manager) {
lockAcquired.countDown();
try {
finishLock.await(5, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {}
}
});
holder.start();
assertTrue(lockAcquired.await(2, TimeUnit.SECONDS));
try {
CompletableFuture<Void> call = CompletableFuture.runAsync(() -> manager.ensureStarted());
call.get(2, TimeUnit.SECONDS);
} finally {
finishLock.countDown();
holder.join();
}
}
@Test
void ensureStartedBindsTheBackingRegistryToLoopbackOnly() {
when(lifecycleManager.createAndStart(any())).thenReturn(
@@ -905,6 +942,44 @@ class EcrRegistryManagerTest {
"/var/lib/registry/docker/registry/v2/repositories/000000000000/us-east-1/team/app/_uploads");
}
@Test
@SuppressWarnings("unchecked")
void runGarbageCollectTimeoutWithExecStillRunningKeepsAdmissionClosed() throws Exception {
ManualClock clock = new ManualClock(Instant.now());
manager.setClock(clock);
manager.setSleeper(millis -> clock.advance(Duration.ofMillis(millis)));
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
when(lifecycleManager.presenceOf("container-id")).thenReturn(ContainerPresence.RUNNING);
manager.ensureStarted();
ExecCreateCmd execCreateCmd = Mockito.mock(ExecCreateCmd.class, Mockito.RETURNS_SELF);
ExecCreateCmdResponse execResponse = Mockito.mock(ExecCreateCmdResponse.class);
when(dockerClient.execCreateCmd("container-id")).thenReturn(execCreateCmd);
when(execCreateCmd.exec()).thenReturn(execResponse);
when(execResponse.getId()).thenReturn("gc-exec-1");
ExecStartCmd execStartCmd = Mockito.mock(ExecStartCmd.class, Mockito.RETURNS_SELF);
when(dockerClient.execStartCmd("gc-exec-1")).thenReturn(execStartCmd);
ResultCallback.Adapter<Frame> execCallback = Mockito.mock(ResultCallback.Adapter.class);
when(execStartCmd.exec(any())).thenReturn(execCallback);
when(execCallback.awaitCompletion(anyLong(), any())).thenReturn(false);
InspectExecCmd inspectCmd = Mockito.mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = Mockito.mock(InspectExecResponse.class);
when(dockerClient.inspectExecCmd("gc-exec-1")).thenReturn(inspectCmd);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(inspectResponse.getExitCodeLong()).thenReturn(null);
assertThrows(RuntimeException.class, () -> manager.runGarbageCollect(1));
assertTrue(manager.isGarbageCollecting());
assertFalse(manager.tryAcquireWriteAdmission());
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
manager.confirmExecTerminated("gc-exec-1");
assertFalse(manager.isGarbageCollecting());
assertTrue(manager.tryAcquireWriteAdmission());
}
@ParameterizedTest
@CsvSource({
"123456789012.dkr.ecr.eu-west-1.amazonaws.com/spark/custom:7.5.0, eu-west-1",