Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
rds: promote the target reader on FailoverDBCluster (data-plane) (#1610)
kiran01bmab6036b75bea
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c5cef93a..998e4b7a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **RDS — `FailoverDBCluster` promotes replicated PostgreSQL readers** — with `MINISTACK_RDS_PG_CLUSTER_REPLICATION=1`, failover now calls `pg_promote()` on the selected hot standby, makes it the writer endpoint, and re-clones the former writer with `pg_basebackup` as a read-only standby. Metadata changes only after promotion succeeds; shared-container clusters retain their existing metadata-only behavior. Contributed by @kiran01bm.### Fixed- **CloudFormation — a failed update keeps the pre-existing resources when it rolls back** — the rollback of a failed stack update deleted every resource the run had touched, and a run touches every resource in the template: unchanged resources and resources updated in place went down together with what the update had actually created, while the restored stack still recorded them. The rollback now deletes only what the update created and replacements under a new physical id; a resource that kept its physical id is left standing. Not covered: an in-place change is not reverted, and a replacement's old resource, already removed by the update, is not recreated. Contributed by @iot-rocket.- **CloudFormation — `DeleteChangeSet` of a change set that does not exist succeeds** — it answered `ChangeSetNotFound` (404), and the response of a successful delete carried no `DeleteChangeSetResult` element, so boto3 could not parse it at all. The CDK removes a possible leftover `cdk-deploy-change-set` before every deploy of an existing stack, addresses the stack by its ARN, and only tolerates `ChangeSetNotFoundException`, so every `cdk deploy` of an already deployed stack aborted with `ChangeSet [cdk-deploy-change-set] does not exist`. A real account answers that delete with a plain success; the stack is now resolved by name or stack ID first, and a stack that does not exist is still a `ValidationError`. Contributed by @iot-rocket.diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 0acb5325..51d33a33 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -152,6 +152,7 @@ _MYSQL_BINLOG_RETENTION_SECONDS = 604800 # 7 days# convention as the MySQL replication user above._PG_REPLICATION_USER = "rdsrepladmin"_PG_REPLICATION_PASSWORD = "rdsrepladmin-local-password"+_PG_FAILOVER_TIMEOUT_SECONDS = 60# Runs on the writer container (docker exec). Idempotently creates the# replication role and opens pg_hba.conf for remote replication connections:@@ -6760,21 +6761,136 @@ def _stop_db_cluster(p):f"<StopDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></StopDBClusterResult>")+def _promote_pg_reader(instance):+ """Promote a PostgreSQL standby and wait for recovery to finish."""+ docker_client = _get_docker()+ container_id = instance.get("_docker_container_id")+ if not docker_client or not container_id:+ return False+ try:+ container = docker_client.containers.get(container_id)+ exit_code, output = container.exec_run([+ "sh", "-c",+ "psql -v ON_ERROR_STOP=1 --username \"$POSTGRES_USER\" "+ "--dbname \"$POSTGRES_DB\" -Atc "+ f"\"SELECT pg_promote(true, {_PG_FAILOVER_TIMEOUT_SECONDS}) "+ "AND NOT pg_is_in_recovery()\"",+ ])+ except Exception as e:+ logger.warning("RDS: failed to promote reader %s: %s",+ instance.get("DBInstanceIdentifier"), e)+ return False+ promoted = output.decode(errors="replace").strip().lower() if isinstance(output, bytes) else str(output).strip().lower()+ if exit_code != 0 or promoted not in ("t", "true"):+ logger.warning("RDS: reader promotion for %s exited %s: %s",+ instance.get("DBInstanceIdentifier"), exit_code, promoted)+ return False+ return True+++def _adopt_promoted_pg_writer(cluster, target):+ """Make a promoted reader's container the cluster-owned writer compute."""+ old = {+ "container_id": cluster.get("_shared_container_id"),+ "volume_name": cluster.get("_shared_volume_name"),+ "host_port": cluster.get("_shared_host_port"),+ "internal_address": cluster.get("_shared_internal_address"),+ "internal_port": cluster.get("_shared_internal_port"),+ }+ cluster.update({+ "_shared_container_id": target.get("_docker_container_id"),+ "_shared_volume_name": target.get("_docker_volume_name"),+ "_shared_host_port": target.get("_HostPort"),+ "_shared_internal_address": target.get("_internal_address"),+ "_shared_internal_port": target.get("_internal_port"),+ "_shared_container_ready": True,+ "_pg_replication_source_ready": True,+ })+ # Keep the stable cluster address where Docker DNS is available. The+ # promoted container already has its instance endpoint for host-mode use.+ endpoint = copy.deepcopy(target.get("Endpoint") or cluster.get("_shared_endpoint"))+ cluster["_shared_endpoint"] = endpoint+ target.pop("_pg_standby", None)+ target["_shared_cluster_id"] = cluster["DBClusterIdentifier"]+ return old+++def _reclone_old_pg_writer(cluster, instance, old_compute):+ """Replace the former writer with a fresh base-backup standby.++ MiniStack readers are disposable compute, like Aurora readers. Re-cloning+ with the existing pg_basebackup bootstrap is slower than pg_rewind but+ avoids a second recovery implementation and guarantees the former writer+ follows the complete promoted timeline.+ """+ instance.pop("_shared_cluster_id", None)+ instance.update({+ "_pg_standby": True,+ "_docker_container_id": old_compute.get("container_id"),+ "_docker_volume_name": old_compute.get("volume_name"),+ "_HostPort": old_compute.get("host_port"),+ "_internal_address": old_compute.get("internal_address"),+ "_internal_port": old_compute.get("internal_port"),+ "DBInstanceStatus": "rebooting",+ })+ if not _revive_pg_reader(instance["DBInstanceIdentifier"], instance, cluster):+ return False+ deadline = time.time() + _PG_FAILOVER_TIMEOUT_SECONDS+ while time.time() < deadline:+ if instance.get("DBInstanceStatus") == "available":+ return True+ if instance.get("DBInstanceStatus") in ("failed", "stopped"):+ return False+ time.sleep(0.25)+ return False++def _failover_db_cluster(p):with _shared_container_lock:- return _failover_db_cluster_impl(p)+ response, reclone = _failover_db_cluster_impl(p)+ if reclone is None:+ return response+ # The former writer is re-cloned outside the lock. Its readiness worker+ # takes ``_shared_container_lock`` to provision the replication source+ # and to publish the member ``available``, so waiting for that landing+ # while holding the lock could only ever time out.+ cluster, old_writer, old_compute = reclone+ recloned = old_writer is not None and _reclone_old_pg_writer(+ cluster, old_writer, old_compute,+ )+ cluster["Status"] = "available"+ _sync_cluster_endpoints(cluster)+ if not recloned:+ # Promotion cannot safely be undone after the new timeline accepts+ # writes. Keep metadata pointed at the real writer and fail loudly.+ return _error(+ "InternalFailure",+ "Failed to create a standby after failing over DB cluster "+ f"{cluster['DBClusterIdentifier']}.",+ 500,+ )+ return _failover_db_cluster_response(cluster)+++def _failover_db_cluster_response(cluster):+ response_cluster = copy.deepcopy(cluster)+ response_cluster["Status"] = "failing-over"+ return _xml(200, "FailoverDBClusterResponse",+ f"<FailoverDBClusterResult><DBCluster>{_cluster_xml(response_cluster)}</DBCluster></FailoverDBClusterResult>")def _failover_db_cluster_impl(p):"""Force an intra-cluster failover: promote a reader member to writer.- Metadata-only for now, mirroring ``_failover_global_cluster``: the member- ``IsClusterWriter`` flags flip and the response reports the transitional- ``failing-over`` cluster status (the stored status stays ``available``,- as a follow-up DescribeDBClusters observes on AWS once the failover- completes). Data-plane promotion of a replicating reader container is a- follow-up (#1325); with today's shared-container clusters every member- already points at the same process, so there is nothing to re-point.+ Runs under ``_shared_container_lock``. Returns ``(response, reclone)``:+ ``reclone`` is ``None`` when the response is final, or the+ ``(cluster, old_writer, old_compute)`` the caller must re-clone once+ the lock is released, in which case ``response`` is ``None``.++ Replicating Aurora PostgreSQL readers are promoted in PostgreSQL before+ their metadata changes. The former writer is then re-cloned as a standby.+ Shared-container and control-plane-only clusters retain the metadata-only+ behavior because every member already addresses the same process.Error fidelity notes (wire codes from the RDS service model):- unknown cluster: ``DBClusterNotFoundFault`` (404)@@ -6789,10 +6905,10 @@ def _failover_db_cluster_impl(p):if not cluster:wrong_region = _invalid_cluster_identifier_error(cluster_id)if wrong_region:- return wrong_region- return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404)+ return wrong_region, None+ return _error("DBClusterNotFoundFault", f"DBCluster {cluster_id} not found.", 404), Noneif switch_error := _mysql_global_writer_switch_mutation_error(cluster):- return switch_error+ return switch_error, Nonecluster_id = cluster.get("DBClusterIdentifier", cluster_id)status = cluster.get("Status")if status != "available":@@ -6801,7 +6917,7 @@ def _failover_db_cluster_impl(p):f"DbCluster {cluster_id} is in {status} state but expected it to ""be one of available.",400,- )+ ), Noneif cluster.get("_shared_legacy_migration_in_progress") or cluster.get("_shared_legacy_migration_blocked",):@@ -6815,7 +6931,7 @@ def _failover_db_cluster_impl(p):f"Cannot failover DB cluster {cluster_id} while legacy shared-""storage migration is in progress.",400,- )+ ), Nonemembers = cluster.get("DBClusterMembers", [])readers = [m for m in members if not m.get("IsClusterWriter")]@@ -6829,27 +6945,27 @@ def _failover_db_cluster_impl(p):if not target:if not _resolve_instance(target_id):return _error(- "DBInstanceNotFound", f"DBInstance {target_id} not found.", 404)+ "DBInstanceNotFound", f"DBInstance {target_id} not found.", 404), Nonereturn _error("InvalidDBInstanceState",f"DBInstance {target_id} is not a member of DB cluster "f"{cluster_id}.",400,- )+ ), Noneif target.get("IsClusterWriter"):return _error("InvalidDBInstanceState",f"DBInstance {target_id} is already the writer of DB cluster "f"{cluster_id}; specify a reader instance to promote.",400,- )+ ), Nonetarget_instance = _resolve_instance(target_id)if target_instance is None:# A member with no backing instance record cannot happen today# (deletion unregisters the member synchronously), but promoting# a phantom would strand the cluster; refuse defensively.return _error(- "DBInstanceNotFound", f"DBInstance {target_id} not found.", 404)+ "DBInstanceNotFound", f"DBInstance {target_id} not found.", 404), Noneif target_instance.get("DBInstanceStatus") != "available":return _error("InvalidDBInstanceState",@@ -6857,7 +6973,7 @@ def _failover_db_cluster_impl(p):f"{target_instance.get('DBInstanceStatus')} state but expected ""it to be one of available.",400,- )+ ), Noneelse:# AWS promotes the best candidate from the lowest promotion tier;# within a tier Ministack keeps member order (no instance sizing).@@ -6875,19 +6991,41 @@ def _failover_db_cluster_impl(p):f"Cannot failover DB cluster {cluster_id} because it has no ""available reader instance to promote.",400,- )+ ), Nonetarget = candidates[0]target_id = target["DBInstanceIdentifier"]+ old_writer_member = next((m for m in members if m.get("IsClusterWriter")), None)+ old_writer = _resolve_instance(old_writer_member.get("DBInstanceIdentifier")) if old_writer_member else None+ target_instance = _resolve_instance(target_id)+ data_plane_failover = bool(+ target_instance+ and target_instance.get("_pg_standby")+ and _pg_cluster_replication_enabled(cluster)+ )+ if data_plane_failover:+ cluster["Status"] = "failing-over"+ target_instance["DBInstanceStatus"] = "rebooting"+ if not _promote_pg_reader(target_instance):+ cluster["Status"] = "available"+ target_instance["DBInstanceStatus"] = "available"+ return _error(+ "InternalFailure",+ f"Failed to promote reader {target_id} for DB cluster {cluster_id}.",+ 500,+ ), None+ old_compute = _adopt_promoted_pg_writer(cluster, target_instance)+for member in members:member["IsClusterWriter"] = (member.get("DBInstanceIdentifier") == target_id)- response_cluster = copy.deepcopy(cluster)- response_cluster["Status"] = "failing-over"- return _xml(200, "FailoverDBClusterResponse",- f"<FailoverDBClusterResult><DBCluster>{_cluster_xml(response_cluster)}</DBCluster></FailoverDBClusterResult>")+ if data_plane_failover:+ target_instance["DBInstanceStatus"] = "available"+ return None, (cluster, old_writer, old_compute)++ return _failover_db_cluster_response(cluster), None# ---------------------------------------------------------------------------diff --git a/tests/test_rds.py b/tests/test_rds.pyindex f9ebb065..6a0c2520 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -12069,8 +12069,10 @@ def _pg_repl_fake_docker(m, monkeypatch, member_ips, exec_calls, removed):def reload(self):pass- def exec_run(self, _cmd):+ def exec_run(self, cmd):exec_calls.append(self.name)+ if "pg_promote" in str(cmd):+ return 0, b"t\n"return 0, b""def start(self):@@ -12127,6 +12129,61 @@ def _pg_repl_fake_docker(m, monkeypatch, member_ips, exec_calls, removed):}+def test_rds_pg_failover_promotes_and_reclones_writer(monkeypatch):+ """The data-plane failover swaps compute only after promotion succeeds."""+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch,+ {"failover-pg-reader": "10.0.0.7", "failover-pg-writer": "10.0.0.8"},+ exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)+ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "failover-pg",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("failover-pg-writer", "failover-pg-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "failover-pg",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("failover-pg")+ assert _poll_until(lambda: cluster["Status"] == "available")++ status, _, body = m._failover_db_cluster({+ "DBClusterIdentifier": "failover-pg",+ "TargetDBInstanceIdentifier": "failover-pg-reader",+ })+ assert status == 200+ assert b"<Status>failing-over</Status>" in body+ assert cluster["Status"] == "available"+ assert _cluster_writer_flags(cluster) == {+ "failover-pg-writer": False,+ "failover-pg-reader": True,+ }+ promoted = m._instances.get("failover-pg-reader")+ standby = m._instances.get("failover-pg-writer")+ assert "_pg_standby" not in promoted+ assert standby["_pg_standby"] is True+ assert standby["DBInstanceStatus"] == "available"+ assert cluster["_shared_container_id"] == promoted["_docker_container_id"]+ assert cluster["ReaderEndpoint"] == standby["Endpoint"]["Address"]+ assert any("failover-pg-reader" in name for name in exec_calls)+ finally:+ m._instances.clear()+ m._clusters.clear()++def test_rds_pg_two_replicating_readers_provision_source_once(monkeypatch):"""Two readers on one cluster: the writer is provisioned exactly once,ReaderEndpoint selection is deterministic (member order), and a standby@@ -13324,6 +13381,53 @@ def test_aurora_pg_replicating_reader_live(rds):assert excinfo.value.pgcode == "25006"+ not _PG_REPLICATION_LIVE,+ reason="DOCKER_NETWORK and MINISTACK_RDS_PG_CLUSTER_REPLICATION not set "+ "-- live Aurora PostgreSQL replication",+)+def test_aurora_pg_failover_promotes_data_plane(rds):+ """Failover moves writes to the reader and re-clones the old writer."""+ with _live_pg_cluster(rds) as (cluster_id, writer_id, reader_id, writer, _reader, _cluster):+ with _pg_connect(writer["Endpoint"]) as conn:+ conn.autocommit = True+ with conn.cursor() as cursor:+ cursor.execute("CREATE TABLE failover_rows (id INT PRIMARY KEY)")+ cursor.execute("INSERT INTO failover_rows VALUES (1)")++ response = rds.failover_db_cluster(+ DBClusterIdentifier=cluster_id,+ TargetDBInstanceIdentifier=reader_id,+ )["DBCluster"]+ assert response["Status"] == "failing-over"++ cluster = rds.describe_db_clusters(+ DBClusterIdentifier=cluster_id,+ )["DBClusters"][0]+ assert cluster["Status"] == "available"+ assert {+ member["DBInstanceIdentifier"]: member["IsClusterWriter"]+ for member in cluster["DBClusterMembers"]+ } == {writer_id: False, reader_id: True}++ writer_endpoint = {"Address": cluster["Endpoint"], "Port": cluster["Port"]}+ with _pg_connect(writer_endpoint) as conn:+ conn.autocommit = True+ with conn.cursor() as cursor:+ cursor.execute("SELECT id FROM failover_rows")+ assert cursor.fetchall() == [(1,)]+ cursor.execute("INSERT INTO failover_rows VALUES (2)")++ reader_endpoint = {"Address": cluster["ReaderEndpoint"], "Port": cluster["Port"]}+ import psycopg2++ with _pg_connect(reader_endpoint) as conn:+ conn.autocommit = True+ with conn.cursor() as cursor, pytest.raises(psycopg2.Error) as excinfo:+ cursor.execute("INSERT INTO failover_rows VALUES (3)")+ assert excinfo.value.pgcode == "25006"++# ---------------------------------------------------------------------------# RDS Proxy (control plane)# ---------------------------------------------------------------------------