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): register a service's tasks in its target groups (#1550)
Jacob Schooley2f7c5c2cb709
diff --git a/ministack/services/alb.py b/ministack/services/alb.pyindex 8032a31a..2ee8d25a 100644--- a/ministack/services/alb.py+++ b/ministack/services/alb.py@@ -863,6 +863,19 @@ def _set_rule_priorities(params):# Target registration handlers# ---------------------------------------------------------------------------+def set_targets_for_group(tg_arn, targets):+ """Replace a target group's registrations. Used by ECS, whose services own the+ membership of their target group and reconcile it as tasks come and go.++ ``targets`` is an iterable of ``(id, port)``. Unknown target groups are ignored+ rather than raising: a service can outlive the group it referenced.+ """+ if tg_arn not in _tgs:+ return False+ _targets[tg_arn] = [{"Id": tid, "Port": port} for tid, port in targets]+ return True++def _register_targets(params):tg_arn = _p(params, "TargetGroupArn")if tg_arn not in _tgs:diff --git a/ministack/services/ecs.py b/ministack/services/ecs.pyindex 55ee5bb3..47da1b03 100644--- a/ministack/services/ecs.py+++ b/ministack/services/ecs.py@@ -33,7 +33,7 @@ import timefrom ministack.core import container_reaperfrom ministack.core.arn import ArnParseError, parse_arn-from ministack.core.concurrency import run_reentrant+from ministack.core.concurrency import resource_lock, run_reentrantfrom ministack.core.persistence import load_statefrom ministack.core.responses import (AccountRegionScopedDict,@@ -652,6 +652,92 @@ def _make_deployment(task_definition, desired_count, status="PRIMARY"):}+def _record_task_ip(task, container, ecs_network):+ """Store the container's address on the task as an ENI attachment.++ Real awsvpc tasks expose it as attachments[].details[privateIPv4Address], which+ is where an ALB target group and DescribeTasks both look for it.+ """+ if task.get("attachments"):+ return+ try:+ container.reload()+ nets = container.attrs["NetworkSettings"]["Networks"]+ ip = (nets.get(ecs_network) or next(iter(nets.values()), {})).get("IPAddress")+ except Exception:+ ip = None+ if not ip:+ return+ task["attachments"] = [{+ "id": new_uuid(),+ "type": "ElasticNetworkInterface",+ "status": "ATTACHED",+ "details": [{"name": "privateIPv4Address", "value": ip}],+ }]+ task["attachmentsStatus"] = "ATTACHED"+++def _task_ip(task):+ for att in task.get("attachments") or []:+ for d in att.get("details") or []:+ if d.get("name") == "privateIPv4Address":+ return d.get("value")+ return None+++def _sync_service_targets(cluster_name, svc):+ """Register the service's running tasks in its target groups.++ An ECS service owns the membership of the target groups named in its+ loadBalancers block, so this replaces the registration wholesale rather than+ tracking individual add/remove events — that makes it correct for scale-up,+ scale-in, task replacement and service deletion alike.++ Tasks are selected by ``group``, the same predicate _reconcile_service_tasks+ uses for its own recount, so the registered targets cannot disagree with the+ runningCount reported alongside them.++ Collecting the addresses and publishing them is a read-modify-write on shared+ state, and handlers no longer run serialised on the event loop, so it is done+ under resource_lock. There is no Docker call or re-entrant dispatch inside the+ lock, per the rule in ministack.core.concurrency.+ """+ lbs = svc.get("loadBalancers") or []+ if not lbs:+ return+ try:+ from ministack.services import alb+ except Exception:+ return++ svc_name = svc.get("serviceName")+ cluster_arn = svc.get("clusterArn")+ active = svc.get("status") == "ACTIVE"+ group = f"service:{svc_name}"++ for lb in lbs:+ tg_arn = lb.get("targetGroupArn")+ if not tg_arn:+ continue+ port = lb.get("containerPort", 80)+ with resource_lock("elbv2-targets", tg_arn):+ targets = []+ if active:+ for task in list(_tasks.values()):+ if task.get("group") != group:+ continue+ if task.get("clusterArn") != cluster_arn:+ continue+ if task.get("lastStatus") != "RUNNING":+ continue+ ip = _task_ip(task)+ if ip:+ targets.append((ip, port))+ published = alb.set_targets_for_group(tg_arn, targets)+ if published:+ logger.debug("ECS: %s -> %d target(s) in %s", svc_name, len(targets), tg_arn)++def _reconcile_service_tasks(cluster_name, svc_key):"""Spawn or stop tasks so running tasks match desiredCount and task definition."""svc = _services.get(svc_key)@@ -725,6 +811,9 @@ def _reconcile_service_tasks(cluster_name, svc_key):svc["deployments"][0]["runningCount"] = running_recount_cluster(cluster_name)+ # Membership of the service's target groups follows its running tasks.+ _sync_service_targets(cluster_name, svc)+def _create_service(data):cluster_name = _resolve_cluster_name(data.get("cluster", "default"))@@ -849,6 +938,9 @@ def _delete_service(data):# conflicts on status=ACTIVE.svc["status"] = "INACTIVE"+ # A deleted service leaves nothing registered behind it.+ _sync_service_targets(cluster_name, svc)+_recount_cluster(cluster_name)return json_response({"service": _sanitize(svc)})@@ -1342,6 +1434,7 @@ def _run_task(data):task.setdefault("_metadata_tokens", []).append(metadata_token)if i < len(task["containers"]):task["containers"][i]["runtimeId"] = container.id[:12]+ _record_task_ip(task, container, ecs_network)logger.info("ECS: started container %s for task %s", cdef['image'], task_id[:8])except Exception as e:ecs_metadata.unregister_token(metadata_token)diff --git a/tests/test_ecs.py b/tests/test_ecs.pyindex d6819237..22f53d9d 100644--- a/tests/test_ecs.py+++ b/tests/test_ecs.py@@ -1471,3 +1471,222 @@ def test_ecs_bridge_task_still_publishes_host_ports(monkeypatch):_image, kwargs = fake_containers.calls[0]assert kwargs.get("ports") == {"80/tcp": 8080}+def test_ecs_service_registers_tasks_in_target_group(monkeypatch):+ """A service with loadBalancers must register its running tasks as targets.++ Without this the ALB data plane has nothing to forward to and every request+ falls through to the listener's default action.+ """+ from ministack.services import alb as _alb+ from ministack.services import ecs as _ecs++ task_ip = "172.30.0.7"++ class FakeContainer:+ def __init__(self, cid):+ self.id = cid+ self.attrs = {"NetworkSettings": {"Networks": {"ministack_default": {"IPAddress": task_ip}}}}++ def reload(self):+ pass++ class FakeContainers:+ def __init__(self):+ self.n = 0++ def get(self, _name):+ raise Exception("not found")++ def list(self, *a, **k):+ return []++ def run(self, image, **kwargs):+ self.n += 1+ return FakeContainer(f"container-{self.n:012d}")++ monkeypatch.setattr(_ecs, "_get_docker", lambda: SimpleNamespace(containers=FakeContainers()))++ tg_arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-reg/abc123"+ _alb._tgs[tg_arn] = {"TargetGroupArn": tg_arn, "Port": 80, "TargetType": "ip"}+ _alb._targets[tg_arn] = []++ _ecs._register_task_definition({+ "family": "lb-reg-td",+ "networkMode": "awsvpc",+ "containerDefinitions": [{"name": "web", "image": "busybox"}],+ })+ _ecs._create_service({+ "cluster": "lb-reg-c",+ "serviceName": "lb-reg-svc",+ "taskDefinition": "lb-reg-td",+ "desiredCount": 1,+ "loadBalancers": [+ {"targetGroupArn": tg_arn, "containerName": "web", "containerPort": 80},+ ],+ })++ registered = _alb._targets.get(tg_arn, [])+ assert registered == [{"Id": task_ip, "Port": 80}], registered++ # ...and deleting the service leaves nothing registered behind it.+ _ecs._delete_service({"cluster": "lb-reg-c", "service": "lb-reg-svc", "force": True})+ assert _alb._targets.get(tg_arn) == []+++def test_ecs_task_records_private_ipv4_attachment(monkeypatch):+ """awsvpc tasks expose their address the way real ECS does."""+ from ministack.services import ecs as _ecs++ class FakeContainer:+ id = "container-000000000001"+ attrs = {"NetworkSettings": {"Networks": {"ministack_default": {"IPAddress": "172.30.0.9"}}}}++ def reload(self):+ pass++ class FakeContainers:+ def get(self, _name):+ raise Exception("not found")++ def list(self, *a, **k):+ return []++ def run(self, image, **kwargs):+ return FakeContainer()++ monkeypatch.setattr(_ecs, "_get_docker", lambda: SimpleNamespace(containers=FakeContainers()))++ _ecs._register_task_definition({+ "family": "eni-td",+ "networkMode": "awsvpc",+ "containerDefinitions": [{"name": "web", "image": "busybox"}],+ })+ resp = _ecs._run_task({"cluster": "eni-c", "taskDefinition": "eni-td"})+ _status, _headers, raw = resp+ task = json.loads(raw)["tasks"][0]++ assert _ecs._task_ip(task) == "172.30.0.9"+ assert task["attachmentsStatus"] == "ATTACHED"+ assert task["attachments"][0]["type"] == "ElasticNetworkInterface"+++def test_ecs_sync_service_targets_selects_tasks_by_group(monkeypatch):+ """Target selection must use the same predicate as the service's own recount.++ _reconcile_service_tasks counts a service's tasks by `group`; selecting targets+ by any other field lets the registered targets disagree with the runningCount+ reported next to them.+ """+ from ministack.services import alb as _alb+ from ministack.services import ecs as _ecs++ tg_arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-pred/abc"+ _alb._tgs[tg_arn] = {"TargetGroupArn": tg_arn, "Port": 80, "TargetType": "ip"}+ _alb._targets[tg_arn] = []++ svc = {+ "serviceName": "pred-svc",+ "clusterArn": "arn:aws:ecs:us-east-1:000000000000:cluster/pred-c",+ "status": "ACTIVE",+ "loadBalancers": [{"targetGroupArn": tg_arn, "containerName": "web", "containerPort": 80}],+ }++ def _task(ip, **over):+ t = {+ "group": "service:pred-svc",+ "clusterArn": svc["clusterArn"],+ "lastStatus": "RUNNING",+ "attachments": [{+ "type": "ElasticNetworkInterface",+ "details": [{"name": "privateIPv4Address", "value": ip}],+ }],+ }+ t.update(over)+ return t++ monkeypatch.setattr(_ecs, "_tasks", {+ "a": _task("10.0.0.1"),+ # carries the group but no startedBy — still this service's task+ "b": _task("10.0.0.2", startedBy=None),+ # right group, wrong cluster+ "c": _task("10.0.0.3", clusterArn="arn:aws:ecs:us-east-1:000000000000:cluster/other"),+ # right cluster, different service+ "d": _task("10.0.0.4", group="service:someone-else"),+ # this service, not running+ "e": _task("10.0.0.5", lastStatus="STOPPED"),+ })++ _ecs._sync_service_targets("pred-c", svc)+ assert sorted(t["Id"] for t in _alb._targets[tg_arn]) == ["10.0.0.1", "10.0.0.2"]+++def test_ecs_sync_service_targets_does_not_publish_a_stale_view(monkeypatch):+ """A slow reconciliation must not overwrite a newer one's registration.++ The failure this guards is last-writer-wins on a stale read: a reconcile that+ sampled the tasks before a scale-in, but publishes after it, would re-register+ the tasks that scale-in removed. Serialising the read and the publish means the+ last write is also the last read, so the final registration matches the final+ task state.+ """+ import threading++ from ministack.services import alb as _alb+ from ministack.services import ecs as _ecs++ tg_arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-stale/abc"+ _alb._tgs[tg_arn] = {"TargetGroupArn": tg_arn, "Port": 80, "TargetType": "ip"}+ _alb._targets[tg_arn] = []++ svc = {+ "serviceName": "stale-svc",+ "clusterArn": "arn:aws:ecs:us-east-1:000000000000:cluster/stale-c",+ "status": "ACTIVE",+ "loadBalancers": [{"targetGroupArn": tg_arn, "containerName": "web", "containerPort": 80}],+ }++ def _task(ip):+ return {+ "group": "service:stale-svc",+ "clusterArn": svc["clusterArn"],+ "lastStatus": "RUNNING",+ "attachments": [{+ "type": "ElasticNetworkInterface",+ "details": [{"name": "privateIPv4Address", "value": ip}],+ }],+ }++ before = {ip: _task(ip) for ip in ("10.3.0.1", "10.3.0.2", "10.3.0.3")}+ after = {"10.3.0.1": _task("10.3.0.1")} # scaled in to one task+ shared = dict(before)+ monkeypatch.setattr(_ecs, "_tasks", shared, raising=False)++ sampled = threading.Event()+ scaled_in = threading.Event()++ real_task_ip = _ecs._task_ip+ slowed = {"done": False}++ def slow_task_ip(task):+ # Let the first reconcile sample the pre-scale-in state, then stall it+ # until the scale-in has happened and been published by the other thread.+ if not slowed["done"]:+ slowed["done"] = True+ sampled.set()+ scaled_in.wait(timeout=5)+ return real_task_ip(task)++ monkeypatch.setattr(_ecs, "_task_ip", slow_task_ip)++ slow = threading.Thread(target=_ecs._sync_service_targets, args=("stale-c", svc))+ slow.start()++ assert sampled.wait(timeout=5), "the slow reconcile never sampled"+ shared.clear()+ shared.update(after)+ _ecs._sync_service_targets("stale-c", svc) # the newer, post-scale-in view+ scaled_in.set()+ slow.join(timeout=10)++ final = sorted(t["Id"] for t in _alb._targets[tg_arn])+ assert final == ["10.3.0.1"], f"a stale view was published: {final}"