Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
rds: reshape Aurora cluster compute lifecycle for per-instance containers (#1339)
kiran01bm39e3278c726f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 01e945bc..c7782bb1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed- **CloudFormation — resources unchanged by a stack update are left alone** — every previously-provisioned resource was reprocessed on every stack update regardless of whether its properties changed, and any resource type with no dedicated update handler fell back to calling create again — a fallback whose own name-generation regenerated a fresh random suffix on every call, and whose caller passed the wrong id into it, on top of that. An auto-named resource's "idempotent" create (the type framework's own documented expectation) silently produced a brand new, empty resource under a new identity on every single update, orphaning the real one — and anything referencing it via `Ref`/`Fn::GetAtt` picked up that new, wrong identity the moment it was reprocessed later in the same update, since real CloudFormation does propagate a changed reference. Found via a DynamoDB table silently duplicating on an unrelated update to a real multi-stack deploy. A genuinely unchanged resource is no longer touched at all, matching real CloudFormation; auto-generated names are now a deterministic hash of (stack name, logical id) rather than random, so the remaining case — a resource's properties *did* change but its type still has no update handler — reproduces the same name it started with. Also fixes the same symptom for `AWS::Events::EventBus` (previously failed a stack update outright with "already exists" once created) and any other resource type with no update handler and no name-collision guard of its own. Contributed by @ryan-bennett.- **CloudFormation — `AWS::SSM::Parameter::Value<...>` template parameters now resolve against SSM Parameter Store** — a template parameter typed `AWS::SSM::Parameter::Value<String>` (or `<List<String>>` / `<AWS::EC2::Image::Id>`) takes an SSM parameter *name* as its Default/provided value; real CloudFormation resolves that name against Parameter Store before `Ref` ever sees it — the mechanism behind, e.g., CDK's `StringParameter.valueForStringParameter`. MiniStack treated these like any other AWS-specific parameter type and passed the literal name straight through, so `Ref` returned the parameter's name instead of its stored value, and any resource property built from it (or a nested stack composing two independently-deployed stacks through a shared parameter) silently received the wrong string. Resolution now looks the name up in the SSM store at parameter-resolution time; a name that doesn't exist fails `CreateStack`/`UpdateStack` synchronously with a `ValidationError`, matching AWS. Contributed by @ryan-bennett.diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 10c1d85d..d83a8070 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -995,6 +995,43 @@ def _start_cluster_shared_container(cluster_id, cluster, remove_stale=False):}+def _instance_owns_container(instance):+ """True when the instance record owns its backing Docker container.++ Standalone DB instances own their container: instance-level delete and+ reset must remove it. Aurora cluster members do not — they alias the+ cluster-owned shared container (marked by ``_shared_cluster_id``), whose+ lifecycle belongs to the cluster helpers. Cluster members that own a+ container of their own (per-instance reader containers, #1325) are+ handled like standalone instances by ownership-based code paths.+ """+ return bool(+ instance.get("_docker_container_id")+ and not instance.get("_shared_cluster_id")+ )+++def _cluster_owned_container_ids(cluster):+ """All Docker container IDs backing an Aurora cluster's compute.++ Today a cluster has at most one: the cluster-owned shared container.+ Member instances that own a container of their own (per-instance reader+ containers, #1325) are included so cluster-wide compute operations act+ on every container the cluster is responsible for. IDs are deduplicated+ (first occurrence wins) so a member aliasing an already-listed container+ is not operated on twice.+ """+ ids = []+ if cluster.get("_shared_container_id"):+ ids.append(cluster["_shared_container_id"])+ for member in _cluster_member_instances(cluster):+ if _instance_owns_container(member):+ container_id = member["_docker_container_id"]+ if container_id not in ids:+ ids.append(container_id)+ return ids++def _stop_cluster_shared_container(cluster_id, cluster):"""Stop, but do not remove, an Aurora cluster's database compute.@@ -1017,29 +1054,36 @@ def _stop_cluster_shared_container(cluster_id, cluster):cluster.get("_shared_container_epoch", 0),) + 1cluster["_shared_container_ready"] = False- container_id = cluster.get("_shared_container_id")+ container_ids = _cluster_owned_container_ids(cluster)docker_client = _get_docker()- if not docker_client or not container_id:+ if not docker_client or not container_ids:return True- try:- container = docker_client.containers.get(container_id)- except Exception:- # A container that no longer exists is not running compute; the- # goal state is already met.- return True- try:- container.reload()- if container.status not in ("created", "exited", "dead", "removing"):- container.stop(timeout=5)- logger.info("RDS: stopped shared container for cluster %s", cluster_id)- except Exception as e:- logger.warning(- "RDS: failed to stop shared container for cluster %s: %s",- cluster_id,- e,- )- return False- return True+ all_stopped = True+ for container_id in container_ids:+ try:+ container = docker_client.containers.get(container_id)+ except Exception:+ # A container that no longer exists is not running compute;+ # the goal state is already met.+ continue+ try:+ container.reload()+ if container.status not in ("created", "exited", "dead", "removing"):+ container.stop(timeout=5)+ logger.info(+ "RDS: stopped container %s for cluster %s",+ container_id,+ cluster_id,+ )+ except Exception as e:+ logger.warning(+ "RDS: failed to stop container %s for cluster %s: %s",+ container_id,+ cluster_id,+ e,+ )+ all_stopped = False+ return all_stoppeddef _remove_cluster_shared_resources(@@ -2400,18 +2444,31 @@ def _attach_instance_to_shared_cluster(instance, cluster):)+def _cluster_reader_endpoint(cluster):+ """The endpoint a cluster's ``ReaderEndpoint`` should resolve to.++ Today this is the writer's shared endpoint, so the local reader endpoint+ is read/write: it resolves to the same database process as the writer.+ Genuine read-only behavior requires a separate replicating process —+ per-instance reader containers (#1325) will resolve here instead once a+ cluster has one.+ """+ return cluster.get("_shared_endpoint")++def _sync_cluster_endpoints(cluster):- """Point both Aurora endpoints at the cluster-owned shared container.+ """Point the Aurora writer and reader endpoints at cluster compute.- The local reader endpoint is intentionally read/write because it resolves- to the same MySQL process as the writer. Genuine read-only behavior would- require a separate replicating process.+ The writer endpoint resolves to the cluster-owned shared container; the+ reader endpoint resolves to whatever ``_cluster_reader_endpoint``+ selects (currently the same container — see its docstring)."""endpoint = cluster.get("_shared_endpoint")if not endpoint:return+ reader_endpoint = _cluster_reader_endpoint(cluster) or endpointcluster["Endpoint"] = endpoint.get("Address", cluster.get("Endpoint", ""))- cluster["ReaderEndpoint"] = endpoint.get(+ cluster["ReaderEndpoint"] = reader_endpoint.get("Address", cluster.get("ReaderEndpoint", ""),)cluster["Port"] = int(endpoint.get("Port", cluster.get("Port", 0)))@@ -3047,11 +3104,7 @@ def _delete_db_instance(p):_stop_cluster_shared_container(shared_cluster_id, cluster)docker_client = _get_docker()- if (- docker_client- and instance.get("_docker_container_id")- and not instance.get("_shared_cluster_id")- ):+ if docker_client and _instance_owns_container(instance):try:c = docker_client.containers.get(instance["_docker_container_id"])c.stop(timeout=5)@@ -6286,7 +6339,7 @@ def reset():if (cidand cid not in shared_container_ids- and not instance.get("_shared_cluster_id")+ and _instance_owns_container(instance)):try:c = docker_client.containers.get(cid)diff --git a/tests/test_rds.py b/tests/test_rds.pyindex d30f34ae..94674395 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -9048,3 +9048,93 @@ def test_rds_delete_protected_cluster_keeps_managed_secret(rds, sm):rds.modify_db_cluster(DBClusterIdentifier=cluster_id, DeletionProtection=False)rds.delete_db_cluster(DBClusterIdentifier=cluster_id, SkipFinalSnapshot=True)+++def test_rds_instance_owns_container_predicate():+ """Container ownership: standalone instances own theirs, cluster members alias.++ A cluster member that owns a container of its own (per-instance reader+ containers, #1325) is treated like a standalone instance.+ """+ from ministack.services import rds as m++ # Standalone instance with a container: owns it.+ assert m._instance_owns_container({"_docker_container_id": "c1"})+ # Cluster member aliasing the shared container: does not own it.+ assert not m._instance_owns_container({+ "_docker_container_id": "c1",+ "_shared_cluster_id": "my-cluster",+ })+ # No container at all: nothing to own.+ assert not m._instance_owns_container({})+ assert not m._instance_owns_container({"_docker_container_id": None})+++def test_rds_cluster_owned_container_ids():+ """Cluster compute enumeration: shared container plus member-owned containers."""+ from ministack.core.responses import get_account_id, set_request_account_id+ from ministack.services import rds as m++ original_account = get_account_id()+ member_id = "enum-cluster-member-1"+ try:+ set_request_account_id("111111111111")++ # No compute at all.+ assert m._cluster_owned_container_ids({"DBClusterIdentifier": "empty"}) == []++ # Shared container only (every cluster today).+ cluster = {+ "DBClusterIdentifier": "enum-cluster",+ "_shared_container_id": "shared-c",+ "DBClusterMembers": [+ {"DBInstanceIdentifier": member_id},+ ],+ }+ m._instances[member_id] = {+ "DBInstanceIdentifier": member_id,+ "_docker_container_id": "shared-c",+ "_shared_cluster_id": "enum-cluster",+ }+ # Aliasing member contributes nothing beyond the shared container.+ assert m._cluster_owned_container_ids(cluster) == ["shared-c"]++ # A member owning its own container (reader containers, #1325) is+ # enumerated as cluster compute.+ m._instances[member_id] = {+ "DBInstanceIdentifier": member_id,+ "_docker_container_id": "reader-c",+ }+ assert m._cluster_owned_container_ids(cluster) == ["shared-c", "reader-c"]++ # A member that owns a container whose id happens to alias an+ # already-listed one is deduplicated, so cluster-wide compute+ # operations never act on the same container twice.+ m._instances[member_id] = {+ "DBInstanceIdentifier": member_id,+ "_docker_container_id": "shared-c",+ }+ assert m._cluster_owned_container_ids(cluster) == ["shared-c"]+ finally:+ set_request_account_id(original_account)+ m._instances.pop(member_id, None)+++def test_rds_cluster_reader_endpoint_resolves_shared_endpoint():+ """ReaderEndpoint resolves through _cluster_reader_endpoint (today: the writer's)."""+ from ministack.services import rds as m++ endpoint = {"Address": "10.0.0.5", "Port": 5432, "HostedZoneId": "Z2R2ITUGPM61AM"}+ cluster = {"DBClusterIdentifier": "reader-ep", "_shared_endpoint": endpoint}+ assert m._cluster_reader_endpoint(cluster) == endpoint++ m._sync_cluster_endpoints(cluster)+ assert cluster["Endpoint"] == "10.0.0.5"+ assert cluster["ReaderEndpoint"] == "10.0.0.5"+ assert cluster["Port"] == 5432++ # No shared endpoint yet (cluster created, no instance): sync is a no-op.+ bare = {"DBClusterIdentifier": "no-ep"}+ assert m._cluster_reader_endpoint(bare) is None+ m._sync_cluster_endpoints(bare)+ assert "ReaderEndpoint" not in bare