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
@@ -2,9 +2,11 @@ package io.floci.aws.core.common.docker;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
@@ -46,6 +48,68 @@ public class PerKeyContainerPool {
|
||||
* nothing left able to ever stop it again.
|
||||
*/
|
||||
private final AtomicLong generation = new AtomicLong();
|
||||
private final ConcurrentHashMap<String, Integer> activeUses = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, List<StartedContainer>> retiredContainers = new ConcurrentHashMap<>();
|
||||
|
||||
/** Protects every container observed during an admitted use, including an unhealthy predecessor. */
|
||||
public void beginUse(String key) {
|
||||
activeUses.merge(key, 1, Integer::sum);
|
||||
}
|
||||
|
||||
/** Releases a use and removes retired containers once the last admitted use has finished. */
|
||||
public void endUse(String key) {
|
||||
Object lock = startLocks.computeIfAbsent(key, k -> new Object());
|
||||
synchronized (lock) {
|
||||
AtomicBoolean drained = new AtomicBoolean();
|
||||
activeUses.compute(key, (k, active) -> {
|
||||
if (active == null) {
|
||||
throw new IllegalStateException("No active container use for key " + key);
|
||||
}
|
||||
drained.set(active == 1);
|
||||
return active == 1 ? null : active - 1;
|
||||
});
|
||||
if (drained.get()) {
|
||||
stopRetired(key, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void stopRetired(String key, boolean strict) {
|
||||
List<StartedContainer> retired = retiredContainers.get(key);
|
||||
if (retired == null) {
|
||||
return;
|
||||
}
|
||||
RuntimeException failure = null;
|
||||
for (StartedContainer container : List.copyOf(retired)) {
|
||||
try {
|
||||
lifecycleManager.stopAndRemoveStrict(container.containerId(), null);
|
||||
retired.remove(container);
|
||||
} catch (RuntimeException e) {
|
||||
if (strict) {
|
||||
failure = accumulateFailure(failure, e);
|
||||
} else {
|
||||
LOG.warnv(e, "Could not remove retired sidecar container {0} for key {1}; cleanup can retry",
|
||||
container.containerId(), key);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (retired.isEmpty()) {
|
||||
retiredContainers.remove(key, retired);
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private static RuntimeException accumulateFailure(RuntimeException failure, RuntimeException next) {
|
||||
if (failure == null) {
|
||||
return next;
|
||||
}
|
||||
if (failure != next) {
|
||||
failure.addSuppressed(next);
|
||||
}
|
||||
return failure;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param healthPath path (e.g. {@code /-/ping}) appended to a container's base URL to probe
|
||||
@@ -75,7 +139,21 @@ public class PerKeyContainerPool {
|
||||
}
|
||||
if (existing != null) {
|
||||
LOG.warnv("Sidecar container for key {0} is no longer healthy; restarting it", key);
|
||||
lifecycleManager.stopAndRemove(existing.containerId(), null);
|
||||
StartedContainer predecessor = existing;
|
||||
AtomicBoolean retained = new AtomicBoolean();
|
||||
// Admission and detachment share a short map operation, never startup or Docker I/O.
|
||||
// A use admitted after detachment cannot discover the predecessor in containers.
|
||||
activeUses.compute(key, (k, active) -> {
|
||||
retained.set(active != null);
|
||||
if (active != null) {
|
||||
retiredContainers.computeIfAbsent(key, unused -> new ArrayList<>()).add(predecessor);
|
||||
}
|
||||
containers.remove(key, predecessor);
|
||||
return active;
|
||||
});
|
||||
if (!retained.get()) {
|
||||
lifecycleManager.stopAndRemove(existing.containerId(), null);
|
||||
}
|
||||
}
|
||||
long startedGeneration = generation.get();
|
||||
StartedContainer started = starter.start();
|
||||
@@ -112,7 +190,7 @@ public class PerKeyContainerPool {
|
||||
* brand-new one just to find out it has nothing.
|
||||
*/
|
||||
public boolean isTracked(String key) {
|
||||
return containers.containsKey(key);
|
||||
return containers.containsKey(key) || retiredContainers.containsKey(key);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -138,14 +216,27 @@ public class PerKeyContainerPool {
|
||||
}
|
||||
Object lock = startLocks.computeIfAbsent(key, k -> new Object());
|
||||
synchronized (lock) {
|
||||
RuntimeException failure = null;
|
||||
try {
|
||||
stopRetired(key, strict);
|
||||
} catch (RuntimeException e) {
|
||||
failure = e;
|
||||
}
|
||||
StartedContainer container = containers.get(key);
|
||||
if (container != null) {
|
||||
if (strict) {
|
||||
lifecycleManager.stopAndRemoveStrict(container.containerId(), null);
|
||||
} else {
|
||||
lifecycleManager.stopAndRemove(container.containerId(), null);
|
||||
try {
|
||||
if (strict) {
|
||||
lifecycleManager.stopAndRemoveStrict(container.containerId(), null);
|
||||
} else {
|
||||
lifecycleManager.stopAndRemove(container.containerId(), null);
|
||||
}
|
||||
containers.remove(key, container);
|
||||
} catch (RuntimeException e) {
|
||||
failure = accumulateFailure(failure, e);
|
||||
}
|
||||
containers.remove(key, container);
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,6 +244,16 @@ public class PerKeyContainerPool {
|
||||
/** Stops and removes every container this pool has started, then forgets them all. */
|
||||
public void stopAll() {
|
||||
generation.incrementAndGet();
|
||||
for (String key : List.copyOf(retiredContainers.keySet())) {
|
||||
Object lock = startLocks.computeIfAbsent(key, k -> new Object());
|
||||
synchronized (lock) {
|
||||
try {
|
||||
stopRetired(key, false);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv(e, "Failed to stop retired sidecar containers for key {0}", key);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (containers.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -171,7 +272,10 @@ public class PerKeyContainerPool {
|
||||
public void stopAllStrictExcept(Set<String> protectedKeys) {
|
||||
generation.incrementAndGet();
|
||||
RuntimeException failure = null;
|
||||
for (String key : List.copyOf(containers.keySet())) {
|
||||
Set<String> keys = ConcurrentHashMap.newKeySet();
|
||||
keys.addAll(containers.keySet());
|
||||
keys.addAll(retiredContainers.keySet());
|
||||
for (String key : keys) {
|
||||
if (protectedKeys.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -9,10 +9,14 @@ 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.PerKeyContainerPool;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.inject.Named;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Starts and stops one BaGetter container per CodeArtifact repository backing the {@code nuget}
|
||||
* format, the same per-repository shape as Verdaccio (npm) and pypiserver (pypi) rather than
|
||||
@@ -47,13 +51,15 @@ public class BagetterSidecarManager implements ContainerTeardown {
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final SidecarRepositoryLease lease;
|
||||
private final RunLabelledContainers runContainers;
|
||||
|
||||
@Inject
|
||||
public BagetterSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, @Named("codeartifact") RunLabelledContainers runContainers) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.runContainers = runContainers;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.lease = new SidecarRepositoryLease("BaGetter", pool);
|
||||
}
|
||||
@@ -101,8 +107,9 @@ public class BagetterSidecarManager implements ContainerTeardown {
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String nugetRepositoryId) {
|
||||
String image = config.services().codeartifact().nugetImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-bagetter-" + nugetRepositoryId);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
runContainers.removeLeftovers();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-bagetter-" + nugetRepositoryId
|
||||
+ "-" + UUID.randomUUID());
|
||||
|
||||
// Loopback-only: this container authenticates nothing on its own (ApiKey left empty
|
||||
// below), so the Bearer/Basic check in CodeArtifactNuGetController is the only thing
|
||||
@@ -116,6 +123,8 @@ public class BagetterSidecarManager implements ContainerTeardown {
|
||||
// an explicit path.
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels("codeartifact", nugetRepositoryId, null, null))
|
||||
.withLabels(runContainers.labels())
|
||||
.withEnv("ApiKey", "")
|
||||
// Already the image's own shipped default; set explicitly so a future image
|
||||
// default change can't quietly start resolving packages from the real nuget.org,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Produces;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.inject.Named;
|
||||
import jakarta.inject.Singleton;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/** One process identity shared by all repository formats, including their admitted predecessors. */
|
||||
@ApplicationScoped
|
||||
public class CodeArtifactContainerRuns {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeArtifactContainerRuns.class);
|
||||
private final RunLabelledContainers containers;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactContainerRuns(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) {
|
||||
containers = new RunLabelledContainers(lifecycleManager, config, "codeartifact", "io.floci.codeartifact.run", LOG);
|
||||
}
|
||||
|
||||
@Produces
|
||||
@Singleton
|
||||
@Named("codeartifact")
|
||||
public RunLabelledContainers containers() {
|
||||
return containers;
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,14 @@ 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.PerKeyContainerPool;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.inject.Named;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
@@ -59,6 +62,7 @@ public class KellnrSidecarManager implements ContainerTeardown {
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final SidecarRepositoryLease lease;
|
||||
private final RunLabelledContainers runContainers;
|
||||
// One random admin password per repository's own container, regenerated every time
|
||||
// startContainer() runs for that key (including an internal pool restart of an unhealthy
|
||||
// container under the same key): KellnrSidecarClient reads this fresh on every admin login
|
||||
@@ -67,10 +71,11 @@ public class KellnrSidecarManager implements ContainerTeardown {
|
||||
|
||||
@Inject
|
||||
public KellnrSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, @Named("codeartifact") RunLabelledContainers runContainers) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.runContainers = runContainers;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.lease = new SidecarRepositoryLease("Kellnr", pool);
|
||||
}
|
||||
@@ -146,8 +151,9 @@ public class KellnrSidecarManager implements ContainerTeardown {
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String cargoRepositoryId) {
|
||||
String image = config.services().codeartifact().cargoImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-kellnr-" + cargoRepositoryId);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
runContainers.removeLeftovers();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-kellnr-" + cargoRepositoryId
|
||||
+ "-" + UUID.randomUUID());
|
||||
|
||||
// Set before the container is created, not after: KellnrSidecarClient's own adminLogin
|
||||
// reads this map directly, so the new password must already be visible to it the moment
|
||||
@@ -165,6 +171,8 @@ public class KellnrSidecarManager implements ContainerTeardown {
|
||||
// live), see this class's own javadoc for why that default is never left in place.
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels("codeartifact", cargoRepositoryId, null, null))
|
||||
.withLabels(runContainers.labels())
|
||||
.withEnv("KELLNR_ORIGIN__HOSTNAME", "localhost")
|
||||
.withEnv("KELLNR_SETUP__ADMIN_PWD", adminPassword)
|
||||
.withLoopbackPortBinding(KELLNR_PORT, 0)
|
||||
|
||||
@@ -9,11 +9,14 @@ 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.PerKeyContainerPool;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.inject.Named;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Starts and stops one pypiserver container per CodeArtifact repository backing the {@code pypi}
|
||||
@@ -40,13 +43,15 @@ public class PypiserverSidecarManager implements ContainerTeardown {
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final SidecarRepositoryLease lease;
|
||||
private final RunLabelledContainers runContainers;
|
||||
|
||||
@Inject
|
||||
public PypiserverSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, @Named("codeartifact") RunLabelledContainers runContainers) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.runContainers = runContainers;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.lease = new SidecarRepositoryLease("pypiserver", pool);
|
||||
}
|
||||
@@ -93,8 +98,9 @@ public class PypiserverSidecarManager implements ContainerTeardown {
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String pypiRepositoryId) {
|
||||
String image = config.services().codeartifact().pypiImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-pypiserver-" + pypiRepositoryId);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
runContainers.removeLeftovers();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-pypiserver-" + pypiRepositoryId
|
||||
+ "-" + UUID.randomUUID());
|
||||
|
||||
// Loopback-only: this container authenticates nothing on its own (auth disabled below), so
|
||||
// the Bearer check in CodeArtifactPypiController is the only thing standing between a
|
||||
@@ -102,6 +108,8 @@ public class PypiserverSidecarManager implements ContainerTeardown {
|
||||
// can reach the host bypass that check entirely, the same reasoning as Verdaccio's binding.
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels("codeartifact", pypiRepositoryId, null, null))
|
||||
.withLabels(runContainers.labels())
|
||||
.withLoopbackPortBinding(PYPISERVER_PORT, 0)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
.withEmbeddedDns()
|
||||
|
||||
@@ -41,6 +41,7 @@ final class SidecarRepositoryLease {
|
||||
throw new IllegalStateException(sidecarName + " sidecar is being released for repository "
|
||||
+ repositoryId);
|
||||
}
|
||||
pool.beginUse(repositoryId);
|
||||
use.active++;
|
||||
}
|
||||
}
|
||||
@@ -58,6 +59,7 @@ final class SidecarRepositoryLease {
|
||||
use.active--;
|
||||
}
|
||||
try {
|
||||
pool.endUse(repositoryId);
|
||||
stopIfUnused(repositoryId, use);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not stop {0} sidecar for repository {1} after its last use; "
|
||||
|
||||
@@ -10,11 +10,14 @@ import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import io.floci.aws.core.common.docker.RetryingTarCopier;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.inject.Named;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Starts and stops one Verdaccio container per CodeArtifact npm repository, unlike Reposilite's one
|
||||
@@ -70,13 +73,15 @@ public class VerdaccioSidecarManager implements ContainerTeardown {
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final SidecarRepositoryLease lease;
|
||||
private final RunLabelledContainers runContainers;
|
||||
|
||||
@Inject
|
||||
public VerdaccioSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, @Named("codeartifact") RunLabelledContainers runContainers) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.runContainers = runContainers;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.lease = new SidecarRepositoryLease("Verdaccio", pool);
|
||||
}
|
||||
@@ -124,8 +129,9 @@ public class VerdaccioSidecarManager implements ContainerTeardown {
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String npmRepositoryId, String publicUrl) {
|
||||
String image = config.services().codeartifact().npmImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-verdaccio-" + npmRepositoryId);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
runContainers.removeLeftovers();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-verdaccio-" + npmRepositoryId
|
||||
+ "-" + UUID.randomUUID());
|
||||
|
||||
// Loopback-only: this container has no auth of its own (open $all access, matching the
|
||||
// Maven proxy's own deliberate choice not to resolve upstreams), so the Bearer check in
|
||||
@@ -134,6 +140,8 @@ public class VerdaccioSidecarManager implements ContainerTeardown {
|
||||
// bypass that check entirely.
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels("codeartifact", npmRepositoryId, null, null))
|
||||
.withLabels(runContainers.labels())
|
||||
.withEnv("VERDACCIO_PUBLIC_URL", publicUrl)
|
||||
.withLoopbackPortBinding(VERDACCIO_PORT, 0)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
|
||||
@@ -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