Skip to content

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

feat(efs): scope state by region (#1174)

Ian Oberst89943509c226
diff --git a/ministack/core/persistence.py b/ministack/core/persistence.py
index 226b4fff..9dc540da 100644
--- a/ministack/core/persistence.py
+++ b/ministack/core/persistence.py
@@ -30,6 +30,7 @@ SERVICE_STATE_FORMAT_VERSIONS = {
"appsync": 3,
"autoscaling": 3,
"athena": 3,
+ "efs": 3,
"s3files": 3,
"batch": 3,
"ecs": 3,
diff --git a/ministack/services/efs.py b/ministack/services/efs.py
index 067c204b..0b5efffb 100644
--- a/ministack/services/efs.py
+++ b/ministack/services/efs.py
@@ -26,7 +26,12 @@ import time
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.persistence import PERSIST_STATE, load_state
-from ministack.core.responses import AccountScopedDict, get_account_id, get_region
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+)
logger = logging.getLogger("efs")
@@ -36,9 +41,9 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
# State
# ---------------------------------------------------------------------------
-_file_systems = AccountScopedDict() # fs_id -> fs record
-_mount_targets = AccountScopedDict() # mt_id -> mount target record
-_access_points = AccountScopedDict() # ap_id -> access point record
+_file_systems = AccountRegionScopedDict() # fs_id -> fs record
+_mount_targets = AccountRegionScopedDict() # mt_id -> mount target record
+_access_points = AccountRegionScopedDict() # ap_id -> access point record
# ---------------------------------------------------------------------------
# ID generators
@@ -384,8 +389,16 @@ def _find_resource(resource_id, resource_type=None):
# Lifecycle / Backup / Account (stubs)
# ---------------------------------------------------------------------------
-_lifecycle_configs = AccountScopedDict()
-_backup_policies = AccountScopedDict()
+_lifecycle_configs = AccountRegionScopedDict()
+_backup_policies = AccountRegionScopedDict()
+
+
+def _clear_state():
+ _file_systems.clear()
+ _mount_targets.clear()
+ _access_points.clear()
+ _lifecycle_configs.clear()
+ _backup_policies.clear()
def get_state():
@@ -399,16 +412,45 @@ def get_state():
def restore_state(data):
- _file_systems.clear()
+ if not data:
+ return
+ _clear_state()
_file_systems.update(data.get("file_systems", {}))
- _mount_targets.clear()
_mount_targets.update(data.get("mount_targets", {}))
- _access_points.clear()
_access_points.update(data.get("access_points", {}))
- _lifecycle_configs.clear()
- _lifecycle_configs.update(data.get("lifecycle_configs", {}))
- _backup_policies.clear()
- _backup_policies.update(data.get("backup_policies", {}))
+ fs_regions = {
+ (account_id, fs_id): region
+ for (account_id, region, fs_id), _fs in _file_systems.all_items()
+ }
+ for store, state_key in (
+ (_lifecycle_configs, "lifecycle_configs"),
+ (_backup_policies, "backup_policies"),
+ ):
+ _restore_file_system_child_store(
+ store,
+ data.get(state_key, {}),
+ fs_regions,
+ )
+
+
+def _restore_file_system_child_store(store, restored, fs_regions):
+ """Adopt legacy ARN-less state into its parent file system'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, fs_id), value in items:
+ region = fs_regions.get(
+ (account_id, fs_id),
+ store._region_for_legacy_value(fs_id, value),
+ )
+ store.set_scoped(account_id, region, fs_id, value)
try:
@@ -590,8 +632,4 @@ def _error(status, code, message):
# ---------------------------------------------------------------------------
def reset():
- _file_systems.clear()
- _mount_targets.clear()
- _access_points.clear()
- _lifecycle_configs.clear()
- _backup_policies.clear()
+ _clear_state()
diff --git a/tests/test_efs.py b/tests/test_efs.py
index e0431cde..d5b03468 100644
--- a/tests/test_efs.py
+++ b/tests/test_efs.py
@@ -6,10 +6,23 @@ import uuid as _uuid_mod
import zipfile
from urllib.parse import urlparse
+import boto3
import pytest
+from botocore.config import Config
from botocore.exceptions import ClientError
+def _efs_client(region):
+ return boto3.client(
+ "efs",
+ endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ region_name=region,
+ config=Config(region_name=region, retries={"mode": "standard"}),
+ )
+
+
def test_efs_create_and_describe_filesystem(efs):
resp = efs.create_file_system(
PerformanceMode="generalPurpose",
@@ -33,6 +46,170 @@ def test_efs_creation_token_idempotency(efs):
r2 = efs.create_file_system(CreationToken=token)
assert r1["FileSystemId"] == r2["FileSystemId"]
+
+def test_efs_resources_are_region_scoped():
+ east = _efs_client("us-east-1")
+ west = _efs_client("us-west-2")
+ token = f"regional-{_uuid_mod.uuid4().hex}"
+ east_fs = east.create_file_system(CreationToken=token)
+ west_fs = west.create_file_system(CreationToken=token)
+ east_mt = east.create_mount_target(
+ FileSystemId=east_fs["FileSystemId"],
+ SubnetId="subnet-00000001",
+ )
+ west_mt = west.create_mount_target(
+ FileSystemId=west_fs["FileSystemId"],
+ SubnetId="subnet-00000002",
+ )
+ east_ap = east.create_access_point(FileSystemId=east_fs["FileSystemId"])
+ west_ap = west.create_access_point(FileSystemId=west_fs["FileSystemId"])
+ east.put_lifecycle_configuration(
+ FileSystemId=east_fs["FileSystemId"],
+ LifecyclePolicies=[{"TransitionToIA": "AFTER_7_DAYS"}],
+ )
+ west.put_lifecycle_configuration(
+ FileSystemId=west_fs["FileSystemId"],
+ LifecyclePolicies=[{"TransitionToIA": "AFTER_30_DAYS"}],
+ )
+ east.put_backup_policy(
+ FileSystemId=east_fs["FileSystemId"],
+ BackupPolicy={"Status": "ENABLED"},
+ )
+ west.put_backup_policy(
+ FileSystemId=west_fs["FileSystemId"],
+ BackupPolicy={"Status": "DISABLED"},
+ )
+
+ try:
+ east_ids = {fs["FileSystemId"] for fs in east.describe_file_systems()["FileSystems"]}
+ west_ids = {fs["FileSystemId"] for fs in west.describe_file_systems()["FileSystems"]}
+ assert east_fs["FileSystemId"] in east_ids
+ assert east_fs["FileSystemId"] not in west_ids
+ assert west_fs["FileSystemId"] in west_ids
+ assert west_fs["FileSystemId"] not in east_ids
+ assert ":us-east-1:" in east_fs["FileSystemArn"]
+ assert ":us-west-2:" in west_fs["FileSystemArn"]
+
+ assert east.describe_mount_targets(FileSystemId=east_fs["FileSystemId"])["MountTargets"][0]["MountTargetId"] == east_mt["MountTargetId"]
+ assert west.describe_mount_targets(FileSystemId=west_fs["FileSystemId"])["MountTargets"][0]["MountTargetId"] == west_mt["MountTargetId"]
+ assert east.describe_access_points(FileSystemId=east_fs["FileSystemId"])["AccessPoints"][0]["AccessPointId"] == east_ap["AccessPointId"]
+ assert west.describe_access_points(FileSystemId=west_fs["FileSystemId"])["AccessPoints"][0]["AccessPointId"] == west_ap["AccessPointId"]
+ assert east.describe_lifecycle_configuration(FileSystemId=east_fs["FileSystemId"])["LifecyclePolicies"] == [{"TransitionToIA": "AFTER_7_DAYS"}]
+ assert west.describe_lifecycle_configuration(FileSystemId=west_fs["FileSystemId"])["LifecyclePolicies"] == [{"TransitionToIA": "AFTER_30_DAYS"}]
+ assert east.describe_backup_policy(FileSystemId=east_fs["FileSystemId"])["BackupPolicy"]["Status"] == "ENABLED"
+ assert west.describe_backup_policy(FileSystemId=west_fs["FileSystemId"])["BackupPolicy"]["Status"] == "DISABLED"
+ finally:
+ east.delete_access_point(AccessPointId=east_ap["AccessPointId"])
+ west.delete_access_point(AccessPointId=west_ap["AccessPointId"])
+ east.delete_mount_target(MountTargetId=east_mt["MountTargetId"])
+ west.delete_mount_target(MountTargetId=west_mt["MountTargetId"])
+ east.delete_file_system(FileSystemId=east_fs["FileSystemId"])
+ west.delete_file_system(FileSystemId=west_fs["FileSystemId"])
+
+
+def test_efs_restore_legacy_state_places_children_beside_parent():
+ from ministack.core.responses import (
+ AccountScopedDict,
+ get_account_id,
+ get_region,
+ set_request_account_id,
+ set_request_region,
+ )
+ from ministack.services import efs as service
+
+ original_account = get_account_id()
+ original_region = get_region()
+ account_id = "111111111111"
+ boot_region = "us-east-1"
+ resource_region = "us-west-2"
+ fs_id = "fs-11111111111111111"
+ mt_id = "fsmt-11111111111111111"
+ ap_id = "fsap-11111111111111111"
+ payload = {}
+
+ set_request_account_id(account_id)
+ set_request_region(boot_region)
+ for state_key, resource_key, value in (
+ (
+ "file_systems",
+ fs_id,
+ {
+ "FileSystemId": fs_id,
+ "FileSystemArn": f"arn:aws:elasticfilesystem:{resource_region}:{account_id}:file-system/{fs_id}",
+ },
+ ),
+ (
+ "mount_targets",
+ mt_id,
+ {
+ "MountTargetId": mt_id,
+ "FileSystemId": fs_id,
+ "MountTargetArn": f"arn:aws:elasticfilesystem:{resource_region}:{account_id}:file-system/{fs_id}/mount-target/{mt_id}",
+ },
+ ),
+ (
+ "access_points",
+ ap_id,
+ {
+ "AccessPointId": ap_id,
+ "FileSystemId": fs_id,
+ "AccessPointArn": f"arn:aws:elasticfilesystem:{resource_region}:{account_id}:access-point/{ap_id}",
+ },
+ ),
+ ("lifecycle_configs", fs_id, [{"TransitionToIA": "AFTER_30_DAYS"}]),
+ ("backup_policies", fs_id, {"Status": "ENABLED"}),
+ ):
+ store = AccountScopedDict()
+ store[resource_key] = value
+ payload[state_key] = store
+
+ service.reset()
+ try:
+ service.restore_state(payload)
+ assert service._file_systems.get_scoped(account_id, resource_region, fs_id)["FileSystemId"] == fs_id
+ assert service._mount_targets.get_scoped(account_id, resource_region, mt_id)["FileSystemId"] == fs_id
+ assert service._access_points.get_scoped(account_id, resource_region, ap_id)["FileSystemId"] == fs_id
+ assert service._lifecycle_configs.get_scoped(account_id, resource_region, fs_id) == [{"TransitionToIA": "AFTER_30_DAYS"}]
+ assert service._backup_policies.get_scoped(account_id, resource_region, fs_id) == {"Status": "ENABLED"}
+ for store, key in (
+ (service._file_systems, fs_id),
+ (service._mount_targets, mt_id),
+ (service._access_points, ap_id),
+ (service._lifecycle_configs, fs_id),
+ (service._backup_policies, fs_id),
+ ):
+ assert store.get_scoped(account_id, boot_region, key) is None
+ finally:
+ service.reset()
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+def test_efs_reset_clears_state_across_regions():
+ from ministack.core.responses import get_region, set_request_region
+ from ministack.services import efs as service
+
+ original_region = get_region()
+ stores = (
+ service._file_systems,
+ service._mount_targets,
+ service._access_points,
+ service._lifecycle_configs,
+ service._backup_policies,
+ )
+ 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_efs_delete_filesystem(efs):
resp = efs.create_file_system()
fs_id = resp["FileSystemId"]
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 87acb611..81f70c4c 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -1868,11 +1868,8 @@ def test_appsync_region_scoped_state_is_rejected_by_v2_reader(
assert persistence.load_state("appsync") is None
-def test_s3files_region_scoped_state_is_rejected_by_v2_reader(
- monkeypatch, tmp_path
-):
- """A rollback binary must reject S3 Files' regional schema instead of
- accepting it as v2 and silently dropping every regional store."""
+def test_efs_region_scoped_state_is_rejected_by_v2_reader(monkeypatch, tmp_path):
+ """A rollback binary must reject EFS regional state instead of dropping it."""
import json as _json
from ministack.core.responses import AccountRegionScopedDict
@@ -1886,25 +1883,24 @@ def test_s3files_region_scoped_state_is_rejected_by_v2_reader(
"us-west-2",
"fs-11111111111111111",
{
- "fileSystemId": "fs-11111111111111111",
- "fileSystemArn": (
- "arn:aws:s3files:us-west-2:000000000000:"
+ "FileSystemId": "fs-11111111111111111",
+ "FileSystemArn": (
+ "arn:aws:elasticfilesystem:us-west-2:000000000000:"
"file-system/fs-11111111111111111"
),
},
)
- persistence.save_state("s3files", {"file_systems": file_systems})
+ persistence.save_state("efs", {"file_systems": file_systems})
- raw = _json.loads((tmp_path / "s3files.json").read_text())
+ raw = _json.loads((tmp_path / "efs.json").read_text())
assert raw["__ministack_format__"] == 3
- loaded_file_systems = persistence.load_state("s3files")["file_systems"]
- assert loaded_file_systems.get_scoped(
+ loaded = persistence.load_state("efs")["file_systems"]
+ assert loaded.get_scoped(
"000000000000", "us-west-2", "fs-11111111111111111"
- )["fileSystemId"] == "fs-11111111111111111"
+ )["FileSystemId"] == "fs-11111111111111111"
- # Simulate the previous binary, whose highest understood format is v2.
monkeypatch.setattr(persistence, "SERVICE_STATE_FORMAT_VERSIONS", {})
- assert persistence.load_state("s3files") is None
+ assert persistence.load_state("efs") is None
def test_resource_groups_region_scoped_state_is_rejected_by_v2_reader(