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(ecs): relaunch a restored service's tasks (#1557)
Jacob Schooley9e541ee32314
diff --git a/ministack/app.py b/ministack/app.pyindex fce27fd4..8575d353 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2449,6 +2449,19 @@ def _load_persisted_state():_get_module("lambda_svc") # module file is lambda_svc.py (lambda is a keyword)logger.info("Lambda: eager-loaded module to resume event-source-mapping pollers at boot")+ # ECS services are restored with every task marked STOPPED — their+ # containers went with the previous process — and the relaunch happens on+ # the module's import-time restore hook. ECS is otherwise imported lazily on+ # the first ECS request, so a workload that only talks to the service+ # through a load balancer never triggers it: the service reports its+ # persisted runningCount, nothing is running, and every request through the+ # balancer fails. Same conditional shape as RDS — only pay the cold-start+ # when there are services to bring back.+ _ecs_state = load_state("ecs")+ if _ecs_state and getattr(_ecs_state.get("services"), "_data", _ecs_state.get("services")):+ _get_module("ecs")+ logger.info("ECS: eager-loaded module to relaunch persisted services at boot")+async def _wait_for_port(port, timeout=30):"""Wait until the server is accepting TCP connections."""diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 86106254..3ad8910c 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -83,6 +83,10 @@ _docker = None# exit on their own and accumulate indefinitely. A background daemon thread# sweeps them every ECS_REAP_INTERVAL_SECONDS (default 60)._ECS_REAP_INTERVAL = int(os.environ.get("ECS_REAP_INTERVAL_SECONDS", "60"))+# Give the process a moment to finish binding before pulling images and starting+# containers for restored services.+_ECS_RESTORE_RECONCILE_DELAY = float(+ os.environ.get("ECS_RESTORE_RECONCILE_DELAY_SECONDS", "2"))_ecs_reaper_started = False_ecs_reaper_lock = threading.Lock()@@ -238,10 +242,54 @@ def restore_state(data):_tasks.set_scoped(get_account_id(), region, arn, restored_task)+def _reconcile_restored_services():+ """Relaunch the tasks of every ACTIVE service after a restore.++ restore_state marks each restored task STOPPED — its container went with the+ process that ran it. Without this the service still reports its persisted+ runningCount while nothing is running, and any load balancer in front of it+ keeps forwarding to addresses nothing is listening on. Real ECS relaunches:+ keeping desiredCount satisfied is the service scheduler's whole job.++ Failures are logged and skipped rather than raised, so one unreachable image+ cannot stop the remaining services from coming back.+ """+ for svc_key, svc in list(_services.items()):+ if not isinstance(svc, dict) or svc.get("status") != "ACTIVE":+ continue+ cluster_name = svc_key.split("/", 1)[0]+ try:+ _reconcile_service_tasks(cluster_name, svc_key)+ except Exception as exc:+ logger.warning(+ "ECS: could not relaunch service %s after restore: %s",+ svc.get("serviceName", svc_key), exc)+++def _start_restored_service_reconciler():+ """Run the reconcile off the import path.++ restore_state runs at import; pulling images and starting containers there+ would block startup behind the Docker daemon, so this happens on a daemon+ thread once the process is up.+ """+ def _run():+ time.sleep(_ECS_RESTORE_RECONCILE_DELAY)+ try:+ _reconcile_restored_services()+ except Exception:+ logger.exception("ECS: restored-service reconcile failed")++ threading.Thread(+ target=_run, daemon=True, name="ministack-ecs-restore-reconcile"+ ).start()++try:_restored = load_state("ecs")if _restored:restore_state(_restored)+ _start_restored_service_reconciler()except Exception:import logginglogging.getLogger(__name__).exception(diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex a2713c03..34d62270 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -1692,6 +1692,53 @@ def test_ecs_sync_service_targets_does_not_publish_a_stale_view(monkeypatch):assert final == ["10.3.0.1"], f"a stale view was published: {final}"+def test_ecs_restored_services_relaunch_their_tasks(monkeypatch):+ """A service must satisfy desiredCount again after a restore.++ restore_state marks every restored task STOPPED, because its container is+ gone with the process that ran it. Nothing then reconciles the services, so+ a restarted ministack reports runningCount from the persisted record while+ no container exists, and the load balancer keeps forwarding to addresses+ nothing is listening on. Real ECS relaunches: the service scheduler exists+ to keep desiredCount satisfied.+ """+ from ministack.services import ecs as _ecs++ launched = []+ monkeypatch.setattr(_ecs, "_run_task", lambda data: launched.append(data))+ monkeypatch.setattr(_ecs, "_clusters", {"c1": {"clusterName": "c1"}})+ monkeypatch.setattr(_ecs, "_task_defs", {+ "web:1": {"taskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/web:1",+ "family": "web"},+ })+ monkeypatch.setattr(_ecs, "_services", {+ "c1/web": {+ "serviceName": "web", "status": "ACTIVE", "desiredCount": 2,+ "taskDefinition": "arn:aws:ecs:us-east-1:000000000000:task-definition/web:1", "clusterArn": "arn:cluster/c1",+ "launchType": "FARGATE", "deployments": [{"runningCount": 2}],+ },+ # An inactive service must not be relaunched.+ "c1/old": {+ "serviceName": "old", "status": "INACTIVE", "desiredCount": 3,+ "taskDefinition": "arn:aws:ecs:us-east-1:000000000000:task-definition/web:1", "clusterArn": "arn:cluster/c1",+ "launchType": "FARGATE", "deployments": [],+ },+ })+ # What restore_state leaves behind: the tasks exist but are STOPPED.+ monkeypatch.setattr(_ecs, "_tasks", {+ "arn:task/1": {"group": "service:web", "clusterArn": "arn:cluster/c1",+ "lastStatus": "STOPPED", "taskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/web:1"},+ "arn:task/2": {"group": "service:web", "clusterArn": "arn:cluster/c1",+ "lastStatus": "STOPPED", "taskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/web:1"},+ })++ _ecs._reconcile_restored_services()++ assert len(launched) == 1, f"expected one RunTask call, got {launched}"+ call = launched[0]+ assert call["group"] == "service:web"+ assert call["count"] == 2, "both stopped tasks must be replaced"+ assert all(c["group"] != "service:old" for c in launched)def test_ecs_service_reconcile_spares_foreign_targets(monkeypatch):"""A service withdraws only its own registrations: targets registered byhand (or by another service sharing the group) survive its reconcile and