Skip to content

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

fix(rds): keep database containers reachable under MINISTACK_RDS_PUBLIC_ENDPOINT (#1885)

Jeff Heller7692452d8f4c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a9527668..5d480032 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **RDS — instances become `available` under `MINISTACK_RDS_PUBLIC_ENDPOINT=1` in a container** — with the setting on, database containers were left off MiniStack's network and readiness dialled `127.0.0.1:<host port>`, which inside MiniStack's own container is not the database, so a new instance or cluster stayed `creating` forever. A containerised MiniStack now keeps its database containers on its network for readiness and internal wiring, and still reports `{MINISTACK_HOST, host_port}` for writer and reader endpoints; DSQL, which shares the network lookup, gets the same reachable backend. A MiniStack running on the host is unchanged. Fixes #1884.
- **IoT — `RegisterCACertificate` checks the verification certificate** — in `DEFAULT` mode a CA now registers only with a `verificationCertificate` that the CA signed and whose CN is the account's registration code, `SNI_ONLY` refuses one, and each failure returns the error AWS returns, so an `AWS::IoT::CACertificate` in `DEFAULT` mode without `VerificationCertificatePem` fails as well.
- **CloudFormation — `OnFailure` and `OnStackFailure` are honoured** — CreateStack `OnFailure=DO_NOTHING` leaves a failed create in `CREATE_FAILED`, as `DisableRollback=true` does, and `DELETE` rolls the create back and then deletes the stack, which ends `DELETE_COMPLETE` (or `DELETE_FAILED` when a resource does not delete). `OnFailure` together with `DisableRollback` is a `ValidationError`. CreateChangeSet `OnStackFailure` makes the same choice when the change set executes; `DELETE` is refused unless `ChangeSetType` is `CREATE`, DescribeChangeSet reports the value, and ExecuteChangeSet refuses `DisableRollback` for such a change set. ExecuteChangeSet ignored `DisableRollback=true` and rolled back anyway; it now leaves the failed operation in `CREATE_FAILED` or `UPDATE_FAILED`.
- **CloudFormation — `DeleteStack` takes `DeletionMode=FORCE_DELETE_STACK`** — on a `DELETE_FAILED` stack, the resources that failed to delete and the resources they depend on are retained with a `DELETE_SKIPPED` event, and the stack reaches `DELETE_COMPLETE`. On any other status the call is a `ValidationError`, and DescribeStacks reports the stack's `DeletionMode`.
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index f378919a..d4be75a9 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -92,11 +92,10 @@ BASE_PORT = int(os.environ.get("RDS_BASE_PORT", "15432"))
RDS_TMPFS_SIZE = os.environ.get("RDS_TMPFS_SIZE", "256m")
RDS_PERSIST = os.environ.get("RDS_PERSIST", "0").lower() in ("1", "true", "yes")
DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
-# When set, skip ministack's own Docker network auto-detect so DescribeDBInstances
-# returns {MINISTACK_HOST, host_port} — the address that's actually reachable
-# from outside the Docker network (remote ministack deployments, host-side
-# clients of a containerised ministack). Off by default: existing in-network
-# behavior unchanged.
+# When set, DescribeDBInstances returns {MINISTACK_HOST, host_port} — the
+# address that's actually reachable from outside the Docker network (remote
+# ministack deployments, host-side clients of a containerised ministack).
+# Off by default: existing in-network behavior unchanged.
RDS_PUBLIC_ENDPOINT = os.environ.get("MINISTACK_RDS_PUBLIC_ENDPOINT", "0").lower() in ("1", "true", "yes")
# Opt-in: per-instance Aurora PostgreSQL reader containers backed by real
# streaming replication (#1325). Scoped to aurora-postgresql by name and by
@@ -1372,13 +1371,14 @@ def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):
networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
container_ip = networks.get(ms_network, {}).get("IPAddress", "")
if container_ip:
- # Report the alias, not the address behind it. An address changes
+ # Report the alias (or, under MINISTACK_RDS_PUBLIC_ENDPOINT, the
+ # published port), not the address behind it. An address changes
# when the container is replaced, and every consumer holding the
# old one is then pointing at whatever took over that IP. Internal
# wiring and the readiness probe keep using the address.
- endpoint_host = (endpoint_aliases[0] if endpoint_aliases
- else container_ip)
- endpoint_port = container_port
+ endpoint_host, endpoint_port = _reported_endpoint(
+ endpoint_aliases[0] if endpoint_aliases else container_ip,
+ container_port, host_port)
internal_host = container_ip
internal_port = container_port
readiness_host = container_ip
@@ -1614,8 +1614,8 @@ def _start_pg_reader_container(db_id, cluster):
networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
container_ip = networks.get(ms_network, {}).get("IPAddress", "")
if container_ip:
- endpoint_host = container_ip
- endpoint_port = container_port
+ endpoint_host, endpoint_port = _reported_endpoint(
+ container_ip, container_port, host_port)
internal_host = container_ip
internal_port = container_port
except Exception:
@@ -2285,13 +2285,13 @@ def _restart_cluster_shared_container(cluster_id, cluster):
networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
container_ip = networks.get(ms_network, {}).get("IPAddress", "")
if container_ip:
- # Report the alias, not the address behind it — same rule as first
- # launch. StopDBCluster/StartDBCluster must not rewrite a stored
+ # Report the alias (or the published port), not the address behind
+ # it — same rule as first launch. StopDBCluster/StartDBCluster must not rewrite a stored
# DNS name into a raw address: the name keeps resolving to the
# restarted container, while the address may not survive.
- endpoint_host = (endpoint_aliases[0] if endpoint_aliases
- else container_ip)
- endpoint_port = container_port
+ endpoint_host, endpoint_port = _reported_endpoint(
+ endpoint_aliases[0] if endpoint_aliases else container_ip,
+ container_port, host_port)
internal_host = container_ip
internal_port = container_port
readiness_host = container_ip
@@ -2501,8 +2501,9 @@ def _start_rds_container_for_instance(db_id, instance):
if container_ip:
internal_host = container_ip
internal_port = container_port
- instance.setdefault("Endpoint", {})["Address"] = container_ip
- instance["Endpoint"]["Port"] = container_port
+ endpoint = instance.setdefault("Endpoint", {})
+ endpoint["Address"], endpoint["Port"] = _reported_endpoint(
+ container_ip, container_port, host_port)
except Exception:
pass
instance["_internal_address"] = internal_host
@@ -2552,17 +2553,15 @@ def _get_docker():
def _get_ministack_network(docker_client):
"""Detect the Docker network MiniStack is running on (if containerised).
- Honors MINISTACK_RDS_PUBLIC_ENDPOINT — when set, returns None so the
- DescribeDBInstances endpoint resolves to {MINISTACK_HOST, host_port}
- instead of the container-internal address (useful for remote-ministack
- deployments where external clients can't reach the Docker network).
+ Under MINISTACK_RDS_PUBLIC_ENDPOINT the database containers join the
+ network only when MiniStack itself is containerised, so readiness and
+ internal wiring can reach them while _reported_endpoint reports the
+ published port.
"""
global _ministack_network
- if RDS_PUBLIC_ENDPOINT:
- return None
if _ministack_network is not None:
return _ministack_network or None
- if DOCKER_NETWORK:
+ if DOCKER_NETWORK and not RDS_PUBLIC_ENDPOINT:
_ministack_network = DOCKER_NETWORK
logger.debug("RDS: using DOCKER_NETWORK=%s", DOCKER_NETWORK)
return DOCKER_NETWORK
@@ -2572,7 +2571,8 @@ def _get_ministack_network(docker_client):
nets = list(
self_container.attrs["NetworkSettings"]["Networks"].keys())
if nets:
- _ministack_network = nets[0]
+ _ministack_network = (DOCKER_NETWORK if DOCKER_NETWORK in nets
+ else nets[0])
logger.debug("RDS: detected MiniStack network: %s",
_ministack_network)
return _ministack_network
@@ -2583,6 +2583,13 @@ def _get_ministack_network(docker_client):
return None
+def _reported_endpoint(host, port, host_port):
+ """The endpoint DescribeDB* report for a container on MiniStack's network."""
+ if RDS_PUBLIC_ENDPOINT:
+ return _MINISTACK_HOST, host_port
+ return host, port
+
+
def _wait_for_port(host, port, timeout=60):
"""Block until a TCP connection to host:port succeeds."""
deadline = time.time() + timeout
@@ -4443,6 +4450,10 @@ def _sync_cluster_endpoints(cluster):
reader_address = writer_address.replace(
".cluster-", ".cluster-ro-", 1,
)
+ elif RDS_PUBLIC_ENDPOINT:
+ # The internal address is not reachable by the clients the
+ # published endpoint is reported to.
+ reader_address = writer_address
else:
reader_address = (
cluster.get("_shared_internal_address")
@@ -4767,8 +4778,8 @@ def _create_db_instance_impl(p):
if container_ip:
internal_host = container_ip
internal_port = container_port
- endpoint_host = container_ip
- endpoint_port = container_port
+ endpoint_host, endpoint_port = _reported_endpoint(
+ container_ip, container_port, host_port)
readiness_host = container_ip
readiness_port = container_port
else:
diff --git a/tests/test_rds.py b/tests/test_rds.py
index 5b4fb2d1..0f7e197d 100644
--- a/tests/test_rds.py
+++ b/tests/test_rds.py
@@ -16159,3 +16159,191 @@ def test_rds_server_certificate_without_cryptography_raises(monkeypatch):
monkeypatch.setattr(x509_utils, "HAS_CRYPTO", False)
with pytest.raises(RuntimeError, match="requires the `cryptography` package"):
rds_service._pg_server_material(["localhost"], [])
+
+
+def _fake_docker_self(networks):
+ """A Docker client whose HOSTNAME lookup finds MiniStack's own container."""
+
+ class FakeContainers:
+ def get(self, _identifier):
+ if networks is None:
+ raise Exception("not a container")
+ return types.SimpleNamespace(
+ attrs={"NetworkSettings": {"Networks": {n: {} for n in networks}}})
+
+ class FakeDocker:
+ containers = FakeContainers()
+
+ return FakeDocker()
+
+
+def test_rds_public_endpoint_containerised_ministack_joins_its_network(monkeypatch):
+ """#1884: the database container must stay reachable from a containerised MiniStack."""
+ from ministack.services import rds as m
+
+ monkeypatch.setattr(m, "RDS_PUBLIC_ENDPOINT", True)
+ monkeypatch.setattr(m, "DOCKER_NETWORK", "compose_default")
+ monkeypatch.setattr(m, "_ministack_network", None)
+ client = _fake_docker_self(["bridge", "compose_default"])
+ assert m._get_ministack_network(client) == "compose_default"
+
+
+def test_rds_public_endpoint_host_run_ministack_stays_off_network(monkeypatch):
+ """A MiniStack running on the host keeps probing the published port."""
+ from ministack.services import rds as m
+
+ monkeypatch.setattr(m, "RDS_PUBLIC_ENDPOINT", True)
+ monkeypatch.setattr(m, "DOCKER_NETWORK", "compose_default")
+ monkeypatch.setattr(m, "_ministack_network", None)
+ assert m._get_ministack_network(_fake_docker_self(None)) is None
+
+
+def test_rds_public_endpoint_reports_published_port_probes_container(monkeypatch):
+ """#1884: DescribeDBInstances reports {MINISTACK_HOST, host_port}; readiness dials the container."""
+ from ministack.services import rds as m
+
+ container_ip = "10.0.0.9"
+ host_port = 16099
+
+ class FakeContainer:
+ id = "public-endpoint-container"
+ status = "running"
+ attrs = {"NetworkSettings": {"Networks": {"ms_net": {"IPAddress": container_ip}}}}
+
+ def reload(self):
+ pass
+
+ container = FakeContainer()
+
+ class FakeContainers:
+ def run(self, **_kwargs):
+ return container
+
+ def get(self, identifier):
+ if identifier == container.id:
+ return container
+ raise Exception("not found")
+
+ class FakeImages:
+ def get(self, _image):
+ return object()
+
+ class FakeDocker:
+ containers = FakeContainers()
+ images = FakeImages()
+
+ readiness_dials = []
+
+ def _fake_wait_ready(host, port, *_args, **_kwargs):
+ readiness_dials.append((host, port))
+ return True
+
+ monkeypatch.setattr(m, "RDS_PUBLIC_ENDPOINT", True)
+ monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())
+ monkeypatch.setattr(m, "_get_ministack_network", lambda _client: "ms_net")
+ monkeypatch.setattr(m, "_next_port", lambda: host_port)
+ monkeypatch.setattr(m, "_is_host_port_free", lambda _port: True)
+ monkeypatch.setattr(m, "_wait_for_database_ready", _fake_wait_ready)
+
+ m._instances.clear()
+ try:
+ m._create_db_instance({
+ "DBInstanceIdentifier": "public-endpoint-solo",
+ "DBInstanceClass": "db.t3.micro",
+ "Engine": "postgres",
+ "MasterUsername": "admin",
+ "MasterUserPassword": "password123",
+ "AllocatedStorage": "20",
+ })
+ deadline = time.time() + 2
+ while (time.time() < deadline
+ and m._instances["public-endpoint-solo"]["DBInstanceStatus"] != "available"):
+ time.sleep(0.01)
+ inst = m._instances["public-endpoint-solo"]
+ assert inst["DBInstanceStatus"] == "available"
+ assert (inst["Endpoint"]["Address"], inst["Endpoint"]["Port"]) == (m._MINISTACK_HOST, host_port)
+ assert readiness_dials[-1][0] == container_ip
+ finally:
+ m._instances.clear()
+
+
+def test_rds_public_endpoint_cluster_reports_published_port(monkeypatch):
+ """#1884: an Aurora cluster reports {MINISTACK_HOST, host_port} for writer and reader, before and after restart."""
+ from ministack.services import rds as m
+
+ host_port = 16072
+
+ class FakeContainer:
+ id = "public-endpoint-shared-container"
+ attrs = {"NetworkSettings": {"Networks": {"ms_net": {"IPAddress": "172.31.77.50"}}}}
+
+ def __init__(self):
+ self.status = "running"
+
+ def reload(self):
+ pass
+
+ def start(self):
+ self.status = "running"
+
+ def stop(self, timeout=5):
+ self.status = "exited"
+
+ container = FakeContainer()
+
+ class FakeContainers:
+ def run(self, **_kwargs):
+ container.status = "running"
+ return container
+
+ def get(self, identifier):
+ if identifier in (container.id, m._rds_cluster_docker_name("public-endpoint-cluster")):
+ return container
+ raise Exception("not found")
+
+ class FakeDocker:
+ def __init__(self):
+ self.containers = FakeContainers()
+
+ monkeypatch.setattr(m, "RDS_PUBLIC_ENDPOINT", True)
+ monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())
+ monkeypatch.setattr(m, "_get_ministack_network", lambda _client: "ms_net")
+ monkeypatch.setattr(m, "_next_port", lambda: host_port)
+ monkeypatch.setattr(m, "_is_host_port_free", lambda _port: True)
+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr(m, "_ensure_mysql_compatibility", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr(m, "_grant_mysql_master_user_privileges", lambda *_args: None)
+
+ def _wait_available(cluster):
+ deadline = time.time() + 2
+ while time.time() < deadline and cluster["Status"] != "available":
+ time.sleep(0.01)
+ assert cluster["Status"] == "available"
+
+ m._instances.clear()
+ m._clusters.clear()
+ try:
+ m._create_db_cluster({
+ "DBClusterIdentifier": "public-endpoint-cluster",
+ "Engine": "aurora-mysql",
+ "MasterUsername": "admin",
+ "MasterUserPassword": "password123",
+ })
+ m._create_db_instance({
+ "DBInstanceIdentifier": "public-endpoint-writer",
+ "DBClusterIdentifier": "public-endpoint-cluster",
+ "DBInstanceClass": "db.r6g.large",
+ "Engine": "aurora-mysql",
+ })
+ cluster = m._clusters["public-endpoint-cluster"]
+ _wait_available(cluster)
+ published = (m._MINISTACK_HOST, m._MINISTACK_HOST, host_port)
+ assert (cluster["Endpoint"], cluster["ReaderEndpoint"], cluster["Port"]) == published
+
+ m._stop_db_cluster({"DBClusterIdentifier": "public-endpoint-cluster"})
+ m._start_db_cluster({"DBClusterIdentifier": "public-endpoint-cluster"})
+ _wait_available(cluster)
+ assert (cluster["Endpoint"], cluster["ReaderEndpoint"], cluster["Port"]) == published
+ finally:
+ m._instances.clear()
+ m._clusters.clear()