diff --git a/compatibility-tests/sdk-test-awscli/test/rds.bats b/compatibility-tests/sdk-test-awscli/test/rds.bats index 4adf96bd6e..180fd8596a 100644 --- a/compatibility-tests/sdk-test-awscli/test/rds.bats +++ b/compatibility-tests/sdk-test-awscli/test/rds.bats @@ -504,3 +504,45 @@ teardown() { assert_failure assert_output --partial 'DBProxyEndpointNotFoundFault' } + +@test "rds: a deleted instance keeps its automated backup, which replicates and is deleted" { + aws_west() { aws --endpoint-url "$FLOCI_ENDPOINT" --region us-west-2 --output json "$@" 2>&1; } + run aws_cmd rds create-db-instance --db-instance-identifier "$DB_ID" --engine postgres \ + --db-instance-class db.t3.micro --allocated-storage 10 --backup-retention-period 2 + assert_success + dbi="$(json_get "$output" '.DBInstance.DbiResourceId')" + source_arn="$(json_get "$output" '.DBInstance.DBInstanceArn')" + + run aws_cmd rds describe-db-instance-automated-backups --dbi-resource-id "$dbi" + assert_success + [ "$(json_get "$output" '.DBInstanceAutomatedBackups[0].Status')" = "active" ] + + run aws_west rds start-db-instance-automated-backups-replication --source-db-instance-arn "$source_arn" + assert_success + [ "$(json_get "$output" '.DBInstanceAutomatedBackup.Status')" = "replicating" ] + replica_arn="$(json_get "$output" '.DBInstanceAutomatedBackup.DBInstanceAutomatedBackupsArn')" + run aws_cmd rds describe-db-instances --db-instance-identifier "$DB_ID" \ + --query 'DBInstances[0].DBInstanceAutomatedBackupsReplications[0].DBInstanceAutomatedBackupsArn' --output text + assert_success + assert_output "$replica_arn" + run aws_west rds stop-db-instance-automated-backups-replication --source-db-instance-arn "$source_arn" + assert_success + [ "$(json_get "$output" '.DBInstanceAutomatedBackup.Status')" = "retained" ] + run aws_west rds delete-db-instance-automated-backup --db-instance-automated-backups-arn "$replica_arn" + assert_success + + run aws_cmd rds delete-db-instance --db-instance-identifier "$DB_ID" --skip-final-snapshot \ + --no-delete-automated-backups + assert_success + run aws_cmd rds describe-db-instance-automated-backups --dbi-resource-id "$dbi" \ + --query 'DBInstanceAutomatedBackups[0].Status' --output text + assert_success + assert_output 'retained' + + run aws_cmd rds delete-db-instance-automated-backup --dbi-resource-id "$dbi" + assert_success + [ "$(json_get "$output" '.DBInstanceAutomatedBackup.Status')" = "deleting" ] + run aws_cmd rds describe-db-instance-automated-backups --dbi-resource-id "$dbi" + assert_failure + assert_output --partial 'DBInstanceAutomatedBackupNotFound' +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java index 2823d3913e..f16bf6b897 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java @@ -27,6 +27,8 @@ import software.amazon.awssdk.services.rds.model.DBClusterRole; import software.amazon.awssdk.services.rds.model.DBClusterSnapshot; import software.amazon.awssdk.services.rds.model.DBEngineVersion; import software.amazon.awssdk.services.rds.model.DBInstance; +import software.amazon.awssdk.services.rds.model.DBInstanceAutomatedBackup; +import software.amazon.awssdk.services.rds.model.DBInstanceAutomatedBackupsReplication; import software.amazon.awssdk.services.rds.model.DBInstanceRole; import software.amazon.awssdk.services.rds.model.DBProxyEndpointTargetRole; import software.amazon.awssdk.services.rds.model.DBProxyTarget; @@ -36,6 +38,7 @@ import software.amazon.awssdk.services.rds.model.DbClusterEndpointNotFoundExcept import software.amazon.awssdk.services.rds.model.DbClusterRoleAlreadyExistsException; import software.amazon.awssdk.services.rds.model.DbClusterRoleNotFoundException; import software.amazon.awssdk.services.rds.model.DbClusterSnapshotNotFoundException; +import software.amazon.awssdk.services.rds.model.DbInstanceAutomatedBackupNotFoundException; import software.amazon.awssdk.services.rds.model.DbInstanceRoleAlreadyExistsException; import software.amazon.awssdk.services.rds.model.DbInstanceRoleNotFoundException; import software.amazon.awssdk.services.rds.model.DbLogFileNotFoundException; @@ -53,6 +56,7 @@ import software.amazon.awssdk.services.rds.model.DescribeOptionGroupsResponse; import software.amazon.awssdk.services.rds.model.DescribeOrderableDbInstanceOptionsResponse; import software.amazon.awssdk.services.rds.model.DownloadDbLogFilePortionResponse; import software.amazon.awssdk.services.rds.model.EngineDefaults; +import software.amazon.awssdk.services.rds.model.InvalidDbInstanceAutomatedBackupStateException; import software.amazon.awssdk.services.rds.model.InvalidDbInstanceStateException; import software.amazon.awssdk.services.rds.model.InvalidDbProxyEndpointStateException; import software.amazon.awssdk.services.rds.model.InvalidOptionGroupStateException; @@ -921,6 +925,56 @@ class RdsControlPlaneTest { .isEqualTo("rds-ca-rsa2048-g1"); } + @Test + @DisplayName("Automated backups: active, retained after a delete, restored from, replicated and deleted") + void sdkRoundTripsAutomatedBackups() { + String instanceName = TestFixtures.uniqueName("rds-ab"); + String restoredName = TestFixtures.uniqueName("rds-ab-restored"); + Region destination = Region.US_WEST_2; + try (RdsClient west = rdsClient(destination)) { + DBInstance created = createDbInstance(rds, instanceName, "ab-secret").dbInstance(); + String dbi = created.dbiResourceId(); + DBInstanceAutomatedBackup active = rds.describeDBInstanceAutomatedBackups(b -> b.dbiResourceId(dbi)) + .dbInstanceAutomatedBackups().get(0); + assertThat(active.status()).isEqualTo("active"); + assertThat(active.dbInstanceAutomatedBackupsArn()).endsWith(":auto-backup:ab-" + dbi.substring(3)); + assertThat(active.restoreWindow().earliestTime()).isBeforeOrEqualTo(active.restoreWindow().latestTime()); + assertThatThrownBy(() -> rds.deleteDBInstanceAutomatedBackup(b -> b.dbiResourceId(dbi))) + .isInstanceOf(InvalidDbInstanceAutomatedBackupStateException.class); + + DBInstanceAutomatedBackup replica = west.startDBInstanceAutomatedBackupsReplication(b -> b + .sourceDBInstanceArn(created.dbInstanceArn()).backupRetentionPeriod(5)) + .dbInstanceAutomatedBackup(); + assertThat(replica.status()).isEqualTo("replicating"); + assertThat(replica.backupRetentionPeriod()).isEqualTo(5); + assertThat(rds.describeDBInstances(b -> b.dbInstanceIdentifier(instanceName)).dbInstances().get(0) + .dbInstanceAutomatedBackupsReplications()) + .extracting(DBInstanceAutomatedBackupsReplication::dbInstanceAutomatedBackupsArn) + .containsExactly(replica.dbInstanceAutomatedBackupsArn()); + assertThat(west.stopDBInstanceAutomatedBackupsReplication(b -> b + .sourceDBInstanceArn(created.dbInstanceArn())).dbInstanceAutomatedBackup().status()) + .isEqualTo("retained"); + west.deleteDBInstanceAutomatedBackup(b -> b + .dbInstanceAutomatedBackupsArn(replica.dbInstanceAutomatedBackupsArn())); + + rds.deleteDBInstance(b -> b.dbInstanceIdentifier(instanceName).skipFinalSnapshot(true) + .deleteAutomatedBackups(false)); + assertThat(rds.describeDBInstanceAutomatedBackups(b -> b.dbiResourceId(dbi)) + .dbInstanceAutomatedBackups().get(0).status()).isEqualTo("retained"); + assertThat(rds.restoreDBInstanceToPointInTime(b -> b.sourceDbiResourceId(dbi) + .targetDBInstanceIdentifier(restoredName).useLatestRestorableTime(true)) + .dbInstance().dbInstanceIdentifier()).isEqualTo(restoredName); + + assertThat(rds.deleteDBInstanceAutomatedBackup(b -> b.dbiResourceId(dbi)) + .dbInstanceAutomatedBackup().status()).isEqualTo("deleting"); + assertThatThrownBy(() -> rds.describeDBInstanceAutomatedBackups(b -> b.dbiResourceId(dbi))) + .isInstanceOf(DbInstanceAutomatedBackupNotFoundException.class); + } finally { + deleteDbInstance(rds, restoredName); + deleteDbInstance(rds, instanceName); + } + } + @Test @DisplayName("IAM role associations: add, describe and remove for a cluster and an instance") void sdkRoundTripsIamRoleAssociations() { diff --git a/docs/services/index.md b/docs/services/index.md index f5d52dddfe..63656c5143 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -64,7 +64,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 | 32 | | [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 | 111 | +| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 117 | | [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 | diff --git a/docs/services/rds.md b/docs/services/rds.md index 9151420fcd..6a9ce8aa5f 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -124,6 +124,10 @@ RDS endpoints return the us-east-1 hosted zone ID `Z2R2ITUGPM61AM` in all region | `ModifyDBSnapshot` | Change the engine version or option group of an available manual DB snapshot | | `RestoreDBInstanceFromDBSnapshot` | Create a new DB instance from a snapshot | | `RestoreDBInstanceToPointInTime` | Create a new DB instance from a source instance at a time in its restorable window; see [Point in time restore](#point-in-time-restore) | +| `DescribeDBInstanceAutomatedBackups` | List the Region's instance automated backups: `active` for live instances, `retained` and `replicating` ones; see [Automated backups](#automated-backups) | +| `DeleteDBInstanceAutomatedBackup` | Delete a retained instance automated backup by `DbiResourceId` or `DBInstanceAutomatedBackupsArn` | +| `StartDBInstanceAutomatedBackupsReplication` | Replicate a source instance's automated backups from its Region to this one (metadata only) | +| `StopDBInstanceAutomatedBackupsReplication` | Stop replicating to this Region; the replica is kept as `retained` | | `DescribeDBSnapshots` | List DB instance snapshots | | `DescribeDBSnapshotAttributes` | Return a snapshot's `restore` attribute (accounts authorized to copy/restore it) | | `ModifyDBSnapshotAttribute` | Add or remove accounts authorized to copy/restore a snapshot | @@ -146,6 +150,8 @@ RDS endpoints return the us-east-1 hosted zone ID `Z2R2ITUGPM61AM` in all region | `CopyDBClusterSnapshot` | Copy an available cluster snapshot (by identifier or same-region ARN) to a new manual one with its data; `CopyTags` and `Tags`; the copy reports `SourceDBClusterSnapshotArn` | | `RestoreDBClusterFromSnapshot` | Create a cluster from a cluster snapshot's settings and data; `Engine` must match the snapshot's | | `RestoreDBClusterToPointInTime` | Create a cluster from a source cluster at a time in its restorable window; see [Point in time restore](#point-in-time-restore) | +| `DescribeDBClusterAutomatedBackups` | List the Region's retained cluster automated backups; see [Automated backups](#automated-backups) | +| `DeleteDBClusterAutomatedBackup` | Delete a retained cluster automated backup by `DbClusterResourceId` | | `DescribeDBClusterSnapshotAttributes` | Return the `restore` attribute of a cluster snapshot | | `ModifyDBClusterSnapshotAttribute` | Add or remove `restore` values (account ids or `all`) on a cluster snapshot | | `StartExportTask` | Start an export task for a DB snapshot or DB cluster snapshot; see [Exporting snapshots to Amazon S3](#exporting-snapshots-to-amazon-s3) | @@ -807,11 +813,10 @@ retention period up to `LatestRestorableTime` on `DescribeDBInstances`; an insta window runs from its creation (`EarliestRestorableTime`) to `LatestRestorableTime` on `DescribeDBClusters`. -An instance source is named by `SourceDBInstanceIdentifier` or `SourceDbiResourceId`, a cluster -source by `SourceDBClusterIdentifier` (identifier or ARN) or `SourceDbClusterResourceId`. Restoring -from retained automated backups (`SourceDBInstanceAutomatedBackupsArn`, used for a deleted instance) -is not supported, since Floci keeps no automated backups, and answers -`DBInstanceAutomatedBackupNotFound`. A restored instance takes the source's engine, version, +An instance source is named by `SourceDBInstanceIdentifier`, `SourceDbiResourceId` or +`SourceDBInstanceAutomatedBackupsArn`, a cluster source by `SourceDBClusterIdentifier` (identifier +or ARN) or `SourceDbClusterResourceId`. A resource ID or backups ARN can also name a deleted source +through the automated backup it kept; see [Automated backups](#automated-backups). A restored instance takes the source's engine, version, credentials, database name, storage and encryption, and its instance class unless the request names one; everything else is the request's or the default a new instance gets. A restored cluster takes the source's engine, version, credentials, database name and encryption, and has no instances until @@ -823,6 +828,33 @@ replicas use, so the restored data is the source's latest state whatever time in asked for; this is also why `LatestRestorableTime` is always the current time. As with `CreateDBSnapshot`, only PostgreSQL sources are accepted. +## Automated backups + +A standalone instance with `BackupRetentionPeriod` above 0 has an `active` automated backup, which +`DescribeDBInstanceAutomatedBackups` builds from the instance: its `RestoreWindow` is the instance's +restorable window, and its ARN is `auto-backup:ab-` followed by the `DbiResourceId` after `db-`. +Aurora instances are not listed, since their backups belong to the cluster. + +`DeleteDBInstance` and `DeleteDBCluster` take `DeleteAutomatedBackups`. It defaults to `true`, which +removes the backups with the resource, as on AWS. With `false`, a standalone instance with backups on +leaves a `retained` backup, and a cluster leaves one that `DescribeDBClusterAutomatedBackups` lists. +Its restore window ends at the deletion. Outside mock mode a PostgreSQL source's data is saved with +the backup (a `pg_dumpall`, as for snapshots), so a point in time restore from it brings the data +back; if that copy fails, the delete fails and nothing is deleted. A restore from a backup that holds +no data, such as one kept in mock mode, fails outside mock mode. Floci does not expire retained +backups: they stay until `DeleteDBInstanceAutomatedBackup` or `DeleteDBClusterAutomatedBackup` +removes them, and a backup of a live resource cannot be deleted +(`InvalidDBInstanceAutomatedBackupState`, `InvalidDBClusterAutomatedBackupStateFault`). + +`StartDBInstanceAutomatedBackupsReplication` is called in the destination Region with the source's +ARN. The source must be a live standalone instance with backups on, in another Region. The replica +is listed in the destination Region as `replicating`, with the `BackupRetentionPeriod` asked for (7 +days by default), and the source lists it under `DBInstanceAutomatedBackupsReplications` in +`DescribeDBInstances`. Replication is metadata only: no data is copied between Regions, so a restore +from a replica copies the live source. `StopDBInstanceAutomatedBackupsReplication`, or deleting the +source, keeps the replica as `retained`; a stop with nothing replicating to the Region answers +`InvalidDBInstanceState`. + ## Exporting snapshots to Amazon S3 `StartExportTask`, `DescribeExportTasks` and `CancelExportTask` manage RDS snapshot export tasks. diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java index 2aa231d2c7..ecb60f3a5b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java @@ -14,11 +14,13 @@ import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler; import io.github.hectorvent.floci.services.rds.export.RdsExportTaskService; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; import io.github.hectorvent.floci.services.rds.model.DbCluster; +import io.github.hectorvent.floci.services.rds.model.DbClusterAutomatedBackup; import io.github.hectorvent.floci.services.rds.model.DbClusterEndpoint; import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot; import io.github.hectorvent.floci.services.rds.model.DbEndpoint; import io.github.hectorvent.floci.services.rds.model.DbInstance; +import io.github.hectorvent.floci.services.rds.model.DbInstanceAutomatedBackup; import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings; import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus; @@ -173,6 +175,12 @@ public class RdsQueryHandler { case "ModifyDBSnapshot" -> handleModifyDbSnapshot(params, region); case "RestoreDBInstanceFromDBSnapshot" -> handleRestoreDbInstanceFromDbSnapshot(params, region); case "RestoreDBInstanceToPointInTime" -> handleRestoreDbInstanceToPointInTime(params, region); + case "DescribeDBInstanceAutomatedBackups" -> handleDescribeDbInstanceAutomatedBackups(params, region); + case "DeleteDBInstanceAutomatedBackup" -> handleDeleteDbInstanceAutomatedBackup(params, region); + case "StartDBInstanceAutomatedBackupsReplication" -> + handleStartDbInstanceAutomatedBackupsReplication(params, region); + case "StopDBInstanceAutomatedBackupsReplication" -> + handleStopDbInstanceAutomatedBackupsReplication(params, region); case "DescribeDBSnapshots" -> handleDescribeDbSnapshots(params, region); case "DescribeDBSnapshotAttributes" -> handleDescribeDbSnapshotAttributes(params, region); case "ModifyDBSnapshotAttribute" -> handleModifyDbSnapshotAttribute(params, region); @@ -195,6 +203,8 @@ public class RdsQueryHandler { case "CopyDBClusterSnapshot" -> handleCopyDbClusterSnapshot(params, region); case "RestoreDBClusterFromSnapshot" -> handleRestoreDbClusterFromSnapshot(params, region); case "RestoreDBClusterToPointInTime" -> handleRestoreDbClusterToPointInTime(params, region); + case "DescribeDBClusterAutomatedBackups" -> handleDescribeDbClusterAutomatedBackups(params, region); + case "DeleteDBClusterAutomatedBackup" -> handleDeleteDbClusterAutomatedBackup(params, region); case "DescribeDBClusterSnapshotAttributes" -> handleDescribeDbClusterSnapshotAttributes(params, region); case "ModifyDBClusterSnapshotAttribute" -> handleModifyDbClusterSnapshotAttribute(params, region); case "StartExportTask" -> handleStartExportTask(params, region); @@ -775,7 +785,7 @@ public class RdsQueryHandler { } try { DbInstance instance = service.getDbInstance(id, region); - service.deleteDbInstance(id, region); + service.deleteDbInstance(id, region, !Boolean.FALSE.equals(parseOptionalBoolean(params, "DeleteAutomatedBackups"))); String result = dbInstanceXml(instance); return Response.ok(AwsQueryResponse.envelope("DeleteDBInstance", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -1442,7 +1452,7 @@ public class RdsQueryHandler { } try { DbCluster cluster = service.getDbCluster(id, region); - service.deleteDbCluster(id, region); + service.deleteDbCluster(id, region, !Boolean.FALSE.equals(parseOptionalBoolean(params, "DeleteAutomatedBackups"))); String result = dbClusterXml(cluster); return Response.ok(AwsQueryResponse.envelope("DeleteDBCluster", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -2891,6 +2901,171 @@ public class RdsQueryHandler { // ── XML builders ────────────────────────────────────────────────────────── + // ── Automated backups ───────────────────────────────────────────────────── + + private Response handleDescribeDbInstanceAutomatedBackups(MultivaluedMap params, String region) { + RdsService.AutomatedBackupPage page = service.describeDbInstanceAutomatedBackups( + region, params.getFirst("DbiResourceId"), params.getFirst("DBInstanceIdentifier"), + params.getFirst("DBInstanceAutomatedBackupsArn"), + extractRdsFilterValues(params, "status"), + extractRdsFilterValues(params, "db-instance-id"), + extractRdsFilterValues(params, "dbi-resource-id"), + optionalInt(params.getFirst("MaxRecords")), params.getFirst("Marker")); + XmlBuilder xml = new XmlBuilder().start("DBInstanceAutomatedBackups"); + for (DbInstanceAutomatedBackup backup : page.backups()) { + xml.raw(instanceAutomatedBackupXml(backup)); + } + xml.end("DBInstanceAutomatedBackups"); + if (page.marker() != null) { + xml.elem("Marker", page.marker()); + } + return Response.ok(AwsQueryResponse.envelope("DescribeDBInstanceAutomatedBackups", AwsNamespaces.RDS, + xml.build())).build(); + } + + private Response handleDeleteDbInstanceAutomatedBackup(MultivaluedMap params, String region) { + DbInstanceAutomatedBackup backup = service.deleteDbInstanceAutomatedBackup(region, + params.getFirst("DbiResourceId"), params.getFirst("DBInstanceAutomatedBackupsArn")); + return Response.ok(AwsQueryResponse.envelope("DeleteDBInstanceAutomatedBackup", AwsNamespaces.RDS, + instanceAutomatedBackupXml(backup))).build(); + } + + private Response handleStartDbInstanceAutomatedBackupsReplication(MultivaluedMap params, + String region) { + DbInstanceAutomatedBackup backup = service.startDbInstanceAutomatedBackupsReplication(region, + params.getFirst("SourceDBInstanceArn"), parseIntegerParam(params, "BackupRetentionPeriod"), + params.getFirst("KmsKeyId")); + return Response.ok(AwsQueryResponse.envelope("StartDBInstanceAutomatedBackupsReplication", AwsNamespaces.RDS, + instanceAutomatedBackupXml(backup))).build(); + } + + private Response handleStopDbInstanceAutomatedBackupsReplication(MultivaluedMap params, + String region) { + DbInstanceAutomatedBackup backup = service.stopDbInstanceAutomatedBackupsReplication(region, + params.getFirst("SourceDBInstanceArn")); + return Response.ok(AwsQueryResponse.envelope("StopDBInstanceAutomatedBackupsReplication", AwsNamespaces.RDS, + instanceAutomatedBackupXml(backup))).build(); + } + + private Response handleDescribeDbClusterAutomatedBackups(MultivaluedMap params, String region) { + RdsService.AutomatedBackupPage page = service.describeDbClusterAutomatedBackups( + region, params.getFirst("DbClusterResourceId"), params.getFirst("DBClusterIdentifier"), + extractRdsFilterValues(params, "status"), + extractRdsFilterValues(params, "db-cluster-id"), + extractRdsFilterValues(params, "db-cluster-resource-id"), + optionalInt(params.getFirst("MaxRecords")), params.getFirst("Marker")); + XmlBuilder xml = new XmlBuilder().start("DBClusterAutomatedBackups"); + for (DbClusterAutomatedBackup backup : page.backups()) { + xml.raw(clusterAutomatedBackupXml(backup)); + } + xml.end("DBClusterAutomatedBackups"); + if (page.marker() != null) { + xml.elem("Marker", page.marker()); + } + return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterAutomatedBackups", AwsNamespaces.RDS, + xml.build())).build(); + } + + private Response handleDeleteDbClusterAutomatedBackup(MultivaluedMap params, String region) { + DbClusterAutomatedBackup backup = service.deleteDbClusterAutomatedBackup(region, + params.getFirst("DbClusterResourceId")); + return Response.ok(AwsQueryResponse.envelope("DeleteDBClusterAutomatedBackup", AwsNamespaces.RDS, + clusterAutomatedBackupXml(backup))).build(); + } + + private String instanceAutomatedBackupXml(DbInstanceAutomatedBackup backup) { + DbInstance i = backup.getInstance(); + String engine = instanceEngine(i); + XmlBuilder xml = new XmlBuilder().start("DBInstanceAutomatedBackup") + .elem("DBInstanceArn", i.getDbInstanceArn()) + .elem("DbiResourceId", i.getDbiResourceId()) + .elem("Region", backup.getRegion()) + .elem("DBInstanceIdentifier", i.getDbInstanceIdentifier()) + .start("RestoreWindow") + .elem("EarliestTime", backup.getEarliestTime().toString()) + .elem("LatestTime", backup.getLatestTime().toString()) + .end("RestoreWindow") + .elem("AllocatedStorage", i.getAllocatedStorage()) + .elem("Status", backup.getStatus()) + .elem("Port", i.getEndpoint() != null ? i.getEndpoint().port() : i.getProxyPort()) + .elem("AvailabilityZone", i.getAvailabilityZone() != null + ? i.getAvailabilityZone() : config.defaultAvailabilityZone()); + if (i.getVpcId() != null) { + xml.elem("VpcId", i.getVpcId()); + } + if (i.getCreatedAt() != null) { + xml.elem("InstanceCreateTime", i.getCreatedAt().toString()); + } + xml.elem("MasterUsername", i.getMasterUsername()) + .elem("Engine", engine) + .elem("EngineVersion", i.getEngineVersion()) + .elem("LicenseModel", licenseModel(engine)); + if (i.getOptionGroupName() != null) { + xml.elem("OptionGroupName", i.getOptionGroupName()); + } + xml.elem("Encrypted", i.isStorageEncrypted()) + .elem("StorageType", i.getStorageType()); + if (backup.getKmsKeyId() != null) { + xml.elem("KmsKeyId", backup.getKmsKeyId()); + } + xml.elem("IAMDatabaseAuthenticationEnabled", i.isIamDatabaseAuthenticationEnabled()) + .elem("BackupRetentionPeriod", backup.getBackupRetentionPeriod()) + .elem("PreferredBackupWindow", i.getPreferredBackupWindow() != null + ? i.getPreferredBackupWindow() : DbInstanceSettings.DEFAULT_BACKUP_WINDOW) + .elem("DBInstanceAutomatedBackupsArn", backup.getDbInstanceAutomatedBackupsArn()); + // Only the source's own backup lists where it replicates to. + if (DbInstanceAutomatedBackup.ACTIVE.equals(backup.getStatus())) { + xml.raw(automatedBackupReplicationsXml(i)); + } + xml.elem("BackupTarget", "region"); + return xml.end("DBInstanceAutomatedBackup").build(); + } + + private static String automatedBackupReplicationsXml(DbInstance i) { + XmlBuilder xml = new XmlBuilder().start("DBInstanceAutomatedBackupsReplications"); + for (String arn : i.getAutomatedBackupReplicationArns()) { + xml.start("DBInstanceAutomatedBackupsReplication") + .elem("DBInstanceAutomatedBackupsArn", arn) + .end("DBInstanceAutomatedBackupsReplication"); + } + return xml.end("DBInstanceAutomatedBackupsReplications").build(); + } + + private String clusterAutomatedBackupXml(DbClusterAutomatedBackup backup) { + DbCluster c = backup.getCluster(); + String engine = clusterEngine(c); + XmlBuilder xml = new XmlBuilder().start("DBClusterAutomatedBackup") + .elem("Engine", engine); + if (c.getVpcId() != null) { + xml.elem("VpcId", c.getVpcId()); + } + xml.elem("DBClusterAutomatedBackupsArn", backup.getDbClusterAutomatedBackupsArn()) + .elem("DBClusterIdentifier", c.getDbClusterIdentifier()) + .start("RestoreWindow") + .elem("EarliestTime", backup.getEarliestTime().toString()) + .elem("LatestTime", backup.getLatestTime().toString()) + .end("RestoreWindow") + .elem("MasterUsername", c.getMasterUsername()) + .elem("DbClusterResourceId", c.getDbClusterResourceId()) + .elem("Region", backup.getRegion()) + .elem("LicenseModel", licenseModel(engine)) + .elem("Status", backup.getStatus()) + .elem("IAMDatabaseAuthenticationEnabled", c.isIamDatabaseAuthenticationEnabled()); + if (c.getCreatedAt() != null) { + xml.elem("ClusterCreateTime", c.getCreatedAt().toString()); + } + xml.elem("StorageEncrypted", c.isStorageEncrypted()) + .elem("EngineVersion", c.getEngineVersion()) + .elem("DBClusterArn", c.getDbClusterArn()) + .elem("BackupRetentionPeriod", backup.getBackupRetentionPeriod()) + .elem("PreferredBackupWindow", "04:00-06:00") + .elem("EngineMode", c.getEngineMode() != null ? c.getEngineMode() : "provisioned"); + if (c.getEndpoint() != null) { + xml.elem("Port", c.getEndpoint().port()); + } + return xml.end("DBClusterAutomatedBackup").build(); + } + private String dbInstanceXml(DbInstance i) { return new XmlBuilder().start("DBInstance").raw(dbInstanceInnerXml(i)).end("DBInstance").build(); } @@ -3098,6 +3273,7 @@ public class RdsQueryHandler { if (i.hasReadReplicaSource()) { xml.elem("ReadReplicaSourceDBInstanceIdentifier", i.getReadReplicaSourceDbInstanceIdentifier()); } + xml.raw(automatedBackupReplicationsXml(i)); xml.start("ReadReplicaDBInstanceIdentifiers"); for (String replicaId : i.getReadReplicaDbInstanceIdentifiers()) { xml.elem("ReadReplicaDBInstanceIdentifier", replicaId); diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 22e97e9e3d..57edf92c34 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -37,11 +37,13 @@ import io.github.hectorvent.floci.services.rds.container.RdsContainerManager; import io.github.hectorvent.floci.services.rds.export.SnapshotExportSource; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; import io.github.hectorvent.floci.services.rds.model.DbCluster; +import io.github.hectorvent.floci.services.rds.model.DbClusterAutomatedBackup; import io.github.hectorvent.floci.services.rds.model.DbClusterEndpoint; import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot; import io.github.hectorvent.floci.services.rds.model.DbEndpoint; import io.github.hectorvent.floci.services.rds.model.DbInstance; +import io.github.hectorvent.floci.services.rds.model.DbInstanceAutomatedBackup; import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings; import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus; @@ -187,6 +189,10 @@ public class RdsService implements Resettable, ResourceProvider { /** The account's ModifyCertificates override per Region, by CA identifier. */ private final StorageBackend certificateOverrides; private final StorageBackend proxyEndpoints; + /** Retained and replicated instance backups, by Region and the source's DbiResourceId. */ + private final StorageBackend instanceAutomatedBackups; + /** Retained cluster backups, by Region and the cluster's DbClusterResourceId. */ + private final StorageBackend clusterAutomatedBackups; private final RdsContainerManager containerManager; private final RdsProxyManager proxyManager; // CreateDBCluster/CreateDBInstance register the new resource only after the @@ -290,6 +296,10 @@ public class RdsService implements Resettable, ResourceProvider { new TypeReference>() {}); this.certificateOverrides = storageFactory.create("rds", "rds-certificate-overrides.json", new TypeReference>() {}); + this.instanceAutomatedBackups = storageFactory.create("rds", "rds-instance-automated-backups.json", + new TypeReference>() {}); + this.clusterAutomatedBackups = storageFactory.create("rds", "rds-cluster-automated-backups.json", + new TypeReference>() {}); } RdsService(RdsContainerManager containerManager, @@ -430,6 +440,8 @@ public class RdsService implements Resettable, ResourceProvider { this.certificateOverrides = new InMemoryStorage<>(); this.clusterEndpoints = new InMemoryStorage<>(); this.proxyEndpoints = new InMemoryStorage<>(); + this.instanceAutomatedBackups = new InMemoryStorage<>(); + this.clusterAutomatedBackups = new InMemoryStorage<>(); } public void restorePersistedRuntime() { @@ -1336,25 +1348,26 @@ public class RdsService implements Resettable, ResourceProvider { if (targetId == null || targetId.isBlank()) { throw new AwsException("InvalidParameterValue", "TargetDBInstanceIdentifier is required.", 400); } - DbInstance source = resolvePointInTimeSource(request, effectiveRegion); + Instant now = Instant.now(); + PointInTimeSource pointInTimeSource = resolvePointInTimeSource(request, effectiveRegion, now); + DbInstance source = pointInTimeSource.instance(); String sourceId = source.getDbInstanceIdentifier(); if (source.getDbClusterIdentifier() != null && !source.getDbClusterIdentifier().isBlank()) { throw new AwsException("InvalidParameterCombination", "DB instance " + sourceId + " belongs to DB cluster " + source.getDbClusterIdentifier() + ". Use RestoreDBClusterToPointInTime to restore the cluster.", 400); } - if (source.getStatus() != DbInstanceStatus.AVAILABLE) { + if (pointInTimeSource.live() && source.getStatus() != DbInstanceStatus.AVAILABLE) { throw new AwsException("InvalidDBInstanceState", "DB instance " + sourceId + " is not in available state.", 400); } - if (source.getBackupRetentionPeriod() <= 0) { + if (pointInTimeSource.live() && source.getBackupRetentionPeriod() <= 0) { throw new AwsException("PointInTimeRestoreNotEnabled", "Point-in-time restore is not enabled for DB instance " + sourceId + " because its backup retention period is 0.", 400); } - Instant now = Instant.now(); requireRestorableTime(request.restoreTime(), request.useLatestRestorableTime(), - earliestRestorableTime(source, now), now, "RestoreTime"); + pointInTimeSource.earliest(), pointInTimeSource.latest(), "RestoreTime"); if (source.getEngine() != DatabaseEngine.POSTGRES) { // CreateDBSnapshot draws the same line: the copy of the source is pg_dumpall based. throw new AwsException("InvalidDBInstanceState", @@ -1404,11 +1417,16 @@ public class RdsService implements Resettable, ResourceProvider { try { // Without both containers there is nothing to copy from or into, and reporting the // restore as done would hand back an instance without the source's data. - if (source.getContainerId() == null || instance.getContainerId() == null) { + if ((pointInTimeSource.live() && source.getContainerId() == null) + || instance.getContainerId() == null) { throw new IllegalStateException("the source or target database container is not running"); } - String sqlDump = containerManager.createPostgresSnapshot( - source.getContainerId(), source.getMasterUsername()); + if (!pointInTimeSource.live() && pointInTimeSource.savedData() == null) { + throw new IllegalStateException("the automated backup holds no saved data"); + } + String sqlDump = pointInTimeSource.live() + ? containerManager.createPostgresSnapshot(source.getContainerId(), source.getMasterUsername()) + : pointInTimeSource.savedData(); containerManager.restorePostgresSnapshot( instance.getContainerId(), instance.getMasterUsername(), sqlDump); if (renameDatabase) { @@ -1438,10 +1456,19 @@ public class RdsService implements Resettable, ResourceProvider { } /** - * The source of a point in time restore. A live instance can be named by identifier or by its - * DbiResourceId; an automated backups ARN names retained backups, which Floci does not keep. + * What a point in time restore copies: a live instance, or the instance a retained backup + * kept, with the window it can be restored to and, for a retained backup, its saved data. */ - private DbInstance resolvePointInTimeSource(PointInTimeRestoreRequest request, String region) { + private record PointInTimeSource(DbInstance instance, boolean live, Instant earliest, Instant latest, + String savedData) {} + + /** + * The source of a point in time restore. A live instance can be named by identifier or by its + * DbiResourceId; a deleted one by the DbiResourceId or ARN of the automated backup it kept. A + * replicated backup's ARN names its live source in the source Region. + */ + private synchronized PointInTimeSource resolvePointInTimeSource(PointInTimeRestoreRequest request, + String region, Instant now) { String byId = request.sourceDbInstanceIdentifier(); String byResourceId = request.sourceDbiResourceId(); String byBackupsArn = request.sourceDbInstanceAutomatedBackupsArn(); @@ -1452,16 +1479,41 @@ public class RdsService implements Resettable, ResourceProvider { + "SourceDBInstanceAutomatedBackupsArn.", 400); } if (!isBlank(byId)) { - return getDbInstance(byId, region); + return livePointInTimeSource(getDbInstance(byId, region), now); } - if (!isBlank(byResourceId)) { - return listDbInstancesByDbiResourceIds(List.of(byResourceId), region).stream() + DbInstanceAutomatedBackup backup = instanceBackupsIn(region).stream() + .filter(b -> isBlank(byResourceId) + ? byBackupsArn.equals(b.getDbInstanceAutomatedBackupsArn()) + : byResourceId.equalsIgnoreCase(b.getInstance().getDbiResourceId())) + .findFirst() + .orElse(null); + if (backup == null && !isBlank(byResourceId)) { + // An instance without backups has no automated backup, but is still named by its ID. + DbInstance live = listDbInstancesByDbiResourceIds(List.of(byResourceId), region).stream() .findFirst() .orElseThrow(() -> new AwsException("DBInstanceNotFound", "DB instance with resource ID " + byResourceId + " not found.", 404)); + return livePointInTimeSource(live, now); } - throw new AwsException("DBInstanceAutomatedBackupNotFound", - "Automated backups " + byBackupsArn + " not found.", 404); + if (backup == null) { + throw instanceBackupNotFound(byBackupsArn); + } + return switch (backup.getStatus()) { + case DbInstanceAutomatedBackup.ACTIVE -> livePointInTimeSource(backup.getInstance(), now); + // The live source's data, checked against the replica's own window. + case DbInstanceAutomatedBackup.REPLICATING -> new PointInTimeSource( + getDbInstance(backup.getInstance().getDbInstanceIdentifier(), backup.getRegion()), true, + backup.getEarliestTime(), backup.getLatestTime(), null); + default -> new PointInTimeSource(backup.getInstance(), false, backup.getEarliestTime(), + backup.getLatestTime(), backup.isDataSaved() + ? snapshotData.get(instanceBackupDataKey(region, backup.getInstance().getDbiResourceId())) + .orElse(null) + : null); + }; + } + + private static PointInTimeSource livePointInTimeSource(DbInstance instance, Instant now) { + return new PointInTimeSource(instance, true, earliestRestorableTime(instance, now), now, null); } /** @@ -1490,6 +1542,360 @@ public class RdsService implements Resettable, ResourceProvider { return value == null || value.isBlank(); } + // ── Automated backups ───────────────────────────────────────────────────── + + /** AWS's default retention for replicated automated backups, in days. */ + static final int DEFAULT_REPLICATED_BACKUP_RETENTION_DAYS = 7; + /** Floci does not model a cluster's backup retention period; one day is the AWS default. */ + static final int CLUSTER_BACKUP_RETENTION_DAYS = 1; + + public record AutomatedBackupPage(List backups, String marker) {} + + /** + * An instance's automated backups and their replicas in this Region: each live standalone + * instance with backups on has an {@code active} one, and retained and replicated ones are + * stored. Aurora instances are left out, since their backups belong to the cluster. + */ + public synchronized AutomatedBackupPage describeDbInstanceAutomatedBackups( + String region, String dbiResourceId, String instanceId, String backupsArn, + List statuses, List instanceIds, List resourceIds, + Integer maxRecords, String marker) { + String effectiveRegion = effectiveRegion(region); + requireValidMaxRecords(maxRecords); + List matching = instanceBackupsIn(effectiveRegion).stream() + .filter(b -> isBlank(dbiResourceId) + || dbiResourceId.equalsIgnoreCase(b.getInstance().getDbiResourceId())) + .filter(b -> isBlank(instanceId) + || instanceId.equalsIgnoreCase(b.getInstance().getDbInstanceIdentifier())) + .filter(b -> isBlank(backupsArn) || backupsArn.equals(b.getDbInstanceAutomatedBackupsArn())) + .filter(b -> statuses.isEmpty() || statuses.contains(b.getStatus())) + .filter(b -> instanceIds.isEmpty() + || instanceIds.contains(b.getInstance().getDbInstanceIdentifier()) + || instanceIds.contains(b.getInstance().getDbInstanceArn())) + .filter(b -> resourceIds.isEmpty() + || resourceIds.contains(b.getInstance().getDbiResourceId()) + || resourceIds.contains(b.getDbInstanceAutomatedBackupsArn())) + .sorted(Comparator.comparing((DbInstanceAutomatedBackup b) -> b.getInstance().getDbInstanceIdentifier()) + .thenComparing(DbInstanceAutomatedBackup::getDbInstanceAutomatedBackupsArn)) + .toList(); + if (matching.isEmpty() && !(isBlank(dbiResourceId) && isBlank(instanceId) && isBlank(backupsArn))) { + throw instanceBackupNotFound(firstNonBlank(dbiResourceId, firstNonBlank(instanceId, backupsArn))); + } + OffsetPage page = offsetPage(matching, maxRecords, marker); + return new AutomatedBackupPage<>(page.items(), page.marker()); + } + + /** Deletes a retained or stopped replicated backup, named by its source's DbiResourceId or its ARN. */ + public synchronized DbInstanceAutomatedBackup deleteDbInstanceAutomatedBackup( + String region, String dbiResourceId, String backupsArn) { + String effectiveRegion = effectiveRegion(region); + if (isBlank(dbiResourceId) == isBlank(backupsArn)) { + throw new AwsException("InvalidParameterCombination", + "Specify exactly one of DbiResourceId and DBInstanceAutomatedBackupsArn.", 400); + } + DbInstanceAutomatedBackup backup = instanceBackupsIn(effectiveRegion).stream() + .filter(b -> isBlank(dbiResourceId) + ? backupsArn.equals(b.getDbInstanceAutomatedBackupsArn()) + : dbiResourceId.equalsIgnoreCase(b.getInstance().getDbiResourceId())) + .findFirst() + .orElseThrow(() -> instanceBackupNotFound(firstNonBlank(dbiResourceId, backupsArn))); + if (!DbInstanceAutomatedBackup.RETAINED.equals(backup.getStatus())) { + throw new AwsException("InvalidDBInstanceAutomatedBackupState", + "Automated backup " + backup.getDbInstanceAutomatedBackupsArn() + " is " + backup.getStatus() + + ", and only a retained automated backup can be deleted.", 400); + } + String dbi = backup.getInstance().getDbiResourceId(); + instanceAutomatedBackups.delete(dbResourceKey(effectiveRegion, dbi)); + snapshotData.delete(instanceBackupDataKey(effectiveRegion, dbi)); + backup.setStatus("deleting"); + return backup; + } + + /** + * Starts replicating a source instance's automated backups from its Region to this one. The + * replica is metadata only: no data crosses Regions, so a restore from it copies the source's + * current data while the source lives. + */ + public synchronized DbInstanceAutomatedBackup startDbInstanceAutomatedBackupsReplication( + String region, String sourceInstanceArn, Integer backupRetentionPeriod, String kmsKeyId) { + String effectiveRegion = effectiveRegion(region); + DbInstance source = requireReplicationSource(sourceInstanceArn, effectiveRegion); + String sourceId = source.getDbInstanceIdentifier(); + if (!isBlank(source.getDbClusterIdentifier())) { + throw new AwsException("InvalidDBInstanceState", + "DB instance " + sourceId + " belongs to DB cluster " + source.getDbClusterIdentifier() + + ", and automated backup replication is not supported for it.", 400); + } + if (source.getStatus() != DbInstanceStatus.AVAILABLE) { + throw new AwsException("InvalidDBInstanceState", + "DB instance " + sourceId + " is not in available state.", 400); + } + if (source.getBackupRetentionPeriod() <= 0) { + throw new AwsException("InvalidDBInstanceState", + "Automated backups are not enabled for DB instance " + sourceId + ".", 400); + } + int retention = backupRetentionPeriod != null ? backupRetentionPeriod : DEFAULT_REPLICATED_BACKUP_RETENTION_DAYS; + if (retention < 1 || retention > 35) { + throw new AwsException("InvalidParameterValue", + "BackupRetentionPeriod must be between 1 and 35.", 400); + } + String key = dbResourceKey(effectiveRegion, source.getDbiResourceId()); + // A replica kept as retained after a stop is replaced, so replication can start again. + if (instanceAutomatedBackups.get(key) + .filter(b -> DbInstanceAutomatedBackup.REPLICATING.equals(b.getStatus())).isPresent()) { + throw new AwsException("InvalidDBInstanceAutomatedBackupState", + "DB instance " + sourceId + " is already replicating to " + effectiveRegion + ".", 400); + } + Instant now = Instant.now(); + DbInstanceAutomatedBackup replica = new DbInstanceAutomatedBackup(); + replica.setDbInstanceAutomatedBackupsArn(instanceBackupArn(effectiveRegion, source.getDbiResourceId())); + replica.setStatus(DbInstanceAutomatedBackup.REPLICATING); + replica.setInstance(source); + replica.setRegion(regionFromArn(source.getDbInstanceArn())); + replica.setEarliestTime(now); + replica.setLatestTime(now); + replica.setBackupRetentionPeriod(retention); + replica.setKmsKeyId(isBlank(kmsKeyId) ? null : kmsKeyId); + instanceAutomatedBackups.put(key, replica); + source.getAutomatedBackupReplicationArns().add(replica.getDbInstanceAutomatedBackupsArn()); + putInstanceForScope(currentAccountId(), replica.getRegion(), sourceId, source); + LOG.infov("Replicating automated backups of DB instance {0} to {1}", sourceId, effectiveRegion); + return replica; + } + + /** Stops replicating a source's backups to this Region; the replica is kept as retained. */ + public synchronized DbInstanceAutomatedBackup stopDbInstanceAutomatedBackupsReplication( + String region, String sourceInstanceArn) { + String effectiveRegion = effectiveRegion(region); + DbInstance source = requireReplicationSource(sourceInstanceArn, effectiveRegion); + String key = dbResourceKey(effectiveRegion, source.getDbiResourceId()); + DbInstanceAutomatedBackup replica = instanceAutomatedBackups.get(key) + .filter(b -> DbInstanceAutomatedBackup.REPLICATING.equals(b.getStatus())) + .orElseThrow(() -> new AwsException("InvalidDBInstanceState", + "DB instance " + source.getDbInstanceIdentifier() + + " is not replicating to the current region.", 400)); + source.getAutomatedBackupReplicationArns().remove(replica.getDbInstanceAutomatedBackupsArn()); + putInstanceForScope(currentAccountId(), replica.getRegion(), source.getDbInstanceIdentifier(), source); + replica.setStatus(DbInstanceAutomatedBackup.RETAINED); + replica.setLatestTime(Instant.now()); + instanceAutomatedBackups.put(key, replica); + LOG.infov("Stopped replicating automated backups of DB instance {0} to {1}", + source.getDbInstanceIdentifier(), effectiveRegion); + return replica; + } + + /** Retained cluster backups in this Region. A live cluster's backups are not listed, as in AWS. */ + public synchronized AutomatedBackupPage describeDbClusterAutomatedBackups( + String region, String clusterResourceId, String clusterId, List statuses, + List clusterIds, List resourceIds, Integer maxRecords, String marker) { + String effectiveRegion = effectiveRegion(region); + requireValidMaxRecords(maxRecords); + List matching = clusterBackupsIn(effectiveRegion).stream() + .filter(b -> isBlank(clusterResourceId) + || clusterResourceId.equalsIgnoreCase(b.getCluster().getDbClusterResourceId())) + .filter(b -> isBlank(clusterId) || clusterId.equalsIgnoreCase(b.getCluster().getDbClusterIdentifier())) + .filter(b -> statuses.isEmpty() || statuses.contains(b.getStatus())) + .filter(b -> clusterIds.isEmpty() + || clusterIds.contains(b.getCluster().getDbClusterIdentifier()) + || clusterIds.contains(b.getCluster().getDbClusterArn())) + .filter(b -> resourceIds.isEmpty() + || resourceIds.contains(b.getCluster().getDbClusterResourceId()) + || resourceIds.contains(b.getDbClusterAutomatedBackupsArn())) + .sorted(Comparator.comparing((DbClusterAutomatedBackup b) -> b.getCluster().getDbClusterIdentifier()) + .thenComparing(DbClusterAutomatedBackup::getDbClusterAutomatedBackupsArn)) + .toList(); + if (matching.isEmpty() && !(isBlank(clusterResourceId) && isBlank(clusterId))) { + throw clusterBackupNotFound(firstNonBlank(clusterResourceId, clusterId)); + } + OffsetPage page = offsetPage(matching, maxRecords, marker); + return new AutomatedBackupPage<>(page.items(), page.marker()); + } + + public synchronized DbClusterAutomatedBackup deleteDbClusterAutomatedBackup(String region, String clusterResourceId) { + String effectiveRegion = effectiveRegion(region); + if (isBlank(clusterResourceId)) { + throw new AwsException("InvalidParameterValue", "DbClusterResourceId is required.", 400); + } + DbClusterAutomatedBackup backup = clusterBackupsIn(effectiveRegion).stream() + .filter(b -> clusterResourceId.equalsIgnoreCase(b.getCluster().getDbClusterResourceId())) + .findFirst() + .orElse(null); + if (backup == null) { + boolean live = listDbClusters(null, effectiveRegion).stream() + .anyMatch(c -> clusterResourceId.equalsIgnoreCase(c.getDbClusterResourceId())); + if (live) { + throw new AwsException("InvalidDBClusterAutomatedBackupStateFault", + "The automated backups of " + clusterResourceId + " belong to a live DB cluster.", 400); + } + throw clusterBackupNotFound(clusterResourceId); + } + String resourceId = backup.getCluster().getDbClusterResourceId(); + clusterAutomatedBackups.delete(dbResourceKey(effectiveRegion, resourceId)); + snapshotData.delete(clusterBackupDataKey(effectiveRegion, resourceId)); + backup.setStatus("deleting"); + return backup; + } + + private List instanceBackupsIn(String region) { + Instant now = Instant.now(); + List all = new ArrayList<>(); + for (DbInstance instance : listDbInstances(null, region)) { + if (isBlank(instance.getDbClusterIdentifier()) && instance.getBackupRetentionPeriod() > 0) { + all.add(activeInstanceBackupOf(instance, region, now)); + } + } + String prefix = region + "::"; + for (DbInstanceAutomatedBackup stored : instanceAutomatedBackups.scan(key -> key.startsWith(prefix))) { + if (DbInstanceAutomatedBackup.REPLICATING.equals(stored.getStatus())) { + // A replica follows its live source up to now. + stored.setLatestTime(now); + } + all.add(stored); + } + return all; + } + + private List clusterBackupsIn(String region) { + String prefix = region + "::"; + return clusterAutomatedBackups.scan(key -> key.startsWith(prefix)); + } + + private DbInstanceAutomatedBackup activeInstanceBackupOf(DbInstance instance, String region, Instant now) { + DbInstanceAutomatedBackup backup = new DbInstanceAutomatedBackup(); + backup.setDbInstanceAutomatedBackupsArn(instanceBackupArn(region, instance.getDbiResourceId())); + backup.setStatus(DbInstanceAutomatedBackup.ACTIVE); + backup.setInstance(instance); + backup.setRegion(region); + backup.setEarliestTime(earliestRestorableTime(instance, now)); + backup.setLatestTime(now); + backup.setBackupRetentionPeriod(instance.getBackupRetentionPeriod()); + backup.setKmsKeyId(instance.getKmsKeyId()); + return backup; + } + + /** + * The backup a deleted instance leaves: its restore window ends now, and outside mock mode a + * PostgreSQL instance's data is copied so a later restore can bring it back. A failed copy + * fails the delete, which has changed nothing yet. + */ + private DbInstanceAutomatedBackup retainedInstanceBackupOf(DbInstance instance, String region) { + Instant now = Instant.now(); + DbInstanceAutomatedBackup backup = activeInstanceBackupOf(instance, region, now); + backup.setStatus(DbInstanceAutomatedBackup.RETAINED); + backup.setInstance(instance); + String dump = saveBackupData(instance.getEngine(), instance.getContainerId(), instance.getMasterUsername(), + "DB instance " + instance.getDbInstanceIdentifier(), "InvalidDBInstanceState"); + if (dump != null) { + snapshotData.put(instanceBackupDataKey(region, instance.getDbiResourceId()), dump); + backup.setDataSaved(true); + } + return backup; + } + + private DbClusterAutomatedBackup retainedClusterBackupOf(DbCluster cluster, String region) { + Instant now = Instant.now(); + DbClusterAutomatedBackup backup = new DbClusterAutomatedBackup(); + backup.setDbClusterAutomatedBackupsArn(regionResolver.buildArn("rds", region, + "cluster-auto-backup:" + cluster.getDbClusterResourceId())); + backup.setStatus(DbClusterAutomatedBackup.RETAINED); + backup.setCluster(cluster); + backup.setRegion(region); + backup.setEarliestTime(cluster.getCreatedAt() != null ? cluster.getCreatedAt() : now); + backup.setLatestTime(now); + backup.setBackupRetentionPeriod(CLUSTER_BACKUP_RETENTION_DAYS); + String dump = saveBackupData(cluster.getEngine(), cluster.getContainerId(), cluster.getMasterUsername(), + "DB cluster " + cluster.getDbClusterIdentifier(), "InvalidDBClusterStateFault"); + if (dump != null) { + snapshotData.put(clusterBackupDataKey(region, cluster.getDbClusterResourceId()), dump); + backup.setDataSaved(true); + } + return backup; + } + + /** A dump of a PostgreSQL database's data, or null in mock mode or for an engine Floci cannot copy. */ + private String saveBackupData(DatabaseEngine engine, String containerId, String masterUsername, + String owner, String errorCode) { + if (config.services().rds().mock() || engine != DatabaseEngine.POSTGRES || containerId == null) { + return null; + } + try { + return containerManager.createPostgresSnapshot(containerId, masterUsername); + } catch (Exception e) { + LOG.warnv(e, "Failed to save the automated backup of {0}", owner); + AwsException failure = new AwsException(errorCode, + "Failed to save the automated backup of " + owner + ": " + e.getMessage(), 400); + failure.initCause(e); + throw failure; + } + } + + /** A deleted instance's replicas in other Regions stop following it and are kept as retained. */ + private void retainReplicatedBackups(DbInstance instance) { + Instant now = Instant.now(); + for (String replicaArn : instance.getAutomatedBackupReplicationArns()) { + String key = dbResourceKey(regionFromArn(replicaArn), instance.getDbiResourceId()); + instanceAutomatedBackups.get(key).ifPresent(replica -> { + replica.setStatus(DbInstanceAutomatedBackup.RETAINED); + replica.setLatestTime(now); + instanceAutomatedBackups.put(key, replica); + }); + } + instance.getAutomatedBackupReplicationArns().clear(); + } + + /** The live instance a replication request names by ARN, in a Region other than this one. */ + private DbInstance requireReplicationSource(String sourceInstanceArn, String region) { + if (isBlank(sourceInstanceArn)) { + throw new AwsException("InvalidParameterValue", "SourceDBInstanceArn is required.", 400); + } + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(sourceInstanceArn); + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidParameterValue", + "SourceDBInstanceArn " + sourceInstanceArn + " is not a valid DB instance ARN.", 400); + } + if (!arn.resource().startsWith("db:")) { + throw new AwsException("InvalidParameterValue", + "SourceDBInstanceArn " + sourceInstanceArn + " is not a valid DB instance ARN.", 400); + } + if (region.equals(arn.region())) { + throw new AwsException("InvalidParameterValue", + "The source DB instance must be in a Region other than " + region + ".", 400); + } + String sourceId = arn.resource().substring("db:".length()); + DbInstance source = findInstanceForScope(currentAccountId(), arn.region(), sourceId); + // The whole ARN must name the instance, so another account's or partition's ARN finds nothing. + if (source == null || !sourceInstanceArn.equals(source.getDbInstanceArn())) { + throw new AwsException("DBInstanceNotFound", "DB instance " + sourceInstanceArn + " not found.", 404); + } + return source; + } + + /** {@code db-XXXX} names the instance; its backups are {@code auto-backup:ab-XXXX}, as in AWS. */ + private String instanceBackupArn(String region, String dbiResourceId) { + String suffix = dbiResourceId.startsWith("db-") ? dbiResourceId.substring("db-".length()) : dbiResourceId; + return regionResolver.buildArn("rds", region, "auto-backup:ab-" + suffix); + } + + private String instanceBackupDataKey(String region, String dbiResourceId) { + return dbResourceKey(region, "auto-backup:" + dbiResourceId); + } + + private String clusterBackupDataKey(String region, String clusterResourceId) { + return dbResourceKey(region, "cluster-auto-backup:" + clusterResourceId); + } + + private static AwsException instanceBackupNotFound(String name) { + return new AwsException("DBInstanceAutomatedBackupNotFound", + "Automated backups " + name + " not found.", 404); + } + + private static AwsException clusterBackupNotFound(String name) { + return new AwsException("DBClusterAutomatedBackupNotFoundFault", + "Automated backups " + name + " not found.", 404); + } + // ── Read replicas ───────────────────────────────────────────────────────── static final String READ_REPLICATION_REPLICATING = "replicating"; @@ -2130,22 +2536,42 @@ public class RdsService implements Resettable, ResourceProvider { throw new AwsException("InvalidParameterValue", "RestoreType must be full-copy or copy-on-write.", 400); } - // SourceDBClusterIdentifier takes the cluster's identifier or its ARN (API reference). - DbCluster source = !isBlank(sourceClusterRef) - ? getDbCluster(clusterIdentifierFromArnOrName(sourceClusterRef, effectiveRegion), effectiveRegion) - : listDbClusters(null, effectiveRegion).stream() + // SourceDBClusterIdentifier takes the cluster's identifier or its ARN (API reference). A + // resource ID names a live cluster, or a deleted one through the backup it kept. + DbClusterAutomatedBackup retained = null; + DbCluster source; + String savedData = null; + if (!isBlank(sourceClusterRef)) { + source = getDbCluster(clusterIdentifierFromArnOrName(sourceClusterRef, effectiveRegion), effectiveRegion); + } else { + synchronized (this) { + source = listDbClusters(null, effectiveRegion).stream() .filter(c -> sourceClusterResourceId.equals(c.getDbClusterResourceId())) .findFirst() - .orElseThrow(() -> new AwsException("DBClusterNotFoundFault", - "DB cluster with resource ID " + sourceClusterResourceId + " not found.", 404)); + .orElse(null); + if (source == null) { + retained = clusterBackupsIn(effectiveRegion).stream() + .filter(b -> sourceClusterResourceId.equals(b.getCluster().getDbClusterResourceId())) + .findFirst() + .orElseThrow(() -> new AwsException("DBClusterNotFoundFault", + "DB cluster with resource ID " + sourceClusterResourceId + " not found.", 404)); + source = retained.getCluster(); + savedData = retained.isDataSaved() + ? snapshotData.get(clusterBackupDataKey(effectiveRegion, sourceClusterResourceId)).orElse(null) + : null; + } + } + } String sourceId = source.getDbClusterIdentifier(); - if (source.getStatus() != null && source.getStatus() != DbInstanceStatus.AVAILABLE) { + if (retained == null && source.getStatus() != null && source.getStatus() != DbInstanceStatus.AVAILABLE) { throw new AwsException("InvalidDBClusterStateFault", "DB cluster " + sourceId + " is not in available state.", 400); } Instant now = Instant.now(); - Instant earliest = source.getCreatedAt() != null ? source.getCreatedAt() : now; - requireRestorableTime(restoreToTime, useLatestRestorableTime, earliest, now, "RestoreToTime"); + Instant earliest = retained != null ? retained.getEarliestTime() + : source.getCreatedAt() != null ? source.getCreatedAt() : now; + Instant latest = retained != null ? retained.getLatestTime() : now; + requireRestorableTime(restoreToTime, useLatestRestorableTime, earliest, latest, "RestoreToTime"); if (source.getEngine() != DatabaseEngine.POSTGRES) { throw new AwsException("InvalidDBClusterStateFault", "Operation RestoreDBClusterToPointInTime is not supported for engine " @@ -2167,11 +2593,15 @@ public class RdsService implements Resettable, ResourceProvider { } if (!config.services().rds().mock()) { try { - if (source.getContainerId() == null || cluster.getContainerId() == null) { + if ((retained == null && source.getContainerId() == null) || cluster.getContainerId() == null) { throw new IllegalStateException("the source or target database container is not running"); } - String sqlDump = containerManager.createPostgresSnapshot( - source.getContainerId(), source.getMasterUsername()); + if (retained != null && savedData == null) { + throw new IllegalStateException("the automated backup holds no saved data"); + } + String sqlDump = retained == null + ? containerManager.createPostgresSnapshot(source.getContainerId(), source.getMasterUsername()) + : savedData; containerManager.restorePostgresSnapshot( cluster.getContainerId(), cluster.getMasterUsername(), sqlDump); } catch (Exception e) { @@ -4369,13 +4799,22 @@ public class RdsService implements Resettable, ResourceProvider { } public void deleteDbInstance(String id, String region) { + deleteDbInstance(id, region, true); + } + + /** + * Deletes a DB instance. With {@code deleteAutomatedBackups} false, a standalone instance + * that keeps backups leaves a {@code retained} automated backup behind, which a point in time + * restore can still use; the default removes the backups with the instance, as in AWS. + */ + public void deleteDbInstance(String id, String region, boolean deleteAutomatedBackups) { withInstancePublication(id, region, () -> { - doDeleteDbInstance(id, region); + doDeleteDbInstance(id, region, deleteAutomatedBackups); return null; }); } - private synchronized void doDeleteDbInstance(String id, String region) { + private synchronized void doDeleteDbInstance(String id, String region, boolean deleteAutomatedBackups) { String effectiveRegion = effectiveRegion(region); DbInstance instance = Optional.ofNullable( findInstanceForScope(currentAccountId(), effectiveRegion, id)) @@ -4394,6 +4833,10 @@ public class RdsService implements Resettable, ResourceProvider { } String clusterId = instance.getDbClusterIdentifier(); + // Taken before the instance changes, so a failed copy of its data leaves it as it was. + DbInstanceAutomatedBackup retained = !deleteAutomatedBackups && isBlank(clusterId) + && instance.getBackupRetentionPeriod() > 0 + ? retainedInstanceBackupOf(instance, effectiveRegion) : null; instance.setStatus(DbInstanceStatus.DELETING); putInstanceForScope(currentAccountId(), effectiveRegion, id, instance); detachReadReplicaLinksBeforeDelete(instance); @@ -4436,6 +4879,10 @@ public class RdsService implements Resettable, ResourceProvider { releaseProxyPort(instance.getProxyPort()); deleteInstanceForScope(currentAccountId(), effectiveRegion, id); reportedMemberRelayFailures.remove(instance.getDbInstanceArn()); + retainReplicatedBackups(instance); + if (retained != null) { + instanceAutomatedBackups.put(dbResourceKey(effectiveRegion, instance.getDbiResourceId()), retained); + } LOG.infov("DB instance {0} deleted", id); } @@ -5183,6 +5630,14 @@ public class RdsService implements Resettable, ResourceProvider { } public void deleteDbCluster(String id, String region) { + deleteDbCluster(id, region, true); + } + + /** + * Deletes a DB cluster. With {@code deleteAutomatedBackups} false the cluster leaves a + * {@code retained} automated backup behind, which RestoreDBClusterToPointInTime can still use. + */ + public void deleteDbCluster(String id, String region, boolean deleteAutomatedBackups) { String effectiveRegion = effectiveRegion(region); while (true) { DbCluster cluster = getDbCluster(id, effectiveRegion); @@ -5191,14 +5646,14 @@ public class RdsService implements Resettable, ResourceProvider { if (findClusterForScope(currentAccountId(), effectiveRegion, id) != cluster) { continue; } - doDeleteDbCluster(id, region); + doDeleteDbCluster(id, region, deleteAutomatedBackups); return; } } } } - private void doDeleteDbCluster(String id, String region) { + private void doDeleteDbCluster(String id, String region, boolean deleteAutomatedBackups) { String effectiveRegion = effectiveRegion(region); DbCluster cluster = Optional.ofNullable( findClusterForScope(currentAccountId(), effectiveRegion, id)) @@ -5215,6 +5670,9 @@ public class RdsService implements Resettable, ResourceProvider { throw new AwsException("InvalidDBClusterStateFault", "DB cluster " + id + " is registered with a DB proxy target group.", 400); } + // Taken before the cluster changes, so a failed copy of its data leaves it as it was. + DbClusterAutomatedBackup retained = deleteAutomatedBackups ? null + : retainedClusterBackupOf(cluster, effectiveRegion); detachFromGlobalClusterBeforeDelete(cluster); detachManagedMasterUserSecret(cluster, effectiveRegion); @@ -5242,6 +5700,9 @@ public class RdsService implements Resettable, ResourceProvider { // Custom endpoints belong to their cluster and go with it. clusterEndpointsOf(effectiveRegion, id).forEach(endpoint -> clusterEndpoints.delete( clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier()))); + if (retained != null) { + clusterAutomatedBackups.put(dbResourceKey(effectiveRegion, cluster.getDbClusterResourceId()), retained); + } LOG.infov("DB cluster {0} deleted", id); } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterAutomatedBackup.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterAutomatedBackup.java new file mode 100644 index 0000000000..c1efdce335 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterAutomatedBackup.java @@ -0,0 +1,52 @@ +package io.github.hectorvent.floci.services.rds.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * A deleted DB cluster's {@code retained} automated backup, kept when the cluster is deleted with + * {@code DeleteAutomatedBackups=false}, with the cluster as it was. DescribeDBClusterAutomatedBackups + * lists only these: a live cluster's backups are not listed, as in AWS. + */ +@RegisterForReflection +public class DbClusterAutomatedBackup { + + public static final String RETAINED = "retained"; + + private String dbClusterAutomatedBackupsArn; + private String status; + private DbCluster cluster; + private String region; + private Instant earliestTime; + private Instant latestTime; + private int backupRetentionPeriod; + /** Whether the cluster's data was saved with the backup, so a restore from it can copy it. */ + private boolean dataSaved; + + public DbClusterAutomatedBackup() {} + + public String getDbClusterAutomatedBackupsArn() { return dbClusterAutomatedBackupsArn; } + public void setDbClusterAutomatedBackupsArn(String arn) { this.dbClusterAutomatedBackupsArn = arn; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public DbCluster getCluster() { return cluster; } + public void setCluster(DbCluster cluster) { this.cluster = cluster; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + + public Instant getEarliestTime() { return earliestTime; } + public void setEarliestTime(Instant earliestTime) { this.earliestTime = earliestTime; } + + public Instant getLatestTime() { return latestTime; } + public void setLatestTime(Instant latestTime) { this.latestTime = latestTime; } + + public int getBackupRetentionPeriod() { return backupRetentionPeriod; } + public void setBackupRetentionPeriod(int backupRetentionPeriod) { this.backupRetentionPeriod = backupRetentionPeriod; } + + public boolean isDataSaved() { return dataSaved; } + public void setDataSaved(boolean dataSaved) { this.dataSaved = dataSaved; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java index 9357007f8b..49778b0606 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java @@ -80,6 +80,8 @@ public class DbInstance { // gone. private String readReplicaSourceDbInstanceIdentifier; private List readReplicaDbInstanceIdentifiers = new ArrayList<>(); + /** The ARNs of this instance's automated backups replicated to other Regions. */ + private List automatedBackupReplicationArns = new ArrayList<>(); private String readReplicationStatus; private String dockerVolumeName; @@ -243,6 +245,12 @@ public class DbInstance { this.readReplicaSourceDbInstanceIdentifier = readReplicaSourceDbInstanceIdentifier; } + public List getAutomatedBackupReplicationArns() { return automatedBackupReplicationArns; } + public void setAutomatedBackupReplicationArns(List automatedBackupReplicationArns) { + this.automatedBackupReplicationArns = automatedBackupReplicationArns != null + ? new ArrayList<>(automatedBackupReplicationArns) : new ArrayList<>(); + } + public List getReadReplicaDbInstanceIdentifiers() { return readReplicaDbInstanceIdentifiers; } public void setReadReplicaDbInstanceIdentifiers(List readReplicaDbInstanceIdentifiers) { this.readReplicaDbInstanceIdentifiers = readReplicaDbInstanceIdentifiers != null diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceAutomatedBackup.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceAutomatedBackup.java new file mode 100644 index 0000000000..b74acee053 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceAutomatedBackup.java @@ -0,0 +1,61 @@ +package io.github.hectorvent.floci.services.rds.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * A DB instance's automated backups as DescribeDBInstanceAutomatedBackups reports them. A live + * instance's {@code active} backup is built from the instance when described. A {@code retained} + * backup, kept when an instance is deleted with {@code DeleteAutomatedBackups=false}, and a + * {@code replicating} backup in another Region are stored, with the instance as it was. + */ +@RegisterForReflection +public class DbInstanceAutomatedBackup { + + public static final String ACTIVE = "active"; + public static final String RETAINED = "retained"; + public static final String REPLICATING = "replicating"; + + private String dbInstanceAutomatedBackupsArn; + private String status; + /** The source instance: live for an active backup, as it was for a stored one. */ + private DbInstance instance; + /** The source instance's Region. */ + private String region; + private Instant earliestTime; + private Instant latestTime; + private int backupRetentionPeriod; + private String kmsKeyId; + /** Whether the source's data was saved with the backup, so a restore from it can copy it. */ + private boolean dataSaved; + + public DbInstanceAutomatedBackup() {} + + public String getDbInstanceAutomatedBackupsArn() { return dbInstanceAutomatedBackupsArn; } + public void setDbInstanceAutomatedBackupsArn(String arn) { this.dbInstanceAutomatedBackupsArn = arn; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public DbInstance getInstance() { return instance; } + public void setInstance(DbInstance instance) { this.instance = instance; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } + + public Instant getEarliestTime() { return earliestTime; } + public void setEarliestTime(Instant earliestTime) { this.earliestTime = earliestTime; } + + public Instant getLatestTime() { return latestTime; } + public void setLatestTime(Instant latestTime) { this.latestTime = latestTime; } + + public int getBackupRetentionPeriod() { return backupRetentionPeriod; } + public void setBackupRetentionPeriod(int backupRetentionPeriod) { this.backupRetentionPeriod = backupRetentionPeriod; } + + public String getKmsKeyId() { return kmsKeyId; } + public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; } + + public boolean isDataSaved() { return dataSaved; } + public void setDataSaved(boolean dataSaved) { this.dataSaved = dataSaved; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsAutomatedBackupsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsAutomatedBackupsIntegrationTest.java new file mode 100644 index 0000000000..b774f89a8e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsAutomatedBackupsIntegrationTest.java @@ -0,0 +1,348 @@ +package io.github.hectorvent.floci.services.rds; + +import io.github.hectorvent.floci.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.AfterEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; + +import static io.restassured.RestAssured.given; +import static io.restassured.http.ContentType.URLENC; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Instance and cluster automated backups over the Query protocol: the active backup a live instance + * has, the retained one a delete with {@code DeleteAutomatedBackups=false} leaves and a point in time + * restore can use, and replication to another Region. The requests sign for Regions no other test + * uses, so the Region-wide listings hold only what these tests create. + */ +@QuarkusTest +@TestProfile(RdsMockProfile.class) +class RdsAutomatedBackupsIntegrationTest { + + private static final String SOURCE_REGION = "ap-southeast-2"; + private static final String DESTINATION_REGION = "ap-northeast-3"; + + private static RequestSpecification query(String action) { + return query(action, SOURCE_REGION); + } + + private static RequestSpecification query(String action, String region) { + return given().header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20261028/" + region + + "/rds/aws4_request, SignedHeaders=content-type;host, Signature=test") + .contentType(URLENC) + .formParam("Action", action) + .formParam("Version", "2014-10-31"); + } + + private static void createInstance(String id) { + query("CreateDBInstance") + .formParam("DBInstanceIdentifier", id) + .formParam("Engine", "postgres") + .formParam("DBInstanceClass", "db.t3.micro") + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123") + .formParam("AllocatedStorage", "20") + .formParam("BackupRetentionPeriod", "3") + .when().post("/").then().statusCode(200); + } + + private static String dbiResourceId(String id) { + return query("DescribeDBInstances").formParam("DBInstanceIdentifier", id) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("**.find { it.name() == 'DbiResourceId' }"); + } + + private static XmlPath backupsOf(String dbiResourceId, String region) { + return query("DescribeDBInstanceAutomatedBackups", region).formParam("DbiResourceId", dbiResourceId) + .when().post("/").then().statusCode(200).extract().xmlPath(); + } + + /** Instances hold ports the other tests in this Quarkus app expect to find free. */ + @AfterEach + void cleanUp() { + for (String id : new String[] {"ab-live", "ab-kept", "ab-gone", "ab-restored", "ab-by-arn", "ab-src"}) { + query("DeleteDBInstance").formParam("DBInstanceIdentifier", id) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + } + for (String id : new String[] {"abc-kept", "abc-restored"}) { + query("DeleteDBCluster").formParam("DBClusterIdentifier", id) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + } + } + + @Test + void aLiveInstanceHasAnActiveBackupThatCannotBeDeleted() { + createInstance("ab-live"); + String dbi = dbiResourceId("ab-live"); + + XmlPath backup = backupsOf(dbi, SOURCE_REGION); + String prefix = "DescribeDBInstanceAutomatedBackupsResponse.DescribeDBInstanceAutomatedBackupsResult" + + ".DBInstanceAutomatedBackups.DBInstanceAutomatedBackup."; + assertEquals("active", backup.getString(prefix + "Status")); + assertEquals("ab-live", backup.getString(prefix + "DBInstanceIdentifier")); + assertEquals(SOURCE_REGION, backup.getString(prefix + "Region")); + assertEquals("3", backup.getString(prefix + "BackupRetentionPeriod")); + assertEquals("arn:aws:rds:" + SOURCE_REGION + ":000000000000:auto-backup:ab-" + dbi.substring(3), + backup.getString(prefix + "DBInstanceAutomatedBackupsArn")); + Instant earliest = Instant.parse(backup.getString(prefix + "RestoreWindow.EarliestTime")); + Instant latest = Instant.parse(backup.getString(prefix + "RestoreWindow.LatestTime")); + assertTrue(!earliest.isAfter(latest), "the window must open before it closes"); + + query("DeleteDBInstanceAutomatedBackup").formParam("DbiResourceId", dbi) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidDBInstanceAutomatedBackupState")); + query("DescribeDBInstanceAutomatedBackups").formParam("DbiResourceId", "db-NOSUCHRESOURCE") + .when().post("/").then().statusCode(404) + .body(containsString("DBInstanceAutomatedBackupNotFound")); + } + + @Test + void aDeleteThatKeepsBackupsLeavesARetainedBackupToRestoreFrom() { + createInstance("ab-kept"); + String dbi = dbiResourceId("ab-kept"); + query("DeleteDBInstance").formParam("DBInstanceIdentifier", "ab-kept") + .formParam("SkipFinalSnapshot", "true").formParam("DeleteAutomatedBackups", "false") + .when().post("/").then().statusCode(200); + + query("DescribeDBInstanceAutomatedBackups") + .formParam("Filters.Filter.1.Name", "status") + .formParam("Filters.Filter.1.Values.Value.1", "retained") + .when().post("/").then().statusCode(200) + .body(containsString("" + dbi + "")) + .body(containsString("retained")) + .body(not(containsString("active"))); + String arn = backupsOf(dbi, SOURCE_REGION).getString("**.find { it.name() == 'DBInstanceAutomatedBackupsArn' }"); + + query("RestoreDBInstanceToPointInTime") + .formParam("SourceDbiResourceId", dbi) + .formParam("TargetDBInstanceIdentifier", "ab-restored") + .formParam("UseLatestRestorableTime", "true") + .when().post("/").then().statusCode(200) + .body(containsString("ab-restored")); + query("RestoreDBInstanceToPointInTime") + .formParam("SourceDBInstanceAutomatedBackupsArn", arn) + .formParam("TargetDBInstanceIdentifier", "ab-by-arn") + .formParam("UseLatestRestorableTime", "true") + .when().post("/").then().statusCode(200); + query("RestoreDBInstanceToPointInTime") + .formParam("SourceDbiResourceId", dbi) + .formParam("TargetDBInstanceIdentifier", "ab-too-late") + .formParam("RestoreTime", Instant.now().plusSeconds(3600).toString()) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidRestoreFault")); + + query("DeleteDBInstanceAutomatedBackup").formParam("DBInstanceAutomatedBackupsArn", arn) + .when().post("/").then().statusCode(200) + .body(containsString("deleting")) + .body(containsString("" + dbi + "")); + query("DescribeDBInstanceAutomatedBackups").formParam("DbiResourceId", dbi) + .when().post("/").then().statusCode(404); + } + + @Test + void aPlainDeleteRemovesTheBackups() { + createInstance("ab-gone"); + String dbi = dbiResourceId("ab-gone"); + query("DeleteDBInstance").formParam("DBInstanceIdentifier", "ab-gone") + .formParam("SkipFinalSnapshot", "true") + .when().post("/").then().statusCode(200); + + query("DescribeDBInstanceAutomatedBackups").formParam("DbiResourceId", dbi) + .when().post("/").then().statusCode(404) + .body(containsString("DBInstanceAutomatedBackupNotFound")); + query("RestoreDBInstanceToPointInTime") + .formParam("SourceDbiResourceId", dbi) + .formParam("TargetDBInstanceIdentifier", "ab-restored") + .formParam("UseLatestRestorableTime", "true") + .when().post("/").then().statusCode(404); + } + + @Test + void replicationListsAReplicaInTheDestinationUntilItStops() { + createInstance("ab-src"); + String dbi = dbiResourceId("ab-src"); + String sourceArn = "arn:aws:rds:" + SOURCE_REGION + ":000000000000:db:ab-src"; + String replicaArn = "arn:aws:rds:" + DESTINATION_REGION + ":000000000000:auto-backup:ab-" + dbi.substring(3); + + query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", sourceArn) + .formParam("BackupRetentionPeriod", "10") + .when().post("/").then().statusCode(200) + .body(containsString("replicating")) + .body(containsString("" + replicaArn + "")) + .body(containsString("10")) + .body(containsString("" + SOURCE_REGION + "")); + query("DescribeDBInstances").formParam("DBInstanceIdentifier", "ab-src") + .when().post("/").then().statusCode(200) + .body(containsString("" + + "" + replicaArn + "")); + query("DescribeDBInstanceAutomatedBackups", DESTINATION_REGION) + .formParam("DBInstanceAutomatedBackupsArn", replicaArn) + .when().post("/").then().statusCode(200) + .body(containsString("replicating")); + query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", sourceArn) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidDBInstanceAutomatedBackupState")); + query("DeleteDBInstanceAutomatedBackup", DESTINATION_REGION).formParam("DBInstanceAutomatedBackupsArn", replicaArn) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidDBInstanceAutomatedBackupState")); + + query("StopDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", sourceArn) + .when().post("/").then().statusCode(200) + .body(containsString("retained")); + query("DescribeDBInstances").formParam("DBInstanceIdentifier", "ab-src") + .when().post("/").then().statusCode(200) + .body(containsString("")); + query("StopDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", sourceArn) + .when().post("/").then().statusCode(400) + .body(containsString("not replicating to the current region")); + + // A stopped replica does not stand in the way of starting again. + query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", sourceArn) + .when().post("/").then().statusCode(200) + .body(containsString("replicating")); + query("StopDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", sourceArn) + .when().post("/").then().statusCode(200); + query("DeleteDBInstanceAutomatedBackup", DESTINATION_REGION).formParam("DBInstanceAutomatedBackupsArn", replicaArn) + .when().post("/").then().statusCode(200); + } + + @Test + void aRestoreFromAReplicaIsCheckedAgainstTheReplicasWindow() { + createInstance("ab-src"); + String dbi = dbiResourceId("ab-src"); + Instant sourceEarliest = Instant.parse(backupsOf(dbi, SOURCE_REGION) + .getString("**.find { it.name() == 'EarliestTime' }")); + String replicaArn = query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:rds:" + SOURCE_REGION + ":000000000000:db:ab-src") + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("**.find { it.name() == 'DBInstanceAutomatedBackupsArn' }"); + Instant replicaStart = Instant.parse(backupsOf(dbi, DESTINATION_REGION) + .getString("**.find { it.name() == 'EarliestTime' }")); + Instant beforeReplica = replicaStart.minusNanos(1); + assertTrue(beforeReplica.isAfter(sourceEarliest), + "the source must have been restorable before the replica started"); + + // Inside the source's window, but before the replica's. + query("RestoreDBInstanceToPointInTime", DESTINATION_REGION) + .formParam("SourceDBInstanceAutomatedBackupsArn", replicaArn) + .formParam("TargetDBInstanceIdentifier", "ab-restored") + .formParam("RestoreTime", beforeReplica.toString()) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidRestoreFault")); + query("RestoreDBInstanceToPointInTime", DESTINATION_REGION) + .formParam("SourceDBInstanceAutomatedBackupsArn", replicaArn) + .formParam("TargetDBInstanceIdentifier", "ab-restored") + .formParam("RestoreTime", replicaStart.toString()) + .when().post("/").then().statusCode(200); + + query("DeleteDBInstance", DESTINATION_REGION).formParam("DBInstanceIdentifier", "ab-restored") + .formParam("SkipFinalSnapshot", "true").when().post("/").then().statusCode(200); + query("StopDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:rds:" + SOURCE_REGION + ":000000000000:db:ab-src") + .when().post("/").then().statusCode(200); + query("DeleteDBInstanceAutomatedBackup", DESTINATION_REGION).formParam("DBInstanceAutomatedBackupsArn", replicaArn) + .when().post("/").then().statusCode(200); + } + + @Test + void replicationNeedsALiveSourceInAnotherRegion() { + createInstance("ab-src"); + query("StartDBInstanceAutomatedBackupsReplication", SOURCE_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:rds:" + SOURCE_REGION + ":000000000000:db:ab-src") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:rds:" + SOURCE_REGION + ":000000000000:db:ab-nosuch") + .when().post("/").then().statusCode(404) + .body(containsString("DBInstanceNotFound")); + // The same identifier in another account's ARN is not this account's instance. + query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:rds:" + SOURCE_REGION + ":111111111111:db:ab-src") + .when().post("/").then().statusCode(404) + .body(containsString("DBInstanceNotFound")); + query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:docdb:" + SOURCE_REGION + ":000000000000:db:ab-src") + .when().post("/").then().statusCode(404) + .body(containsString("DBInstanceNotFound")); + query("StopDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:rds:" + SOURCE_REGION + ":000000000000:db:ab-src") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidDBInstanceState")); + } + + @Test + void aDeletedSourceKeepsItsReplicaAsRetained() { + createInstance("ab-src"); + String dbi = dbiResourceId("ab-src"); + query("StartDBInstanceAutomatedBackupsReplication", DESTINATION_REGION) + .formParam("SourceDBInstanceArn", "arn:aws:rds:" + SOURCE_REGION + ":000000000000:db:ab-src") + .when().post("/").then().statusCode(200); + query("DeleteDBInstance").formParam("DBInstanceIdentifier", "ab-src") + .formParam("SkipFinalSnapshot", "true") + .when().post("/").then().statusCode(200); + + assertEquals("retained", backupsOf(dbi, DESTINATION_REGION) + .getString("**.find { it.name() == 'Status' }")); + query("DeleteDBInstanceAutomatedBackup", DESTINATION_REGION).formParam("DbiResourceId", dbi) + .when().post("/").then().statusCode(200); + } + + @Test + void aClusterDeleteThatKeepsBackupsLeavesARetainedBackupToRestoreFrom() { + query("CreateDBCluster") + .formParam("DBClusterIdentifier", "abc-kept") + .formParam("Engine", "aurora-postgresql") + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123") + .when().post("/").then().statusCode(200); + String resourceId = query("DescribeDBClusters").formParam("DBClusterIdentifier", "abc-kept") + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("**.find { it.name() == 'DbClusterResourceId' }"); + query("DescribeDBClusterAutomatedBackups").formParam("DbClusterResourceId", resourceId) + .when().post("/").then().statusCode(404) + .body(containsString("DBClusterAutomatedBackupNotFoundFault")); + query("DeleteDBClusterAutomatedBackup").formParam("DbClusterResourceId", resourceId) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidDBClusterAutomatedBackupStateFault")); + + query("DeleteDBCluster").formParam("DBClusterIdentifier", "abc-kept") + .formParam("SkipFinalSnapshot", "true").formParam("DeleteAutomatedBackups", "false") + .when().post("/").then().statusCode(200); + query("DescribeDBClusterAutomatedBackups").formParam("DBClusterIdentifier", "abc-kept") + .when().post("/").then().statusCode(200) + .body("DescribeDBClusterAutomatedBackupsResponse.DescribeDBClusterAutomatedBackupsResult" + + ".DBClusterAutomatedBackups.DBClusterAutomatedBackup.Status", equalTo("retained")) + .body(containsString("" + resourceId + "")) + .body(containsString("arn:aws:rds:" + SOURCE_REGION + + ":000000000000:cluster-auto-backup:" + resourceId + "")); + + query("RestoreDBClusterToPointInTime") + .formParam("DBClusterIdentifier", "abc-restored") + .formParam("SourceDbClusterResourceId", resourceId) + .formParam("UseLatestRestorableTime", "true") + .when().post("/").then().statusCode(200) + .body(containsString("abc-restored")); + + query("DeleteDBClusterAutomatedBackup").formParam("DbClusterResourceId", resourceId) + .when().post("/").then().statusCode(200) + .body(containsString("deleting")); + query("DeleteDBClusterAutomatedBackup").formParam("DbClusterResourceId", resourceId) + .when().post("/").then().statusCode(404) + .body(containsString("DBClusterAutomatedBackupNotFoundFault")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsPointInTimeRestoreIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsPointInTimeRestoreIntegrationTest.java index 5d3d284c7c..07d1587519 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsPointInTimeRestoreIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsPointInTimeRestoreIntegrationTest.java @@ -185,6 +185,49 @@ class RdsPointInTimeRestoreIntegrationTest { } } + @Test + void aDeletedInstanceRestoresFromTheBackupItKeptWithItsData() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String source = "pitr-kept-" + suffix; + String target = "pitr-back-" + suffix; + + query("CreateDBInstance") + .formParam("DBInstanceIdentifier", source) + .formParam("Engine", "postgres") + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123") + .formParam("DBName", "appdb") + .formParam("DBInstanceClass", "db.t3.micro") + .formParam("AllocatedStorage", "20") + .when().post("/").then().statusCode(200); + waitForDb(source); + DbInstance sourceInstance = rdsService.getDbInstance(source); + psql(sourceInstance.getContainerId(), "CREATE TABLE marker(v text); INSERT INTO marker VALUES ('kept-row');"); + String dbiResourceId = sourceInstance.getDbiResourceId(); + + // The source's container goes with the delete, so the restore can only copy what the + // retained backup saved. + query("DeleteDBInstance") + .formParam("DBInstanceIdentifier", source) + .formParam("SkipFinalSnapshot", "true") + .formParam("DeleteAutomatedBackups", "false") + .when().post("/").then().statusCode(200); + query("RestoreDBInstanceToPointInTime") + .formParam("SourceDbiResourceId", dbiResourceId) + .formParam("TargetDBInstanceIdentifier", target) + .formParam("UseLatestRestorableTime", "true") + .when().post("/").then().statusCode(200) + .body(containsString("appdb")); + waitForDb(target); + assertEquals("kept-row", psql(rdsService.getDbInstance(target).getContainerId(), + "SELECT v FROM marker;").trim()); + + query("DeleteDBInstance").formParam("DBInstanceIdentifier", target) + .when().post("/").then().statusCode(200); + query("DeleteDBInstanceAutomatedBackup").formParam("DbiResourceId", dbiResourceId) + .when().post("/").then().statusCode(200); + } + @Test void sourceWithoutDbNameRestoresItsDefaultDatabaseUnderTheRequestedName() throws Exception { String suffix = Long.toString(System.nanoTime(), 36); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java index 680c72973d..3a64ebcdb2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java @@ -574,7 +574,7 @@ class RdsQueryHandlerTest { when(service.getDbInstance("mydb", null)).thenReturn(makeInstance("mydb")); doThrow(new AwsException("InvalidParameterCombination", "Cannot delete protected DB Instance, please disable deletion protection and try again.", 400)) - .when(service).deleteDbInstance("mydb", null); + .when(service).deleteDbInstance("mydb", null, true); MultivaluedMap p = params(); p.add("DBInstanceIdentifier", "mydb"); @@ -790,14 +790,14 @@ class RdsQueryHandlerTest { verify(service).listDbInstances(null, "us-west-2"); verify(service).getDbInstance("mydb", "us-west-2"); - verify(service).deleteDbInstance("mydb", "us-west-2"); + verify(service).deleteDbInstance("mydb", "us-west-2", true); verify(service).modifyDbInstance( eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), eq("us-west-2"), isNull(), any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull(), isNull()); verify(service).rebootDbInstance("mydb", "us-west-2"); verify(service).listDbClusters(null, "us-west-2"); verify(service).getDbCluster("mycluster", "us-west-2"); - verify(service).deleteDbCluster("mycluster", "us-west-2"); + verify(service).deleteDbCluster("mycluster", "us-west-2", true); verify(service).modifyDbCluster("mycluster", null, null, null, null, null, null, null, null, "us-west-2"); }