Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(rds): global clusters and FailoverDBCluster (#3819)

David54a5cf3e9c94
diff --git a/docs/services/rds.md b/docs/services/rds.md
index cc2be4d766..da99068f9c 100644
--- a/docs/services/rds.md
+++ b/docs/services/rds.md
@@ -66,7 +66,14 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou
| `ModifyDBProxyTargetGroup` | Update target-group connection-pool configuration |
| `DescribeDBProxyTargets` | List a proxy target group's registered targets |
| `DescribeDBClusterSnapshots` | Return an empty cluster-snapshot list (snapshots are not modeled) |
-| `DescribeGlobalClusters` | List global clusters — always empty, as none are modeled |
+| `DescribeGlobalClusters` | List the account's global clusters with their primary and secondary members; see [Global clusters](#global-clusters) |
+| `CreateGlobalCluster` | Create an Aurora global database, empty or with an existing Aurora cluster as its primary |
+| `ModifyGlobalCluster` | Rename a global cluster, set deletion protection, or upgrade its engine version (members follow) |
+| `DeleteGlobalCluster` | Delete a global cluster once every member has been removed and deletion protection is off |
+| `RemoveFromGlobalCluster` | Detach a member into a standalone cluster; the primary goes last |
+| `FailoverGlobalCluster` | Promote a secondary to primary (failover with `AllowDataLoss`, or switchover) |
+| `SwitchoverGlobalCluster` | Promote a secondary to primary and demote the current primary to a secondary |
+| `FailoverDBCluster` | Move a DB cluster's writer role to a reader instance, the named one or the first |
| `AddTagsToResource` | Add tags to a DB resource |
| `ListTagsForResource` | List tags for a DB resource |
| `RemoveTagsFromResource` | Remove tags from a DB resource |
@@ -350,6 +357,36 @@ same-region replicas; a cross-region replica keeps its link with the replication
`terminated` until it is promoted or deleted, which is what AWS does for PostgreSQL. Deleting a
replica drops it from its source's list.
+## Global clusters
+
+`CreateGlobalCluster` creates an Aurora global database (`aurora-mysql` or `aurora-postgresql`),
+either empty or with an existing Aurora cluster as its primary through `SourceDBClusterIdentifier`
+(an ARN, or an identifier in the request's region), in which case engine, version, database name
+and encryption come from that cluster and may not be given, as on AWS. The record is account wide:
+its ARN has no region and `DescribeGlobalClusters` lists it from any region.
+
+`CreateDBCluster` with `GlobalClusterIdentifier` joins a cluster: the first one becomes the
+primary, every later one a secondary. A secondary must be in a region that holds neither the
+primary nor another secondary, may not carry its own master credentials or database name (it takes
+the primary's), and its database is initialised from a `pg_dumpall` of the primary the way a read
+replica is, so only `aurora-postgresql` primaries accept secondaries; writes after that are not
+streamed. `DescribeGlobalClusters` reports every member with `IsWriter` and, on the primary, the
+secondaries under `Readers`; `DescribeDBClusters` reports `GlobalClusterIdentifier` on members.
+
+`SwitchoverGlobalCluster`, and `FailoverGlobalCluster` with or without `AllowDataLoss`, promote
+the named secondary and demote the current primary to a secondary, the topology AWS keeps for a
+switchover and restores after a managed failover once the old primary region is healthy again.
+The response is the completed state; AWS answers with a pending `FailoverState` because the
+operation runs asynchronously there. `RemoveFromGlobalCluster` detaches a member into a standalone
+cluster; the primary can only be removed once every secondary is gone, and deleting the primary
+cluster while secondaries remain is refused the same way. `DeleteGlobalCluster` needs an empty
+global cluster with deletion protection off.
+
+`FailoverDBCluster` moves the writer role inside a DB cluster to the named reader instance, or to
+the first reader when none is named; a cluster with no reader has nothing to fail over to and is
+refused. `DescribeDBClusters` reports the role as `IsClusterWriter`, and deleting the writer
+promotes a remaining member, as Aurora does on its own.
+
## Persistence
Each DB instance and cluster gets its own named Docker volume (`floci-rds-{volumeId}`) created
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java
index e4ae7e8fc7..18476c3b71 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java
@@ -5,7 +5,6 @@ import io.github.hectorvent.floci.core.common.AwsErrorMessages;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
-import io.github.hectorvent.floci.core.common.RdsFamilyQuerySupport;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
@@ -22,6 +21,8 @@ import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
+import io.github.hectorvent.floci.services.rds.model.GlobalCluster;
+import io.github.hectorvent.floci.services.rds.model.GlobalClusterMember;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.model.RdsEvent;
@@ -122,6 +123,13 @@ public class RdsQueryHandler {
case "DescribeDBProxyTargets" -> handleDescribeDbProxyTargets(params, region);
case "DescribeDBClusterSnapshots" -> handleDescribeDbClusterSnapshots(params);
case "DescribeGlobalClusters" -> handleDescribeGlobalClusters(params);
+ case "CreateGlobalCluster" -> handleCreateGlobalCluster(params, region);
+ case "ModifyGlobalCluster" -> handleModifyGlobalCluster(params);
+ case "DeleteGlobalCluster" -> handleDeleteGlobalCluster(params);
+ case "RemoveFromGlobalCluster" -> handleRemoveFromGlobalCluster(params, region);
+ case "FailoverGlobalCluster" -> handleFailoverGlobalCluster(params, region);
+ case "SwitchoverGlobalCluster" -> handleSwitchoverGlobalCluster(params, region);
+ case "FailoverDBCluster" -> handleFailoverDbCluster(params, region);
case "AddTagsToResource" -> handleAddTagsToResource(params, region);
case "ListTagsForResource" -> handleListTagsForResource(params, region);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params, region);
@@ -682,11 +690,18 @@ public class RdsQueryHandler {
Double serverlessV2Max = parseDoubleParam(params, "ServerlessV2ScalingConfiguration.MaxCapacity");
Integer serverlessV2SecondsUntilAutoPause = parseIntegerParam(
params, "ServerlessV2ScalingConfiguration.SecondsUntilAutoPause");
- DbCluster cluster = service.createDbCluster(id, engine, engineVersion, masterUsername,
- masterPassword, databaseName, iamEnabled, paramGroupName,
- dbSubnetGroupName, availabilityZone, multiAz, region,
- serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
- manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted);
+ String globalClusterIdentifier = params.getFirst("GlobalClusterIdentifier");
+ DbCluster cluster = globalClusterIdentifier != null && !globalClusterIdentifier.isBlank()
+ ? service.createDbClusterInGlobalCluster(globalClusterIdentifier, id, engine,
+ params.getFirst("EngineVersion"), masterUsername, masterPassword, databaseName,
+ iamEnabled, paramGroupName, dbSubnetGroupName, availabilityZone, multiAz, region,
+ serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
+ manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted)
+ : service.createDbCluster(id, engine, engineVersion, masterUsername,
+ masterPassword, databaseName, iamEnabled, paramGroupName,
+ dbSubnetGroupName, availabilityZone, multiAz, region,
+ serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
+ manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted);
String result = dbClusterXml(cluster);
return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -1651,8 +1666,207 @@ public class RdsQueryHandler {
return xml.build();
}
+ // ── Global clusters ───────────────────────────────────────────────────────
+
private Response handleDescribeGlobalClusters(MultivaluedMap<String, String> params) {
- return RdsFamilyQuerySupport.handleDescribeGlobalClusters(LOG, params);
+ String maxRecords = params.getFirst("MaxRecords");
+ if (maxRecords != null && !maxRecords.isBlank()) {
+ int max = -1;
+ try {
+ max = Integer.parseInt(maxRecords.trim());
+ } catch (NumberFormatException e) {
+ LOG.debugv("Non-numeric MaxRecords {0} on DescribeGlobalClusters", maxRecords);
+ }
+ if (max < 20 || max > 100) {
+ return AwsQueryResponse.error("InvalidParameterValue",
+ "Invalid value " + maxRecords + " for MaxRecords. Must be between 20 and 100",
+ AwsNamespaces.RDS, 400);
+ }
+ }
+ try {
+ // AWS resolves the identifier before it looks at the marker, so a bad marker with an
+ // unknown identifier answers not found.
+ String identifier = params.getFirst("GlobalClusterIdentifier");
+ List<GlobalCluster> result = identifier != null && !identifier.isBlank()
+ ? List.of(service.describeGlobalCluster(identifier))
+ : service.listGlobalClusters();
+ String marker = params.getFirst("Marker");
+ if (marker != null && !marker.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "The request token is invalid.", AwsNamespaces.RDS, 400);
+ }
+ XmlBuilder xml = new XmlBuilder().start("GlobalClusters");
+ for (GlobalCluster global : result) {
+ xml.raw(globalClusterXml(global, "GlobalClusterMember"));
+ }
+ xml.end("GlobalClusters");
+ return Response.ok(AwsQueryResponse.envelope("DescribeGlobalClusters", AwsNamespaces.RDS, xml.build())).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleCreateGlobalCluster(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("GlobalClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "GlobalClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ GlobalCluster global = service.createGlobalCluster(id,
+ params.getFirst("SourceDBClusterIdentifier"),
+ params.getFirst("Engine"),
+ params.getFirst("EngineVersion"),
+ params.getFirst("DatabaseName"),
+ parseOptionalBoolean(params, "StorageEncrypted"),
+ parseOptionalBoolean(params, "DeletionProtection"),
+ parseTags(params), region);
+ return Response.ok(AwsQueryResponse.envelope("CreateGlobalCluster", AwsNamespaces.RDS,
+ globalClusterXml(global, "GlobalCluster"))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleModifyGlobalCluster(MultivaluedMap<String, String> params) {
+ String id = params.getFirst("GlobalClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "GlobalClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ GlobalCluster global = service.modifyGlobalCluster(id,
+ params.getFirst("NewGlobalClusterIdentifier"),
+ parseOptionalBoolean(params, "DeletionProtection"),
+ params.getFirst("EngineVersion"),
+ parseOptionalBoolean(params, "AllowMajorVersionUpgrade"));
+ return Response.ok(AwsQueryResponse.envelope("ModifyGlobalCluster", AwsNamespaces.RDS,
+ globalClusterXml(global, "GlobalCluster"))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleDeleteGlobalCluster(MultivaluedMap<String, String> params) {
+ String id = params.getFirst("GlobalClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "GlobalClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ GlobalCluster global = service.deleteGlobalCluster(id);
+ return Response.ok(AwsQueryResponse.envelope("DeleteGlobalCluster", AwsNamespaces.RDS,
+ globalClusterXml(global, "GlobalCluster"))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleRemoveFromGlobalCluster(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("GlobalClusterIdentifier");
+ String clusterId = params.getFirst("DbClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "GlobalClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ if (clusterId == null || clusterId.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "DbClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ GlobalCluster global = service.removeFromGlobalCluster(id, clusterId, region);
+ return Response.ok(AwsQueryResponse.envelope("RemoveFromGlobalCluster", AwsNamespaces.RDS,
+ globalClusterXml(global, "GlobalCluster"))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleFailoverGlobalCluster(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("GlobalClusterIdentifier");
+ String target = params.getFirst("TargetDbClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "GlobalClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ if (target == null || target.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "TargetDbClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ GlobalCluster global = service.failoverGlobalCluster(id, target,
+ parseOptionalBoolean(params, "AllowDataLoss"),
+ parseOptionalBoolean(params, "Switchover"), region);
+ return Response.ok(AwsQueryResponse.envelope("FailoverGlobalCluster", AwsNamespaces.RDS,
+ globalClusterXml(global, "GlobalCluster"))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleSwitchoverGlobalCluster(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("GlobalClusterIdentifier");
+ String target = params.getFirst("TargetDbClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "GlobalClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ if (target == null || target.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "TargetDbClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ GlobalCluster global = service.switchoverGlobalCluster(id, target, region);
+ return Response.ok(AwsQueryResponse.envelope("SwitchoverGlobalCluster", AwsNamespaces.RDS,
+ globalClusterXml(global, "GlobalCluster"))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleFailoverDbCluster(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("DBClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ DbCluster cluster = service.failoverDbCluster(id, params.getFirst("TargetDBInstanceIdentifier"), region);
+ return Response.ok(AwsQueryResponse.envelope("FailoverDBCluster", AwsNamespaces.RDS,
+ dbClusterXml(cluster))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ /**
+ * The GlobalCluster shape. The list element of DescribeGlobalClusters is named
+ * GlobalClusterMember by the service model, the same name as the entries of GlobalClusterMembers.
+ */
+ private static String globalClusterXml(GlobalCluster g, String elementName) {
+ XmlBuilder xml = new XmlBuilder().start(elementName)
+ .elem("GlobalClusterIdentifier", g.getGlobalClusterIdentifier())
+ .elem("GlobalClusterResourceId", g.getGlobalClusterResourceId())
+ .elem("GlobalClusterArn", g.getGlobalClusterArn())
+ .elem("Status", g.getStatus())
+ .elem("Engine", g.getEngine())
+ .elem("EngineVersion", g.getEngineVersion());
+ if (g.getDatabaseName() != null && !g.getDatabaseName().isBlank()) {
+ xml.elem("DatabaseName", g.getDatabaseName());
+ }
+ xml.elem("StorageEncrypted", g.isStorageEncrypted())
+ .elem("DeletionProtection", g.isDeletionProtection());
+ List<String> readerArns = g.getMembers().stream()
+ .filter(member -> !member.isWriter())
+ .map(GlobalClusterMember::getDbClusterArn)
+ .toList();
+ xml.start("GlobalClusterMembers");
+ for (GlobalClusterMember member : g.getMembers()) {
+ xml.start("GlobalClusterMember")
+ .elem("DBClusterArn", member.getDbClusterArn());
+ xml.start("Readers");
+ if (member.isWriter()) {
+ readerArns.forEach(arn -> xml.elem("member", arn));
+ }
+ xml.end("Readers");
+ xml.elem("IsWriter", member.isWriter())
+ .elem("SynchronizationStatus", "connected")
+ .end("GlobalClusterMember");
+ }
+ xml.end("GlobalClusterMembers");
+ xml.start("TagList");
+ writeTags(xml, g.getTags());
+ xml.end("TagList");
+ return xml.end(elementName).build();
}
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params) {
@@ -1952,12 +2166,16 @@ public class RdsQueryHandler {
}
xml.end("ServerlessV2ScalingConfiguration");
}
+ if (c.getGlobalClusterIdentifier() != null && !c.getGlobalClusterIdentifier().isBlank()) {
+ xml.elem("GlobalClusterIdentifier", c.getGlobalClusterIdentifier());
+ }
xml.start("DBClusterMembers");
if (c.getDbClusterMembers() != null) {
+ String writer = c.resolveWriterIdentifier();
for (String memberId : c.getDbClusterMembers()) {
xml.start("member")
.elem("DBInstanceIdentifier", memberId)
- .elem("IsClusterWriter", true)
+ .elem("IsClusterWriter", memberId.equals(writer))
.end("member");
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
index 2dbcdf716a..2216461093 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
@@ -41,6 +41,8 @@ import io.github.hectorvent.floci.services.rds.model.RdsEvent;
import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
import io.github.hectorvent.floci.services.rds.model.DbSnapshot;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
+import io.github.hectorvent.floci.services.rds.model.GlobalCluster;
+import io.github.hectorvent.floci.services.rds.model.GlobalClusterMember;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
@@ -145,6 +147,7 @@ public class RdsService implements Resettable, ResourceProvider {
private final StorageBackend<String, DbProxy> proxies;
private final StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups;
private final StorageBackend<String, DbSnapshot> snapshots;
+ private final StorageBackend<String, GlobalCluster> globalClusters;
private final StorageBackend<String, String> snapshotData;
private StorageBackend<String, RdsEvent> events = new InMemoryStorage<>();
private final RdsContainerManager containerManager;
@@ -224,6 +227,8 @@ public class RdsService implements Resettable, ResourceProvider {
new TypeReference<Map<String, DbProxy>>() {});
this.proxyTargetGroups = storageFactory.create("rds", "rds-proxy-target-groups.json",
new TypeReference<Map<String, DbProxyTargetGroup>>() {});
+ this.globalClusters = storageFactory.create("rds", "rds-global-clusters.json",
+ new TypeReference<Map<String, GlobalCluster>>() {});
this.snapshots = storageFactory.create("rds", "rds-snapshots.json",
new TypeReference<Map<String, DbSnapshot>>() {});
this.snapshotData = storageFactory.create("rds", "rds-snapshot-data.json",
@@ -361,6 +366,7 @@ public class RdsService implements Resettable, ResourceProvider {
this.proxies = proxies;
this.proxyTargetGroups = proxyTargetGroups;
this.taggingService = taggingService;
+ this.globalClusters = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
this.snapshots = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
this.snapshotData = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
}
@@ -751,6 +757,10 @@ public class RdsService implements Resettable, ResourceProvider {
currentAccountId(), effectiveRegion, dbClusterIdentifier);
if (cluster != null) {
cluster.getDbClusterMembers().add(id);
+ if (cluster.resolveWriterIdentifier() == null
+ || !cluster.getDbClusterMembers().contains(cluster.getClusterWriterIdentifier())) {
+ cluster.setClusterWriterIdentifier(cluster.resolveWriterIdentifier());
+ }
putClusterForScope(currentAccountId(), effectiveRegion,
dbClusterIdentifier, cluster);
}
@@ -2301,6 +2311,8 @@ public class RdsService implements Resettable, ResourceProvider {
currentAccountId(), effectiveRegion, clusterId);
if (cluster != null) {
cluster.getDbClusterMembers().remove(id);
+ // Losing the writer promotes a remaining member, as Aurora fails over on its own.
+ cluster.setClusterWriterIdentifier(cluster.resolveWriterIdentifier());
putClusterForScope(currentAccountId(), effectiveRegion, clusterId, cluster);
}
}
@@ -2785,6 +2797,7 @@ public class RdsService implements Resettable, ResourceProvider {
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster " + id + " is registered with a DB proxy target group.", 400);
}
+ detachFromGlobalClusterBeforeDelete(cluster);
detachManagedMasterUserSecret(cluster, effectiveRegion);
@@ -2811,6 +2824,546 @@ public class RdsService implements Resettable, ResourceProvider {
LOG.infov("DB cluster {0} deleted", id);
}
+ // ── Global clusters (Aurora global databases) ─────────────────────────────
+
+ private static final Set<String> GLOBAL_CLUSTER_ENGINES = Set.of("aurora-mysql", "aurora-postgresql");
+
+ /**
+ * Creates an Aurora global database, empty or with an existing cluster (named by ARN or, in
+ * the request Region, by identifier) as its primary. With a source, engine, version, database
+ * name and encryption come from that cluster and may not be given, as the API reference
+ * states.
+ */
+ public synchronized GlobalCluster createGlobalCluster(String id, String sourceDbClusterIdentifier,
+ String engine, String engineVersion,
+ String databaseName, Boolean storageEncrypted,
+ Boolean deletionProtection,
+ Map<String, String> tags, String region) {
+ if (id == null || id.isBlank()) {
+ throw new AwsException("InvalidParameterValue", "GlobalClusterIdentifier is required.", 400);
+ }
+ String accountId = currentAccountId();
+ if (findGlobalCluster(accountId, id) != null) {
+ throw new AwsException("GlobalClusterAlreadyExistsFault",
+ "Global cluster " + id + " already exists.", 400);
+ }
+ GlobalCluster global = new GlobalCluster();
+ global.setGlobalClusterIdentifier(id.toLowerCase(Locale.ROOT));
+ global.setGlobalClusterResourceId("cluster-" + java.util.UUID.randomUUID().toString()
+ .replace("-", "").substring(0, 24).toUpperCase());
+ global.setGlobalClusterArn(globalClusterArn(accountId, global.getGlobalClusterIdentifier()));
+ global.setStatus("available");
+ global.setDeletionProtection(Boolean.TRUE.equals(deletionProtection));
+ global.setTags(tags);
+ global.setCreatedAt(Instant.now());
+
+ if (sourceDbClusterIdentifier != null && !sourceDbClusterIdentifier.isBlank()) {
+ if (hasText(engine) || hasText(engineVersion) || hasText(databaseName)
+ || storageEncrypted != null) {
+ throw new AwsException("InvalidParameterCombination",
+ "Engine, EngineVersion, DatabaseName and StorageEncrypted can't be specified "
+ + "when SourceDBClusterIdentifier is specified; the global cluster uses the "
+ + "values of the source DB cluster.", 400);
+ }
+ DbCluster source = resolveClusterReference(sourceDbClusterIdentifier, region);
+ requireGlobalClusterEngine(source.getEngineIdentifier(), source.getDbClusterIdentifier());
+ if (source.getGlobalClusterIdentifier() != null) {
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + source.getDbClusterIdentifier() + " is already a member of "
+ + "global cluster " + source.getGlobalClusterIdentifier() + ".", 400);
+ }
+ global.setEngine(source.getEngineIdentifier());
+ global.setEngineVersion(source.getEngineVersion());
+ global.setDatabaseName(source.getDatabaseName());
+ global.setStorageEncrypted(source.isStorageEncrypted());
+ global.getMembers().add(new GlobalClusterMember(source.getDbClusterArn(), true));
+ source.setGlobalClusterIdentifier(global.getGlobalClusterIdentifier());
+ putClusterForScope(accountId, regionFromArn(source.getDbClusterArn()),
+ source.getDbClusterIdentifier(), source);
+ } else {
+ if (!hasText(engine)) {
+ throw new AwsException("InvalidParameterCombination",
+ "Engine must be specified when SourceDBClusterIdentifier is not.", 400);
+ }
+ requireGlobalClusterEngine(engine, null);
+ global.setEngine(engine.toLowerCase(Locale.ROOT));
+ global.setEngineVersion(hasText(engineVersion)
+ ? engineVersion : defaultGlobalEngineVersion(global.getEngine()));
+ global.setDatabaseName(hasText(databaseName) ? databaseName : null);
+ global.setStorageEncrypted(Boolean.TRUE.equals(storageEncrypted));
+ }
+ putGlobalCluster(accountId, global);
+ LOG.infov("Global cluster {0} created, engine={1}", global.getGlobalClusterIdentifier(), global.getEngine());
+ return global;
+ }
+
+ /**
+ * CreateDBCluster with GlobalClusterIdentifier: the first cluster becomes the primary, every
+ * later one a secondary in a Region that has neither the primary nor another secondary. A
+ * secondary takes credentials, database name, version and encryption from the primary and
+ * may not be given its own, and its database is initialised from a dump of the primary the
+ * way a read replica is.
+ */
+ public DbCluster createDbClusterInGlobalCluster(String globalClusterIdentifier, String id,
+ String engineParam, String engineVersion,
+ String masterUsername, String masterPassword,
+ String databaseName, boolean iamEnabled,
+ String paramGroupName, String dbSubnetGroupName,
+ String availabilityZone, boolean multiAz, String region,
+ Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
+ Integer serverlessV2SecondsUntilAutoPause,
+ boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
+ String engineMode, boolean storageEncrypted) {
+ String effectiveRegion = effectiveRegion(region);
+ String accountId = currentAccountId();
+ GlobalCluster global = requireGlobalCluster(accountId, globalClusterIdentifier);
+ String engineName = hasText(engineParam) ? engineParam.toLowerCase(Locale.ROOT) : global.getEngine();
+ if (!engineName.equals(global.getEngine())) {
+ throw new AwsException("InvalidParameterCombination",
+ "Engine " + engineName + " does not match engine " + global.getEngine()
+ + " of global cluster " + global.getGlobalClusterIdentifier() + ".", 400);
+ }
+ DbCluster primary = global.findPrimary()
+ .map(member -> findClusterByArn(accountId, member.getDbClusterArn()))
+ .orElse(null);
+ DbCluster cluster;
+ if (primary == null) {
+ cluster = createDbCluster(id, engineName, hasText(engineVersion) ? engineVersion : global.getEngineVersion(),
+ masterUsername, masterPassword,
+ hasText(databaseName) ? databaseName : global.getDatabaseName(), iamEnabled,
+ paramGroupName, dbSubnetGroupName, availabilityZone, multiAz, effectiveRegion,
+ serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
+ manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode,
+ storageEncrypted || global.isStorageEncrypted());
+ } else {
+ if (hasText(masterUsername) || hasText(masterPassword) || manageMasterUserPassword) {
+ throw new AwsException("InvalidParameterCombination",
+ "Cannot specify user name for cross region replication cluster", 400);
+ }
+ if (hasText(databaseName)) {
+ throw new AwsException("InvalidParameterCombination",
+ "Cannot specify database name for cross region replication cluster", 400);
+ }
+ String primaryRegion = regionFromArn(primary.getDbClusterArn());
+ if (primaryRegion.equals(effectiveRegion)) {
+ throw new AwsException("InvalidParameterCombination",
+ "A secondary cluster must be in a different Region than the primary cluster "
+ + primary.getDbClusterIdentifier() + " (" + primaryRegion + ").", 400);
+ }
+ for (GlobalClusterMember member : global.getMembers()) {
+ if (regionFromArn(member.getDbClusterArn()).equals(effectiveRegion)) {
+ throw new AwsException("InvalidParameterCombination",
+ "Global cluster " + global.getGlobalClusterIdentifier()
+ + " already has a cluster in " + effectiveRegion + ".", 400);
+ }
+ }
+ if (primary.getEngine() != DatabaseEngine.POSTGRES) {
+ // The point-in-time copy of the primary is pg_dumpall based, the line
+ // CreateDBSnapshot and CreateDBInstanceReadReplica draw as well.
+ throw new AwsException("InvalidDBClusterStateFault",
+ "Adding a secondary cluster is not supported for engine "
+ + primary.getEngineIdentifier() + ".", 400);
+ }
+ cluster = createDbCluster(id, engineName, primary.getEngineVersion(),
+ primary.getMasterUsername(), primary.getMasterPassword(),
+ primary.getDatabaseName(), iamEnabled, paramGroupName, dbSubnetGroupName,
+ availabilityZone, multiAz, effectiveRegion, serverlessV2MinCapacity,
+ serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause, false, null,
+ engineMode, primary.isStorageEncrypted());
+ }
+ try {
+ attachToGlobalCluster(accountId, global.getGlobalClusterIdentifier(), cluster, primary == null);
+ if (primary != null && !config.services().rds().mock()
+ && primary.getContainerId() != null && cluster.getContainerId() != null) {
+ String sqlDump = containerManager.createPostgresSnapshot(
+ primary.getContainerId(), primary.getMasterUsername());
+ containerManager.restorePostgresSnapshot(
+ cluster.getContainerId(), cluster.getMasterUsername(), sqlDump);
+ }
+ } catch (Exception e) {
+ try {
+ deleteDbCluster(id, effectiveRegion);
+ } catch (RuntimeException cleanupError) {
+ e.addSuppressed(cleanupError);
+ }
+ if (e instanceof AwsException aws) {
+ throw aws;
+ }
+ AwsException failure = new AwsException("InvalidDBClusterStateFault",
+ "Failed to initialise secondary cluster " + id + " from the primary: " + e.getMessage(), 400);
+ failure.initCause(e);
+ throw failure;
+ }
+ return getDbCluster(id, effectiveRegion);
+ }
+
+ public synchronized GlobalCluster describeGlobalCluster(String id) {
+ return requireGlobalCluster(currentAccountId(), id);
+ }
+
+ public synchronized List<GlobalCluster> listGlobalClusters() {
+ String accountId = currentAccountId();
+ List<GlobalCluster> result = new ArrayList<>();
+ if (globalClusters instanceof AccountAwareStorageBackend<GlobalCluster> aware) {
+ result.addAll(aware.scanForAccount(accountId, k -> true));
+ } else {
+ for (GlobalCluster candidate : globalClusters.scan(k -> true)) {
+ if (accountId.equals(accountIdFromArn(candidate.getGlobalClusterArn()))) {
+ result.add(candidate);
+ }
+ }
+ }
+ result.sort(Comparator.comparing(GlobalCluster::getGlobalClusterIdentifier));
+ return result;
+ }
+
+ /**
+ * Renames the global cluster, toggles deletion protection or upgrades the engine version,
+ * which member clusters follow. A rename is reflected on every member.
+ */
+ public synchronized GlobalCluster modifyGlobalCluster(String id, String newGlobalClusterIdentifier,
+ Boolean deletionProtection, String engineVersion,
+ Boolean allowMajorVersionUpgrade) {
+ String accountId = currentAccountId();
+ GlobalCluster global = requireGlobalCluster(accountId, id);
+ if (hasText(engineVersion) && !engineVersion.equals(global.getEngineVersion())
+ && !sameMajorVersion(global.getEngineVersion(), engineVersion)
+ && !Boolean.TRUE.equals(allowMajorVersionUpgrade)) {
+ throw new AwsException("InvalidParameterCombination",
+ "The AllowMajorVersionUpgrade flag must be present when upgrading to a new major version.", 400);
+ }
+ if (hasText(newGlobalClusterIdentifier)
+ && !newGlobalClusterIdentifier.equalsIgnoreCase(global.getGlobalClusterIdentifier())) {
+ String newId = newGlobalClusterIdentifier.toLowerCase(Locale.ROOT);
+ if (findGlobalCluster(accountId, newId) != null) {
+ throw new AwsException("GlobalClusterAlreadyExistsFault",
+ "Global cluster " + newId + " already exists.", 400);
+ }
+ deleteGlobalClusterRecord(accountId, global.getGlobalClusterIdentifier());
+ global.setGlobalClusterIdentifier(newId);
+ global.setGlobalClusterArn(globalClusterArn(accountId, newId));
+ for (GlobalClusterMember member : global.getMembers()) {
+ DbCluster cluster = findClusterByArn(accountId, member.getDbClusterArn());
+ if (cluster != null) {
+ cluster.setGlobalClusterIdentifier(newId);
+ putClusterForScope(accountId, regionFromArn(cluster.getDbClusterArn()),
+ cluster.getDbClusterIdentifier(), cluster);
+ }
+ }
+ }
+ if (deletionProtection != null) {
+ global.setDeletionProtection(deletionProtection);
+ }
+ if (hasText(engineVersion)) {
+ global.setEngineVersion(engineVersion);
+ for (GlobalClusterMember member : global.getMembers()) {
+ DbCluster cluster = findClusterByArn(accountId, member.getDbClusterArn());
+ if (cluster != null) {
+ cluster.setEngineVersion(engineVersion);
+ putClusterForScope(accountId, regionFromArn(cluster.getDbClusterArn()),
+ cluster.getDbClusterIdentifier(), cluster);
+ }
+ }
+ }
+ putGlobalCluster(accountId, global);
+ return global;
+ }
+
+ /** Deletes an empty global cluster; one with members or deletion protection is refused. */
+ public synchronized GlobalCluster deleteGlobalCluster(String id) {
+ String accountId = currentAccountId();
+ GlobalCluster global = requireGlobalCluster(accountId, id);
+ if (global.isDeletionProtection()) {
+ throw new AwsException("InvalidGlobalClusterStateFault",
+ "Cannot delete protected Global Cluster, please disable deletion protection and try again.", 400);
+ }
+ if (!global.getMembers().isEmpty()) {
+ throw new AwsException("InvalidGlobalClusterStateFault",
+ "Global cluster " + global.getGlobalClusterIdentifier() + " still has "
+ + global.getMembers().size() + " DB cluster(s) attached. Remove them first.", 400);
+ }
+ deleteGlobalClusterRecord(accountId, global.getGlobalClusterIdentifier());
+ global.setStatus("deleting");
+ LOG.infov("Global cluster {0} deleted", global.getGlobalClusterIdentifier());
+ return global;
+ }
+
+ /**
+ * Detaches a member: it becomes a standalone cluster with read-write capability. The primary
+ * can only be removed once every secondary has been.
+ */
+ public synchronized GlobalCluster removeFromGlobalCluster(String id, String dbClusterIdentifier, String region) {
+ String accountId = currentAccountId();
+ GlobalCluster global = requireGlobalCluster(accountId, id);
+ DbCluster cluster = resolveClusterReference(dbClusterIdentifier, region);
+ GlobalClusterMember member = global.findMember(cluster.getDbClusterArn())
+ .orElseThrow(() -> new AwsException("DBClusterNotFoundFault",
+ "DB cluster " + cluster.getDbClusterIdentifier() + " is not a member of global cluster "
+ + global.getGlobalClusterIdentifier() + ".", 404));
+ if (member.isWriter() && global.getMembers().size() > 1) {
+ throw new AwsException("InvalidGlobalClusterStateFault",
+ "DB cluster " + cluster.getDbClusterIdentifier() + " is the primary cluster of global "
+ + "cluster " + global.getGlobalClusterIdentifier()
+ + "; remove all secondary clusters before removing the primary.", 400);
+ }
+ global.getMembers().remove(member);
+ putGlobalCluster(accountId, global);
+ cluster.setGlobalClusterIdentifier(null);
+ putClusterForScope(accountId, regionFromArn(cluster.getDbClusterArn()),
+ cluster.getDbClusterIdentifier(), cluster);
+ return global;
+ }
+
+ /**
+ * Promotes the named secondary to primary and demotes the current primary to a secondary, the
+ * topology AWS keeps for a switchover and restores after a managed failover once the old
+ * primary Region is healthy again, which here it always is.
+ */
+ public synchronized GlobalCluster failoverGlobalCluster(String id, String targetDbClusterIdentifier,
+ Boolean allowDataLoss, Boolean switchover,
+ String region) {
+ if (Boolean.TRUE.equals(allowDataLoss) && switchover != null) {
+ throw new AwsException("InvalidParameterCombination",
+ "AllowDataLoss and Switchover can't be specified together.", 400);
+ }
+ return promoteGlobalClusterMember(id, targetDbClusterIdentifier, region);
+ }
+
+ public synchronized GlobalCluster switchoverGlobalCluster(String id, String targetDbClusterIdentifier,
+ String region) {
+ return promoteGlobalClusterMember(id, targetDbClusterIdentifier, region);
+ }
+
+ private GlobalCluster promoteGlobalClusterMember(String id, String targetDbClusterIdentifier, String region) {
+ String accountId = currentAccountId();
+ GlobalCluster global = requireGlobalCluster(accountId, id);
+ if (targetDbClusterIdentifier == null || targetDbClusterIdentifier.isBlank()) {
+ throw new AwsException("InvalidParameterValue", "TargetDbClusterIdentifier is required.", 400);
+ }
+ DbCluster target = resolveClusterReference(targetDbClusterIdentifier, region);
+ GlobalClusterMember targetMember = global.findMember(target.getDbClusterArn())
+ .orElseThrow(() -> new AwsException("DBClusterNotFoundFault",
+ "DB cluster " + target.getDbClusterIdentifier() + " is not a member of global cluster "
+ + global.getGlobalClusterIdentifier() + ".", 404));
+ if (global.getMembers().size() < 2) {
+ throw new AwsException("InvalidGlobalClusterStateFault",
+ "Global cluster " + global.getGlobalClusterIdentifier()
+ + " has no secondary cluster to promote.", 400);
+ }
+ if (targetMember.isWriter()) {
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + target.getDbClusterIdentifier() + " is already the primary cluster of "
+ + "global cluster " + global.getGlobalClusterIdentifier() + ".", 400);
+ }
+ for (GlobalClusterMember member : global.getMembers()) {
+ member.setWriter(member == targetMember);
+ }
+ putGlobalCluster(accountId, global);
+ LOG.infov("Global cluster {0}: {1} is now the primary cluster",
+ global.getGlobalClusterIdentifier(), target.getDbClusterIdentifier());
+ return global;
+ }
+
+ /**
+ * Forces a failover inside a DB cluster: the named member, or the first reader when none is
+ * named, becomes the writer. A cluster without a reader has nothing to fail over to.
+ */
+ public synchronized DbCluster failoverDbCluster(String id, String targetDbInstanceIdentifier, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbCluster cluster = getDbCluster(id, effectiveRegion);
+ String writer = cluster.resolveWriterIdentifier();
+ List<String> readers = cluster.getDbClusterMembers().stream()
+ .filter(member -> !member.equalsIgnoreCase(writer))
+ .toList();
+ if (readers.isEmpty()) {
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + id + " has no reader instance to fail over to.", 400);
+ }
+ String target = readers.get(0);
+ if (hasText(targetDbInstanceIdentifier)) {
+ target = cluster.getDbClusterMembers().stream()
+ .filter(member -> member.equalsIgnoreCase(targetDbInstanceIdentifier))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("InvalidDBInstanceState",
+ "DB instance " + targetDbInstanceIdentifier + " is not a member of DB cluster "
+ + id + ".", 400));
+ if (target.equalsIgnoreCase(writer)) {
+ throw new AwsException("InvalidDBInstanceState",
+ "DB instance " + target + " is already the writer of DB cluster " + id + ".", 400);
+ }
+ }
+ cluster.setClusterWriterIdentifier(target);
+ putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
+ LOG.infov("DB cluster {0}: {1} is now the writer", id, target);
+ return cluster;
+ }
+
+ /**
+ * The membership checks run again here, under the lock, because the cluster's container was
+ * started outside it: two concurrent joins that both passed the early checks would otherwise
+ * both attach, leaving two primaries or two secondaries in one Region. A join that lost the
+ * race fails, and the caller deletes the cluster it created.
+ */
+ private void attachToGlobalCluster(String accountId, String globalClusterIdentifier,
+ DbCluster cluster, boolean asPrimary) {
+ synchronized (this) {
+ GlobalCluster global = requireGlobalCluster(accountId, globalClusterIdentifier);
+ String region = regionFromArn(cluster.getDbClusterArn());
+ if (asPrimary && global.findPrimary().isPresent()) {
+ throw new AwsException("InvalidParameterCombination",
+ "Global cluster " + global.getGlobalClusterIdentifier()
+ + " already has a primary cluster.", 400);
+ }
+ if (!asPrimary && global.findPrimary().isEmpty()) {
+ throw new AwsException("InvalidGlobalClusterStateFault",
+ "Global cluster " + global.getGlobalClusterIdentifier()
+ + " has no primary cluster to replicate from.", 400);
+ }
+ for (GlobalClusterMember member : global.getMembers()) {
+ if (regionFromArn(member.getDbClusterArn()).equals(region)) {
+ throw new AwsException("InvalidParameterCombination",
+ "Global cluster " + global.getGlobalClusterIdentifier()
+ + " already has a cluster in " + region + ".", 400);
+ }
+ }
+ global.getMembers().add(new GlobalClusterMember(cluster.getDbClusterArn(), asPrimary));
+ putGlobalCluster(accountId, global);
+ cluster.setGlobalClusterIdentifier(global.getGlobalClusterIdentifier());
+ putClusterForScope(accountId, regionFromArn(cluster.getDbClusterArn()),
+ cluster.getDbClusterIdentifier(), cluster);
+ }
+ }
+
+ /**
+ * A member cluster leaves its global cluster when deleted, except the primary while
+ * secondaries remain, which AWS refuses.
+ */
+ private void detachFromGlobalClusterBeforeDelete(DbCluster cluster) {
+ if (cluster.getGlobalClusterIdentifier() == null) {
+ return;
+ }
+ String accountId = currentAccountId();
+ GlobalCluster global = findGlobalCluster(accountId, cluster.getGlobalClusterIdentifier());
+ if (global == null) {
+ cluster.setGlobalClusterIdentifier(null);
+ return;
+ }
+ GlobalClusterMember member = global.findMember(cluster.getDbClusterArn()).orElse(null);
+ if (member == null) {
+ cluster.setGlobalClusterIdentifier(null);
+ return;
+ }
+ if (member.isWriter() && global.getMembers().size() > 1) {
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + cluster.getDbClusterIdentifier() + " is the primary cluster of global "
+ + "cluster " + global.getGlobalClusterIdentifier()
+ + "; remove all secondary clusters before deleting it.", 400);
+ }
+ global.getMembers().remove(member);
+ putGlobalCluster(accountId, global);
+ cluster.setGlobalClusterIdentifier(null);
+ }
+
+ private GlobalCluster requireGlobalCluster(String accountId, String id) {
+ if (id == null || id.isBlank()) {
+ throw new AwsException("InvalidParameterValue", "GlobalClusterIdentifier is required.", 400);
+ }
+ GlobalCluster global = findGlobalCluster(accountId, id);
+ if (global == null) {
+ throw new AwsException("GlobalClusterNotFoundFault",
+ "Global cluster '" + id + "' not found", 404);
+ }
+ return global;
+ }
+
+ private GlobalCluster findGlobalCluster(String accountId, String id) {
+ String key = globalClusterKey(id);
+ if (globalClusters instanceof AccountAwareStorageBackend<GlobalCluster> aware) {
+ return aware.getForAccount(accountId, key).orElse(null);
+ }
+ return globalClusters.get(key)
+ .filter(global -> accountId.equals(accountIdFromArn(global.getGlobalClusterArn())))
+ .orElse(null);
+ }
+
+ private void putGlobalCluster(String accountId, GlobalCluster global) {
+ String key = globalClusterKey(global.getGlobalClusterIdentifier());
+ if (globalClusters instanceof AccountAwareStorageBackend<GlobalCluster> aware) {
+ aware.putForAccount(accountId, key, global);
+ } else {
+ globalClusters.put(key, global);
+ }
+ }
+
+ private void deleteGlobalClusterRecord(String accountId, String id) {
+ String key = globalClusterKey(id);
+ if (globalClusters instanceof AccountAwareStorageBackend<GlobalCluster> aware) {
+ aware.deleteForAccount(accountId, key);
+ } else {
+ globalClusters.delete(key);
+ }
+ }
+
+ private static String globalClusterKey(String id) {
+ return "global:" + id.toLowerCase(Locale.ROOT);
+ }
+
+ private static String globalClusterArn(String accountId, String id) {
+ return "arn:aws:rds::" + accountId + ":global-cluster:" + id;
+ }
+
+ private static void requireGlobalClusterEngine(String engine, String clusterId) {
+ String name = engine == null ? "" : engine.toLowerCase(Locale.ROOT);
+ if (!GLOBAL_CLUSTER_ENGINES.contains(name)) {
+ throw new AwsException("InvalidParameterValue",
+ (clusterId != null ? "DB cluster " + clusterId + " runs engine " + name + "; only "
+ : "Engine " + name + " is not valid for a global cluster; only ")
+ + "aurora-mysql and aurora-postgresql are supported.", 400);
+ }
+ }
+
+ private static String defaultGlobalEngineVersion(String engine) {
+ return "aurora-mysql".equals(engine) ? "8.0.mysql_aurora.3.05.2" : "16.3";
+ }
+
+ private static boolean sameMajorVersion(String current, String requested) {
+ if (current == null || requested == null) {
+ return true;
+ }
+ return current.split("\\.")[0].equals(requested.split("\\.")[0]);
+ }
+
+ private static boolean hasText(String value) {
+ return value != null && !value.isBlank();
+ }
+
+ /** A DB cluster named by ARN (any Region of the account) or by identifier in the request Region. */
+ private DbCluster resolveClusterReference(String reference, String region) {
+ String accountId = currentAccountId();
+ if (reference == null || reference.isBlank()) {
+ throw new AwsException("InvalidParameterValue", "DBClusterIdentifier is required.", 400);
+ }
+ if (reference.startsWith("arn:")) {
+ DbCluster cluster = findClusterByArn(accountId, reference);
+ if (cluster == null) {
+ throw new AwsException("DBClusterNotFoundFault", "DB cluster " + reference + " not found.", 404);
+ }
+ return cluster;
+ }
+ return getDbCluster(reference, effectiveRegion(region));
+ }
+
+ private DbCluster findClusterByArn(String accountId, String arn) {
+ for (DbCluster candidate : clusters.scan(k -> true)) {
+ if (arn.equalsIgnoreCase(candidate.getDbClusterArn())
+ && accountId.equals(accountIdFromArn(candidate.getDbClusterArn()))) {
+ return findClusterForScope(accountId, regionFromArn(candidate.getDbClusterArn()),
+ candidate.getDbClusterIdentifier());
+ }
+ }
+ return null;
+ }
+
// ── DB Proxies (AWS::RDS::DBProxy) ──────────────────────────────────────────
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java
index 319d5643fc..0dac695e07 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java
@@ -23,6 +23,11 @@ public class DbCluster {
private DbEndpoint readerEndpoint;
private boolean iamDatabaseAuthenticationEnabled;
private List<String> dbClusterMembers = new ArrayList<>();
+ // The member that holds the writer role. Null on a cluster persisted before the role was
+ // modelled, in which case the first member is the writer, as it always was reported.
+ private String clusterWriterIdentifier;
+ // Set while the cluster is the primary or a secondary of a global cluster.
+ private String globalClusterIdentifier;
private String parameterGroupName;
private String dbSubnetGroupName;
private String vpcId;
@@ -115,6 +120,20 @@ public class DbCluster {
public List<String> getDbClusterMembers() { return dbClusterMembers; }
public void setDbClusterMembers(List<String> dbClusterMembers) { this.dbClusterMembers = dbClusterMembers; }
+ public String getClusterWriterIdentifier() { return clusterWriterIdentifier; }
+ public void setClusterWriterIdentifier(String clusterWriterIdentifier) { this.clusterWriterIdentifier = clusterWriterIdentifier; }
+
+ /** The member DescribeDBClusters reports as the writer; null only when there are no members. */
+ public String resolveWriterIdentifier() {
+ if (clusterWriterIdentifier != null && dbClusterMembers.contains(clusterWriterIdentifier)) {
+ return clusterWriterIdentifier;
+ }
+ return dbClusterMembers.isEmpty() ? null : dbClusterMembers.get(0);
+ }
+
+ public String getGlobalClusterIdentifier() { return globalClusterIdentifier; }
+ public void setGlobalClusterIdentifier(String globalClusterIdentifier) { this.globalClusterIdentifier = globalClusterIdentifier; }
+
public String getParameterGroupName() { return parameterGroupName; }
public void setParameterGroupName(String parameterGroupName) { this.parameterGroupName = parameterGroupName; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/GlobalCluster.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/GlobalCluster.java
new file mode 100644
index 0000000000..787e909aa8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/GlobalCluster.java
@@ -0,0 +1,85 @@
+package io.github.hectorvent.floci.services.rds.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * An Aurora global database: an account-wide record (its ARN carries no Region) holding one
+ * primary cluster and any number of secondaries, each in its own Region.
+ */
+@RegisterForReflection
+public class GlobalCluster {
+
+ private String globalClusterIdentifier;
+ private String globalClusterResourceId;
+ private String globalClusterArn;
+ private String status;
+ private String engine;
+ private String engineVersion;
+ private String databaseName;
+ private boolean storageEncrypted;
+ private boolean deletionProtection;
+ private List<GlobalClusterMember> members = new ArrayList<>();
+ private Map<String, String> tags = new LinkedHashMap<>();
+ private Instant createdAt;
+
+ public GlobalCluster() {}
+
+ public String getGlobalClusterIdentifier() { return globalClusterIdentifier; }
+ public void setGlobalClusterIdentifier(String globalClusterIdentifier) { this.globalClusterIdentifier = globalClusterIdentifier; }
+
+ public String getGlobalClusterResourceId() { return globalClusterResourceId; }
+ public void setGlobalClusterResourceId(String globalClusterResourceId) { this.globalClusterResourceId = globalClusterResourceId; }
+
+ public String getGlobalClusterArn() { return globalClusterArn; }
+ public void setGlobalClusterArn(String globalClusterArn) { this.globalClusterArn = globalClusterArn; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public String getEngine() { return engine; }
+ public void setEngine(String engine) { this.engine = engine; }
+
+ public String getEngineVersion() { return engineVersion; }
+ public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; }
+
+ public String getDatabaseName() { return databaseName; }
+ public void setDatabaseName(String databaseName) { this.databaseName = databaseName; }
+
+ public boolean isStorageEncrypted() { return storageEncrypted; }
+ public void setStorageEncrypted(boolean storageEncrypted) { this.storageEncrypted = storageEncrypted; }
+
+ public boolean isDeletionProtection() { return deletionProtection; }
+ public void setDeletionProtection(boolean deletionProtection) { this.deletionProtection = deletionProtection; }
+
+ public List<GlobalClusterMember> getMembers() { return members; }
+ public void setMembers(List<GlobalClusterMember> members) {
+ this.members = members != null ? new ArrayList<>(members) : new ArrayList<>();
+ }
+
+ public Map<String, String> getTags() { return tags; }
+ public void setTags(Map<String, String> tags) {
+ this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>();
+ }
+
+ public Instant getCreatedAt() { return createdAt; }
+ public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
+
+ // Helpers, not bean properties: the persisted form must carry only settable properties.
+
+ public Optional<GlobalClusterMember> findPrimary() {
+ return members.stream().filter(GlobalClusterMember::isWriter).findFirst();
+ }
+
+ public Optional<GlobalClusterMember> findMember(String dbClusterArn) {
+ return members.stream()
+ .filter(member -> member.getDbClusterArn().equalsIgnoreCase(dbClusterArn))
+ .findFirst();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/GlobalClusterMember.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/GlobalClusterMember.java
new file mode 100644
index 0000000000..d484eccad2
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/GlobalClusterMember.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.services.rds.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/** One DB cluster of an Aurora global database: the primary (writer) or a secondary. */
+@RegisterForReflection
+public class GlobalClusterMember {
+
+ private String dbClusterArn;
+ private boolean writer;
+
+ public GlobalClusterMember() {}
+
+ public GlobalClusterMember(String dbClusterArn, boolean writer) {
+ this.dbClusterArn = dbClusterArn;
+ this.writer = writer;
+ }
+
+ public String getDbClusterArn() { return dbClusterArn; }
+ public void setDbClusterArn(String dbClusterArn) { this.dbClusterArn = dbClusterArn; }
+
+ public boolean isWriter() { return writer; }
+ public void setWriter(boolean writer) { this.writer = writer; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsGlobalClusterIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsGlobalClusterIntegrationTest.java
new file mode 100644
index 0000000000..7406f0d444
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsGlobalClusterIntegrationTest.java
@@ -0,0 +1,290 @@
+package io.github.hectorvent.floci.services.rds;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static io.restassured.http.ContentType.URLENC;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * The Aurora global database lifecycle over the Query protocol: an empty global cluster, a
+ * primary and a secondary joined through CreateDBCluster, describe, switchover and failover,
+ * removal in the documented order, and FailoverDBCluster inside a cluster.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class RdsGlobalClusterIntegrationTest {
+
+ private static final String GLOBAL = "gdb-test";
+ private static final String PRIMARY = "gdb-test-primary";
+ private static final String SECONDARY = "gdb-test-secondary";
+ private static final String PRIMARY_ARN = "arn:aws:rds:us-east-1:000000000000:cluster:" + PRIMARY;
+ private static final String SECONDARY_ARN = "arn:aws:rds:eu-west-1:000000000000:cluster:" + SECONDARY;
+
+ private static RequestSpecification query(String action, String region) {
+ return given().header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260615/" + region + "/rds/aws4_request, "
+ + "SignedHeaders=content-type;host, Signature=test")
+ .contentType(URLENC)
+ .formParam("Action", action)
+ .formParam("Version", "2014-10-31");
+ }
+
+ private static RequestSpecification query(String action) {
+ return query(action, "us-east-1");
+ }
+
+ @Test
+ @Order(1)
+ void createGlobalClusterThenPrimaryThenSecondary() {
+ query("CreateGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("Engine", "aurora-postgresql")
+ .formParam("EngineVersion", "16.3")
+ .formParam("DatabaseName", "appdb")
+ .formParam("Tags.Tag.1.Key", "team")
+ .formParam("Tags.Tag.1.Value", "data")
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<CreateGlobalClusterResult>"))
+ .body(containsString("<GlobalClusterIdentifier>" + GLOBAL + "</GlobalClusterIdentifier>"))
+ .body(containsString("<GlobalClusterArn>arn:aws:rds::000000000000:global-cluster:" + GLOBAL + "</GlobalClusterArn>"))
+ .body(containsString("<Status>available</Status>"))
+ .body(containsString("<Engine>aurora-postgresql</Engine>"))
+ .body(containsString("<GlobalClusterMembers></GlobalClusterMembers>"))
+ .body(containsString("<Value>data</Value>"));
+
+ query("CreateGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("Engine", "aurora-postgresql")
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>GlobalClusterAlreadyExistsFault</Code>"));
+
+ query("CreateDBCluster")
+ .formParam("DBClusterIdentifier", PRIMARY)
+ .formParam("Engine", "aurora-postgresql")
+ .formParam("EngineVersion", "16.3")
+ .formParam("MasterUsername", "admin")
+ .formParam("MasterUserPassword", "password123")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<GlobalClusterIdentifier>" + GLOBAL + "</GlobalClusterIdentifier>"))
+ .body(containsString("<DatabaseName>appdb</DatabaseName>"));
+
+ query("CreateDBCluster", "eu-west-1")
+ .formParam("DBClusterIdentifier", SECONDARY)
+ .formParam("Engine", "aurora-postgresql")
+ .formParam("EngineVersion", "16.3")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<DBClusterArn>" + SECONDARY_ARN + "</DBClusterArn>"))
+ .body(containsString("<MasterUsername>admin</MasterUsername>"))
+ .body(containsString("<GlobalClusterIdentifier>" + GLOBAL + "</GlobalClusterIdentifier>"));
+
+ query("DescribeGlobalClusters")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<GlobalClusters><GlobalClusterMember>"))
+ .body(containsString("<DBClusterArn>" + PRIMARY_ARN + "</DBClusterArn><Readers><member>"
+ + SECONDARY_ARN + "</member></Readers><IsWriter>true</IsWriter>"))
+ .body(containsString("<DBClusterArn>" + SECONDARY_ARN + "</DBClusterArn><Readers></Readers><IsWriter>false</IsWriter>"))
+ .body(containsString("<SynchronizationStatus>connected</SynchronizationStatus>"));
+
+ // A secondary may not sit in the primary's Region nor bring its own credentials.
+ query("CreateDBCluster")
+ .formParam("DBClusterIdentifier", "gdb-test-third")
+ .formParam("Engine", "aurora-postgresql")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidParameterCombination</Code>"));
+ query("CreateDBCluster", "ap-south-1")
+ .formParam("DBClusterIdentifier", "gdb-test-third")
+ .formParam("Engine", "aurora-postgresql")
+ .formParam("MasterUsername", "admin")
+ .formParam("MasterUserPassword", "password123")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidParameterCombination</Code>"))
+ .body(containsString("Cannot specify user name"));
+ }
+
+ @Test
+ @Order(2)
+ void switchoverAndFailoverMoveThePrimaryRole() {
+ query("SwitchoverGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("TargetDbClusterIdentifier", SECONDARY_ARN)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<SwitchoverGlobalClusterResult>"))
+ .body(containsString("<DBClusterArn>" + SECONDARY_ARN + "</DBClusterArn><Readers><member>"
+ + PRIMARY_ARN + "</member></Readers><IsWriter>true</IsWriter>"));
+
+ query("SwitchoverGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("TargetDbClusterIdentifier", SECONDARY_ARN)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidDBClusterStateFault</Code>"));
+
+ query("FailoverGlobalCluster", "us-east-1")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("TargetDbClusterIdentifier", PRIMARY_ARN)
+ .formParam("AllowDataLoss", "true")
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<FailoverGlobalClusterResult>"))
+ .body(containsString("<DBClusterArn>" + PRIMARY_ARN + "</DBClusterArn><Readers><member>"
+ + SECONDARY_ARN + "</member></Readers><IsWriter>true</IsWriter>"));
+
+ query("FailoverGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("TargetDbClusterIdentifier", SECONDARY_ARN)
+ .formParam("AllowDataLoss", "true")
+ .formParam("Switchover", "true")
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidParameterCombination</Code>"));
+ }
+
+ @Test
+ @Order(3)
+ void modifyRenamesAndProtects() {
+ query("ModifyGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("DeletionProtection", "true")
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<ModifyGlobalClusterResult>"))
+ .body(containsString("<DeletionProtection>true</DeletionProtection>"));
+
+ query("DescribeDBClusters")
+ .formParam("DBClusterIdentifier", PRIMARY)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<GlobalClusterIdentifier>" + GLOBAL + "</GlobalClusterIdentifier>"));
+ }
+
+ @Test
+ @Order(4)
+ void removalFollowsTheDocumentedOrderAndDeletionNeedsAnEmptyUnprotectedGlobalCluster() {
+ query("RemoveFromGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("DbClusterIdentifier", PRIMARY_ARN)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidGlobalClusterStateFault</Code>"));
+
+ query("DeleteGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidGlobalClusterStateFault</Code>"));
+
+ query("RemoveFromGlobalCluster", "eu-west-1")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("DbClusterIdentifier", SECONDARY_ARN)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<RemoveFromGlobalClusterResult>"))
+ .body(not(containsString(SECONDARY_ARN)));
+ query("DescribeDBClusters", "eu-west-1")
+ .formParam("DBClusterIdentifier", SECONDARY)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("<GlobalClusterIdentifier>")));
+
+ query("RemoveFromGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("DbClusterIdentifier", PRIMARY_ARN)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<GlobalClusterMembers></GlobalClusterMembers>"));
+
+ query("DeleteGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidGlobalClusterStateFault</Code>"))
+ .body(containsString("deletion protection"));
+ query("ModifyGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .formParam("DeletionProtection", "false")
+ .when().post("/").then().statusCode(200);
+ query("DeleteGlobalCluster")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<DeleteGlobalClusterResult>"))
+ .body(containsString("<Status>deleting</Status>"));
+ query("DescribeGlobalClusters")
+ .formParam("GlobalClusterIdentifier", GLOBAL)
+ .when().post("/").then().statusCode(404)
+ .body(containsString("<Code>GlobalClusterNotFoundFault</Code>"));
+ }
+
+ @Test
+ @Order(5)
+ void failoverDbClusterPromotesAReader() {
+ query("CreateDBInstance")
+ .formParam("DBInstanceIdentifier", "gdb-test-writer")
+ .formParam("DBClusterIdentifier", PRIMARY)
+ .formParam("Engine", "aurora-postgresql")
+ .formParam("DBInstanceClass", "db.r6g.large")
+ .when().post("/").then().statusCode(200);
+
+ query("FailoverDBCluster")
+ .formParam("DBClusterIdentifier", PRIMARY)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidDBClusterStateFault</Code>"));
+
+ query("CreateDBInstance")
+ .formParam("DBInstanceIdentifier", "gdb-test-reader")
+ .formParam("DBClusterIdentifier", PRIMARY)
+ .formParam("Engine", "aurora-postgresql")
+ .formParam("DBInstanceClass", "db.r6g.large")
+ .when().post("/").then().statusCode(200);
+ query("DescribeDBClusters")
+ .formParam("DBClusterIdentifier", PRIMARY)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<DBInstanceIdentifier>gdb-test-writer</DBInstanceIdentifier><IsClusterWriter>true</IsClusterWriter>"))
+ .body(containsString("<DBInstanceIdentifier>gdb-test-reader</DBInstanceIdentifier><IsClusterWriter>false</IsClusterWriter>"));
+
+ query("FailoverDBCluster")
+ .formParam("DBClusterIdentifier", PRIMARY)
+ .formParam("TargetDBInstanceIdentifier", "gdb-test-reader")
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<FailoverDBClusterResult>"))
+ .body(containsString("<DBInstanceIdentifier>gdb-test-reader</DBInstanceIdentifier><IsClusterWriter>true</IsClusterWriter>"))
+ .body(containsString("<DBInstanceIdentifier>gdb-test-writer</DBInstanceIdentifier><IsClusterWriter>false</IsClusterWriter>"));
+ }
+
+ @Test
+ @Order(6)
+ void cleanUp() {
+ for (String instance : new String[]{"gdb-test-writer", "gdb-test-reader"}) {
+ query("DeleteDBInstance").formParam("DBInstanceIdentifier", instance)
+ .when().post("/").then().statusCode(200);
+ }
+ query("DeleteDBCluster").formParam("DBClusterIdentifier", PRIMARY)
+ .when().post("/").then().statusCode(200);
+ query("DeleteDBCluster", "eu-west-1").formParam("DBClusterIdentifier", SECONDARY)
+ .when().post("/").then().statusCode(200);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java
index b0318362f1..6b0e8de551 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java
@@ -1166,6 +1166,8 @@ class RdsQueryHandlerTest {
// answers it with GlobalClusterNotFoundFault rather than an empty list.
MultivaluedMap<String, String> params = params();
params.putSingle("GlobalClusterIdentifier", "no-such-gc");
+ when(service.describeGlobalCluster("no-such-gc")).thenThrow(
+ new AwsException("GlobalClusterNotFoundFault", "Global cluster 'no-such-gc' not found", 404));
Response response = handler.handle("DescribeGlobalClusters", params);
@@ -1191,6 +1193,8 @@ class RdsQueryHandlerTest {
void describeGlobalClusters_rejectsMaxRecordsOutsideTheAllowedRange() {
// A live account rejects this before it looks the identifier up, so an empty model is no
// reason to accept a value AWS refuses.
+ when(service.describeGlobalCluster("no-such-gc")).thenThrow(
+ new AwsException("GlobalClusterNotFoundFault", "Global cluster 'no-such-gc' not found", 404));
for (String value : new String[]{"5", "101", "abc"}) {
MultivaluedMap<String, String> params = params();
params.putSingle("MaxRecords", value);
@@ -1227,6 +1231,8 @@ class RdsQueryHandlerTest {
assertTrue(((String) response.getEntity()).contains("The request token is invalid."));
params.putSingle("GlobalClusterIdentifier", "no-such-gc");
+ when(service.describeGlobalCluster("no-such-gc")).thenThrow(
+ new AwsException("GlobalClusterNotFoundFault", "Global cluster 'no-such-gc' not found", 404));
Response withBoth = handler.handle("DescribeGlobalClusters", params);
assertEquals(404, withBoth.getStatus());
assertTrue(((String) withBoth.getEntity()).contains("GlobalClusterNotFoundFault"));
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
index 21256ff917..cdd1af7141 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
@@ -29,6 +29,8 @@ import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
+import io.github.hectorvent.floci.services.rds.model.GlobalCluster;
+import io.github.hectorvent.floci.services.rds.model.GlobalClusterMember;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.model.RdsEvent;
@@ -6743,4 +6745,277 @@ class RdsServiceTest {
rdsService.promoteReadReplicaDbCluster("aurora", null));
assertEquals("InvalidDBClusterStateFault", notReplicaCluster.getErrorCode());
}
+
+ // ── Global clusters ───────────────────────────────────────────────────────
+
+ private static final String PRIMARY_ARN = "arn:aws:rds:us-east-1:123456789012:cluster:gdb-primary";
+ private static final String SECONDARY_ARN = "arn:aws:rds:eu-west-1:123456789012:cluster:gdb-secondary";
+
+ private DbCluster createGlobalMember(String globalId, String clusterId, String region,
+ String masterUsername, String masterPassword) {
+ return rdsService.createDbClusterInGlobalCluster(globalId, clusterId, "aurora-postgresql", null,
+ masterUsername, masterPassword, null, false, null, null, null, false, region,
+ null, null, null, false, null, null, false);
+ }
+
+ private static List<String> writers(GlobalCluster global) {
+ return global.getMembers().stream().filter(GlobalClusterMember::isWriter)
+ .map(GlobalClusterMember::getDbClusterArn).toList();
+ }
+
+ @Test
+ void globalClusterGrowsFromEmptyToPrimaryAndSecondary() {
+ when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> new RdsContainerHandle(
+ "cont-" + invocation.getArgument(1), invocation.getArgument(1), "localhost", 5432));
+ GlobalCluster global = rdsService.createGlobalCluster("gdb", null, "aurora-postgresql", null,
+ "appdb", true, null, Map.of("team", "data"), null);
+ assertEquals("gdb", global.getGlobalClusterIdentifier());
+ assertEquals("arn:aws:rds::123456789012:global-cluster:gdb", global.getGlobalClusterArn());
+ assertEquals("available", global.getStatus());
+ assertEquals("aurora-postgresql", global.getEngine());
+ assertEquals("16.3", global.getEngineVersion(), "the engine's default version when none is given");
+ assertTrue(global.isStorageEncrypted());
+ assertTrue(global.getMembers().isEmpty());
+
+ DbCluster primary = createGlobalMember("gdb", "gdb-primary", null, "admin", "password");
+ assertEquals("gdb", primary.getGlobalClusterIdentifier());
+ assertEquals("appdb", primary.getDatabaseName(), "the global cluster's database name");
+ assertTrue(primary.isStorageEncrypted());
+ assertEquals(List.of(PRIMARY_ARN), writers(rdsService.describeGlobalCluster("gdb")));
+
+ when(containerManager.createPostgresSnapshot("cont-gdb-primary", "admin")).thenReturn("DUMP");
+ DbCluster secondary = createGlobalMember("gdb", "gdb-secondary", "eu-west-1", null, null);
+ assertEquals("gdb", secondary.getGlobalClusterIdentifier());
+ assertEquals("admin", secondary.getMasterUsername(), "a secondary takes the primary's credentials");
+ assertEquals("password", secondary.getMasterPassword());
+ assertEquals("appdb", secondary.getDatabaseName());
+ assertEquals(SECONDARY_ARN, secondary.getDbClusterArn());
+ verify(containerManager).restorePostgresSnapshot("cont-gdb-secondary", "admin", "DUMP");
+ global = rdsService.describeGlobalCluster("gdb");
+ assertEquals(2, global.getMembers().size());
+ assertEquals(List.of(PRIMARY_ARN), writers(global));
+ assertEquals(List.of(global), rdsService.listGlobalClusters());
+
+ // What AWS refuses on a secondary: the primary's Region, a Region already used, its own
+ // credentials, a different engine.
+ AwsException sameRegion = assertThrows(AwsException.class, () ->
+ createGlobalMember("gdb", "gdb-third", null, null, null));
+ assertEquals("InvalidParameterCombination", sameRegion.getErrorCode());
+ AwsException usedRegion = assertThrows(AwsException.class, () ->
+ createGlobalMember("gdb", "gdb-third", "eu-west-1", null, null));
+ assertEquals("InvalidParameterCombination", usedRegion.getErrorCode());
+ AwsException credentials = assertThrows(AwsException.class, () ->
+ createGlobalMember("gdb", "gdb-third", "ap-south-1", "admin", "password"));
+ assertEquals("InvalidParameterCombination", credentials.getErrorCode());
+ assertTrue(credentials.getMessage().contains("Cannot specify user name"));
+ AwsException engine = assertThrows(AwsException.class, () ->
+ rdsService.createDbClusterInGlobalCluster("gdb", "gdb-third", "aurora-mysql", null,
+ null, null, null, false, null, null, null, false, "ap-south-1",
+ null, null, null, false, null, null, false));
+ assertEquals("InvalidParameterCombination", engine.getErrorCode());
+ AwsException unknownGlobal = assertThrows(AwsException.class, () ->
+ createGlobalMember("nope", "gdb-third", "ap-south-1", null, null));
+ assertEquals("GlobalClusterNotFoundFault", unknownGlobal.getErrorCode());
+ assertThrows(AwsException.class, () -> rdsService.getDbCluster("gdb-third", "ap-south-1"),
+ "a refused secondary leaves no cluster behind");
+ }
+
+ /**
+ * The membership checks run before the container starts, outside the lock, so two joins can
+ * both pass them. The container start is the interleaving point: while one join's container
+ * is starting, a competing join completes. The late one must be refused when it attaches, and
+ * the cluster it created must be gone.
+ */
+ @Test
+ void concurrentJoinsCannotProduceTwoPrimariesOrTwoSecondariesInOneRegion() {
+ rdsService.createGlobalCluster("gdb", null, "aurora-postgresql", null, null, null, null, Map.of(), null);
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+ when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ String id = invocation.getArgument(1);
+ if ("primary-a".equals(id)) {
+ createGlobalMember("gdb", "primary-b", null, "admin", "password");
+ } else if ("secondary-a".equals(id)) {
+ createGlobalMember("gdb", "secondary-b", "eu-west-1", null, null);
+ }
+ return new RdsContainerHandle("cont-" + id, id, "localhost", 5432);
+ });
+
+ AwsException twoPrimaries = assertThrows(AwsException.class, () ->
+ rdsService.createDbClusterInGlobalCluster("gdb", "primary-a", "aurora-postgresql", null,
+ "admin", "password", null, false, null, null, null, false, "us-west-2",
+ null, null, null, false, null, null, false));
+ assertEquals("InvalidParameterCombination", twoPrimaries.getErrorCode());
+ assertEquals(List.of("arn:aws:rds:us-east-1:123456789012:cluster:primary-b"),
+ writers(rdsService.describeGlobalCluster("gdb")));
+ assertThrows(AwsException.class, () -> rdsService.getDbCluster("primary-a", "us-west-2"),
+ "the losing join's cluster is deleted");
+
+ AwsException twoSecondaries = assertThrows(AwsException.class, () ->
+ createGlobalMember("gdb", "secondary-a", "eu-west-1", null, null));
+ assertEquals("InvalidParameterCombination", twoSecondaries.getErrorCode());
+ assertEquals(2, rdsService.describeGlobalCluster("gdb").getMembers().size());
+ assertEquals("gdb", rdsService.getDbCluster("secondary-b", "eu-west-1").getGlobalClusterIdentifier());
+ assertThrows(AwsException.class, () -> rdsService.getDbCluster("secondary-a", "eu-west-1"));
+ }
+
+ @Test
+ void globalClusterFromAnExistingClusterTakesItsSettings() {
+ rdsService.createDbCluster("existing", "aurora-mysql", "8.0.mysql_aurora.3.05.2",
+ "admin", "password", "shop", false, null);
+ rdsService.createDbCluster("plain", "postgres", "16.3", "admin", "password", "shop", false, null);
+
+ AwsException withEngine = assertThrows(AwsException.class, () -> rdsService.createGlobalCluster(
+ "gdb", "arn:aws:rds:us-east-1:123456789012:cluster:existing", "aurora-mysql", null,
+ null, null, null, Map.of(), null));
+ assertEquals("InvalidParameterCombination", withEngine.getErrorCode());
+ AwsException notAurora = assertThrows(AwsException.class, () -> rdsService.createGlobalCluster(
+ "gdb", "plain", null, null, null, null, null, Map.of(), null));
+ assertEquals("InvalidParameterValue", notAurora.getErrorCode());
+ AwsException noEngine = assertThrows(AwsException.class, () -> rdsService.createGlobalCluster(
+ "gdb", null, null, null, null, null, null, Map.of(), null));
+ assertEquals("InvalidParameterCombination", noEngine.getErrorCode());
+
+ GlobalCluster global = rdsService.createGlobalCluster("gdb",
+ "arn:aws:rds:us-east-1:123456789012:cluster:existing", null, null, null, null, null,
+ Map.of(), null);
+ assertEquals("aurora-mysql", global.getEngine());
+ assertEquals("8.0.mysql_aurora.3.05.2", global.getEngineVersion());
+ assertEquals("shop", global.getDatabaseName());
+ assertEquals(List.of("arn:aws:rds:us-east-1:123456789012:cluster:existing"), writers(global));
+ assertEquals("gdb", rdsService.getDbCluster("existing").getGlobalClusterIdentifier());
+
+ AwsException duplicate = assertThrows(AwsException.class, () -> rdsService.createGlobalCluster(
+ "gdb", null, "aurora-postgresql", null, null, null, null, Map.of(), null));
+ assertEquals("GlobalClusterAlreadyExistsFault", duplicate.getErrorCode());
+ AwsException alreadyMember = assertThrows(AwsException.class, () -> rdsService.createGlobalCluster(
+ "gdb2", "existing", null, null, null, null, null, Map.of(), null));
+ assertEquals("InvalidDBClusterStateFault", alreadyMember.getErrorCode());
+ }
+
+ @Test
+ void switchoverAndFailoverPromoteTheNamedSecondary() {
+ rdsService.createGlobalCluster("gdb", null, "aurora-postgresql", null, null, null, null, Map.of(), null);
+ createGlobalMember("gdb", "gdb-primary", null, "admin", "password");
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+
+ AwsException noSecondary = assertThrows(AwsException.class, () ->
+ rdsService.switchoverGlobalCluster("gdb", PRIMARY_ARN, null));
+ assertEquals("InvalidGlobalClusterStateFault", noSecondary.getErrorCode());
+
+ createGlobalMember("gdb", "gdb-secondary", "eu-west-1", null, null);
+ GlobalCluster switched = rdsService.switchoverGlobalCluster("gdb", SECONDARY_ARN, null);
+ assertEquals(List.of(SECONDARY_ARN), writers(switched));
+ assertEquals(2, switched.getMembers().size(), "the old primary stays as a secondary");
+
+ AwsException alreadyPrimary = assertThrows(AwsException.class, () ->
+ rdsService.switchoverGlobalCluster("gdb", SECONDARY_ARN, null));
+ assertEquals("InvalidDBClusterStateFault", alreadyPrimary.getErrorCode());
+ AwsException notMember = assertThrows(AwsException.class, () ->
+ rdsService.failoverGlobalCluster("gdb", "arn:aws:rds:us-east-1:123456789012:cluster:nope",
+ true, null, null));
+ assertEquals("DBClusterNotFoundFault", notMember.getErrorCode());
+ AwsException bothFlags = assertThrows(AwsException.class, () ->
+ rdsService.failoverGlobalCluster("gdb", PRIMARY_ARN, true, true, null));
+ assertEquals("InvalidParameterCombination", bothFlags.getErrorCode());
+
+ GlobalCluster failedOver = rdsService.failoverGlobalCluster("gdb", "gdb-primary", true, null, null);
+ assertEquals(List.of(PRIMARY_ARN), writers(failedOver), "a plain identifier resolves in the request Region");
+ }
+
+ @Test
+ void removalAndDeletionFollowTheDocumentedOrder() {
+ rdsService.createGlobalCluster("gdb", null, "aurora-postgresql", null, null, null, true, Map.of(), null);
+ createGlobalMember("gdb", "gdb-primary", null, "admin", "password");
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+ createGlobalMember("gdb", "gdb-secondary", "eu-west-1", null, null);
+
+ AwsException primaryFirst = assertThrows(AwsException.class, () ->
+ rdsService.removeFromGlobalCluster("gdb", PRIMARY_ARN, null));
+ assertEquals("InvalidGlobalClusterStateFault", primaryFirst.getErrorCode());
+ AwsException deletePrimary = assertThrows(AwsException.class, () ->
+ rdsService.deleteDbCluster("gdb-primary"));
+ assertEquals("InvalidDBClusterStateFault", deletePrimary.getErrorCode());
+ AwsException withMembers = assertThrows(AwsException.class, () -> rdsService.deleteGlobalCluster("gdb"));
+ assertEquals("InvalidGlobalClusterStateFault", withMembers.getErrorCode());
+
+ GlobalCluster afterSecondary = rdsService.removeFromGlobalCluster("gdb", SECONDARY_ARN, null);
+ assertEquals(1, afterSecondary.getMembers().size());
+ assertNull(rdsService.getDbCluster("gdb-secondary", "eu-west-1").getGlobalClusterIdentifier(),
+ "a removed cluster is standalone");
+ AwsException notMember = assertThrows(AwsException.class, () ->
+ rdsService.removeFromGlobalCluster("gdb", SECONDARY_ARN, null));
+ assertEquals("DBClusterNotFoundFault", notMember.getErrorCode());
+
+ // Deleting a member cluster detaches it; the primary is last and deletion protection holds.
+ rdsService.deleteDbCluster("gdb-primary");
+ assertTrue(rdsService.describeGlobalCluster("gdb").getMembers().isEmpty());
+ AwsException protectedGlobal = assertThrows(AwsException.class, () -> rdsService.deleteGlobalCluster("gdb"));
+ assertEquals("InvalidGlobalClusterStateFault", protectedGlobal.getErrorCode());
+ assertTrue(protectedGlobal.getMessage().contains("deletion protection"));
+ rdsService.modifyGlobalCluster("gdb", null, false, null, null);
+ assertEquals("deleting", rdsService.deleteGlobalCluster("gdb").getStatus());
+ AwsException gone = assertThrows(AwsException.class, () -> rdsService.describeGlobalCluster("gdb"));
+ assertEquals("GlobalClusterNotFoundFault", gone.getErrorCode());
+ assertTrue(rdsService.listGlobalClusters().isEmpty());
+ }
+
+ @Test
+ void modifyGlobalClusterRenamesAndUpgradesItsMembers() {
+ rdsService.createGlobalCluster("gdb", null, "aurora-postgresql", "15.4", null, null, null, Map.of(), null);
+ createGlobalMember("gdb", "gdb-primary", null, "admin", "password");
+
+ GlobalCluster renamed = rdsService.modifyGlobalCluster("gdb", "GDB-Renamed", true, null, null);
+ assertEquals("gdb-renamed", renamed.getGlobalClusterIdentifier());
+ assertEquals("arn:aws:rds::123456789012:global-cluster:gdb-renamed", renamed.getGlobalClusterArn());
+ assertTrue(renamed.isDeletionProtection());
+ assertEquals("gdb-renamed", rdsService.getDbCluster("gdb-primary").getGlobalClusterIdentifier());
+ assertThrows(AwsException.class, () -> rdsService.describeGlobalCluster("gdb"));
+
+ AwsException major = assertThrows(AwsException.class, () ->
+ rdsService.modifyGlobalCluster("gdb-renamed", null, null, "16.3", null));
+ assertEquals("InvalidParameterCombination", major.getErrorCode());
+ GlobalCluster upgraded = rdsService.modifyGlobalCluster("gdb-renamed", null, null, "16.3", true);
+ assertEquals("16.3", upgraded.getEngineVersion());
+ assertEquals("16.3", rdsService.getDbCluster("gdb-primary").getEngineVersion());
+
+ rdsService.createGlobalCluster("other", null, "aurora-mysql", null, null, null, null, Map.of(), null);
+ AwsException taken = assertThrows(AwsException.class, () ->
+ rdsService.modifyGlobalCluster("gdb-renamed", "other", null, null, null));
+ assertEquals("GlobalClusterAlreadyExistsFault", taken.getErrorCode());
+ }
+
+ @Test
+ void failoverDbClusterMovesTheWriterRole() {
+ rdsService.createDbCluster("aurora", "aurora-postgresql", "16.3", "admin", "password", "appdb", false, null);
+ AwsException noMembers = assertThrows(AwsException.class, () ->
+ rdsService.failoverDbCluster("aurora", null, null));
+ assertEquals("InvalidDBClusterStateFault", noMembers.getErrorCode());
+
+ rdsService.createDbInstance("writer", "aurora-postgresql", "16.3", null, null, null,
+ "db.r6g.large", 0, false, null, null, "aurora", null, false);
+ assertEquals("writer", rdsService.getDbCluster("aurora").resolveWriterIdentifier());
+ AwsException noReader = assertThrows(AwsException.class, () ->
+ rdsService.failoverDbCluster("aurora", null, null));
+ assertEquals("InvalidDBClusterStateFault", noReader.getErrorCode());
+
+ rdsService.createDbInstance("reader", "aurora-postgresql", "16.3", null, null, null,
+ "db.r6g.large", 0, false, null, null, "aurora", null, false);
+ assertEquals("writer", rdsService.getDbCluster("aurora").resolveWriterIdentifier(),
+ "a second member joins as a reader");
+ assertEquals("reader", rdsService.failoverDbCluster("aurora", null, null).resolveWriterIdentifier());
+ assertEquals("writer", rdsService.failoverDbCluster("aurora", "writer", null).resolveWriterIdentifier());
+
+ AwsException alreadyWriter = assertThrows(AwsException.class, () ->
+ rdsService.failoverDbCluster("aurora", "writer", null));
+ assertEquals("InvalidDBInstanceState", alreadyWriter.getErrorCode());
+ AwsException stranger = assertThrows(AwsException.class, () ->
+ rdsService.failoverDbCluster("aurora", "nope", null));
+ assertEquals("InvalidDBInstanceState", stranger.getErrorCode());
+
+ // Losing the writer promotes the remaining member.
+ rdsService.deleteDbInstance("writer");
+ assertEquals("reader", rdsService.getDbCluster("aurora").resolveWriterIdentifier());
+ }
}