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
fix(rds): restart database compute on instance reboot (#2217)
Jay Janssenf68314c62c44
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0246da73..8b4928f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Changed+- **RDS — real instance reboot** — `RebootDBInstance` now returns `rebooting`, stops and starts its backing database container, and waits for SQL readiness before reporting `available`. Data and endpoint bindings are preserved. Optional `RDS_REBOOT_DOWNTIME_SECONDS` (0–3600, default 0) holds the engine stopped for local outage testing. Docker failures no longer report a successful reboot.+### Added- **S3 Control — Multi-Region Access Points** — `CreateMultiRegionAccessPoint`, `DeleteMultiRegionAccessPoint`, `PutMultiRegionAccessPointPolicy`, `DescribeMultiRegionAccessPointOperation`, `GetMultiRegionAccessPoint`, `GetMultiRegionAccessPointPolicy`, `ListMultiRegionAccessPoints`, `GetMultiRegionAccessPointRoutes` and `SubmitMultiRegionAccessPointRoutes`. The async operations apply at once and `Describe` reports `SUCCEEDED`, or `FAILED` with AWS's `ErrorDetails` for a missing bucket, two buckets in one region or a name already in use. Management is served from `us-west-2` and route operations from `us-east-1`, `us-west-2`, `eu-west-1`, `ap-northeast-1` and `ap-southeast-2`, as on AWS; other regions get `301 PermanentRedirect`. `DeleteBucket` on a member returns `BucketHasAccessPointsAttached`. Under `AUTH=true` each operation needs its `s3:` IAM action. Access points from `AWS::S3::MultiRegionAccessPoint` appear in the API.- **S3 — Multi-Region Access Point failover** — a request through the MRAP host goes to the member with a traffic dial of 100 that is homed in `MINISTACK_REGION`, else the first active member. Setting a dial to 0 moves traffic to the other member, and an update that leaves every dial at 0 is refused.diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 2fa3da38..290e0811 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -5613,9 +5613,90 @@ def _stop_db_instance(p):def _reboot_db_instance(p):- return _set_db_instance_status(- p, "available", "RebootDBInstanceResponse", "RebootDBInstanceResult",- )+ # Offloaded requests can arrive concurrently; claim rebooting atomically.+ with _shared_container_lock:+ return _begin_instance_reboot(p)+++def _begin_instance_reboot(p):+ db_id = _p(p, "DBInstanceIdentifier")+ instance = _resolve_instance(db_id)+ if not instance:+ invalid_arn = _invalid_db_instance_identifier_error(db_id)+ if invalid_arn:+ return invalid_arn+ return _error("DBInstanceNotFound", f"DBInstance {db_id} not found.", 404)+ if instance.get("DBInstanceStatus") != "available":+ return _error("InvalidDBInstanceState", "DB instance must be available to reboot.", 400)+ # A local fault-injection setting, not an AWS request parameter. Keep the+ # engine stopped during this interval so clients experience real downtime.+ try:+ downtime = float(os.environ.get("RDS_REBOOT_DOWNTIME_SECONDS", "0"))+ if not 0 <= downtime <= 3600:+ raise ValueError+ except ValueError:+ return _error("InvalidParameterValue", "RDS_REBOOT_DOWNTIME_SECONDS must be between 0 and 3600.", 400)+ cluster_id = instance.get("_shared_cluster_id") or instance.get("DBClusterIdentifier")+ cluster = _resolve_cluster_in_request_region(cluster_id) if cluster_id else None+ if cluster and (switch_error := _begin_mysql_global_instance_mutation(cluster)):+ return switch_error+ instance["DBInstanceStatus"] = "rebooting"+ # Serialize the response before starting the worker: a fast local reboot+ # must not race the response back to available.+ response = _single_instance_response("RebootDBInstanceResponse", "RebootDBInstanceResult", instance)+ context = contextvars.copy_context()+ threading.Thread(+ target=context.run, args=(_finish_instance_reboot, instance, cluster, downtime),+ daemon=True,+ ).start()+ return response+++def _finish_instance_reboot(instance, cluster, downtime):+ db_id = instance["DBInstanceIdentifier"]++ def current():+ return _instances.get(db_id) is instance and instance.get("DBInstanceStatus") == "rebooting"++ try:+ client = _get_docker()+ container_id = instance.get("_docker_container_id")+ if client and container_id:+ container = client.containers.get(container_id)+ container.stop(timeout=5)+ if downtime:+ time.sleep(downtime)+ if not current():+ return+ container.start()++ def alive():+ if not current():+ return False+ container.reload()+ return container.status not in ("exited", "dead", "removing")++ endpoint = instance.get("Endpoint", {})+ host = instance.get("_internal_address") or "127.0.0.1"+ port = instance.get("_internal_port") or instance.get("_HostPort") or endpoint.get("Port")+ if not _wait_for_database_ready(+ host, port, instance.get("Engine", "mysql"),+ instance.get("MasterUsername", "root"),+ instance.get("_MasterUserPassword", "password"),+ instance.get("DBName"), alive,+ ):+ raise RuntimeError("database stopped before reboot readiness")+ elif downtime:+ time.sleep(downtime)+ if current():+ instance["DBInstanceStatus"] = "available"+ except Exception:+ logger.exception("RDS: reboot failed for %s", db_id)+ if current():+ instance["DBInstanceStatus"] = "failed"+ finally:+ if cluster:+ _end_mysql_global_instance_mutation(cluster)# ---------------------------------------------------------------------------diff --git a/tests/test_rds.py b/tests/test_rds.pyindex f9fb1645..6da03ad7 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -4829,7 +4829,7 @@ def test_rds_create_read_replica_source_not_found(rds):def test_rds_reboot_db_instance(rds):- """RebootDBInstance sets the instance status back to available."""+ """RebootDBInstance returns rebooting, then converges to available."""rds.create_db_instance(DBInstanceIdentifier="reboot-test",DBInstanceClass="db.t3.micro",@@ -4839,8 +4839,10 @@ def test_rds_reboot_db_instance(rds):AllocatedStorage=10,)try:+ rds.get_waiter("db_instance_available").wait(DBInstanceIdentifier="reboot-test", WaiterConfig={"Delay": 1, "MaxAttempts": 120})resp = rds.reboot_db_instance(DBInstanceIdentifier="reboot-test")- assert resp["DBInstance"]["DBInstanceStatus"] == "available"+ assert resp["DBInstance"]["DBInstanceStatus"] == "rebooting"+ rds.get_waiter("db_instance_available").wait(DBInstanceIdentifier="reboot-test", WaiterConfig={"Delay": 1, "MaxAttempts": 120})desc = rds.describe_db_instances(DBInstanceIdentifier="reboot-test")assert desc["DBInstances"][0]["DBInstanceStatus"] == "available"diff --git a/tests/test_rds_reboot.py b/tests/test_rds_reboot.pynew file mode 100644index 00000000..82e8f849--- /dev/null+++ b/tests/test_rds_reboot.py@@ -0,0 +1,156 @@+"""RDS reboot lifecycle; direct handler tests do not require a running server."""+import threading+import time+from types import SimpleNamespace++import pytest++from ministack.services import rds+++def instance(monkeypatch):+ monkeypatch.setattr(rds, "_single_instance_response", lambda *args: args[-1].copy())+ value = {+ "DBInstanceIdentifier": "reboot-test", "DBInstanceStatus": "available",+ "Engine": "mysql", "MasterUsername": "root", "_MasterUserPassword": "test",+ "_docker_container_id": "owned", "_HostPort": 13306,+ "Endpoint": {"Address": "localhost", "Port": 13306},+ }+ rds._instances["reboot-test"] = value+ yield value+ rds._instances.pop("reboot-test", None)+++def test_reboot_is_async_and_waits_for_sql(monkeypatch, instance):+ entered = threading.Event()+ release = threading.Event()+ done = threading.Event()+ calls = []+ class Container:+ status = "running"+ def stop(self, timeout):+ calls.append("stop")+ def start(self):+ calls.append("start")+ def reload(self):+ pass+ monkeypatch.setattr(rds, "_get_docker", lambda: SimpleNamespace(containers=SimpleNamespace(get=lambda ident: Container())))+ def ready(*args):+ calls.append("ready")+ entered.set()+ assert release.wait(5)+ return True+ monkeypatch.setattr(rds, "_wait_for_database_ready", ready)+ original = rds._finish_instance_reboot+ def finish(*args):+ try:+ original(*args)+ finally:+ done.set()+ monkeypatch.setattr(rds, "_finish_instance_reboot", finish)+ try:+ rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})+ assert entered.wait(5)+ assert instance["DBInstanceStatus"] == "rebooting"+ assert calls == ["stop", "start", "ready"]+ finally:+ release.set()+ assert done.wait(5)+ assert instance["DBInstanceStatus"] == "available"++[email protected]_plane+def test_reboot_preserves_mysql_data_and_breaks_sessions(monkeypatch, instance):+ import docker+ import pymysql++ import socket+ client = docker.from_env()+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ port = sock.getsockname()[1]+ container = client.containers.run(+ "mysql:8.0", detach=True, ports={"3306/tcp": ("127.0.0.1", port)},+ environment={"MYSQL_ROOT_PASSWORD": "test", "MYSQL_ROOT_HOST": "%"},+ )+ connection = None+ try:+ container.reload()+ port = int(container.attrs["NetworkSettings"]["Ports"]["3306/tcp"][0]["HostPort"])+ instance["_HostPort"] = port+ instance["_docker_container_id"] = container.id+ def connect():+ return pymysql.connect(host="127.0.0.1", port=port, user="root", password="test", connect_timeout=2, read_timeout=2, autocommit=True)+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ try:+ connection = connect()+ break+ except pymysql.Error:+ time.sleep(0.5)+ assert connection is not None+ with connection.cursor() as cursor:+ cursor.execute("CREATE DATABASE reboot_test")+ cursor.execute("CREATE TABLE reboot_test.evidence (value INT)")+ cursor.execute("INSERT INTO reboot_test.evidence VALUES (42)")+ monkeypatch.setattr(rds, "_get_docker", lambda: client)+ monkeypatch.setenv("RDS_REBOOT_DOWNTIME_SECONDS", "2")+ response = rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})+ assert response["DBInstanceStatus"] == "rebooting"+ deadline = time.monotonic() + 90+ while instance["DBInstanceStatus"] == "rebooting" and time.monotonic() < deadline:+ time.sleep(0.2)+ assert instance["DBInstanceStatus"] == "available"+ with pytest.raises(pymysql.Error):+ connection.ping(reconnect=False)+ with connect() as recovered:+ with recovered.cursor() as cursor:+ cursor.execute("SELECT value FROM reboot_test.evidence")+ assert cursor.fetchone() == (42,)+ finally:+ if connection:+ connection.close()+ container.remove(force=True, v=True)+++def test_downtime_is_between_stop_and_start(monkeypatch, instance):+ calls = []+ container = SimpleNamespace(stop=lambda **kw: calls.append("stop"), start=lambda: calls.append("start"))+ monkeypatch.setattr(rds, "_get_docker", lambda: SimpleNamespace(containers=SimpleNamespace(get=lambda ident: container)))+ monkeypatch.setattr(rds.time, "sleep", lambda seconds: calls.append(seconds))+ monkeypatch.setattr(rds, "_wait_for_database_ready", lambda *a: True)+ instance["DBInstanceStatus"] = "rebooting"+ rds._finish_instance_reboot(instance, None, 7)+ assert calls == ["stop", 7, "start"]+ assert instance["DBInstanceStatus"] == "available"+++def test_failed_restart_does_not_report_available(monkeypatch, instance):+ def fail():+ raise RuntimeError("Docker unavailable")+ monkeypatch.setattr(rds, "_get_docker", fail)+ instance["DBInstanceStatus"] = "rebooting"+ rds._finish_instance_reboot(instance, None, 0)+ assert instance["DBInstanceStatus"] == "failed"+++def test_deleted_instance_is_not_resurrected(monkeypatch, instance):+ replacement = dict(instance)+ def ready(*args):+ rds._instances["reboot-test"] = replacement+ return True+ container = SimpleNamespace(stop=lambda **kw: None, start=lambda: None)+ monkeypatch.setattr(rds, "_get_docker", lambda: SimpleNamespace(containers=SimpleNamespace(get=lambda ident: container)))+ monkeypatch.setattr(rds, "_wait_for_database_ready", ready)+ instance["DBInstanceStatus"] = "rebooting"+ rds._finish_instance_reboot(instance, None, 0)+ assert rds._instances["reboot-test"] is replacement+ assert instance["DBInstanceStatus"] == "rebooting"++[email protected]("delay", ["-1", "nan", "inf", "bad", "3601"])+def test_invalid_downtime_is_rejected(monkeypatch, instance, delay):+ monkeypatch.setenv("RDS_REBOOT_DOWNTIME_SECONDS", delay)+ rds._reboot_db_instance({"DBInstanceIdentifier": "reboot-test"})+ assert instance["DBInstanceStatus"] == "available"