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:
David authored and GitHub committed 2026-11-12 11:10:15 -04:00
1 parent acdbde836a
commit 654473f754
8 files changed
+1508 -1

No files matched your search

@@ -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; }
}
}