diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java index 746bcd7c95..37f2591086 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java @@ -80,29 +80,61 @@ public class EcrRegistryDataPlane { return; } - context.request().pause(); - - RegistryRequest registryRequest = request.get(); - if (!registryRequest.repositoryName().isEmpty()) { - registryRequest = registryRequest.withStorageRepositoryName( - ecrService.registryRepositoryName( - registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region())); - } - String immutableTag = immutableTag(context, registryRequest); - if (immutableTag != null && !ecrService.claimImmutableTag(immutableTag)) { - context.request().resume(); - imageTagAlreadyExists(context, registryRequest); + boolean isWrite = isWriteRequest(context.request().method()); + // Bug #6150: Refuse mutating write requests with HTTP 503 while garbage collection runs + if (isWrite && !registryManager.tryAcquireWriteAdmission()) { + registryUnavailable(context, "ECR registry is temporarily unavailable while garbage collection is in progress."); return; } - Exchange exchange = new Exchange(immutableTag, manifestWriteRepository(context, registryRequest)); - // A client that goes away, by resetting its HTTP/2 stream or closing the connection, ends - // the exchange at any point, the registry check included: otherwise the registry keeps - // waiting for the rest of a body with a Content-Length, and the exchange's connection, - // client and immutable tag lock stay. - context.response().closeHandler(closed -> exchange.end()); - context.request().exceptionHandler(failure -> exchange.end()); - lockRepositoryWritesThenCheck(context, registryRequest, exchange); + boolean writeAdmissionHeld = isWrite; + Exchange activeExchange = null; + String immutableTag = null; + boolean tagClaimed = false; + try { + context.request().pause(); + + RegistryRequest registryRequest = request.get(); + if (!registryRequest.repositoryName().isEmpty()) { + registryRequest = registryRequest.withStorageRepositoryName( + ecrService.registryRepositoryName( + registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region())); + } + immutableTag = immutableTag(context, registryRequest); + if (immutableTag != null) { + if (!ecrService.claimImmutableTag(immutableTag)) { + context.request().resume(); + if (writeAdmissionHeld) { + writeAdmissionHeld = false; + registryManager.releaseWriteAdmission(); + } + imageTagAlreadyExists(context, registryRequest); + return; + } + tagClaimed = true; + } + + Exchange exchange = new Exchange(immutableTag, manifestWriteRepository(context, registryRequest), isWrite); + activeExchange = exchange; + writeAdmissionHeld = false; + context.response().closeHandler(closed -> exchange.end()); + context.request().exceptionHandler(failure -> exchange.end()); + + lockRepositoryWritesThenCheck(context, registryRequest, exchange); + } catch (Throwable t) { + if (activeExchange != null) { + activeExchange.end(); + } else { + if (tagClaimed) { + release(immutableTag); + } + if (writeAdmissionHeld) { + writeAdmissionHeld = false; + registryManager.releaseWriteAdmission(); + } + } + throw t; + } } /** @@ -135,6 +167,12 @@ public class EcrRegistryDataPlane { if (exchange.ended() || exchange.holdingWriteLock()) { return; } + // Bug #6150: If GC began while polling for the repository write lock, refuse the queued write request + if (registryManager.isGarbageCollecting() && isWriteRequest(context.request().method())) { + exchange.end(); + registryUnavailable(context, "ECR registry is temporarily unavailable while garbage collection is in progress."); + return; + } String repository = exchange.writeLockRepository(); if (repository == null || ecrService.tryLockRepositoryWrites(repository)) { exchange.writeLockAcquired(); @@ -211,6 +249,12 @@ public class EcrRegistryDataPlane { // registry. return; } + if (exchange.isWrite() && registryManager.isGarbageCollecting()) { + context.request().resume(); + exchange.end(); + registryUnavailable(context, "ECR registry is temporarily unavailable while garbage collection is in progress."); + return; + } if (result.failed()) { context.request().resume(); exchange.end(); @@ -274,15 +318,25 @@ public class EcrRegistryDataPlane { } private static void registryUnavailable(RoutingContext context) { + registryUnavailable(context, "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)."); + } + + private static void registryUnavailable(RoutingContext context, String message) { 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); } } + private static boolean isWriteRequest(HttpMethod method) { + return method == HttpMethod.POST + || method == HttpMethod.PUT + || method == HttpMethod.PATCH + || method == HttpMethod.DELETE; + } + /** 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()) { @@ -359,15 +413,22 @@ public class EcrRegistryDataPlane { private final String immutableTag; private final String writeLockRepository; + private final boolean isWrite; private final AtomicBoolean writeLockHeld = new AtomicBoolean(); private final AtomicBoolean ended = new AtomicBoolean(); + private final AtomicBoolean admissionReleased = new AtomicBoolean(); private Buffer waitingBody; private boolean waitingBodyRead; private HttpClient client; - private Exchange(String immutableTag, String writeLockRepository) { + private Exchange(String immutableTag, String writeLockRepository, boolean isWrite) { this.immutableTag = immutableTag; this.writeLockRepository = writeLockRepository; + this.isWrite = isWrite; + } + + private boolean isWrite() { + return isWrite; } private boolean ended() { @@ -430,19 +491,36 @@ public class EcrRegistryDataPlane { return registryClient; } + private void releaseAdmission() { + if (isWrite && admissionReleased.compareAndSet(false, true)) { + registryManager.releaseWriteAdmission(); + } + } + private void end() { if (!ended.compareAndSet(false, true)) { return; } releaseWriteLock(); if (client == null) { - release(immutableTag); + try { + releaseAdmission(); + } finally { + release(immutableTag); + } return; } // Closing the client closes the exchange's registry connection, which the registry - // sees and aborts on. The tag is free only once it is closed, so another write of the - // tag cannot start its check while this one can still reach the registry. - client.close().onComplete(closed -> release(immutableTag)); + // sees and aborts on. The tag and write admission are free only once it is closed, so + // another write of the tag or garbage collection cannot start while this one can still + // reach the registry. + client.close().onComplete(closed -> { + try { + releaseAdmission(); + } finally { + release(immutableTag); + } + }); } private void releaseWriteLock() { diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java index 4fb02c3107..244e39ef49 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java @@ -33,6 +33,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.time.Clock; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -63,6 +64,7 @@ public class EcrRegistryManager { private static final int REPOSITORY_DELETION_KILL_GRACE_SECONDS = 1; private static final String NAMED_VOLUME = "ecr-registry-data"; private static final String REPOSITORIES_PATH = "/var/lib/registry/docker/registry/v2/repositories/"; + private static final int GC_KILL_GRACE_SECONDS = 2; /** * Matches an AWS-shaped ECR image URI in any partition: @@ -98,9 +100,17 @@ public class EcrRegistryManager { private final PortAllocator portAllocator; private final EmulatorConfig config; private final RegionResolver regionResolver; + private volatile Clock clock; + private volatile Sleeper sleeper; private volatile boolean started; + private volatile boolean ready; private volatile boolean reconciled; + // Bug #6150: Track active garbage collection window + private volatile boolean garbageCollecting; + private final Object writeAdmissionLock = new Object(); + private int admittedWrites; + private volatile String activeGcExecId; /** host:port Docker reports for the running registry; null until one is started or adopted. */ private volatile String registryAddress; private volatile boolean unavailableLogged; @@ -120,6 +130,21 @@ public class EcrRegistryManager { PortAllocator portAllocator, EmulatorConfig config, RegionResolver regionResolver) { + this(containerBuilder, lifecycleManager, logStreamer, containerDetector, + currentContainerNetworkResolver, portAllocator, config, regionResolver, + Clock.systemUTC(), Thread::sleep); + } + + EcrRegistryManager(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerLogStreamer logStreamer, + ContainerDetector containerDetector, + CurrentContainerNetworkResolver currentContainerNetworkResolver, + PortAllocator portAllocator, + EmulatorConfig config, + RegionResolver regionResolver, + Clock clock, + Sleeper sleeper) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.logStreamer = logStreamer; @@ -129,6 +154,21 @@ public class EcrRegistryManager { this.config = config; this.regionResolver = regionResolver; this.hostPort = config.services().ecr().registryBasePort(); + this.clock = clock; + this.sleeper = sleeper; + } + + @FunctionalInterface + interface Sleeper { + void sleep(long millis) throws InterruptedException; + } + + void setClock(Clock clock) { + this.clock = clock; + } + + void setSleeper(Sleeper sleeper) { + this.sleeper = sleeper; } /** @@ -360,7 +400,21 @@ public class EcrRegistryManager { * Lazily starts (or reuses) the {@code registry:2} container. Idempotent and * thread-safe. Throws if Docker is unreachable. */ - public synchronized void ensureStarted() { + public void ensureStarted() { + if (!config.services().ecr().enabled()) { + throw new IllegalStateException("ECR is disabled, the backing registry is not started"); + } + // Bug #6150: Fast-path probe avoids acquiring the monitor when already running + if (ready) { + ContainerPresence presence = lifecycleManager.presenceOf(containerId); + if (presence == ContainerPresence.RUNNING || presence == ContainerPresence.UNKNOWN) { + return; + } + } + ensureStartedSynchronized(); + } + + private synchronized void ensureStartedSynchronized() { if (!config.services().ecr().enabled()) { throw new IllegalStateException("ECR is disabled, the backing registry is not started"); } @@ -374,6 +428,7 @@ public class EcrRegistryManager { containerId = null; registryAddress = null; started = false; + ready = false; if (presence == ContainerPresence.ABSENT) { portAllocator.release(hostPort); hostPort = config.services().ecr().registryBasePort(); @@ -399,6 +454,7 @@ public class EcrRegistryManager { this.activeContainerName = adoptedName; adoptExisting(existing.get()); runReconcileOnce(); + this.ready = true; return; } // Recreated under the current name; the data volume is resolved by its own probe. @@ -425,6 +481,7 @@ public class EcrRegistryManager { throw new RuntimeException("Failed to start ECR backing registry container: " + e.getMessage(), e); } runReconcileOnce(); + this.ready = true; } private ContainerSpec registryContainerSpec(String name, int port) { @@ -563,54 +620,140 @@ public class EcrRegistryManager { * @throws IllegalStateException if the registry is not started * @throws RuntimeException if the exec fails, exits non-zero, or times out */ - public synchronized GcResult runGarbageCollect(int timeoutSeconds) { + public GcResult runGarbageCollect(int timeoutSeconds) { if (!started || containerId == null) { throw new IllegalStateException("ECR registry is not started"); } - long startMs = System.currentTimeMillis(); - StringBuilder output = new StringBuilder(); + if (garbageCollecting) { + throw new IllegalStateException("ECR garbage collection is already in progress"); + } - DockerClient dockerClient = lifecycleManager.getDockerClient(); - - ExecCreateCmdResponse exec = dockerClient - .execCreateCmd(containerId) - .withCmd("registry", "garbage-collect", "/etc/docker/registry/config.yml") - .withAttachStdout(true) - .withAttachStderr(true) - .exec(); - - try { - boolean completed = dockerClient.execStartCmd(exec.getId()) - .exec(new ResultCallback.Adapter() { - @Override - public void onNext(Frame frame) { - output.append(new String(frame.getPayload(), StandardCharsets.UTF_8)); - } - }) - .awaitCompletion(timeoutSeconds, TimeUnit.SECONDS); - - if (!completed) { - throw new RuntimeException("garbage-collect timed out after " + timeoutSeconds + "s"); + // Bug #6150: Atomically close write admission and drain admitted writes before starting GC + synchronized (writeAdmissionLock) { + if (garbageCollecting) { + throw new IllegalStateException("ECR garbage collection is already in progress"); + } + garbageCollecting = true; + long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds); + while (admittedWrites > 0) { + long remaining = deadline - System.currentTimeMillis(); + if (remaining <= 0) { + garbageCollecting = false; + writeAdmissionLock.notifyAll(); + throw new RuntimeException("garbage-collect timed out waiting for admitted writes to drain"); + } + try { + writeAdmissionLock.wait(remaining); + } catch (InterruptedException e) { + garbageCollecting = false; + writeAdmissionLock.notifyAll(); + Thread.currentThread().interrupt(); + throw new RuntimeException("garbage-collect interrupted while waiting for admitted writes to drain", e); + } } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException("garbage-collect interrupted", e); } - InspectExecResponse inspect = dockerClient.inspectExecCmd(exec.getId()).exec(); - long durationMs = System.currentTimeMillis() - startMs; - Long exitCode = inspect.getExitCodeLong(); + // Bug #6150: Mutual exclusion with EcrService manifest delete/restore, pruneStorage, and + // deleteRepositoryStorage. Acquire the manager monitor ('this') only after admitted writes drain + // to prevent deadlock if an in-flight write requires ensureStartedSynchronized(). + synchronized (this) { + if (!started || containerId == null) { + reopenWriteAdmission(); + throw new IllegalStateException("ECR registry is not started"); + } + boolean execStarted = false; + boolean execTerminated = false; + String execId = null; + try { + long startMs = System.currentTimeMillis(); + StringBuilder output = new StringBuilder(); - if (exitCode == null) { - throw new RuntimeException("garbage-collect did not exit (still running after await)"); - } - if (exitCode != 0) { - LOG.warnv("ECR GC exited with code {0}: {1}", exitCode, output); - throw new RuntimeException("garbage-collect exited with code " + exitCode + ": " + output); - } + DockerClient dockerClient = lifecycleManager.getDockerClient(); - LOG.infov("ECR GC completed in {0}ms", durationMs); - return new GcResult(output.toString(), durationMs); + ExecCreateCmdResponse exec = dockerClient + .execCreateCmd(containerId) + .withCmd("timeout", "-k", String.valueOf(GC_KILL_GRACE_SECONDS), + String.valueOf(timeoutSeconds), "registry", "garbage-collect", + "/etc/docker/registry/config.yml") + .withAttachStdout(true) + .withAttachStderr(true) + .exec(); + + execId = exec.getId(); + activeGcExecId = execId; + final String finalExecId = execId; + + try { + ResultCallback.Adapter asyncCallback = dockerClient.execStartCmd(finalExecId) + .exec(new ResultCallback.Adapter() { + @Override + public void onNext(Frame frame) { + output.append(new String(frame.getPayload(), StandardCharsets.UTF_8)); + } + + @Override + public void onComplete() { + super.onComplete(); + confirmExecTerminated(finalExecId); + } + + @Override + public void onError(Throwable throwable) { + super.onError(throwable); + confirmExecTerminated(finalExecId); + } + }); + execStarted = true; + boolean completed = asyncCallback + .awaitCompletion(timeoutSeconds + GC_KILL_GRACE_SECONDS + 1, TimeUnit.SECONDS); + + if (!completed) { + execTerminated = awaitTermination(dockerClient, finalExecId, 3); + throw new RuntimeException("garbage-collect timed out after " + timeoutSeconds + "s"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + execTerminated = awaitTermination(dockerClient, finalExecId, 3); + throw new RuntimeException("garbage-collect interrupted", e); + } catch (Throwable t) { + if (!execStarted) { + reopenWriteAdmission(); + } + throw t; + } + + InspectExecResponse inspect; + try { + inspect = dockerClient.inspectExecCmd(finalExecId).exec(); + } catch (Throwable t) { + execTerminated = true; + reopenWriteAdmission(); + throw new RuntimeException("failed to inspect garbage-collect exec " + finalExecId, t); + } + long durationMs = System.currentTimeMillis() - startMs; + Long exitCode = inspect != null ? inspect.getExitCodeLong() : null; + + if (exitCode != null) { + execTerminated = true; + } + if (exitCode == null) { + throw new RuntimeException("garbage-collect did not exit (still running after await)"); + } + if (exitCode != 0) { + LOG.warnv("ECR GC exited with code {0}: {1}", exitCode, output); + throw new RuntimeException("garbage-collect exited with code " + exitCode + ": " + output); + } + + LOG.infov("ECR GC completed in {0}ms", durationMs); + return new GcResult(output.toString(), durationMs); + } finally { + if (!execStarted || execTerminated) { + reopenWriteAdmission(); + } else { + LOG.errorv("ECR GC exec {0} did not confirm termination; write admission remains closed for storage safety", execId); + } + } + } } /** Removes repository manifest storage without removing descendant repository directories. */ @@ -693,7 +836,9 @@ public class EcrRegistryManager { registryAddress = null; logStream = null; started = false; + ready = false; reconciled = false; + reopenWriteAdmission(); hostPort = config.services().ecr().registryBasePort(); } @@ -742,6 +887,8 @@ public class EcrRegistryManager { LOG.warnv("Failed to adopt existing ECR registry container: {0}", e.getMessage()); this.containerId = null; this.registryAddress = null; + this.started = false; + this.ready = false; } } @@ -782,8 +929,78 @@ public class EcrRegistryManager { } } - // Test seam - boolean isStarted() { + // Bug #6150: Accessor for active garbage collection status + public boolean isGarbageCollecting() { + return garbageCollecting; + } + + public boolean tryAcquireWriteAdmission() { + synchronized (writeAdmissionLock) { + if (garbageCollecting) { + return false; + } + admittedWrites++; + return true; + } + } + + public void releaseWriteAdmission() { + synchronized (writeAdmissionLock) { + if (admittedWrites > 0) { + admittedWrites--; + if (admittedWrites == 0) { + writeAdmissionLock.notifyAll(); + } + } + } + } + + boolean awaitTermination(DockerClient dockerClient, String execId, int maxSeconds) { + long deadline = clock.millis() + TimeUnit.SECONDS.toMillis(maxSeconds); + while (clock.millis() < deadline) { + try { + InspectExecResponse inspect = dockerClient.inspectExecCmd(execId).exec(); + if (inspect != null && inspect.getExitCodeLong() != null) { + return true; + } + } catch (Exception ignored) { + } + try { + // Bug #6150: Pause on every pass even if inspect throws to avoid tight spin loop + sleeper.sleep(200); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + return false; + } + } + return false; + } + + void confirmExecTerminated(String execId) { + try { + DockerClient dockerClient = lifecycleManager.getDockerClient(); + InspectExecResponse inspect = dockerClient.inspectExecCmd(execId).exec(); + if (inspect != null && inspect.getExitCodeLong() != null) { + synchronized (writeAdmissionLock) { + if (execId.equals(activeGcExecId)) { + reopenWriteAdmission(); + } + } + } + } catch (Exception e) { + LOG.debugv("Failed to inspect exec {0} on completion: {1}", execId, e.getMessage()); + } + } + + private void reopenWriteAdmission() { + synchronized (writeAdmissionLock) { + garbageCollecting = false; + activeGcExecId = null; + writeAdmissionLock.notifyAll(); + } + } + + public boolean isStarted() { return started; } } diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java index 5dba7b8c08..4601a7830b 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java @@ -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. diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java index a0e042a7c1..0cce3c9a68 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java @@ -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 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 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",