diff --git a/src/main/java/io/floci/aws/core/common/ContainerTeardown.java b/src/main/java/io/floci/aws/core/common/ContainerTeardown.java index 7b87722344..1a832dc5a5 100644 --- a/src/main/java/io/floci/aws/core/common/ContainerTeardown.java +++ b/src/main/java/io/floci/aws/core/common/ContainerTeardown.java @@ -23,6 +23,14 @@ package io.floci.aws.core.common; */ public interface ContainerTeardown { + /** + * Tells this teardown that the coming {@link #beginTeardown()} and {@link #stopManagedContainers()} are the + * process shutdown, not a reset or nuke: nothing can end a use that is still running once the process exits. + * {@code EmulatorLifecycle.onStop} calls it on every teardown before preparing any of them. + */ + default void beginShutdown() { + } + /** Prevents new work before any service starts draining its containers. */ default void beginTeardown() { } diff --git a/src/main/java/io/floci/aws/core/common/ContainerTeardowns.java b/src/main/java/io/floci/aws/core/common/ContainerTeardowns.java index f970113953..a56c00a5f9 100644 --- a/src/main/java/io/floci/aws/core/common/ContainerTeardowns.java +++ b/src/main/java/io/floci/aws/core/common/ContainerTeardowns.java @@ -29,6 +29,18 @@ public final class ContainerTeardowns { stopPrepared(prepareAll(teardowns, log), log); } + /** Calls {@link ContainerTeardown#beginShutdown()} on every teardown, tolerating a failure in one. */ + public static void beginShutdown(Instance teardowns, Logger log) { + for (ContainerTeardown teardown : teardowns) { + try { + teardown.beginShutdown(); + } catch (Exception e) { + log.warnv(e, "Marking the shutdown failed for {0}; its teardown may wait for uses still active", + teardown.getClass().getSimpleName()); + } + } + } + public static List prepareAll(Instance teardowns, Logger log) { List ordered = new ArrayList<>(); for (ContainerTeardown teardown : teardowns) { diff --git a/src/main/java/io/floci/aws/core/common/docker/PerKeyContainerPool.java b/src/main/java/io/floci/aws/core/common/docker/PerKeyContainerPool.java index 7c809f0578..a78c7dcd62 100644 --- a/src/main/java/io/floci/aws/core/common/docker/PerKeyContainerPool.java +++ b/src/main/java/io/floci/aws/core/common/docker/PerKeyContainerPool.java @@ -48,6 +48,7 @@ public class PerKeyContainerPool { * nothing left able to ever stop it again. */ private final AtomicLong generation = new AtomicLong(); + private volatile boolean refusingStarts; private final ConcurrentHashMap activeUses = new ConcurrentHashMap<>(); private final ConcurrentHashMap> retiredContainers = new ConcurrentHashMap<>(); @@ -120,6 +121,15 @@ public class PerKeyContainerPool { this.healthPath = healthPath; } + /** + * Makes every later {@link #ensureReady} that would start a container fail instead. For process + * shutdown: a container started after the final stop would have nothing left to stop it. A start + * already past the check is still caught by the generation bump of that final stop. + */ + public void refuseNewStarts() { + refusingStarts = true; + } + /** * Base URL of a ready container for {@code key}, starting one via {@code starter} if this is * the first use or the previous container is no longer healthy. Concurrent calls for @@ -155,7 +165,13 @@ public class PerKeyContainerPool { lifecycleManager.stopAndRemove(existing.containerId(), null); } } + // The generation is read before the refusal check, so a start that passes the check just + // before a shutdown sets the flag always sees that shutdown's later generation bump. long startedGeneration = generation.get(); + if (refusingStarts) { + throw new IllegalStateException("Sidecar pool is shutting down; not starting a container for key " + + key); + } StartedContainer started = starter.start(); // Registered before checking the generation, not after: checking first and only then // registering leaves a gap between the two where a concurrent stopAll() can run and diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java index 034dedf0a5..8de9ea0e8e 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java @@ -509,6 +509,7 @@ public class EmulatorLifecycle { runCleanup("Kinesis poller", kinesisPoller::shutdown); runCleanup("Redshift zero-ETL consumer", redshiftZeroEtlConsumer::shutdown); runCleanup("storage flush", storageFactory::flushAll); + ContainerTeardowns.beginShutdown(containerTeardowns, LOG); List prepared = ContainerTeardowns.prepareAll(containerTeardowns, LOG); runCleanup("RDS instance starts", rdsService::shutdownInstanceStarts); runCleanup("EC2 metadata server", () -> { diff --git a/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarManager.java index 6fd9eff574..162e184c75 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/BagetterSidecarManager.java @@ -150,6 +150,11 @@ public class BagetterSidecarManager implements ContainerTeardown { } } + @Override + public void beginShutdown() { + lease.beginShutdown(); + } + @Override public void stopManagedContainers() { lease.stopManagedContainers(); diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java index 746eb539ed..1cf41daf65 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlane.java @@ -139,10 +139,14 @@ public class CodeArtifactNpmDataPlane { } NpmUse use = new NpmUse(npmRepositoryId); AtomicReference cleanupOnClose = new AtomicReference<>(() -> { }); - context.response().endHandler(ignored -> use.responseDone()); - context.response().closeHandler(ignored -> { + // Through the routing context, never response().endHandler/closeHandler: the first + // addEndHandler (the publish path adds one) replaces the response's own handlers, which + // would lose this release and pin the repository's Verdaccio container for good. + context.addEndHandler(ended -> { use.responseDone(); - cleanupOnClose.get().run(); + if (ended.failed()) { + cleanupOnClose.get().run(); + } }); if (isPublish(context.request().method(), npmRequest.rest())) { diff --git a/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java index a96254e210..45bd211f5a 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java @@ -210,6 +210,11 @@ public class KellnrSidecarManager implements ContainerTeardown { return hex.toString(); } + @Override + public void beginShutdown() { + lease.beginShutdown(); + } + @Override public void stopManagedContainers() { lease.stopManagedContainers(); diff --git a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java index c4aa303f02..94167b8a7f 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/PypiserverSidecarManager.java @@ -179,6 +179,11 @@ public class PypiserverSidecarManager implements ContainerTeardown { } } + @Override + public void beginShutdown() { + lease.beginShutdown(); + } + @Override public void stopManagedContainers() { lease.stopManagedContainers(); diff --git a/src/main/java/io/floci/aws/services/codeartifact/SidecarRepositoryLease.java b/src/main/java/io/floci/aws/services/codeartifact/SidecarRepositoryLease.java index f37c42e571..a2e440d355 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/SidecarRepositoryLease.java +++ b/src/main/java/io/floci/aws/services/codeartifact/SidecarRepositoryLease.java @@ -14,6 +14,7 @@ final class SidecarRepositoryLease { private final String sidecarName; private final PerKeyContainerPool pool; private final ConcurrentHashMap uses = new ConcurrentHashMap<>(); + private volatile boolean shuttingDown; private static final class UseState { private int active; @@ -27,6 +28,17 @@ final class SidecarRepositoryLease { this.pool = pool; } + /** + * Makes the next {@link #stopManagedContainers()} stop every container, even one with uses still + * active. A reset or nuke keeps waiting for those uses (they can still finish), but once the process + * exits nothing can end them, so a container left running then would outlive Floci. For the same + * reason the pool starts no container from then on, not even for a use admitted before. + */ + void beginShutdown() { + shuttingDown = true; + pool.refuseNewStarts(); + } + void registerRepository(String repositoryId) { uses.putIfAbsent(repositoryId, new UseState()); } @@ -51,12 +63,21 @@ final class SidecarRepositoryLease { if (use == null) { throw new IllegalStateException("No " + sidecarName + " sidecar use for repository " + repositoryId); } + boolean stoppedByShutdown; synchronized (use) { if (use.active == 0) { throw new IllegalStateException("No active " + sidecarName + " sidecar use for repository " + repositoryId); } use.active--; + stoppedByShutdown = use.stopped; + if (stoppedByShutdown && use.active == 0) { + uses.remove(repositoryId, use); + } + } + if (stoppedByShutdown) { + pool.endUse(repositoryId); + return; } try { pool.endUse(repositoryId); @@ -82,17 +103,31 @@ final class SidecarRepositoryLease { } use.stopping = true; } + stop(repositoryId, use); + } + + private void stopDespiteActiveUses(String repositoryId, UseState use) { + synchronized (use) { + if (use.stopping || use.stopped) { + return; + } + use.stopping = true; + } + stop(repositoryId, use); + } + + private void stop(String repositoryId, UseState use) { boolean stopped = false; try { - if (pool.isTracked(repositoryId)) { - pool.stopContainerStrict(repositoryId); - } + // Not gated on isTracked, an unlocked read: the strict stop takes the key's start lock, so a + // start still building its container is waited for and what it registers is stopped. + pool.stopContainerStrict(repositoryId); stopped = true; } finally { synchronized (use) { use.stopped = stopped; use.stopping = false; - if (stopped) { + if (stopped && use.active == 0) { uses.remove(repositoryId, use); } } @@ -101,12 +136,25 @@ final class SidecarRepositoryLease { void stopManagedContainers() { RuntimeException[] failure = new RuntimeException[1]; + boolean force = shuttingDown; uses.forEach((id, use) -> { + int active; synchronized (use) { use.releasing = true; + active = use.active; } try { - stopIfUnused(id, use); + if (active != 0 && force) { + LOG.warnv("Stopping the {0} sidecar for repository {1} at shutdown with {2} use(s) still active.", + sidecarName, id, active); + stopDespiteActiveUses(id, use); + } else { + if (active != 0) { + LOG.warnv("Leaving the {0} sidecar for repository {1} running: {2} use(s) still active. " + + "It stops when the last one ends.", sidecarName, id, active); + } + stopIfUnused(id, use); + } } catch (RuntimeException e) { if (failure[0] == null) { failure[0] = e; diff --git a/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java index 5bb6af7445..46b307571f 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/VerdaccioSidecarManager.java @@ -174,6 +174,11 @@ public class VerdaccioSidecarManager implements ContainerTeardown { RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, backoffMillis); } + @Override + public void beginShutdown() { + lease.beginShutdown(); + } + @Override public void stopManagedContainers() { lease.stopManagedContainers(); diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java index 59912808fd..6b6cf2012a 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java @@ -238,7 +238,7 @@ class EmulatorLifecycleTest { void preparesContainerOwnersBeforeRetiringSharedCredentials() { ContainerTeardown first = Mockito.mock(ContainerTeardown.class); ContainerTeardown second = Mockito.mock(ContainerTeardown.class); - when(containerTeardowns.iterator()).thenReturn(List.of(first, second).iterator()); + when(containerTeardowns.iterator()).thenAnswer(ignored -> List.of(first, second).iterator()); when(ecsTaskRoleCredentialsConfig.enabled()).thenReturn(true); emulatorLifecycle.onStop(new ShutdownEvent()); @@ -255,6 +255,23 @@ class EmulatorLifecycleTest { verify(second).beginTeardown(); } + /** A lease owner learns the teardown is a shutdown before any teardown is prepared or drained. */ + @Test + void marksTheShutdownOnEveryContainerOwnerBeforePreparingAny() { + ContainerTeardown first = Mockito.mock(ContainerTeardown.class); + ContainerTeardown second = Mockito.mock(ContainerTeardown.class); + when(containerTeardowns.iterator()).thenAnswer(ignored -> List.of(first, second).iterator()); + + emulatorLifecycle.onStop(new ShutdownEvent()); + + InOrder order = Mockito.inOrder(first, second); + order.verify(first).beginShutdown(); + order.verify(second).beginShutdown(); + order.verify(first).beginTeardown(); + order.verify(second).beginTeardown(); + order.verify(first).stopManagedContainers(); + } + private void stubStorageConfig() { when(config.storage()).thenReturn(storageConfig); when(storageConfig.mode()).thenReturn("in-memory"); diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java index 8b840e5db2..6c3656fc7d 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDataPlaneTest.java @@ -350,6 +350,38 @@ class CodeArtifactNpmDataPlaneTest { assertEquals(true, upstreamReceivedPut.get()); } + /** + * The forwarded publish adds a routing-context end handler, which replaces any handler set on + * the response itself. The request's own release must survive that, or the repository keeps an + * active sidecar use forever and its Verdaccio container outlives DeleteRepository, reset and + * shutdown. + */ + @Test + void aForwardedPublishEndsItsSidecarUse() throws Exception { + upstream = vertx.createHttpServer() + .requestHandler(request -> request.response().setStatusCode(201).end()) + .listen(0, "127.0.0.1") + .toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + + CodeArtifactService service = mock(CodeArtifactService.class); + when(service.resolveAuthorizationToken("good-token", DOMAIN)) + .thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1"))); + when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY)) + .thenReturn(NPM_REPOSITORY_ID); + VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class); + when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString())) + .thenReturn("http://127.0.0.1:" + upstream.actualPort()); + startDataPlane(service, verdaccioClient); + + HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token", + npmPublishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", + "fresh bytes".getBytes(StandardCharsets.UTF_8))); + + assertEquals(201, response.statusCode()); + verify(verdaccioClient).beginUse(NPM_REPOSITORY_ID); + verify(verdaccioClient, timeout(2000)).endUse(NPM_REPOSITORY_ID); + } + /** * Qodo review finding: a real npm publish that republishes a coordinate an earlier * updatePackageVersionsStatus/disposePackageVersions call left Archived or Disposed must not diff --git a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDockerNightlyIntegrationTest.java index 390cd1e11d..68cf7d804e 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/CodeArtifactNpmDockerNightlyIntegrationTest.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.Base64; import java.util.List; import java.util.Map; @@ -34,6 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static io.floci.aws.testing.CodeArtifactRequests.npmPublishEnvelope; import static io.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration; import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -90,6 +92,31 @@ class CodeArtifactNpmDockerNightlyIntegrationTest { expectedTarballBytes = Base64.getDecoder().decode(base64Tarball); } + @Test + @Order(Integer.MAX_VALUE) + void deleteDomainsAndRepositories() { + String westAuth = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-west-2/codeartifact/aws4_request"; + String otherAccountAuth = "AWS4-HMAC-SHA256 Credential=111122223333/20260904/us-east-1/codeartifact/aws4_request"; + deleteDomain(AUTH, DOMAIN); + deleteDomain(AUTH, "other-npm-token-domain"); + deleteDomain(westAuth, "npm-sidecar-non-default-region-domain"); + deleteDomain(otherAccountAuth, "npm-sidecar-cross-account-domain"); + } + + private static void deleteDomain(String auth, String domain) { + List repositories = given().contentType("application/json").header("Authorization", auth) + .body("{}") + .post("/v1/domain/repositories?domain=" + domain) + .then().statusCode(200) + .extract().jsonPath().getList("repositories.name", String.class); + for (String repository : repositories) { + given().header("Authorization", auth) + .delete("/v1/repository?domain=" + domain + "&repository=" + repository) + .then().statusCode(200); + } + given().header("Authorization", auth).delete("/v1/domain?domain=" + domain).then().statusCode(200); + } + @Test @Order(0) void createDomainRepositoryAndAuthorizationToken() { @@ -266,7 +293,8 @@ class CodeArtifactNpmDockerNightlyIntegrationTest { @Test @Order(7) - void recreatingASameNamedRepositoryDoesNotInheritThePreviousOnesPackages() { + void recreatingASameNamedRepositoryDoesNotInheritThePreviousOnesPackages() throws Exception { + int baseline = runningVerdaccioTestContainerCount(); given().contentType("application/json").header("Authorization", AUTH).body("{}") .post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name") .then().statusCode(200); @@ -274,10 +302,15 @@ class CodeArtifactNpmDockerNightlyIntegrationTest { .body(publishFixture) .put("/codeartifact/npm/" + DOMAIN + "/reused-name/" + PACKAGE_NAME) .then().statusCode(anyOf201Or200()); + assertEquals(baseline + 1, runningVerdaccioTestContainerCount()); given().header("Authorization", AUTH) .delete("/v1/repository?domain=" + DOMAIN + "&repository=reused-name") .then().statusCode(200); + // A forwarded publish once left its sidecar use open, so the deleted repository's + // container kept running through reset and shutdown. + await().atMost(Duration.ofSeconds(10)) + .until(() -> runningVerdaccioTestContainerCount() == baseline); given().contentType("application/json").header("Authorization", AUTH).body("{}") .post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name") .then().statusCode(200); diff --git a/src/test/java/io/floci/aws/services/codeartifact/SidecarRepositoryLeaseTest.java b/src/test/java/io/floci/aws/services/codeartifact/SidecarRepositoryLeaseTest.java index e41762d8c3..75ef5956c1 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/SidecarRepositoryLeaseTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/SidecarRepositoryLeaseTest.java @@ -10,10 +10,15 @@ import org.junit.jupiter.api.parallel.ResourceLock; import java.io.IOException; import java.net.InetSocketAddress; +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -32,6 +37,111 @@ class SidecarRepositoryLeaseTest { verifyRetirement(true); } + @Test + void shutdownStopsAContainerWithActiveUsesAndALateEndUseIsANoOp() throws IOException { + HttpServer server = server(new AtomicBoolean()); + try { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + PerKeyContainerPool pool = new PerKeyContainerPool(lifecycle, "/health"); + SidecarRepositoryLease lease = new SidecarRepositoryLease("test", pool); + lease.registerRepository("repository"); + lease.beginUse("repository"); + pool.ensureReady("repository", () -> new PerKeyContainerPool.StartedContainer("container", url(server))); + + lease.beginShutdown(); + lease.stopManagedContainers(); + verify(lifecycle).stopAndRemoveStrict("container", null); + assertThrows(IllegalStateException.class, () -> lease.beginUse("repository")); + + lease.endUse("repository"); + lease.stopManagedContainers(); + verifyNoMoreInteractions(lifecycle); + } finally { + server.stop(0); + } + } + + /** + * A use admitted before shutdown can still reach the pool after the shutdown stop and its final + * sweep, an npm publish still receiving its body say. A container started then would outlive + * Floci, since the use's own end skips a lease the shutdown already stopped. + */ + @Test + void aUseAdmittedBeforeShutdownStartsNoContainerAfterTheShutdownStop() { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + PerKeyContainerPool pool = new PerKeyContainerPool(lifecycle, "/health"); + SidecarRepositoryLease lease = new SidecarRepositoryLease("test", pool); + lease.registerRepository("repository"); + lease.beginUse("repository"); + + lease.beginShutdown(); + lease.stopManagedContainers(); + AtomicBoolean started = new AtomicBoolean(); + assertThrows(IllegalStateException.class, () -> pool.ensureReady("repository", () -> { + started.set(true); + return new PerKeyContainerPool.StartedContainer("late", "http://127.0.0.1:1"); + })); + + assertFalse(started.get()); + lease.endUse("repository"); + verifyNoInteractions(lifecycle); + } + + /** + * A start that passed the pool's refusal check before shutdown can still be building its container + * when the shutdown stop runs. The stop must wait for it and stop what it registers: the final sweep + * skips a key the lease still tracks, and the use's own end skips a lease already stopped. + */ + @Test + void theShutdownStopWaitsForAStartInFlightAndStopsTheContainerItRegisters() throws Exception { + HttpServer server = server(new AtomicBoolean()); + try { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + PerKeyContainerPool pool = new PerKeyContainerPool(lifecycle, "/health"); + SidecarRepositoryLease lease = new SidecarRepositoryLease("test", pool); + lease.registerRepository("repository"); + lease.beginUse("repository"); + CountDownLatch building = new CountDownLatch(1); + CountDownLatch built = new CountDownLatch(1); + Thread start = Thread.ofVirtual().start(() -> pool.ensureReady("repository", () -> { + building.countDown(); + awaitQuietly(built); + return new PerKeyContainerPool.StartedContainer("in-flight", url(server)); + })); + assertTrue(building.await(5, TimeUnit.SECONDS)); + + lease.beginShutdown(); + Thread shutdown = Thread.ofPlatform().daemon().start(lease::stopManagedContainers); + awaitBlocked(shutdown); + built.countDown(); + start.join(Duration.ofSeconds(10)); + shutdown.join(Duration.ofSeconds(10)); + + verify(lifecycle).stopAndRemoveStrict("in-flight", null); + lease.endUse("repository"); + } finally { + server.stop(0); + } + } + + /** Waits for {@code thread} to block on a monitor, the key's start lock the in-flight start holds. */ + private static void awaitBlocked(Thread thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (thread.getState() != Thread.State.BLOCKED && thread.isAlive() && System.nanoTime() < deadline) { + Thread.sleep(5); + } + assertEquals(Thread.State.BLOCKED, thread.getState(), + "the shutdown stop should wait on the start lock of the start still building its container"); + } + + private static void awaitQuietly(CountDownLatch latch) { + try { + latch.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + private void verifyRetirement(boolean reset) throws IOException { AtomicBoolean unhealthy = new AtomicBoolean(); HttpServer previous = server(unhealthy);