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): drain completed service deployments (#1779)
Copilot1035af93a673
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex df12403f..49c11116 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -888,12 +888,75 @@ def _refresh_service_state(cluster_name, group):pending += 1svc["runningCount"] = runningsvc["pendingCount"] = pending- if svc.get("deployments"):- svc["deployments"][0]["runningCount"] = running- svc["deployments"][0]["pendingCount"] = pending+ _refresh_service_deployments(cluster_name, svc)_sync_service_targets(cluster_name, svc)+def _refresh_service_deployments(cluster_name, svc):+ """Reconcile per-deployment counts and retire a completed old deployment."""+ deployments = svc.get("deployments") or []+ if not deployments:+ return++ cluster_arn = svc.get("clusterArn", "")+ group = f"service:{svc.get('serviceName', '')}"+ service_tasks = [+ task for task in _tasks.values()+ if task.get("group") == group+ and task.get("clusterArn") == cluster_arn+ ]+ for deployment in deployments:+ td_arn = deployment.get("taskDefinition")+ matching = [task for task in service_tasks+ if task.get("taskDefinitionArn") == td_arn]+ deployment["runningCount"] = sum(+ task.get("lastStatus") == "RUNNING" for task in matching+ )+ deployment["pendingCount"] = sum(+ task.get("lastStatus") == "PENDING" for task in matching+ )++ primary = deployments[0]+ primary_desired = primary.get("desiredCount", svc.get("desiredCount", 0))+ healthy = primary.get("runningCount", 0) >= primary_desired+ if len(deployments) > 1 and not healthy:+ primary["rolloutState"] = "IN_PROGRESS"+ primary["rolloutStateReason"] = ""+ return+ if not healthy:+ return++ primary["rolloutState"] = "COMPLETED"+ primary["rolloutStateReason"] = "ECS deployment completed."+ primary_td = primary.get("taskDefinition")+ for deployment in deployments[1:]:+ deployment["desiredCount"] = 0+ stale = [+ task for task in service_tasks+ if task.get("taskDefinitionArn") != primary_td+ and task.get("lastStatus") in _PRE_STOP_STATUSES+ ]+ for task in stale:+ _stop_task({+ "task": task["taskArn"],+ "cluster": cluster_name,+ "reason": "ECS deployment completed",+ })++ # _stop_task refreshes this service recursively, so only live tasks can+ # keep an old deployment in the response.+ for deployment in list(deployments[1:]):+ td_arn = deployment.get("taskDefinition")+ if not any(+ task.get("taskDefinitionArn") == td_arn+ and task.get("group") == group+ and task.get("clusterArn") == cluster_arn+ and task.get("lastStatus") in _PRE_STOP_STATUSES+ for task in _tasks.values()+ ):+ deployments.remove(deployment)++def _reconcile_service_tasks(cluster_name, svc_key):"""Spawn or stop active tasks so desiredCount and task definition match."""svc = _services.get(svc_key)@@ -926,11 +989,6 @@ def _reconcile_service_tasks(cluster_name, svc_key):else:stale_tasks.append((arn, t))- # Stop tasks running on a stale task definition- for task_arn, _ in stale_tasks:- _stop_task({"task": task_arn, "cluster": cluster_name,- "reason": "Task definition updated"})-# Scale up: spawn tasks to reach desiredCountto_spawn = desired - len(current_tasks)if to_spawn > 0:@@ -939,6 +997,19 @@ def _reconcile_service_tasks(cluster_name, svc_key):if svc["deployments"]:svc["deployments"][0]["runningCount"] = desiredreturn+ deployment_config = svc.get("deploymentConfiguration") or {}+ maximum_percent = int(deployment_config.get("maximumPercent", 200))+ max_running = max(1, desired * maximum_percent // 100)+ capacity = max_running - len(current_tasks) - len(stale_tasks)+ if capacity < to_spawn:+ # A maximumPercent of 100 requires old tasks to drain before+ # replacement tasks can be started.+ for task_arn, _ in stale_tasks[:to_spawn - max(0, capacity)]:+ _stop_task({+ "task": task_arn,+ "cluster": cluster_name,+ "reason": "Deployment capacity limit",+ })_run_task({"cluster": cluster_name,"taskDefinition": td_arn,@@ -1012,6 +1083,8 @@ def _create_service(data):"healthCheckGracePeriodSeconds": data.get("healthCheckGracePeriodSeconds", 0),"schedulingStrategy": data.get("schedulingStrategy", "REPLICA"),"deploymentController": data.get("deploymentController", {"type": "ECS"}),+ # deploymentCircuitBreaker and alarms are accepted for API+ # compatibility but are not evaluated by the emulator."deploymentConfiguration": data.get("deploymentConfiguration", {"maximumPercent": 200,"minimumHealthyPercent": 100,diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex b6b81ae0..931092f5 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -1197,10 +1197,10 @@ def test_ecs_service_td_update_replaces_tasks(ecs):containerDefinitions=[{"name": "app", "image": "nginx:latest", "cpu": 64, "memory": 128}],)ecs.create_service(- cluster=cluster, serviceName="tdu-svc", taskDefinition="tdu-td:1", desiredCount=2,+ cluster=cluster, serviceName="tdu-svc", taskDefinition="tdu-td:1", desiredCount=1,)old_tasks = ecs.list_tasks(cluster=cluster, serviceName="tdu-svc")- assert len(old_tasks["taskArns"]) == 2+ assert len(old_tasks["taskArns"]) == 1# Register new revision and update serviceresp2 = ecs.register_task_definition(@@ -1210,9 +1210,23 @@ def test_ecs_service_td_update_replaces_tasks(ecs):new_td_arn = resp2["taskDefinition"]["taskDefinitionArn"]ecs.update_service(cluster=cluster, service="tdu-svc", taskDefinition="tdu-td:2")+ # ECS keeps both deployments while the replacement becomes healthy, then+ # drains the old deployment and collapses the service to the new one.+ _wait_until(+ lambda: (+ len(ecs.describe_services(+ cluster=cluster, services=["tdu-svc"]+ )["services"][0]["deployments"]) == 1+ and ecs.describe_services(+ cluster=cluster, services=["tdu-svc"]+ )["services"][0]["deployments"][0]["rolloutState"] == "COMPLETED"+ ),+ timeout=30,+ )+# New tasks should be on the new TDnew_tasks = ecs.list_tasks(cluster=cluster, serviceName="tdu-svc")- assert len(new_tasks["taskArns"]) == 2+ assert len(new_tasks["taskArns"]) == 1# Verify all running tasks use the new task definition_wait_until(@@ -1239,11 +1253,16 @@ def test_ecs_service_td_update_replaces_tasks(ecs):_wait_until(lambda: ecs.describe_services(cluster=cluster, services=["tdu-svc"]- )["services"][0]["runningCount"] == 2,+ )["services"][0]["runningCount"] == 1,timeout=30,)svc = ecs.describe_services(cluster=cluster, services=["tdu-svc"])- assert svc["services"][0]["runningCount"] == 2+ service = svc["services"][0]+ assert service["runningCount"] == 1+ assert len(service["deployments"]) == 1+ assert service["deployments"][0]["taskDefinition"] == new_td_arn+ assert service["deployments"][0]["status"] == "PRIMARY"+ assert service["deployments"][0]["rolloutState"] == "COMPLETED"def test_ecs_service_delete_stops_tasks(ecs):