mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(memorydb): restore persistent cluster runtimes after restart (#7540)
* fix(memorydb): restore persistent cluster runtimes after restart Restore account-scoped cluster backends, authentication and stable proxy endpoints from persisted metadata. Retain data storage across restart and preserve retryable ownership on failed provisioning cleanup. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(memorydb): retain default backend and log names Keep default-account/default-region container and engine-log names stable while retaining scoped runtime and proxy keys. Pass the logical name and stored owner through creation, restoration, deletion and rollback. Use an unambiguous separator for foreign Docker names in the retained hyphen-prefix collision case, without changing foreign log names or persisted volume identities. Preserve restore and cleanup coverage; new naming regressions fail the former manager. Local mocked-Docker and loopback RESP qualification only, no managed AWS or native runtime claim. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * test(memorydb): share container naming fixtures Move the two naming cases into MemoryDbContainerManagerTest and reuse its manager setup. Share the four loopback PONG responders through one helper, observing completion and propagating responder failures. Preserve naming, collision, cleanup and lifecycle assertions. No production change. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> --------- Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
7b3f5812e2
commit
87c7a9ce7d
10 files changed
+1389
-134
No files matched your search
@@ -40,6 +40,35 @@ Set `FLOCI_SERVICES_MEMORYDB_MOCK=true` to manage clusters as control-plane-only
|
||||
| `FLOCI_SERVICES_MEMORYDB_PROXY_MAX_PORT` | `6419` | Last host port in the MemoryDB proxy range |
|
||||
| `FLOCI_SERVICES_MEMORYDB_DEFAULT_IMAGE` | `valkey/valkey:8` | Docker image for Redis/Valkey containers |
|
||||
|
||||
### Persistence and restart
|
||||
|
||||
With `FLOCI_STORAGE_MODE=persistent`, `hybrid`, or `wal`, MemoryDB stores backend data
|
||||
in a per-cluster volume or the configured host persistent path. Redis/Valkey uses
|
||||
an append-only file with synchronous writes. Persist Floci's metadata directory
|
||||
as well as backend storage to restore the cluster after restarting Floci.
|
||||
|
||||
Startup reserves each cluster's proxy port and restores its backend and authentication
|
||||
under the stored account and region. A cluster is `creating` while its backend starts.
|
||||
Restoration failures are logged and do not leave a reachable-Docker failure advertised
|
||||
as `available`. As on creation, an unreachable Docker daemon permits metadata-only
|
||||
operation; mock mode starts no backend.
|
||||
|
||||
Clusters in the configured default account and region keep the short Docker name
|
||||
`floci-aws-memorydb-<name>` and engine log group
|
||||
`/aws/memorydb/cluster/<name>/engine-log`. Internal runtime and proxy keys remain
|
||||
account- and region-scoped. Other scopes use `<account>_<region>_<name>` in Docker
|
||||
names to distinguish them from default-scope cluster names containing the old
|
||||
hyphenated owner prefix. Docker resource namespaces still apply.
|
||||
|
||||
Named volumes follow `FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE`. Recreating a deleted
|
||||
cluster uses fresh storage even when its previous volume was retained. Memory storage
|
||||
mode remains ephemeral. Previously unpersisted data cannot be recovered from metadata.
|
||||
|
||||
Legacy metadata migrates using its stored account and ARN region. Existing scoped
|
||||
records take precedence. Conflicting legacy records remain in the metadata snapshot
|
||||
under the owning account's `legacy-clusters/` keys for manual recovery and are not
|
||||
started. Contradictory ownership is reported without allocating a backend.
|
||||
|
||||
### Docker Compose
|
||||
|
||||
MemoryDB requires the Docker socket and port range exposure. For private registry authentication and other Docker settings see [Docker Configuration](../configuration/docker.md).
|
||||
|
||||
@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoll
|
||||
import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService;
|
||||
import io.github.hectorvent.floci.services.memorydb.MemoryDbService;
|
||||
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager;
|
||||
@@ -92,6 +93,7 @@ public class EmulatorLifecycle {
|
||||
private final RdsProxyManager rdsProxyManager;
|
||||
private final MemoryDbContainerManager memoryDbContainerManager;
|
||||
private final MemoryDbProxyManager memoryDbProxyManager;
|
||||
private final MemoryDbService memoryDbService;
|
||||
private final DocDbContainerManager docDbContainerManager;
|
||||
private final NeptuneContainerManager neptuneContainerManager;
|
||||
private final NeptuneProxyManager neptuneProxyManager;
|
||||
@@ -136,6 +138,7 @@ public class EmulatorLifecycle {
|
||||
RdsProxyManager rdsProxyManager,
|
||||
MemoryDbContainerManager memoryDbContainerManager,
|
||||
MemoryDbProxyManager memoryDbProxyManager,
|
||||
MemoryDbService memoryDbService,
|
||||
DocDbContainerManager docDbContainerManager,
|
||||
NeptuneContainerManager neptuneContainerManager,
|
||||
NeptuneProxyManager neptuneProxyManager,
|
||||
@@ -177,6 +180,7 @@ public class EmulatorLifecycle {
|
||||
this.rdsProxyManager = rdsProxyManager;
|
||||
this.memoryDbContainerManager = memoryDbContainerManager;
|
||||
this.memoryDbProxyManager = memoryDbProxyManager;
|
||||
this.memoryDbService = memoryDbService;
|
||||
this.docDbContainerManager = docDbContainerManager;
|
||||
this.neptuneContainerManager = neptuneContainerManager;
|
||||
this.neptuneProxyManager = neptuneProxyManager;
|
||||
@@ -261,6 +265,12 @@ public class EmulatorLifecycle {
|
||||
pipesService.startPersistedPollers();
|
||||
redshiftZeroEtlConsumer.startPersistedIntegrations();
|
||||
rdsService.restorePersistedRuntime();
|
||||
if (config.services().memorydb().enabled()) {
|
||||
memoryDbService.restorePersistedRuntime().exceptionally(ex -> {
|
||||
LOG.warnv(ex, "MemoryDB runtime restoration failed");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
if (config.services().timestreamInfluxdb().enabled()) {
|
||||
timestreamInfluxDbService.restorePersistedRuntime();
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.StripedLocks;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend.AccountEntry;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
|
||||
@@ -31,6 +33,8 @@ 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.regex.Pattern;
|
||||
|
||||
@@ -55,6 +59,7 @@ public class MemoryDbService {
|
||||
private static final String DEFAULT_ACL = "open-access";
|
||||
private static final String DEFAULT_USER = "default";
|
||||
private static final String ACTIVE = "active";
|
||||
private static final String LEGACY_CLUSTER_BACKUP_PREFIX = "legacy-clusters/";
|
||||
private static final int REDIS_PORT = 6379;
|
||||
|
||||
// Per the MemoryDB API: a user name must start with a letter and contain only
|
||||
@@ -62,9 +67,9 @@ public class MemoryDbService {
|
||||
private static final Pattern USER_NAME_PATTERN =
|
||||
Pattern.compile("[a-zA-Z][a-zA-Z0-9\\-]*");
|
||||
|
||||
private final StorageBackend<String, Cluster> clusters;
|
||||
private final StorageBackend<String, User> users;
|
||||
private final StorageBackend<String, Acl> acls;
|
||||
private final AccountAwareStorageBackend<Cluster> clusters;
|
||||
private final AccountAwareStorageBackend<User> users;
|
||||
private final AccountAwareStorageBackend<Acl> acls;
|
||||
private final MemoryDbContainerManager containerManager;
|
||||
private final MemoryDbProxyManager proxyManager;
|
||||
private final SigV4Validator sigV4Validator;
|
||||
@@ -72,6 +77,8 @@ public class MemoryDbService {
|
||||
private final RegionResolver regionResolver;
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> provisioningClusterNames = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, Integer> ownedProxyPorts = new ConcurrentHashMap<>();
|
||||
private final StripedLocks clusterLocks = new StripedLocks(256);
|
||||
|
||||
@Inject
|
||||
public MemoryDbService(MemoryDbContainerManager containerManager,
|
||||
@@ -104,7 +111,8 @@ public class MemoryDbService {
|
||||
// Claim the name for the whole provisioning attempt so a concurrent create can't race
|
||||
// ahead and be stopped by this request's handle-less rollback fallback. The existence
|
||||
// check follows the claim, so a create that ended before it is seen.
|
||||
if (!provisioningClusterNames.add(resourceKey)) {
|
||||
String claimKey = regionResolver.getAccountId() + "/" + resourceKey;
|
||||
if (!provisioningClusterNames.add(claimKey)) {
|
||||
throw new AwsException("ClusterAlreadyExistsFault",
|
||||
"Cluster " + name + " is already being created.", 400);
|
||||
}
|
||||
@@ -136,21 +144,25 @@ public class MemoryDbService {
|
||||
cluster.setArn(buildArn(region, "cluster", name));
|
||||
cluster.setCreatedAt(Instant.now());
|
||||
cluster.setTags(spec.getTags());
|
||||
if (!config.services().memorydb().mock() && config.storage() != null
|
||||
&& !"memory".equals(config.storage().mode())) {
|
||||
cluster.setVolumeId(UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
if (config.services().memorydb().mock()) {
|
||||
LOG.infov("Creating MemoryDB cluster {0} in mock mode (no container)", name);
|
||||
cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), REDIS_PORT));
|
||||
clusters.putAllAtomicallyForAccount(cluster.getAccountId(), Map.of(resourceKey, cluster));
|
||||
} else {
|
||||
startBackend(cluster, authRequired);
|
||||
}
|
||||
|
||||
clusters.put(resourceKey, cluster);
|
||||
LOG.infov("MemoryDB cluster {0} created (acl={1}, authRequired={2}), endpoint={3}:{4}",
|
||||
name, aclName, String.valueOf(authRequired), cluster.getClusterEndpoint().address(),
|
||||
String.valueOf(cluster.getClusterEndpoint().port()));
|
||||
return cluster;
|
||||
} finally {
|
||||
provisioningClusterNames.remove(resourceKey);
|
||||
provisioningClusterNames.remove(claimKey);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,7 +209,14 @@ public class MemoryDbService {
|
||||
|
||||
public Cluster deleteCluster(String name, String region) {
|
||||
Cluster cluster = getCluster(name, region);
|
||||
cluster.setStatus(ClusterStatus.DELETING);
|
||||
String ownerKey = cluster.getAccountId() + "/" + key(region, name);
|
||||
boolean pendingBackend;
|
||||
synchronized (clusterLocks.lockFor(ownerKey)) {
|
||||
pendingBackend = cluster.getStatus() == ClusterStatus.CREATING
|
||||
|| cluster.getStatus() == ClusterStatus.DELETING;
|
||||
cluster.setStatus(ClusterStatus.DELETING);
|
||||
clusters.putForAccount(cluster.getAccountId(), key(region, name), cluster);
|
||||
}
|
||||
String identity = identityName(cluster.getAccountId(), region, name);
|
||||
|
||||
proxyManager.stopProxy(identity);
|
||||
@@ -205,14 +224,290 @@ public class MemoryDbService {
|
||||
if (cluster.getContainerId() != null) {
|
||||
containerManager.stop(new MemoryDbContainerHandle(
|
||||
cluster.getContainerId(), identity, cluster.getContainerHost(), cluster.getContainerPort()));
|
||||
} else if (pendingBackend && !config.services().memorydb().mock()) {
|
||||
containerManager.stopByClusterName(identity, cluster.getAccountId(),
|
||||
cluster.getRegion(), cluster.getName());
|
||||
}
|
||||
|
||||
releaseProxyPort(cluster.getProxyPort());
|
||||
clusters.delete(key(region, name));
|
||||
containerManager.removeStorage(identity, cluster.getVolumeId());
|
||||
synchronized (clusterLocks.lockFor(ownerKey)) {
|
||||
releaseOwnedProxyPort(ownerKey, cluster.getProxyPort());
|
||||
clusters.deleteForAccount(cluster.getAccountId(), key(region, name));
|
||||
}
|
||||
LOG.infov("MemoryDB cluster {0} deleted", name);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> restorePersistedRuntime() {
|
||||
if (config.services().memorydb().mock()) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
List<RuntimeException> migrationFailures = new ArrayList<>();
|
||||
List<AccountEntry<Cluster>> persisted = migratePersistedClusters(migrationFailures);
|
||||
List<AccountEntry<Cluster>> pending = new ArrayList<>();
|
||||
RuntimeException reservationFailure = null;
|
||||
for (RuntimeException failure : migrationFailures) {
|
||||
if (reservationFailure == null) {
|
||||
reservationFailure = failure;
|
||||
} else {
|
||||
reservationFailure.addSuppressed(failure);
|
||||
}
|
||||
}
|
||||
for (AccountEntry<Cluster> entry : persisted) {
|
||||
Cluster cluster = entry.value();
|
||||
String ownerKey = entry.accountId() + "/" + entry.key();
|
||||
synchronized (clusterLocks.lockFor(ownerKey)) {
|
||||
if (!provisioningClusterNames.add(ownerKey)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
cluster.setAccountId(entry.accountId());
|
||||
cluster.setRegion(restoredRegion(cluster));
|
||||
if (cluster.getStatus() == ClusterStatus.DELETING) {
|
||||
clusters.putAllAtomicallyForAccount(entry.accountId(), Map.of(entry.key(), cluster));
|
||||
provisioningClusterNames.remove(ownerKey);
|
||||
continue;
|
||||
}
|
||||
Integer ownedPort = ownedProxyPorts.get(ownerKey);
|
||||
int requested = cluster.getProxyPort();
|
||||
int port = ownedPort != null ? ownedPort
|
||||
: requested >= config.services().memorydb().proxyBasePort()
|
||||
&& requested <= config.services().memorydb().proxyMaxPort()
|
||||
&& usedPorts.add(requested) ? requested : allocateProxyPort();
|
||||
ownedProxyPorts.put(ownerKey, port);
|
||||
cluster.setProxyPort(port);
|
||||
cluster.setClusterEndpoint(null);
|
||||
cluster.setStatus(ClusterStatus.CREATING);
|
||||
if (cluster.getVolumeId() == null && config.storage() != null
|
||||
&& !"memory".equals(config.storage().mode())) {
|
||||
cluster.setVolumeId(UUID.randomUUID().toString());
|
||||
}
|
||||
clusters.putAllAtomicallyForAccount(entry.accountId(), Map.of(entry.key(), cluster));
|
||||
pending.add(entry);
|
||||
} catch (RuntimeException e) {
|
||||
releaseOwnedProxyPort(ownerKey, cluster.getProxyPort());
|
||||
provisioningClusterNames.remove(ownerKey);
|
||||
if (cluster.getStatus() != ClusterStatus.DELETING) {
|
||||
cluster.setStatus(ClusterStatus.CREATING);
|
||||
}
|
||||
cluster.setClusterEndpoint(null);
|
||||
try {
|
||||
clusters.putForAccount(entry.accountId(), entry.key(), cluster);
|
||||
} catch (RuntimeException persistFailure) {
|
||||
e.addSuppressed(persistFailure);
|
||||
}
|
||||
LOG.warnv(e, "Failed to reserve the MemoryDB runtime for {0}", ownerKey);
|
||||
if (reservationFailure == null) {
|
||||
reservationFailure = e;
|
||||
} else {
|
||||
reservationFailure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RuntimeException initialFailure = reservationFailure;
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
RuntimeException failure = initialFailure;
|
||||
for (AccountEntry<Cluster> entry : pending) {
|
||||
try {
|
||||
restoreCluster(entry);
|
||||
} catch (RuntimeException e) {
|
||||
if (failure == null) {
|
||||
failure = e;
|
||||
} else {
|
||||
failure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private List<AccountEntry<Cluster>> migratePersistedClusters(List<RuntimeException> failures) {
|
||||
List<AccountEntry<Cluster>> normalized = new ArrayList<>();
|
||||
Set<String> included = new HashSet<>();
|
||||
for (AccountEntry<Cluster> entry : clusters.scanAllAccountEntries(
|
||||
storedKey -> !storedKey.startsWith(LEGACY_CLUSTER_BACKUP_PREFIX))) {
|
||||
Cluster cluster = entry.value();
|
||||
try {
|
||||
boolean prefixed = clusters.getForAccount(entry.accountId(), entry.key())
|
||||
.filter(current -> current == cluster).isPresent();
|
||||
AwsArnUtils.Arn arn = cluster.getArn() == null || cluster.getArn().isBlank()
|
||||
? null : AwsArnUtils.parse(cluster.getArn());
|
||||
String account = prefixed ? entry.accountId() : cluster.getAccountId();
|
||||
if (account == null || account.isBlank()) {
|
||||
account = arn != null ? arn.accountId() : regionResolver.getDefaultAccountId();
|
||||
}
|
||||
String region = restoredRegion(cluster);
|
||||
if ((cluster.getAccountId() != null && !cluster.getAccountId().isBlank()
|
||||
&& !account.equals(cluster.getAccountId()))
|
||||
|| (arn != null && (!"memorydb".equals(arn.service())
|
||||
|| !account.equals(arn.accountId()) || !region.equals(arn.region())))) {
|
||||
throw new IllegalStateException("MemoryDB persisted owner or region contradicts its storage key or ARN");
|
||||
}
|
||||
String name = cluster.getName();
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalStateException("MemoryDB persisted cluster has no name");
|
||||
}
|
||||
String logicalKey = key(region, name);
|
||||
if (!entry.key().equals(name) && !entry.key().equals(logicalKey)) {
|
||||
throw new IllegalStateException("MemoryDB persisted cluster name contradicts its storage key");
|
||||
}
|
||||
String sourceKey = prefixed
|
||||
? AccountAwareStorageBackend.rawKey(entry.accountId(), entry.key()) : entry.key();
|
||||
String destinationKey = AccountAwareStorageBackend.rawKey(account, logicalKey);
|
||||
Optional<Cluster> existing = clusters.getForAccount(account, logicalKey);
|
||||
cluster.setAccountId(account);
|
||||
cluster.setRegion(region);
|
||||
if (existing.isPresent() && existing.get() != cluster) {
|
||||
String backupKey = LEGACY_CLUSTER_BACKUP_PREFIX + UUID.randomUUID();
|
||||
clusters.putAllAtomicallyForAccount(account, Map.of(backupKey, cluster));
|
||||
clusters.deleteRaw(sourceKey);
|
||||
LOG.warnv("MemoryDB legacy record at {0} conflicts with {1}; retained at {2}/{3} for recovery",
|
||||
sourceKey, destinationKey, account, backupKey);
|
||||
continue;
|
||||
}
|
||||
if (!sourceKey.equals(destinationKey)) {
|
||||
clusters.putAllAtomicallyForAccount(account, Map.of(logicalKey, cluster));
|
||||
clusters.deleteRaw(sourceKey);
|
||||
}
|
||||
if (included.add(destinationKey)) {
|
||||
normalized.add(new AccountEntry<>(account, logicalKey, cluster));
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
failures.add(failure);
|
||||
LOG.warnv(failure, "Failed to migrate MemoryDB metadata at {0}/{1}",
|
||||
entry.accountId(), entry.key());
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private void restoreCluster(AccountEntry<Cluster> entry) {
|
||||
Cluster cluster = entry.value();
|
||||
String ownerKey = entry.accountId() + "/" + entry.key();
|
||||
String identity = identityName(entry.accountId(), cluster.getRegion(), cluster.getName());
|
||||
MemoryDbContainerHandle handle = null;
|
||||
try {
|
||||
boolean authRequired = isAuthRequired(cluster.getAclName(), cluster.getRegion(), entry.accountId());
|
||||
String image = config.services().memorydb().defaultImage();
|
||||
boolean unavailable = false;
|
||||
if (cluster.getContainerId() != null) {
|
||||
if (!containerManager.isDockerReachable()) {
|
||||
unavailable = true;
|
||||
} else {
|
||||
handle = new MemoryDbContainerHandle(cluster.getContainerId(), identity,
|
||||
cluster.getContainerHost(), cluster.getContainerPort());
|
||||
containerManager.stop(handle);
|
||||
clearBackend(cluster);
|
||||
clusters.putAllAtomicallyForAccount(entry.accountId(), Map.of(entry.key(), cluster));
|
||||
handle = null;
|
||||
}
|
||||
}
|
||||
if (!unavailable) {
|
||||
handle = containerManager.tryStart(identity, image, cluster.getVolumeId(),
|
||||
entry.accountId(), cluster.getRegion(), cluster.getName());
|
||||
}
|
||||
boolean lost;
|
||||
synchronized (clusterLocks.lockFor(ownerKey)) {
|
||||
lost = restoreTargetLost(entry);
|
||||
if (!lost) {
|
||||
if (handle != null) {
|
||||
cluster.setContainerId(handle.getContainerId());
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
proxyManager.startProxy(identity, authRequired, cluster.getProxyPort(),
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, secret) -> authenticate(cluster.getName(), username, secret,
|
||||
cluster.getRegion(), entry.accountId()));
|
||||
} else {
|
||||
LOG.warnv("MemoryDB cluster {0} restored as metadata only: no Docker daemon is reachable",
|
||||
ownerKey);
|
||||
}
|
||||
cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), cluster.getProxyPort()));
|
||||
cluster.setStatus(ClusterStatus.AVAILABLE);
|
||||
clusters.putAllAtomicallyForAccount(entry.accountId(), Map.of(entry.key(), cluster));
|
||||
}
|
||||
}
|
||||
if (lost && handle != null) {
|
||||
containerManager.stop(handle);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
boolean cleaned = true;
|
||||
try {
|
||||
proxyManager.stopProxy(identity);
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
e.addSuppressed(cleanupFailure);
|
||||
cleaned = false;
|
||||
}
|
||||
try {
|
||||
if (handle != null) {
|
||||
containerManager.stop(handle);
|
||||
} else {
|
||||
containerManager.stopByClusterName(identity, cluster.getAccountId(),
|
||||
cluster.getRegion(), cluster.getName());
|
||||
}
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
e.addSuppressed(cleanupFailure);
|
||||
cleaned = false;
|
||||
}
|
||||
synchronized (clusterLocks.lockFor(ownerKey)) {
|
||||
Optional<Cluster> current = clusters.getForAccount(entry.accountId(), entry.key());
|
||||
if (!restoreTargetLost(entry)
|
||||
|| (!cleaned && (current.isEmpty() || current.get() == cluster))) {
|
||||
if (cluster.getStatus() != ClusterStatus.DELETING) {
|
||||
cluster.setStatus(ClusterStatus.CREATING);
|
||||
}
|
||||
cluster.setClusterEndpoint(null);
|
||||
if (cleaned) {
|
||||
clearBackend(cluster);
|
||||
releaseOwnedProxyPort(ownerKey, cluster.getProxyPort());
|
||||
} else if (handle != null) {
|
||||
cluster.setContainerId(handle.getContainerId());
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
}
|
||||
try {
|
||||
clusters.putAllAtomicallyForAccount(entry.accountId(), Map.of(entry.key(), cluster));
|
||||
} catch (RuntimeException persistFailure) {
|
||||
e.addSuppressed(persistFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
LOG.warnv(e, "Failed to restore MemoryDB runtime for {0}", ownerKey);
|
||||
throw e;
|
||||
} finally {
|
||||
provisioningClusterNames.remove(ownerKey);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean restoreTargetLost(AccountEntry<Cluster> entry) {
|
||||
return clusters.getForAccount(entry.accountId(), entry.key())
|
||||
.map(current -> current != entry.value() || current.getStatus() == ClusterStatus.DELETING)
|
||||
.orElse(true);
|
||||
}
|
||||
|
||||
private String restoredRegion(Cluster cluster) {
|
||||
if (cluster.getRegion() != null && !cluster.getRegion().isBlank()) {
|
||||
return cluster.getRegion();
|
||||
}
|
||||
if (AwsArnUtils.isArn(cluster.getArn())) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(cluster.getArn());
|
||||
if ("memorydb".equals(arn.service()) && !arn.region().isBlank()) {
|
||||
return arn.region();
|
||||
}
|
||||
}
|
||||
return regionResolver.getDefaultRegion();
|
||||
}
|
||||
|
||||
private static void clearBackend(Cluster cluster) {
|
||||
cluster.setContainerId(null);
|
||||
cluster.setContainerHost(null);
|
||||
cluster.setContainerPort(0);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Users ────────────────────────────
|
||||
|
||||
public User createUser(User spec, String region) {
|
||||
@@ -443,7 +738,12 @@ public class MemoryDbService {
|
||||
}
|
||||
|
||||
public boolean authenticate(String clusterName, String username, String secret, String region) {
|
||||
Cluster cluster = resourceGet(clusters, clusterName, region).orElse(null);
|
||||
return authenticate(clusterName, username, secret, region, regionResolver.getAccountId());
|
||||
}
|
||||
|
||||
private boolean authenticate(String clusterName, String username, String secret, String region,
|
||||
String accountId) {
|
||||
Cluster cluster = ownedResourceGet(clusters, accountId, clusterName, region).orElse(null);
|
||||
if (cluster == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -451,7 +751,7 @@ public class MemoryDbService {
|
||||
if (DEFAULT_ACL.equals(aclName)) {
|
||||
return true;
|
||||
}
|
||||
Acl acl = resourceGet(acls, aclName, region).orElse(null);
|
||||
Acl acl = ownedResourceGet(acls, accountId, aclName, region).orElse(null);
|
||||
if (acl == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -459,7 +759,7 @@ public class MemoryDbService {
|
||||
if (!acl.getUserNames().contains(target)) {
|
||||
return false;
|
||||
}
|
||||
User user = resolveUser(target, region);
|
||||
User user = resolveUser(target, region, accountId);
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -472,15 +772,19 @@ public class MemoryDbService {
|
||||
|
||||
/** True if the ACL has at least one user that requires a credential (password or IAM). */
|
||||
private boolean isAuthRequired(String aclName, String region) {
|
||||
return isAuthRequired(aclName, region, regionResolver.getAccountId());
|
||||
}
|
||||
|
||||
private boolean isAuthRequired(String aclName, String region, String accountId) {
|
||||
if (DEFAULT_ACL.equals(aclName)) {
|
||||
return false;
|
||||
}
|
||||
Acl acl = resourceGet(acls, aclName, region).orElse(null);
|
||||
Acl acl = ownedResourceGet(acls, accountId, aclName, region).orElse(null);
|
||||
if (acl == null) {
|
||||
return false;
|
||||
}
|
||||
return acl.getUserNames().stream()
|
||||
.map(name -> resolveUser(name, region))
|
||||
.map(name -> resolveUser(name, region, accountId))
|
||||
.filter(Objects::nonNull)
|
||||
.anyMatch(u -> u.getAuthMode() != AuthMode.NO_PASSWORD);
|
||||
}
|
||||
@@ -495,11 +799,21 @@ public class MemoryDbService {
|
||||
return DEFAULT_USER.equals(name) || resourceGet(users, name, region).isPresent();
|
||||
}
|
||||
|
||||
private User resolveUser(String name, String region) {
|
||||
return resourceGet(users, name, region)
|
||||
private User resolveUser(String name, String region, String accountId) {
|
||||
return ownedResourceGet(users, accountId, name, region)
|
||||
.orElseGet(() -> DEFAULT_USER.equals(name) ? builtinDefaultUser(region) : null);
|
||||
}
|
||||
|
||||
private <V> Optional<V> ownedResourceGet(AccountAwareStorageBackend<V> store, String accountId,
|
||||
String name, String region) {
|
||||
if (Objects.equals(accountId, regionResolver.getDefaultAccountId())
|
||||
&& Objects.equals(region, regionResolver.getDefaultRegion())) {
|
||||
return store.getForAccountMigratingLegacyKeys(accountId, key(region, name), List.of(name),
|
||||
value -> true);
|
||||
}
|
||||
return store.getForAccount(accountId, key(region, name));
|
||||
}
|
||||
|
||||
private User builtinDefaultUser(String region) {
|
||||
User user = new User();
|
||||
user.setName(DEFAULT_USER);
|
||||
@@ -551,6 +865,17 @@ public class MemoryDbService {
|
||||
String name = cluster.getName();
|
||||
String identity = identityName(cluster.getAccountId(), cluster.getRegion(), name);
|
||||
int proxyPort = allocateProxyPort();
|
||||
String ownerKey = cluster.getAccountId() + "/" + key(cluster.getRegion(), name);
|
||||
ownedProxyPorts.put(ownerKey, proxyPort);
|
||||
cluster.setProxyPort(proxyPort);
|
||||
cluster.setStatus(ClusterStatus.CREATING);
|
||||
try {
|
||||
clusters.putAllAtomicallyForAccount(cluster.getAccountId(),
|
||||
Map.of(key(cluster.getRegion(), name), cluster));
|
||||
} catch (RuntimeException e) {
|
||||
releaseOwnedProxyPort(ownerKey, proxyPort);
|
||||
throw e;
|
||||
}
|
||||
String image = config.services().memorydb().defaultImage();
|
||||
LOG.infov("Creating MemoryDB cluster {0} with authRequired={1} on proxy port {2}",
|
||||
name, String.valueOf(authRequired), String.valueOf(proxyPort));
|
||||
@@ -561,62 +886,90 @@ public class MemoryDbService {
|
||||
// from configuration and need no Docker, so the cluster is created and reaches
|
||||
// 'available' even when no daemon is reachable. Only connecting to the cache needs
|
||||
// the container.
|
||||
handle = containerManager.tryStart(identity, image);
|
||||
cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), proxyPort));
|
||||
cluster.setProxyPort(proxyPort);
|
||||
handle = containerManager.tryStart(identity, image, cluster.getVolumeId(),
|
||||
cluster.getAccountId(), cluster.getRegion(), cluster.getName());
|
||||
synchronized (clusterLocks.lockFor(ownerKey)) {
|
||||
if (clusters.getForAccount(cluster.getAccountId(), key(cluster.getRegion(), name))
|
||||
.filter(current -> current == cluster && current.getStatus() != ClusterStatus.DELETING)
|
||||
.isEmpty()) {
|
||||
throw new IllegalStateException("MemoryDB cluster was deleted while its backend was starting");
|
||||
}
|
||||
if (handle != null) {
|
||||
cluster.setContainerId(handle.getContainerId());
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
|
||||
if (handle != null) {
|
||||
cluster.setContainerId(handle.getContainerId());
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
|
||||
proxyManager.startProxy(identity, authRequired, proxyPort,
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, secret) -> authenticate(name, username, secret, cluster.getRegion()));
|
||||
} else {
|
||||
LOG.warnv("MemoryDB cluster {0} created without a backing container: no Docker "
|
||||
+ "daemon is reachable. Metadata operations work; connections to the "
|
||||
+ "cluster do not until a daemon appears.", name);
|
||||
proxyManager.startProxy(identity, authRequired, proxyPort,
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, secret) -> authenticate(name, username, secret, cluster.getRegion(),
|
||||
cluster.getAccountId()));
|
||||
} else {
|
||||
LOG.warnv("MemoryDB cluster {0} created without a backing container: no Docker "
|
||||
+ "daemon is reachable. Metadata operations work; connections to the "
|
||||
+ "cluster do not until a daemon appears.", name);
|
||||
}
|
||||
cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), proxyPort));
|
||||
cluster.setStatus(ClusterStatus.AVAILABLE);
|
||||
clusters.putAllAtomicallyForAccount(cluster.getAccountId(),
|
||||
Map.of(key(cluster.getRegion(), name), cluster));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("MemoryDB cluster {0} provisioning failed, rolling back: {1}", name, e.getMessage());
|
||||
rollbackBackend(identity, handle, proxyPort);
|
||||
boolean cleaned = rollbackBackend(identity, handle, cluster, e);
|
||||
synchronized (clusterLocks.lockFor(ownerKey)) {
|
||||
try {
|
||||
if (cluster.getStatus() != ClusterStatus.DELETING) {
|
||||
cluster.setStatus(ClusterStatus.CREATING);
|
||||
}
|
||||
cluster.setClusterEndpoint(null);
|
||||
if (cleaned) {
|
||||
clearBackend(cluster);
|
||||
clusters.deleteAllAtomicallyForAccounts(
|
||||
Map.of(cluster.getAccountId(), Set.of(key(cluster.getRegion(), name))));
|
||||
releaseOwnedProxyPort(ownerKey, proxyPort);
|
||||
} else {
|
||||
clusters.putAllAtomicallyForAccount(cluster.getAccountId(),
|
||||
Map.of(key(cluster.getRegion(), name), cluster));
|
||||
}
|
||||
} catch (RuntimeException persistenceFailure) {
|
||||
e.addSuppressed(persistenceFailure);
|
||||
}
|
||||
}
|
||||
LOG.warnv(e, "MemoryDB cluster {0} provisioning failed; cleanup complete={1}", ownerKey, cleaned);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void rollbackBackend(String name, MemoryDbContainerHandle handle, int proxyPort) {
|
||||
private boolean rollbackBackend(String name, MemoryDbContainerHandle handle, Cluster cluster,
|
||||
RuntimeException failure) {
|
||||
boolean cleaned = true;
|
||||
try {
|
||||
try {
|
||||
// The proxy only starts after the container is ready, so a null handle means it
|
||||
// never started — nothing to stop.
|
||||
if (handle != null) {
|
||||
proxyManager.stopProxy(name);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Error stopping proxy for MemoryDB cluster {0}: {1}", name, e.getMessage());
|
||||
if (handle != null) {
|
||||
proxyManager.stopProxy(name);
|
||||
}
|
||||
try {
|
||||
if (handle != null) {
|
||||
// We have the exact handle from this request's start() call, so stop by it
|
||||
// directly. Falling back to stopByClusterName here instead would look up
|
||||
// whatever is currently registered for name, which could be a different
|
||||
// container if an overlapping create for the same name raced ahead of this
|
||||
// rollback.
|
||||
containerManager.stop(handle);
|
||||
} else {
|
||||
// No handle: a readiness timeout in containerManager.start() throws after the
|
||||
// container was created and registered but before the handle is returned, so
|
||||
// cleaning up by handle here isn't possible. stopByClusterName is idempotent,
|
||||
// so it's safe when the container never started.
|
||||
containerManager.stopByClusterName(name);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Error stopping container for MemoryDB cluster {0}: {1}", name, e.getMessage());
|
||||
}
|
||||
} finally {
|
||||
releaseProxyPort(proxyPort);
|
||||
} catch (RuntimeException e) {
|
||||
failure.addSuppressed(e);
|
||||
cleaned = false;
|
||||
}
|
||||
try {
|
||||
if (handle != null) {
|
||||
containerManager.stop(handle);
|
||||
} else {
|
||||
containerManager.stopByClusterName(name, cluster.getAccountId(),
|
||||
cluster.getRegion(), cluster.getName());
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
failure.addSuppressed(e);
|
||||
cleaned = false;
|
||||
}
|
||||
if (cleaned) {
|
||||
try {
|
||||
containerManager.removeStorage(name, cluster.getVolumeId());
|
||||
} catch (RuntimeException e) {
|
||||
failure.addSuppressed(e);
|
||||
cleaned = false;
|
||||
}
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
private String key(String region, String name) {
|
||||
@@ -633,12 +986,6 @@ public class MemoryDbService {
|
||||
}
|
||||
|
||||
private String identityName(String accountId, String region, String name) {
|
||||
String defaultAccount = regionResolver.getDefaultAccountId();
|
||||
String defaultRegion = regionResolver.getDefaultRegion();
|
||||
if ((defaultAccount == null || Objects.equals(defaultAccount, accountId))
|
||||
&& (defaultRegion == null || Objects.equals(defaultRegion, region))) {
|
||||
return name;
|
||||
}
|
||||
return accountId + "-" + region + "-" + name;
|
||||
}
|
||||
|
||||
@@ -695,7 +1042,7 @@ public class MemoryDbService {
|
||||
// unscoped record to account/name without adding the new region component. Move those
|
||||
// intermediate keys as well so unfiltered operations cannot omit them.
|
||||
for (String legacyKey : aware.keysForAccount(accountId)) {
|
||||
if (legacyKey.contains(":")) {
|
||||
if (legacyKey.contains(":") || legacyKey.startsWith(LEGACY_CLUSTER_BACKUP_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
aware.getForAccount(accountId, legacyKey)
|
||||
@@ -768,4 +1115,10 @@ public class MemoryDbService {
|
||||
private void releaseProxyPort(int port) {
|
||||
usedPorts.remove(port);
|
||||
}
|
||||
|
||||
private void releaseOwnedProxyPort(String ownerKey, int port) {
|
||||
if (ownedProxyPorts.remove(ownerKey, port)) {
|
||||
releaseProxyPort(port);
|
||||
}
|
||||
}
|
||||
}
|
||||
+116
-15
@@ -24,7 +24,10 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
/**
|
||||
* Manages backend Docker container lifecycle for MemoryDB clusters.
|
||||
@@ -50,6 +53,8 @@ public class MemoryDbContainerManager {
|
||||
private final RegionResolver regionResolver;
|
||||
private final Map<String, MemoryDbContainerHandle> activeContainers = new ConcurrentHashMap<>();
|
||||
private volatile boolean dockerUnavailableLogged;
|
||||
private final ReentrantReadWriteLock runtimeAdmission = new ReentrantReadWriteLock();
|
||||
private volatile boolean stopping;
|
||||
|
||||
@Inject
|
||||
public MemoryDbContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -76,12 +81,22 @@ public class MemoryDbContainerManager {
|
||||
* @return the container handle, or {@code null} when no Docker daemon is reachable
|
||||
*/
|
||||
public MemoryDbContainerHandle tryStart(String clusterName, String image) {
|
||||
return tryStart(clusterName, image, null, regionResolver.getAccountId(), resolvedRegion());
|
||||
}
|
||||
|
||||
public MemoryDbContainerHandle tryStart(String clusterName, String image, String volumeId,
|
||||
String accountId, String region) {
|
||||
return tryStart(clusterName, image, volumeId, accountId, region, clusterName);
|
||||
}
|
||||
|
||||
public MemoryDbContainerHandle tryStart(String runtimeIdentity, String image, String volumeId,
|
||||
String accountId, String region, String logicalName) {
|
||||
try {
|
||||
MemoryDbContainerHandle handle = start(clusterName, image);
|
||||
MemoryDbContainerHandle handle = start(runtimeIdentity, image, volumeId, accountId, region, logicalName);
|
||||
dockerUnavailableLogged = false;
|
||||
return handle;
|
||||
} catch (RuntimeException e) {
|
||||
if (isDockerReachable()) {
|
||||
if (stopping || isDockerReachable()) {
|
||||
throw e;
|
||||
}
|
||||
if (!dockerUnavailableLogged) {
|
||||
@@ -110,18 +125,53 @@ public class MemoryDbContainerManager {
|
||||
}
|
||||
|
||||
public MemoryDbContainerHandle start(String clusterName, String image) {
|
||||
return start(clusterName, image, null, regionResolver.getAccountId(), resolvedRegion());
|
||||
}
|
||||
|
||||
public MemoryDbContainerHandle start(String clusterName, String image, String volumeId,
|
||||
String accountId, String region) {
|
||||
return start(clusterName, image, volumeId, accountId, region, clusterName);
|
||||
}
|
||||
|
||||
public MemoryDbContainerHandle start(String runtimeIdentity, String image, String volumeId,
|
||||
String accountId, String region, String logicalName) {
|
||||
runtimeAdmission.readLock().lock();
|
||||
try {
|
||||
if (stopping) {
|
||||
throw new IllegalStateException("MemoryDB is shutting down");
|
||||
}
|
||||
return startAdmitted(runtimeIdentity, image, volumeId, accountId, region, logicalName);
|
||||
} finally {
|
||||
runtimeAdmission.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private MemoryDbContainerHandle startAdmitted(String clusterName, String image, String volumeId,
|
||||
String accountId, String region, String logicalName) {
|
||||
LOG.infov("Starting MemoryDB backend container for cluster: {0}", clusterName);
|
||||
|
||||
String containerName = containerName(clusterName);
|
||||
String containerName = containerName(accountId, region, logicalName);
|
||||
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
lifecycleManager.removeIfExistsStrict(containerName, true);
|
||||
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withDockerNetwork(config.services().memorydb().dockerNetwork())
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"memorydb", clusterName, regionResolver.getAccountId(), resolvedRegion()));
|
||||
"memorydb", clusterName, accountId, region));
|
||||
|
||||
if (volumeId != null) {
|
||||
String volumeName = ContainerStorageHelper.resourceName(config, "memorydb", volumeId, clusterName);
|
||||
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager, volumeName, "/data");
|
||||
} else {
|
||||
String path = ContainerStorageHelper.hostResourcePath(config, "memorydb", volumeId).toString();
|
||||
ContainerStorageHelper.ensureHostDir(path);
|
||||
specBuilder.withBind(path, "/data");
|
||||
}
|
||||
specBuilder.withCmd(List.of("--appendonly", "yes", "--appendfsync", "always"));
|
||||
}
|
||||
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
specBuilder.withDynamicPort(BACKEND_PORT);
|
||||
@@ -131,7 +181,7 @@ public class MemoryDbContainerManager {
|
||||
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
|
||||
ContainerInfo info = lifecycleManager.createAndStart(spec);
|
||||
ContainerInfo info = lifecycleManager.createAndStartEphemeral(spec);
|
||||
EndpointInfo endpoint = info.getEndpoint(BACKEND_PORT);
|
||||
|
||||
LOG.infov("MemoryDB backend for cluster {0}: {1}", clusterName, endpoint);
|
||||
@@ -143,19 +193,29 @@ public class MemoryDbContainerManager {
|
||||
String shortId = info.containerId().length() >= 8
|
||||
? info.containerId().substring(0, 8)
|
||||
: info.containerId();
|
||||
String logGroup = "/aws/memorydb/cluster/" + clusterName + "/engine-log";
|
||||
String logName = isDefaultScope(accountId, region) ? logicalName : clusterName;
|
||||
String logGroup = "/aws/memorydb/cluster/" + logName + "/engine-log";
|
||||
String logStream = logStreamer.generateLogStreamName(shortId);
|
||||
String region = resolvedRegion();
|
||||
|
||||
Closeable logHandle = logStreamer.attach(
|
||||
info.containerId(), logGroup, logStream, region, "memorydb:" + clusterName);
|
||||
handle.setLogStream(logHandle);
|
||||
|
||||
waitForBackendReady(clusterName, endpoint.host(), endpoint.port());
|
||||
if (stopping) {
|
||||
stop(handle);
|
||||
throw new IllegalStateException("MemoryDB shut down while the backend was starting");
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
public void removeStorage(String clusterName, String volumeId) {
|
||||
if (volumeId != null && ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
ContainerStorageHelper.removeNamedVolumeStrict(config, lifecycleManager,
|
||||
ContainerStorageHelper.resourceName(config, "memorydb", volumeId, clusterName));
|
||||
}
|
||||
}
|
||||
|
||||
private static void waitForBackendReady(String clusterName, String host, int port) {
|
||||
long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS;
|
||||
int attempt = 0;
|
||||
@@ -199,8 +259,8 @@ public class MemoryDbContainerManager {
|
||||
if (handle == null) {
|
||||
return;
|
||||
}
|
||||
activeContainers.remove(handle.getClusterName());
|
||||
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
|
||||
lifecycleManager.stopAndRemoveStrict(handle.getContainerId(), handle.getLogStream(), 5, true);
|
||||
activeContainers.remove(handle.getClusterName(), handle);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -213,16 +273,26 @@ public class MemoryDbContainerManager {
|
||||
* registered. Idempotent — a no-op when nothing is running for the name.
|
||||
*/
|
||||
public void stopByClusterName(String clusterName) {
|
||||
stopByClusterName(clusterName, regionResolver.getAccountId(), resolvedRegion(), clusterName);
|
||||
}
|
||||
|
||||
public void stopByClusterName(String clusterName, String accountId, String region, String logicalName) {
|
||||
MemoryDbContainerHandle handle = activeContainers.get(clusterName);
|
||||
if (handle != null) {
|
||||
stop(handle);
|
||||
return;
|
||||
}
|
||||
lifecycleManager.removeIfExists(containerName(clusterName));
|
||||
lifecycleManager.removeIfExistsStrict(containerName(accountId, region, logicalName), true);
|
||||
}
|
||||
|
||||
private String containerName(String clusterName) {
|
||||
return ContainerStorageHelper.resourceName(config, "memorydb", null, clusterName);
|
||||
private String containerName(String accountId, String region, String logicalName) {
|
||||
String name = isDefaultScope(accountId, region) ? logicalName : accountId + "_" + region + "_" + logicalName;
|
||||
return ContainerStorageHelper.resourceName(config, "memorydb", null, name);
|
||||
}
|
||||
|
||||
private boolean isDefaultScope(String accountId, String region) {
|
||||
return Objects.equals(accountId, regionResolver.getDefaultAccountId())
|
||||
&& Objects.equals(region, regionResolver.getDefaultRegion());
|
||||
}
|
||||
|
||||
private String resolvedRegion() {
|
||||
@@ -231,12 +301,43 @@ public class MemoryDbContainerManager {
|
||||
}
|
||||
|
||||
public void stopAll() {
|
||||
stopping = true;
|
||||
boolean admitted;
|
||||
try {
|
||||
admitted = runtimeAdmission.writeLock().tryLock(BACKEND_READY_DEADLINE_MS, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Interrupted while awaiting MemoryDB backend startup", e);
|
||||
}
|
||||
if (!admitted) {
|
||||
throw new IllegalStateException("MemoryDB backend startup did not finish before shutdown deadline");
|
||||
}
|
||||
try {
|
||||
stopAdmittedContainers();
|
||||
} finally {
|
||||
runtimeAdmission.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void stopAdmittedContainers() {
|
||||
List<MemoryDbContainerHandle> handles = new ArrayList<>(activeContainers.values());
|
||||
if (!handles.isEmpty()) {
|
||||
LOG.infov("Stopping {0} MemoryDB container(s) on shutdown", handles.size());
|
||||
}
|
||||
RuntimeException failure = null;
|
||||
for (MemoryDbContainerHandle handle : handles) {
|
||||
stop(handle);
|
||||
try {
|
||||
stop(handle);
|
||||
} catch (RuntimeException e) {
|
||||
if (failure == null) {
|
||||
failure = e;
|
||||
} else {
|
||||
failure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ public class Cluster {
|
||||
private String arn;
|
||||
private Instant createdAt;
|
||||
private int proxyPort;
|
||||
private String volumeId;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
// Transient fields — not persisted, restored on container restart
|
||||
@@ -80,6 +81,9 @@ public class Cluster {
|
||||
public int getProxyPort() { return proxyPort; }
|
||||
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
|
||||
|
||||
public String getVolumeId() { return volumeId; }
|
||||
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags != null ? tags : new LinkedHashMap<>();
|
||||
|
||||
@@ -30,6 +30,7 @@ import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoll
|
||||
import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService;
|
||||
import io.github.hectorvent.floci.services.memorydb.MemoryDbService;
|
||||
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager;
|
||||
@@ -104,6 +105,8 @@ class EmulatorLifecycleTest {
|
||||
@Mock private RdsProxyManager rdsProxyManager;
|
||||
@Mock private MemoryDbContainerManager memoryDbContainerManager;
|
||||
@Mock private MemoryDbProxyManager memoryDbProxyManager;
|
||||
@Mock private MemoryDbService memoryDbService;
|
||||
@Mock private EmulatorConfig.MemoryDbServiceConfig memoryDbServiceConfig;
|
||||
@Mock private DocDbContainerManager docDbContainerManager;
|
||||
@Mock private NeptuneContainerManager neptuneContainerManager;
|
||||
@Mock private NeptuneProxyManager neptuneProxyManager;
|
||||
@@ -141,6 +144,7 @@ class EmulatorLifecycleTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
Mockito.lenient().when(config.services()).thenReturn(servicesConfig);
|
||||
Mockito.lenient().when(servicesConfig.memorydb()).thenReturn(memoryDbServiceConfig);
|
||||
Mockito.lenient().when(servicesConfig.ec2()).thenReturn(ec2ServiceConfig);
|
||||
Mockito.lenient().when(servicesConfig.ecs()).thenReturn(ecsServiceConfig);
|
||||
Mockito.lenient().when(ecsServiceConfig.taskRoleCredentials()).thenReturn(ecsTaskRoleCredentialsConfig);
|
||||
@@ -170,7 +174,7 @@ class EmulatorLifecycleTest {
|
||||
iamService, elastiCacheService, elastiCacheMemcachedService,
|
||||
elastiCacheContainerManager, elastiCacheMemcachedContainerManager,
|
||||
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
|
||||
memoryDbContainerManager, memoryDbProxyManager,
|
||||
memoryDbContainerManager, memoryDbProxyManager, memoryDbService,
|
||||
docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
|
||||
rabbitMqManager, flinkContainerManager, rdsService, timestreamInfluxDbService,
|
||||
elbV2Service, elbClassicService, ecsService,
|
||||
|
||||
+18
@@ -23,6 +23,24 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
*/
|
||||
class MemoryDbPersistenceTest {
|
||||
|
||||
@Test
|
||||
void persistsBackendVolumeIdentityAcrossReload(@TempDir Path dir) {
|
||||
Path file = dir.resolve("memorydb-clusters.json");
|
||||
PersistentStorage<String, Cluster> original =
|
||||
new PersistentStorage<>(file, new TypeReference<Map<String, Cluster>>() {});
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("durable");
|
||||
cluster.setVolumeId("incarnation-a");
|
||||
original.put("durable", cluster);
|
||||
original.flush();
|
||||
|
||||
PersistentStorage<String, Cluster> reloaded =
|
||||
new PersistentStorage<>(file, new TypeReference<Map<String, Cluster>>() {});
|
||||
reloaded.load();
|
||||
|
||||
assertEquals("incarnation-a", reloaded.get("durable").orElseThrow().getVolumeId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsLegacySnapshotContainingRemovedAuthFields(@TempDir Path dir) throws Exception {
|
||||
Path file = dir.resolve("memorydb-clusters.json");
|
||||
|
||||
+546
@@ -0,0 +1,546 @@
|
||||
package io.github.hectorvent.floci.services.memorydb;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
|
||||
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerHandle;
|
||||
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.Acl;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.ClusterStatus;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.User;
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbAuthProxy;
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class MemoryDbRuntimeRestoreTest {
|
||||
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
private final InMemoryStorage<String, Cluster> rawClusters = new InMemoryStorage<>();
|
||||
private final AccountAwareStorageBackend<Cluster> clusters =
|
||||
spy(new AccountAwareStorageBackend<>(rawClusters, null, DEFAULT_ACCOUNT));
|
||||
private final AccountAwareStorageBackend<User> users = AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT);
|
||||
private final AccountAwareStorageBackend<Acl> acls = AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT);
|
||||
private MemoryDbContainerManager containers;
|
||||
private MemoryDbProxyManager proxies;
|
||||
private EmulatorConfig config;
|
||||
private MemoryDbService service;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
containers = mock(MemoryDbContainerManager.class);
|
||||
when(containers.isDockerReachable()).thenReturn(true);
|
||||
proxies = mock(MemoryDbProxyManager.class);
|
||||
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().memorydb().proxyBasePort()).thenReturn(17400);
|
||||
when(config.services().memorydb().proxyMaxPort()).thenReturn(17403);
|
||||
when(config.services().memorydb().defaultImage()).thenReturn("valkey/valkey:8");
|
||||
when(config.storage().mode()).thenReturn("persistent");
|
||||
when(config.hostname()).thenReturn(Optional.of("localhost"));
|
||||
StorageFactory storage = mock(StorageFactory.class);
|
||||
when(storage.create(eq("memorydb"), eq("memorydb-clusters.json"), any())).thenAnswer(inv -> clusters);
|
||||
when(storage.create(eq("memorydb"), eq("memorydb-users.json"), any())).thenAnswer(inv -> users);
|
||||
when(storage.create(eq("memorydb"), eq("memorydb-acls.json"), any())).thenAnswer(inv -> acls);
|
||||
service = new MemoryDbService(containers, proxies, mock(SigV4Validator.class), storage, config,
|
||||
new RegionResolver("us-east-1", DEFAULT_ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void creationPersistsItsOwnerVolumeAndPortBeforeStartingDocker() {
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
Cluster pending = clusters.getForAccount(DEFAULT_ACCOUNT, "us-east-1:new").orElseThrow();
|
||||
assertEquals(ClusterStatus.CREATING, pending.getStatus());
|
||||
assertEquals(DEFAULT_ACCOUNT, pending.getAccountId());
|
||||
assertEquals("us-east-1", pending.getRegion());
|
||||
assertEquals(inv.getArgument(2), pending.getVolumeId());
|
||||
assertEquals(17400, pending.getProxyPort());
|
||||
assertNull(pending.getClusterEndpoint());
|
||||
return new MemoryDbContainerHandle("new-cid", inv.getArgument(0), "localhost", 6379);
|
||||
});
|
||||
|
||||
assertEquals(ClusterStatus.AVAILABLE, service.createCluster(spec("new"), "us-east-1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedOwnershipPersistenceDoesNotAllocateRuntimeAndReleasesItsPort() {
|
||||
doThrow(new IllegalStateException("snapshot rejected")).when(clusters)
|
||||
.putAllAtomicallyForAccount(eq(DEFAULT_ACCOUNT), anyMap());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> service.createCluster(spec("new"), "us-east-1"));
|
||||
|
||||
verifyNoInteractions(containers, proxies);
|
||||
assertTrue(clusters.getForAccount(DEFAULT_ACCOUNT, "us-east-1:new").isEmpty());
|
||||
doCallRealMethod().when(clusters).putAllAtomicallyForAccount(eq(DEFAULT_ACCOUNT), anyMap());
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("retry-cid", "retry", "localhost", 6379));
|
||||
assertEquals(17400, service.createCluster(spec("retry"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedCleanupRetainsOwnershipAndPortUntilDeletionRetries() {
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("failed-cid",
|
||||
"000000000000-us-east-1-failed", "localhost", 6379);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(handle);
|
||||
doThrow(new IllegalStateException("proxy rejected")).when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doThrow(new IllegalStateException("Docker cleanup rejected")).when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class,
|
||||
() -> service.createCluster(spec("failed"), "us-east-1"));
|
||||
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
Cluster retained = service.getCluster("failed", "us-east-1");
|
||||
assertEquals(ClusterStatus.CREATING, retained.getStatus());
|
||||
assertNull(retained.getClusterEndpoint());
|
||||
assertEquals("failed-cid", retained.getContainerId());
|
||||
assertNotNull(retained.getVolumeId());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
doNothing().when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
service.deleteCluster("failed", "us-east-1");
|
||||
assertThrows(AwsException.class, () -> service.getCluster("failed", "us-east-1"));
|
||||
assertEquals(17400, service.createCluster(spec("replacement"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRollbackPersistenceKeepsTheClusterUnavailableAndItsPortReserved() {
|
||||
AtomicInteger writes = new AtomicInteger();
|
||||
doAnswer(inv -> {
|
||||
if (writes.incrementAndGet() == 2) {
|
||||
throw new IllegalStateException("final record write rejected");
|
||||
}
|
||||
return inv.callRealMethod();
|
||||
}).when(clusters).putAllAtomicallyForAccount(anyString(), anyMap());
|
||||
doThrow(new IllegalStateException("rollback record deletion rejected"))
|
||||
.when(clusters).deleteAllAtomicallyForAccounts(anyMap());
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> new MemoryDbContainerHandle("owned-cid", inv.getArgument(0),
|
||||
"localhost", 6379));
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class,
|
||||
() -> service.createCluster(spec("failed"), "us-east-1"));
|
||||
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
Cluster retained = service.getCluster("failed", "us-east-1");
|
||||
assertEquals(ClusterStatus.CREATING, retained.getStatus());
|
||||
assertNull(retained.getClusterEndpoint());
|
||||
assertNull(retained.getContainerId());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
doCallRealMethod().when(clusters).deleteAllAtomicallyForAccounts(anyMap());
|
||||
service.deleteCluster("failed", "us-east-1");
|
||||
assertEquals(17400, service.createCluster(spec("replacement"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresEveryOwnerAndRegionWithTheirOwnAuthenticationAndReservedPorts() throws Exception {
|
||||
Cluster first = persisted(DEFAULT_ACCOUNT, "us-east-1", "same", 17400);
|
||||
Cluster second = persisted("111111111111", "eu-west-1", "same", 17401);
|
||||
passwordAcl(first, "first-secret");
|
||||
passwordAcl(second, "second-secret");
|
||||
Map<Integer, MemoryDbAuthProxy.AuthValidator> validators = new ConcurrentHashMap<>();
|
||||
doAnswer(inv -> {
|
||||
validators.put(inv.getArgument(2), inv.getArgument(5));
|
||||
return null;
|
||||
}).when(proxies).startProxy(anyString(), eq(true), anyInt(), anyString(), anyInt(), any());
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> new MemoryDbContainerHandle(inv.getArgument(2), inv.getArgument(0),
|
||||
"127.0.0.1", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(ClusterStatus.AVAILABLE, first.getStatus());
|
||||
assertEquals(ClusterStatus.AVAILABLE, second.getStatus());
|
||||
assertEquals(17400, first.getClusterEndpoint().port());
|
||||
assertEquals(17401, second.getClusterEndpoint().port());
|
||||
assertTrue(validators.get(17400).authenticate("user", "first-secret"));
|
||||
assertFalse(validators.get(17400).authenticate("user", "second-secret"));
|
||||
assertTrue(validators.get(17401).authenticate("user", "second-secret"));
|
||||
assertFalse(validators.get(17401).authenticate("user", "first-secret"));
|
||||
verify(containers).tryStart(eq("000000000000-us-east-1-same"), eq("valkey/valkey:8"), eq(first.getVolumeId()),
|
||||
eq(DEFAULT_ACCOUNT), eq("us-east-1"), eq("same"));
|
||||
verify(containers).tryStart(eq("111111111111-eu-west-1-same"), eq("valkey/valkey:8"), eq(second.getVolumeId()),
|
||||
eq("111111111111"), eq("eu-west-1"), eq("same"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultAccountNameCannotCollideWithAnotherAccountsBackendIdentity() throws Exception {
|
||||
persisted(DEFAULT_ACCOUNT, "us-east-1", "111111111111-eu-west-1-same", 17400);
|
||||
persisted("111111111111", "eu-west-1", "same", 17401);
|
||||
Map<String, String> backendOwners = new ConcurrentHashMap<>();
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
String identity = inv.getArgument(0);
|
||||
String account = inv.getArgument(3);
|
||||
assertNull(backendOwners.putIfAbsent(identity, account),
|
||||
"Backend identities must remain unique across account and region boundaries");
|
||||
return new MemoryDbContainerHandle(inv.getArgument(2), identity, "localhost", 6379);
|
||||
});
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(2, backendOwners.size());
|
||||
assertEquals(2, backendOwners.values().stream().distinct().count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionWhileBackendStartsDoesNotRestoreTheRecordOrReleaseAnotherClustersPort() throws Exception {
|
||||
Cluster old = persisted(DEFAULT_ACCOUNT, "us-east-1", "old", 17400);
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch finish = new CountDownLatch(1);
|
||||
MemoryDbContainerHandle oldHandle = new MemoryDbContainerHandle("old-cid", "old", "localhost", 6379);
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-old"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
started.countDown();
|
||||
assertTrue(finish.await(5, TimeUnit.SECONDS));
|
||||
return oldHandle;
|
||||
});
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-replacement"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("new-cid", "replacement", "localhost", 6379));
|
||||
CompletableFuture<Void> restored = service.restorePersistedRuntime();
|
||||
try {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
assertEquals(ClusterStatus.CREATING, old.getStatus());
|
||||
service.deleteCluster("old", "us-east-1");
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("replacement");
|
||||
spec.setAclName("open-access");
|
||||
Cluster replacement = service.createCluster(spec, "us-east-1");
|
||||
assertEquals(17400, replacement.getProxyPort());
|
||||
finish.countDown();
|
||||
restored.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(clusters.getForAccount(DEFAULT_ACCOUNT, "us-east-1:old").isEmpty());
|
||||
verify(containers).stop(oldHandle);
|
||||
verify(proxies, never()).startProxy(eq("000000000000-us-east-1-old"), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
Cluster nextSpec = new Cluster();
|
||||
nextSpec.setName("next");
|
||||
nextSpec.setAclName("open-access");
|
||||
assertEquals(17401, service.createCluster(nextSpec, "us-east-1").getProxyPort());
|
||||
} finally {
|
||||
finish.countDown();
|
||||
restored.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingPendingCreateDoesNotResurrectItOrReleaseAReusedPort() throws Exception {
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch finish = new CountDownLatch(1);
|
||||
MemoryDbContainerHandle oldHandle = new MemoryDbContainerHandle("old-cid",
|
||||
"000000000000-us-east-1-old", "localhost", 6379);
|
||||
when(containers.tryStart(eq(oldHandle.getClusterName()), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
started.countDown();
|
||||
assertTrue(finish.await(5, TimeUnit.SECONDS));
|
||||
return oldHandle;
|
||||
});
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-other"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("other-cid", "other", "localhost", 6379));
|
||||
CompletableFuture<Cluster> creation = CompletableFuture.supplyAsync(
|
||||
() -> service.createCluster(spec("old"), "us-east-1"));
|
||||
try {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
assertEquals(ClusterStatus.CREATING, service.getCluster("old", "us-east-1").getStatus());
|
||||
service.deleteCluster("old", "us-east-1");
|
||||
assertEquals(17400, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
finish.countDown();
|
||||
assertThrows(ExecutionException.class, () -> creation.get(5, TimeUnit.SECONDS));
|
||||
assertThrows(AwsException.class, () -> service.getCluster("old", "us-east-1"));
|
||||
verify(containers).stop(oldHandle);
|
||||
verify(proxies, never()).startProxy(eq(oldHandle.getClusterName()),
|
||||
anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
assertEquals(17401, service.createCluster(spec("next"), "us-east-1").getProxyPort());
|
||||
} finally {
|
||||
finish.countDown();
|
||||
assertThrows(ExecutionException.class, () -> creation.get(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBackendIsNotAdvertisedAsAvailableAndOtherClustersStillRestore() throws Exception {
|
||||
Cluster failed = persisted(DEFAULT_ACCOUNT, "us-east-1", "failed", 17400);
|
||||
Cluster healthy = persisted(DEFAULT_ACCOUNT, "us-east-1", "healthy", 17401);
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-failed"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenThrow(new IllegalStateException("backend rejected"));
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-healthy"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("healthy-cid", "healthy", "localhost", 6379));
|
||||
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals(ClusterStatus.CREATING, failed.getStatus());
|
||||
assertNull(failed.getClusterEndpoint());
|
||||
assertNull(failed.getContainerId());
|
||||
assertEquals(ClusterStatus.AVAILABLE, healthy.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unprefixedLegacyArnRestoresItsOwnAccountAndRegion() throws Exception {
|
||||
Cluster legacy = spec("legacy");
|
||||
legacy.setArn("arn:aws:memorydb:eu-west-1:111111111111:cluster/legacy");
|
||||
rawClusters.put("legacy", legacy);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("legacy-cid", "legacy", "localhost", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertSame(legacy, clusters.getForAccount("111111111111", "eu-west-1:legacy").orElseThrow());
|
||||
assertEquals("111111111111", legacy.getAccountId());
|
||||
assertEquals("eu-west-1", legacy.getRegion());
|
||||
assertTrue(rawClusters.get("legacy").isEmpty());
|
||||
assertTrue(service.describeClusters(null, "eu-west-1").isEmpty());
|
||||
verify(containers).tryStart(eq("111111111111-eu-west-1-legacy"), eq("valkey/valkey:8"), eq(legacy.getVolumeId()),
|
||||
eq("111111111111"), eq("eu-west-1"), eq("legacy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void oldAccountPrefixedNameMigratesToItsRegionalKey() throws Exception {
|
||||
Cluster legacy = spec("legacy");
|
||||
legacy.setAccountId("111111111111");
|
||||
legacy.setRegion("eu-west-1");
|
||||
rawClusters.put("111111111111/legacy", legacy);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertSame(legacy, clusters.getForAccount("111111111111", "eu-west-1:legacy").orElseThrow());
|
||||
assertTrue(rawClusters.get("111111111111/legacy").isEmpty());
|
||||
assertTrue(service.describeClusters(null, "eu-west-1").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingScopedRecordWinsWithoutDiscardingConflictingLegacyData() throws Exception {
|
||||
Cluster current = persisted(DEFAULT_ACCOUNT, "us-east-1", "same", 17400);
|
||||
Cluster legacy = spec("same");
|
||||
legacy.setVolumeId("retained-legacy-data");
|
||||
rawClusters.put("same", legacy);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(List.of(current), List.copyOf(service.describeClusters(null, "us-east-1")));
|
||||
assertEquals(List.of(current), List.copyOf(service.describeClusters("same", "us-east-1")));
|
||||
assertSame(current, service.getCluster("same", "us-east-1"));
|
||||
assertEquals(List.of(legacy), rawClusters.scan(
|
||||
key -> key.startsWith(DEFAULT_ACCOUNT + "/legacy-clusters/")));
|
||||
assertTrue(rawClusters.get("same").isEmpty());
|
||||
verify(containers, times(1)).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void contradictoryStoredOwnerIsReportedWithoutAllocatingOrReassigningIt() {
|
||||
Cluster inconsistent = spec("conflict");
|
||||
inconsistent.setAccountId(DEFAULT_ACCOUNT);
|
||||
inconsistent.setRegion("eu-west-1");
|
||||
rawClusters.put("111111111111/eu-west-1:conflict", inconsistent);
|
||||
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals(DEFAULT_ACCOUNT, inconsistent.getAccountId());
|
||||
assertSame(inconsistent, rawClusters.get("111111111111/eu-west-1:conflict").orElseThrow());
|
||||
verifyNoInteractions(containers, proxies);
|
||||
}
|
||||
|
||||
@Test
|
||||
void restorationUsesThePersistedArnRegionWhenTheLegacyRegionFieldIsMissing() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "eu-west-1", "legacy", 17400);
|
||||
cluster.setRegion(null);
|
||||
cluster.setArn("arn:aws:memorydb:eu-west-1:000000000000:cluster/legacy");
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("restored-cid", "legacy", "localhost", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("eu-west-1", cluster.getRegion());
|
||||
verify(containers).tryStart(eq("000000000000-eu-west-1-legacy"), eq("valkey/valkey:8"), eq(cluster.getVolumeId()),
|
||||
eq(DEFAULT_ACCOUNT), eq("eu-west-1"), eq("legacy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingLegacyRecordKeepsItsStoredOwnerAndCanBeDeletedAfterRestart() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "deleting", 17400);
|
||||
cluster.setAccountId(null);
|
||||
cluster.setRegion(null);
|
||||
cluster.setStatus(ClusterStatus.DELETING);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
verifyNoInteractions(containers, proxies);
|
||||
assertEquals(DEFAULT_ACCOUNT, cluster.getAccountId());
|
||||
assertEquals("us-east-1", cluster.getRegion());
|
||||
service.deleteCluster("deleting", "us-east-1");
|
||||
assertThrows(AwsException.class, () -> service.getCluster("deleting", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restorationRetiresPersistedBackendBeforeReplacingIt() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "legacy", 17400);
|
||||
cluster.setContainerId("legacy-cid");
|
||||
cluster.setContainerHost("localhost");
|
||||
cluster.setContainerPort(6379);
|
||||
when(containers.isDockerReachable()).thenReturn(true);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("replacement-cid", "legacy", "localhost", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
InOrder ordering = inOrder(containers);
|
||||
ordering.verify(containers).isDockerReachable();
|
||||
ordering.verify(containers).stop(argThat(handle -> "legacy-cid".equals(handle.getContainerId())));
|
||||
ordering.verify(containers).tryStart(eq("000000000000-us-east-1-legacy"), eq("valkey/valkey:8"),
|
||||
eq(cluster.getVolumeId()), eq(DEFAULT_ACCOUNT), eq("us-east-1"), eq("legacy"));
|
||||
assertEquals("replacement-cid", cluster.getContainerId());
|
||||
assertEquals(ClusterStatus.AVAILABLE, cluster.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unavailableDaemonDoesNotDiscardPersistedBackendOwnership() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "legacy", 17400);
|
||||
cluster.setContainerId("legacy-cid");
|
||||
cluster.setContainerHost("localhost");
|
||||
cluster.setContainerPort(6379);
|
||||
String volumeId = cluster.getVolumeId();
|
||||
when(containers.isDockerReachable()).thenReturn(false);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("legacy-cid", cluster.getContainerId());
|
||||
assertEquals(volumeId, cluster.getVolumeId());
|
||||
assertEquals(ClusterStatus.AVAILABLE, cluster.getStatus());
|
||||
verify(containers, never()).stop(any(MemoryDbContainerHandle.class));
|
||||
verify(containers, never()).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
verifyNoInteractions(proxies);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPersistedBackendCleanupKeepsTheExactOldBackendForRetry() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "legacy", 17400);
|
||||
cluster.setContainerId("legacy-cid");
|
||||
cluster.setContainerHost("localhost");
|
||||
cluster.setContainerPort(6379);
|
||||
when(containers.isDockerReachable()).thenReturn(true);
|
||||
doThrow(new IllegalStateException("legacy cleanup rejected")).when(containers)
|
||||
.stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals("legacy-cid", cluster.getContainerId());
|
||||
assertEquals(ClusterStatus.CREATING, cluster.getStatus());
|
||||
assertNull(cluster.getClusterEndpoint());
|
||||
verify(containers, never()).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRestoreCleanupRetainsItsBackendPortAndDataForDeletionRetry() throws Exception {
|
||||
Cluster failed = persisted(DEFAULT_ACCOUNT, "us-east-1", "failed", 17400);
|
||||
String volumeId = failed.getVolumeId();
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("restore-cid",
|
||||
"000000000000-us-east-1-failed", "localhost", 6379);
|
||||
when(containers.tryStart(eq(handle.getClusterName()), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(handle);
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-other"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("other-cid", "other", "localhost", 6379));
|
||||
doThrow(new IllegalStateException("proxy rejected")).when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doThrow(new IllegalStateException("Docker cleanup rejected")).when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals(1, failure.getCause().getSuppressed().length);
|
||||
assertEquals(ClusterStatus.CREATING, failed.getStatus());
|
||||
assertNull(failed.getClusterEndpoint());
|
||||
assertEquals("restore-cid", failed.getContainerId());
|
||||
assertEquals(volumeId, failed.getVolumeId());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
verify(containers, never()).removeStorage(anyString(), anyString());
|
||||
doNothing().when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
service.deleteCluster("failed", "us-east-1");
|
||||
verify(containers).removeStorage(handle.getClusterName(), volumeId);
|
||||
assertThrows(AwsException.class, () -> service.getCluster("failed", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryingRestorationReusesThePortRetainedAfterCleanupFailure() throws Exception {
|
||||
Cluster failed = persisted(DEFAULT_ACCOUNT, "us-east-1", "failed", 17400);
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("restore-cid",
|
||||
"000000000000-us-east-1-failed", "localhost", 6379);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(handle);
|
||||
doThrow(new IllegalStateException("proxy rejected")).when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doThrow(new IllegalStateException("Docker cleanup rejected")).when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
doNothing().when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doNothing().when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(ClusterStatus.AVAILABLE, failed.getStatus());
|
||||
assertEquals(17400, failed.getClusterEndpoint().port());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mockRestorationDoesNotAllocateContainersOrProxies() throws Exception {
|
||||
persisted(DEFAULT_ACCOUNT, "us-east-1", "mocked", 17400);
|
||||
when(config.services().memorydb().mock()).thenReturn(true);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
verifyNoInteractions(containers, proxies);
|
||||
}
|
||||
|
||||
private Cluster persisted(String account, String region, String name, int port) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(name);
|
||||
cluster.setAccountId(account);
|
||||
cluster.setRegion(region);
|
||||
cluster.setStatus(ClusterStatus.AVAILABLE);
|
||||
cluster.setAclName("open-access");
|
||||
cluster.setProxyPort(port);
|
||||
cluster.setVolumeId(account + "-" + region + "-" + name);
|
||||
clusters.putForAccount(account, region + ":" + name, cluster);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private Cluster spec(String name) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(name);
|
||||
cluster.setAclName("open-access");
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private void passwordAcl(Cluster cluster, String password) {
|
||||
cluster.setAclName("private");
|
||||
Acl acl = new Acl();
|
||||
acl.setName("private");
|
||||
acl.setUserNames(List.of("user"));
|
||||
acls.putForAccount(cluster.getAccountId(), cluster.getRegion() + ":private", acl);
|
||||
User user = new User();
|
||||
user.setName("user");
|
||||
user.setAuthMode(AuthMode.PASSWORD);
|
||||
user.setPasswords(List.of(password));
|
||||
users.putForAccount(cluster.getAccountId(), cluster.getRegion() + ":user", user);
|
||||
}
|
||||
}
|
||||
+38
-13
@@ -30,6 +30,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -81,7 +82,7 @@ class MemoryDbServiceTest {
|
||||
"000000000000", inv.getArgument(2)).toString());
|
||||
|
||||
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
when(containerManager.tryStart(anyString(), anyString()))
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "cluster", "localhost", 6379));
|
||||
doNothing().when(proxyManager).startProxy(anyString(), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
|
||||
@@ -89,6 +90,29 @@ class MemoryDbServiceTest {
|
||||
storageFactory, config, regionResolver);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recreatedPersistentClusterDoesNotReuseRetainedDataVolume() {
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(storage.mode()).thenReturn("persistent");
|
||||
when(containerManager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "durable", "localhost", 6379));
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("durable");
|
||||
spec.setAclName("open-access");
|
||||
|
||||
Cluster first = service.createCluster(spec, "us-east-1");
|
||||
service.deleteCluster("durable", "us-east-1");
|
||||
Cluster replacement = service.createCluster(spec, "us-east-1");
|
||||
|
||||
assertNotEquals(first.getVolumeId(), replacement.getVolumeId());
|
||||
verify(containerManager).removeStorage("000000000000-us-east-1-durable", first.getVolumeId());
|
||||
verify(containerManager).tryStart(eq("000000000000-us-east-1-durable"), eq("valkey/valkey:8"),
|
||||
eq(first.getVolumeId()), eq("000000000000"), eq("us-east-1"), eq("durable"));
|
||||
verify(containerManager).tryStart(eq("000000000000-us-east-1-durable"), eq("valkey/valkey:8"),
|
||||
eq(replacement.getVolumeId()), eq("000000000000"), eq("us-east-1"), eq("durable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndDescribeCluster() {
|
||||
Cluster spec = new Cluster();
|
||||
@@ -341,7 +365,7 @@ class MemoryDbServiceTest {
|
||||
void failedProvisioningReleasesProxyPort() {
|
||||
when(mdbConfig.proxyBasePort()).thenReturn(16400);
|
||||
when(mdbConfig.proxyMaxPort()).thenReturn(16400); // exactly one port available
|
||||
when(containerManager.tryStart(anyString(), anyString()))
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString()))
|
||||
.thenThrow(new RuntimeException("docker unavailable"))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "c2", "localhost", 6379));
|
||||
|
||||
@@ -361,11 +385,11 @@ class MemoryDbServiceTest {
|
||||
@Test
|
||||
void failedProvisioningRollsBackContainerAndReleasesProxyPort() {
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("cid", "c1", "localhost", 6379);
|
||||
when(containerManager.tryStart(anyString(), anyString())).thenReturn(handle);
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString())).thenReturn(handle);
|
||||
|
||||
// Proxy startup blows up after the port is reserved and the container is started.
|
||||
doThrow(new RuntimeException("proxy boom"))
|
||||
.when(proxyManager).startProxy(eq("c1"), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
.when(proxyManager).startProxy(eq("000000000000-us-east-1-c1"), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("c1");
|
||||
@@ -378,9 +402,9 @@ class MemoryDbServiceTest {
|
||||
// handle from this request, not by name: a concurrent create for the same cluster name
|
||||
// could have raced ahead and overwritten the registered container, and looking it up by
|
||||
// name here would risk stopping that other request's container instead of this one's.
|
||||
verify(proxyManager).stopProxy("c1");
|
||||
verify(proxyManager).stopProxy("000000000000-us-east-1-c1");
|
||||
verify(containerManager).stop(handle);
|
||||
verify(containerManager, never()).stopByClusterName(anyString());
|
||||
verify(containerManager, never()).stopByClusterName(anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
// The reserved proxy port was released: a subsequent successful create reuses the base port
|
||||
// instead of skipping to the next one (which is what a leak would cause).
|
||||
@@ -400,7 +424,8 @@ class MemoryDbServiceTest {
|
||||
// and (crucially) a readiness timeout, where start() created + registered the container
|
||||
// before throwing, so no handle ever reaches the service.
|
||||
doThrow(new RuntimeException("readiness boom"))
|
||||
.when(containerManager).tryStart(eq("c1"), anyString());
|
||||
.when(containerManager).tryStart(eq("000000000000-us-east-1-c1"), anyString(), any(),
|
||||
anyString(), anyString(), anyString());
|
||||
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("c1");
|
||||
@@ -413,10 +438,10 @@ class MemoryDbServiceTest {
|
||||
verify(proxyManager, never()).stopProxy(anyString());
|
||||
// ...but the container must still be cleaned up by name, since start() may have created
|
||||
// and registered it before failing. Cleaning up by handle here would orphan it.
|
||||
verify(containerManager).stopByClusterName("c1");
|
||||
verify(containerManager).stopByClusterName(eq("000000000000-us-east-1-c1"), anyString(), anyString(), anyString());
|
||||
|
||||
// The reserved proxy port was still released: a subsequent successful create reuses the base port.
|
||||
when(containerManager.tryStart(anyString(), anyString()))
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "c2", "localhost", 6379));
|
||||
Cluster second = new Cluster();
|
||||
second.setName("c2");
|
||||
@@ -445,7 +470,7 @@ class MemoryDbServiceTest {
|
||||
void concurrentCreateForSameNameIsRejectedWhileFirstIsProvisioning() throws InterruptedException {
|
||||
CountDownLatch startedLatch = new CountDownLatch(1);
|
||||
CountDownLatch releaseLatch = new CountDownLatch(1);
|
||||
when(containerManager.tryStart(anyString(), anyString())).thenAnswer(inv -> {
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString())).thenAnswer(inv -> {
|
||||
startedLatch.countDown();
|
||||
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
|
||||
return new MemoryDbContainerHandle("cid", "c1", "localhost", 6379);
|
||||
@@ -465,7 +490,7 @@ class MemoryDbServiceTest {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.createCluster(spec2, "us-east-1"));
|
||||
assertEquals("ClusterAlreadyExistsFault", ex.jsonType());
|
||||
verify(containerManager, never()).stop(any());
|
||||
verify(containerManager, never()).stopByClusterName(anyString());
|
||||
verify(containerManager, never()).stopByClusterName(anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
releaseLatch.countDown();
|
||||
firstRequest.join(5000);
|
||||
@@ -530,7 +555,7 @@ class MemoryDbServiceTest {
|
||||
}
|
||||
}
|
||||
assertEquals(1, succeeded, "exactly one create of the name succeeds");
|
||||
verify(containerManager, times(1)).tryStart(anyString(), anyString());
|
||||
verify(containerManager, times(1)).tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -589,7 +614,7 @@ class MemoryDbServiceTest {
|
||||
// tryStart() returns null when no Docker daemon is reachable. The cluster record is
|
||||
// metadata, so the create still succeeds, the cluster reaches 'available' on the first
|
||||
// describe (what SDK/Terraform waiters poll), and no auth proxy is started.
|
||||
when(containerManager.tryStart(anyString(), anyString())).thenReturn(null);
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString())).thenReturn(null);
|
||||
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("no-docker-cluster");
|
||||
|
||||
+201
-36
@@ -8,32 +8,107 @@ import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class MemoryDbContainerManagerTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(MemoryDbContainerManagerTest.class);
|
||||
@Test
|
||||
void failedStartPreservesTheCleanupAwareLifecycleFailure() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
RuntimeException failure = new RuntimeException("backend start denied");
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenThrow(failure);
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
|
||||
assertSame(failure, assertThrows(RuntimeException.class,
|
||||
() -> manager.start("cache", "valkey/valkey:8")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingBackendReclaimsImageDeclaredAnonymousVolumes() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("owned-cid", "cache", "localhost", 6379);
|
||||
|
||||
manager.stop(handle);
|
||||
|
||||
verify(lifecycle).stopAndRemoveStrict("owned-cid", null, 5, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownRejectsNewBackendStarts() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
|
||||
manager.stopAll();
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start("late", "valkey/valkey:8"));
|
||||
verify(lifecycle, Mockito.never()).createAndStartEphemeral(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownWaitsForAdmittedCreateAndRemovesItsLateBackend() throws Exception {
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
CountDownLatch finish = new CountDownLatch(1);
|
||||
CountDownLatch shutdownStarted = new CountDownLatch(1);
|
||||
try (ServerSocket backend = new ServerSocket(0)) {
|
||||
CompletableFuture<Void> responder = startPongResponder(backend, 1);
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenAnswer(inv -> {
|
||||
entered.countDown();
|
||||
assertTrue(finish.await(5, TimeUnit.SECONDS));
|
||||
return new ContainerLifecycleManager.ContainerInfo("late-cid",
|
||||
Map.of(6379, new ContainerLifecycleManager.EndpointInfo(
|
||||
"127.0.0.1", backend.getLocalPort())));
|
||||
});
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
CompletableFuture<MemoryDbContainerHandle> starting =
|
||||
CompletableFuture.supplyAsync(() -> manager.start("late", "valkey/valkey:8"));
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
CompletableFuture<Void> shutdown = CompletableFuture.runAsync(() -> {
|
||||
shutdownStarted.countDown();
|
||||
manager.stopAll();
|
||||
});
|
||||
try {
|
||||
assertTrue(shutdownStarted.await(5, TimeUnit.SECONDS));
|
||||
assertThrows(TimeoutException.class, () -> shutdown.get(1, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
finish.countDown();
|
||||
assertThrows(ExecutionException.class, () -> starting.get(5, TimeUnit.SECONDS));
|
||||
shutdown.get(5, TimeUnit.SECONDS);
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
verify(lifecycle).stopAndRemoveStrict("late-cid", null, 5, true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopByClusterNameRemovesByDeterministicNameWhenNothingRegistered() {
|
||||
@@ -46,7 +121,7 @@ class MemoryDbContainerManagerTest {
|
||||
// Rollback must still fall back to the deterministic name so nothing is orphaned.
|
||||
manager.stopByClusterName("my-cluster");
|
||||
|
||||
verify(lifecycleManager).removeIfExists("floci-aws-memorydb-my-cluster");
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-aws-memorydb-my-cluster", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -54,7 +129,7 @@ class MemoryDbContainerManagerTest {
|
||||
// Floci running inside Docker without a mounted daemon socket: the MemoryDB control
|
||||
// plane must keep working, so the failure is reported rather than propagated.
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
when(lifecycleManager.createAndStartEphemeral(any()))
|
||||
.thenThrow(new RuntimeException("java.net.SocketException: No such file or directory"));
|
||||
when(lifecycleManager.getDockerClient()).thenThrow(
|
||||
new RuntimeException("java.net.SocketException: No such file or directory"));
|
||||
@@ -73,7 +148,7 @@ class MemoryDbContainerManagerTest {
|
||||
// A reachable daemon that cannot start the container is a genuine failure, not a
|
||||
// degraded mode: CreateCluster must still surface it.
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
when(lifecycleManager.createAndStartEphemeral(any()))
|
||||
.thenThrow(new RuntimeException("no such image: valkey/valkey:8"));
|
||||
DockerClient dockerClient = mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
@@ -86,26 +161,14 @@ class MemoryDbContainerManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryStartReturnsTheHandleOnceADaemonIsReachable() throws IOException, InterruptedException {
|
||||
void tryStartReturnsTheHandleOnceADaemonIsReachable() throws Exception {
|
||||
// Real loopback socket standing in for the backend container's Redis port, so the
|
||||
// manager's PING/PONG readiness probe succeeds without a real container.
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
Thread responder = new Thread(() -> {
|
||||
try (Socket socket = serverSocket.accept()) {
|
||||
socket.getInputStream().read(new byte[64]);
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
// Test teardown races the socket close; nothing left to assert on.
|
||||
LOG.debugv(e, "Acceptor socket closed during test teardown");
|
||||
}
|
||||
});
|
||||
responder.setDaemon(true);
|
||||
responder.start();
|
||||
CompletableFuture<Void> responder = startPongResponder(serverSocket, 1);
|
||||
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(6379, new ContainerLifecycleManager.EndpointInfo(
|
||||
"127.0.0.1", serverSocket.getLocalPort()))));
|
||||
|
||||
@@ -115,28 +178,23 @@ class MemoryDbContainerManagerTest {
|
||||
|
||||
assertEquals("container-id", handle.getContainerId());
|
||||
assertEquals(serverSocket.getLocalPort(), handle.getPort());
|
||||
responder.join(5000);
|
||||
Mockito.doThrow(new RuntimeException("cleanup rejected")).doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict("container-id", null, 5, true);
|
||||
assertThrows(RuntimeException.class, () -> manager.stop(handle));
|
||||
manager.stopAll();
|
||||
manager.stopAll();
|
||||
verify(lifecycleManager, Mockito.times(2)).stopAndRemoveStrict("container-id", null, 5, true);
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void startLabelsContainerWithResourceIdentity() throws IOException {
|
||||
void startLabelsContainerWithResourceIdentity() throws Exception {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
Thread responder = new Thread(() -> {
|
||||
try (Socket socket = serverSocket.accept()) {
|
||||
socket.getInputStream().read(new byte[64]);
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Acceptor socket closed during test teardown");
|
||||
}
|
||||
});
|
||||
responder.setDaemon(true);
|
||||
responder.start();
|
||||
CompletableFuture<Void> responder = startPongResponder(serverSocket, 1);
|
||||
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(6379, new ContainerLifecycleManager.EndpointInfo(
|
||||
"127.0.0.1", serverSocket.getLocalPort()))));
|
||||
|
||||
@@ -164,9 +222,110 @@ class MemoryDbContainerManagerTest {
|
||||
"io.floci.resource-id", "cluster1",
|
||||
"io.floci.account", "000000000000",
|
||||
"io.floci.region", "us-east-1"));
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void logicalDefaultNamesKeepLogsAndContainersWhileRuntimeKeysStayScoped() throws Exception {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
ContainerBuilder containers = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
when(containers.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(new ContainerSpec("valkey/valkey:8"));
|
||||
ContainerLogStreamer logs = mock(ContainerLogStreamer.class);
|
||||
when(logs.generateLogStreamName(anyString())).thenReturn("engine");
|
||||
MemoryDbContainerManager manager = newManager(containers, lifecycle, logs);
|
||||
String defaultIdentity = "000000000000-us-east-1-cache";
|
||||
String collisionIdentity = "000000000000-us-east-1-111111111111-eu-west-1-same";
|
||||
String foreignIdentity = "111111111111-eu-west-1-same";
|
||||
try (ServerSocket backend = new ServerSocket(0)) {
|
||||
CompletableFuture<Void> responder = startPongResponder(backend, 3);
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenReturn(
|
||||
new ContainerLifecycleManager.ContainerInfo("default-cid", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))),
|
||||
new ContainerLifecycleManager.ContainerInfo("collision-cid", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))),
|
||||
new ContainerLifecycleManager.ContainerInfo("foreign-cid", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))));
|
||||
try {
|
||||
MemoryDbContainerHandle first = manager.tryStart(defaultIdentity, "valkey/valkey:8", null,
|
||||
"000000000000", "us-east-1", "cache");
|
||||
MemoryDbContainerHandle collision = manager.tryStart(collisionIdentity, "valkey/valkey:8", null,
|
||||
"000000000000", "us-east-1", "111111111111-eu-west-1-same");
|
||||
MemoryDbContainerHandle foreign = manager.tryStart(foreignIdentity, "valkey/valkey:8", null,
|
||||
"111111111111", "eu-west-1", "same");
|
||||
assertEquals(defaultIdentity, first.getClusterName());
|
||||
assertEquals(collisionIdentity, collision.getClusterName());
|
||||
assertEquals(foreignIdentity, foreign.getClusterName());
|
||||
ArgumentCaptor<String> names = ArgumentCaptor.forClass(String.class);
|
||||
verify(builder, times(3)).withName(names.capture());
|
||||
assertEquals(List.of("floci-aws-memorydb-cache",
|
||||
"floci-aws-memorydb-111111111111-eu-west-1-same",
|
||||
"floci-aws-memorydb-111111111111_eu-west-1_same"), names.getAllValues());
|
||||
verify(logs).attach("default-cid", "/aws/memorydb/cluster/cache/engine-log", "engine",
|
||||
"us-east-1", "memorydb:" + defaultIdentity);
|
||||
verify(logs).attach("collision-cid",
|
||||
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
|
||||
"us-east-1", "memorydb:" + collisionIdentity);
|
||||
verify(logs).attach("foreign-cid",
|
||||
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
|
||||
"eu-west-1", "memorydb:" + foreignIdentity);
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
backend.close();
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
verify(lifecycle).stopAndRemoveStrict("default-cid", null, 5, true);
|
||||
verify(lifecycle).stopAndRemoveStrict("collision-cid", null, 5, true);
|
||||
verify(lifecycle).stopAndRemoveStrict("foreign-cid", null, 5, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedCreationRollbackUsesTheSameDefaultAndForeignContainerNames() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
ContainerBuilder containers = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
when(containers.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(new ContainerSpec("valkey/valkey:8"));
|
||||
RuntimeException failure = new IllegalStateException("creation failed before registration");
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenThrow(failure);
|
||||
MemoryDbContainerManager manager = newManager(containers, lifecycle, mock(ContainerLogStreamer.class));
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> manager.start("000000000000-us-east-1-cache", "valkey/valkey:8", null,
|
||||
"000000000000", "us-east-1", "cache")));
|
||||
manager.stopByClusterName("000000000000-us-east-1-cache", "000000000000", "us-east-1", "cache");
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> manager.start("111111111111-eu-west-1-cache", "valkey/valkey:8", null,
|
||||
"111111111111", "eu-west-1", "cache")));
|
||||
manager.stopByClusterName("111111111111-eu-west-1-cache", "111111111111", "eu-west-1", "cache");
|
||||
verify(lifecycle, times(2)).removeIfExistsStrict("floci-aws-memorydb-cache", true);
|
||||
verify(lifecycle, times(2)).removeIfExistsStrict("floci-aws-memorydb-111111111111_eu-west-1_cache", true);
|
||||
}
|
||||
|
||||
private static CompletableFuture<Void> startPongResponder(ServerSocket backend, int connections) {
|
||||
CompletableFuture<Void> completed = new CompletableFuture<>();
|
||||
Thread responder = new Thread(() -> {
|
||||
try {
|
||||
for (int i = 0; i < connections; i++) {
|
||||
try (Socket socket = backend.accept()) {
|
||||
socket.setSoTimeout(5000);
|
||||
socket.getInputStream().read(new byte[64]);
|
||||
socket.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
|
||||
socket.getOutputStream().flush();
|
||||
}
|
||||
}
|
||||
completed.complete(null);
|
||||
} catch (IOException e) {
|
||||
completed.completeExceptionally(e);
|
||||
}
|
||||
});
|
||||
responder.setDaemon(true);
|
||||
responder.start();
|
||||
return completed;
|
||||
}
|
||||
|
||||
private MemoryDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {
|
||||
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
@@ -176,6 +335,12 @@ class MemoryDbContainerManagerTest {
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
|
||||
return newManager(containerBuilder, lifecycleManager, logStreamer);
|
||||
}
|
||||
|
||||
private MemoryDbContainerManager newManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerLogStreamer logStreamer) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.MemoryDbServiceConfig memorydb = mock(EmulatorConfig.MemoryDbServiceConfig.class);
|
||||
|
||||
Reference in new issue
Block a user