fix(codeartifact): stop sidecar containers on state reset and nuke (#4411)

A state reset wiped every CodeArtifact repository record without
stopping the Docker containers backing them. Reposilite's one shared
instance kept running with nothing left to reconcile it against;
Verdaccio, one container per repository, leaked one per repository
that existed at reset time, every reset.

Neither manager implemented ContainerTeardown, the interface
ContainerTeardowns.stopAll already runs on both /state/reset and
/state/nuke, and at process shutdown in place of an ad hoc @Observes
ShutdownEvent handler. Implementing it on both replaces their existing
onStop methods with stopManagedContainers(), the same shutdown
behavior now also reached from a reset.

A repository-record walk in CodeArtifactService.beforeReset() was
added as an earlier attempt at this, then removed once ContainerTeardown
turned out to be the actual, already-established mechanism: it is
driven by what each pool is really tracking rather than by
still-existing repository metadata, so it does not miss a container a
delete raced against, and it is what the rest of the codebase already
relies on for the exact same problem (Batch, CodeBuild, SageMaker,
Timestream for InfluxDB).

Verified live: starting a repository's Verdaccio container, calling
/state/reset, and confirming via a real Docker query that the
container is gone, not just that some Java method ran.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-25 17:39:03 -05:00
1 parent 8f5ba2b2a8
commit 61e7f07fb6
9 files changed
+231 -56

No files matched your search

@@ -20,6 +20,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
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;
@@ -148,6 +149,40 @@ class PerKeyContainerPoolTest {
verify(lifecycleManager).stopAndRemove("container-1", null);
}
@Test
void ensureReadyStopsItsOwnContainerWhenStopAllRunsWhileItWasStarting() throws Exception {
CountDownLatch starterEntered = new CountDownLatch(1);
CountDownLatch releaseStarter = new CountDownLatch(1);
ExecutorService pool2 = Executors.newFixedThreadPool(2);
try {
Future<?> startFuture = pool2.submit(() -> assertThrows(IllegalStateException.class,
() -> pool.ensureReady("key-1", () -> {
starterEntered.countDown();
try {
assertTrue(releaseStarter.await(5, TimeUnit.SECONDS));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new StartedContainer("container-1", "http://127.0.0.1:1");
})));
// stopAll() has no single key to lock, so it cannot serialize against an in-flight
// start the way stopContainer() does: this is what forces the exact race that would
// otherwise let the container this start commits to outlive the reset that was
// supposed to remove it.
assertTrue(starterEntered.await(5, TimeUnit.SECONDS));
pool.stopAll();
releaseStarter.countDown();
startFuture.get(5, TimeUnit.SECONDS);
} finally {
pool2.shutdown();
assertTrue(pool2.awaitTermination(30, TimeUnit.SECONDS));
}
verify(lifecycleManager).stopAndRemove("container-1", null);
}
@Test
void stopAllStopsEveryTrackedContainerAndForgetsThem() throws IOException {
String urlA = startFakePing(200);
@@ -276,6 +276,63 @@ class CodeArtifactNpmDockerIntegrationTest {
.then().statusCode(200);
}
/**
* Proves the actual mechanism, not just that {@code VerdaccioSidecarManager} has a method
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on
* {@code /state/reset}, and this is what stops a live container, not the repository-record
* walk {@code CodeArtifactService} used to do (which only knew about repositories that still
* existed in storage).
*
* <p>Ordered before every other test, not after: a reset stops every container this process's
* pool is tracking, not just the one this test starts, so running it after the other tests
* have already started their own containers would make this test's own reset sweep those up
* too and fail the baseline comparison below for a reason that has nothing to do with whether
* reset-repo's own container was actually stopped. Running first means the only baseline is
* whatever this namespace already had running before this test class touched it at all (e.g.
* a container an earlier interrupted run never got the chance to clean up), which this reset
* cannot be expected to touch either. Self-contained (its own domain, repository and token)
* since the class's shared domain/token fields are not populated until {@code Order(0)} runs,
* and a state reset wipes them regardless, so every later test must not depend on anything
* this one touched.
*/
@Test
@Order(-1)
void stateResetStopsTheRepositorysVerdaccioContainer() throws Exception {
int baseline = runningVerdaccioTestContainerCount();
String domain = "npm-sidecar-reset-domain";
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=" + domain)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + domain + "&repository=reset-repo")
.then().statusCode(200);
String token = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + domain)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
// A 404 read still starts the container; only a missing token skips it.
given().header("Authorization", "Bearer " + token)
.get("/codeartifact/npm/" + domain + "/reset-repo/does-not-exist")
.then().statusCode(404);
assertEquals(baseline + 1, runningVerdaccioTestContainerCount(),
"expected reset-repo's Verdaccio container to be running before reset");
given().post("/_floci/state/reset").then().statusCode(200);
assertEquals(baseline, runningVerdaccioTestContainerCount(),
"state reset must stop reset-repo's Verdaccio container");
}
private static int runningVerdaccioTestContainerCount() throws IOException, InterruptedException {
Process process = new ProcessBuilder("docker", "ps", "-q",
"--filter", "name=floci-aws-codeartifact-npm-test-verdaccio-")
.redirectErrorStream(true).start();
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
process.waitFor();
return output.isBlank() ? 0 : (int) output.lines().count();
}
private static Matcher<Integer> anyOf201Or200() {
return anyOf(is(200), is(201));
}
@@ -394,37 +394,6 @@ class CodeArtifactServiceTest {
verify(reposiliteClient).release(created.getSidecarContainerIds().get("maven"));
}
@Test
void beforeResetReleasesEveryRepositorysSidecarStorageAcrossEveryAccount() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository first = service.createRepository(REGION, "dom", null, "repo-1", null, null, Map.of());
CodeArtifactRepository second = service.createRepository(REGION, "dom", null, "repo-2", null, null, Map.of());
service.beforeReset();
verify(verdaccioManager).release(first.getSidecarContainerIds().get("npm"));
verify(reposiliteClient).release(first.getSidecarContainerIds().get("maven"));
verify(verdaccioManager).release(second.getSidecarContainerIds().get("npm"));
verify(reposiliteClient).release(second.getSidecarContainerIds().get("maven"));
}
@Test
void beforeResetToleratesASidecarReleaseFailureAndStillReleasesTheRest() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository first = service.createRepository(REGION, "dom", null, "repo-1", null, null, Map.of());
CodeArtifactRepository second = service.createRepository(REGION, "dom", null, "repo-2", null, null, Map.of());
doThrow(new IllegalStateException("Reposilite unreachable")).when(reposiliteClient)
.release(first.getSidecarContainerIds().get("maven"));
// A reset must not abort partway through and leave later repositories' containers running
// just because one repository's release failed.
service.beforeReset();
verify(reposiliteClient).release(second.getSidecarContainerIds().get("maven"));
verify(verdaccioManager).release(first.getSidecarContainerIds().get("npm"));
verify(verdaccioManager).release(second.getSidecarContainerIds().get("npm"));
}
@Test
void deleteRepositorySucceedsEvenWhenOneFormatsSidecarReleaseFails() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -106,6 +106,25 @@ class ReposiliteSidecarManagerTest {
verifyNoInteractions(containerBuilder, lifecycleManager);
}
@Test
void stopManagedContainersStopsAndForgetsTheManagedContainer() throws Exception {
ReposiliteSidecarManager manager = manager();
setField(manager, "containerId", "running-reposilite");
manager.stopManagedContainers();
verify(lifecycleManager).stopAndRemove("running-reposilite", null);
}
@Test
void stopManagedContainersIsANoOpWhenNothingWasEverStarted() {
ReposiliteSidecarManager manager = manager();
manager.stopManagedContainers();
verifyNoInteractions(lifecycleManager);
}
private ReposiliteSidecarManager manager() {
return new ReposiliteSidecarManager(containerBuilder, lifecycleManager, config, "unused-managed-secret");
}
@@ -0,0 +1,79 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* {@link VerdaccioSidecarManager#stopManagedContainers()} is a thin delegation to
* {@link PerKeyContainerPool#stopAll()}, whose own behavior (stop every tracked container,
* tolerate a failure in one, forget them all) is already covered by
* {@code PerKeyContainerPoolTest}. What matters here, and what a Docker-gated integration test
* cannot isolate from every other moving part, is the wiring: that the manager genuinely
* implements {@link ContainerTeardown} (so {@code ContainerTeardowns.stopAll} finds it on
* {@code /state/reset}, {@code /state/nuke}, and process shutdown) and that it hands the pool
* container ids it actually started rather than something it invented. A container is seeded
* directly into the pool's tracking map by reflection, the same way
* {@code ReposiliteSidecarManagerTest} seeds a stale endpoint, so this needs no Docker daemon.
*/
class VerdaccioSidecarManagerTest {
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
private final EmulatorConfig config = mock(EmulatorConfig.class);
@Test
void implementsContainerTeardownSoStateResetAndNukeCanFindIt() {
assertInstanceOf(ContainerTeardown.class, manager());
}
@Test
void stopManagedContainersStopsEveryContainerThePoolIsTracking() throws Exception {
VerdaccioSidecarManager manager = manager();
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1");
seedPooledContainer(manager, "npm-repo-2", "tracked-verdaccio-2");
manager.stopManagedContainers();
verify(lifecycleManager).stopAndRemove("tracked-verdaccio-1", null);
verify(lifecycleManager).stopAndRemove("tracked-verdaccio-2", null);
}
@Test
void stopManagedContainersIsANoOpWhenNothingWasEverStarted() {
VerdaccioSidecarManager manager = manager();
manager.stopManagedContainers();
verifyNoInteractions(lifecycleManager);
}
private VerdaccioSidecarManager manager() {
return new VerdaccioSidecarManager(containerBuilder, lifecycleManager, config);
}
@SuppressWarnings("unchecked")
private static void seedPooledContainer(VerdaccioSidecarManager manager, String key, String containerId)
throws Exception {
Field poolField = VerdaccioSidecarManager.class.getDeclaredField("pool");
poolField.setAccessible(true);
PerKeyContainerPool pool = (PerKeyContainerPool) poolField.get(manager);
Field containersField = PerKeyContainerPool.class.getDeclaredField("containers");
containersField.setAccessible(true);
ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer> containers =
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, "http://127.0.0.1:1"));
}
}