mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(codeartifact): retain unhealthy sidecars during active requests (#8692)
* fix(codeartifact): retain unhealthy sidecars during active requests * fix(codeartifact): drain retired sidecar cleanup after failures * fix(codeartifact): keep replacement sidecar names distinct * fix(codeartifact): keep repository admission independent of startup * fix(codeartifact): reclaim untracked repository sidecars * fix(codeartifact): share run-labelled container cleanup
This commit is contained in:
1 parent
b2f550e6be
commit
07f6dea386
22 files changed
+832
-33
No files matched your search
@@ -11,6 +11,7 @@ import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -20,9 +21,13 @@ 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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
@@ -43,6 +48,122 @@ class PerKeyContainerPoolTest {
|
||||
fakeContainers.forEach(server -> server.stop(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastUseAttemptsEveryRetirementAndRetriesOnlyFailedRemoval() throws IOException {
|
||||
prepareTwoRetiredContainers();
|
||||
IllegalStateException failedRemoval = new IllegalStateException("first removal failed");
|
||||
doThrow(failedRemoval).doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict("retired-first", null);
|
||||
|
||||
assertSame(failedRemoval, assertThrows(IllegalStateException.class, () -> pool.endUse("key-1")));
|
||||
verify(lifecycleManager).stopAndRemoveStrict("retired-second", null);
|
||||
pool.stopContainerStrict("key-1");
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("retired-first", null);
|
||||
verify(lifecycleManager).stopAndRemoveStrict("current", null);
|
||||
verifyNoMoreInteractions(lifecycleManager);
|
||||
assertFalse(pool.isTracked("key-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void strictTeardownAttemptsRetiredAndCurrentContainersBeforeReportingFailures() throws IOException {
|
||||
prepareTwoRetiredContainers();
|
||||
IllegalStateException first = new IllegalStateException("first removal failed");
|
||||
IllegalStateException second = new IllegalStateException("second removal failed");
|
||||
IllegalStateException current = new IllegalStateException("current removal failed");
|
||||
doThrow(first).doNothing().when(lifecycleManager).stopAndRemoveStrict("retired-first", null);
|
||||
doThrow(second).doNothing().when(lifecycleManager).stopAndRemoveStrict("retired-second", null);
|
||||
doThrow(current).doNothing().when(lifecycleManager).stopAndRemoveStrict("current", null);
|
||||
|
||||
assertSame(first, assertThrows(IllegalStateException.class, () -> pool.stopContainerStrict("key-1")));
|
||||
assertEquals(List.of(second, current), List.of(first.getSuppressed()));
|
||||
assertTrue(pool.isTracked("key-1"));
|
||||
pool.stopAllStrictExcept(Set.of());
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("retired-first", null);
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("retired-second", null);
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("current", null);
|
||||
verifyNoMoreInteractions(lifecycleManager);
|
||||
assertFalse(pool.isTracked("key-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bestEffortTeardownRetainsFailedRetirementsForStrictRetry() throws IOException {
|
||||
prepareTwoRetiredContainers();
|
||||
doThrow(new IllegalStateException("remove failed")).doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict("retired-first", null);
|
||||
|
||||
pool.stopAll();
|
||||
verify(lifecycleManager).stopAndRemoveStrict("retired-second", null);
|
||||
verify(lifecycleManager).stopAndRemove("current", null);
|
||||
assertTrue(pool.isTracked("key-1"));
|
||||
pool.stopAllStrictExcept(Set.of());
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("retired-first", null);
|
||||
verifyNoMoreInteractions(lifecycleManager);
|
||||
assertFalse(pool.isTracked("key-1"));
|
||||
}
|
||||
|
||||
private void prepareTwoRetiredContainers() throws IOException {
|
||||
pool.beginUse("key-1");
|
||||
String firstUrl = startFakePing(200);
|
||||
pool.ensureReady("key-1", () -> new StartedContainer("retired-first", firstUrl));
|
||||
fakeContainers.forEach(server -> server.stop(0));
|
||||
String secondUrl = startFakePing(200);
|
||||
pool.ensureReady("key-1", () -> new StartedContainer("retired-second", secondUrl));
|
||||
fakeContainers.forEach(server -> server.stop(0));
|
||||
String currentUrl = startFakePing(200);
|
||||
pool.ensureReady("key-1", () -> new StartedContainer("current", currentUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unhealthyRetirementWaitsForEveryAdmittedUse() throws IOException {
|
||||
String staleUrl = startFakePing(200);
|
||||
pool.beginUse("key-1");
|
||||
pool.ensureReady("key-1", () -> new StartedContainer("stale-container", staleUrl));
|
||||
fakeContainers.forEach(server -> server.stop(0));
|
||||
pool.beginUse("key-1");
|
||||
String freshUrl = startFakePing(200);
|
||||
assertEquals(freshUrl, pool.ensureReady("key-1", () -> new StartedContainer("fresh-container", freshUrl)));
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
pool.endUse("key-1");
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
pool.endUse("key-1");
|
||||
verify(lifecycleManager).stopAndRemoveStrict("stale-container", null);
|
||||
verifyNoMoreInteractions(lifecycleManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedReplacementKeepsRetiredContainerOwnedUntilUseEnds() throws IOException {
|
||||
String staleUrl = startFakePing(200);
|
||||
pool.beginUse("key-1");
|
||||
pool.ensureReady("key-1", () -> new StartedContainer("stale-container", staleUrl));
|
||||
fakeContainers.forEach(server -> server.stop(0));
|
||||
assertThrows(IllegalStateException.class, () -> pool.ensureReady("key-1", () -> {
|
||||
throw new IllegalStateException("start failed");
|
||||
}));
|
||||
assertTrue(pool.isTracked("key-1"));
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
pool.endUse("key-1");
|
||||
verify(lifecycleManager).stopAndRemoveStrict("stale-container", null);
|
||||
assertTrue(!pool.isTracked("key-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRetirementIsRetriedByStrictTeardown() throws IOException {
|
||||
String staleUrl = startFakePing(200);
|
||||
pool.beginUse("key-1");
|
||||
pool.ensureReady("key-1", () -> new StartedContainer("stale-container", staleUrl));
|
||||
fakeContainers.forEach(server -> server.stop(0));
|
||||
assertThrows(IllegalStateException.class, () -> pool.ensureReady("key-1", () -> {
|
||||
throw new IllegalStateException("start failed");
|
||||
}));
|
||||
doThrow(new IllegalStateException("remove failed")).doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict("stale-container", null);
|
||||
assertThrows(IllegalStateException.class, () -> pool.endUse("key-1"));
|
||||
assertTrue(pool.isTracked("key-1"));
|
||||
pool.stopAllStrictExcept(Set.of());
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("stale-container", null);
|
||||
assertTrue(!pool.isTracked("key-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureReadyStartsAContainerOnFirstUse() throws IOException {
|
||||
String url = startFakePing(200);
|
||||
|
||||
@@ -486,7 +486,8 @@ class BagetterSidecarClientTest {
|
||||
}
|
||||
|
||||
private BagetterSidecarManager manager() {
|
||||
return new BagetterSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new BagetterSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
private BagetterSidecarClient client(BagetterSidecarManager manager) {
|
||||
|
||||
@@ -113,7 +113,8 @@ class BagetterSidecarManagerTest {
|
||||
}
|
||||
|
||||
private BagetterSidecarManager manager() {
|
||||
return new BagetterSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new BagetterSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.ListContainersCmd;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class CodeArtifactContainerRunsTest {
|
||||
|
||||
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
private final ListContainersCmd list = mock(ListContainersCmd.class);
|
||||
private final CodeArtifactContainerRuns producer;
|
||||
|
||||
CodeArtifactContainerRunsTest() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
when(lifecycle.getDockerClient()).thenReturn(docker);
|
||||
when(docker.listContainersCmd()).thenReturn(list);
|
||||
when(list.withShowAll(true)).thenReturn(list);
|
||||
when(list.withLabelFilter(anyMap())).thenReturn(list);
|
||||
producer = new CodeArtifactContainerRuns(lifecycle, config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retriesLeftoversWithoutRemovingAnyCurrentFormatOrAdmittedPredecessor() {
|
||||
RunLabelledContainers runs = producer.containers();
|
||||
assertSame(runs, producer.containers());
|
||||
List<Container> inventory = new ArrayList<>();
|
||||
for (String format : List.of("pypi", "npm", "nuget", "cargo")) {
|
||||
inventory.add(container(format, runs.labels()));
|
||||
inventory.add(container(format + "-predecessor", runs.labels()));
|
||||
}
|
||||
Map<String, String> old = new HashMap<>(runs.labels());
|
||||
old.put("io.floci.codeartifact.run", "previous-run");
|
||||
inventory.add(container("leftover", old));
|
||||
when(list.exec()).thenReturn(inventory);
|
||||
doThrow(new IllegalStateException("Docker unavailable")).doNothing()
|
||||
.when(lifecycle).removeIfExistsStrict("leftover", true);
|
||||
|
||||
runs.removeLeftovers();
|
||||
producer.containers().removeLeftovers();
|
||||
|
||||
verify(lifecycle, times(2)).removeIfExistsStrict("leftover", true);
|
||||
for (String format : List.of("pypi", "npm", "nuget", "cargo")) {
|
||||
verify(lifecycle, never()).removeIfExistsStrict(format, true);
|
||||
verify(lifecycle, never()).removeIfExistsStrict(format + "-predecessor", true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void inventoryFailureIsRetriedAndForeignOwnerAndServiceArePreserved() {
|
||||
RunLabelledContainers runs = producer.containers();
|
||||
Map<String, String> foreign = new HashMap<>(runs.labels());
|
||||
foreign.put(ContainerStorageHelper.OWNER_LABEL, "another-deployment");
|
||||
foreign.put("io.floci.codeartifact.run", "previous-run");
|
||||
Container foreignContainer = container("foreign", foreign);
|
||||
Container otherService = container("other-service", foreign);
|
||||
Map<String, String> other = new HashMap<>(runs.labels());
|
||||
other.put(ContainerStorageHelper.SERVICE_LABEL, "batch");
|
||||
other.put("io.floci.codeartifact.run", "previous-run");
|
||||
when(otherService.getLabels()).thenReturn(other);
|
||||
when(list.exec()).thenThrow(new IllegalStateException("Docker unavailable"))
|
||||
.thenReturn(List.of(foreignContainer, otherService));
|
||||
|
||||
runs.removeLeftovers();
|
||||
runs.removeLeftovers();
|
||||
|
||||
verify(lifecycle, never()).removeIfExistsStrict("foreign", true);
|
||||
verify(lifecycle, never()).removeIfExistsStrict("other-service", true);
|
||||
verify(list, atLeast(2)).withShowAll(true);
|
||||
}
|
||||
|
||||
private static Container container(String id, Map<String, String> runLabels) {
|
||||
Container container = mock(Container.class);
|
||||
when(container.getId()).thenReturn(id);
|
||||
Map<String, String> labels = new HashMap<>(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"codeartifact", id, null, null));
|
||||
labels.putAll(runLabels);
|
||||
when(container.getLabels()).thenReturn(labels);
|
||||
return container;
|
||||
}
|
||||
}
|
||||
@@ -1324,7 +1324,8 @@ class CodeArtifactNpmDataPlaneTest {
|
||||
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
|
||||
.thenReturn(NPM_REPOSITORY_ID);
|
||||
VerdaccioSidecarManager leases = new VerdaccioSidecarManager(mock(ContainerBuilder.class),
|
||||
mock(ContainerLifecycleManager.class), mock(EmulatorConfig.class));
|
||||
mock(ContainerLifecycleManager.class), mock(EmulatorConfig.class),
|
||||
new CodeArtifactContainerRuns(mock(ContainerLifecycleManager.class), mock(EmulatorConfig.class)).containers());
|
||||
leases.registerRepository(NPM_REPOSITORY_ID);
|
||||
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
|
||||
doAnswer(call -> {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationToken;
|
||||
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
|
||||
@@ -34,6 +37,7 @@ import org.mockito.InOrder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
@@ -52,8 +56,10 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
@@ -140,6 +146,86 @@ class CodeArtifactServiceTest {
|
||||
List.of(verdaccioClient, reposiliteClient, pypiserverClient, bagetterClient)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void repositoryAdmissionDoesNotHoldServiceMonitorDuringStartup(boolean failStartup) throws Exception {
|
||||
service.createDomain(REGION, "admission", null, Map.of());
|
||||
service.createRepository(REGION, "admission", null, "repo", null, null, Map.of());
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
PerKeyContainerPool pool = new PerKeyContainerPool(lifecycle, "/health");
|
||||
SidecarRepositoryLease lease = new SidecarRepositoryLease("test", pool);
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch finishStartup = new CountDownLatch(1);
|
||||
CountDownLatch secondAdmission = new CountDownLatch(1);
|
||||
AtomicInteger admissions = new AtomicInteger();
|
||||
doAnswer(invocation -> {
|
||||
lease.registerRepository(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(pypiserverClient).registerRepository(anyString());
|
||||
doAnswer(invocation -> {
|
||||
if (admissions.incrementAndGet() == 2) {
|
||||
secondAdmission.countDown();
|
||||
}
|
||||
lease.beginUse(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(pypiserverClient).beginUse(anyString());
|
||||
String id = service.resolveContainerIdAndBeginUse(
|
||||
"pypi", REGION, "admission", null, "repo", pypiserverClient);
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/health", exchange -> {
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
String endpoint = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
try {
|
||||
Future<String> startup = executor.submit(() -> pool.ensureReady(id, () -> {
|
||||
started.countDown();
|
||||
try {
|
||||
assertTrue(finishStartup.await(10, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
if (failStartup) {
|
||||
throw new IllegalStateException("controlled startup failure");
|
||||
}
|
||||
return new PerKeyContainerPool.StartedContainer("owned-container", endpoint);
|
||||
}));
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
Future<String> admission = executor.submit(() -> service.resolveContainerIdAndBeginUse(
|
||||
"pypi", REGION, "admission", null, "repo", pypiserverClient));
|
||||
assertTrue(secondAdmission.await(5, TimeUnit.SECONDS));
|
||||
Future<DomainView> unrelated = executor.submit(() ->
|
||||
service.createDomain(REGION, "unrelated", null, Map.of()));
|
||||
assertDoesNotThrow(() -> unrelated.get(2, TimeUnit.SECONDS),
|
||||
"A same-repository admission must not hold the service monitor during startup");
|
||||
assertEquals(id, admission.get(2, TimeUnit.SECONDS));
|
||||
finishStartup.countDown();
|
||||
if (failStartup) {
|
||||
assertEquals("controlled startup failure", assertThrows(
|
||||
ExecutionException.class,
|
||||
() -> startup.get(5, TimeUnit.SECONDS)).getCause().getMessage());
|
||||
} else {
|
||||
assertEquals(endpoint, startup.get(5, TimeUnit.SECONDS));
|
||||
}
|
||||
lease.release(id);
|
||||
lease.endUse(id);
|
||||
verify(lifecycle, never()).stopAndRemoveStrict(anyString(), any());
|
||||
lease.endUse(id);
|
||||
if (!failStartup) {
|
||||
verify(lifecycle).stopAndRemoveStrict("owned-container", null);
|
||||
}
|
||||
} finally {
|
||||
finishStartup.countDown();
|
||||
}
|
||||
} finally {
|
||||
lease.stopManagedContainers();
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- domains
|
||||
|
||||
@Test
|
||||
|
||||
@@ -485,7 +485,8 @@ class KellnrSidecarClientTest {
|
||||
}
|
||||
|
||||
private KellnrSidecarManager manager() {
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
@@ -114,7 +114,8 @@ class KellnrSidecarManagerTest {
|
||||
}
|
||||
|
||||
private KellnrSidecarManager manager() {
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
@@ -708,7 +708,8 @@ class PypiserverSidecarClientTest {
|
||||
}
|
||||
|
||||
private PypiserverSidecarManager manager() {
|
||||
return new PypiserverSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new PypiserverSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
private PypiserverSidecarClient client(PypiserverSidecarManager manager) {
|
||||
|
||||
@@ -88,7 +88,8 @@ class PypiserverSidecarManagerTest {
|
||||
ContainerBuilder realBuilder = new ContainerBuilder(
|
||||
deepConfig, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class));
|
||||
when(lifecycleManager.startCreated(any(), any())).thenThrow(new IllegalStateException("no Docker here"));
|
||||
PypiserverSidecarManager manager = new PypiserverSidecarManager(realBuilder, lifecycleManager, deepConfig);
|
||||
PypiserverSidecarManager manager = new PypiserverSidecarManager(realBuilder, lifecycleManager, deepConfig,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, deepConfig).containers());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.ensureReady("pypi-repo-1", "http://localhost:4566"));
|
||||
|
||||
@@ -107,7 +108,8 @@ class PypiserverSidecarManagerTest {
|
||||
}
|
||||
|
||||
private PypiserverSidecarManager manager() {
|
||||
return new PypiserverSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new PypiserverSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.ListContainersCmd;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SidecarReplacementTest {
|
||||
|
||||
enum Format {
|
||||
PYPI, NPM, NUGET, CARGO
|
||||
}
|
||||
|
||||
private record Manager(BiFunction<String, String, String> ready, Consumer<String> register,
|
||||
Consumer<String> begin, Consumer<String> end, Runnable stop) {}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(Format.class)
|
||||
void actualStarterKeepsAnAdmittedPredecessorUntilItsUseEnds(Format format) throws Exception {
|
||||
AtomicBoolean healthy = new AtomicBoolean(true);
|
||||
HttpServer first = healthServer(healthy);
|
||||
HttpServer replacement = healthServer(new AtomicBoolean(true));
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().codeartifact().pypiImage()).thenReturn("pypi-test");
|
||||
when(config.services().codeartifact().npmImage()).thenReturn("npm-test");
|
||||
when(config.services().codeartifact().nugetImage()).thenReturn("nuget-test");
|
||||
when(config.services().codeartifact().cargoImage()).thenReturn("cargo-test");
|
||||
when(config.services().dockerNetwork()).thenReturn(Optional.empty());
|
||||
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
|
||||
when(config.docker().logMaxSize()).thenReturn("10m");
|
||||
when(config.docker().logMaxFile()).thenReturn("3");
|
||||
ContainerBuilder builder = new ContainerBuilder(
|
||||
config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class));
|
||||
Map<String, String> liveNames = new HashMap<>();
|
||||
Map<String, String> createdNames = new HashMap<>();
|
||||
String service = switch (format) {
|
||||
case PYPI -> "pypiserver";
|
||||
case NPM -> "verdaccio";
|
||||
case NUGET -> "bagetter";
|
||||
case CARGO -> "kellnr";
|
||||
};
|
||||
String baseName = ContainerStorageHelper.dockerName(config, "floci-" + service + "-repository");
|
||||
liveNames.put(baseName, "stale-fixed");
|
||||
liveNames.put(baseName + "-11111111-1111-1111-1111-111111111111", "stale-unique");
|
||||
liveNames.put(baseName + "-other-repository", "unrelated");
|
||||
liveNames.put(baseName + "-22222222-2222-2222-2222-222222222222", "foreign-namespace");
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ListContainersCmd list = mock(ListContainersCmd.class);
|
||||
when(lifecycle.getDockerClient()).thenReturn(docker);
|
||||
when(docker.listContainersCmd()).thenReturn(list);
|
||||
when(list.withShowAll(true)).thenReturn(list);
|
||||
when(list.withLabelFilter(any(Map.class))).thenReturn(list);
|
||||
Map<String, Map<String, String>> liveLabels = new HashMap<>();
|
||||
RunLabelledContainers runs = new CodeArtifactContainerRuns(lifecycle, config).containers();
|
||||
when(list.exec()).thenAnswer(invocation -> {
|
||||
List<Container> inventory = new ArrayList<>();
|
||||
liveNames.forEach((name, id) -> {
|
||||
Container container = mock(Container.class);
|
||||
when(container.getId()).thenReturn(id);
|
||||
when(container.getNames()).thenReturn(new String[]{"/" + name});
|
||||
Map<String, String> labels = new HashMap<>(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"codeartifact", "repository", null, null));
|
||||
labels.putAll(runs.labels());
|
||||
labels.put("io.floci.codeartifact.run", "previous-run");
|
||||
if (id.equals("foreign-namespace")) {
|
||||
labels.put(ContainerStorageHelper.OWNER_LABEL, "other");
|
||||
} else if (id.equals("unrelated")) {
|
||||
labels.put(ContainerStorageHelper.SERVICE_LABEL, "other-service");
|
||||
}
|
||||
labels.putAll(liveLabels.getOrDefault(id, Map.of()));
|
||||
when(container.getLabels()).thenReturn(labels);
|
||||
inventory.add(container);
|
||||
});
|
||||
return inventory;
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
liveNames.values().remove(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(lifecycle).removeIfExistsStrict(anyString(), eq(true));
|
||||
AtomicInteger created = new AtomicInteger();
|
||||
when(lifecycle.create(any())).thenAnswer(invocation -> {
|
||||
ContainerSpec spec = invocation.getArgument(0);
|
||||
assertEquals("codeartifact", spec.labels().get(ContainerStorageHelper.SERVICE_LABEL));
|
||||
assertEquals("repository", spec.labels().get(ContainerStorageHelper.RESOURCE_ID_LABEL));
|
||||
runs.labels().forEach((key, value) -> assertEquals(value, spec.labels().get(key)));
|
||||
String id = "container-" + created.incrementAndGet();
|
||||
assertFalse(liveNames.containsKey(spec.name()), "Docker cannot create a duplicate live name");
|
||||
liveNames.put(spec.name(), id);
|
||||
createdNames.put(id, spec.name());
|
||||
liveLabels.put(id, spec.labels());
|
||||
return id;
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
liveNames.remove(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(lifecycle).removeIfExists(anyString());
|
||||
doAnswer(invocation -> {
|
||||
liveNames.values().remove(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(lifecycle).stopAndRemoveStrict(anyString(), any());
|
||||
doAnswer(invocation -> {
|
||||
liveNames.values().remove(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(lifecycle).stopAndRemove(anyString(), any());
|
||||
when(lifecycle.startCreated(anyString(), any())).thenAnswer(invocation -> {
|
||||
String id = invocation.getArgument(0);
|
||||
int port = (id.equals("container-1") ? first : replacement).getAddress().getPort();
|
||||
EndpointInfo endpoint = new EndpointInfo("127.0.0.1", port);
|
||||
return new ContainerInfo(id, Map.of(8080, endpoint, 4873, endpoint, 8000, endpoint));
|
||||
});
|
||||
Manager manager = manager(format, builder, lifecycle, config, runs);
|
||||
boolean admitted = false;
|
||||
try {
|
||||
manager.register().accept("repository");
|
||||
manager.begin().accept("repository");
|
||||
admitted = true;
|
||||
String original = manager.ready().apply("repository", "http://localhost:4566");
|
||||
assertFalse(liveNames.containsValue("stale-fixed"), "Interrupted fixed-name start must be reclaimed");
|
||||
assertFalse(liveNames.containsValue("stale-unique"), "Interrupted UUID start must be reclaimed");
|
||||
assertTrue(liveNames.containsValue("unrelated"));
|
||||
assertTrue(liveNames.containsValue("foreign-namespace"));
|
||||
assertEquals(original, manager.ready().apply("repository", "http://localhost:4566"));
|
||||
assertEquals(1, created.get(), "Healthy reuse must not create a new container");
|
||||
healthy.set(false);
|
||||
String next = manager.ready().apply("repository", "http://localhost:4566");
|
||||
|
||||
assertNotEquals(original, next);
|
||||
assertTrue(liveNames.containsValue("container-1"),
|
||||
"The actual replacement starter must not remove the admitted predecessor by name");
|
||||
assertNotEquals(createdNames.get("container-1"), createdNames.get("container-2"));
|
||||
manager.end().accept("repository");
|
||||
admitted = false;
|
||||
assertFalse(liveNames.containsValue("container-1"));
|
||||
assertTrue(liveNames.containsValue("container-2"));
|
||||
} finally {
|
||||
try {
|
||||
if (admitted) {
|
||||
manager.end().accept("repository");
|
||||
}
|
||||
manager.stop().run();
|
||||
} finally {
|
||||
first.stop(0);
|
||||
replacement.stop(0);
|
||||
}
|
||||
}
|
||||
assertEquals(2, liveNames.size(), "Teardown must leave other repositories and namespaces alone");
|
||||
assertTrue(liveNames.containsValue("unrelated"));
|
||||
assertTrue(liveNames.containsValue("foreign-namespace"));
|
||||
}
|
||||
|
||||
private static HttpServer healthServer(AtomicBoolean healthy) throws Exception {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
exchange.sendResponseHeaders(healthy.get() ? 200 : 503, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
return server;
|
||||
}
|
||||
|
||||
private static Manager manager(Format format, ContainerBuilder builder,
|
||||
ContainerLifecycleManager lifecycle, EmulatorConfig config, RunLabelledContainers runs) {
|
||||
return switch (format) {
|
||||
case PYPI -> {
|
||||
PypiserverSidecarManager manager = new PypiserverSidecarManager(builder, lifecycle, config, runs);
|
||||
yield new Manager(manager::ensureReady, manager::registerRepository,
|
||||
manager::beginUse, manager::endUse, manager::stopManagedContainers);
|
||||
}
|
||||
case NPM -> {
|
||||
VerdaccioSidecarManager manager = spy(new VerdaccioSidecarManager(builder, lifecycle, config, runs));
|
||||
doNothing().when(manager).copyConfig(anyString(), anyLong());
|
||||
yield new Manager(manager::ensureReady, manager::registerRepository,
|
||||
manager::beginUse, manager::endUse, manager::stopManagedContainers);
|
||||
}
|
||||
case NUGET -> {
|
||||
BagetterSidecarManager manager = new BagetterSidecarManager(builder, lifecycle, config, runs);
|
||||
yield new Manager(manager::ensureReady, manager::registerRepository,
|
||||
manager::beginUse, manager::endUse, manager::stopManagedContainers);
|
||||
}
|
||||
case CARGO -> {
|
||||
KellnrSidecarManager manager = new KellnrSidecarManager(builder, lifecycle, config, runs);
|
||||
yield new Manager(manager::ensureReady, manager::registerRepository,
|
||||
manager::beginUse, manager::endUse, manager::stopManagedContainers);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
|
||||
class SidecarRepositoryLeaseTest {
|
||||
|
||||
@Test
|
||||
void unhealthyReplacementPreservesBothAdmittedUses() throws IOException {
|
||||
verifyRetirement(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetProtectsRetiredAndCurrentContainersUntilUsesFinish() throws IOException {
|
||||
verifyRetirement(true);
|
||||
}
|
||||
|
||||
private void verifyRetirement(boolean reset) throws IOException {
|
||||
AtomicBoolean unhealthy = new AtomicBoolean();
|
||||
HttpServer previous = server(unhealthy);
|
||||
HttpServer replacement = 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("previous", url(previous)));
|
||||
unhealthy.set(true);
|
||||
lease.beginUse("repository");
|
||||
assertEquals(url(replacement), pool.ensureReady("repository",
|
||||
() -> new PerKeyContainerPool.StartedContainer("replacement", url(replacement))));
|
||||
if (reset) {
|
||||
lease.stopManagedContainers();
|
||||
assertThrows(IllegalStateException.class, () -> lease.beginUse("repository"));
|
||||
}
|
||||
verifyNoInteractions(lifecycle);
|
||||
lease.endUse("repository");
|
||||
verifyNoInteractions(lifecycle);
|
||||
lease.endUse("repository");
|
||||
verify(lifecycle).stopAndRemoveStrict("previous", null);
|
||||
if (reset) {
|
||||
verify(lifecycle).stopAndRemoveStrict("replacement", null);
|
||||
}
|
||||
verifyNoMoreInteractions(lifecycle);
|
||||
} finally {
|
||||
previous.stop(0);
|
||||
replacement.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
private HttpServer server(AtomicBoolean unhealthy) throws IOException {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/health", exchange -> {
|
||||
try (exchange) {
|
||||
exchange.sendResponseHeaders(unhealthy.get() ? 503 : 200, -1);
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
return server;
|
||||
}
|
||||
|
||||
private String url(HttpServer server) {
|
||||
return "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,8 @@ class VerdaccioConfigRetryTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = new VerdaccioSidecarManager(mock(ContainerBuilder.class), lifecycle, mock(EmulatorConfig.class));
|
||||
manager = new VerdaccioSidecarManager(mock(ContainerBuilder.class), lifecycle, mock(EmulatorConfig.class),
|
||||
new CodeArtifactContainerRuns(lifecycle, mock(EmulatorConfig.class)).containers());
|
||||
when(lifecycle.getDockerClient()).thenReturn(docker);
|
||||
}
|
||||
|
||||
@@ -102,7 +103,8 @@ class VerdaccioConfigRetryTest {
|
||||
when(config.docker().logMaxFile()).thenReturn("3");
|
||||
ContainerBuilder builder = new ContainerBuilder(config,
|
||||
mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class));
|
||||
manager = new VerdaccioSidecarManager(builder, lifecycle, config);
|
||||
manager = new VerdaccioSidecarManager(builder, lifecycle, config,
|
||||
new CodeArtifactContainerRuns(lifecycle, config).containers());
|
||||
when(lifecycle.create(any(ContainerSpec.class))).thenReturn("container");
|
||||
uploads.failures = 1;
|
||||
uploads.failure = new NotFoundException("container missing");
|
||||
|
||||
@@ -481,7 +481,8 @@ class VerdaccioSidecarClientTest {
|
||||
}
|
||||
|
||||
private VerdaccioSidecarManager manager() {
|
||||
return new VerdaccioSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new VerdaccioSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
private VerdaccioSidecarClient client(VerdaccioSidecarManager manager) {
|
||||
|
||||
@@ -142,7 +142,8 @@ class VerdaccioSidecarManagerTest {
|
||||
when(remove.withForce(true)).thenReturn(remove);
|
||||
doThrow(new IllegalStateException("Docker removal failed")).doNothing().when(remove).exec();
|
||||
ContainerLifecycleManager realLifecycle = new ContainerLifecycleManager(docker, null, null, null);
|
||||
VerdaccioSidecarManager manager = new VerdaccioSidecarManager(containerBuilder, realLifecycle, config);
|
||||
VerdaccioSidecarManager manager = new VerdaccioSidecarManager(containerBuilder, realLifecycle, config,
|
||||
new CodeArtifactContainerRuns(realLifecycle, config).containers());
|
||||
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1", "http://127.0.0.1:1");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.release("npm-repo-1"));
|
||||
@@ -237,7 +238,8 @@ class VerdaccioSidecarManagerTest {
|
||||
}
|
||||
|
||||
private VerdaccioSidecarManager manager() {
|
||||
return new VerdaccioSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
return new VerdaccioSidecarManager(containerBuilder, lifecycleManager, config,
|
||||
new CodeArtifactContainerRuns(lifecycleManager, config).containers());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
Reference in new issue
Block a user