Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(rds): emulate Aurora MySQL replication (#1157)

Ian Oberst46d65bc40834
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 692be478..c87b9b01 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -87,6 +87,17 @@ _docker = None
_ministack_network = None
_shared_container_lock = threading.RLock()
+_MYSQL_REPLICATION_USER = "rdsrepladmin"
+_MYSQL_REPLICATION_PASSWORD = "ministack-rds-replication"
+_MYSQL_CONTROL_USER = "rdsadmin"
+_MYSQL_CONTROL_PASSWORD = "ministack-rds-control"
+_MYSQL_REPLICATION_RETRY_ATTEMPTS = 60
+_MYSQL_REPLICATION_RETRY_INTERVAL = 1
+_MYSQL_BINLOG_RETENTION_SECONDS = max(
+ 1,
+ int(os.environ.get("RDS_MYSQL_BINLOG_RETENTION_SECONDS", "604800")),
+)
+
# Aurora MySQL versions are the creatable set returned by AWS RDS as of
# 2026-07-09. Refresh with:
# aws rds describe-db-engine-versions --engine aurora-mysql \
@@ -180,6 +191,13 @@ def restore_state(data):
for key in list(_clusters._data):
cluster = _clusters._data[key]
cluster["_shared_container_id"] = None
+ cluster.pop("_mysql_replication_retry_marker", None)
+ if cluster.get("_mysql_replication_source_arn"):
+ # A respawned MySQL container gets a new hostname, while the
+ # persisted replica repository and relay-log names belong to the
+ # previous container. Recover the channel from the durable GTID
+ # execution set before relinking it to the restored source.
+ cluster["_mysql_replication_reset_pending"] = True
if cluster.get("_shared_endpoint"):
cluster["_shared_container_ready"] = False
_subnet_groups.update(data.get("subnet_groups", {}))
@@ -189,6 +207,14 @@ def restore_state(data):
_db_cluster_snapshots.update(data.get("db_cluster_snapshots", {}))
_option_groups.update(data.get("option_groups", {}))
_global_clusters.update(data.get("global_clusters", {}))
+ # Persistence contains every account, while AccountScopedDict.values()
+ # intentionally exposes only the active request account. Reconcile the
+ # raw persisted records so a warm boot cannot leave secondary metadata
+ # stale merely because another account happened to be active at startup.
+ for global_cluster in _global_clusters._data.values():
+ writer = _global_cluster_writer_cluster(global_cluster)
+ if writer and _aurora_mysql_8_replication_enabled(writer):
+ _sync_global_mysql_credentials(writer, global_cluster)
_tags.update(data.get("tags", {}))
if "port_counter" in data:
_port_counter[0] = data["port_counter"]
@@ -252,6 +278,15 @@ def restore_state(data):
else:
standalone.append((account_id, region, db_id, inst))
+ # A global secondary keeps applying source GTIDs after its final DB
+ # instance is deleted. There is no instance record to pull an empty
+ # secondary into ``shared_groups`` on warm boot, so retain the explicit
+ # headless-applier intent as its own restore work item.
+ for key, cluster in list(_clusters._data.items()):
+ account_id, region, cluster_id = key
+ if cluster.get("_mysql_headless_applier_required"):
+ shared_groups.setdefault((account_id, region, cluster_id), [])
+
# A pre-namespace standalone named ``cluster-<id>`` used the same Docker
# name now reserved for cluster ``<id>``. Remove those legacy containers
# before any asynchronous cluster runner can claim the name, and mark the
@@ -293,7 +328,7 @@ def restore_state(data):
cluster = _clusters.get_scoped(
account_id or get_account_id(), region, cluster_id,
)
- if cluster:
+ if cluster and members:
# Publish the restore/migration gate before the daemon starts. A
# create arriving immediately after restore_state() must not start
# fresh cluster storage before the writer volume is adopted.
@@ -335,14 +370,14 @@ def restore_state(data):
),
None,
)
- writer = member_by_id.get(writer_id) or members[0]
+ writer = member_by_id.get(writer_id) or (members[0] if members else None)
legacy_volumes = {
member.get("_docker_volume_name")
for member in members
if member.get("_docker_volume_name")
}
adopted_volume = cluster.get("_shared_volume_name")
- if not adopted_volume:
+ if not adopted_volume and writer is not None:
adopted_volume = writer.get("_docker_volume_name")
if adopted_volume:
cluster["_shared_volume_name"] = adopted_volume
@@ -466,11 +501,19 @@ def restore_state(data):
and _instances.get(member_id) is member_by_id[member_id]
for member_id in original_member_ids
)
+ headless_applier_still_required = bool(
+ not original_member_ids
+ and not current_member_ids
+ and cluster.get("_mysql_headless_applier_required")
+ )
if (
current_cluster is not cluster
or int(cluster.get("_shared_container_epoch", 0))
!= restore_epoch
- or not original_member_still_attached
+ or not (
+ original_member_still_attached
+ or headless_applier_still_required
+ )
):
if current_cluster is cluster:
cluster.pop(
@@ -515,15 +558,28 @@ def restore_state(data):
if pending_rotation
else cluster.get("_MasterUserPassword", "password")
)
+ readiness_user = cluster.get("MasterUsername", "admin")
+ if _mysql_replication_secondary(cluster):
+ # A fresh secondary volume has only the image's local
+ # root account. Once replication setup creates the
+ # non-binlogged control account, persisted restarts use
+ # that stable credential instead of the replicated
+ # application administrator.
+ readiness_user = "root"
+ if cluster.get("_mysql_control_user_ready"):
+ readiness_user = _MYSQL_CONTROL_USER
+ readiness_password = _MYSQL_CONTROL_PASSWORD
authenticated_ready = _wait_for_database_ready(
result.get("readiness_host")
or cluster["_shared_endpoint"]["Address"],
result.get("readiness_port")
or cluster["_shared_endpoint"]["Port"],
cluster.get("Engine", "aurora-postgresql"),
- cluster.get("MasterUsername", "admin"),
+ readiness_user,
readiness_password,
- cluster.get("DatabaseName") or "mydb",
+ None
+ if _mysql_replication_secondary(cluster)
+ else cluster.get("DatabaseName") or "mydb",
_container_alive,
)
with _shared_container_lock:
@@ -551,11 +607,12 @@ def restore_state(data):
cluster.pop(
"_pending_master_password_rotation", None,
)
+ _sync_global_mysql_credentials(cluster)
if authenticated_ready:
cluster["_shared_storage_initialized"] = True
if authenticated_ready and _is_mysql_engine(
cluster.get("Engine", ""),
- ):
+ ) and not _mysql_replication_secondary(cluster):
_grant_mysql_master_user_privileges(
result.get("readiness_host")
or cluster["_shared_endpoint"]["Address"],
@@ -566,6 +623,10 @@ def restore_state(data):
cluster_id,
)
cluster["_shared_container_ready"] = authenticated_ready
+ if authenticated_ready and _aurora_mysql_8_replication_enabled(
+ cluster,
+ ):
+ _configure_or_defer_mysql_replication(cluster_id, cluster)
status = "available" if authenticated_ready else "failed"
for current_member in cluster.get(
"DBClusterMembers", [],
@@ -729,6 +790,14 @@ def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):
)
if not image:
return {"started": False, "failed": False, "readiness_host": None, "readiness_port": None}
+ if _mysql_replication_secondary(cluster):
+ # The writer's retained GTID history must be the sole creator of the
+ # application database and master user on a fresh global secondary.
+ # Letting both image entrypoints create them assigns different local
+ # GTIDs and makes replay stop on duplicate CREATE USER / DATABASE.
+ env = dict(env)
+ for key in ("MYSQL_DATABASE", "MYSQL_USER", "MYSQL_PASSWORD"):
+ env.pop(key, None)
container_name = _rds_cluster_docker_name(cluster_id)
if remove_stale:
@@ -775,6 +844,20 @@ def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):
"region": get_region(),
},
)
+ if _prepare_mysql_gtid_history(cluster):
+ server_id = _mysql_replication_server_id(
+ get_account_id(),
+ get_region(),
+ cluster_id,
+ )
+ container_kwargs["command"] = [
+ f"--server-id={server_id}",
+ "--log-bin=mysql-bin",
+ "--gtid-mode=ON",
+ "--enforce-gtid-consistency=ON",
+ "--log-replica-updates",
+ f"--binlog-expire-logs-seconds={_MYSQL_BINLOG_RETENTION_SECONDS}",
+ ]
if ms_network:
container_kwargs["network"] = ms_network
# Aurora storage belongs to the cluster, not to any member instance. Use a
@@ -1202,6 +1285,519 @@ def _is_postgres_engine(engine):
return any(e in engine for e in ("postgres", "aurora-postgresql"))
+def _aurora_mysql_8_replication_enabled(cluster):
+ """Return whether this cluster is in the native-replication spike scope."""
+ return (
+ cluster.get("Engine") == "aurora-mysql"
+ and _mysql_community_major_minor(cluster.get("EngineVersion")) == "8.0"
+ )
+
+
+def _prepare_mysql_gtid_history(cluster):
+ """Enable GTID history only before a cluster volume is initialized.
+
+ New Aurora MySQL 8 clusters always start GTID-capable so they can later be
+ attached as a global source without omitting pre-attach transactions. A
+ persisted volume from an older MiniStack release has anonymous history;
+ starting it with GTID enabled would make auto-position appear healthy
+ while leaving that history absent on a fresh secondary.
+ """
+ if not _aurora_mysql_8_replication_enabled(cluster):
+ return False
+ if cluster.get("_mysql_gtid_initialized_at_creation"):
+ return True
+ if cluster.get("_shared_storage_initialized"):
+ return False
+ cluster["_mysql_gtid_initialized_at_creation"] = True
+ return True
+
+
+def _mysql_gtid_history_ready(cluster):
+ return bool(
+ not _aurora_mysql_8_replication_enabled(cluster)
+ or cluster.get("_mysql_gtid_initialized_at_creation")
+ )
+
+
+def _mysql_replication_server_id(account_id, region, cluster_id):
+ """Derive a stable, non-zero MySQL server ID from the cluster scope."""
+ identity = f"{account_id}/{region}/{cluster_id}".encode()
+ return int.from_bytes(hashlib.sha256(identity).digest()[:4], "big") or 1
+
+
+def _global_cluster_member_for_cluster(cluster):
+ global_id = cluster.get("GlobalClusterIdentifier")
+ if not global_id:
+ return None, None
+ global_cluster = _global_clusters.get(global_id)
+ if not global_cluster:
+ return None, None
+ member = next(
+ (
+ item
+ for item in global_cluster.get("GlobalClusterMembers", [])
+ if item.get("DBClusterArn") == cluster.get("DBClusterArn")
+ ),
+ None,
+ )
+ return global_cluster, member
+
+
+def _mysql_replication_secondary(cluster):
+ if not _aurora_mysql_8_replication_enabled(cluster):
+ return False
+ _global_cluster, member = _global_cluster_member_for_cluster(cluster)
+ return bool(member and not member.get("IsWriter"))
+
+
+def _resolve_global_member_cluster(member):
+ parsed = _parse_rds_arn(member.get("DBClusterArn", "")) if member else None
+ if not parsed:
+ return None
+ spec, resource_type, cluster_id = parsed
+ if resource_type != "cluster":
+ return None
+ return _clusters.get_scoped(spec.account_id, spec.region, cluster_id)
+
+
+def _global_cluster_writer_cluster(global_cluster):
+ writer_member = next(
+ (
+ member
+ for member in global_cluster.get("GlobalClusterMembers", [])
+ if member.get("IsWriter")
+ ),
+ None,
+ )
+ return _resolve_global_member_cluster(writer_member)
+
+
+def _sync_global_mysql_credentials(writer, global_cluster=None):
+ """Keep member metadata aligned with credentials replicated from writer."""
+ if global_cluster is None:
+ global_cluster, writer_member = _global_cluster_member_for_cluster(writer)
+ else:
+ writer_member = next(
+ (
+ member
+ for member in global_cluster.get("GlobalClusterMembers", [])
+ if member.get("DBClusterArn") == writer.get("DBClusterArn")
+ ),
+ None,
+ )
+ if not global_cluster or not writer_member or not writer_member.get("IsWriter"):
+ return
+ for member in global_cluster.get("GlobalClusterMembers", []):
+ cluster = _resolve_global_member_cluster(member)
+ if cluster is None or cluster is writer:
+ continue
+ cluster["MasterUsername"] = writer.get("MasterUsername", "admin")
+ cluster["_MasterUserPassword"] = writer.get(
+ "_MasterUserPassword",
+ "password",
+ )
+ cluster["DatabaseName"] = writer.get("DatabaseName")
+ parsed = _parse_rds_arn(cluster.get("DBClusterArn", ""))
+ for cluster_member in cluster.get("DBClusterMembers", []):
+ instance = None
+ if parsed:
+ spec, resource_type, _cluster_id = parsed
+ if resource_type == "cluster":
+ instance = _instances.get_scoped(
+ spec.account_id,
+ spec.region,
+ cluster_member.get("DBInstanceIdentifier"),
+ )
+ if instance is not None:
+ _attach_instance_to_shared_cluster(instance, cluster)
+
+
+def _mysql_cluster_connection(cluster, user, password):
+ import pymysql
+
+ endpoint = cluster.get("_shared_endpoint") or {}
+ host = cluster.get("_shared_internal_address") or endpoint.get("Address")
+ port = cluster.get("_shared_internal_port") or endpoint.get("Port")
+ if not host or not port:
+ return None
+ return pymysql.connect(
+ host=host,
+ port=int(port),
+ user=user,
+ password=password,
+ autocommit=True,
+ connect_timeout=3,
+ )
+
+
+def _mysql_admin_connection(cluster):
+ return _mysql_cluster_connection(
+ cluster,
+ "root",
+ cluster.get("_MasterUserPassword", "password"),
+ )
+
+
+def _mysql_replication_connection(cluster):
+ return _mysql_cluster_connection(
+ cluster,
+ _MYSQL_CONTROL_USER,
+ _MYSQL_CONTROL_PASSWORD,
+ )
+
+
+def _ensure_mysql_control_user(cluster):
+ """Create a local, non-replicated account for replica lifecycle SQL."""
+ if cluster.get("_mysql_control_user_ready"):
+ return True
+ cluster_id = cluster.get("DBClusterIdentifier", "unknown")
+ conn = None
+ cur = None
+ try:
+ conn = _mysql_admin_connection(cluster)
+ if conn is None:
+ return False
+ cur = conn.cursor()
+ cur.execute("SET SESSION sql_log_bin=0")
+ cur.execute(
+ "CREATE USER IF NOT EXISTS %s@'%%' "
+ "IDENTIFIED WITH mysql_native_password BY %s",
+ (_MYSQL_CONTROL_USER, _MYSQL_CONTROL_PASSWORD),
+ )
+ cur.execute(
+ "GRANT RELOAD ON *.* TO %s@'%%'",
+ (_MYSQL_CONTROL_USER,),
+ )
+ cur.execute(
+ "GRANT CONNECTION_ADMIN, REPLICATION_SLAVE_ADMIN, "
+ "SYSTEM_VARIABLES_ADMIN ON *.* TO %s@'%%'",
+ (_MYSQL_CONTROL_USER,),
+ )
+ cur.execute("FLUSH PRIVILEGES")
+ cluster["_mysql_control_user_ready"] = True
+ return True
+ except Exception as e:
+ logger.warning(
+ "RDS: failed to prepare local MySQL control account for %s: %s",
+ cluster_id,
+ e,
+ )
+ return False
+ finally:
+ if cur is not None:
+ cur.close()
+ if conn is not None:
+ conn.close()
+
+
+def _ensure_mysql_replication_user(cluster):
+ """Ensure the internal replication account exists on a writer cluster."""
+ cluster_id = cluster.get("DBClusterIdentifier", "unknown")
+ conn = None
+ cur = None
+ try:
+ conn = _mysql_admin_connection(cluster)
+ if conn is None:
+ return False
+ cur = conn.cursor()
+ cur.execute(
+ "CREATE USER IF NOT EXISTS %s@'%%' "
+ "IDENTIFIED WITH mysql_native_password BY %s",
+ (_MYSQL_REPLICATION_USER, _MYSQL_REPLICATION_PASSWORD),
+ )
+ cur.execute(
+ "GRANT REPLICATION SLAVE ON *.* TO %s@'%%'",
+ (_MYSQL_REPLICATION_USER,),
+ )
+ cur.execute("FLUSH PRIVILEGES")
+ return True
+ except Exception as e:
+ logger.warning(
+ "RDS: failed to prepare MySQL replication source %s: %s",
+ cluster_id,
+ e,
+ )
+ return False
+ finally:
+ if cur is not None:
+ cur.close()
+ if conn is not None:
+ conn.close()
+
+
+def _configure_mysql_replication(cluster_id, cluster):
+ """Configure an Aurora MySQL 8 global member as source or replica.
+
+ Returns True when configuration is complete, False when it should be
+ retried, and None when replication does not apply to this cluster.
+ """
+ if not _aurora_mysql_8_replication_enabled(cluster):
+ return None
+
+ global_cluster, member = _global_cluster_member_for_cluster(cluster)
+ if not global_cluster or not member:
+ return None
+ if not cluster.get("_shared_container_ready"):
+ return False
+ if not _mysql_gtid_history_ready(cluster):
+ cluster["_mysql_replication_blocked_reason"] = "legacy-non-gtid-volume"
+ cluster["_shared_container_ready"] = False
+ for cluster_member in cluster.get("DBClusterMembers", []):
+ instance = _instances.get(
+ cluster_member.get("DBInstanceIdentifier"),
+ )
+ if instance is not None:
+ instance["DBInstanceStatus"] = "failed"
+ logger.error(
+ "RDS: refusing MySQL replication for %s because its initialized "
+ "volume predates GTID-at-creation tracking",
+ cluster_id,
+ )
+ return None
+ if not _ensure_mysql_control_user(cluster):
+ return False
+ cluster.pop("_mysql_replication_blocked_reason", None)
+
+ if member.get("IsWriter"):
+ if not _ensure_mysql_replication_user(cluster):
+ return False
+ for secondary_member in global_cluster.get("GlobalClusterMembers", []):
+ if secondary_member.get("IsWriter"):
+ continue
+ secondary = _resolve_global_member_cluster(secondary_member)
+ if secondary and secondary.get("_shared_container_ready"):
+ secondary_id = secondary.get("DBClusterIdentifier", "unknown")
+ if _configure_mysql_replication(secondary_id, secondary) is False:
+ _schedule_mysql_replication_retry(secondary_id, secondary)
+ return True
+
+ writer_member = next(
+ (
+ item
+ for item in global_cluster.get("GlobalClusterMembers", [])
+ if item.get("IsWriter")
+ ),
+ None,
+ )
+ writer = _resolve_global_member_cluster(writer_member)
+ if (
+ not writer
+ or not _aurora_mysql_8_replication_enabled(writer)
+ or not writer.get("_shared_container_ready")
+ or not writer.get("_shared_internal_address")
+ or not writer.get("_shared_internal_port")
+ or not cluster.get("_shared_internal_address")
+ ):
+ return False
+ if not _ensure_mysql_replication_user(writer):
+ return False
+
+ conn = None
+ cur = None
+ try:
+ conn = _mysql_replication_connection(cluster)
+ if conn is None:
+ return False
+ cur = conn.cursor()
+ try:
+ cur.execute("STOP REPLICA")
+ except Exception as e:
+ logger.debug(
+ "RDS: STOP REPLICA was a no-op for %s: %s",
+ cluster_id,
+ e,
+ )
+ if cluster.get("_mysql_replication_reset_pending"):
+ # RESET REPLICA ALL clears stale connection/applier repositories
+ # and relay logs but deliberately preserves gtid_executed. Within
+ # the source's configured retention window, auto-position can
+ # request every transaction not yet applied before the restart.
+ cur.execute("RESET REPLICA ALL")
+ cur.execute(
+ "CHANGE REPLICATION SOURCE TO "
+ "SOURCE_HOST=%s, SOURCE_PORT=%s, SOURCE_USER=%s, "
+ "SOURCE_PASSWORD=%s, SOURCE_AUTO_POSITION=1, "
+ "GET_SOURCE_PUBLIC_KEY=1",
+ (
+ writer["_shared_internal_address"],
+ int(writer["_shared_internal_port"]),
+ _MYSQL_REPLICATION_USER,
+ _MYSQL_REPLICATION_PASSWORD,
+ ),
+ )
+ cur.execute("START REPLICA")
+ cur.execute("SET GLOBAL super_read_only=ON")
+ except Exception as e:
+ logger.warning(
+ "RDS: failed to configure MySQL replication for %s: %s",
+ cluster_id,
+ e,
+ )
+ return False
+ finally:
+ if cur is not None:
+ cur.close()
+ if conn is not None:
+ conn.close()
+
+ cluster["_mysql_replication_source_arn"] = writer.get("DBClusterArn")
+ cluster.pop("_mysql_replication_reset_pending", None)
+ cluster.pop("_mysql_replication_retry_marker", None)
+ # If MiniStack restarted or a detach statement failed after the channel
+ # had been changed, successful reconfiguration is the rollback/repair
+ # point. Global membership remains authoritative until RemoveFromGlobal
+ # Cluster commits its metadata update.
+ cluster.pop("_mysql_replication_detach_state", None)
+ logger.info(
+ "RDS: configured MySQL replication for %s from %s",
+ cluster_id,
+ writer.get("DBClusterIdentifier", "unknown"),
+ )
+ return True
+
+
+def _detach_mysql_replication(cluster_id, cluster):
+ """Stop a global secondary and make its data plane writable."""
+ if not _mysql_replication_secondary(cluster):
+ return True
+ if not cluster.get("_shared_storage_initialized"):
+ return True
+ if not cluster.get("_shared_container_ready"):
+ return False
+ if not _ensure_mysql_control_user(cluster):
+ return False
+
+ # Persist the transition before destructive SQL. A failed request keeps
+ # global membership intact; immediate rollback (or the normal restore-time
+ # configure path after a process restart) relinks the channel and clears
+ # this marker. Successful detach leaves the marker until the caller
+ # commits the global/member metadata update under the same lifecycle lock.
+ state = cluster.setdefault("_mysql_replication_detach_state", "requested")
+ conn = None
+ cur = None
+ try:
+ conn = _mysql_replication_connection(cluster)
+ if conn is None:
+ return False
+ cur = conn.cursor()
+ if state == "requested":
+ cur.execute("STOP REPLICA")
+ cluster["_mysql_replication_detach_state"] = "stopped"
+ state = "stopped"
+ if state in ("stopped", "resetting"):
+ # ``resetting`` is written first so a crash between MySQL applying
+ # RESET and Python publishing the next state is recoverable.
+ cluster["_mysql_replication_detach_state"] = "resetting"
+ cur.execute("RESET REPLICA ALL")
+ cluster["_mysql_replication_detach_state"] = "reset"
+ state = "reset"
+ if state == "reset":
+ cur.execute("SET GLOBAL super_read_only=OFF")
+ except Exception as e:
+ logger.warning(
+ "RDS: failed to detach MySQL replication for %s: %s",
+ cluster_id,
+ e,
+ )
+ # Best-effort atomic rollback: if the connection is still usable (or a
+ # fresh one can be opened), restore auto-position and read-only mode.
+ # If that is temporarily impossible, the durable state remains and the
+ # normal readiness/configuration path repairs it on retry or restart.
+ if _configure_mysql_replication(cluster_id, cluster) is True:
+ logger.info(
+ "RDS: restored MySQL replication for %s after detach failed",
+ cluster_id,
+ )
+ else:
+ # Reconfiguration may fail after recreating or starting the
+ # channel. Do not trust the detach stage recorded before that
+ # partial rollback: the next detach attempt must conservatively
+ # stop and reset any channel that may now exist.
+ cluster["_mysql_replication_detach_state"] = "requested"
+ return False
+ finally:
+ if cur is not None:
+ cur.close()
+ if conn is not None:
+ conn.close()
+
+ return True
+
+
+def _clear_mysql_replication_metadata(cluster):
+ """Commit the metadata half of a successful global-secondary detach."""
+ for field in (
+ "_mysql_replication_source_arn",
+ "_mysql_replication_reset_pending",
+ "_mysql_replication_retry_marker",
+ "_mysql_replication_blocked_reason",
+ "_mysql_replication_detach_state",
+ "_mysql_headless_applier_required",
+ ):
+ cluster.pop(field, None)
+
+
+def _schedule_mysql_replication_retry(cluster_id, cluster):
+ """Retry a deferred cross-region link without blocking RDS readiness."""
+ parsed = _parse_rds_arn(cluster.get("DBClusterArn", ""))
+ if not parsed:
+ return
+ spec, resource_type, parsed_cluster_id = parsed
+ if resource_type != "cluster":
+ return
+ epoch = cluster.get("_shared_container_epoch")
+ marker = (epoch, cluster.get("GlobalClusterIdentifier"))
+ if cluster.get("_mysql_replication_retry_marker") == marker:
+ return
+ cluster["_mysql_replication_retry_marker"] = marker
+ ctx = contextvars.copy_context()
+
+ def _retry():
+ for _attempt in range(_MYSQL_REPLICATION_RETRY_ATTEMPTS):
+ time.sleep(_MYSQL_REPLICATION_RETRY_INTERVAL)
+ with _shared_container_lock:
+ current = _clusters.get_scoped(
+ spec.account_id,
+ spec.region,
+ parsed_cluster_id,
+ )
+ if (
+ current is not cluster
+ or current.get("_shared_container_epoch") != epoch
+ or current.get("_mysql_replication_retry_marker") != marker
+ ):
+ return
+ result = _configure_mysql_replication(cluster_id, current)
+ if result is not False:
+ current.pop("_mysql_replication_retry_marker", None)
+ return
+ with _shared_container_lock:
+ current = _clusters.get_scoped(
+ spec.account_id,
+ spec.region,
+ parsed_cluster_id,
+ )
+ if (
+ current is cluster
+ and current.get("_shared_container_epoch") == epoch
+ and current.get("_mysql_replication_retry_marker") == marker
+ ):
+ current.pop("_mysql_replication_retry_marker", None)
+ logger.warning(
+ "RDS: MySQL replication for %s did not become configurable "
+ "after %s attempts",
+ cluster_id,
+ _MYSQL_REPLICATION_RETRY_ATTEMPTS,
+ )
+
+ threading.Thread(target=ctx.run, args=(_retry,), daemon=True).start()
+
+
+def _configure_or_defer_mysql_replication(cluster_id, cluster):
+ if _configure_mysql_replication(cluster_id, cluster) is False:
+ _schedule_mysql_replication_retry(cluster_id, cluster)
+
+
def _grant_mysql_master_user_privileges(host, port, master_user, master_pass, db_id):
"""Grant the emulated MySQL master user AWS/RDS-like admin privileges."""
try:
@@ -1256,7 +1852,7 @@ def _try_database_connect(host, port, engine, user, password, db_name):
except ImportError:
return _wait_for_port(host, port, timeout=1)
conn = pymysql.connect(
- host=host, port=int(port), user="root",
+ host=host, port=int(port), user=user,
password=password, database=db_name or None,
connect_timeout=2, read_timeout=2, write_timeout=2,
autocommit=True)
@@ -1756,6 +2352,7 @@ def _register_instance_in_cluster(instance):
"IsClusterWriter": is_writer,
"PromotionTier": int(instance.get("PromotionTier", 1)),
})
+ cluster.pop("_mysql_headless_applier_required", None)
_sync_cluster_endpoints(cluster)
_refresh_cluster_status(cid)
@@ -2160,11 +2757,23 @@ def _create_db_instance(p):
return c.status not in ("exited", "dead", "removing")
except Exception:
return False
+ readiness_cluster = _clusters.get(cluster_id) if cluster_id else None
+ readiness_user = master_user
+ if readiness_cluster and _mysql_replication_secondary(readiness_cluster):
+ readiness_user = "root"
+ if readiness_cluster.get("_mysql_control_user_ready"):
+ readiness_user = _MYSQL_CONTROL_USER
+ readiness_master_pass = _MYSQL_CONTROL_PASSWORD
+ readiness_db_name = (
+ None
+ if readiness_cluster and _mysql_replication_secondary(readiness_cluster)
+ else db_name
+ )
database_ready = _wait_for_database_ready(
- ready_host, ready_port, engine, master_user,
- readiness_master_pass, db_name, _container_alive,
+ ready_host, ready_port, engine, readiness_user,
+ readiness_master_pass, readiness_db_name, _container_alive,
)
- cluster = _clusters.get(cluster_id) if cluster_id else None
+ cluster = readiness_cluster
if cluster:
with _shared_container_lock:
if (
@@ -2219,14 +2828,19 @@ def _create_db_instance(p):
return
if pending_rotation:
cluster.pop("_pending_master_password_rotation", None)
+ _sync_global_mysql_credentials(cluster)
- if _is_mysql_engine(engine):
+ if _is_mysql_engine(engine) and not _mysql_replication_secondary(
+ cluster,
+ ):
_grant_mysql_master_user_privileges(
ready_host, ready_port, master_user,
cluster.get("_MasterUserPassword", master_pass),
cluster_id,
)
cluster["_shared_container_ready"] = True
+ if _aurora_mysql_8_replication_enabled(cluster):
+ _configure_or_defer_mysql_replication(cluster_id, cluster)
for member in cluster.get("DBClusterMembers", []):
inst = _instances.get(member.get("DBInstanceIdentifier"))
if inst is not None:
@@ -2310,7 +2924,14 @@ def _delete_db_instance(p):
if shared_cluster_id:
cluster = _resolve_cluster_in_request_region(shared_cluster_id)
if cluster and not cluster.get("DBClusterMembers"):
- _stop_empty_cluster_shared_container(shared_cluster_id, cluster)
+ if _mysql_replication_secondary(cluster):
+ # Aurora global headless secondaries have no query compute but
+ # their storage continues to synchronize. MiniStack's single
+ # shared process is also the applier, so preserve it until the
+ # secondary is detached, deleted, or gains compute again.
+ cluster["_mysql_headless_applier_required"] = True
+ else:
+ _stop_empty_cluster_shared_container(shared_cluster_id, cluster)
docker_client = _get_docker()
if (
@@ -2719,7 +3340,52 @@ def _create_db_cluster(p):
)
engine_version = expected_engine_version or engine_version
port = int(_p(p, "Port") or _default_port(engine))
- master_user = _p(p, "MasterUsername") or "admin"
+ explicit_master_user = _p(p, "MasterUsername") or None
+ explicit_master_pass = _p(p, "MasterUserPassword") or None
+ explicit_database_name = _p(p, "DatabaseName") or None
+ global_writer = (
+ _global_cluster_writer_cluster(global_cluster)
+ if global_cluster
+ else None
+ )
+ if global_writer:
+ inherited_fields = (
+ ("MasterUsername", explicit_master_user, global_writer.get("MasterUsername")),
+ (
+ "MasterUserPassword",
+ explicit_master_pass,
+ global_writer.get("_MasterUserPassword"),
+ ),
+ ("DatabaseName", explicit_database_name, global_writer.get("DatabaseName")),
+ )
+ conflicting_field = next(
+ (
+ field
+ for field, explicit_value, inherited_value in inherited_fields
+ if explicit_value is not None
+ and explicit_value != inherited_value
+ ),
+ None,
+ )
+ if conflicting_field:
+ return _error(
+ "InvalidParameterValue",
+ f"{conflicting_field} must match the global writer when "
+ "creating a secondary cluster.",
+ 400,
+ )
+ if not _mysql_gtid_history_ready(global_writer):
+ return _error(
+ "InvalidDBClusterStateFault",
+ "The global writer volume predates GTID-at-creation tracking "
+ "and cannot safely seed a secondary.",
+ 400,
+ )
+ master_user = (
+ global_writer.get("MasterUsername", "admin")
+ if global_writer
+ else explicit_master_user or "admin"
+ )
arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster:{cluster_id}"
unique_suffix = new_uuid()[:8]
now_ts = time.time()
@@ -2730,7 +3396,16 @@ def _create_db_cluster(p):
if not az_list:
az_list = [f"{get_region()}a", f"{get_region()}b", f"{get_region()}c"]
- master_pass = _p(p, "MasterUserPassword") or "password"
+ master_pass = (
+ global_writer.get("_MasterUserPassword", "password")
+ if global_writer
+ else explicit_master_pass or "password"
+ )
+ database_name = (
+ global_writer.get("DatabaseName")
+ if global_writer
+ else explicit_database_name
+ )
cluster = {
"DBClusterIdentifier": cluster_id,
@@ -2741,7 +3416,7 @@ def _create_db_cluster(p):
"Status": "available",
"MasterUsername": master_user,
"_MasterUserPassword": master_pass,
- "DatabaseName": _p(p, "DatabaseName") or None,
+ "DatabaseName": database_name,
"NetworkType": _p(p, "NetworkType") or "IPV4",
"EngineLifecycleSupport": _p(p, "EngineLifecycleSupport") or "open-source-rds-extended-support",
"Endpoint": f"{cluster_id}.cluster-{unique_suffix}.{get_region()}.rds.amazonaws.com",
@@ -2785,6 +3460,7 @@ def _create_db_cluster(p):
"_shared_container_epoch": 0,
"_shared_storage_initialized": False,
}
+ _prepare_mysql_gtid_history(cluster)
_clusters[cluster_id] = cluster
if global_cluster:
is_first_member = not global_cluster.get("GlobalClusterMembers")
@@ -2994,6 +3670,12 @@ def _modify_db_cluster(p):
if _p(p, "EngineVersion"):
cluster["EngineVersion"] = _p(p, "EngineVersion")
if _p(p, "MasterUserPassword"):
+ if _mysql_replication_secondary(cluster):
+ return _error(
+ "InvalidDBClusterStateFault",
+ "MasterUserPassword must be changed on the global writer.",
+ 400,
+ )
new_pass = _p(p, "MasterUserPassword")
with _shared_container_lock:
old_pass = cluster.get("_MasterUserPassword", "password")
@@ -3015,6 +3697,7 @@ def _modify_db_cluster(p):
cluster, rotation_old_pass, new_pass,
):
cluster.pop("_pending_master_password_rotation", None)
+ _sync_global_mysql_credentials(cluster)
elif (
cluster.get("_shared_container_id")
or cluster.get("_shared_storage_initialized")
@@ -3829,10 +4512,9 @@ def _invalid_global_cluster_identifier_error(global_id):
# ---------------------------------------------------------------------------
# Global Clusters
#
-# Emulation scope: metadata-level Aurora Global Database membership. This
-# supports the create/read/update/delete control-plane path needed by local
-# acceptance tests, without simulating storage replication, failover, or
-# switchover.
+# Emulation scope: Aurora Global Database membership plus native MySQL 8 GTID
+# replication between provisioned members. Failover and switchover remain
+# metadata-only; their data-plane promotion behavior is a separate phase.
# ---------------------------------------------------------------------------
def _create_global_cluster(p):
@@ -3875,6 +4557,16 @@ def _create_global_cluster(p):
f"global cluster {existing_global_id}.",
400,
)
+ if (
+ _aurora_mysql_8_replication_enabled(source_cluster)
+ and not _prepare_mysql_gtid_history(source_cluster)
+ ):
+ return _error(
+ "InvalidDBClusterStateFault",
+ "The source cluster volume predates GTID-at-creation tracking "
+ "and cannot safely become a global writer.",
+ 400,
+ )
engine = source_cluster["Engine"]
engine_version = source_cluster["EngineVersion"]
@@ -3953,25 +4645,52 @@ def _remove_from_global_cluster(p):
return _error("GlobalClusterNotFoundFault",
f"Global cluster {gc_id} not found.", 404)
- members = gc.get("GlobalClusterMembers", [])
- cluster = _resolve_cluster(db_cluster_id)
- db_cluster_arn = cluster["DBClusterArn"] if cluster else db_cluster_id
- member = next((m for m in members if m["DBClusterArn"] == db_cluster_arn), None)
- if not member:
- return _error("DBClusterNotFoundFault",
- f"DBCluster {db_cluster_id} is not a member of global cluster {gc_id}.", 404)
- if member.get("IsWriter") and len(members) > 1:
- return _error("InvalidGlobalClusterStateFault",
- "Cannot remove the writer DB cluster while reader members remain.", 400)
+ with _shared_container_lock:
+ members = gc.get("GlobalClusterMembers", [])
+ cluster = _resolve_cluster(db_cluster_id)
+ db_cluster_arn = cluster["DBClusterArn"] if cluster else db_cluster_id
+ member = next(
+ (m for m in members if m["DBClusterArn"] == db_cluster_arn),
+ None,
+ )
+ if not member:
+ return _error("DBClusterNotFoundFault",
+ f"DBCluster {db_cluster_id} is not a member of global cluster {gc_id}.", 404)
+ if member.get("IsWriter") and len(members) > 1:
+ return _error("InvalidGlobalClusterStateFault",
+ "Cannot remove the writer DB cluster while reader members remain.", 400)
- new_members = [m for m in members if m["DBClusterArn"] != db_cluster_arn]
- gc["GlobalClusterMembers"] = new_members
- _refresh_global_cluster_readers(gc)
- if not cluster:
- cluster = _resolve_cluster(db_cluster_arn)
- if cluster:
- cluster.pop("GlobalClusterIdentifier", None)
- cluster.pop("GlobalWriteForwardingStatus", None)
+ if not cluster:
+ cluster = _resolve_cluster(db_cluster_arn)
+ if (
+ cluster
+ and not member.get("IsWriter")
+ and not _detach_mysql_replication(
+ cluster.get("DBClusterIdentifier", db_cluster_id),
+ cluster,
+ )
+ ):
+ return _error(
+ "InvalidDBClusterStateFault",
+ "Cannot detach the secondary until its replication channel "
+ "is stopped and reset.",
+ 400,
+ )
+
+ gc["GlobalClusterMembers"] = [
+ m for m in members if m["DBClusterArn"] != db_cluster_arn
+ ]
+ _refresh_global_cluster_readers(gc)
+ if cluster:
+ cluster.pop("GlobalClusterIdentifier", None)
+ cluster.pop("GlobalWriteForwardingStatus", None)
+ if not member.get("IsWriter"):
+ _clear_mysql_replication_metadata(cluster)
+ if not cluster.get("DBClusterMembers"):
+ _stop_empty_cluster_shared_container(
+ cluster.get("DBClusterIdentifier", db_cluster_id),
+ cluster,
+ )
return _xml(200, "RemoveFromGlobalClusterResponse",
f"<RemoveFromGlobalClusterResult><GlobalCluster>{_global_cluster_xml(gc)}</GlobalCluster></RemoveFromGlobalClusterResult>")
diff --git a/tests/test_rds.py b/tests/test_rds.py
index d76861a5..b0ce194a 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -3158,6 +3158,8 @@ def test_rds_restore_state_respawns_docker_container(monkeypatch):
"member-added-during-readiness",
"member-added-during-migration",
"pending-password-rotation",
+ "global-secondary",
+ "global-secondary-before-control-user",
"last-member-deleted-during-readiness",
"last-members-deleted-before-start",
],
@@ -3177,6 +3179,7 @@ def test_rds_restore_state_respawns_one_container_per_cluster(
readiness_credentials = []
rotations = []
grants = []
+ replication_configs = []
remaining_legacy_names = set()
legacy_owner_by_name = {}
writer_legacy_container_name = [None]
@@ -3309,9 +3312,26 @@ def test_rds_restore_state_respawns_one_container_per_cluster(
def _grant(_host, _port, user, password, db_id):
grants.append((user, password, db_id))
+ def _configure_replication(db_id, cluster):
+ replication_configs.append(
+ (
+ db_id,
+ cluster.get("_shared_container_epoch"),
+ cluster.get("_shared_container_ready"),
+ cluster.get("_mysql_replication_reset_pending"),
+ )
+ )
+
monkeypatch.setattr(m, "_wait_for_database_ready", _wait_for_database_ready)
monkeypatch.setattr(m, "_rotate_real_password", _rotate)
monkeypatch.setattr(m, "_grant_mysql_master_user_privileges", _grant)
+ monkeypatch.setattr(
+ m,
+ "_configure_or_defer_mysql_replication",
+ _configure_replication,
+ )
+ if scenario.startswith("global-secondary"):
+ monkeypatch.setattr(m, "_mysql_replication_secondary", lambda _cluster: True)
account_id = get_account_id()
region = get_region()
@@ -3361,6 +3381,13 @@ def test_rds_restore_state_respawns_one_container_per_cluster(
"old_password": "writer-password",
"new_password": "rotated-password",
}
+ elif scenario.startswith("global-secondary"):
+ cluster_record["_mysql_replication_source_arn"] = (
+ "arn:aws:rds:us-east-1:111111111111:cluster:global-primary"
+ )
+ cluster_record["_mysql_gtid_initialized_at_creation"] = True
+ if scenario == "global-secondary":
+ cluster_record["_mysql_control_user_ready"] = True
clusters.set_scoped(account_id, region, cluster_id, cluster_record)
instances = AccountRegionScopedDict()
for db_id in ("restored-writer", "restored-reader"):
@@ -3497,16 +3524,40 @@ def test_rds_restore_state_respawns_one_container_per_cluster(
assert len(runs) == 1
assert runs[0]["name"] == m._rds_cluster_docker_name(cluster_id)
- assert runs[0]["environment"]["MYSQL_USER"] == "writer-admin"
+ if scenario.startswith("global-secondary"):
+ assert "MYSQL_USER" not in runs[0]["environment"]
+ assert "MYSQL_PASSWORD" not in runs[0]["environment"]
+ assert "MYSQL_DATABASE" not in runs[0]["environment"]
+ else:
+ assert runs[0]["environment"]["MYSQL_USER"] == "writer-admin"
expected_password = (
"rotated-password"
if scenario == "pending-password-rotation"
else "writer-password"
)
assert runs[0]["environment"]["MYSQL_ROOT_PASSWORD"] == expected_password
- assert runs[0]["environment"]["MYSQL_DATABASE"] == "writer-db"
+ if not scenario.startswith("global-secondary"):
+ assert runs[0]["environment"]["MYSQL_DATABASE"] == "writer-db"
assert readiness_credentials == [
- ("writer-admin", "writer-password", "writer-db"),
+ (
+ (
+ m._MYSQL_CONTROL_USER
+ if scenario == "global-secondary"
+ else "root"
+ if scenario == "global-secondary-before-control-user"
+ else "writer-admin"
+ ),
+ (
+ m._MYSQL_CONTROL_PASSWORD
+ if scenario == "global-secondary"
+ else "writer-password"
+ ),
+ (
+ None
+ if scenario.startswith("global-secondary")
+ else "writer-db"
+ ),
+ ),
]
assert runs[0]["volumes"] == {
"legacy-restored-writer-volume": {
@@ -3533,6 +3584,22 @@ def test_rds_restore_state_respawns_one_container_per_cluster(
)
assert grants == (
[("writer-admin", expected_password, cluster_id)]
+ if database_ready and not scenario.startswith("global-secondary")
+ else []
+ )
+ assert replication_configs == (
+ [
+ (
+ cluster_id,
+ restored_cluster["_shared_container_epoch"],
+ True,
+ (
+ True
+ if scenario.startswith("global-secondary")
+ else None
+ ),
+ )
+ ]
if database_ready
else []
)
@@ -5674,6 +5741,53 @@ def test_rds_mysql_readiness_probe_requires_successful_query(monkeypatch):
assert attempts == ["SELECT 1", "cursor.close", "connection.close"]
+def test_rds_mysql_readiness_probe_uses_supplied_control_user(monkeypatch):
+ """Replica readiness must authenticate as the local control account."""
+ from ministack.services import rds
+
+ connection_args = []
+
+ class FakeCursor:
+ def execute(self, sql):
+ assert sql == "SELECT 1"
+
+ def close(self):
+ pass
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ pass
+
+ def connect(**kwargs):
+ connection_args.append(kwargs)
+ return FakeConnection()
+
+ monkeypatch.setitem(sys.modules, "pymysql", types.SimpleNamespace(connect=connect))
+
+ assert rds._try_database_connect(
+ "127.0.0.1",
+ 3306,
+ "aurora-mysql",
+ rds._MYSQL_CONTROL_USER,
+ rds._MYSQL_CONTROL_PASSWORD,
+ None,
+ )
+ assert connection_args == [{
+ "host": "127.0.0.1",
+ "port": 3306,
+ "user": rds._MYSQL_CONTROL_USER,
+ "password": rds._MYSQL_CONTROL_PASSWORD,
+ "database": None,
+ "connect_timeout": 2,
+ "read_timeout": 2,
+ "write_timeout": 2,
+ "autocommit": True,
+ }]
+
+
def test_rds_cluster_password_rotation_alters_mysql_password(monkeypatch):
"""Password rotation assumes the instance already passed readiness."""
from ministack.services import rds
@@ -5933,3 +6047,1709 @@ def test_aurora_delete_member_keeps_shared_data(rds, rds_data):
filters={"label": ["ministack=rds", f"cluster_id={cluster_id}"]},
)
assert containers == []
+
+
+def test_rds_aurora_mysql_8_replication_command_is_stable_and_scoped(monkeypatch):
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import rds as m
+
+ runs = []
+
+ class FakeContainer:
+ def __init__(self, name):
+ self.id = f"container-{len(runs)}"
+ self.name = name
+ self.attrs = {"NetworkSettings": {"Networks": {}}}
+
+ def reload(self):
+ pass
+
+ class FakeContainers:
+ def run(self, **kwargs):
+ runs.append(kwargs)
+ return FakeContainer(kwargs["name"])
+
+ class FakeDocker:
+ def __init__(self):
+ self.containers = FakeContainers()
+
+ monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())
+ monkeypatch.setattr(m, "_get_ministack_network", lambda _client: None)
+ monkeypatch.setattr(m, "_is_host_port_free", lambda _port: True)
+ monkeypatch.setattr(m, "_port_counter", [17000])
+ monkeypatch.setattr(
+ m,
+ "_mysql_replication_secondary",
+ lambda cluster: cluster.get("DBClusterIdentifier") == "global-secondary",
+ )
+
+ original_account = get_account_id()
+ original_region = get_region()
+
+ def command_for(
+ account,
+ region,
+ cluster_id,
+ engine="aurora-mysql",
+ engine_version="8.0.mysql_aurora.3.10.3",
+ ):
+ set_request_account_id(account)
+ set_request_region(region)
+ cluster = {
+ "DBClusterIdentifier": cluster_id,
+ "Engine": engine,
+ "EngineVersion": engine_version,
+ "MasterUsername": "admin",
+ "_MasterUserPassword": "password123",
+ "DatabaseName": "mydb",
+ }
+ m._start_cluster_shared_container(cluster_id, cluster)
+ return runs[-1]
+
+ try:
+ east_first = command_for("111111111111", "us-east-1", "global-primary")
+ east_again = command_for("111111111111", "us-east-1", "global-primary")
+ west = command_for("111111111111", "us-west-2", "global-secondary")
+ other_account = command_for("222222222222", "us-east-1", "global-primary")
+ mysql_57 = command_for(
+ "111111111111",
+ "us-east-1",
+ "mysql-57-cluster",
+ engine_version="5.7.mysql_aurora.2.12.6",
+ )
+ mysql_84 = command_for(
+ "111111111111",
+ "us-east-1",
+ "mysql-84-cluster",
+ engine_version="8.4.mysql_aurora.8.4.7",
+ )
+ postgres = command_for(
+ "111111111111",
+ "us-east-1",
+ "postgres-cluster",
+ engine="aurora-postgresql",
+ engine_version="15.3",
+ )
+ finally:
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+ required_flags = {
+ "--log-bin=mysql-bin",
+ "--gtid-mode=ON",
+ "--enforce-gtid-consistency=ON",
+ "--log-replica-updates",
+ f"--binlog-expire-logs-seconds={m._MYSQL_BINLOG_RETENTION_SECONDS}",
+ }
+ for run in (east_first, east_again, west, other_account):
+ assert required_flags <= set(run["command"])
+
+ def server_id(run):
+ raw = next(
+ arg.removeprefix("--server-id=")
+ for arg in run["command"]
+ if arg.startswith("--server-id=")
+ )
+ parsed = int(raw)
+ assert 1 <= parsed <= 2**32 - 1
+ return parsed
+
+ assert server_id(east_first) == server_id(east_again)
+ assert len(
+ {
+ server_id(east_first),
+ server_id(west),
+ server_id(other_account),
+ }
+ ) == 3
+ for unsupported in (mysql_57, mysql_84, postgres):
+ assert "command" not in unsupported
+ assert "--binlog-expire-logs-seconds=0" not in east_first["command"]
+ assert east_first["environment"]["MYSQL_USER"] == "admin"
+ assert east_first["environment"]["MYSQL_DATABASE"] == "mydb"
+ assert west["environment"] == {
+ "MYSQL_ROOT_PASSWORD": "password123",
+ "MYSQL_ROOT_HOST": "%",
+ }
+
+
+def _mysql_replication_unit_topology():
+ writer = {
+ "DBClusterIdentifier": "primary",
+ "DBClusterArn": "arn:aws:rds:us-east-1:111111111111:cluster:primary",
+ "Engine": "aurora-mysql",
+ "EngineVersion": "8.0.mysql_aurora.3.10.3",
+ "GlobalClusterIdentifier": "global-repl",
+ "_mysql_gtid_initialized_at_creation": True,
+ "_shared_container_ready": True,
+ "_shared_internal_address": "172.20.0.10",
+ "_shared_internal_port": 3306,
+ }
+ secondary = {
+ "DBClusterIdentifier": "secondary",
+ "DBClusterArn": "arn:aws:rds:us-west-2:111111111111:cluster:secondary",
+ "Engine": "aurora-mysql",
+ "EngineVersion": "8.0.mysql_aurora.3.10.3",
+ "GlobalClusterIdentifier": "global-repl",
+ "_mysql_gtid_initialized_at_creation": True,
+ "_shared_container_ready": True,
+ "_shared_internal_address": "172.20.0.20",
+ "_shared_internal_port": 3306,
+ }
+ writer_member = {"DBClusterArn": writer["DBClusterArn"], "IsWriter": True}
+ secondary_member = {
+ "DBClusterArn": secondary["DBClusterArn"],
+ "IsWriter": False,
+ }
+ global_cluster = {
+ "GlobalClusterIdentifier": "global-repl",
+ "GlobalClusterMembers": [writer_member, secondary_member],
+ }
+ return writer, secondary, writer_member, secondary_member, global_cluster
+
+
+def _patch_mysql_replication_unit_topology(monkeypatch, m, topology):
+ writer, secondary, writer_member, secondary_member, global_cluster = topology
+
+ def member_for(cluster):
+ member = writer_member if cluster is writer else secondary_member
+ return global_cluster, member
+
+ def resolve(member):
+ return writer if member is writer_member else secondary
+
+ monkeypatch.setattr(m, "_global_cluster_member_for_cluster", member_for)
+ monkeypatch.setattr(m, "_resolve_global_member_cluster", resolve)
+ monkeypatch.setattr(m, "_ensure_mysql_control_user", lambda _cluster: True)
+
+
+ ("control_ready", "expected_user", "expected_password"),
+ [
+ (False, "root", "global-password"),
+ (True, "rdsadmin", "ministack-rds-control"),
+ ],
+)
+def test_rds_global_secondary_readiness_uses_bootstrap_state_credentials(
+ monkeypatch,
+ control_ready,
+ expected_user,
+ expected_password,
+):
+ """The real create-member readiness call distinguishes fresh and restored."""
+ import threading
+
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_region,
+ )
+ from ministack.services import rds as m
+
+ account_id = get_account_id()
+ original_region = get_region()
+ topology = _mysql_replication_unit_topology()
+ writer, secondary, _writer_member, _secondary_member, global_cluster = topology
+ writer.update({
+ "MasterUsername": "global_admin",
+ "_MasterUserPassword": "global-password",
+ "DatabaseName": "global_db",
+ })
+ secondary.update({
+ "MasterUsername": "global_admin",
+ "_MasterUserPassword": "global-password",
+ "DatabaseName": "global_db",
+ "DBClusterMembers": [],
+ "Port": 3306,
+ })
+ if control_ready:
+ secondary["_mysql_control_user_ready"] = True
+
+ readiness_credentials = []
+ readiness_finished = threading.Event()
+
+ class FakeContainer:
+ status = "running"
+
+ def reload(self):
+ pass
+
+ class FakeContainers:
+ def get(self, _container_id):
+ return FakeContainer()
+
+ class FakeDocker:
+ containers = FakeContainers()
+
+ def start_cluster(_cluster_id, cluster, remove_stale=False):
+ assert remove_stale is False
+ cluster.update({
+ "_shared_container_id": "secondary-container",
+ "_shared_container_epoch": 1,
+ "_shared_container_ready": False,
+ "_shared_endpoint": {"Address": "127.0.0.1", "Port": 3306},
+ "_shared_internal_address": "172.20.0.20",
+ "_shared_internal_port": 3306,
+ })
+ return {
+ "started": True,
+ "failed": False,
+ "readiness_host": "127.0.0.1",
+ "readiness_port": 3306,
+ "container_epoch": 1,
+ }
+
+ def wait_for_ready(_host, _port, _engine, user, password, db_name, *_args):
+ readiness_credentials.append((user, password, db_name))
+ return True
+
+ def configured(*_args):
+ readiness_finished.set()
+
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+ try:
+ m._clusters.set_scoped(account_id, "us-east-1", "primary", writer)
+ m._clusters.set_scoped(account_id, "us-west-2", "secondary", secondary)
+ m._global_clusters["global-repl"] = global_cluster
+ set_request_region("us-west-2")
+ monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())
+ monkeypatch.setattr(m, "_start_cluster_shared_container", start_cluster)
+ monkeypatch.setattr(m, "_wait_for_database_ready", wait_for_ready)
+ monkeypatch.setattr(m, "_configure_or_defer_mysql_replication", configured)
+
+ status, _, body = m._create_db_instance({
+ "DBInstanceIdentifier": "secondary-reader",
+ "DBClusterIdentifier": "secondary",
+ "DBInstanceClass": "db.r6g.large",
+ "Engine": "aurora-mysql",
+ })
+
+ assert status == 200, body
+ assert readiness_finished.wait(timeout=1)
+ assert readiness_credentials == [
+ (expected_user, expected_password, None),
+ ]
+ finally:
+ set_request_region(original_region)
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_mysql_replication_secondary_sql_is_idempotent(monkeypatch):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ ensured = []
+ statements = []
+ closed = []
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+
+ def close(self):
+ closed.append("cursor")
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ closed.append("connection")
+
+ monkeypatch.setattr(
+ m,
+ "_ensure_mysql_replication_user",
+ lambda cluster: ensured.append(cluster) or True,
+ )
+ monkeypatch.setattr(
+ m,
+ "_mysql_replication_connection",
+ lambda cluster: FakeConnection() if cluster is secondary else None,
+ )
+
+ assert m._configure_mysql_replication("secondary", secondary) is True
+ assert m._configure_mysql_replication("secondary", secondary) is True
+
+ assert ensured == [writer, writer]
+ assert [statement for statement, _params in statements] == [
+ "STOP REPLICA",
+ (
+ "CHANGE REPLICATION SOURCE TO "
+ "SOURCE_HOST=%s, SOURCE_PORT=%s, SOURCE_USER=%s, "
+ "SOURCE_PASSWORD=%s, SOURCE_AUTO_POSITION=1, "
+ "GET_SOURCE_PUBLIC_KEY=1"
+ ),
+ "START REPLICA",
+ "SET GLOBAL super_read_only=ON",
+ ] * 2
+ assert statements[1][1] == (
+ writer["_shared_internal_address"],
+ writer["_shared_internal_port"],
+ m._MYSQL_REPLICATION_USER,
+ m._MYSQL_REPLICATION_PASSWORD,
+ )
+ assert statements[5][1] == statements[1][1]
+ assert closed == ["cursor", "connection"] * 2
+ assert secondary["_mysql_replication_source_arn"] == writer["DBClusterArn"]
+ secondary["_mysql_replication_detach_state"] = "resetting"
+ assert m._configure_mysql_replication("secondary", secondary) is True
+ assert "_mysql_replication_detach_state" not in secondary
+
+
+def test_rds_mysql_replication_restore_resets_once_then_is_idempotent(monkeypatch):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ secondary["_mysql_replication_source_arn"] = writer["DBClusterArn"]
+ secondary["_mysql_replication_reset_pending"] = True
+ statements = []
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+
+ def close(self):
+ pass
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(m, "_ensure_mysql_replication_user", lambda _cluster: True)
+ monkeypatch.setattr(
+ m,
+ "_mysql_replication_connection",
+ lambda cluster: FakeConnection() if cluster is secondary else None,
+ )
+
+ assert m._configure_mysql_replication("secondary", secondary) is True
+ assert "_mysql_replication_reset_pending" not in secondary
+ assert m._configure_mysql_replication("secondary", secondary) is True
+
+ assert [statement for statement, _params in statements] == [
+ "STOP REPLICA",
+ "RESET REPLICA ALL",
+ (
+ "CHANGE REPLICATION SOURCE TO "
+ "SOURCE_HOST=%s, SOURCE_PORT=%s, SOURCE_USER=%s, "
+ "SOURCE_PASSWORD=%s, SOURCE_AUTO_POSITION=1, "
+ "GET_SOURCE_PUBLIC_KEY=1"
+ ),
+ "START REPLICA",
+ "SET GLOBAL super_read_only=ON",
+ "STOP REPLICA",
+ (
+ "CHANGE REPLICATION SOURCE TO "
+ "SOURCE_HOST=%s, SOURCE_PORT=%s, SOURCE_USER=%s, "
+ "SOURCE_PASSWORD=%s, SOURCE_AUTO_POSITION=1, "
+ "GET_SOURCE_PUBLIC_KEY=1"
+ ),
+ "START REPLICA",
+ "SET GLOBAL super_read_only=ON",
+ ]
+ assert sum(
+ statement == "RESET REPLICA ALL" for statement, _params in statements
+ ) == 1
+ assert secondary["_mysql_replication_source_arn"] == writer["DBClusterArn"]
+
+
+def test_rds_mysql_replication_writer_sweep_closes_reverse_readiness_race(
+ monkeypatch,
+):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ secondary["_shared_container_ready"] = True
+ writer["_shared_container_ready"] = False
+ scheduled = []
+ statements = []
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+
+ def close(self):
+ pass
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(m, "_ensure_mysql_replication_user", lambda _cluster: True)
+ monkeypatch.setattr(
+ m,
+ "_mysql_replication_connection",
+ lambda cluster: FakeConnection() if cluster is secondary else None,
+ )
+ monkeypatch.setattr(
+ m,
+ "_schedule_mysql_replication_retry",
+ lambda cluster_id, cluster: scheduled.append((cluster_id, cluster)),
+ )
+
+ m._configure_or_defer_mysql_replication("secondary", secondary)
+ assert scheduled == [("secondary", secondary)]
+ assert statements == []
+
+ writer["_shared_container_ready"] = True
+ assert m._configure_mysql_replication("primary", writer) is True
+ assert [statement for statement, _params in statements] == [
+ "STOP REPLICA",
+ (
+ "CHANGE REPLICATION SOURCE TO "
+ "SOURCE_HOST=%s, SOURCE_PORT=%s, SOURCE_USER=%s, "
+ "SOURCE_PASSWORD=%s, SOURCE_AUTO_POSITION=1, "
+ "GET_SOURCE_PUBLIC_KEY=1"
+ ),
+ "START REPLICA",
+ "SET GLOBAL super_read_only=ON",
+ ]
+ assert secondary["_mysql_replication_source_arn"] == writer["DBClusterArn"]
+
+
+def test_rds_mysql_replication_failure_is_retryable_and_closes_connections(
+ monkeypatch,
+ caplog,
+):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ _writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ scheduled = []
+ closed = []
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ if statement.startswith("CHANGE REPLICATION SOURCE"):
+ raise RuntimeError("source is temporarily unavailable")
+
+ def close(self):
+ closed.append("cursor")
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ closed.append("connection")
+
+ monkeypatch.setattr(m, "_ensure_mysql_replication_user", lambda _cluster: True)
+ monkeypatch.setattr(m, "_mysql_replication_connection", lambda _cluster: FakeConnection())
+ monkeypatch.setattr(
+ m,
+ "_schedule_mysql_replication_retry",
+ lambda cluster_id, cluster: scheduled.append((cluster_id, cluster)),
+ )
+
+ with caplog.at_level("WARNING"):
+ m._configure_or_defer_mysql_replication("secondary", secondary)
+
+ assert scheduled == [("secondary", secondary)]
+ assert closed == ["cursor", "connection"]
+ assert "_mysql_replication_source_arn" not in secondary
+ assert "source is temporarily unavailable" in caplog.text
+
+
+def test_rds_mysql_replication_retry_ignores_stale_container_epoch(monkeypatch):
+ from ministack.services import rds as m
+
+ cluster = {
+ "DBClusterIdentifier": "secondary",
+ "DBClusterArn": "arn:aws:rds:us-west-2:111111111111:cluster:secondary",
+ "GlobalClusterIdentifier": "global-repl",
+ "_shared_container_epoch": 7,
+ }
+ threads = []
+ configured = []
+
+ class FakeClusters:
+ def get_scoped(self, _account_id, _region, _cluster_id):
+ return cluster
+
+ class DeferredThread:
+ def __init__(self, target, args=(), daemon=None):
+ self.target = target
+ self.args = args
+ threads.append(self)
+
+ def start(self):
+ pass
+
+ monkeypatch.setattr(m, "_clusters", FakeClusters())
+ monkeypatch.setattr(m.threading, "Thread", DeferredThread)
+ monkeypatch.setattr(m.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ m,
+ "_configure_mysql_replication",
+ lambda cluster_id, current: configured.append((cluster_id, current)) or True,
+ )
+
+ m._schedule_mysql_replication_retry("secondary", cluster)
+ assert cluster["_mysql_replication_retry_marker"] == (7, "global-repl")
+ assert len(threads) == 1
+
+ cluster["_shared_container_epoch"] = 8
+ m._schedule_mysql_replication_retry("secondary", cluster)
+ assert cluster["_mysql_replication_retry_marker"] == (8, "global-repl")
+ assert len(threads) == 2
+
+ threads[0].target(*threads[0].args)
+ assert configured == []
+
+ threads[1].target(*threads[1].args)
+ assert configured == [("secondary", cluster)]
+ assert "_mysql_replication_retry_marker" not in cluster
+
+
+def test_rds_mysql_replication_retry_exhaustion_preserves_new_epoch_marker(
+ monkeypatch,
+):
+ from ministack.services import rds as m
+
+ cluster = {
+ "DBClusterIdentifier": "secondary",
+ "DBClusterArn": "arn:aws:rds:us-west-2:111111111111:cluster:secondary",
+ "GlobalClusterIdentifier": "global-repl",
+ "_shared_container_epoch": 7,
+ }
+ threads = []
+
+ class FakeClusters:
+ def get_scoped(self, _account_id, _region, _cluster_id):
+ return cluster
+
+ class DeferredThread:
+ def __init__(self, target, args=(), daemon=None):
+ self.target = target
+ self.args = args
+ threads.append(self)
+
+ def start(self):
+ pass
+
+ class EpochHandoffLock:
+ enters = 0
+
+ def __enter__(self):
+ self.enters += 1
+ if self.enters == 2:
+ cluster["_shared_container_epoch"] = 8
+ cluster["_mysql_replication_retry_marker"] = (8, "global-repl")
+
+ def __exit__(self, *_args):
+ pass
+
+ monkeypatch.setattr(m, "_clusters", FakeClusters())
+ monkeypatch.setattr(m, "_shared_container_lock", EpochHandoffLock())
+ monkeypatch.setattr(m.threading, "Thread", DeferredThread)
+ monkeypatch.setattr(m.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(m, "_MYSQL_REPLICATION_RETRY_ATTEMPTS", 1)
+ monkeypatch.setattr(m, "_configure_mysql_replication", lambda *_args: False)
+
+ m._schedule_mysql_replication_retry("secondary", cluster)
+ threads[0].target(*threads[0].args)
+
+ assert cluster["_mysql_replication_retry_marker"] == (8, "global-repl")
+
+
+def test_rds_mysql_replication_legacy_volume_fails_closed_on_global_attach():
+ from ministack.services import rds as m
+
+ cluster_id = "legacy-source"
+ cluster = {
+ "DBClusterIdentifier": cluster_id,
+ "DBClusterArn": f"arn:aws:rds:us-east-1:000000000000:cluster:{cluster_id}",
+ "Engine": "aurora-mysql",
+ "EngineVersion": "8.0.mysql_aurora.3.10.3",
+ "_shared_storage_initialized": True,
+ }
+ m._clusters.clear()
+ m._global_clusters.clear()
+ try:
+ m._clusters[cluster_id] = cluster
+
+ status, _, body = m._create_global_cluster({
+ "GlobalClusterIdentifier": "legacy-global",
+ "SourceDBClusterIdentifier": cluster["DBClusterArn"],
+ })
+
+ assert status == 400
+ assert b"InvalidDBClusterStateFault" in body
+ assert b"predates GTID-at-creation tracking" in body
+ assert "legacy-global" not in m._global_clusters
+ assert "GlobalClusterIdentifier" not in cluster
+ finally:
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_global_secondary_inherits_writer_credentials_and_database():
+ from ministack.core.responses import (
+ get_region,
+ set_request_region,
+ )
+ from ministack.services import rds as m
+
+ writer = {
+ "DBClusterIdentifier": "primary",
+ "DBClusterArn": "arn:aws:rds:us-east-1:000000000000:cluster:primary",
+ "Engine": "aurora-mysql",
+ "EngineVersion": "8.0.mysql_aurora.3.10.3",
+ "MasterUsername": "global_admin",
+ "_MasterUserPassword": "global-password",
+ "DatabaseName": "global_db",
+ "_mysql_gtid_initialized_at_creation": True,
+ }
+ global_cluster = {
+ "GlobalClusterIdentifier": "global-repl",
+ "Engine": writer["Engine"],
+ "EngineVersion": writer["EngineVersion"],
+ "GlobalClusterMembers": [
+ {"DBClusterArn": writer["DBClusterArn"], "IsWriter": True},
+ ],
+ }
+ m._clusters.clear()
+ m._global_clusters.clear()
+ original_region = get_region()
+ try:
+ m._clusters["primary"] = writer
+ m._global_clusters["global-repl"] = global_cluster
+ set_request_region("us-west-2")
+
+ status, _, _body = m._create_db_cluster({
+ "DBClusterIdentifier": "secondary",
+ "Engine": "aurora-mysql",
+ "EngineVersion": writer["EngineVersion"],
+ "GlobalClusterIdentifier": "global-repl",
+ })
+
+ assert status == 200, _body
+ secondary = m._clusters["secondary"]
+ assert secondary["MasterUsername"] == "global_admin"
+ assert secondary["_MasterUserPassword"] == "global-password"
+ assert secondary["DatabaseName"] == "global_db"
+
+ status, _, body = m._create_db_cluster({
+ "DBClusterIdentifier": "conflicting-secondary",
+ "Engine": "aurora-mysql",
+ "EngineVersion": writer["EngineVersion"],
+ "GlobalClusterIdentifier": "global-repl",
+ "MasterUsername": "different_admin",
+ })
+ assert status == 400
+ assert b"InvalidParameterValue" in body
+ assert "conflicting-secondary" not in m._clusters
+ finally:
+ set_request_region(original_region)
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_deleting_last_global_secondary_instance_preserves_headless_applier(
+ monkeypatch,
+):
+ from ministack.core.responses import get_account_id, get_region, set_request_region
+ from ministack.services import rds as m
+
+ account_id = get_account_id()
+ original_region = get_region()
+ writer, secondary, _writer_member, _secondary_member, global_cluster = (
+ _mysql_replication_unit_topology()
+ )
+ secondary.update({
+ "DBClusterMembers": [{
+ "DBInstanceIdentifier": "secondary-reader",
+ "IsClusterWriter": True,
+ }],
+ "_shared_storage_initialized": True,
+ "_shared_container_id": "secondary-container",
+ })
+ instance = {
+ "DBInstanceIdentifier": "secondary-reader",
+ "DBInstanceClass": "db.r6g.large",
+ "Engine": "aurora-mysql",
+ "EngineVersion": DEFAULT_AURORA_MYSQL_ENGINE_VERSION,
+ "DBInstanceStatus": "available",
+ "MasterUsername": "admin",
+ "Endpoint": {"Address": "secondary", "Port": 3306},
+ "AllocatedStorage": 1,
+ "DBInstanceArn": (
+ f"arn:aws:rds:us-west-2:{account_id}:db:secondary-reader"
+ ),
+ "DBClusterIdentifier": "secondary",
+ "_shared_cluster_id": "secondary",
+ "DeletionProtection": False,
+ }
+ stopped = []
+
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+ try:
+ m._clusters.set_scoped(account_id, "us-east-1", "primary", writer)
+ m._clusters.set_scoped(account_id, "us-west-2", "secondary", secondary)
+ m._instances.set_scoped(
+ account_id,
+ "us-west-2",
+ "secondary-reader",
+ instance,
+ )
+ m._global_clusters["global-repl"] = global_cluster
+ set_request_region("us-west-2")
+ monkeypatch.setattr(
+ m,
+ "_stop_empty_cluster_shared_container",
+ lambda cluster_id, cluster: stopped.append((cluster_id, cluster)),
+ )
+
+ status, _, body = m._delete_db_instance({
+ "DBInstanceIdentifier": "secondary-reader",
+ "SkipFinalSnapshot": "true",
+ })
+
+ assert status == 200, body
+ assert stopped == []
+ assert secondary["DBClusterMembers"] == []
+ assert secondary["_shared_container_ready"] is True
+ assert secondary["_mysql_headless_applier_required"] is True
+ finally:
+ set_request_region(original_region)
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_restore_respawns_persisted_headless_secondary_applier(monkeypatch):
+ import threading
+
+ from ministack.core.responses import AccountRegionScopedDict, AccountScopedDict
+ from ministack.services import rds as m
+
+ account_id = "000000000000"
+ writer_arn = f"arn:aws:rds:us-east-1:{account_id}:cluster:primary"
+ secondary_arn = f"arn:aws:rds:us-west-2:{account_id}:cluster:secondary"
+ writer = {
+ "DBClusterIdentifier": "primary",
+ "DBClusterArn": writer_arn,
+ "Engine": "aurora-mysql",
+ "EngineVersion": DEFAULT_AURORA_MYSQL_ENGINE_VERSION,
+ "GlobalClusterIdentifier": "global-repl",
+ "MasterUsername": "admin",
+ "_MasterUserPassword": "password123",
+ "DatabaseName": "mydb",
+ "DBClusterMembers": [],
+ }
+ secondary = {
+ "DBClusterIdentifier": "secondary",
+ "DBClusterArn": secondary_arn,
+ "Engine": "aurora-mysql",
+ "EngineVersion": DEFAULT_AURORA_MYSQL_ENGINE_VERSION,
+ "GlobalClusterIdentifier": "global-repl",
+ "MasterUsername": "admin",
+ "_MasterUserPassword": "password123",
+ "DatabaseName": "mydb",
+ "DBClusterMembers": [],
+ "Port": 3306,
+ "_shared_storage_initialized": True,
+ "_shared_volume_name": "secondary-volume",
+ "_shared_endpoint": {"Address": "127.0.0.1", "Port": 16020},
+ "_mysql_gtid_initialized_at_creation": True,
+ "_mysql_control_user_ready": True,
+ "_mysql_replication_source_arn": writer_arn,
+ "_mysql_headless_applier_required": True,
+ }
+ clusters = AccountRegionScopedDict()
+ clusters.set_scoped(account_id, "us-east-1", "primary", writer)
+ clusters.set_scoped(account_id, "us-west-2", "secondary", secondary)
+ global_clusters = AccountScopedDict()
+ global_clusters.set_scoped(account_id, None, "global-repl", {
+ "GlobalClusterIdentifier": "global-repl",
+ "GlobalClusterMembers": [
+ {"DBClusterArn": writer_arn, "IsWriter": True},
+ {"DBClusterArn": secondary_arn, "IsWriter": False},
+ ],
+ })
+ started = []
+ readiness_credentials = []
+ configured = threading.Event()
+
+ class FakeContainer:
+ status = "running"
+
+ def reload(self):
+ pass
+
+ class FakeContainers:
+ def get(self, _container_id):
+ return FakeContainer()
+
+ class FakeDocker:
+ containers = FakeContainers()
+
+ def start_cluster(cluster_id, cluster, remove_stale=False):
+ started.append((cluster_id, remove_stale))
+ cluster.update({
+ "_shared_container_id": "restored-headless-container",
+ "_shared_container_epoch": 1,
+ "_shared_container_ready": False,
+ "_shared_endpoint": {"Address": "127.0.0.1", "Port": 16020},
+ "_shared_internal_address": "172.20.0.20",
+ "_shared_internal_port": 3306,
+ })
+ return {
+ "started": True,
+ "failed": False,
+ "readiness_host": "127.0.0.1",
+ "readiness_port": 16020,
+ "container_epoch": 1,
+ }
+
+ def wait_for_ready(_host, _port, _engine, user, password, db_name, *_args):
+ readiness_credentials.append((user, password, db_name))
+ return True
+
+ def configure(cluster_id, cluster):
+ assert cluster_id == "secondary"
+ assert cluster["_mysql_headless_applier_required"] is True
+ configured.set()
+
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+ try:
+ monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())
+ monkeypatch.setattr(m, "_start_cluster_shared_container", start_cluster)
+ monkeypatch.setattr(m, "_wait_for_database_ready", wait_for_ready)
+ monkeypatch.setattr(m, "_configure_or_defer_mysql_replication", configure)
+
+ m.restore_state({
+ "instances": AccountRegionScopedDict(),
+ "clusters": clusters,
+ "global_clusters": global_clusters,
+ })
+
+ assert configured.wait(timeout=1)
+ assert started == [("secondary", True)]
+ assert readiness_credentials == [
+ (m._MYSQL_CONTROL_USER, m._MYSQL_CONTROL_PASSWORD, None),
+ ]
+ restored = m._clusters.get_scoped(
+ account_id,
+ "us-west-2",
+ "secondary",
+ )
+ assert restored["_shared_container_ready"] is True
+ assert restored["DBClusterMembers"] == []
+ finally:
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_mysql_replication_detach_stops_resets_and_enables_writes(
+ monkeypatch,
+):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ _writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ secondary.update({
+ "_shared_storage_initialized": True,
+ "_mysql_replication_source_arn": "source-arn",
+ "_mysql_replication_reset_pending": True,
+ "_mysql_replication_retry_marker": (7, "global-repl"),
+ })
+ statements = []
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+
+ def close(self):
+ pass
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(
+ m,
+ "_mysql_replication_connection",
+ lambda cluster: FakeConnection() if cluster is secondary else None,
+ )
+
+ assert m._detach_mysql_replication("secondary", secondary) is True
+ assert [statement for statement, _params in statements] == [
+ "STOP REPLICA",
+ "RESET REPLICA ALL",
+ "SET GLOBAL super_read_only=OFF",
+ ]
+ assert secondary["_mysql_replication_detach_state"] == "reset"
+ assert secondary["_mysql_replication_source_arn"] == "source-arn"
+
+ m._clear_mysql_replication_metadata(secondary)
+ assert "_mysql_replication_source_arn" not in secondary
+ assert "_mysql_replication_reset_pending" not in secondary
+ assert "_mysql_replication_retry_marker" not in secondary
+ assert "_mysql_replication_detach_state" not in secondary
+
+
+ "failed_statement",
+ [
+ "STOP REPLICA",
+ "RESET REPLICA ALL",
+ "SET GLOBAL super_read_only=OFF",
+ ],
+)
+def test_rds_mysql_replication_detach_statement_failures_are_recoverable(
+ monkeypatch,
+ failed_statement,
+):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ _writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ secondary.update({
+ "_shared_storage_initialized": True,
+ "_mysql_replication_source_arn": "source-arn",
+ })
+ statements = []
+ closed = []
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+ if statement == failed_statement:
+ raise RuntimeError(f"failed: {statement}")
+
+ def close(self):
+ closed.append("cursor")
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ closed.append("connection")
+
+ monkeypatch.setattr(
+ m,
+ "_mysql_replication_connection",
+ lambda cluster: FakeConnection() if cluster is secondary else None,
+ )
+ rollback_attempts = []
+ monkeypatch.setattr(
+ m,
+ "_configure_mysql_replication",
+ lambda cluster_id, cluster: rollback_attempts.append(
+ (cluster_id, cluster),
+ ) or False,
+ )
+
+ assert m._detach_mysql_replication("secondary", secondary) is False
+ assert secondary["_mysql_replication_detach_state"] == "requested"
+ assert secondary["_mysql_replication_source_arn"] == "source-arn"
+ assert rollback_attempts == [("secondary", secondary)]
+ assert [statement for statement, _params in statements][-1] == failed_statement
+ assert closed == ["cursor", "connection"]
+
+
+ "failed_statement",
+ [
+ "STOP REPLICA",
+ "RESET REPLICA ALL",
+ "SET GLOBAL super_read_only=OFF",
+ ],
+)
+def test_rds_mysql_replication_detach_failure_rolls_channel_back_atomically(
+ monkeypatch,
+ failed_statement,
+):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ secondary.update({
+ "_shared_storage_initialized": True,
+ "_mysql_replication_source_arn": writer["DBClusterArn"],
+ })
+ statements = []
+ failure_remaining = [True]
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+ if statement == failed_statement and failure_remaining[0]:
+ failure_remaining[0] = False
+ raise RuntimeError(f"failed once: {statement}")
+
+ def close(self):
+ pass
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(m, "_ensure_mysql_replication_user", lambda _cluster: True)
+ monkeypatch.setattr(m, "_mysql_replication_connection", lambda _cluster: FakeConnection())
+
+ assert m._detach_mysql_replication("secondary", secondary) is False
+ assert "_mysql_replication_detach_state" not in secondary
+ assert secondary["_mysql_replication_source_arn"] == writer["DBClusterArn"]
+ rollback_statements = [statement for statement, _params in statements]
+ assert "CHANGE REPLICATION SOURCE TO " in rollback_statements[-3]
+ assert rollback_statements[-2:] == [
+ "START REPLICA",
+ "SET GLOBAL super_read_only=ON",
+ ]
+
+
+ "rollback_failed_statement",
+ [
+ "START REPLICA",
+ "SET GLOBAL super_read_only=ON",
+ ],
+)
+def test_rds_mysql_replication_detach_partial_rollback_retries_from_requested(
+ monkeypatch,
+ rollback_failed_statement,
+):
+ from ministack.services import rds as m
+
+ topology = _mysql_replication_unit_topology()
+ writer, secondary, _writer_member, _secondary_member, _global = topology
+ _patch_mysql_replication_unit_topology(monkeypatch, m, topology)
+ secondary.update({
+ "_shared_storage_initialized": True,
+ "_mysql_replication_source_arn": writer["DBClusterArn"],
+ })
+ statements = []
+ failures = {
+ "SET GLOBAL super_read_only=OFF": 1,
+ rollback_failed_statement: 1,
+ }
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+ if failures.get(statement, 0):
+ failures[statement] -= 1
+ raise RuntimeError(f"failed once: {statement}")
+
+ def close(self):
+ pass
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(m, "_ensure_mysql_replication_user", lambda _cluster: True)
+ monkeypatch.setattr(m, "_mysql_replication_connection", lambda _cluster: FakeConnection())
+
+ assert m._detach_mysql_replication("secondary", secondary) is False
+ assert secondary["_mysql_replication_detach_state"] == "requested"
+ assert secondary["_mysql_replication_source_arn"] == writer["DBClusterArn"]
+
+ retry_start = len(statements)
+ assert m._detach_mysql_replication("secondary", secondary) is True
+ assert [statement for statement, _params in statements[retry_start:]] == [
+ "STOP REPLICA",
+ "RESET REPLICA ALL",
+ "SET GLOBAL super_read_only=OFF",
+ ]
+ assert secondary["_mysql_replication_detach_state"] == "reset"
+
+
+def test_rds_remove_global_secondary_keeps_membership_when_detach_fails(
+ monkeypatch,
+):
+ from ministack.core.responses import (
+ get_account_id,
+ set_request_account_id,
+ )
+ from ministack.services import rds as m
+
+ writer, secondary, writer_member, secondary_member, global_cluster = (
+ _mysql_replication_unit_topology()
+ )
+ m._clusters.clear()
+ m._global_clusters.clear()
+ original_account = get_account_id()
+ try:
+ set_request_account_id("111111111111")
+ m._clusters.set_scoped(
+ "111111111111", "us-east-1", "primary", writer,
+ )
+ m._clusters.set_scoped(
+ "111111111111", "us-west-2", "secondary", secondary,
+ )
+ m._global_clusters["global-repl"] = global_cluster
+ monkeypatch.setattr(m, "_detach_mysql_replication", lambda *_args: False)
+
+ status, _, body = m._remove_from_global_cluster({
+ "GlobalClusterIdentifier": "global-repl",
+ "DbClusterIdentifier": secondary["DBClusterArn"],
+ })
+
+ assert status == 400
+ assert b"InvalidDBClusterStateFault" in body
+ assert global_cluster["GlobalClusterMembers"] == [
+ writer_member,
+ secondary_member,
+ ]
+ assert secondary["GlobalClusterIdentifier"] == "global-repl"
+ finally:
+ set_request_account_id(original_account)
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_remove_headless_global_secondary_commits_detach_and_stops_applier(
+ monkeypatch,
+):
+ from ministack.core.responses import get_account_id, set_request_account_id
+ from ministack.services import rds as m
+
+ original_account = get_account_id()
+ account_id = "111111111111"
+ writer, secondary, writer_member, _secondary_member, global_cluster = (
+ _mysql_replication_unit_topology()
+ )
+ global_cluster.update({
+ "GlobalClusterArn": (
+ f"arn:aws:rds::{account_id}:global-cluster:global-repl"
+ ),
+ "GlobalClusterResourceId": "cluster-global-repl",
+ "Engine": "aurora-mysql",
+ "EngineVersion": DEFAULT_AURORA_MYSQL_ENGINE_VERSION,
+ "Status": "available",
+ })
+ secondary.update({
+ "DBClusterMembers": [],
+ "_shared_storage_initialized": True,
+ "_mysql_headless_applier_required": True,
+ "_mysql_replication_source_arn": writer["DBClusterArn"],
+ "_mysql_replication_detach_state": "reset",
+ })
+ stopped = []
+
+ m._clusters.clear()
+ m._global_clusters.clear()
+ try:
+ set_request_account_id(account_id)
+ m._clusters.set_scoped(account_id, "us-east-1", "primary", writer)
+ m._clusters.set_scoped(account_id, "us-west-2", "secondary", secondary)
+ m._global_clusters["global-repl"] = global_cluster
+ monkeypatch.setattr(m, "_detach_mysql_replication", lambda *_args: True)
+ monkeypatch.setattr(
+ m,
+ "_stop_empty_cluster_shared_container",
+ lambda cluster_id, cluster: stopped.append((cluster_id, cluster)),
+ )
+
+ status, _, body = m._remove_from_global_cluster({
+ "GlobalClusterIdentifier": "global-repl",
+ "DbClusterIdentifier": secondary["DBClusterArn"],
+ })
+
+ assert status == 200, body
+ assert global_cluster["GlobalClusterMembers"] == [writer_member]
+ assert "GlobalClusterIdentifier" not in secondary
+ assert "_mysql_headless_applier_required" not in secondary
+ assert "_mysql_replication_source_arn" not in secondary
+ assert "_mysql_replication_detach_state" not in secondary
+ assert stopped == [("secondary", secondary)]
+ finally:
+ set_request_account_id(original_account)
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_mysql_writer_password_rotation_syncs_global_member_metadata(
+ monkeypatch,
+):
+ from ministack.core.responses import (
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import rds as m
+
+ writer, secondary, _writer_member, _secondary_member, global_cluster = (
+ _mysql_replication_unit_topology()
+ )
+ writer.update({
+ "MasterUsername": "admin",
+ "_MasterUserPassword": "old-password",
+ "Status": "available",
+ "Port": 3306,
+ "DBClusterMembers": [{"DBInstanceIdentifier": "writer-instance"}],
+ "_shared_container_id": "writer-container",
+ })
+ secondary.update({
+ "MasterUsername": "admin",
+ "_MasterUserPassword": "old-password",
+ "DBClusterMembers": [{"DBInstanceIdentifier": "secondary-instance"}],
+ "_shared_endpoint": {"Address": "secondary", "Port": 3306},
+ })
+ secondary_instance = {"DBInstanceIdentifier": "secondary-instance"}
+ m._clusters.clear()
+ m._global_clusters.clear()
+ m._instances.clear()
+ original_account = get_account_id()
+ original_region = get_region()
+ try:
+ set_request_account_id("111111111111")
+ set_request_region("us-east-1")
+ m._clusters.set_scoped(
+ "111111111111", "us-east-1", "primary", writer,
+ )
+ m._clusters.set_scoped(
+ "111111111111", "us-west-2", "secondary", secondary,
+ )
+ m._global_clusters["global-repl"] = global_cluster
+ m._instances.set_scoped(
+ "111111111111",
+ "us-west-2",
+ "secondary-instance",
+ secondary_instance,
+ )
+ monkeypatch.setattr(m, "_rotate_real_password", lambda *_args: True)
+
+ status, _, _body = m._modify_db_cluster({
+ "DBClusterIdentifier": "primary",
+ "MasterUserPassword": "new-password",
+ })
+
+ assert status == 200
+ assert writer["_MasterUserPassword"] == "new-password"
+ assert secondary["_MasterUserPassword"] == "new-password"
+ assert secondary_instance["_MasterUserPassword"] == "new-password"
+
+ set_request_region("us-west-2")
+ status, _, body = m._modify_db_cluster({
+ "DBClusterIdentifier": "secondary",
+ "MasterUserPassword": "secondary-only-password",
+ })
+ assert status == 400
+ assert b"InvalidDBClusterStateFault" in body
+ assert secondary["_MasterUserPassword"] == "new-password"
+ finally:
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
[email protected]("persisted_account", ["000000000000", "222222222222"])
+def test_rds_restore_syncs_stale_secondary_credentials_from_global_writer(
+ persisted_account,
+):
+ from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ get_account_id,
+ )
+ from ministack.services import rds as m
+
+ active_account = get_account_id()
+ account_id = persisted_account
+ assert active_account == "000000000000"
+ writer_arn = f"arn:aws:rds:us-east-1:{account_id}:cluster:primary"
+ secondary_arn = f"arn:aws:rds:us-west-2:{account_id}:cluster:secondary"
+ writer = {
+ "DBClusterIdentifier": "primary",
+ "DBClusterArn": writer_arn,
+ "Engine": "aurora-mysql",
+ "EngineVersion": "8.0.mysql_aurora.3.10.3",
+ "GlobalClusterIdentifier": "global-repl",
+ "MasterUsername": "admin",
+ "_MasterUserPassword": "rotated-password",
+ "DatabaseName": "global_db",
+ "DBClusterMembers": [],
+ }
+ secondary = {
+ "DBClusterIdentifier": "secondary",
+ "DBClusterArn": secondary_arn,
+ "Engine": "aurora-mysql",
+ "EngineVersion": "8.0.mysql_aurora.3.10.3",
+ "GlobalClusterIdentifier": "global-repl",
+ "MasterUsername": "stale-admin",
+ "_MasterUserPassword": "stale-password",
+ "DatabaseName": "stale_db",
+ "DBClusterMembers": [],
+ }
+ clusters = AccountRegionScopedDict()
+ clusters.set_scoped(account_id, "us-east-1", "primary", writer)
+ clusters.set_scoped(account_id, "us-west-2", "secondary", secondary)
+ global_clusters = AccountScopedDict()
+ global_clusters.set_scoped(account_id, None, "global-repl", {
+ "GlobalClusterIdentifier": "global-repl",
+ "GlobalClusterMembers": [
+ {"DBClusterArn": writer_arn, "IsWriter": True},
+ {"DBClusterArn": secondary_arn, "IsWriter": False},
+ ],
+ })
+
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+ try:
+ m.restore_state({
+ "instances": AccountRegionScopedDict(),
+ "clusters": clusters,
+ "global_clusters": global_clusters,
+ })
+
+ restored_secondary = m._clusters.get_scoped(
+ account_id,
+ "us-west-2",
+ "secondary",
+ )
+ assert restored_secondary["MasterUsername"] == "admin"
+ assert restored_secondary["_MasterUserPassword"] == "rotated-password"
+ assert restored_secondary["DatabaseName"] == "global_db"
+ finally:
+ m._instances.clear()
+ m._clusters.clear()
+ m._global_clusters.clear()
+
+
+def test_rds_mysql_control_user_is_local_and_used_for_replica_sql(monkeypatch):
+ from ministack.services import rds as m
+
+ cluster = {"DBClusterIdentifier": "secondary"}
+ statements = []
+ connection_args = []
+
+ class FakeCursor:
+ def execute(self, statement, params=None):
+ statements.append((statement, params))
+
+ def close(self):
+ pass
+
+ class FakeConnection:
+ def cursor(self):
+ return FakeCursor()
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(m, "_mysql_admin_connection", lambda _cluster: FakeConnection())
+
+ assert m._ensure_mysql_control_user(cluster) is True
+ assert statements[0][0] == "SET SESSION sql_log_bin=0"
+ assert cluster["_mysql_control_user_ready"] is True
+
+ monkeypatch.setattr(
+ m,
+ "_mysql_cluster_connection",
+ lambda target, user, password: connection_args.append(
+ (target, user, password),
+ ) or FakeConnection(),
+ )
+ m._mysql_replication_connection(cluster)
+ assert connection_args == [
+ (cluster, m._MYSQL_CONTROL_USER, m._MYSQL_CONTROL_PASSWORD),
+ ]
+
+
+def _wait_for_replica_status(endpoint, timeout=120):
+ import pymysql
+
+ deadline = time.time() + timeout
+ last_status = None
+ while time.time() < deadline:
+ try:
+ with _aurora_connect(endpoint) as conn:
+ with conn.cursor(pymysql.cursors.DictCursor) as cursor:
+ cursor.execute("SHOW REPLICA STATUS")
+ last_status = cursor.fetchone()
+ if (
+ last_status
+ and last_status["Replica_IO_Running"] == "Yes"
+ and last_status["Replica_SQL_Running"] == "Yes"
+ ):
+ return last_status
+ except (pymysql.err.OperationalError, OSError):
+ pass
+ time.sleep(1)
+ pytest.fail(f"replica was not healthy after {timeout}s: {last_status!r}")
+
+
+def _wait_for_gtid(
+ writer_endpoint,
+ secondary_endpoint,
+ timeout=30,
+ password=PASSWORD,
+):
+ with _aurora_connect(writer_endpoint, password=password) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute("SELECT @@GLOBAL.gtid_executed")
+ executed = cursor.fetchone()[0]
+ assert executed, "writer did not report an executed GTID set"
+
+ with _aurora_connect(secondary_endpoint, password=password) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "SELECT WAIT_FOR_EXECUTED_GTID_SET(%s, %s)",
+ (executed, timeout),
+ )
+ result = cursor.fetchone()[0]
+ assert result == 0, (
+ f"secondary did not execute writer GTID set within {timeout}s: "
+ f"result={result!r}, gtid={executed!r}"
+ )
+
+
+ not os.environ.get("DOCKER_NETWORK"),
+ reason="DOCKER_NETWORK not set -- live Aurora global replication",
+)
+def test_aurora_mysql_global_replication_replays_and_streams_rows():
+ import pymysql
+
+ east = _regional_rds("us-east-1")
+ west = _regional_rds("us-west-2")
+ suffix = uuid.uuid4().hex[:10]
+ global_id = f"global-repl-{suffix}"
+ primary_id = f"global-repl-primary-{suffix}"
+ primary_instance_id = f"{primary_id}-writer"
+ secondary_id = f"global-repl-secondary-{suffix}"
+ secondary_instance_id = f"{secondary_id}-reader"
+ engine_version = "8.0.mysql_aurora.3.10.3"
+ rotated_password = f"rotated-{suffix}"
+ primary_arn = None
+ secondary_arn = None
+
+ try:
+ primary = east.create_db_cluster(
+ DBClusterIdentifier=primary_id,
+ Engine="aurora-mysql",
+ EngineVersion=engine_version,
+ MasterUsername="admin",
+ MasterUserPassword=PASSWORD,
+ DatabaseName=DATABASE,
+ )["DBCluster"]
+ primary_arn = primary["DBClusterArn"]
+ east.create_db_instance(
+ DBInstanceIdentifier=primary_instance_id,
+ DBClusterIdentifier=primary_id,
+ DBInstanceClass="db.r6g.large",
+ Engine="aurora-mysql",
+ )
+ primary_instance = _wait_for_instance(east, primary_instance_id)
+
+ with _aurora_connect(primary_instance["Endpoint"]) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "CREATE TABLE global_replication_rows "
+ "(id INT PRIMARY KEY, value VARCHAR(32))"
+ )
+ cursor.execute(
+ "INSERT INTO global_replication_rows VALUES (1, 'before-link')"
+ )
+
+ east.create_global_cluster(
+ GlobalClusterIdentifier=global_id,
+ SourceDBClusterIdentifier=primary_arn,
+ )
+ secondary = west.create_db_cluster(
+ DBClusterIdentifier=secondary_id,
+ Engine="aurora-mysql",
+ EngineVersion=engine_version,
+ GlobalClusterIdentifier=global_id,
+ MasterUsername="admin",
+ MasterUserPassword=PASSWORD,
+ DatabaseName=DATABASE,
+ )["DBCluster"]
+ secondary_arn = secondary["DBClusterArn"]
+ west.create_db_instance(
+ DBInstanceIdentifier=secondary_instance_id,
+ DBClusterIdentifier=secondary_id,
+ DBInstanceClass="db.r6g.large",
+ Engine="aurora-mysql",
+ )
+ secondary_instance = _wait_for_instance(west, secondary_instance_id)
+
+ replica_status = _wait_for_replica_status(secondary_instance["Endpoint"])
+ assert int(replica_status["Auto_Position"]) == 1
+ assert replica_status["Last_IO_Error"] == ""
+ assert replica_status["Last_SQL_Error"] == ""
+
+ _wait_for_gtid(
+ primary_instance["Endpoint"],
+ secondary_instance["Endpoint"],
+ )
+ with _aurora_connect(secondary_instance["Endpoint"]) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute("SELECT id, value FROM global_replication_rows ORDER BY id")
+ assert cursor.fetchall() == ((1, "before-link"),)
+
+ with _aurora_connect(primary_instance["Endpoint"]) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "INSERT INTO global_replication_rows VALUES (2, 'after-link')"
+ )
+ _wait_for_gtid(
+ primary_instance["Endpoint"],
+ secondary_instance["Endpoint"],
+ )
+ with _aurora_connect(secondary_instance["Endpoint"]) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute("SELECT id, value FROM global_replication_rows ORDER BY id")
+ assert cursor.fetchall() == (
+ (1, "before-link"),
+ (2, "after-link"),
+ )
+ with pytest.raises(pymysql.err.OperationalError) as exc_info:
+ cursor.execute(
+ "INSERT INTO global_replication_rows VALUES (3, 'secondary-write')"
+ )
+ assert exc_info.value.args[0] == 1290
+
+ with _aurora_connect(primary_instance["Endpoint"]) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "INSERT INTO global_replication_rows VALUES (3, 'primary-write')"
+ )
+ _wait_for_gtid(
+ primary_instance["Endpoint"],
+ secondary_instance["Endpoint"],
+ )
+
+ east.modify_db_cluster(
+ DBClusterIdentifier=primary_id,
+ MasterUserPassword=rotated_password,
+ )
+ _wait_for_gtid(
+ primary_instance["Endpoint"],
+ secondary_instance["Endpoint"],
+ password=rotated_password,
+ )
+
+ # A global secondary without DB instances still owns synchronized
+ # storage. The saved endpoint is intentionally used only as a direct
+ # test probe for MiniStack's internal applier after the public instance
+ # record is gone.
+ headless_applier_endpoint = secondary_instance["Endpoint"]
+ west.delete_db_instance(
+ DBInstanceIdentifier=secondary_instance_id,
+ SkipFinalSnapshot=True,
+ )
+ with pytest.raises(ClientError) as exc_info:
+ west.describe_db_instances(
+ DBInstanceIdentifier=secondary_instance_id,
+ )
+ assert exc_info.value.response["Error"]["Code"] == "DBInstanceNotFound"
+
+ with _aurora_connect(
+ primary_instance["Endpoint"],
+ password=rotated_password,
+ ) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "INSERT INTO global_replication_rows VALUES "
+ "(4, 'while-secondary-headless')"
+ )
+ _wait_for_gtid(
+ primary_instance["Endpoint"],
+ headless_applier_endpoint,
+ password=rotated_password,
+ )
+
+ east.remove_from_global_cluster(
+ GlobalClusterIdentifier=global_id,
+ DbClusterIdentifier=secondary_arn,
+ )
+ west.create_db_instance(
+ DBInstanceIdentifier=secondary_instance_id,
+ DBClusterIdentifier=secondary_id,
+ DBInstanceClass="db.r6g.large",
+ Engine="aurora-mysql",
+ )
+ secondary_instance = _wait_for_instance(west, secondary_instance_id)
+ with _aurora_connect(
+ secondary_instance["Endpoint"],
+ password=rotated_password,
+ ) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "INSERT INTO global_replication_rows VALUES "
+ "(5, 'detached-secondary')"
+ )
+
+ with _aurora_connect(
+ primary_instance["Endpoint"],
+ password=rotated_password,
+ ) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "INSERT INTO global_replication_rows VALUES (6, 'after-detach')"
+ )
+ time.sleep(2)
+ with _aurora_connect(
+ secondary_instance["Endpoint"],
+ password=rotated_password,
+ ) as conn:
+ with conn.cursor() as cursor:
+ cursor.execute(
+ "SELECT id, value FROM global_replication_rows ORDER BY id"
+ )
+ assert cursor.fetchall() == (
+ (1, "before-link"),
+ (2, "after-link"),
+ (3, "primary-write"),
+ (4, "while-secondary-headless"),
+ (5, "detached-secondary"),
+ )
+ finally:
+ if secondary_arn:
+ _remove_global_member(east, global_id, secondary_arn)
+ if primary_arn:
+ _remove_global_member(east, global_id, primary_arn)
+ _delete_instance(west, secondary_instance_id)
+ _delete_instance(east, primary_instance_id)
+ _delete_cluster(west, secondary_id)
+ _delete_cluster(east, primary_id)
+ _delete_global_cluster(east, global_id)