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
feat(autoscaling): scope state by region (#1169)
Ian Oberst00dc1706b3c6
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.pyindex 564a2805..227ac62e 100644--- a/ministack/core/persistence.py+++ b/ministack/core/persistence.py@@ -27,6 +27,7 @@ STATE_DIR = os.environ.get("STATE_DIR", "/tmp/ministack-state")# still load and migrate. (U4)STATE_FORMAT_VERSION = 2SERVICE_STATE_FORMAT_VERSIONS = {+ "autoscaling": 3,"athena": 3,"batch": 3,"ecs": 3,diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.pyindex 0dc58316..b7a1e497 100644--- a/ministack/services/autoscaling.py+++ b/ministack/services/autoscaling.py@@ -23,17 +23,33 @@ import timefrom collections import defaultdictfrom ministack.core.persistence import load_state-from ministack.core.responses import AccountScopedDict, get_account_id, get_region, new_uuid, now_iso+from ministack.core.responses import (+ AccountRegionScopedDict,+ AccountScopedDict,+ get_account_id,+ get_region,+ new_uuid,+ now_iso,+)logger = logging.getLogger("autoscaling")REGION = os.environ.get("MINISTACK_REGION", "us-east-1")-_asgs = AccountScopedDict()-_launch_configs = AccountScopedDict()-_policies = AccountScopedDict()-_hooks = AccountScopedDict()-_scheduled_actions = AccountScopedDict()-_tags = AccountScopedDict() # asg_name -> [{"Key":..., "Value":...}, ...]+_asgs = AccountRegionScopedDict()+_launch_configs = AccountRegionScopedDict()+_policies = AccountRegionScopedDict()+_hooks = AccountRegionScopedDict()+_scheduled_actions = AccountRegionScopedDict()+_tags = AccountRegionScopedDict() # asg_name -> [{"Key":..., "Value":...}, ...]+++def _clear_state():+ _asgs.clear()+ _launch_configs.clear()+ _policies.clear()+ _hooks.clear()+ _scheduled_actions.clear()+ _tags.clear()def get_state():@@ -48,13 +64,45 @@ def get_state():def restore_state(data):- if data:- _asgs.update(data.get("asgs", {}))- _launch_configs.update(data.get("launch_configs", {}))- _policies.update(data.get("policies", {}))- _hooks.update(data.get("hooks", {}))- _scheduled_actions.update(data.get("scheduled_actions", {}))- _tags.update(data.get("tags", {}))+ if not data:+ return++ _clear_state()+ _asgs.update(data.get("asgs", {}))+ _launch_configs.update(data.get("launch_configs", {}))++ asg_regions = {+ (account_id, asg_name): region+ for (account_id, region, asg_name), _asg in _asgs.all_items()+ }+ for store, key in (+ (_policies, "policies"),+ (_hooks, "hooks"),+ (_scheduled_actions, "scheduled_actions"),+ (_tags, "tags"),+ ):+ _restore_asg_child_store(store, data.get(key, {}), asg_regions)+++def _restore_asg_child_store(store, restored, asg_regions):+ """Adopt legacy name-keyed child state into its parent ASG's region."""+ if isinstance(restored, AccountRegionScopedDict):+ store.update(restored)+ return++ if isinstance(restored, AccountScopedDict):+ items = restored._data.items()+ else:+ account_id = get_account_id()+ items = (((account_id, key), value) for key, value in restored.items())++ for (account_id, key), value in items:+ asg_name = value.get("AutoScalingGroupName") if isinstance(value, dict) else key+ region = asg_regions.get(+ (account_id, asg_name),+ store._region_for_legacy_value(key, value),+ )+ store.set_scoped(account_id, region, key, value)try:@@ -66,12 +114,7 @@ except Exception:def reset():- _asgs.clear()- _launch_configs.clear()- _policies.clear()- _hooks.clear()- _scheduled_actions.clear()- _tags.clear()+ _clear_state()def _p(params, key):diff --git a/tests/test_autoscaling.py b/tests/test_autoscaling.pyindex 569568ae..72f59a96 100644--- a/tests/test_autoscaling.py+++ b/tests/test_autoscaling.py@@ -1,6 +1,9 @@+import osimport uuid+import boto3import pytest+from botocore.config import Configfrom botocore.exceptions import ClientError@@ -8,6 +11,17 @@ def _uid(prefix="test"):return f"{prefix}-{uuid.uuid4().hex[:8]}"+def _client(region):+ return boto3.client(+ "autoscaling",+ endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name=region,+ aws_access_key_id="test",+ aws_secret_access_key="test",+ config=Config(retries={"mode": "standard"}),+ )++# ---------------------------------------------------------------------------# AutoScalingGroup: Create, Describe, Update, Delete# ---------------------------------------------------------------------------@@ -60,6 +74,142 @@ def test_create_asg_duplicate_fails(autoscaling):autoscaling.delete_auto_scaling_group(AutoScalingGroupName=name)+def test_autoscaling_groups_and_tags_are_region_scoped():+ east = _client("us-east-1")+ west = _client("us-west-2")+ name = _uid("asg-region")++ east.create_auto_scaling_group(+ AutoScalingGroupName=name,+ MinSize=1,+ MaxSize=3,+ AvailabilityZones=["us-east-1a"],+ Tags=[{"Key": "region", "Value": "east", "PropagateAtLaunch": True}],+ )+ west.create_auto_scaling_group(+ AutoScalingGroupName=name,+ MinSize=2,+ MaxSize=4,+ AvailabilityZones=["us-west-2a"],+ Tags=[{"Key": "region", "Value": "west", "PropagateAtLaunch": True}],+ )+ try:+ east_group = east.describe_auto_scaling_groups(+ AutoScalingGroupNames=[name]+ )["AutoScalingGroups"][0]+ west_group = west.describe_auto_scaling_groups(+ AutoScalingGroupNames=[name]+ )["AutoScalingGroups"][0]++ assert east_group["MinSize"] == 1+ assert west_group["MinSize"] == 2+ assert ":us-east-1:" in east_group["AutoScalingGroupARN"]+ assert ":us-west-2:" in west_group["AutoScalingGroupARN"]+ assert east_group["Tags"][0]["Value"] == "east"+ assert west_group["Tags"][0]["Value"] == "west"+ finally:+ east.delete_auto_scaling_group(AutoScalingGroupName=name)+ west.delete_auto_scaling_group(AutoScalingGroupName=name)+++def test_restore_legacy_child_state_uses_parent_asg_region():+ from ministack.core.responses import (+ AccountScopedDict,+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import autoscaling as service++ account_id = "111111111111"+ boot_region = "us-east-1"+ resource_region = "us-west-2"+ asg_name = "legacy-asg"+ child_key = f"{asg_name}/legacy-child"+ original_account = get_account_id()+ original_region = get_region()++ asgs = AccountScopedDict()+ policies = AccountScopedDict()+ hooks = AccountScopedDict()+ scheduled_actions = AccountScopedDict()+ tags = AccountScopedDict()++ set_request_account_id(account_id)+ set_request_region(boot_region)+ asgs[asg_name] = {+ "AutoScalingGroupName": asg_name,+ "AutoScalingGroupARN": (+ f"arn:aws:autoscaling:{resource_region}:{account_id}:"+ f"autoScalingGroup:legacy:autoScalingGroupName/{asg_name}"+ ),+ }+ policies[child_key] = {"AutoScalingGroupName": asg_name}+ hooks[child_key] = {"AutoScalingGroupName": asg_name}+ scheduled_actions[child_key] = {"AutoScalingGroupName": asg_name}+ tags[asg_name] = [{"Key": "legacy", "Value": "true"}]++ service.reset()+ try:+ service.restore_state(+ {+ "asgs": asgs,+ "policies": policies,+ "hooks": hooks,+ "scheduled_actions": scheduled_actions,+ "tags": tags,+ }+ )+ assert service._asgs.get_scoped(+ account_id, resource_region, asg_name+ )["AutoScalingGroupName"] == asg_name+ for store in (+ service._policies,+ service._hooks,+ service._scheduled_actions,+ ):+ assert (+ store.get_scoped(account_id, resource_region, child_key) is not None+ )+ assert store.get_scoped(account_id, boot_region, child_key) is None+ assert service._tags.get_scoped(account_id, resource_region, asg_name) == [+ {"Key": "legacy", "Value": "true"}+ ]+ assert service._tags.get_scoped(account_id, boot_region, asg_name) is None+ finally:+ service.reset()+ set_request_account_id(original_account)+ set_request_region(original_region)+++def test_reset_clears_autoscaling_state_across_regions():+ from ministack.core.responses import get_region, set_request_region+ from ministack.services import autoscaling as service++ original_region = get_region()+ stores = (+ service._asgs,+ service._launch_configs,+ service._policies,+ service._hooks,+ service._scheduled_actions,+ service._tags,+ )+ service.reset()+ try:+ for region in ("us-east-1", "us-west-2"):+ set_request_region(region)+ for store in stores:+ store[f"resource-{region}"] = {"region": region}++ service.reset()+ assert all(not store.has_any() for store in stores)+ finally:+ service.reset()+ set_request_region(original_region)++def test_describe_asgs_empty(autoscaling):bogus = _uid("no-exist")resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[bogus])diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 9dd2187b..fb1a53ea 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -1832,11 +1832,11 @@ def test_ecs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path)assert persistence.load_state("ecs") is None-def test_athena_region_scoped_state_is_rejected_by_v2_reader(+def test_autoscaling_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):- """A rollback binary must reject Athena's regional schema instead of- accepting it as v2 and silently dropping every regional store."""+ """A rollback binary must reject Auto Scaling's regional schema instead+ of accepting it as v2 and silently dropping every regional store."""import json as _jsonfrom ministack.core.responses import AccountRegionScopedDict@@ -1844,25 +1844,30 @@ def test_athena_region_scoped_state_is_rejected_by_v2_reader(monkeypatch.setattr(persistence, "PERSIST_STATE", True)monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))- workgroups = AccountRegionScopedDict()- workgroups.set_scoped(+ asgs = AccountRegionScopedDict()+ asgs.set_scoped("000000000000","us-west-2",- "regional-workgroup",- {"Name": "regional-workgroup", "Description": "west"},+ "regional-asg",+ {+ "AutoScalingGroupARN": (+ "arn:aws:autoscaling:us-west-2:000000000000:"+ "autoScalingGroup:regional:autoScalingGroupName/regional-asg"+ )+ },)- persistence.save_state("athena", {"_workgroups": workgroups})+ persistence.save_state("autoscaling", {"asgs": asgs})- raw = _json.loads((tmp_path / "athena.json").read_text())+ raw = _json.loads((tmp_path / "autoscaling.json").read_text())assert raw["__ministack_format__"] == 3- loaded_workgroups = persistence.load_state("athena")["_workgroups"]- assert loaded_workgroups.get_scoped(- "000000000000", "us-west-2", "regional-workgroup"- )["Description"] == "west"+ loaded_asgs = persistence.load_state("autoscaling")["asgs"]+ assert loaded_asgs.get_scoped(+ "000000000000", "us-west-2", "regional-asg"+ )["AutoScalingGroupARN"].endswith("autoScalingGroupName/regional-asg")# Simulate the previous binary, whose highest understood format is v2.monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})- assert persistence.load_state("athena") is None+ assert persistence.load_state("autoscaling") is Nonedef test_resource_groups_region_scoped_state_is_rejected_by_v2_reader(