mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(rds): add blue/green deployments for DB instances (#8104)
CreateBlueGreenDeployment stages a green copy of a PostgreSQL, MySQL or MariaDB instance with the target engine version, parameter group, class and storage, linked to the blue instance as a read replica and loaded from a dump of it. SwitchoverBlueGreenDeployment gives green the blue identifier, ARN, endpoint and tags and renames blue to <name>-old<n>; the container manager moves each running container to its new ARN so stop and delete still find it. DescribeBlueGreenDeployments supports the four documented filters and paging, and reports INVALID_CONFIGURATION when a member is gone. DeleteBlueGreenDeployment honours DeleteTarget before switchover. Deployments are taggable by their deployment ARN. Closes #8069
This commit is contained in:
1 parent
acdbde836a
commit
654473f754
8 files changed
+1508
-1
No files matched your search
@@ -68,7 +68,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 35 |
|
||||
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 |
|
||||
| [Aurora DSQL](dsql.md) | `/cluster`, `/cluster/{identifier}`, `/cluster/{identifier}/policy` + TLS endpoint | REST JSON + wire | 9 |
|
||||
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 117 |
|
||||
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 121 |
|
||||
| [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 |
|
||||
| [Timestream for InfluxDB](timestream-influxdb.md) | `POST /` + `X-Amz-Target: AmazonTimestreamInfluxDB.*` + InfluxDB container | JSON 1.0 + InfluxDB HTTP | 24 |
|
||||
| [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 |
|
||||
|
||||
@@ -165,6 +165,10 @@ RDS endpoints return the us-east-1 hosted zone ID `Z2R2ITUGPM61AM` in all region
|
||||
| `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 |
|
||||
| `CreateBlueGreenDeployment` | Stage a green copy of a DB instance with a new engine version, parameter group, class or storage; see [Blue/Green deployments](#bluegreen-deployments) |
|
||||
| `DescribeBlueGreenDeployments` | List blue/green deployments, by identifier and the `blue-green-deployment-identifier`, `blue-green-deployment-name`, `source` and `target` filters |
|
||||
| `SwitchoverBlueGreenDeployment` | Make the green instance production: it takes the blue name, ARN, endpoint and tags, and blue becomes `<name>-old1` |
|
||||
| `DeleteBlueGreenDeployment` | Delete a deployment, with `DeleteTarget` also deleting the green instance before switchover |
|
||||
| `AddTagsToResource` | Add tags to a DB resource |
|
||||
| `ListTagsForResource` | List tags for a DB resource |
|
||||
| `RemoveTagsFromResource` | Remove tags from a DB resource |
|
||||
@@ -708,6 +712,42 @@ 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.
|
||||
|
||||
## Blue/Green deployments
|
||||
|
||||
`CreateBlueGreenDeployment` takes a PostgreSQL, MySQL or MariaDB DB instance by ARN as `Source`
|
||||
and creates its green copy, named `<source>-green-<suffix>`. The green instance inherits the
|
||||
blue one's settings and tags, with `TargetEngineVersion`, `TargetDBParameterGroupName`,
|
||||
`TargetDBInstanceClass`, `TargetAllocatedStorage` and `TargetStorageType` applied. Without
|
||||
`TargetDBParameterGroupName` it keeps the blue parameter group when the engine version stays in the
|
||||
same family, and gets the default group of the new family on a major upgrade. Both instances report
|
||||
the link in `DescribeDBInstances` as a read replica pair. The green database is initialised from a
|
||||
dump of the blue one taken at creation, the mechanism snapshots use, so it holds the blue data as
|
||||
of that moment; writes made to blue afterwards are not streamed to it.
|
||||
|
||||
Creation finishes before the response, so the deployment is reported `AVAILABLE` straight away
|
||||
with its `SwitchoverDetails` and `Tasks`. As on AWS, a source needs automated backups on
|
||||
(`InvalidDBInstanceState` otherwise), a lower `TargetEngineVersion` is refused, and an instance can
|
||||
be in one deployment at a time. Floci refuses with `SourceDatabaseNotSupportedFault` an instance
|
||||
that belongs to a cluster, is a read replica or has read replicas, keeps its master password in
|
||||
Secrets Manager, or is a DB proxy target, and refuses a DB cluster source with
|
||||
`SourceClusterNotSupportedFault`. `TargetIops`, `TargetStorageThroughput` and
|
||||
`UpgradeTargetStorageConfig` are accepted and not applied, as `CreateDBInstance` treats IOPS.
|
||||
|
||||
`SwitchoverBlueGreenDeployment` requires the deployment to be `AVAILABLE` and both instances
|
||||
available. Green takes the blue identifier, ARN, endpoint and tags, so clients that connect to the
|
||||
blue endpoint reach the new database without a change. Blue is renamed `<name>-old<n>`, moves to
|
||||
the endpoint green had, and keeps running. The deployment ends `SWITCHOVER_COMPLETED`, with
|
||||
`Source` naming the old instance and `Target` the new production one. The switchover completes
|
||||
before the response; `SwitchoverTimeout` is checked against the 30 to 3600 second range and has
|
||||
nothing else to bound. The old instance is not made read only.
|
||||
|
||||
Before switchover, a deployment whose blue or green instance has been deleted, or whose green
|
||||
instance was promoted, reports `INVALID_CONFIGURATION` and can no longer be switched over.
|
||||
`DeleteBlueGreenDeployment` deletes the green instance too with `DeleteTarget`, which is refused
|
||||
after switchover; without it the green instance is kept as a standalone instance. The blue
|
||||
instance is never touched. A deployment is tagged through its
|
||||
`arn:aws:rds:<region>:<account>:deployment:<identifier>` ARN.
|
||||
|
||||
## Engine catalogue
|
||||
|
||||
`DescribeDBEngineVersions` and `DescribeOrderableDBInstanceOptions` read one curated catalogue: a
|
||||
|
||||
@@ -13,6 +13,7 @@ import io.floci.aws.core.common.XmlBuilder;
|
||||
import io.floci.aws.services.docdb.DocDbQueryHandler;
|
||||
import io.floci.aws.services.neptune.NeptuneQueryHandler;
|
||||
import io.floci.aws.services.rds.export.RdsExportTaskService;
|
||||
import io.floci.aws.services.rds.model.BlueGreenDeployment;
|
||||
import io.floci.aws.services.rds.model.DatabaseEngine;
|
||||
import io.floci.aws.services.rds.model.DbCluster;
|
||||
import io.floci.aws.services.rds.model.DbClusterAutomatedBackup;
|
||||
@@ -219,6 +220,10 @@ public class RdsQueryHandler {
|
||||
case "FailoverGlobalCluster" -> handleFailoverGlobalCluster(params, region);
|
||||
case "SwitchoverGlobalCluster" -> handleSwitchoverGlobalCluster(params, region);
|
||||
case "FailoverDBCluster" -> handleFailoverDbCluster(params, region);
|
||||
case "CreateBlueGreenDeployment" -> handleCreateBlueGreenDeployment(params, region);
|
||||
case "DescribeBlueGreenDeployments" -> handleDescribeBlueGreenDeployments(params, region);
|
||||
case "SwitchoverBlueGreenDeployment" -> handleSwitchoverBlueGreenDeployment(params, region);
|
||||
case "DeleteBlueGreenDeployment" -> handleDeleteBlueGreenDeployment(params, region);
|
||||
case "AddTagsToResource" -> handleAddTagsToResource(params, region);
|
||||
case "ListTagsForResource" -> handleListTagsForResource(params, region);
|
||||
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params, region);
|
||||
@@ -234,6 +239,96 @@ public class RdsQueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Blue/Green deployments ────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateBlueGreenDeployment(MultivaluedMap<String, String> params, String region) {
|
||||
BlueGreenDeployment deployment = service.createBlueGreenDeployment(
|
||||
new RdsService.BlueGreenDeploymentRequest(
|
||||
params.getFirst("BlueGreenDeploymentName"),
|
||||
params.getFirst("Source"),
|
||||
params.getFirst("TargetEngineVersion"),
|
||||
params.getFirst("TargetDBParameterGroupName"),
|
||||
params.getFirst("TargetDBClusterParameterGroupName"),
|
||||
params.getFirst("TargetDBInstanceClass"),
|
||||
parseOptionalInteger(params, "TargetAllocatedStorage"),
|
||||
params.getFirst("TargetStorageType"),
|
||||
parseTags(params)),
|
||||
region);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateBlueGreenDeployment", AwsNamespaces.RDS,
|
||||
blueGreenDeploymentXml("BlueGreenDeployment", deployment))).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeBlueGreenDeployments(MultivaluedMap<String, String> params, String region) {
|
||||
Map<String, List<String>> filters = new LinkedHashMap<>();
|
||||
for (int i = 1; params.getFirst("Filters.Filter." + i + ".Name") != null; i++) {
|
||||
String name = params.getFirst("Filters.Filter." + i + ".Name");
|
||||
filters.put(name, extractRdsFilterValues(params, name));
|
||||
}
|
||||
RdsService.BlueGreenDeploymentPage page = service.describeBlueGreenDeployments(region,
|
||||
params.getFirst("BlueGreenDeploymentIdentifier"), filters,
|
||||
optionalInt(params.getFirst("MaxRecords")), params.getFirst("Marker"));
|
||||
XmlBuilder xml = new XmlBuilder().start("BlueGreenDeployments");
|
||||
for (BlueGreenDeployment deployment : page.deployments()) {
|
||||
xml.raw(blueGreenDeploymentXml("member", deployment));
|
||||
}
|
||||
xml.end("BlueGreenDeployments");
|
||||
if (page.marker() != null) {
|
||||
xml.elem("Marker", page.marker());
|
||||
}
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeBlueGreenDeployments", AwsNamespaces.RDS,
|
||||
xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleSwitchoverBlueGreenDeployment(MultivaluedMap<String, String> params, String region) {
|
||||
BlueGreenDeployment deployment = service.switchoverBlueGreenDeployment(
|
||||
params.getFirst("BlueGreenDeploymentIdentifier"),
|
||||
parseOptionalInteger(params, "SwitchoverTimeout"), region);
|
||||
return Response.ok(AwsQueryResponse.envelope("SwitchoverBlueGreenDeployment", AwsNamespaces.RDS,
|
||||
blueGreenDeploymentXml("BlueGreenDeployment", deployment))).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteBlueGreenDeployment(MultivaluedMap<String, String> params, String region) {
|
||||
BlueGreenDeployment deployment = service.deleteBlueGreenDeployment(
|
||||
params.getFirst("BlueGreenDeploymentIdentifier"),
|
||||
parseOptionalBoolean(params, "DeleteTarget"), region);
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteBlueGreenDeployment", AwsNamespaces.RDS,
|
||||
blueGreenDeploymentXml("BlueGreenDeployment", deployment))).build();
|
||||
}
|
||||
|
||||
private static String blueGreenDeploymentXml(String element, BlueGreenDeployment d) {
|
||||
XmlBuilder xml = new XmlBuilder().start(element)
|
||||
.elem("BlueGreenDeploymentIdentifier", d.getBlueGreenDeploymentIdentifier())
|
||||
.elem("BlueGreenDeploymentName", d.getBlueGreenDeploymentName())
|
||||
.elem("Source", d.getSource())
|
||||
.elem("Target", d.getTarget())
|
||||
.start("SwitchoverDetails");
|
||||
for (BlueGreenDeployment.SwitchoverDetail detail : d.getSwitchoverDetails()) {
|
||||
xml.start("member")
|
||||
.elem("SourceMember", detail.getSourceMember())
|
||||
.elem("TargetMember", detail.getTargetMember())
|
||||
.elem("Status", detail.getStatus())
|
||||
.end("member");
|
||||
}
|
||||
xml.end("SwitchoverDetails").start("Tasks");
|
||||
for (BlueGreenDeployment.Task task : d.getTasks()) {
|
||||
xml.start("member").elem("Name", task.getName()).elem("Status", task.getStatus()).end("member");
|
||||
}
|
||||
xml.end("Tasks").elem("Status", d.getStatus());
|
||||
if (d.getStatusDetails() != null) {
|
||||
xml.elem("StatusDetails", d.getStatusDetails());
|
||||
}
|
||||
if (d.getCreateTime() != null) {
|
||||
xml.elem("CreateTime", d.getCreateTime().toString());
|
||||
}
|
||||
if (d.getDeleteTime() != null) {
|
||||
xml.elem("DeleteTime", d.getDeleteTime().toString());
|
||||
}
|
||||
xml.start("TagList");
|
||||
writeTags(xml, d.getTags());
|
||||
xml.end("TagList");
|
||||
return xml.end(element).build();
|
||||
}
|
||||
|
||||
// ── DB Instances ──────────────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateDbInstance(MultivaluedMap<String, String> params, String region) {
|
||||
|
||||
@@ -35,6 +35,7 @@ import io.floci.aws.services.rds.container.AutoPauseListener;
|
||||
import io.floci.aws.services.rds.container.RdsContainerHandle;
|
||||
import io.floci.aws.services.rds.container.RdsContainerManager;
|
||||
import io.floci.aws.services.rds.export.SnapshotExportSource;
|
||||
import io.floci.aws.services.rds.model.BlueGreenDeployment;
|
||||
import io.floci.aws.services.rds.model.DatabaseEngine;
|
||||
import io.floci.aws.services.rds.model.DbCluster;
|
||||
import io.floci.aws.services.rds.model.DbClusterAutomatedBackup;
|
||||
@@ -187,6 +188,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
private StorageBackend<String, RdsEvent> events = new InMemoryStorage<>();
|
||||
private final StorageBackend<String, EventSubscription> eventSubscriptions;
|
||||
private final StorageBackend<String, DbClusterEndpoint> clusterEndpoints;
|
||||
private final StorageBackend<String, BlueGreenDeployment> blueGreenDeployments;
|
||||
/** The account's ModifyCertificates override per Region, by CA identifier. */
|
||||
private final StorageBackend<String, String> certificateOverrides;
|
||||
private final StorageBackend<String, DbProxyEndpoint> proxyEndpoints;
|
||||
@@ -269,6 +271,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
new TypeReference<Map<String, EventSubscription>>() {});
|
||||
this.clusterEndpoints = storageFactory.create("rds", "rds-cluster-endpoints.json",
|
||||
new TypeReference<Map<String, DbClusterEndpoint>>() {});
|
||||
this.blueGreenDeployments = storageFactory.create("rds", "rds-blue-green-deployments.json",
|
||||
new TypeReference<Map<String, BlueGreenDeployment>>() {});
|
||||
this.proxyEndpoints = storageFactory.create("rds", "rds-proxy-endpoints.json",
|
||||
new TypeReference<Map<String, DbProxyEndpoint>>() {});
|
||||
this.clusters = storageFactory.create("rds", "rds-clusters.json",
|
||||
@@ -440,6 +444,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
this.eventSubscriptions = new InMemoryStorage<>();
|
||||
this.certificateOverrides = new InMemoryStorage<>();
|
||||
this.clusterEndpoints = new InMemoryStorage<>();
|
||||
this.blueGreenDeployments = new InMemoryStorage<>();
|
||||
this.proxyEndpoints = new InMemoryStorage<>();
|
||||
this.instanceAutomatedBackups = new InMemoryStorage<>();
|
||||
this.clusterAutomatedBackups = new InMemoryStorage<>();
|
||||
@@ -3212,6 +3217,13 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
eventSubscriptions.put(eventSubscriptionKey(effectiveRegion, resourceId), subscription);
|
||||
});
|
||||
}
|
||||
case "deployment" -> {
|
||||
BlueGreenDeployment deployment = requireBlueGreenDeployment(effectiveRegion, resourceId);
|
||||
yield new TagHandle(deployment.getTags(), updated -> {
|
||||
deployment.setTags(updated);
|
||||
blueGreenDeployments.put(blueGreenDeploymentKey(effectiveRegion, resourceId), deployment);
|
||||
});
|
||||
}
|
||||
case "db-proxy-endpoint" -> {
|
||||
DbProxyEndpoint endpoint = proxyEndpoints.scan(k -> k.startsWith(effectiveRegion + "::")).stream()
|
||||
.filter(candidate -> resourceName.equals(candidate.getDbProxyEndpointArn()))
|
||||
@@ -5238,6 +5250,10 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
throw new AwsException("InvalidDBInstanceState",
|
||||
"DB instance " + id + " is registered with a DB proxy target group.", 400);
|
||||
}
|
||||
if (provisioningIds.contains(blueGreenSourceKey(instance.getDbInstanceArn()))) {
|
||||
throw new AwsException("InvalidDBInstanceState",
|
||||
"DB instance " + id + " is the source of a blue/green deployment being created.", 400);
|
||||
}
|
||||
|
||||
String clusterId = instance.getDbClusterIdentifier();
|
||||
// Taken before the instance changes, so a failed copy of its data leaves it as it was.
|
||||
@@ -12145,6 +12161,608 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Blue/Green deployments ────────────────────────────────────────────────
|
||||
|
||||
private static final Pattern BLUE_GREEN_DEPLOYMENT_NAME = Pattern.compile("[a-zA-Z](?:-?[a-zA-Z0-9]+)*");
|
||||
private static final int MAX_BLUE_GREEN_DEPLOYMENT_NAME = 60;
|
||||
private static final int MAX_DB_INSTANCE_IDENTIFIER = 63;
|
||||
private static final Set<DatabaseEngine> BLUE_GREEN_ENGINES =
|
||||
Set.of(DatabaseEngine.POSTGRES, DatabaseEngine.MYSQL, DatabaseEngine.MARIADB);
|
||||
private static final Set<String> BLUE_GREEN_FILTERS = Set.of(
|
||||
"blue-green-deployment-identifier", "blue-green-deployment-name", "source", "target");
|
||||
private static final int MIN_SWITCHOVER_TIMEOUT = 30;
|
||||
private static final int MAX_SWITCHOVER_TIMEOUT = 3600;
|
||||
private static final String BLUE_GREEN_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
/** The CreateBlueGreenDeployment request members Floci applies to the green instance. */
|
||||
public record BlueGreenDeploymentRequest(String name,
|
||||
String source,
|
||||
String targetEngineVersion,
|
||||
String targetDbParameterGroupName,
|
||||
String targetDbClusterParameterGroupName,
|
||||
String targetDbInstanceClass,
|
||||
Integer targetAllocatedStorage,
|
||||
String targetStorageType,
|
||||
Map<String, String> tags) {}
|
||||
|
||||
/** One page of deployments, plus the marker to continue from, or null at the end. */
|
||||
public record BlueGreenDeploymentPage(List<BlueGreenDeployment> deployments, String marker) {}
|
||||
|
||||
/**
|
||||
* Creates a blue/green deployment for a DB instance. The green instance is a copy of the blue
|
||||
* one named {@code <blue>-green-<suffix>}, linked to it as a read replica the way
|
||||
* DescribeDBInstances reports it on AWS, with the target engine version, parameter group,
|
||||
* class and storage applied. Its database is initialised from a dump of the blue one taken
|
||||
* now, so it holds the blue data as of creation; later writes to blue do not stream to it.
|
||||
*
|
||||
* <p>Creation runs to completion before the response, so the deployment is reported
|
||||
* {@code AVAILABLE} rather than passing through {@code PROVISIONING}.
|
||||
*/
|
||||
public BlueGreenDeployment createBlueGreenDeployment(BlueGreenDeploymentRequest request, String region) {
|
||||
String effectiveRegion = effectiveRegion(region);
|
||||
String name = request.name();
|
||||
if (isBlank(name)) {
|
||||
throw new AwsException("InvalidParameterValue", "BlueGreenDeploymentName is required.", 400);
|
||||
}
|
||||
if (name.length() > MAX_BLUE_GREEN_DEPLOYMENT_NAME || !BLUE_GREEN_DEPLOYMENT_NAME.matcher(name).matches()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"BlueGreenDeploymentName must be 1 to " + MAX_BLUE_GREEN_DEPLOYMENT_NAME
|
||||
+ " letters, digits or hyphens, start with a letter, and not end with or "
|
||||
+ "contain two consecutive hyphens.", 400);
|
||||
}
|
||||
if (isBlank(request.source())) {
|
||||
throw new AwsException("InvalidParameterValue", "Source is required.", 400);
|
||||
}
|
||||
if (!isBlank(request.targetDbClusterParameterGroupName())) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"TargetDBClusterParameterGroupName applies only to a DB cluster source.", 400);
|
||||
}
|
||||
|
||||
String provisioningKey = "bgd:" + currentAccountId() + ":" + effectiveRegion + ":" + name;
|
||||
if (!provisioningIds.add(provisioningKey)) {
|
||||
throw blueGreenDeploymentAlreadyExists(name);
|
||||
}
|
||||
try {
|
||||
return doCreateBlueGreenDeployment(request, effectiveRegion);
|
||||
} finally {
|
||||
provisioningIds.remove(provisioningKey);
|
||||
}
|
||||
}
|
||||
|
||||
private BlueGreenDeployment doCreateBlueGreenDeployment(BlueGreenDeploymentRequest request, String region) {
|
||||
String name = request.name();
|
||||
DbInstance blue;
|
||||
String sourceKey;
|
||||
synchronized (this) {
|
||||
if (findBlueGreenDeploymentByName(region, name) != null) {
|
||||
throw blueGreenDeploymentAlreadyExists(name);
|
||||
}
|
||||
blue = resolveBlueGreenSource(request.source(), region);
|
||||
requireBlueGreenSourceSupported(blue, region);
|
||||
// The membership check above sees only finished deployments, so a second create naming
|
||||
// the same source while the first is still copying data is stopped here. Taken under
|
||||
// the same lock, so a delete of the source either ran first or sees this and refuses.
|
||||
sourceKey = blueGreenSourceKey(blue.getDbInstanceArn());
|
||||
if (!provisioningIds.add(sourceKey)) {
|
||||
throw new AwsException("InvalidDBInstanceState",
|
||||
"DB instance " + blue.getDbInstanceIdentifier()
|
||||
+ " is already the source of a blue/green deployment being created.", 400);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return provisionBlueGreenDeployment(request, blue, region);
|
||||
} finally {
|
||||
provisioningIds.remove(sourceKey);
|
||||
}
|
||||
}
|
||||
|
||||
private BlueGreenDeployment provisionBlueGreenDeployment(
|
||||
BlueGreenDeploymentRequest request, DbInstance blue, String region) {
|
||||
String name = request.name();
|
||||
String blueId = blue.getDbInstanceIdentifier();
|
||||
|
||||
String sourceVersion = blue.getEngineVersion();
|
||||
String targetVersion = firstNonBlank(request.targetEngineVersion(), sourceVersion);
|
||||
if (sourceVersion != null && RdsEngineCatalog.compareVersions(targetVersion, sourceVersion) < 0) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"TargetEngineVersion " + targetVersion + " is lower than the source engine version "
|
||||
+ sourceVersion + ".", 400);
|
||||
}
|
||||
String engineParam = blue.getEngineIdentifier() != null
|
||||
? blue.getEngineIdentifier() : blue.getEngine().name().toLowerCase(Locale.ROOT);
|
||||
boolean sameFamily = Objects.equals(
|
||||
expectedClusterParameterGroupFamily(engineParam, sourceVersion),
|
||||
expectedClusterParameterGroupFamily(engineParam, targetVersion));
|
||||
String parameterGroupName = !isBlank(request.targetDbParameterGroupName())
|
||||
? request.targetDbParameterGroupName()
|
||||
: sameFamily ? blue.getParameterGroupName() : null;
|
||||
if (!isBlank(request.targetDbParameterGroupName())) {
|
||||
getDbParameterGroup(request.targetDbParameterGroupName(), region);
|
||||
}
|
||||
|
||||
if (request.targetAllocatedStorage() != null && request.targetAllocatedStorage() <= 0) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"TargetAllocatedStorage must be a positive number of GiB.", 400);
|
||||
}
|
||||
String greenId = greenInstanceIdentifier(blueId);
|
||||
DbInstanceSettings settings = new DbInstanceSettings(
|
||||
blue.isStorageEncrypted() ? Boolean.TRUE : null,
|
||||
blue.isStorageEncrypted() ? blue.getKmsKeyId() : null,
|
||||
blue.getBackupRetentionPeriod(), blue.getPreferredBackupWindow(),
|
||||
blue.getPreferredMaintenanceWindow(), blue.isCopyTagsToSnapshot())
|
||||
.withStorageType(firstNonBlank(request.targetStorageType(), blue.getStorageType()))
|
||||
.withCaCertificateIdentifier(blue.getCaCertificateIdentifier());
|
||||
DbInstance green = createDbInstance(greenId, engineParam, targetVersion,
|
||||
blue.getMasterUsername(), blue.getMasterPassword(), blue.getDbName(),
|
||||
firstNonBlank(request.targetDbInstanceClass(), blue.getDbInstanceClass()),
|
||||
request.targetAllocatedStorage() != null
|
||||
? request.targetAllocatedStorage() : blue.getAllocatedStorage(),
|
||||
blue.isIamDatabaseAuthenticationEnabled(), parameterGroupName,
|
||||
blue.getDbSubnetGroupName(), null, blue.getAvailabilityZone(), blue.isMultiAz(),
|
||||
false, null, blue.getTags(), blue.getVpcSecurityGroupIds(), blue.getOptionGroupName(),
|
||||
region, blue.isAutoMinorVersionUpgrade(), settings, blue.isPubliclyAccessible(),
|
||||
null, false);
|
||||
|
||||
linkReadReplica(blue, green);
|
||||
if (!config.services().rds().mock()
|
||||
&& blue.getContainerId() != null && green.getContainerId() != null) {
|
||||
try {
|
||||
copyInstanceData(blue, green);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
deleteDbInstance(greenId, region);
|
||||
} catch (RuntimeException cleanupError) {
|
||||
e.addSuppressed(cleanupError);
|
||||
}
|
||||
AwsException failure = new AwsException("InvalidDBInstanceState",
|
||||
"Failed to initialise green DB instance " + greenId + " from " + blueId + ": "
|
||||
+ e.getMessage(), 400);
|
||||
failure.initCause(e);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (this) {
|
||||
green.setStatus(DbInstanceStatus.AVAILABLE);
|
||||
putInstanceForScope(accountIdFromArn(green.getDbInstanceArn()), region, greenId, green);
|
||||
|
||||
BlueGreenDeployment deployment = new BlueGreenDeployment();
|
||||
String id = "bgd-" + randomLowercase(16);
|
||||
deployment.setBlueGreenDeploymentIdentifier(id);
|
||||
deployment.setBlueGreenDeploymentName(name);
|
||||
deployment.setBlueGreenDeploymentArn(regionResolver.buildArn("rds", region, "deployment:" + id));
|
||||
deployment.setSource(blue.getDbInstanceArn());
|
||||
deployment.setTarget(green.getDbInstanceArn());
|
||||
deployment.setStatus(BlueGreenDeployment.AVAILABLE);
|
||||
deployment.getSwitchoverDetails().add(new BlueGreenDeployment.SwitchoverDetail(
|
||||
blue.getDbInstanceArn(), green.getDbInstanceArn(), BlueGreenDeployment.AVAILABLE));
|
||||
deployment.getTasks().add(new BlueGreenDeployment.Task("CREATING_READ_REPLICA_OF_SOURCE", "COMPLETED"));
|
||||
if (!Objects.equals(targetVersion, sourceVersion)) {
|
||||
deployment.getTasks().add(new BlueGreenDeployment.Task("DB_ENGINE_VERSION_UPGRADE", "COMPLETED"));
|
||||
}
|
||||
deployment.getTasks().add(new BlueGreenDeployment.Task("CONFIGURE_BACKUPS", "COMPLETED"));
|
||||
deployment.setTags(request.tags());
|
||||
deployment.setCreateTime(Instant.now());
|
||||
blueGreenDeployments.put(blueGreenDeploymentKey(region, id), deployment);
|
||||
LOG.infov("Blue/green deployment {0} created: {1} -> {2}", id, blueId, greenId);
|
||||
return deployment;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches the green instance into production. Green takes the blue instance's identifier,
|
||||
* ARN and endpoint, so clients reconnect to the same address and reach the new database; the
|
||||
* blue instance is renamed {@code <name>-old<n>}, moves to the endpoint green had, and stays
|
||||
* running. Blue's tags replace green's, as on AWS. The switchover completes before the
|
||||
* response, so {@code SwitchoverTimeout} is validated and otherwise has nothing to bound.
|
||||
*/
|
||||
public synchronized BlueGreenDeployment switchoverBlueGreenDeployment(
|
||||
String identifier, Integer switchoverTimeout, String region) {
|
||||
String effectiveRegion = effectiveRegion(region);
|
||||
if (switchoverTimeout != null
|
||||
&& (switchoverTimeout < MIN_SWITCHOVER_TIMEOUT || switchoverTimeout > MAX_SWITCHOVER_TIMEOUT)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"SwitchoverTimeout must be between " + MIN_SWITCHOVER_TIMEOUT + " and "
|
||||
+ MAX_SWITCHOVER_TIMEOUT + " seconds.", 400);
|
||||
}
|
||||
// Refreshed first, so a member deleted or promoted since the last describe is caught here.
|
||||
BlueGreenDeployment deployment = refreshBlueGreenStatus(
|
||||
effectiveRegion, requireBlueGreenDeployment(effectiveRegion, identifier));
|
||||
if (!BlueGreenDeployment.AVAILABLE.equals(deployment.getStatus())) {
|
||||
throw new AwsException("InvalidBlueGreenDeploymentStateFault",
|
||||
"Blue/green deployment " + deployment.getBlueGreenDeploymentIdentifier()
|
||||
+ " is " + deployment.getStatus() + " and can't be switched over.", 400);
|
||||
}
|
||||
String accountId = currentAccountId();
|
||||
DbInstance blue = findInstanceByArn(accountId, effectiveRegion, deployment.getSource());
|
||||
DbInstance green = findInstanceByArn(accountId, effectiveRegion, deployment.getTarget());
|
||||
for (DbInstance member : new DbInstance[] {blue, green}) {
|
||||
if (member.getStatus() != DbInstanceStatus.AVAILABLE) {
|
||||
throw new AwsException("InvalidBlueGreenDeploymentStateFault",
|
||||
"DB instance " + member.getDbInstanceIdentifier() + " is not in available state.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
String blueId = blue.getDbInstanceIdentifier();
|
||||
String greenId = green.getDbInstanceIdentifier();
|
||||
String blueArn = blue.getDbInstanceArn();
|
||||
String greenArn = green.getDbInstanceArn();
|
||||
String oldId = oldBlueIdentifier(accountId, effectiveRegion, blueId);
|
||||
String oldArn = regionResolver.buildArn("rds", effectiveRegion, "db:" + oldId);
|
||||
boolean mock = config.services().rds().mock();
|
||||
|
||||
if (!mock) {
|
||||
proxyManager.stopProxy(rdsResourceRelayKey(blueArn, blueId));
|
||||
proxyManager.stopProxy(rdsResourceRelayKey(greenArn, greenId));
|
||||
}
|
||||
unlinkReadReplica(green);
|
||||
|
||||
DbEndpoint blueEndpoint = blue.getEndpoint();
|
||||
int bluePort = blue.getProxyPort();
|
||||
blue.setEndpoint(green.getEndpoint());
|
||||
blue.setProxyPort(green.getProxyPort());
|
||||
green.setEndpoint(blueEndpoint);
|
||||
green.setProxyPort(bluePort);
|
||||
|
||||
// Blue moves off its ARN first, so it is free when green takes it.
|
||||
deleteInstanceForScope(accountId, effectiveRegion, blueId);
|
||||
deleteInstanceForScope(accountId, effectiveRegion, greenId);
|
||||
containerManager.renameRuntime(blueArn, oldArn, oldId);
|
||||
containerManager.renameRuntime(greenArn, blueArn, blueId);
|
||||
blue.setDbInstanceIdentifier(oldId);
|
||||
blue.setDbInstanceArn(oldArn);
|
||||
green.setDbInstanceIdentifier(blueId);
|
||||
green.setDbInstanceArn(blueArn);
|
||||
green.setTags(new LinkedHashMap<>(blue.getTags()));
|
||||
putInstanceForScope(accountId, effectiveRegion, oldId, blue);
|
||||
putInstanceForScope(accountId, effectiveRegion, blueId, green);
|
||||
|
||||
if (!mock) {
|
||||
startInstanceRelay(blue);
|
||||
startInstanceRelay(green);
|
||||
}
|
||||
|
||||
deployment.setSource(oldArn);
|
||||
deployment.setTarget(blueArn);
|
||||
deployment.setStatus(BlueGreenDeployment.SWITCHOVER_COMPLETED);
|
||||
deployment.setSwitchoverDetails(List.of(new BlueGreenDeployment.SwitchoverDetail(
|
||||
oldArn, blueArn, BlueGreenDeployment.SWITCHOVER_COMPLETED)));
|
||||
blueGreenDeployments.put(blueGreenDeploymentKey(effectiveRegion,
|
||||
deployment.getBlueGreenDeploymentIdentifier()), deployment);
|
||||
LOG.infov("Blue/green deployment {0} switched over: {1} is now {2}, {3} is now {1}",
|
||||
deployment.getBlueGreenDeploymentIdentifier(), blueId, oldId, greenId);
|
||||
return deployment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the deployment record. With {@code deleteTarget} the green instance is deleted too,
|
||||
* which AWS allows only before a switchover; without it the green instance is kept as a
|
||||
* standalone instance, as RDS for PostgreSQL leaves it. The blue instance is not touched.
|
||||
*/
|
||||
public synchronized BlueGreenDeployment deleteBlueGreenDeployment(
|
||||
String identifier, Boolean deleteTarget, String region) {
|
||||
String effectiveRegion = effectiveRegion(region);
|
||||
BlueGreenDeployment deployment = requireBlueGreenDeployment(effectiveRegion, identifier);
|
||||
String status = deployment.getStatus();
|
||||
if (BlueGreenDeployment.SWITCHOVER_IN_PROGRESS.equals(status)
|
||||
|| BlueGreenDeployment.DELETING.equals(status)) {
|
||||
throw new AwsException("InvalidBlueGreenDeploymentStateFault",
|
||||
"Blue/green deployment " + deployment.getBlueGreenDeploymentIdentifier()
|
||||
+ " is " + status + " and can't be deleted.", 400);
|
||||
}
|
||||
boolean switchedOver = BlueGreenDeployment.SWITCHOVER_COMPLETED.equals(status);
|
||||
if (Boolean.TRUE.equals(deleteTarget) && switchedOver) {
|
||||
throw new AwsException("InvalidBlueGreenDeploymentStateFault",
|
||||
"DeleteTarget can't be specified after blue/green deployment "
|
||||
+ deployment.getBlueGreenDeploymentIdentifier() + " has switched over.", 400);
|
||||
}
|
||||
if (!switchedOver) {
|
||||
DbInstance green = findInstanceByArnOrNull(currentAccountId(), effectiveRegion, deployment.getTarget());
|
||||
if (green != null) {
|
||||
if (Boolean.TRUE.equals(deleteTarget)) {
|
||||
deleteDbInstance(green.getDbInstanceIdentifier(), effectiveRegion);
|
||||
} else {
|
||||
unlinkReadReplica(green);
|
||||
putInstanceForScope(currentAccountId(), effectiveRegion,
|
||||
green.getDbInstanceIdentifier(), green);
|
||||
}
|
||||
}
|
||||
}
|
||||
blueGreenDeployments.delete(blueGreenDeploymentKey(effectiveRegion,
|
||||
deployment.getBlueGreenDeploymentIdentifier()));
|
||||
deployment.setStatus(BlueGreenDeployment.DELETING);
|
||||
deployment.setDeleteTime(Instant.now());
|
||||
return deployment;
|
||||
}
|
||||
|
||||
/**
|
||||
* The deployments in the Region, or the one the identifier names, narrowed by the four
|
||||
* documented filters and paged by identifier. Before switchover a deployment whose blue or
|
||||
* green instance is gone, or whose green instance was promoted, reports
|
||||
* {@code INVALID_CONFIGURATION}, as AWS does.
|
||||
*/
|
||||
public synchronized BlueGreenDeploymentPage describeBlueGreenDeployments(
|
||||
String region, String identifier, Map<String, List<String>> filters,
|
||||
Integer maxRecords, String marker) {
|
||||
String effectiveRegion = effectiveRegion(region);
|
||||
requireValidMaxRecords(maxRecords);
|
||||
for (String filterName : filters.keySet()) {
|
||||
if (!BLUE_GREEN_FILTERS.contains(filterName)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Unrecognized filter name: " + filterName + ".", 400);
|
||||
}
|
||||
}
|
||||
List<BlueGreenDeployment> all;
|
||||
if (!isBlank(identifier)) {
|
||||
all = List.of(requireBlueGreenDeployment(effectiveRegion, identifier));
|
||||
} else {
|
||||
all = blueGreenDeployments.scan(k -> k.startsWith(blueGreenDeploymentKey(effectiveRegion, "")))
|
||||
.stream()
|
||||
.sorted(Comparator.comparing(BlueGreenDeployment::getBlueGreenDeploymentIdentifier))
|
||||
.toList();
|
||||
}
|
||||
List<BlueGreenDeployment> matching = all.stream()
|
||||
.filter(d -> matchesBlueGreenFilter(filters, "blue-green-deployment-identifier",
|
||||
d.getBlueGreenDeploymentIdentifier()))
|
||||
.filter(d -> matchesBlueGreenFilter(filters, "blue-green-deployment-name",
|
||||
d.getBlueGreenDeploymentName()))
|
||||
.filter(d -> matchesBlueGreenFilter(filters, "source", d.getSource()))
|
||||
.filter(d -> matchesBlueGreenFilter(filters, "target", d.getTarget()))
|
||||
.map(d -> refreshBlueGreenStatus(effectiveRegion, d))
|
||||
.toList();
|
||||
int from = 0;
|
||||
if (!isBlank(marker)) {
|
||||
while (from < matching.size()
|
||||
&& matching.get(from).getBlueGreenDeploymentIdentifier().compareTo(marker) <= 0) {
|
||||
from++;
|
||||
}
|
||||
}
|
||||
int limit = maxRecords == null ? DEFAULT_MAX_RECORDS : maxRecords;
|
||||
int to = Math.min(matching.size(), from + limit);
|
||||
List<BlueGreenDeployment> page = matching.subList(Math.min(from, matching.size()), to);
|
||||
String next = to < matching.size() && !page.isEmpty()
|
||||
? page.getLast().getBlueGreenDeploymentIdentifier() : null;
|
||||
return new BlueGreenDeploymentPage(page, next);
|
||||
}
|
||||
|
||||
private static boolean matchesBlueGreenFilter(Map<String, List<String>> filters, String name, String value) {
|
||||
List<String> wanted = filters.get(name);
|
||||
return wanted == null || wanted.isEmpty() || wanted.contains(value);
|
||||
}
|
||||
|
||||
private BlueGreenDeployment refreshBlueGreenStatus(String region, BlueGreenDeployment deployment) {
|
||||
if (!BlueGreenDeployment.AVAILABLE.equals(deployment.getStatus())) {
|
||||
return deployment;
|
||||
}
|
||||
String accountId = currentAccountId();
|
||||
DbInstance blue = findInstanceByArnOrNull(accountId, region, deployment.getSource());
|
||||
DbInstance green = findInstanceByArnOrNull(accountId, region, deployment.getTarget());
|
||||
String memberStatus = blue == null ? "MISSING_SOURCE"
|
||||
: green == null ? "MISSING_TARGET"
|
||||
: !blue.getDbInstanceIdentifier().equals(green.getReadReplicaSourceDbInstanceIdentifier())
|
||||
? BlueGreenDeployment.INVALID_CONFIGURATION : null;
|
||||
if (memberStatus == null) {
|
||||
return deployment;
|
||||
}
|
||||
deployment.setStatus(BlueGreenDeployment.INVALID_CONFIGURATION);
|
||||
if (!BlueGreenDeployment.INVALID_CONFIGURATION.equals(memberStatus)) {
|
||||
deployment.setSwitchoverDetails(List.of(new BlueGreenDeployment.SwitchoverDetail(
|
||||
deployment.getSource(), deployment.getTarget(), memberStatus)));
|
||||
}
|
||||
blueGreenDeployments.put(blueGreenDeploymentKey(region,
|
||||
deployment.getBlueGreenDeploymentIdentifier()), deployment);
|
||||
return deployment;
|
||||
}
|
||||
|
||||
/** The Source of a create request: the ARN of a DB instance in this account and Region. */
|
||||
private DbInstance resolveBlueGreenSource(String source, String region) {
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(source);
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Source must be the ARN of a DB instance: " + source, 400);
|
||||
}
|
||||
String resource = arn.resource();
|
||||
int sep = resource.indexOf(':');
|
||||
if (!"rds".equals(arn.service()) || sep < 0) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Source must be the ARN of a DB instance: " + source, 400);
|
||||
}
|
||||
String type = resource.substring(0, sep);
|
||||
String id = resource.substring(sep + 1);
|
||||
boolean local = region.equals(arn.region()) && currentAccountId().equals(arn.accountId());
|
||||
if ("cluster".equals(type)) {
|
||||
if (!local || findClusterForScope(currentAccountId(), region, id) == null) {
|
||||
throw new AwsException("DBClusterNotFoundFault", "DB cluster " + id + " not found.", 404);
|
||||
}
|
||||
throw new AwsException("SourceClusterNotSupportedFault",
|
||||
"Floci supports blue/green deployments for DB instances only, not DB cluster " + id + ".", 400);
|
||||
}
|
||||
if (!"db".equals(type)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Source must be the ARN of a DB instance: " + source, 400);
|
||||
}
|
||||
DbInstance instance = local ? findInstanceForScope(currentAccountId(), region, id) : null;
|
||||
if (instance == null || !source.equals(instance.getDbInstanceArn())) {
|
||||
throw new AwsException("DBInstanceNotFound", "DB instance " + id + " not found.", 404);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void requireBlueGreenSourceSupported(DbInstance blue, String region) {
|
||||
String id = blue.getDbInstanceIdentifier();
|
||||
// Ahead of the replica check: a blue instance already has its green copy as a replica.
|
||||
String arn = blue.getDbInstanceArn();
|
||||
for (BlueGreenDeployment existing : blueGreenDeployments.scan(
|
||||
k -> k.startsWith(blueGreenDeploymentKey(region, "")))) {
|
||||
if (!BlueGreenDeployment.SWITCHOVER_COMPLETED.equals(existing.getStatus())
|
||||
&& (arn.equals(existing.getSource()) || arn.equals(existing.getTarget()))) {
|
||||
throw new AwsException("InvalidDBInstanceState",
|
||||
"DB instance " + id + " is already part of blue/green deployment "
|
||||
+ existing.getBlueGreenDeploymentIdentifier() + ".", 400);
|
||||
}
|
||||
}
|
||||
if (!isBlank(blue.getDbClusterIdentifier())) {
|
||||
throw new AwsException("SourceDatabaseNotSupportedFault",
|
||||
"DB instance " + id + " belongs to DB cluster " + blue.getDbClusterIdentifier()
|
||||
+ "; Floci supports blue/green deployments for standalone DB instances only.", 400);
|
||||
}
|
||||
if (!BLUE_GREEN_ENGINES.contains(blue.getEngine())) {
|
||||
throw new AwsException("SourceDatabaseNotSupportedFault",
|
||||
"Blue/green deployments are not supported for engine "
|
||||
+ blue.getEngine().name().toLowerCase(Locale.ROOT) + ".", 400);
|
||||
}
|
||||
if (blue.getReadReplicaSourceDbInstanceIdentifier() != null
|
||||
|| !blue.getReadReplicaDbInstanceIdentifiers().isEmpty()) {
|
||||
throw new AwsException("SourceDatabaseNotSupportedFault",
|
||||
"DB instance " + id + " is a read replica or has read replicas; Floci does not "
|
||||
+ "support blue/green deployments for replicated DB instances.", 400);
|
||||
}
|
||||
if (blue.getMasterUserSecretArn() != null) {
|
||||
throw new AwsException("SourceDatabaseNotSupportedFault",
|
||||
"Blue/green deployments are not supported for DB instance " + id
|
||||
+ " because its master user password is managed in Secrets Manager.", 400);
|
||||
}
|
||||
if (isRegisteredProxyTarget("RDS_INSTANCE", id, region)) {
|
||||
throw new AwsException("SourceDatabaseNotSupportedFault",
|
||||
"DB instance " + id + " is registered with a DB proxy target group; Floci does not "
|
||||
+ "support blue/green deployments for DB proxy targets.", 400);
|
||||
}
|
||||
if (blue.getStatus() != DbInstanceStatus.AVAILABLE) {
|
||||
throw new AwsException("InvalidDBInstanceState",
|
||||
"DB instance " + id + " is not in available state.", 400);
|
||||
}
|
||||
if (blue.getBackupRetentionPeriod() <= 0) {
|
||||
throw new AwsException("InvalidDBInstanceState",
|
||||
"Automated backups must be enabled on DB instance " + id
|
||||
+ " before it can be the source of a blue/green deployment.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code <blue>-green-<6 random>}, with the blue part shortened to keep it a valid identifier. */
|
||||
private String greenInstanceIdentifier(String blueId) {
|
||||
return withIdentifierSuffix(blueId, "-green-" + randomLowercase(6));
|
||||
}
|
||||
|
||||
/** The first free {@code <name>-old<n>}, shortening the name when the suffix would overflow. */
|
||||
private String oldBlueIdentifier(String accountId, String region, String blueId) {
|
||||
for (int n = 1; ; n++) {
|
||||
String candidate = withIdentifierSuffix(blueId, "-old" + n);
|
||||
if (findInstanceForScope(accountId, region, candidate) == null
|
||||
&& !scopedKeyExists(instances, accountId, dbResourceKey(region, candidate))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code base + suffix}, with {@code base} shortened so the result fits the identifier limit
|
||||
* and trimmed of trailing hyphens, which would otherwise leave an invalid double hyphen.
|
||||
*/
|
||||
private static String withIdentifierSuffix(String base, String suffix) {
|
||||
String head = base.length() + suffix.length() > MAX_DB_INSTANCE_IDENTIFIER
|
||||
? base.substring(0, MAX_DB_INSTANCE_IDENTIFIER - suffix.length()) : base;
|
||||
while (head.endsWith("-")) {
|
||||
head = head.substring(0, head.length() - 1);
|
||||
}
|
||||
return head + suffix;
|
||||
}
|
||||
|
||||
private static String blueGreenSourceKey(String sourceArn) {
|
||||
return "bgd-source:" + sourceArn;
|
||||
}
|
||||
|
||||
private static String randomLowercase(int length) {
|
||||
SecureRandom random = new SecureRandom();
|
||||
StringBuilder value = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
value.append(BLUE_GREEN_ID_ALPHABET.charAt(random.nextInt(BLUE_GREEN_ID_ALPHABET.length())));
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
/** Copies the source's databases into the target with the dump and restore snapshots use. */
|
||||
private void copyInstanceData(DbInstance source, DbInstance target) {
|
||||
if (source.getEngine() == DatabaseEngine.POSTGRES) {
|
||||
String dump = containerManager.createPostgresSnapshot(
|
||||
source.getContainerId(), source.getMasterUsername());
|
||||
containerManager.restorePostgresSnapshot(
|
||||
target.getContainerId(), target.getMasterUsername(), dump);
|
||||
} else {
|
||||
String dump = containerManager.createMysqlSnapshot(source.getEngine(), source.getContainerId(),
|
||||
source.getMasterUsername(), source.getMasterPassword());
|
||||
containerManager.restoreMysqlSnapshot(target.getEngine(), target.getContainerId(),
|
||||
target.getMasterUsername(), target.getMasterPassword(), dump);
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the auth relay that publishes an instance's endpoint, when it has a backend to reach. */
|
||||
private void startInstanceRelay(DbInstance instance) {
|
||||
if (!hasBackend(instance.getContainerHost(), instance.getContainerPort()) || instance.getEndpoint() == null) {
|
||||
return;
|
||||
}
|
||||
String id = instance.getDbInstanceIdentifier();
|
||||
String effectiveMasterUser = instance.getMasterUsername() != null ? instance.getMasterUsername() : "root";
|
||||
String accountId = accountIdFromArn(instance.getDbInstanceArn());
|
||||
String instanceRegion = regionFromArn(instance.getDbInstanceArn());
|
||||
InstanceBackendIdentity backendIdentity = instanceBackendIdentity(instance);
|
||||
proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
|
||||
backendIdentity.runtimeId(),
|
||||
instance.getEngine(),
|
||||
instance.isIamDatabaseAuthenticationEnabled(),
|
||||
instance.getProxyPort(), instance.getContainerHost(), instance.getContainerPort(),
|
||||
instance.getEndpoint().address(),
|
||||
effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
|
||||
(user, pw) -> validateDbPasswordForScope(accountId, instanceRegion, id, user, pw),
|
||||
proxyBinding(instance.getEngine(), instance.getEndpoint().address(),
|
||||
instance.getEndpoint().port(), instanceRegion, accountId,
|
||||
backendIdentity.dbUserResourceId()));
|
||||
}
|
||||
|
||||
private DbInstance findInstanceByArn(String accountId, String region, String arn) {
|
||||
DbInstance instance = findInstanceByArnOrNull(accountId, region, arn);
|
||||
if (instance == null) {
|
||||
throw new AwsException("InvalidBlueGreenDeploymentStateFault",
|
||||
"DB instance " + arn + " of the blue/green deployment no longer exists.", 400);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private DbInstance findInstanceByArnOrNull(String accountId, String region, String arn) {
|
||||
if (arn == null) {
|
||||
return null;
|
||||
}
|
||||
String id = arn.substring(arn.lastIndexOf(':') + 1);
|
||||
DbInstance instance = findInstanceForScope(accountId, region, id);
|
||||
return instance != null && arn.equals(instance.getDbInstanceArn()) ? instance : null;
|
||||
}
|
||||
|
||||
private BlueGreenDeployment findBlueGreenDeploymentByName(String region, String name) {
|
||||
return blueGreenDeployments.scan(k -> k.startsWith(blueGreenDeploymentKey(region, ""))).stream()
|
||||
.filter(d -> name.equals(d.getBlueGreenDeploymentName()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private BlueGreenDeployment requireBlueGreenDeployment(String region, String identifier) {
|
||||
if (isBlank(identifier)) {
|
||||
throw new AwsException("InvalidParameterValue", "BlueGreenDeploymentIdentifier is required.", 400);
|
||||
}
|
||||
return blueGreenDeployments.get(blueGreenDeploymentKey(region, identifier))
|
||||
.orElseThrow(() -> new AwsException("BlueGreenDeploymentNotFoundFault",
|
||||
"Blue/green deployment " + identifier + " not found.", 404));
|
||||
}
|
||||
|
||||
private static AwsException blueGreenDeploymentAlreadyExists(String name) {
|
||||
return new AwsException("BlueGreenDeploymentAlreadyExistsFault",
|
||||
"Blue/green deployment " + name + " already exists.", 400);
|
||||
}
|
||||
|
||||
private static String blueGreenDeploymentKey(String region, String identifier) {
|
||||
return "bgd::" + region + "::" + identifier;
|
||||
}
|
||||
|
||||
private static String clusterEndpointKey(String region, String endpointId) {
|
||||
return "cep::" + region + "::" + endpointId;
|
||||
}
|
||||
|
||||
@@ -621,6 +621,39 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
handle.getContainerId(), engine.defaultPort(), preferredNetwork);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a runtime to a new id, as a blue/green switchover does when it renames an instance and
|
||||
* so changes its ARN. The running container, its storage claims, pending cleanup and
|
||||
* auto-pause follow the instance, so a later stop or delete under the new ARN still finds
|
||||
* them. The container itself is not touched.
|
||||
*/
|
||||
public void renameRuntime(String oldRuntimeId, String newRuntimeId, String newInstanceId) {
|
||||
if (oldRuntimeId == null || newRuntimeId == null || oldRuntimeId.equals(newRuntimeId)) {
|
||||
return;
|
||||
}
|
||||
if (activeContainers.containsKey(newRuntimeId) || claimedRuntimes.contains(newRuntimeId)) {
|
||||
throw new IllegalStateException("RDS runtime " + newRuntimeId + " already has an active container");
|
||||
}
|
||||
RdsContainerHandle handle = activeContainers.remove(oldRuntimeId);
|
||||
if (handle != null) {
|
||||
RdsContainerHandle moved = new RdsContainerHandle(handle.getContainerId(), newRuntimeId,
|
||||
newInstanceId, handle.getHost(), handle.getPort(),
|
||||
handle.getStorageKey(), handle.getContainerKey());
|
||||
moved.setLogStream(handle.getLogStream());
|
||||
activeContainers.put(newRuntimeId, moved);
|
||||
}
|
||||
activeStorageOwners.replaceAll((key, owner) -> owner.equals(oldRuntimeId) ? newRuntimeId : owner);
|
||||
for (Set<String> runtimes : List.of(claimedRuntimes, cleanupPending, preCreateCleanupPending)) {
|
||||
if (runtimes.remove(oldRuntimeId)) {
|
||||
runtimes.add(newRuntimeId);
|
||||
}
|
||||
}
|
||||
AutoPauseController autoPause = autoPauses.remove(oldRuntimeId);
|
||||
if (autoPause != null) {
|
||||
autoPauses.put(newRuntimeId, autoPause);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the retained runtime handle used to persist cleanup identity after a failed start. */
|
||||
public RdsContainerHandle getActiveHandle(String runtimeId) {
|
||||
if (runtimeId == null || runtimeId.isBlank()) {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package io.floci.aws.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;
|
||||
|
||||
/**
|
||||
* An RDS blue/green deployment: a production DB instance (blue), a staged copy of it (green) and
|
||||
* the switchover that makes the green one production. Source and Target are the two instances'
|
||||
* ARNs, which follow the renames a switchover makes.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class BlueGreenDeployment {
|
||||
|
||||
public static final String PROVISIONING = "PROVISIONING";
|
||||
public static final String AVAILABLE = "AVAILABLE";
|
||||
public static final String SWITCHOVER_IN_PROGRESS = "SWITCHOVER_IN_PROGRESS";
|
||||
public static final String SWITCHOVER_COMPLETED = "SWITCHOVER_COMPLETED";
|
||||
public static final String INVALID_CONFIGURATION = "INVALID_CONFIGURATION";
|
||||
public static final String DELETING = "DELETING";
|
||||
|
||||
private String blueGreenDeploymentIdentifier;
|
||||
private String blueGreenDeploymentName;
|
||||
private String blueGreenDeploymentArn;
|
||||
private String source;
|
||||
private String target;
|
||||
private String status;
|
||||
private String statusDetails;
|
||||
private List<SwitchoverDetail> switchoverDetails = new ArrayList<>();
|
||||
private List<Task> tasks = new ArrayList<>();
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
private Instant createTime;
|
||||
private Instant deleteTime;
|
||||
|
||||
public BlueGreenDeployment() {}
|
||||
|
||||
public String getBlueGreenDeploymentIdentifier() { return blueGreenDeploymentIdentifier; }
|
||||
public void setBlueGreenDeploymentIdentifier(String id) { this.blueGreenDeploymentIdentifier = id; }
|
||||
|
||||
public String getBlueGreenDeploymentName() { return blueGreenDeploymentName; }
|
||||
public void setBlueGreenDeploymentName(String name) { this.blueGreenDeploymentName = name; }
|
||||
|
||||
public String getBlueGreenDeploymentArn() { return blueGreenDeploymentArn; }
|
||||
public void setBlueGreenDeploymentArn(String arn) { this.blueGreenDeploymentArn = arn; }
|
||||
|
||||
public String getSource() { return source; }
|
||||
public void setSource(String source) { this.source = source; }
|
||||
|
||||
public String getTarget() { return target; }
|
||||
public void setTarget(String target) { this.target = target; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public String getStatusDetails() { return statusDetails; }
|
||||
public void setStatusDetails(String statusDetails) { this.statusDetails = statusDetails; }
|
||||
|
||||
public List<SwitchoverDetail> getSwitchoverDetails() { return switchoverDetails; }
|
||||
public void setSwitchoverDetails(List<SwitchoverDetail> switchoverDetails) {
|
||||
this.switchoverDetails = switchoverDetails != null ? new ArrayList<>(switchoverDetails) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<Task> getTasks() { return tasks; }
|
||||
public void setTasks(List<Task> tasks) {
|
||||
this.tasks = tasks != null ? new ArrayList<>(tasks) : 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 getCreateTime() { return createTime; }
|
||||
public void setCreateTime(Instant createTime) { this.createTime = createTime; }
|
||||
|
||||
public Instant getDeleteTime() { return deleteTime; }
|
||||
public void setDeleteTime(Instant deleteTime) { this.deleteTime = deleteTime; }
|
||||
|
||||
/** One blue resource, the green resource paired with it, and where that pair stands. */
|
||||
@RegisterForReflection
|
||||
public static class SwitchoverDetail {
|
||||
private String sourceMember;
|
||||
private String targetMember;
|
||||
private String status;
|
||||
|
||||
public SwitchoverDetail() {}
|
||||
|
||||
public SwitchoverDetail(String sourceMember, String targetMember, String status) {
|
||||
this.sourceMember = sourceMember;
|
||||
this.targetMember = targetMember;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getSourceMember() { return sourceMember; }
|
||||
public void setSourceMember(String sourceMember) { this.sourceMember = sourceMember; }
|
||||
|
||||
public String getTargetMember() { return targetMember; }
|
||||
public void setTargetMember(String targetMember) { this.targetMember = targetMember; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
}
|
||||
|
||||
/** A step RDS ran on the green environment, such as creating the replica or upgrading it. */
|
||||
@RegisterForReflection
|
||||
public static class Task {
|
||||
private String name;
|
||||
private String status;
|
||||
|
||||
public Task() {}
|
||||
|
||||
public Task(String name, String status) {
|
||||
this.name = name;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package io.floci.aws.services.rds;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.rds.RdsClient;
|
||||
import software.amazon.awssdk.services.rds.model.BlueGreenDeployment;
|
||||
import software.amazon.awssdk.services.rds.model.DBInstance;
|
||||
import software.amazon.awssdk.services.rds.model.DbInstanceNotFoundException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.floci.aws.testing.RdsRequests.assumeDocker;
|
||||
import static io.floci.aws.testing.RdsRequests.rdsClient;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A PostgreSQL 16 to 17 blue/green upgrade against real containers, through the SDK: the green
|
||||
* instance holds the blue rows on the new major version, and after switchover the blue endpoint
|
||||
* serves PostgreSQL 17 with those rows while the renamed {@code -old1} instance keeps serving 16
|
||||
* on the endpoint green had. Both renamed instances can still be deleted, which needs their
|
||||
* containers to have followed them to their new ARNs. Skipped without Docker.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@Tag("docker")
|
||||
class RdsBlueGreenDeploymentDockerIntegrationTest {
|
||||
|
||||
private static final String USER = "admin";
|
||||
private static final String PASSWORD = "Passw0rd12345";
|
||||
|
||||
@BeforeEach
|
||||
void checkDocker() throws Exception {
|
||||
assumeDocker();
|
||||
Class.forName("org.postgresql.Driver");
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchoverMovesTheBlueEndpointToTheUpgradedGreenDatabase() {
|
||||
String blueId = "bg-docker-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String oldId = blueId + "-old1";
|
||||
try (RdsClient rds = rdsClient("us-east-1", "000000000000")) {
|
||||
DBInstance blue = rds.createDBInstance(request -> request.dbInstanceIdentifier(blueId)
|
||||
.engine("postgres").engineVersion("16.3").dbInstanceClass("db.t3.micro")
|
||||
.allocatedStorage(20).masterUsername(USER).masterUserPassword(PASSWORD)
|
||||
.dbName("appdb").backupRetentionPeriod(1)).dbInstance();
|
||||
int bluePort = blue.endpoint().port();
|
||||
try {
|
||||
execute(bluePort, "CREATE TABLE notes (id int PRIMARY KEY, body text)",
|
||||
"INSERT INTO notes VALUES (1, 'kept')");
|
||||
|
||||
BlueGreenDeployment created = rds.createBlueGreenDeployment(request -> request
|
||||
.blueGreenDeploymentName(blueId).source(blue.dbInstanceArn())
|
||||
.targetEngineVersion("17.4")).blueGreenDeployment();
|
||||
assertEquals("AVAILABLE", created.status());
|
||||
String greenId = created.target().substring(created.target().lastIndexOf(':') + 1);
|
||||
int greenPort = rds.describeDBInstances(request -> request.dbInstanceIdentifier(greenId))
|
||||
.dbInstances().getFirst().endpoint().port();
|
||||
assertTrue(query(greenPort, "SHOW server_version").startsWith("17."));
|
||||
assertEquals("kept", query(greenPort, "SELECT body FROM notes WHERE id = 1"));
|
||||
|
||||
BlueGreenDeployment switched = rds.switchoverBlueGreenDeployment(request -> request
|
||||
.blueGreenDeploymentIdentifier(created.blueGreenDeploymentIdentifier()))
|
||||
.blueGreenDeployment();
|
||||
assertEquals("SWITCHOVER_COMPLETED", switched.status());
|
||||
assertEquals(blue.dbInstanceArn(), switched.target());
|
||||
|
||||
DBInstance production = rds.describeDBInstances(request -> request.dbInstanceIdentifier(blueId))
|
||||
.dbInstances().getFirst();
|
||||
assertEquals(bluePort, production.endpoint().port());
|
||||
assertEquals("17.4", production.engineVersion());
|
||||
assertTrue(query(bluePort, "SHOW server_version").startsWith("17."));
|
||||
assertEquals("kept", query(bluePort, "SELECT body FROM notes WHERE id = 1"));
|
||||
assertTrue(query(greenPort, "SHOW server_version").startsWith("16."));
|
||||
|
||||
rds.deleteBlueGreenDeployment(request -> request
|
||||
.blueGreenDeploymentIdentifier(created.blueGreenDeploymentIdentifier()));
|
||||
rds.deleteDBInstance(request -> request.dbInstanceIdentifier(oldId).skipFinalSnapshot(true));
|
||||
assertThrows(DbInstanceNotFoundException.class,
|
||||
() -> rds.describeDBInstances(request -> request.dbInstanceIdentifier(oldId)));
|
||||
} finally {
|
||||
for (String id : new String[] {blueId, oldId}) {
|
||||
try {
|
||||
rds.deleteDBInstance(request -> request.dbInstanceIdentifier(id).skipFinalSnapshot(true));
|
||||
} catch (DbInstanceNotFoundException alreadyGone) {
|
||||
// deleted by the test body
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void execute(int port, String... statements) {
|
||||
whenConnected(port, connection -> {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
for (String sql : statements) {
|
||||
statement.execute(sql);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static String query(int port, String sql) {
|
||||
return whenConnected(port, connection -> {
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery(sql)) {
|
||||
rows.next();
|
||||
return rows.getString(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private interface SqlWork<T> {
|
||||
T run(Connection connection) throws SQLException;
|
||||
}
|
||||
|
||||
/** Runs {@code work} once the server behind the endpoint accepts connections. */
|
||||
private static <T> T whenConnected(int port, SqlWork<T> work) {
|
||||
AtomicReference<T> result = new AtomicReference<>();
|
||||
await().atMost(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(1))
|
||||
.ignoreExceptionsInstanceOf(SQLException.class)
|
||||
.until(() -> {
|
||||
try (Connection connection = DriverManager.getConnection(
|
||||
"jdbc:postgresql://127.0.0.1:" + port + "/appdb?connectTimeout=5&socketTimeout=10",
|
||||
USER, PASSWORD)) {
|
||||
result.set(work.run(connection));
|
||||
return true;
|
||||
}
|
||||
});
|
||||
return result.get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
package io.floci.aws.services.rds;
|
||||
|
||||
import io.floci.aws.testing.RdsMockProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
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.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* CreateBlueGreenDeployment, DescribeBlueGreenDeployments, SwitchoverBlueGreenDeployment and
|
||||
* DeleteBlueGreenDeployment over the Query protocol: the green instance is a linked copy of the
|
||||
* blue one with the target settings, switchover hands green the blue identifier, ARN, endpoint
|
||||
* and tags while blue becomes {@code -old1}, and each operation answers the API reference's
|
||||
* errors for the states that refuse it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(RdsMockProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class RdsBlueGreenDeploymentIntegrationTest {
|
||||
|
||||
private static final String BLUE = "bg-test-blue";
|
||||
private static final String NAME = "bg-test-upgrade";
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260615/us-east-1/rds/aws4_request, "
|
||||
+ "SignedHeaders=content-type;host, Signature=test";
|
||||
|
||||
private static String deploymentId;
|
||||
private static String blueArn;
|
||||
private static String greenId;
|
||||
private static int bluePort;
|
||||
|
||||
/**
|
||||
* Runs last. The test profile's application is shared with the other RDS mock tests, so every
|
||||
* instance this class created is deleted to hand its endpoint port back to the pool. It is an
|
||||
* ordered test rather than an AfterAll because RestAssured's port is reset before AfterAll.
|
||||
*/
|
||||
@Test
|
||||
@Order(Integer.MAX_VALUE)
|
||||
void deleteCreatedResources() {
|
||||
query("DescribeDBInstances").when().post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getList("**.findAll { it.name() == 'DBInstanceIdentifier' }", String.class).stream()
|
||||
.filter(id -> id.startsWith("bg-test-"))
|
||||
.forEach(id -> query("DeleteDBInstance")
|
||||
.formParam("DBInstanceIdentifier", id)
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/"));
|
||||
query("DeleteDBCluster")
|
||||
.formParam("DBClusterIdentifier", "bg-test-cluster")
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
private static RequestSpecification query(String action) {
|
||||
return given().header("Authorization", AUTH)
|
||||
.contentType(URLENC)
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2014-10-31");
|
||||
}
|
||||
|
||||
private static String find(XmlPath xml, String element) {
|
||||
return xml.getString("**.find { it.name() == '" + element + "' }");
|
||||
}
|
||||
|
||||
private static XmlPath createInstance(String id, String engine, String version, String retention) {
|
||||
return query("CreateDBInstance")
|
||||
.formParam("DBInstanceIdentifier", id)
|
||||
.formParam("Engine", engine)
|
||||
.formParam("EngineVersion", version)
|
||||
.formParam("MasterUsername", "admin")
|
||||
.formParam("MasterUserPassword", "password123")
|
||||
.formParam("DBInstanceClass", "db.t3.micro")
|
||||
.formParam("AllocatedStorage", "20")
|
||||
.formParam("BackupRetentionPeriod", retention)
|
||||
.formParam("Tags.Tag.1.Key", "env")
|
||||
.formParam("Tags.Tag.1.Value", "prod")
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
private static XmlPath describeInstance(String id) {
|
||||
return query("DescribeDBInstances")
|
||||
.formParam("DBInstanceIdentifier", id)
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
private static XmlPath createDeployment(String name, String sourceArn) {
|
||||
return query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", name)
|
||||
.formParam("Source", sourceArn)
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createStagesAnUpgradedGreenCopyLinkedToBlue() {
|
||||
XmlPath blue = createInstance(BLUE, "postgres", "16.3", "1");
|
||||
blueArn = find(blue, "DBInstanceArn");
|
||||
bluePort = Integer.parseInt(find(blue, "Port"));
|
||||
|
||||
XmlPath created = query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", NAME)
|
||||
.formParam("Source", blueArn)
|
||||
.formParam("TargetEngineVersion", "17.4")
|
||||
.formParam("TargetDBInstanceClass", "db.t3.medium")
|
||||
.formParam("Tags.Tag.1.Key", "change")
|
||||
.formParam("Tags.Tag.1.Value", "pg17")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<CreateBlueGreenDeploymentResult>"))
|
||||
.body(containsString("<BlueGreenDeploymentName>" + NAME + "</BlueGreenDeploymentName>"))
|
||||
.body(containsString("<Source>" + blueArn + "</Source>"))
|
||||
.body(containsString("<Name>CREATING_READ_REPLICA_OF_SOURCE</Name>"))
|
||||
.body(containsString("<Name>DB_ENGINE_VERSION_UPGRADE</Name>"))
|
||||
.body(containsString("<Status>AVAILABLE</Status>"))
|
||||
.body(containsString("<Key>change</Key>"))
|
||||
.extract().xmlPath();
|
||||
|
||||
deploymentId = find(created, "BlueGreenDeploymentIdentifier");
|
||||
assertThat(deploymentId, matchesPattern("bgd-[a-z0-9]{16}"));
|
||||
String target = find(created, "Target");
|
||||
assertThat(target, matchesPattern(".*:db:" + BLUE + "-green-[a-z0-9]{6}"));
|
||||
assertThat(find(created, "SourceMember"), equalTo(blueArn));
|
||||
assertThat(find(created, "TargetMember"), equalTo(target));
|
||||
greenId = target.substring(target.lastIndexOf(':') + 1);
|
||||
|
||||
XmlPath green = describeInstance(greenId);
|
||||
assertThat(find(green, "EngineVersion"), equalTo("17.4"));
|
||||
assertThat(find(green, "DBInstanceClass"), equalTo("db.t3.medium"));
|
||||
assertThat(find(green, "ReadReplicaSourceDBInstanceIdentifier"), equalTo(BLUE));
|
||||
assertThat(find(green, "DBInstanceStatus"), equalTo("available"));
|
||||
assertThat(find(green, "Value"), equalTo("prod"));
|
||||
assertThat(find(describeInstance(BLUE), "ReadReplicaDBInstanceIdentifier"), equalTo(greenId));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void createRefusesWhatAwsRefuses() {
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", NAME)
|
||||
.formParam("Source", blueArn)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>BlueGreenDeploymentAlreadyExistsFault</Code>"));
|
||||
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-second")
|
||||
.formParam("Source", blueArn)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidDBInstanceState</Code>"))
|
||||
.body(containsString(deploymentId));
|
||||
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-missing")
|
||||
.formParam("Source", blueArn.replace(BLUE, "bg-test-nowhere"))
|
||||
.when().post("/").then().statusCode(404)
|
||||
.body(containsString("<Code>DBInstanceNotFound</Code>"));
|
||||
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg--bad")
|
||||
.formParam("Source", blueArn)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidParameterValue</Code>"));
|
||||
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-nosource")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidParameterValue</Code>"));
|
||||
|
||||
String older = find(createInstance("bg-test-downgrade", "postgres", "16.3", "1"), "DBInstanceArn");
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-downgrade")
|
||||
.formParam("Source", older)
|
||||
.formParam("TargetEngineVersion", "15.12")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidParameterCombination</Code>"));
|
||||
|
||||
String noBackups = find(createInstance("bg-test-nobackups", "postgres", "16.3", "0"), "DBInstanceArn");
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-nobackups")
|
||||
.formParam("Source", noBackups)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidDBInstanceState</Code>"))
|
||||
.body(containsString("Automated backups"));
|
||||
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-greensource")
|
||||
.formParam("Source", blueArn.replace(BLUE, greenId))
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidDBInstanceState</Code>"))
|
||||
.body(containsString(deploymentId));
|
||||
|
||||
query("CreateDBInstanceReadReplica")
|
||||
.formParam("DBInstanceIdentifier", "bg-test-replica")
|
||||
.formParam("SourceDBInstanceIdentifier", "bg-test-downgrade")
|
||||
.when().post("/").then().statusCode(200);
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-replica")
|
||||
.formParam("Source", blueArn.replace(BLUE, "bg-test-replica"))
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>SourceDatabaseNotSupportedFault</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void describeFindsTheDeploymentByIdentifierAndEachFilter() {
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("BlueGreenDeploymentIdentifier", deploymentId)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<DescribeBlueGreenDeploymentsResult>"))
|
||||
.body(containsString("<BlueGreenDeployments><member>"))
|
||||
.body(containsString("<BlueGreenDeploymentIdentifier>" + deploymentId
|
||||
+ "</BlueGreenDeploymentIdentifier>"));
|
||||
|
||||
for (String[] filter : new String[][] {
|
||||
{"blue-green-deployment-identifier", deploymentId},
|
||||
{"blue-green-deployment-name", NAME},
|
||||
{"source", blueArn},
|
||||
{"target", blueArn.replace(BLUE, greenId)}}) {
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("Filters.Filter.1.Name", filter[0])
|
||||
.formParam("Filters.Filter.1.Values.Value.1", filter[1])
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<BlueGreenDeploymentIdentifier>" + deploymentId
|
||||
+ "</BlueGreenDeploymentIdentifier>"));
|
||||
}
|
||||
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("Filters.Filter.1.Name", "blue-green-deployment-name")
|
||||
.formParam("Filters.Filter.1.Values.Value.1", "bg-test-other")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(not(containsString(deploymentId)));
|
||||
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("Filters.Filter.1.Name", "engine")
|
||||
.formParam("Filters.Filter.1.Values.Value.1", "postgres")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidParameterValue</Code>"));
|
||||
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("MaxRecords", "10")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidParameterValue</Code>"));
|
||||
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("BlueGreenDeploymentIdentifier", "bgd-doesnotexist0000")
|
||||
.when().post("/").then().statusCode(404)
|
||||
.body(containsString("<Code>BlueGreenDeploymentNotFoundFault</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void theDeploymentIsTaggableByItsArn() {
|
||||
String arn = blueArn.replace(":db:" + BLUE, ":deployment:" + deploymentId);
|
||||
query("AddTagsToResource")
|
||||
.formParam("ResourceName", arn)
|
||||
.formParam("Tags.Tag.1.Key", "owner")
|
||||
.formParam("Tags.Tag.1.Value", "dba")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
query("ListTagsForResource")
|
||||
.formParam("ResourceName", arn)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Key>change</Key>"))
|
||||
.body(containsString("<Key>owner</Key>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void switchoverHandsGreenTheBlueNameArnEndpointAndTags() {
|
||||
query("SwitchoverBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", deploymentId)
|
||||
.formParam("SwitchoverTimeout", "10")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidParameterValue</Code>"));
|
||||
|
||||
int greenPort = Integer.parseInt(find(describeInstance(greenId), "Port"));
|
||||
|
||||
query("SwitchoverBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", deploymentId)
|
||||
.formParam("SwitchoverTimeout", "300")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<SwitchoverBlueGreenDeploymentResult>"))
|
||||
.body(containsString("<Status>SWITCHOVER_COMPLETED</Status>"))
|
||||
.body(containsString("<Source>" + blueArn + "-old1</Source>"))
|
||||
.body(containsString("<Target>" + blueArn + "</Target>"));
|
||||
|
||||
XmlPath production = describeInstance(BLUE);
|
||||
assertThat(find(production, "EngineVersion"), equalTo("17.4"));
|
||||
assertThat(find(production, "DBInstanceArn"), equalTo(blueArn));
|
||||
assertThat(Integer.parseInt(find(production, "Port")), equalTo(bluePort));
|
||||
assertThat(find(production, "Value"), equalTo("prod"));
|
||||
assertThat(production.prettify(), not(containsString("ReadReplicaSourceDBInstanceIdentifier")));
|
||||
|
||||
XmlPath old = describeInstance(BLUE + "-old1");
|
||||
assertThat(find(old, "EngineVersion"), equalTo("16.3"));
|
||||
assertThat(find(old, "DBInstanceArn"), endsWith(":db:" + BLUE + "-old1"));
|
||||
assertThat(Integer.parseInt(find(old, "Port")), equalTo(greenPort));
|
||||
assertThat(old.prettify(), not(containsString("ReadReplicaDBInstanceIdentifier>")));
|
||||
|
||||
query("DescribeDBInstances")
|
||||
.formParam("DBInstanceIdentifier", greenId)
|
||||
.when().post("/").then().statusCode(404);
|
||||
|
||||
query("SwitchoverBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", deploymentId)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidBlueGreenDeploymentStateFault</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void deleteAfterSwitchoverKeepsBothInstancesAndRefusesDeleteTarget() {
|
||||
query("DeleteBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", deploymentId)
|
||||
.formParam("DeleteTarget", "true")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidBlueGreenDeploymentStateFault</Code>"));
|
||||
|
||||
query("DeleteBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", deploymentId)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<DeleteBlueGreenDeploymentResult>"))
|
||||
.body(containsString("<Status>DELETING</Status>"))
|
||||
.body(containsString("<DeleteTime>"));
|
||||
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("BlueGreenDeploymentIdentifier", deploymentId)
|
||||
.when().post("/").then().statusCode(404);
|
||||
describeInstance(BLUE);
|
||||
describeInstance(BLUE + "-old1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void deleteBeforeSwitchoverDeletesOrReleasesGreen() {
|
||||
String source = find(createInstance("bg-test-mysql", "mysql", "8.0.36", "1"), "DBInstanceArn");
|
||||
|
||||
XmlPath first = createDeployment("bg-test-drop-green", source);
|
||||
String firstGreen = find(first, "Target").substring(find(first, "Target").lastIndexOf(':') + 1);
|
||||
query("DeleteBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", find(first, "BlueGreenDeploymentIdentifier"))
|
||||
.formParam("DeleteTarget", "true")
|
||||
.when().post("/").then().statusCode(200);
|
||||
query("DescribeDBInstances")
|
||||
.formParam("DBInstanceIdentifier", firstGreen)
|
||||
.when().post("/").then().statusCode(404);
|
||||
|
||||
XmlPath second = createDeployment("bg-test-keep-green", source);
|
||||
String secondGreen = find(second, "Target").substring(find(second, "Target").lastIndexOf(':') + 1);
|
||||
query("DeleteBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", find(second, "BlueGreenDeploymentIdentifier"))
|
||||
.when().post("/").then().statusCode(200);
|
||||
assertThat(describeInstance(secondGreen).prettify(),
|
||||
not(containsString("ReadReplicaSourceDBInstanceIdentifier")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void aMissingGreenInstanceMakesTheDeploymentInvalid() {
|
||||
String source = find(createInstance("bg-test-orphan", "postgres", "16.3", "1"), "DBInstanceArn");
|
||||
XmlPath created = createDeployment("bg-test-orphan", source);
|
||||
String id = find(created, "BlueGreenDeploymentIdentifier");
|
||||
String green = find(created, "Target").substring(find(created, "Target").lastIndexOf(':') + 1);
|
||||
|
||||
query("DeleteDBInstance")
|
||||
.formParam("DBInstanceIdentifier", green)
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
query("DescribeBlueGreenDeployments")
|
||||
.formParam("BlueGreenDeploymentIdentifier", id)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Status>INVALID_CONFIGURATION</Status>"))
|
||||
.body(containsString("<Status>MISSING_TARGET</Status>"));
|
||||
|
||||
query("SwitchoverBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", id)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidBlueGreenDeploymentStateFault</Code>"));
|
||||
|
||||
query("DeleteBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", id)
|
||||
.formParam("DeleteTarget", "true")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void clusterSourcesAreNotSupported() {
|
||||
String cluster = query("CreateDBCluster")
|
||||
.formParam("DBClusterIdentifier", "bg-test-cluster")
|
||||
.formParam("Engine", "aurora-postgresql")
|
||||
.formParam("MasterUsername", "admin")
|
||||
.formParam("MasterUserPassword", "password123")
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getString("**.find { it.name() == 'DBClusterArn' }");
|
||||
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-cluster")
|
||||
.formParam("Source", cluster)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>SourceClusterNotSupportedFault</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void switchoverRefusesAPromotedGreenWithoutADescribeFirst() {
|
||||
String source = find(createInstance("bg-test-promoted", "postgres", "16.3", "1"), "DBInstanceArn");
|
||||
|
||||
query("CreateBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentName", "bg-test-promoted")
|
||||
.formParam("Source", source)
|
||||
.formParam("TargetAllocatedStorage", "0")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidParameterValue</Code>"));
|
||||
|
||||
XmlPath created = createDeployment("bg-test-promoted", source);
|
||||
String id = find(created, "BlueGreenDeploymentIdentifier");
|
||||
String green = find(created, "Target").substring(find(created, "Target").lastIndexOf(':') + 1);
|
||||
|
||||
query("PromoteReadReplica")
|
||||
.formParam("DBInstanceIdentifier", green)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
query("SwitchoverBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", id)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidBlueGreenDeploymentStateFault</Code>"));
|
||||
query("DescribeDBInstances")
|
||||
.formParam("DBInstanceIdentifier", "bg-test-promoted")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<DBInstanceArn>" + source + "</DBInstanceArn>"));
|
||||
|
||||
query("DeleteBlueGreenDeployment")
|
||||
.formParam("BlueGreenDeploymentIdentifier", id)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user