mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(neptune): start clusters' containers again when Floci restarts (#9522)
Floci's shutdown stopped every Neptune cluster's proxy and graph database container and nothing started them again, so after a restart with persistent storage a cluster reported available with nothing behind its port. At startup each cluster now reports maintenance, and its instances starting, with its proxy port held for it at once, so a cluster created meanwhile is never handed it. Its container comes back in the background on the volume its graph is kept in, in the engine the graph was kept in, which the cluster's record now names, and its proxy listens on its port again; the cluster and its instances then report available. With no Docker daemon reachable they come back available with no container, as a cluster created then does. A cluster whose container or proxy does not start is left with none and its instances failed, and is tried again at the next start. The restore runs in each cluster's own account and Region, and marking the clusters calls no Docker. Floci now records which cluster holds each proxy port, so a cluster whose stored port another cluster holds moves to a free one, its instances with it, and one restored in the same process keeps its own. One recorded before its engine was kept is taken to be in the configured one, and one recorded before its graph was kept in a volume gets a volume, both kept before any Docker call. A DeleteDBCluster while the restore is starting the cluster's container leaves it deleting until the container has started, a second one too, and the restore removes it then. A delete defers only while a restore owns the cluster, which it does only once its marking is done, so one a failed write left deleting is retried at once; one still deleting at the next start is removed in the background. The delete, the restore and CreateDBInstance decide under a per-cluster lock, and instance creation, deletion and the restore's status writes under a per-instance one, taken first, so the restore never puts back an instance deleted meanwhile. CreateDBInstance is refused with InvalidDBClusterStateFault for a cluster that is not available. Shutdown now marks the container manager first, after which no container starts. A container left under a cluster's name, by a Floci that exited without stopping it, is now stopped with the same 30 seconds as at shutdown before its replacement starts, rather than removed outright, so Gremlin Server saves its graph to the volume first. The message refusing to delete a cluster with instances uses a colon in place of its dash. Closes #5664.
This commit is contained in:
1 parent
5c1e8b8110
commit
f2125d8908
11 files changed
+1487
-66
No files matched your search
@@ -200,8 +200,9 @@ if grep -q '/neptune/' "$SHARD_FILE"; then
|
||||
configured_image neptune default-neo4j-image
|
||||
configured_image neptune default-image
|
||||
fi
|
||||
# NeptuneGraphVolumeDockerNightlyIntegrationTest keeps a graph across containers on both engines' configured images.
|
||||
if starts NeptuneGraphVolumeDockerNightlyIntegrationTest; then
|
||||
# NeptuneGraphVolumeDockerNightlyIntegrationTest keeps a graph across containers on both engines' configured images,
|
||||
# and NeptuneClusterRestartDockerNightlyIntegrationTest restarts clusters on the Gremlin one.
|
||||
if starts NeptuneGraphVolumeDockerNightlyIntegrationTest NeptuneClusterRestartDockerNightlyIntegrationTest; then
|
||||
configured_image neptune default-image
|
||||
configured_image neptune default-neo4j-image
|
||||
fi
|
||||
|
||||
@@ -105,6 +105,25 @@ create that fails leaves no volume behind. A cluster created again under a delet
|
||||
starts on a new, empty volume. In `memory` mode a cluster's graph lasts only as long as its
|
||||
container.
|
||||
|
||||
### Restarts
|
||||
|
||||
When Neptune's records are kept, Floci's shutdown stops each cluster's proxy and container and
|
||||
keeps its volume, and the next start brings them back. Each cluster's port is held for it at once,
|
||||
so a cluster created meanwhile is never handed it. While its container starts again in the
|
||||
background, the cluster reports `maintenance` and its instances `starting`. The new container runs
|
||||
in the engine the cluster's graph was kept in, on its volume, so the graph is there. Its proxy then
|
||||
listens on the same port again, so clients reconnect to the endpoint they had, and the cluster and
|
||||
its instances report `available`. With no Docker daemon reachable they come back `available` with
|
||||
no container, as a cluster created then does. A cluster whose container or proxy does not start is
|
||||
left with none and its instances `failed`, and is tried again at the next start. A
|
||||
`DeleteDBCluster` during the restore leaves the cluster `deleting` until its container has started,
|
||||
and removes it then. `CreateDBInstance` is refused with `InvalidDBClusterStateFault` for a cluster
|
||||
that is not `available`.
|
||||
|
||||
A cluster whose stored port another cluster already holds moves to a free one. A cluster created by
|
||||
a Floci that did not record its engine comes back in the configured `db-type`, and one whose graph
|
||||
was not kept in a volume gets a new, empty one.
|
||||
|
||||
### Docker Compose
|
||||
|
||||
Neptune requires the Docker socket and the Gremlin proxy port range to be exposed. The first cluster claims `PROXY_BASE_PORT`; each additional cluster increments the port.
|
||||
|
||||
@@ -40,6 +40,7 @@ import io.floci.aws.services.memorydb.MemoryDbService;
|
||||
import io.floci.aws.services.memorydb.container.MemoryDbContainerManager;
|
||||
import io.floci.aws.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import io.floci.aws.services.mwaa.MwaaService;
|
||||
import io.floci.aws.services.neptune.NeptuneService;
|
||||
import io.floci.aws.services.neptune.container.NeptuneContainerManager;
|
||||
import io.floci.aws.services.neptune.proxy.NeptuneProxyManager;
|
||||
import io.floci.aws.services.opensearch.OpenSearchService;
|
||||
@@ -108,6 +109,7 @@ public class EmulatorLifecycle {
|
||||
private final DocDbService docDbService;
|
||||
private final NeptuneContainerManager neptuneContainerManager;
|
||||
private final NeptuneProxyManager neptuneProxyManager;
|
||||
private final NeptuneService neptuneService;
|
||||
private final RabbitMqManager rabbitMqManager;
|
||||
private final AmazonMqService amazonMqService;
|
||||
private final FlinkContainerManager flinkContainerManager;
|
||||
@@ -162,6 +164,7 @@ public class EmulatorLifecycle {
|
||||
DocDbService docDbService,
|
||||
NeptuneContainerManager neptuneContainerManager,
|
||||
NeptuneProxyManager neptuneProxyManager,
|
||||
NeptuneService neptuneService,
|
||||
RabbitMqManager rabbitMqManager,
|
||||
AmazonMqService amazonMqService,
|
||||
FlinkContainerManager flinkContainerManager,
|
||||
@@ -213,6 +216,7 @@ public class EmulatorLifecycle {
|
||||
this.docDbService = docDbService;
|
||||
this.neptuneContainerManager = neptuneContainerManager;
|
||||
this.neptuneProxyManager = neptuneProxyManager;
|
||||
this.neptuneService = neptuneService;
|
||||
this.rabbitMqManager = rabbitMqManager;
|
||||
this.amazonMqService = amazonMqService;
|
||||
this.flinkContainerManager = flinkContainerManager;
|
||||
@@ -366,6 +370,13 @@ public class EmulatorLifecycle {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
if (config.services().neptune().enabled()) {
|
||||
// Starts the clusters' containers and proxies in the background, failing the future with the ones it could not.
|
||||
neptuneService.restorePersistedRuntime().exceptionally(ex -> {
|
||||
LOG.error("Failed to restore persisted Neptune clusters at startup", ex);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
if (config.services().elbv2().enabled()) {
|
||||
elbV2Service.restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.neptune.container.NeptuneContainerHandle;
|
||||
@@ -27,9 +29,11 @@ import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@@ -45,8 +49,17 @@ public class NeptuneService {
|
||||
private final RegionResolver regionResolver;
|
||||
private final NeptuneContainerManager containerManager;
|
||||
private final NeptuneProxyManager proxyManager;
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
/** The proxy ports handed out, each to the identity of the cluster that holds it. */
|
||||
private final ConcurrentHashMap<Integer, String> portOwners = new ConcurrentHashMap<>();
|
||||
private final Set<String> provisioningClusterNames = ConcurrentHashMap.newKeySet();
|
||||
/**
|
||||
* One monitor per cluster and per instance, by identity: a cluster's is taken by its delete, its instances'
|
||||
* creation and deletion and its restore, and an instance's by its creation, its deletion and the restore's
|
||||
* status writes, always before its cluster's.
|
||||
*/
|
||||
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
/** The identities of the clusters whose containers the startup restore is bringing back. */
|
||||
private final Set<String> restoringClusters = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Inject
|
||||
public NeptuneService(EmulatorConfig config,
|
||||
@@ -96,7 +109,7 @@ public class NeptuneService {
|
||||
}
|
||||
|
||||
// Open the try immediately after reserving the port so config reads below can't leak it.
|
||||
int proxyPort = allocateProxyPort(settings.port());
|
||||
int proxyPort = allocateProxyPort(settings.port(), resourceIdentity(currentAccount(), currentRegion(), id));
|
||||
NeptuneContainerHandle handle = null;
|
||||
String volumeId = null;
|
||||
boolean provisioned = false;
|
||||
@@ -141,6 +154,7 @@ public class NeptuneService {
|
||||
cluster.setDbClusterMembers(new ArrayList<>());
|
||||
cluster.setProxyPort(proxyPort);
|
||||
cluster.setVolumeId(volumeId);
|
||||
cluster.setDbType(dbType);
|
||||
settings.applyTo(cluster);
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
cluster.setTags(tags);
|
||||
@@ -202,7 +216,7 @@ public class NeptuneService {
|
||||
} finally {
|
||||
// Always release the port — even if a cleanup step throws a non-RuntimeException
|
||||
// (e.g. an Error) — since leaking the port is the exact failure this rollback prevents.
|
||||
releaseProxyPort(proxyPort);
|
||||
releaseProxyPort(proxyPort, identity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,19 +287,37 @@ public class NeptuneService {
|
||||
}
|
||||
|
||||
public void deleteDbCluster(String id) {
|
||||
NeptuneCluster cluster = getStoredCluster(id).orElseThrow(() ->
|
||||
new AwsException("DBClusterNotFoundFault",
|
||||
"Neptune cluster " + id + " not found.", 404));
|
||||
String identity = resourceIdentity(currentAccount(), currentRegion(), id);
|
||||
synchronized (clusterLock(identity)) {
|
||||
NeptuneCluster cluster = getStoredCluster(id).orElseThrow(() ->
|
||||
new AwsException("DBClusterNotFoundFault",
|
||||
"Neptune cluster " + id + " not found.", 404));
|
||||
|
||||
if (cluster.isDeletionProtection()) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"Cannot delete protected Cluster, please disable deletion protection and try again.", 400);
|
||||
}
|
||||
if (cluster.getDbClusterMembers() != null && !cluster.getDbClusterMembers().isEmpty()) {
|
||||
throw new AwsException("InvalidDBClusterStateFault",
|
||||
"Cannot delete Neptune cluster " + id + " — it still has DB instances.", 400);
|
||||
}
|
||||
if (cluster.isDeletionProtection()) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"Cannot delete protected Cluster, please disable deletion protection and try again.", 400);
|
||||
}
|
||||
if (cluster.getDbClusterMembers() != null && !cluster.getDbClusterMembers().isEmpty()) {
|
||||
throw new AwsException("InvalidDBClusterStateFault",
|
||||
"Cannot delete Neptune cluster " + id + ": it still has DB instances.", 400);
|
||||
}
|
||||
if (restoringClusters.contains(identity)) {
|
||||
// Its container is starting again after a restart: the restore removes the cluster once it has.
|
||||
cluster.setStatus("deleting");
|
||||
putCluster(cluster);
|
||||
LOG.infov("Neptune cluster {0} is deleted once its container has started", id);
|
||||
return;
|
||||
}
|
||||
|
||||
removeCluster(cluster);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a cluster's proxy and container and removes its record and port, and its volume as the storage policy
|
||||
* says; the caller holds the cluster's lock.
|
||||
*/
|
||||
private void removeCluster(NeptuneCluster cluster) {
|
||||
cluster.setStatus("deleting");
|
||||
putCluster(cluster);
|
||||
|
||||
@@ -299,9 +331,307 @@ public class NeptuneService {
|
||||
}
|
||||
|
||||
containerManager.removeStorage(cluster.getVolumeId());
|
||||
releaseProxyPort(cluster.getProxyPort());
|
||||
releaseProxyPort(cluster.getProxyPort(), identity);
|
||||
deleteCluster(cluster);
|
||||
LOG.infov("Neptune cluster {0} deleted", id);
|
||||
LOG.infov("Neptune cluster {0} deleted", cluster.getDbClusterIdentifier());
|
||||
}
|
||||
|
||||
// ── Restart ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Brings the stored clusters' graph database containers back after Floci restarts. Shutdown removes them and
|
||||
* their proxies and keeps their volumes, so a cluster read back from storage reported itself available with
|
||||
* nothing behind its port. Each cluster reports {@code maintenance}, and its instances {@code starting}, at once,
|
||||
* with its proxy port held for it, and its container comes back in the background on its volume, in the engine
|
||||
* its graph was kept in, so Floci does not wait for Docker or an image pull. Its proxy then listens on its port
|
||||
* again, and the cluster and its instances report {@code available}. With no Docker daemon reachable they report
|
||||
* {@code available} with no container, as a cluster created then does.
|
||||
*
|
||||
* <p>A cluster whose port another cluster already holds gets a new one. A cluster recorded before its graph was
|
||||
* kept in a volume gets a volume now, and one recorded before its engine was kept is taken to be in the
|
||||
* configured one. A cluster whose container or proxy does not start is left with none and its instances
|
||||
* {@code failed}, and is tried again at the next start; one still {@code deleting} at startup is removed then. A
|
||||
* cluster deleted during its restore is {@code deleting} until its container has started, and goes then. Every
|
||||
* cluster is tried, and the ones that could not be restored fail the returned future together. A shutdown during
|
||||
* the restore leaves the clusters not started yet as they are, for the next start.
|
||||
*/
|
||||
public CompletableFuture<Void> restorePersistedRuntime() {
|
||||
if (!(clusters instanceof AccountAwareStorageBackend<NeptuneCluster> aware)) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
Map<String, RestoringCluster> stored = new LinkedHashMap<>();
|
||||
for (AccountEntry<NeptuneCluster> entry : aware.scanAllAccountEntries(storedKey -> true)) {
|
||||
NeptuneCluster cluster = entry.value();
|
||||
String account = arnAccount(cluster.getDbClusterArn());
|
||||
String region = arnRegion(cluster.getDbClusterArn());
|
||||
if (account.isEmpty() || region.isEmpty()) {
|
||||
account = entry.accountId();
|
||||
region = regionResolver.getDefaultRegion();
|
||||
}
|
||||
String id = cluster.getDbClusterIdentifier();
|
||||
stored.putIfAbsent(resourceIdentity(account, region, id),
|
||||
new RestoringCluster(account, region, id, null, false));
|
||||
}
|
||||
List<RestoringCluster> pending = new ArrayList<>();
|
||||
List<RuntimeException> prepareFailures = new ArrayList<>();
|
||||
// Marking calls no Docker, so it runs before startup goes on; the Docker work is all in the background.
|
||||
for (RestoringCluster candidate : stored.values()) {
|
||||
try {
|
||||
RestoringCluster restoring = RequestScopes.callAs(candidate.accountId(), candidate.region(),
|
||||
() -> prepareRestore(candidate));
|
||||
if (restoring != null) {
|
||||
pending.add(restoring);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
prepareFailures.add(restoreFailure(candidate, e));
|
||||
}
|
||||
}
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
List<RuntimeException> failures = new ArrayList<>(prepareFailures);
|
||||
for (RestoringCluster restoring : pending) {
|
||||
if (containerManager.isShuttingDown()) {
|
||||
// Clusters not reached yet stay as they are, which the next start restores; a delete meanwhile
|
||||
// removes one at once, as no container of it is starting.
|
||||
pending.forEach(left -> restoringClusters.remove(
|
||||
resourceIdentity(left.accountId(), left.region(), left.id())));
|
||||
break;
|
||||
}
|
||||
try {
|
||||
RequestScopes.runAs(restoring.accountId(), restoring.region(), () -> {
|
||||
if (restoring.deleting()) {
|
||||
finishDelete(restoring);
|
||||
} else {
|
||||
restoreCluster(restoring);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
failures.add(restoreFailure(restoring, e));
|
||||
}
|
||||
}
|
||||
if (!failures.isEmpty()) {
|
||||
RuntimeException failure = failures.getFirst();
|
||||
failures.subList(1, failures.size()).forEach(failure::addSuppressed);
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static RuntimeException restoreFailure(RestoringCluster restoring, RuntimeException cause) {
|
||||
return new IllegalStateException("Could not restore Neptune cluster " + restoring.id() + " of account "
|
||||
+ restoring.accountId() + " in " + restoring.region(), cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a stored cluster as being restored, under its lock, holding its proxy port for it, or, for a delete
|
||||
* Floci did not live to finish, as one to remove; null for one gone meanwhile. A cluster recorded before its
|
||||
* graph was kept in a volume is given one here, and one recorded before its engine was kept the configured
|
||||
* one, both kept before any Docker call.
|
||||
*/
|
||||
private RestoringCluster prepareRestore(RestoringCluster candidate) {
|
||||
String identity = resourceIdentity(candidate.accountId(), candidate.region(), candidate.id());
|
||||
RestoringCluster restoring;
|
||||
List<String> members;
|
||||
int port;
|
||||
synchronized (clusterLock(identity)) {
|
||||
// Read as DescribeDBClusters reads it, which moves a record stored under a legacy key onto its key.
|
||||
NeptuneCluster cluster = getStoredCluster(candidate.id()).orElse(null);
|
||||
if (cluster == null) {
|
||||
return null;
|
||||
}
|
||||
// Held at once, whatever happens next: a cluster created now must not be handed this cluster's port.
|
||||
String owner = portOwners.putIfAbsent(cluster.getProxyPort(), identity);
|
||||
if (owner != null && !owner.equals(identity)) {
|
||||
int taken = cluster.getProxyPort();
|
||||
cluster.setProxyPort(allocateProxyPort(null, identity));
|
||||
cluster.setPort(cluster.getProxyPort());
|
||||
LOG.warnv("Neptune cluster {0} moves from port {1}, which another cluster holds, to {2}",
|
||||
candidate.id(), String.valueOf(taken), String.valueOf(cluster.getProxyPort()));
|
||||
}
|
||||
boolean deleting = "deleting".equals(cluster.getStatus());
|
||||
restoring = new RestoringCluster(candidate.accountId(), candidate.region(), candidate.id(),
|
||||
cluster.getDbClusterResourceId(), deleting);
|
||||
if (deleting) {
|
||||
return restoring;
|
||||
}
|
||||
members = List.copyOf(cluster.getDbClusterMembers());
|
||||
if (cluster.getVolumeId() == null && keepsClusters()) {
|
||||
cluster.setVolumeId(UUID.randomUUID().toString());
|
||||
}
|
||||
if (cluster.getDbType() == null) {
|
||||
cluster.setDbType(configuredDbType());
|
||||
}
|
||||
cluster.setStatus("maintenance");
|
||||
putCluster(cluster);
|
||||
port = cluster.getProxyPort();
|
||||
}
|
||||
updateInstances(members, candidate.id(), "starting", port);
|
||||
// Owned by the restore only once nothing here can fail, so one that did leaves no delete waiting on a restore
|
||||
// that never runs. Nothing is started before the restore runs, so a delete before this removes the cluster.
|
||||
restoringClusters.add(identity);
|
||||
return restoring;
|
||||
}
|
||||
|
||||
/** Removes a cluster a delete Floci did not live to finish left behind, its container and volume with it. */
|
||||
private void finishDelete(RestoringCluster restoring) {
|
||||
synchronized (clusterLock(resourceIdentity(restoring.accountId(), restoring.region(), restoring.id()))) {
|
||||
NeptuneCluster cluster = restoreTarget(restoring);
|
||||
if (cluster != null) {
|
||||
removeCluster(cluster);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreCluster(RestoringCluster restoring) {
|
||||
String identity = resourceIdentity(restoring.accountId(), restoring.region(), restoring.id());
|
||||
NeptuneContainerHandle handle = null;
|
||||
try {
|
||||
NeptuneCluster cluster = restoreTarget(restoring);
|
||||
if (cluster == null) {
|
||||
restoringClusters.remove(identity);
|
||||
return;
|
||||
}
|
||||
NeptuneDbType dbType = cluster.getDbType();
|
||||
String image = switch (dbType) {
|
||||
case GREMLIN -> config.services().neptune().defaultImage();
|
||||
case NEO4J -> config.services().neptune().defaultNeo4jImage();
|
||||
};
|
||||
handle = containerManager.tryStart(restoring.id(), image, dbType, restoring.accountId(),
|
||||
restoring.region(), cluster.getVolumeId());
|
||||
finishRestore(restoring, handle);
|
||||
} catch (RuntimeException e) {
|
||||
try {
|
||||
proxyManager.stopProxy(identity);
|
||||
// By identity, not handle: a start that fails after its container exists returns no handle.
|
||||
containerManager.stopByClusterId(identity);
|
||||
} catch (RuntimeException cleanup) {
|
||||
e.addSuppressed(cleanup);
|
||||
}
|
||||
if (containerManager.isShuttingDown()) {
|
||||
// Left as it is, which the next start restores.
|
||||
restoringClusters.remove(identity);
|
||||
LOG.debugv("Neptune cluster {0} not restored: {1}", restoring.id(), e.getMessage());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
failRestore(restoring);
|
||||
} catch (RuntimeException recordFailure) {
|
||||
e.addSuppressed(recordFailure);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the cluster's proxy in front of the container started for it, or leaves it with none when no Docker
|
||||
* daemon is reachable, and makes it and its instances available; a cluster deleted while it started is
|
||||
* removed now.
|
||||
*/
|
||||
private void finishRestore(RestoringCluster restoring, NeptuneContainerHandle handle) {
|
||||
String identity = resourceIdentity(restoring.accountId(), restoring.region(), restoring.id());
|
||||
NeptuneCluster cluster;
|
||||
List<String> members;
|
||||
synchronized (clusterLock(identity)) {
|
||||
// The restore ends here: from now on a delete removes the cluster itself.
|
||||
restoringClusters.remove(identity);
|
||||
cluster = restoreTarget(restoring);
|
||||
if (cluster == null) {
|
||||
if (handle != null) {
|
||||
containerManager.stop(handle);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (handle != null) {
|
||||
cluster.setContainerId(handle.getContainerId());
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
if (!"deleting".equals(cluster.getStatus())) {
|
||||
proxyManager.startProxy(identity, cluster.getProxyPort(), handle.getHost(), handle.getPort());
|
||||
}
|
||||
} else {
|
||||
clearContainer(cluster);
|
||||
}
|
||||
if ("deleting".equals(cluster.getStatus())) {
|
||||
removeCluster(cluster);
|
||||
return;
|
||||
}
|
||||
cluster.setStatus("available");
|
||||
putCluster(cluster);
|
||||
members = List.copyOf(cluster.getDbClusterMembers());
|
||||
}
|
||||
updateInstances(members, restoring.id(), "available", cluster.getProxyPort());
|
||||
}
|
||||
|
||||
/** Leaves a cluster whose container or proxy did not start with none, its instances failed, for the next start. */
|
||||
private void failRestore(RestoringCluster restoring) {
|
||||
NeptuneCluster cluster;
|
||||
List<String> members;
|
||||
String identity = resourceIdentity(restoring.accountId(), restoring.region(), restoring.id());
|
||||
synchronized (clusterLock(identity)) {
|
||||
restoringClusters.remove(identity);
|
||||
cluster = restoreTarget(restoring);
|
||||
if (cluster == null) {
|
||||
return;
|
||||
}
|
||||
if ("deleting".equals(cluster.getStatus())) {
|
||||
removeCluster(cluster);
|
||||
return;
|
||||
}
|
||||
clearContainer(cluster);
|
||||
cluster.setStatus("available");
|
||||
putCluster(cluster);
|
||||
members = List.copyOf(cluster.getDbClusterMembers());
|
||||
}
|
||||
updateInstances(members, restoring.id(), "failed", cluster.getProxyPort());
|
||||
}
|
||||
|
||||
/** The cluster the restore is for, or null when it is gone or another cluster has taken its identifier. */
|
||||
private NeptuneCluster restoreTarget(RestoringCluster restoring) {
|
||||
return getStoredCluster(restoring.id())
|
||||
.filter(cluster -> Objects.equals(cluster.getDbClusterResourceId(), restoring.resourceId()))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static void clearContainer(NeptuneCluster cluster) {
|
||||
cluster.setContainerId(null);
|
||||
cluster.setContainerHost(null);
|
||||
cluster.setContainerPort(0);
|
||||
}
|
||||
|
||||
/** Sets the status of a cluster's instances, and the port they report, which is the cluster's proxy port. */
|
||||
private void updateInstances(List<String> members, String clusterId, String status, int port) {
|
||||
for (String instanceId : members) {
|
||||
// Under the instance's lock, which its deletion and creation take, so a write never puts back an
|
||||
// instance deleted since it was read, nor overwrites one created again under its name.
|
||||
synchronized (instanceLock(resourceIdentity(currentAccount(), currentRegion(), instanceId))) {
|
||||
getStoredInstance(instanceId)
|
||||
.filter(instance -> clusterId.equals(instance.getDbClusterIdentifier()))
|
||||
.ifPresent(instance -> {
|
||||
instance.setStatus(status);
|
||||
instance.setPort(port);
|
||||
putInstance(instance);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private NeptuneDbType configuredDbType() {
|
||||
return NeptuneDbType.fromConfig(config.services().neptune().dbType()).orElse(NeptuneDbType.GREMLIN);
|
||||
}
|
||||
|
||||
private Object clusterLock(String identity) {
|
||||
return locks.computeIfAbsent("cluster:" + identity, ignored -> new Object());
|
||||
}
|
||||
|
||||
private Object instanceLock(String identity) {
|
||||
return locks.computeIfAbsent("instance:" + identity, ignored -> new Object());
|
||||
}
|
||||
|
||||
/**
|
||||
* A cluster the startup restore brings back, or removes when {@code deleting}, by the account and Region it is
|
||||
* stored in and the resource ID it had when marked.
|
||||
*/
|
||||
private record RestoringCluster(String accountId, String region, String id, String resourceId,
|
||||
boolean deleting) {
|
||||
}
|
||||
|
||||
public NeptuneCluster addRoleToDbCluster(String id, String roleArn) {
|
||||
@@ -367,38 +697,47 @@ public class NeptuneService {
|
||||
boolean iamEnabled, NeptuneInstanceSettings settings,
|
||||
Map<String, String> tags) {
|
||||
settings.validate();
|
||||
if (getStoredInstance(id).isPresent()) {
|
||||
throw new AwsException("DBInstanceAlreadyExists",
|
||||
"Neptune instance " + id + " already exists.", 400);
|
||||
}
|
||||
|
||||
NeptuneCluster cluster = getDbCluster(dbClusterIdentifier);
|
||||
String region = currentRegion();
|
||||
// The instance's lock before its cluster's, the one order every path that holds both uses.
|
||||
synchronized (instanceLock(resourceIdentity(currentAccount(), region, id))) {
|
||||
if (getStoredInstance(id).isPresent()) {
|
||||
throw new AwsException("DBInstanceAlreadyExists",
|
||||
"Neptune instance " + id + " already exists.", 400);
|
||||
}
|
||||
|
||||
NeptuneInstance instance = new NeptuneInstance();
|
||||
instance.setDbInstanceIdentifier(id);
|
||||
instance.setDbClusterIdentifier(dbClusterIdentifier);
|
||||
instance.setDbInstanceClass(dbInstanceClass != null ? dbInstanceClass : "db.r5.large");
|
||||
instance.setEngineVersion(engineVersion != null ? engineVersion : cluster.getEngineVersion());
|
||||
instance.setStatus("available");
|
||||
instance.setEndpoint(cluster.getEndpoint());
|
||||
instance.setPort(cluster.getPort());
|
||||
instance.setIamDatabaseAuthenticationEnabled(iamEnabled);
|
||||
instance.setDbInstanceArn(regionResolver.buildArn("neptune", region, "db:" + id));
|
||||
instance.setDbiResourceId("db-" + UUID.randomUUID().toString()
|
||||
.replace("-", "").substring(0, 24).toUpperCase());
|
||||
instance.setCreatedAt(Instant.now());
|
||||
settings.applyTo(instance);
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
instance.setTags(tags);
|
||||
synchronized (clusterLock(resourceIdentity(currentAccount(), region, dbClusterIdentifier))) {
|
||||
NeptuneCluster cluster = getDbCluster(dbClusterIdentifier);
|
||||
if (cluster.getStatus() != null && !"available".equals(cluster.getStatus())) {
|
||||
throw new AwsException("InvalidDBClusterStateFault",
|
||||
"DB cluster is not available for member creation.", 400);
|
||||
}
|
||||
|
||||
NeptuneInstance instance = new NeptuneInstance();
|
||||
instance.setDbInstanceIdentifier(id);
|
||||
instance.setDbClusterIdentifier(dbClusterIdentifier);
|
||||
instance.setDbInstanceClass(dbInstanceClass != null ? dbInstanceClass : "db.r5.large");
|
||||
instance.setEngineVersion(engineVersion != null ? engineVersion : cluster.getEngineVersion());
|
||||
instance.setStatus("available");
|
||||
instance.setEndpoint(cluster.getEndpoint());
|
||||
instance.setPort(cluster.getPort());
|
||||
instance.setIamDatabaseAuthenticationEnabled(iamEnabled);
|
||||
instance.setDbInstanceArn(regionResolver.buildArn("neptune", region, "db:" + id));
|
||||
instance.setDbiResourceId("db-" + UUID.randomUUID().toString()
|
||||
.replace("-", "").substring(0, 24).toUpperCase());
|
||||
instance.setCreatedAt(Instant.now());
|
||||
settings.applyTo(instance);
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
instance.setTags(tags);
|
||||
}
|
||||
|
||||
cluster.getDbClusterMembers().add(id);
|
||||
putCluster(cluster);
|
||||
|
||||
putInstance(instance);
|
||||
LOG.infov("Neptune instance {0} created in cluster {1}", id, dbClusterIdentifier);
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
cluster.getDbClusterMembers().add(id);
|
||||
putCluster(cluster);
|
||||
|
||||
putInstance(instance);
|
||||
LOG.infov("Neptune instance {0} created in cluster {1}", id, dbClusterIdentifier);
|
||||
return instance;
|
||||
}
|
||||
|
||||
public Optional<NeptuneCluster> findDbCluster(String id) {
|
||||
@@ -446,19 +785,24 @@ public class NeptuneService {
|
||||
}
|
||||
|
||||
public void deleteDbInstance(String id) {
|
||||
NeptuneInstance instance = getStoredInstance(id).orElseThrow(() ->
|
||||
new AwsException("DBInstanceNotFound",
|
||||
"Neptune instance " + id + " not found.", 404));
|
||||
String region = currentRegion();
|
||||
synchronized (instanceLock(resourceIdentity(currentAccount(), region, id))) {
|
||||
NeptuneInstance instance = getStoredInstance(id).orElseThrow(() ->
|
||||
new AwsException("DBInstanceNotFound",
|
||||
"Neptune instance " + id + " not found.", 404));
|
||||
|
||||
String clusterId = instance.getDbClusterIdentifier();
|
||||
NeptuneCluster cluster = getStoredCluster(clusterId).orElse(null);
|
||||
if (cluster != null) {
|
||||
cluster.getDbClusterMembers().remove(id);
|
||||
putCluster(cluster);
|
||||
String clusterId = instance.getDbClusterIdentifier();
|
||||
synchronized (clusterLock(resourceIdentity(currentAccount(), region, clusterId))) {
|
||||
NeptuneCluster cluster = getStoredCluster(clusterId).orElse(null);
|
||||
if (cluster != null) {
|
||||
cluster.getDbClusterMembers().remove(id);
|
||||
putCluster(cluster);
|
||||
}
|
||||
}
|
||||
|
||||
deleteInstance(instance);
|
||||
LOG.infov("Neptune instance {0} deleted", id);
|
||||
}
|
||||
|
||||
deleteInstance(instance);
|
||||
LOG.infov("Neptune instance {0} deleted", id);
|
||||
}
|
||||
|
||||
// ── Tags ──────────────────────────────────────────────────────────────────
|
||||
@@ -730,10 +1074,11 @@ public class NeptuneService {
|
||||
return config.hostname().orElse("localhost");
|
||||
}
|
||||
|
||||
private int allocateProxyPort(Integer requested) {
|
||||
private int allocateProxyPort(Integer requested, String owner) {
|
||||
int base = config.services().neptune().proxyBasePort();
|
||||
int max = config.services().neptune().proxyMaxPort();
|
||||
if (requested != null && requested >= base && requested <= max && usedPorts.add(requested)) {
|
||||
if (requested != null && requested >= base && requested <= max
|
||||
&& portOwners.putIfAbsent(requested, owner) == null) {
|
||||
return requested;
|
||||
}
|
||||
if (requested != null) {
|
||||
@@ -742,7 +1087,7 @@ public class NeptuneService {
|
||||
String.valueOf(requested), String.valueOf(base), String.valueOf(max));
|
||||
}
|
||||
for (int port = base; port <= max; port++) {
|
||||
if (usedPorts.add(port)) {
|
||||
if (portOwners.putIfAbsent(port, owner) == null) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
@@ -753,7 +1098,7 @@ public class NeptuneService {
|
||||
"No available proxy ports in range " + base + "-" + max, 400);
|
||||
}
|
||||
|
||||
private void releaseProxyPort(int port) {
|
||||
usedPorts.remove(port);
|
||||
private void releaseProxyPort(int port, String owner) {
|
||||
portOwners.remove(port, owner);
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,7 @@ public class NeptuneContainerManager {
|
||||
private final RegionResolver regionResolver;
|
||||
private final Map<String, NeptuneContainerHandle> activeContainers = new ConcurrentHashMap<>();
|
||||
private volatile boolean dockerUnavailableLogged;
|
||||
private volatile boolean shuttingDown;
|
||||
|
||||
@Inject
|
||||
public NeptuneContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -133,12 +134,17 @@ public class NeptuneContainerManager {
|
||||
*/
|
||||
public NeptuneContainerHandle start(String clusterId, String image, NeptuneDbType dbType,
|
||||
String accountId, String region, String volumeId) {
|
||||
if (shuttingDown) {
|
||||
throw new IllegalStateException("Neptune is shutting down");
|
||||
}
|
||||
LOG.infov("Starting Neptune backend container ({0}) for cluster: {1}", dbType, clusterId);
|
||||
|
||||
int backendPort = dbType.backendPort();
|
||||
String identity = resourceIdentity(accountId, region, clusterId);
|
||||
String containerName = containerName(identity);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
// A container left under the name, by a Floci that exited without stopping it, stops as shutdown stops one,
|
||||
// so Gremlin Server saves its graph to the volume the new container opens rather than losing it.
|
||||
lifecycleManager.stopAndRemove(containerName, null, STOP_TIMEOUT_SECONDS);
|
||||
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
@@ -194,6 +200,10 @@ public class NeptuneContainerManager {
|
||||
handle.setLogStream(logHandle);
|
||||
|
||||
waitForBackendReady(clusterId, dbType, endpoint.host(), endpoint.port());
|
||||
if (shuttingDown) {
|
||||
throw new IllegalStateException("Neptune shut down while the container for cluster " + clusterId
|
||||
+ " was starting");
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
@@ -286,7 +296,17 @@ public class NeptuneContainerManager {
|
||||
return ContainerStorageHelper.resourceName(config, "neptune", null, clusterId);
|
||||
}
|
||||
|
||||
/** Whether shutdown has begun, after which no container starts. */
|
||||
public boolean isShuttingDown() {
|
||||
return shuttingDown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops every container, at shutdown. No container starts after this begins, and a start already running
|
||||
* fails when it finishes, its container left for {@link #stopByClusterId} to remove.
|
||||
*/
|
||||
public void stopAll() {
|
||||
shuttingDown = true;
|
||||
List<NeptuneContainerHandle> handles = new ArrayList<>(activeContainers.values());
|
||||
if (!handles.isEmpty()) {
|
||||
LOG.infov("Stopping {0} Neptune container(s) on shutdown", handles.size());
|
||||
|
||||
@@ -48,6 +48,8 @@ public class NeptuneCluster {
|
||||
private int proxyPort;
|
||||
/** Names the cluster's data volume; null for a cluster whose data is not kept, in memory mode. */
|
||||
private String volumeId;
|
||||
/** The engine the cluster's graph is held in, which its volume's data is for; null for an older record. */
|
||||
private NeptuneDbType dbType;
|
||||
|
||||
public NeptuneCluster() {}
|
||||
|
||||
@@ -173,4 +175,7 @@ public class NeptuneCluster {
|
||||
|
||||
public String getVolumeId() { return volumeId; }
|
||||
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
|
||||
|
||||
public NeptuneDbType getDbType() { return dbType; }
|
||||
public void setDbType(NeptuneDbType dbType) { this.dbType = dbType; }
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.floci.aws.services.neptune.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -15,8 +17,10 @@ import java.util.Optional;
|
||||
* </ul>
|
||||
*
|
||||
* <p>The engine is selected globally via {@code FLOCI_SERVICES_NEPTUNE_DB_TYPE}, mirroring
|
||||
* LocalStack's {@code NEPTUNE_DB_TYPE} toggle.
|
||||
* LocalStack's {@code NEPTUNE_DB_TYPE} toggle. A cluster keeps the engine it was created in, which
|
||||
* its record names, since its graph is that engine's data.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public enum NeptuneDbType {
|
||||
|
||||
GREMLIN(8182),
|
||||
|
||||
@@ -39,6 +39,7 @@ import io.floci.aws.services.memorydb.MemoryDbService;
|
||||
import io.floci.aws.services.memorydb.container.MemoryDbContainerManager;
|
||||
import io.floci.aws.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import io.floci.aws.services.mwaa.MwaaService;
|
||||
import io.floci.aws.services.neptune.NeptuneService;
|
||||
import io.floci.aws.services.neptune.container.NeptuneContainerManager;
|
||||
import io.floci.aws.services.neptune.proxy.NeptuneProxyManager;
|
||||
import io.floci.aws.services.opensearch.OpenSearchService;
|
||||
@@ -120,6 +121,8 @@ class EmulatorLifecycleTest {
|
||||
@Mock private DocDbContainerManager docDbContainerManager;
|
||||
@Mock private NeptuneContainerManager neptuneContainerManager;
|
||||
@Mock private NeptuneProxyManager neptuneProxyManager;
|
||||
@Mock private NeptuneService neptuneService;
|
||||
@Mock private EmulatorConfig.NeptuneServiceConfig neptuneServiceConfig;
|
||||
@Mock private RabbitMqManager rabbitMqManager;
|
||||
@Mock private FlinkContainerManager flinkContainerManager;
|
||||
@Mock private RdsService rdsService;
|
||||
@@ -195,6 +198,8 @@ class EmulatorLifecycleTest {
|
||||
Mockito.lenient().when(servicesConfig.mwaa()).thenReturn(mwaaServiceConfig);
|
||||
Mockito.lenient().when(mwaaServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.docdb()).thenReturn(docDbServiceConfig);
|
||||
Mockito.lenient().when(servicesConfig.neptune()).thenReturn(neptuneServiceConfig);
|
||||
Mockito.lenient().when(neptuneServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(docDbServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(servicesConfig.amazonmq()).thenReturn(amazonMqServiceConfig);
|
||||
Mockito.lenient().when(amazonMqServiceConfig.enabled()).thenReturn(false);
|
||||
@@ -214,7 +219,7 @@ class EmulatorLifecycleTest {
|
||||
elastiCacheContainerManager, elastiCacheMemcachedContainerManager,
|
||||
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
|
||||
memoryDbContainerManager, memoryDbProxyManager, memoryDbService,
|
||||
docDbContainerManager, docDbService, neptuneContainerManager, neptuneProxyManager,
|
||||
docDbContainerManager, docDbService, neptuneContainerManager, neptuneProxyManager, neptuneService,
|
||||
rabbitMqManager, amazonMqService, flinkContainerManager, kinesisAnalyticsService,
|
||||
openSearchService, mwaaService,
|
||||
sageMakerService, rdsService, timestreamInfluxDbService,
|
||||
@@ -692,6 +697,48 @@ class EmulatorLifecycleTest {
|
||||
verify(initLifecycleState).markReadyCompleted();
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresPersistedNeptuneClustersAfterStorageLoad() {
|
||||
stubStorageConfig();
|
||||
when(neptuneServiceConfig.enabled()).thenReturn(true);
|
||||
when(neptuneService.restorePersistedRuntime()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(storageFactory, neptuneService);
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
inOrder.verify(neptuneService).restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedNeptuneRestoreDoesNotStopTheOtherRestores() {
|
||||
stubStorageConfig();
|
||||
when(neptuneServiceConfig.enabled()).thenReturn(true);
|
||||
when(elbv2ServiceConfig.enabled()).thenReturn(true);
|
||||
when(neptuneService.restorePersistedRuntime()).thenReturn(CompletableFuture.failedFuture(
|
||||
new IllegalStateException("Could not restore Neptune cluster demo")));
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
verify(elbV2Service).restorePersistedRuntime();
|
||||
verify(initLifecycleState).markReadyCompleted();
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesNeptuneClustersUntouchedWhenNeptuneIsDisabled() {
|
||||
stubStorageConfig();
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
|
||||
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
verify(neptuneService, never()).restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesDocDbClustersUntouchedWhenDocDbIsDisabled() {
|
||||
stubStorageConfig();
|
||||
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
package io.floci.aws.services.neptune;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.neptune.container.NeptuneContainerHandle;
|
||||
import io.floci.aws.services.neptune.container.NeptuneContainerManager;
|
||||
import io.floci.aws.services.neptune.model.NeptuneCluster;
|
||||
import io.floci.aws.services.neptune.model.NeptuneInstance;
|
||||
import io.floci.aws.services.neptune.proxy.NeptuneProxyManager;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.WebSocket;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* #5664: a Neptune cluster comes back after Floci restarts with the graph it held, on the port it had. Shutdown stops
|
||||
* each cluster's proxy and container and keeps its volume; the startup restore starts a new container on it and the
|
||||
* proxy on the cluster's port again, so a vertex added before reads back through the same endpoint. Stopping the
|
||||
* proxies and containers, as shutdown does, stands in for the shutdown, reloading the records from disk for what a
|
||||
* restart reads back, and the restore is what startup calls. One cluster is in another account and Region, so the
|
||||
* restore is seen starting each in its own.
|
||||
*
|
||||
* <p>A Docker end-to-end check: it runs real Gremlin Server containers with the cluster records on disk, which the
|
||||
* shared test configuration keeps in memory.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(NeptuneClusterRestartDockerNightlyIntegrationTest.Profile.class)
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
@Timeout(value = 10, unit = TimeUnit.MINUTES)
|
||||
class NeptuneClusterRestartDockerNightlyIntegrationTest {
|
||||
|
||||
/** Real Gremlin Server containers, the cluster records on disk, and volumes removed with their clusters. */
|
||||
public static final class Profile implements QuarkusTestProfile {
|
||||
private static final String DATA = "./target/test-data/neptune-restart-" + UUID.randomUUID();
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.neptune.db-type", "gremlin",
|
||||
"floci.storage.mode", "persistent",
|
||||
"floci.storage.persistent-path", DATA,
|
||||
"floci.storage.prune-volumes-on-delete", "true");
|
||||
}
|
||||
}
|
||||
|
||||
private static final String FORM = "application/x-www-form-urlencoded";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String OTHER_ACCOUNT = "111111111111";
|
||||
private static final String OTHER_REGION = "eu-west-1";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
NeptuneService neptuneService;
|
||||
|
||||
@Inject
|
||||
NeptuneContainerManager containerManager;
|
||||
|
||||
@Inject
|
||||
NeptuneProxyManager proxyManager;
|
||||
|
||||
@Inject
|
||||
StorageFactory storageFactory;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
|
||||
"Docker daemon must be available for the Neptune restart check");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterKeepsItsGraphAndPortAcrossARestart() throws Exception {
|
||||
String id = "restart-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String instanceId = id + "-1";
|
||||
String defaultAuth = auth(ACCOUNT, REGION);
|
||||
String otherAuth = auth(OTHER_ACCOUNT, OTHER_REGION);
|
||||
try {
|
||||
call(defaultAuth, "CreateDBCluster", Map.of("DBClusterIdentifier", id, "Engine", "neptune"));
|
||||
call(defaultAuth, "CreateDBInstance", Map.of("DBInstanceIdentifier", instanceId,
|
||||
"DBClusterIdentifier", id, "DBInstanceClass", "db.r5.large", "Engine", "neptune"));
|
||||
call(otherAuth, "CreateDBCluster", Map.of("DBClusterIdentifier", id, "Engine", "neptune"));
|
||||
NeptuneCluster before = cluster(ACCOUNT, REGION, id);
|
||||
NeptuneCluster otherBefore = cluster(OTHER_ACCOUNT, OTHER_REGION, id);
|
||||
assertTrue(gremlin(before.getPort(), "g.addV('person').property('name','here').count()")
|
||||
.contains("\"code\":200"));
|
||||
assertTrue(gremlin(otherBefore.getPort(), "g.addV('person').property('name','elsewhere').count()")
|
||||
.contains("\"code\":200"));
|
||||
|
||||
for (NeptuneCluster cluster : new NeptuneCluster[] {before, otherBefore}) {
|
||||
String identity = identity(cluster, id);
|
||||
proxyManager.stopProxy(identity);
|
||||
containerManager.stop(new NeptuneContainerHandle(cluster.getContainerId(), identity,
|
||||
cluster.getContainerHost(), cluster.getContainerPort()));
|
||||
}
|
||||
storageFactory.create("neptune", "neptune-clusters.json",
|
||||
new TypeReference<Map<String, NeptuneCluster>>() {}).load();
|
||||
storageFactory.create("neptune", "neptune-instances.json",
|
||||
new TypeReference<Map<String, NeptuneInstance>>() {}).load();
|
||||
assertNotSame(before, cluster(ACCOUNT, REGION, id));
|
||||
neptuneService.restorePersistedRuntime().join();
|
||||
|
||||
NeptuneCluster after = cluster(ACCOUNT, REGION, id);
|
||||
assertEquals("available", after.getStatus());
|
||||
assertEquals(before.getPort(), after.getPort());
|
||||
assertNotEquals(before.getContainerId(), after.getContainerId());
|
||||
assertTrue(gremlin(after.getPort(), "g.V().has('person','name','here').values('name')")
|
||||
.contains("here"));
|
||||
NeptuneInstance instance = RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> neptuneService.getDbInstance(instanceId));
|
||||
assertEquals("available", instance.getStatus());
|
||||
assertEquals(after.getPort(), instance.getPort());
|
||||
NeptuneCluster otherAfter = cluster(OTHER_ACCOUNT, OTHER_REGION, id);
|
||||
assertEquals("available", otherAfter.getStatus());
|
||||
assertNotEquals(otherBefore.getContainerId(), otherAfter.getContainerId());
|
||||
assertTrue(gremlin(otherAfter.getPort(), "g.V().has('person','name','elsewhere').values('name')")
|
||||
.contains("elsewhere"));
|
||||
} finally {
|
||||
given().header("Authorization", defaultAuth).contentType(FORM)
|
||||
.formParam("Action", "DeleteDBInstance").formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("SkipFinalSnapshot", "true").when().post("/");
|
||||
for (String auth : new String[] {defaultAuth, otherAuth}) {
|
||||
given().header("Authorization", auth).contentType(FORM)
|
||||
.formParam("Action", "DeleteDBCluster").formParam("DBClusterIdentifier", id)
|
||||
.formParam("SkipFinalSnapshot", "true").when().post("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private NeptuneCluster cluster(String account, String region, String id) {
|
||||
return RequestScopes.callAs(account, region, () -> neptuneService.getDbCluster(id));
|
||||
}
|
||||
|
||||
private static String identity(NeptuneCluster cluster, String id) {
|
||||
String[] arn = cluster.getDbClusterArn().split(":");
|
||||
return arn[4] + "-" + arn[3] + "-" + id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates {@code script} through the cluster's port, as a GraphSON text frame over Gremlin Server's WebSocket
|
||||
* endpoint, and returns the response frame, once the server answers.
|
||||
*/
|
||||
private static String gremlin(int port, String script) {
|
||||
String request = """
|
||||
{"requestId":"%s","op":"eval","processor":"","args":{"gremlin":"%s","language":"gremlin-groovy"}}"""
|
||||
.formatted(UUID.randomUUID(), script);
|
||||
return await("gremlin answer").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(2))
|
||||
.ignoreExceptions()
|
||||
.until(() -> send(port, request), response -> response.contains("\"status\""));
|
||||
}
|
||||
|
||||
private static String send(int port, String request) throws Exception {
|
||||
CompletableFuture<String> response = new CompletableFuture<>();
|
||||
StringBuilder text = new StringBuilder();
|
||||
WebSocket socket = HttpClient.newHttpClient().newWebSocketBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.buildAsync(URI.create("ws://localhost:" + port + "/gremlin"), new WebSocket.Listener() {
|
||||
@Override
|
||||
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
|
||||
text.append(data);
|
||||
if (last) {
|
||||
response.complete(text.toString());
|
||||
}
|
||||
webSocket.request(1);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(WebSocket webSocket, Throwable error) {
|
||||
response.completeExceptionally(error);
|
||||
}
|
||||
})
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
try {
|
||||
socket.sendText(request, true).get(10, TimeUnit.SECONDS);
|
||||
return response.get(30, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
socket.abort();
|
||||
}
|
||||
}
|
||||
|
||||
private static String call(String auth, String action, Map<String, String> params) {
|
||||
return given().header("Authorization", auth).contentType(FORM).formParam("Action", action)
|
||||
.formParams(params)
|
||||
.when().post("/")
|
||||
.then().statusCode(200).extract().asString();
|
||||
}
|
||||
|
||||
private static String auth(String account, String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account + "/20260516/" + region + "/neptune/aws4_request, "
|
||||
+ "SignedHeaders=content-type;host, Signature=test";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,698 @@
|
||||
package io.floci.aws.services.neptune;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.neptune.container.NeptuneContainerHandle;
|
||||
import io.floci.aws.services.neptune.container.NeptuneContainerManager;
|
||||
import io.floci.aws.services.neptune.model.NeptuneCluster;
|
||||
import io.floci.aws.services.neptune.model.NeptuneDbType;
|
||||
import io.floci.aws.services.neptune.model.NeptuneInstance;
|
||||
import io.floci.aws.services.neptune.proxy.NeptuneProxyManager;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
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.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
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;
|
||||
|
||||
/** #5664: a Neptune cluster's container and proxy come back when Floci restarts, on its volume and its port. */
|
||||
class NeptuneRestartTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String GREMLIN_IMAGE = "tinkerpop/gremlin-server:3.7";
|
||||
private static final String NEO4J_IMAGE = "neo4j:5";
|
||||
|
||||
private final AtomicInteger started = new AtomicInteger();
|
||||
private final AtomicBoolean shuttingDown = new AtomicBoolean();
|
||||
/** The stores a restarted service reads back, by file. */
|
||||
private final Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
|
||||
/** The cluster whose marking for the restore the cluster store refuses to write. */
|
||||
private volatile String refuseMarking;
|
||||
/** A cluster and status, {@code id:status}, the cluster store refuses to write once. */
|
||||
private volatile String refuse;
|
||||
/** Runs once, inside the next read of instance {@code c-1}. */
|
||||
private volatile Runnable onInstanceRead;
|
||||
/** An instance and status, {@code id:status}, the instance store refuses to write once. */
|
||||
private volatile String refuseInstance;
|
||||
private volatile String dbType = "gremlin";
|
||||
private EmulatorConfig config;
|
||||
private RegionResolver regionResolver;
|
||||
private StorageFactory storageFactory;
|
||||
private NeptuneContainerManager containers;
|
||||
private NeptuneProxyManager proxies;
|
||||
private NeptuneService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
when(regionResolver.getRegion()).thenReturn(REGION);
|
||||
when(regionResolver.getDefaultRegion()).thenReturn(REGION);
|
||||
when(regionResolver.getDefaultAccountId()).thenReturn(ACCOUNT);
|
||||
when(regionResolver.buildArn(anyString(), anyString(), anyString())).thenAnswer(inv ->
|
||||
"arn:aws:" + inv.getArgument(0) + ":" + inv.getArgument(1) + ":" + ACCOUNT + ":"
|
||||
+ inv.getArgument(2));
|
||||
|
||||
config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.NeptuneServiceConfig neptuneConfig = mock(EmulatorConfig.NeptuneServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.neptune()).thenReturn(neptuneConfig);
|
||||
when(neptuneConfig.proxyBasePort()).thenReturn(18182);
|
||||
when(neptuneConfig.proxyMaxPort()).thenReturn(18199);
|
||||
when(neptuneConfig.dbType()).thenAnswer(inv -> dbType);
|
||||
when(neptuneConfig.defaultImage()).thenReturn(GREMLIN_IMAGE);
|
||||
when(neptuneConfig.defaultNeo4jImage()).thenReturn(NEO4J_IMAGE);
|
||||
when(config.hostname()).thenReturn(Optional.of("localhost"));
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
EmulatorConfig.ServiceStorageOverrides overrides = mock(EmulatorConfig.ServiceStorageOverrides.class);
|
||||
EmulatorConfig.NeptuneStorageConfig neptuneStorage = mock(EmulatorConfig.NeptuneStorageConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(storage.mode()).thenReturn("persistent");
|
||||
when(storage.services()).thenReturn(overrides);
|
||||
when(overrides.neptune()).thenReturn(neptuneStorage);
|
||||
when(neptuneStorage.mode()).thenReturn(Optional.empty());
|
||||
|
||||
storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
|
||||
stores.computeIfAbsent(inv.getArgument(1), file -> switch (file) {
|
||||
case "neptune-clusters.json" -> new AccountAwareStorageBackend<>(new ClusterStore(), null, ACCOUNT);
|
||||
case "neptune-instances.json" -> new AccountAwareStorageBackend<>(new InstanceStore(), null,
|
||||
ACCOUNT);
|
||||
default -> AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
}));
|
||||
|
||||
containers = mock(NeptuneContainerManager.class);
|
||||
proxies = mock(NeptuneProxyManager.class);
|
||||
startsContainers();
|
||||
when(containers.isShuttingDown()).thenAnswer(inv -> shuttingDown.get());
|
||||
service = new NeptuneService(config, regionResolver, containers, proxies, storageFactory);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersContainerAndProxyComeBackOnItsVolumeAndPort() {
|
||||
NeptuneCluster cluster = service.createDbCluster("c", null, false);
|
||||
service.createDbInstance("c-1", "c", null, null, false);
|
||||
clearInvocations(containers, proxies);
|
||||
|
||||
restarted().restorePersistedRuntime().join();
|
||||
|
||||
verify(containers).tryStart("c", GREMLIN_IMAGE, NeptuneDbType.GREMLIN, ACCOUNT, REGION, cluster.getVolumeId());
|
||||
verify(proxies).startProxy(identity("c"), cluster.getProxyPort(), "localhost", 40002);
|
||||
NeptuneCluster restored = service.getDbCluster("c");
|
||||
assertEquals("available", restored.getStatus());
|
||||
assertEquals("container-2", restored.getContainerId());
|
||||
assertEquals(cluster.getProxyPort(), restored.getPort());
|
||||
assertEquals("available", service.getDbInstance("c-1").getStatus());
|
||||
assertEquals(cluster.getProxyPort(), service.getDbInstance("c-1").getPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterComesBackInTheEngineItsGraphWasKeptIn() {
|
||||
NeptuneCluster gremlin = service.createDbCluster("gremlin", null, false);
|
||||
NeptuneCluster older = service.createDbCluster("older", null, false);
|
||||
older.setDbType(null);
|
||||
dbType = "neo4j";
|
||||
clearInvocations(containers);
|
||||
|
||||
restarted().restorePersistedRuntime().join();
|
||||
|
||||
verify(containers).tryStart("gremlin", GREMLIN_IMAGE, NeptuneDbType.GREMLIN, ACCOUNT, REGION,
|
||||
gremlin.getVolumeId());
|
||||
verify(containers).tryStart("older", NEO4J_IMAGE, NeptuneDbType.NEO4J, ACCOUNT, REGION, older.getVolumeId());
|
||||
assertEquals(NeptuneDbType.NEO4J, service.getDbCluster("older").getDbType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterIsInMaintenanceAndItsInstancesStartingWhileItsContainerComesBack() throws Exception {
|
||||
service.createDbCluster("c", null, false);
|
||||
service.createDbInstance("c-1", "c", null, null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
assertEquals("maintenance", service.getDbCluster("c").getStatus());
|
||||
assertEquals("starting", service.getDbInstance("c-1").getStatus());
|
||||
release.countDown();
|
||||
restore.join();
|
||||
|
||||
assertEquals("available", service.getDbCluster("c").getStatus());
|
||||
assertEquals("available", service.getDbInstance("c-1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withNoDockerDaemonAClusterComesBackWithoutAContainer() {
|
||||
service.createDbCluster("c", null, false);
|
||||
service.createDbInstance("c-1", "c", null, null, false);
|
||||
doReturn(null).when(containers).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
clearInvocations(proxies);
|
||||
|
||||
service.restorePersistedRuntime().join();
|
||||
|
||||
assertEquals("available", service.getDbCluster("c").getStatus());
|
||||
assertNull(service.getDbCluster("c").getContainerId());
|
||||
assertEquals("available", service.getDbInstance("c-1").getStatus());
|
||||
verify(proxies, never()).startProxy(anyString(), anyInt(), anyString(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWhoseContainerDoesNotStartIsLeftWithoutOneAndTriedAgainAtTheNextStart() {
|
||||
service.createDbCluster("bad", null, false);
|
||||
service.createDbInstance("bad-1", "bad", null, null, false);
|
||||
service.createDbCluster("good", null, false);
|
||||
doThrow(new IllegalStateException("no such image"))
|
||||
.when(containers).tryStart(eq("bad"), anyString(), any(), anyString(), anyString(), any());
|
||||
|
||||
CompletionException failure = assertThrows(CompletionException.class,
|
||||
() -> service.restorePersistedRuntime().join());
|
||||
|
||||
assertTrue(failure.getCause().getMessage().contains("bad"), failure.getCause().getMessage());
|
||||
assertEquals("available", service.getDbCluster("good").getStatus());
|
||||
assertNull(service.getDbCluster("bad").getContainerId());
|
||||
assertEquals("failed", service.getDbInstance("bad-1").getStatus());
|
||||
verify(containers).stopByClusterId(identity("bad"));
|
||||
|
||||
startsContainers();
|
||||
service.restorePersistedRuntime().join();
|
||||
assertNotNull(service.getDbCluster("bad").getContainerId());
|
||||
assertEquals("available", service.getDbInstance("bad-1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWhoseProxyDoesNotStartHasItsNewContainerRemoved() {
|
||||
service.createDbCluster("c", null, false);
|
||||
service.createDbInstance("c-1", "c", null, null, false);
|
||||
doThrow(new IllegalStateException("port in use"))
|
||||
.when(proxies).startProxy(anyString(), anyInt(), anyString(), anyInt());
|
||||
|
||||
assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join());
|
||||
|
||||
verify(containers).stopByClusterId(identity("c"));
|
||||
assertNull(service.getDbCluster("c").getContainerId());
|
||||
assertEquals("failed", service.getDbInstance("c-1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoredClustersPortIsHeldForItFromTheStart() throws Exception {
|
||||
int stored = service.createDbCluster("stored", null, false).getProxyPort();
|
||||
NeptuneService restarted = restarted();
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
doReturn(new NeptuneContainerHandle("container-new", identity("new"), "localhost", 49999))
|
||||
.when(containers).tryStart(eq("new"), anyString(), any(), anyString(), anyString(), any());
|
||||
|
||||
CompletableFuture<Void> restore = restarted.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
int created = restarted.createDbCluster("new", null, false).getProxyPort();
|
||||
release.countDown();
|
||||
restore.join();
|
||||
|
||||
assertNotEquals(stored, created);
|
||||
assertEquals(stored, restarted.getDbCluster("stored").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWhosePortAnotherHoldsMovesToAFreeOne() {
|
||||
NeptuneCluster first = service.createDbCluster("first", null, false);
|
||||
NeptuneCluster second = service.createDbCluster("second", null, false);
|
||||
service.createDbInstance("first-1", "first", null, null, false);
|
||||
service.createDbInstance("second-1", "second", null, null, false);
|
||||
second.setProxyPort(first.getProxyPort());
|
||||
second.setPort(first.getProxyPort());
|
||||
clearInvocations(proxies);
|
||||
|
||||
restarted().restorePersistedRuntime().join();
|
||||
|
||||
assertNotEquals(service.getDbCluster("first").getProxyPort(), service.getDbCluster("second").getProxyPort());
|
||||
for (String id : List.of("first", "second")) {
|
||||
NeptuneCluster cluster = service.getDbCluster(id);
|
||||
assertEquals(cluster.getProxyPort(), cluster.getPort(), id);
|
||||
assertEquals(cluster.getProxyPort(), service.getDbInstance(id + "-1").getPort(), id);
|
||||
verify(proxies).startProxy(eq(identity(id)), eq(cluster.getProxyPort()), anyString(), anyInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreThatFailsOnceItsProxyHasStartedStopsItAndItsContainer() {
|
||||
service.createDbCluster("c", null, false);
|
||||
service.createDbInstance("c-1", "c", null, null, false);
|
||||
refuse = "c:available";
|
||||
clearInvocations(proxies, containers);
|
||||
|
||||
assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join());
|
||||
|
||||
verify(proxies).startProxy(eq(identity("c")), anyInt(), anyString(), anyInt());
|
||||
verify(proxies).stopProxy(identity("c"));
|
||||
verify(containers).stopByClusterId(identity("c"));
|
||||
assertNull(service.getDbCluster("c").getContainerId());
|
||||
assertEquals("failed", service.getDbInstance("c-1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceMovedToAnotherClusterDuringTheRestoreKeepsThatClustersPort() throws Exception {
|
||||
service.createDbCluster("c", null, false);
|
||||
service.createDbInstance("c-1", "c", null, null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
doReturn(new NeptuneContainerHandle("container-d", identity("d"), "localhost", 49999))
|
||||
.when(containers).tryStart(eq("d"), anyString(), any(), anyString(), anyString(), any());
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
int dPort = service.createDbCluster("d", null, false).getProxyPort();
|
||||
onInstanceRead = () -> {
|
||||
service.deleteDbInstance("c-1");
|
||||
service.createDbInstance("c-1", "d", null, null, false);
|
||||
};
|
||||
release.countDown();
|
||||
restore.join();
|
||||
|
||||
assertEquals("d", service.getDbInstance("c-1").getDbClusterIdentifier());
|
||||
assertEquals(dPort, service.getDbInstance("c-1").getPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterRecordedBeforeItsGraphWasKeptGetsAVolumeKeptEvenWhenTheStartFails() {
|
||||
NeptuneCluster cluster = service.createDbCluster("c", null, false);
|
||||
cluster.setVolumeId(null);
|
||||
doThrow(new IllegalStateException("no such image"))
|
||||
.when(containers).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
clearInvocations(containers);
|
||||
|
||||
assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join());
|
||||
|
||||
String given = service.getDbCluster("c").getVolumeId();
|
||||
assertNotNull(given);
|
||||
verify(containers).tryStart(eq("c"), anyString(), any(), anyString(), anyString(), eq(given));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeleteFlociDidNotLiveToFinishIsFinishedInTheBackground() {
|
||||
NeptuneCluster cluster = service.createDbCluster("gone", null, false);
|
||||
cluster.setStatus("deleting");
|
||||
NeptuneService restarted = restarted();
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(inv -> {
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
return null;
|
||||
}).when(containers).stop(any());
|
||||
clearInvocations(containers);
|
||||
|
||||
CompletableFuture<Void> restore = assertTimeoutPreemptively(Duration.ofSeconds(5),
|
||||
restarted::restorePersistedRuntime);
|
||||
release.countDown();
|
||||
restore.join();
|
||||
|
||||
assertFalse(restarted.hasCluster("gone"));
|
||||
verify(containers).stop(argThat(handle -> cluster.getContainerId().equals(handle.getContainerId())));
|
||||
verify(containers).removeStorage(cluster.getVolumeId());
|
||||
verify(containers, never()).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
assertEquals(cluster.getProxyPort(), restarted.createDbCluster("next", null, false).getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterDeletedDuringItsRestoreGoesOnceItsContainerHasStarted() throws Exception {
|
||||
NeptuneCluster cluster = service.createDbCluster("c", null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
clearInvocations(proxies);
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
service.deleteDbCluster("c");
|
||||
service.deleteDbCluster("c");
|
||||
assertEquals("deleting", service.getDbCluster("c").getStatus());
|
||||
verify(containers, never()).removeStorage(any());
|
||||
release.countDown();
|
||||
restore.join();
|
||||
|
||||
assertFalse(service.hasCluster("c"));
|
||||
verify(containers).stop(argThat(handle -> "container-2".equals(handle.getContainerId())));
|
||||
verify(containers).removeStorage(cluster.getVolumeId());
|
||||
verify(proxies, never()).startProxy(anyString(), anyInt(), anyString(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterDeletedWhileItsStartFailsIsStillRemoved() throws Exception {
|
||||
service.createDbCluster("c", null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(inv -> {
|
||||
starting.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
throw new IllegalStateException("no such image");
|
||||
}).when(containers).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
service.deleteDbCluster("c");
|
||||
release.countDown();
|
||||
|
||||
assertThrows(CompletionException.class, restore::join);
|
||||
assertFalse(service.hasCluster("c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noInstanceJoinsAClusterWhileItsContainerComesBackOrItWaitsToBeDeleted() throws Exception {
|
||||
service.createDbCluster("c", null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
AwsException whileStarting = assertThrows(AwsException.class,
|
||||
() -> service.createDbInstance("c-1", "c", null, null, false));
|
||||
service.deleteDbCluster("c");
|
||||
AwsException whileDeleting = assertThrows(AwsException.class,
|
||||
() -> service.createDbInstance("c-1", "c", null, null, false));
|
||||
release.countDown();
|
||||
restore.join();
|
||||
|
||||
for (AwsException refused : List.of(whileStarting, whileDeleting)) {
|
||||
assertEquals("InvalidDBClusterStateFault", refused.getErrorCode());
|
||||
assertEquals(400, refused.getHttpStatus());
|
||||
}
|
||||
assertFalse(service.hasInstance("c-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterReplacedDuringItsRestoreKeepsItsOwnRecord() throws Exception {
|
||||
NeptuneCluster cluster = service.createDbCluster("c", null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
NeptuneCluster replacement = new NeptuneCluster();
|
||||
replacement.setDbClusterIdentifier("c");
|
||||
replacement.setDbClusterArn(cluster.getDbClusterArn());
|
||||
replacement.setDbClusterResourceId("cluster-REPLACEMENT");
|
||||
replacement.setStatus("available");
|
||||
replacement.setContainerId("replacement-container");
|
||||
clusters().putForAccount(ACCOUNT, REGION + "/c", replacement);
|
||||
release.countDown();
|
||||
restore.join();
|
||||
|
||||
assertEquals("replacement-container", service.getDbCluster("c").getContainerId());
|
||||
verify(containers).stop(argThat(handle -> "container-2".equals(handle.getContainerId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShutdownDuringTheRestoreLeavesTheClustersForTheNextStart() {
|
||||
service.createDbCluster("first", null, false);
|
||||
service.createDbInstance("first-1", "first", null, null, false);
|
||||
service.createDbCluster("second", null, false);
|
||||
service.createDbInstance("second-1", "second", null, null, false);
|
||||
clearInvocations(containers);
|
||||
doAnswer(inv -> {
|
||||
shuttingDown.set(true);
|
||||
throw new IllegalStateException("Neptune is shutting down");
|
||||
}).when(containers).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
|
||||
service.restorePersistedRuntime().join();
|
||||
|
||||
verify(containers, times(1)).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
for (String id : List.of("first", "second")) {
|
||||
assertEquals("maintenance", service.getDbCluster(id).getStatus());
|
||||
assertEquals("starting", service.getDbInstance(id + "-1").getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterThatCannotBeMarkedIsReportedWithoutStoppingStartupOrTheOthers() {
|
||||
service.createDbCluster("broken", null, false);
|
||||
service.createDbCluster("good", null, false);
|
||||
refuseMarking = "broken";
|
||||
clearInvocations(containers);
|
||||
|
||||
CompletionException failure = assertThrows(CompletionException.class,
|
||||
() -> service.restorePersistedRuntime().join());
|
||||
|
||||
assertTrue(failure.getCause().getMessage().contains("broken"), failure.getCause().getMessage());
|
||||
assertEquals("available", service.getDbCluster("good").getStatus());
|
||||
verify(containers, never()).tryStart(eq("broken"), anyString(), any(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreInTheSameProcessKeepsEachClustersPort() {
|
||||
int port = service.createDbCluster("c", null, false).getProxyPort();
|
||||
|
||||
service.restorePersistedRuntime().join();
|
||||
|
||||
assertEquals(port, service.getDbCluster("c").getProxyPort());
|
||||
verify(proxies).startProxy(identity("c"), port, "localhost", 40002);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeleteLeftDeletingWithNoRestoreRunningIsRetriedAtOnce() {
|
||||
NeptuneCluster cluster = service.createDbCluster("c", null, false);
|
||||
cluster.setStatus("deleting");
|
||||
|
||||
service.deleteDbCluster("c");
|
||||
|
||||
assertFalse(service.hasCluster("c"));
|
||||
verify(containers).removeStorage(cluster.getVolumeId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceDeletedWhileTheRestoreWritesItsStatusStaysDeleted() throws Exception {
|
||||
service.createDbCluster("c", null, false);
|
||||
NeptuneInstance created = service.createDbInstance("c-1", "c", null, null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
Thread[] deleter = new Thread[1];
|
||||
// The restore read this instance and is setting its status, between the read and the write.
|
||||
StatusHookedInstance instance = new StatusHookedInstance(created, () -> {
|
||||
deleter[0] = new Thread(() -> service.deleteDbInstance("c-1"));
|
||||
deleter[0].start();
|
||||
// The delete either waits for the instance the restore is writing, or, with nothing to stop it, is done.
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> deleter[0].getState() == Thread.State.BLOCKED
|
||||
|| deleter[0].getState() == Thread.State.TERMINATED);
|
||||
});
|
||||
instances().putForAccount(ACCOUNT, REGION + "/c-1", instance);
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
instance.arm();
|
||||
release.countDown();
|
||||
restore.join();
|
||||
deleter[0].join(10_000);
|
||||
|
||||
assertFalse(service.hasInstance("c-1"));
|
||||
}
|
||||
|
||||
/** An instance that runs a hook, once armed, when the restore makes it available. */
|
||||
private static final class StatusHookedInstance extends NeptuneInstance {
|
||||
private final Runnable hook;
|
||||
private volatile boolean armed;
|
||||
|
||||
StatusHookedInstance(NeptuneInstance from, Runnable hook) {
|
||||
this.hook = hook;
|
||||
setDbInstanceIdentifier(from.getDbInstanceIdentifier());
|
||||
setDbClusterIdentifier(from.getDbClusterIdentifier());
|
||||
setDbInstanceArn(from.getDbInstanceArn());
|
||||
setEndpoint(from.getEndpoint());
|
||||
setPort(from.getPort());
|
||||
super.setStatus(from.getStatus());
|
||||
}
|
||||
|
||||
void arm() {
|
||||
armed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStatus(String status) {
|
||||
super.setStatus(status);
|
||||
if (armed && "available".equals(status)) {
|
||||
armed = false;
|
||||
hook.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void endingARestoreAnyWayLeavesLaterDeletesToRemoveTheClusterAtOnce() throws Exception {
|
||||
service.createDbCluster("gone", null, false);
|
||||
CountDownLatch starting = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
blockStarts(starting, release);
|
||||
|
||||
CompletableFuture<Void> restore = service.restorePersistedRuntime();
|
||||
assertTrue(starting.await(10, TimeUnit.SECONDS));
|
||||
clusters().deleteForAccount(ACCOUNT, REGION + "/gone");
|
||||
release.countDown();
|
||||
restore.join();
|
||||
startsContainers();
|
||||
service.createDbCluster("gone", null, false);
|
||||
service.deleteDbCluster("gone");
|
||||
|
||||
assertFalse(service.hasCluster("gone"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWhoseInstancesCannotBeMarkedLeavesLaterDeletesToRemoveItAtOnce() {
|
||||
service.createDbCluster("c", null, false);
|
||||
service.createDbInstance("c-1", "c", null, null, false);
|
||||
refuseInstance = "c-1:starting";
|
||||
clearInvocations(containers);
|
||||
|
||||
assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join());
|
||||
service.deleteDbInstance("c-1");
|
||||
service.deleteDbCluster("c");
|
||||
|
||||
assertFalse(service.hasCluster("c"));
|
||||
verify(containers, never()).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShutdownDuringTheRestoreLeavesLaterDeletesToRemoveTheClustersAtOnce() {
|
||||
service.createDbCluster("first", null, false);
|
||||
service.createDbCluster("second", null, false);
|
||||
doAnswer(inv -> {
|
||||
shuttingDown.set(true);
|
||||
throw new IllegalStateException("Neptune is shutting down");
|
||||
}).when(containers).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
|
||||
service.restorePersistedRuntime().join();
|
||||
service.deleteDbCluster("first");
|
||||
service.deleteDbCluster("second");
|
||||
|
||||
assertFalse(service.hasCluster("first"));
|
||||
assertFalse(service.hasCluster("second"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletesAfterARestoreOrAFailedOneRemoveTheClusterAtOnce() {
|
||||
service.createDbCluster("restored", null, false);
|
||||
service.createDbCluster("failed", null, false);
|
||||
doThrow(new IllegalStateException("no such image"))
|
||||
.when(containers).tryStart(eq("failed"), anyString(), any(), anyString(), anyString(), any());
|
||||
assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join());
|
||||
|
||||
service.deleteDbCluster("restored");
|
||||
service.deleteDbCluster("failed");
|
||||
|
||||
assertFalse(service.hasCluster("restored"));
|
||||
assertFalse(service.hasCluster("failed"));
|
||||
}
|
||||
|
||||
/** A service over the same stores, as Floci reads them back after a restart, holding no ports yet. */
|
||||
private NeptuneService restarted() {
|
||||
service = new NeptuneService(config, regionResolver, containers, proxies, storageFactory);
|
||||
return service;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AccountAwareStorageBackend<NeptuneCluster> clusters() {
|
||||
return (AccountAwareStorageBackend<NeptuneCluster>) stores.get("neptune-clusters.json");
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AccountAwareStorageBackend<NeptuneInstance> instances() {
|
||||
return (AccountAwareStorageBackend<NeptuneInstance>) stores.get("neptune-instances.json");
|
||||
}
|
||||
|
||||
private static String identity(String id) {
|
||||
return ACCOUNT + "-" + REGION + "-" + id;
|
||||
}
|
||||
|
||||
/** Each start gives a container of its own, numbered in start order, its port after it. */
|
||||
private void startsContainers() {
|
||||
doAnswer(inv -> {
|
||||
int n = started.incrementAndGet();
|
||||
return new NeptuneContainerHandle("container-" + n, inv.getArgument(0), "localhost", 40000 + n);
|
||||
}).when(containers).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
/** Starts that signal {@code starting} and wait for {@code release} before giving their container. */
|
||||
private void blockStarts(CountDownLatch starting, CountDownLatch release) {
|
||||
doAnswer(inv -> {
|
||||
starting.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
int n = started.incrementAndGet();
|
||||
return new NeptuneContainerHandle("container-" + n, inv.getArgument(0), "localhost", 40000 + n);
|
||||
}).when(containers).tryStart(anyString(), anyString(), any(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
/** The cluster store, which a test can have refuse to mark a cluster for the restore. */
|
||||
private final class ClusterStore extends InMemoryStorage<String, NeptuneCluster> {
|
||||
@Override
|
||||
public synchronized void put(String key, NeptuneCluster value) {
|
||||
if ("maintenance".equals(value.getStatus()) && value.getDbClusterIdentifier().equals(refuseMarking)) {
|
||||
throw new IllegalStateException("the cluster store refused the write");
|
||||
}
|
||||
if ((value.getDbClusterIdentifier() + ":" + value.getStatus()).equals(refuse)) {
|
||||
refuse = null;
|
||||
throw new IllegalStateException("the cluster store refused the write");
|
||||
}
|
||||
super.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/** The instance store, which a test can have refuse a write or act inside a read of. */
|
||||
private final class InstanceStore extends InMemoryStorage<String, NeptuneInstance> {
|
||||
@Override
|
||||
public synchronized void put(String key, NeptuneInstance value) {
|
||||
if ((value.getDbInstanceIdentifier() + ":" + value.getStatus()).equals(refuseInstance)) {
|
||||
refuseInstance = null;
|
||||
throw new IllegalStateException("the instance store refused the write");
|
||||
}
|
||||
super.put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<NeptuneInstance> get(String key) {
|
||||
Runnable hook = onInstanceRead;
|
||||
if (hook != null && key.endsWith(REGION + "/c-1")) {
|
||||
onInstanceRead = null;
|
||||
hook.run();
|
||||
}
|
||||
return super.get(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
@@ -19,6 +19,7 @@ import org.junit.jupiter.api.parallel.ResourceAccessMode;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -31,6 +32,7 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -40,6 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -313,6 +316,56 @@ class NeptuneContainerManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noContainerStartsOnceShutdownHasBegun() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
NeptuneContainerManager manager = newManager(lifecycle);
|
||||
|
||||
manager.stopAll();
|
||||
|
||||
assertTrue(manager.isShuttingDown());
|
||||
assertThrows(IllegalStateException.class, () -> manager.start("cluster1", "tinkerpop/gremlin-server:3.7.3",
|
||||
NeptuneDbType.GREMLIN, "000000000000", "us-east-1", null));
|
||||
verify(lifecycle, never()).createAndStart(any(ContainerSpec.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStartThatShutdownOvertakesFailsWithItsContainerLeftToRemoveByIdentity() throws IOException {
|
||||
try (ServerSocket backend = backend(GREMLIN_REPLY)) {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
AtomicReference<NeptuneContainerManager> shutDownBy = new AtomicReference<>();
|
||||
when(lifecycle.createAndStart(any(ContainerSpec.class))).thenAnswer(call -> {
|
||||
shutDownBy.get().stopAll();
|
||||
return info(backend, 8182);
|
||||
});
|
||||
NeptuneContainerManager manager = newManager(lifecycle);
|
||||
shutDownBy.set(manager);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start("cluster1",
|
||||
"tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, "000000000000", "us-east-1", null));
|
||||
manager.stopByClusterId("000000000000-us-east-1-cluster1");
|
||||
|
||||
verify(lifecycle).stopAndRemove(eq("container-id"), any(), eq(30));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContainerLeftUnderTheNameStopsCleanlyBeforeTheNewOneStarts() throws IOException {
|
||||
try (ServerSocket backend = backend(GREMLIN_REPLY)) {
|
||||
ContainerLifecycleManager lifecycle = startsOn(backend, 8182);
|
||||
NeptuneContainerManager manager = newManager(lifecycle, mock(ContainerBuilder.Builder.class,
|
||||
Mockito.RETURNS_SELF), storage("persistent", null, false));
|
||||
|
||||
manager.start("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, "000000000000",
|
||||
"us-east-1", null);
|
||||
|
||||
InOrder order = Mockito.inOrder(lifecycle);
|
||||
order.verify(lifecycle).stopAndRemove("floci-aws-neptune-000000000000-us-east-1-cluster1", null, 30);
|
||||
order.verify(lifecycle).createAndStart(any(ContainerSpec.class));
|
||||
verify(lifecycle, never()).removeIfExists(anyString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContainerHasTimeToSaveItsGraphWhenItStops() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
|
||||
Reference in new issue
Block a user