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): return cluster statistics for include STATISTICS (#1943)
iot-rocketdfd018c19002
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d3c32426..a09c44db 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **ECS — `DescribeClusters` statistics** — `include=["STATISTICS"]` returns the sixteen running/pending task and active/draining service counters per launch type instead of an empty list.+- **ECS — `DescribeClusters` honours `include`** — `settings` and `tags` come back empty and `attachments` and `configuration` are left out unless requested, `CreateCluster` keeps `configuration`, and a CloudFormation cluster reports its tags and the default `containerInsights` setting.- **ECS — `DescribeClusters` honours `include`** — `settings` and `tags` come back empty and `attachments` and `configuration` are left out unless requested, `CreateCluster` keeps `configuration`, and a CloudFormation cluster reports its tags and the default `containerInsights` setting.- **CloudFormation — `AWS::S3::MultiRegionAccessPoint` and `AWS::AutoScaling::LaunchConfiguration` are replaced on update** — every property of both types is create-only, so a change now creates the resource under a new generated name and deletes the old one after the update (a `Regions` change was dropped and the stack reported the alias as the physical id, a launch configuration was overwritten under its old name), fails with the custom-named-resource error when the name is explicit, and is reported as `Replacement: True` in a change set.- **CloudFormation — `AWS::SQS::Queue` with `FifoQueue` gets a generated `.fifo` name** — `FifoQueue: true` without a `QueueName` creates a FIFO queue with a generated `.fifo` name instead of a standard queue, and a `QueueName` whose `.fifo` suffix disagrees with `FifoQueue` fails the resource. Contributed by @iot-rocket.diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 5a39ac4c..a1e43c9b 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -33,6 +33,7 @@ import osimport secretsimport threadingimport time+from collections import Counterfrom ministack.core import container_reaperfrom ministack.core.arn import ArnParseError, parse_arn@@ -569,7 +570,7 @@ def _cluster_view(cluster, include):c = {k: v for k, v in cluster.items()if k not in ("attachments", "attachmentsStatus", "configuration")}c["settings"] = cluster["settings"] if "SETTINGS" in include else []- c["statistics"] = []+ c["statistics"] = _cluster_statistics(cluster) if "STATISTICS" in include else []c["tags"] = _tags.get(cluster["clusterArn"], []) if "TAGS" in include else []if "ATTACHMENTS" in include:c["attachments"] = cluster.get("attachments", [])@@ -578,6 +579,30 @@ def _cluster_view(cluster, include):return c+_STATISTICS_LAUNCH_TYPES = (("EC2", "FARGATE"), ("EXTERNAL",), ("MANAGED_INSTANCES",))+_STATISTICS_LABELS = {"EC2": "EC2", "FARGATE": "Fargate", "EXTERNAL": "External",+ "MANAGED_INSTANCES": "ManagedInstances"}+++def _cluster_statistics(cluster):+ """Task and service counters by launch type, in the order AWS lists them."""+ name = cluster["clusterName"]+ counts = Counter((t["lastStatus"], t.get("launchType")) for t in _tasks.values()+ if t.get("clusterArn") == cluster["clusterArn"])+ counts.update((s["status"], s.get("launchType")) for k, s in _services.items()+ if k.startswith(f"{name}/"))+ stats = []+ for kind, states in (("Tasks", ("RUNNING", "PENDING")), ("Service", ("ACTIVE", "DRAINING"))):+ for group in _STATISTICS_LAUNCH_TYPES:+ for state in states:+ for launch_type in group:+ stats.append({+ "name": f"{state.lower()}{_STATISTICS_LABELS[launch_type]}{kind}Count",+ "value": str(counts[(state, launch_type)]),+ })+ return stats++def _list_clusters(data):arns = [c["clusterArn"] for c in _clusters.values() if c["status"] == "ACTIVE"]return json_response({"clusterArns": arns})diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex f52bcced..b4295552 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -1131,6 +1131,34 @@ def test_ecs_describe_clusters_include_gates_fields(ecs, include):ecs.delete_cluster(cluster=name)+def test_ecs_describe_clusters_statistics_count_services_by_launch_type(ecs):+ """STATISTICS lists the sixteen task and service counters in the AWS order."""+ name = f"stats-{_uuid_mod.uuid4().hex[:8]}"+ ecs.create_cluster(clusterName=name)+ td = ecs.register_task_definition(+ family=name, containerDefinitions=[{"name": "app", "image": "alpine", "memory": 128}],+ )["taskDefinition"]["taskDefinitionArn"]+ ecs.create_service(cluster=name, serviceName="svc", taskDefinition=td,+ desiredCount=0, launchType="EC2")+ try:+ stats = ecs.describe_clusters(clusters=[name], include=["STATISTICS"])["clusters"][0]["statistics"]+ assert [s["name"] for s in stats] == [+ "runningEC2TasksCount", "runningFargateTasksCount",+ "pendingEC2TasksCount", "pendingFargateTasksCount",+ "runningExternalTasksCount", "pendingExternalTasksCount",+ "runningManagedInstancesTasksCount", "pendingManagedInstancesTasksCount",+ "activeEC2ServiceCount", "activeFargateServiceCount",+ "drainingEC2ServiceCount", "drainingFargateServiceCount",+ "activeExternalServiceCount", "drainingExternalServiceCount",+ "activeManagedInstancesServiceCount", "drainingManagedInstancesServiceCount",+ ]+ assert {s["name"]: s["value"] for s in stats if s["value"] != "0"} == {"activeEC2ServiceCount": "1"}+ finally:+ ecs.delete_service(cluster=name, service="svc")+ ecs.delete_cluster(cluster=name)+ ecs.deregister_task_definition(taskDefinition=td)++def test_ecs_timestamps_are_epoch(ecs):"""ECS timestamps should be epoch numbers, not ISO strings."""ecs.create_cluster(clusterName="ts-test-v44")