Repository navigation
Expand file tree
/
Copy pathtest_ecs.py
More file actions
4455 lines (3846 loc) · 176 KB
/
Copy pathtest_ecs.py
File metadata and controls
4455 lines (3846 loc) · 176 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import json
import os
import time
import uuid as _uuid_mod
from types import SimpleNamespace
from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
from conftest import LoopProbe
from ministack.services import ecs as ecs_service
def _replace_arn_section(arn, index, value):
parts = arn.split(":", 5)
parts[index] = value
return ":".join(parts)
def _different_region(region):
return "us-west-2" if region != "us-west-2" else "us-east-1"
def _wait_until(predicate, timeout=5):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return
time.sleep(0.01)
assert predicate(), "condition did not become true before timeout"
def _ecs_docker_reachable():
"""Whether this end-to-end ECS lifecycle test can start real containers."""
try:
import docker
docker.from_env(timeout=2).ping()
except Exception:
return False
return True
requires_ecs_docker = pytest.mark.skipif(
not _ecs_docker_reachable(), reason="requires a reachable Docker daemon")
def _replace_arn_region(arn):
return _replace_arn_section(arn, 3, _different_region(arn.split(":", 5)[3]))
def test_ecs_cluster(ecs):
ecs.create_cluster(clusterName="test-cluster")
clusters = ecs.list_clusters()
assert any("test-cluster" in arn for arn in clusters["clusterArns"])
def test_ecs_task_def(ecs):
resp = ecs.register_task_definition(
family="test-task",
containerDefinitions=[
{
"name": "web",
"image": "nginx:alpine",
"cpu": 128,
"memory": 256,
"portMappings": [{"containerPort": 80, "hostPort": 8080}],
}
],
requiresCompatibilities=["EC2"],
cpu="256",
memory="512",
)
assert resp["taskDefinition"]["family"] == "test-task"
assert resp["taskDefinition"]["revision"] == 1
@pytest.mark.parametrize("cpu", [None, "512"])
@pytest.mark.parametrize("memory", [None, "1024"])
@pytest.mark.parametrize("requires_compatibilities", [None, ["EC2"]])
def test_ecs_task_definition_optional_fields_readback(
ecs, cpu, memory, requires_compatibilities,
):
# AWS RegisterTaskDefinition documents optional EC2 sizing and omission of
# unspecified requiresCompatibilities. Its register/describe/deregister
# examples omit task-level sizing when only container resources are given.
optional_fields = {
field: value for field, value in {
"cpu": cpu,
"memory": memory,
"requiresCompatibilities": requires_compatibilities,
}.items() if value is not None
}
registered = ecs.register_task_definition(
family=f"optional-fields-{_uuid_mod.uuid4().hex[:8]}",
containerDefinitions=[{
"name": "web", "image": "nginx:alpine", "cpu": 128, "memory": 256,
}],
**optional_fields,
)["taskDefinition"]
arn = registered["taskDefinitionArn"]
described = ecs.describe_task_definition(taskDefinition=arn)["taskDefinition"]
deregistered = ecs.deregister_task_definition(taskDefinition=arn)["taskDefinition"]
for td in (registered, described, deregistered):
for field in ("cpu", "memory", "requiresCompatibilities"):
if field in optional_fields:
assert td[field] == optional_fields[field]
else:
assert field not in td
assert td["containerDefinitions"][0]["cpu"] == 128
assert td["containerDefinitions"][0]["memory"] == 256
assert td["networkMode"] == "bridge"
assert registered["status"] == described["status"] == "ACTIVE"
assert deregistered["status"] == "INACTIVE"
def test_ecs_task_definition_explicit_fargate_sizing_readback(ecs):
registered = ecs.register_task_definition(
family=f"explicit-fargate-{_uuid_mod.uuid4().hex[:8]}",
containerDefinitions=[{"name": "web", "image": "nginx:alpine"}],
networkMode="awsvpc",
requiresCompatibilities=["FARGATE"],
cpu="512",
memory="1024",
)["taskDefinition"]
arn = registered["taskDefinitionArn"]
described = ecs.describe_task_definition(taskDefinition=arn)["taskDefinition"]
deregistered = ecs.deregister_task_definition(taskDefinition=arn)["taskDefinition"]
for td in (registered, described, deregistered):
assert td["cpu"] == "512"
assert td["memory"] == "1024"
assert td["requiresCompatibilities"] == ["FARGATE"]
assert td["networkMode"] == "awsvpc"
def test_ecs_list_task_defs(ecs):
resp = ecs.list_task_definitions(familyPrefix="test-task")
assert len(resp["taskDefinitionArns"]) >= 1
@pytest.mark.data_plane
def test_ecs_run_task_stops_after_exit(ecs):
"""DescribeTasks transitions to STOPPED after Docker container exits."""
ecs.create_cluster(clusterName="task-lifecycle")
ecs.register_task_definition(
family="short-lived",
containerDefinitions=[
{
"name": "worker",
"image": "alpine:latest",
"command": ["sh", "-c", "echo done"],
"essential": True,
}
],
)
resp = ecs.run_task(cluster="task-lifecycle", taskDefinition="short-lived")
task_arn = resp["tasks"][0]["taskArn"]
assert resp["tasks"][0]["lastStatus"] in ("PROVISIONING", "PENDING", "RUNNING")
# Poll until STOPPED (container exits almost immediately)
stopped = False
for _ in range(30):
time.sleep(2)
desc = ecs.describe_tasks(cluster="task-lifecycle", tasks=[task_arn])
task = desc["tasks"][0]
if task["lastStatus"] == "STOPPED":
stopped = True
assert task["desiredStatus"] == "STOPPED"
assert task["stopCode"] == "EssentialContainerExited"
assert task["containers"][0]["lastStatus"] == "STOPPED"
assert task["containers"][0]["exitCode"] == 0
break
assert stopped, "Task should transition to STOPPED after container exits"
@pytest.mark.data_plane
def test_ecs_run_task_forwards_awslogs_to_cloudwatch_logs(ecs, logs):
cluster = f"awslogs-{_uuid_mod.uuid4().hex[:8]}"
family = f"{cluster}-td"
group = f"/ecs/{cluster}"
marker = f"ECS-AWSLOGS-{_uuid_mod.uuid4().hex[:8]}"
stream_prefix = "ecs"
logs.create_log_group(logGroupName=group)
ecs.create_cluster(clusterName=cluster)
ecs.register_task_definition(
family=family,
containerDefinitions=[{
"name": "app",
"image": "alpine:latest",
"command": ["sh", "-c", f"echo {marker}"],
"essential": True,
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": group,
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": stream_prefix,
},
},
}],
)
try:
resp = ecs.run_task(cluster=cluster, taskDefinition=family)
except Exception as exc:
pytest.skip(f"ECS RunTask unavailable in this environment: {exc}")
task_arn = resp["tasks"][0]["taskArn"]
task_id = task_arn.rsplit("/", 1)[-1]
stream_name = f"{stream_prefix}/app/{task_id}"
def marker_reached_cloudwatch_logs():
streams = logs.describe_log_streams(
logGroupName=group,
logStreamNamePrefix=stream_name,
)["logStreams"]
if not streams:
return False
events = logs.get_log_events(
logGroupName=group,
logStreamName=stream_name,
)["events"]
return any(marker in event["message"] for event in events)
_wait_until(marker_reached_cloudwatch_logs, timeout=20)
def _logs_client(region):
import boto3
from botocore.config import Config
from conftest import ENDPOINT
return boto3.client("logs", endpoint_url=ENDPOINT, region_name=region,
aws_access_key_id="test", aws_secret_access_key="test",
config=Config(region_name=region, inject_host_prefix=False))
@pytest.mark.data_plane
def test_ecs_awslogs_without_stream_prefix_names_the_stream_after_the_container_id(ecs, logs):
"""AWS: "If you don't specify a prefix with this option, then the log stream
is named after the container ID that's assigned by the Docker daemon"."""
cluster = f"awslogs-noprefix-{_uuid_mod.uuid4().hex[:8]}"
family = f"{cluster}-td"
group = f"/ecs/{cluster}"
marker = f"ECS-NOPREFIX-{_uuid_mod.uuid4().hex[:8]}"
logs.create_log_group(logGroupName=group)
ecs.create_cluster(clusterName=cluster)
ecs.register_task_definition(
family=family,
containerDefinitions=[{
"name": "app",
"image": "alpine:latest",
"command": ["sh", "-c", f"echo {marker}"],
"essential": True,
"logConfiguration": {
"logDriver": "awslogs",
"options": {"awslogs-group": group, "awslogs-region": "us-east-1"},
},
}],
)
task_arn = ecs.run_task(cluster=cluster, taskDefinition=family)["tasks"][0]["taskArn"]
def runtime_id():
containers = ecs.describe_tasks(cluster=cluster, tasks=[task_arn])["tasks"][0]["containers"]
return containers[0].get("runtimeId")
_wait_until(runtime_id, timeout=30)
short_id = runtime_id()
def stream_named_after_the_container():
streams = logs.describe_log_streams(logGroupName=group)["logStreams"]
names = {s["logStreamName"] for s in streams}
if not names:
return False
assert not any("/" in n for n in names), f"expected a bare container id, got {names}"
assert names == {n for n in names if n.startswith(short_id)}, names
stream = next(iter(names))
assert len(stream) == 64, f"expected the full docker container id, got {stream}"
events = logs.get_log_events(logGroupName=group, logStreamName=stream)["events"]
return any(marker in e["message"] for e in events)
_wait_until(stream_named_after_the_container, timeout=30)
@pytest.mark.data_plane
def test_ecs_awslogs_region_option_decides_where_the_logs_land(ecs, logs):
"""awslogs-region is where the driver ships the logs, not where the task ran."""
target_region = _different_region("us-east-1")
remote_logs = _logs_client(target_region)
cluster = f"awslogs-region-{_uuid_mod.uuid4().hex[:8]}"
family = f"{cluster}-td"
group = f"/ecs/{cluster}"
marker = f"ECS-REGION-{_uuid_mod.uuid4().hex[:8]}"
remote_logs.create_log_group(logGroupName=group)
ecs.create_cluster(clusterName=cluster)
ecs.register_task_definition(
family=family,
containerDefinitions=[{
"name": "app",
"image": "alpine:latest",
"command": ["sh", "-c", f"echo {marker}"],
"essential": True,
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": group,
"awslogs-region": target_region,
"awslogs-stream-prefix": "ecs",
},
},
}],
)
task_arn = ecs.run_task(cluster=cluster, taskDefinition=family)["tasks"][0]["taskArn"]
stream = f"ecs/app/{task_arn.rsplit('/', 1)[-1]}"
def marker_in_target_region():
streams = remote_logs.describe_log_streams(
logGroupName=group, logStreamNamePrefix=stream)["logStreams"]
if not streams:
return False
events = remote_logs.get_log_events(logGroupName=group, logStreamName=stream)["events"]
return any(marker in e["message"] for e in events)
_wait_until(marker_in_target_region, timeout=30)
with pytest.raises(ClientError) as exc:
logs.describe_log_streams(logGroupName=group)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
@pytest.mark.data_plane
def test_ecs_list_tasks_reflects_natural_container_exit(ecs):
"""ListTasks must also reconcile lifecycle when a container has exited
on its own. Previously only DescribeTasks ran the reconciler, so a user
who only ever called ListTasks(desiredStatus=RUNNING) saw the dead task
forever, and ListTasks(desiredStatus=STOPPED) returned an empty list.
Reference: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-lifecycle-explanation.html
"Some tasks are meant to run as batch jobs that naturally progress
through from PENDING to RUNNING to STOPPED."
"""
cluster = "task-lifecycle-listtasks"
ecs.create_cluster(clusterName=cluster)
ecs.register_task_definition(
family="short-lived-list",
containerDefinitions=[{
"name": "worker",
"image": "alpine:latest",
"command": ["sh", "-c", "echo done"],
"essential": True,
}],
)
resp = ecs.run_task(cluster=cluster, taskDefinition="short-lived-list")
task_arn = resp["tasks"][0]["taskArn"]
# Give the container time to actually exit before we test the reconciler.
# 6s is enough for `echo done` + Docker bookkeeping on every CI host
# the existing run_task tests already pass on.
time.sleep(6)
# NOTE: explicitly NOT calling describe_tasks — the bug is that
# list_tasks alone never reconciled.
running = ecs.list_tasks(cluster=cluster, desiredStatus="RUNNING")["taskArns"]
assert task_arn not in running, (
"list_tasks(RUNNING) should not return a task whose container exited"
)
stopped = ecs.list_tasks(cluster=cluster, desiredStatus="STOPPED")["taskArns"]
assert task_arn in stopped, (
"list_tasks(STOPPED) should surface the naturally-exited task"
)
@pytest.mark.data_plane
def test_ecs_run_task_network_connectivity(ecs):
"""ECS container can reach Ministack (proves network detection works)."""
endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
# Determine how a container can reach the host where Ministack runs.
# Docker Desktop (macOS/Windows): host.docker.internal works.
# Linux: use the Docker bridge gateway IP (typically 172.17.0.1).
host = os.environ.get("MINISTACK_HOST_FROM_CONTAINER", "")
if not host:
import platform
if platform.system() == "Linux":
# Docker bridge gateway — how containers reach the host on Linux
host = "172.17.0.1"
else:
host = "host.docker.internal"
parsed = urlparse(endpoint)
container_endpoint = f"{parsed.scheme}://{host}:{parsed.port}"
ecs.create_cluster(clusterName="net-test")
ecs.register_task_definition(
family="net-probe",
containerDefinitions=[
{
"name": "probe",
"image": "alpine:latest",
"command": ["sh", "-c", f"wget -q -O /dev/null {container_endpoint}/_ministack/health"],
"essential": True,
}
],
)
resp = ecs.run_task(cluster="net-test", taskDefinition="net-probe")
task_arn = resp["tasks"][0]["taskArn"]
assert resp["tasks"][0]["lastStatus"] in ("PROVISIONING", "PENDING", "RUNNING")
# Poll until STOPPED — wget should succeed (exit 0) if network is correct
success = False
for _ in range(30):
time.sleep(2)
desc = ecs.describe_tasks(cluster="net-test", tasks=[task_arn])
task = desc["tasks"][0]
if task["lastStatus"] == "STOPPED":
exit_code = task["containers"][0].get("exitCode")
assert exit_code == 0, (
f"Container could not reach Ministack at {container_endpoint} "
f"(exit code {exit_code}) — network detection may be broken"
)
success = True
break
assert success, "Task should transition to STOPPED"
@pytest.mark.data_plane
def test_ecs_run_task_metadata_v4(ecs):
"""Container can resolve and read its V4 task-metadata URI end-to-end.
Proves the full wiring: env-var injection in _run_task, the
host.docker.internal/host-gateway extra_hosts mapping, the gateway
routing /v4/<token>/task to ecs_metadata.handle_request, and the task
payload containing the Containers array.
"""
ecs.create_cluster(clusterName="metadata-test")
ecs.register_task_definition(
family="metadata-probe",
containerDefinitions=[
{
"name": "probe",
"image": "alpine:latest",
# wget -O /tmp/r exits 0 only if the URI is reachable and
# returns 200; grep then proves the body is the V4 task
# shape (with a Containers array) rather than something
# else returning 200.
"command": [
"sh", "-c",
'wget -q -O /tmp/r "$ECS_CONTAINER_METADATA_URI_V4/task" '
'&& grep -q \'"Containers"\' /tmp/r',
],
"essential": True,
}
],
)
resp = ecs.run_task(cluster="metadata-test", taskDefinition="metadata-probe")
task_arn = resp["tasks"][0]["taskArn"]
assert resp["tasks"][0]["lastStatus"] in ("PROVISIONING", "PENDING", "RUNNING")
success = False
for _ in range(30):
time.sleep(2)
desc = ecs.describe_tasks(cluster="metadata-test", tasks=[task_arn])
task = desc["tasks"][0]
if task["lastStatus"] == "STOPPED":
exit_code = task["containers"][0].get("exitCode")
assert exit_code == 0, (
f"Container could not read ECS_CONTAINER_METADATA_URI_V4/task "
f"(exit code {exit_code}) — env-var injection, host-gateway "
"mapping, or the /v4/<token> route may be broken"
)
success = True
break
assert success, "Task should transition to STOPPED"
@pytest.mark.parametrize("has_services", [False, True])
def test_ecs_central_restore_reconciles_after_loading_state(monkeypatch, tmp_path, has_services):
"""Boot restores tasks and attributes before scheduling service relaunch."""
import ministack.app as app
from ministack.core import persistence
from ministack.core.responses import AccountRegionScopedDict
account, region = "222222222222", "eu-west-1"
services = AccountRegionScopedDict()
tasks = AccountRegionScopedDict()
attributes = AccountRegionScopedDict()
if has_services:
services.set_scoped(account, region, "cluster/service", {"status": "ACTIVE"})
tasks.set_scoped(account, region, "task", {"lastStatus": "RUNNING", "version": 1})
attributes.set_scoped(account, region, "instance:attr", {"name": "attr", "value": "v"})
for name in ("_services", "_tasks", "_attributes"):
monkeypatch.setattr(ecs_service, name, AccountRegionScopedDict())
monkeypatch.setattr(persistence, "PERSIST_STATE", True)
monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
monkeypatch.setattr(app, "_state_map", {"ecs": "ecs"})
monkeypatch.setattr(app, "_loaded_modules", {})
persistence.save_state("ecs", {"services": services, "tasks": tasks, "attributes": attributes})
scheduled = []
def schedule():
# Capture what the worker would see at the moment it is scheduled.
scheduled.append(copy.deepcopy(ecs_service._tasks.get_scoped(account, region, "task")))
monkeypatch.setattr(ecs_service, "_start_restored_service_reconciler", schedule)
app._load_persisted_state()
task = ecs_service._tasks.get_scoped(account, region, "task")
assert task["lastStatus"] == "STOPPED"
assert task["version"] == 2
assert ecs_service._attributes.get_scoped(account, region, "instance:attr")["value"] == "v"
assert scheduled == ([task] if has_services else [])
def test_ecs_run_task_applies_container_command_overrides(monkeypatch):
"""RunTask containerOverrides.command should reach Docker run kwargs."""
from ministack.services import ecs as _ecs
class FakeContainers:
def __init__(self):
self.calls = []
def get(self, _name):
raise Exception("not found")
def list(self, *args, **kwargs):
return []
def run(self, image, **kwargs):
self.calls.append((image, kwargs))
return SimpleNamespace(id=f"container-{len(self.calls):012d}")
fake_containers = FakeContainers()
fake_docker = SimpleNamespace(containers=fake_containers)
monkeypatch.setattr(_ecs, "_get_docker", lambda: fake_docker)
_ecs._register_task_definition({
"family": "cmd-override-td",
"containerDefinitions": [
{
"name": "web",
"image": "busybox",
"command": ["echo", "default-web"],
},
{
"name": "worker",
"image": "busybox",
"command": ["echo", "default-worker"],
},
],
})
_ecs._run_task({
"cluster": "cmd-override-c",
"taskDefinition": "cmd-override-td",
"overrides": {
"containerOverrides": [
{"name": "web", "command": ["echo", "override-web"]},
],
},
})
_wait_until(lambda: len(fake_containers.calls) == 2)
calls_by_name = {
kwargs["labels"]["com.amazonaws.ecs.container-name"]: kwargs
for _image, kwargs in fake_containers.calls
}
assert calls_by_name["web"]["command"] == ["echo", "override-web"]
assert calls_by_name["worker"]["command"] == ["echo", "default-worker"]
td = _ecs._task_defs["cmd-override-td:1"]
assert td["containerDefinitions"][0]["command"] == ["echo", "default-web"]
def test_ecs_run_task_command_override_allows_empty_command(monkeypatch):
"""An explicit empty command override must replace the task definition command."""
from ministack.services import ecs as _ecs
class FakeContainers:
def __init__(self):
self.calls = []
def get(self, _name):
raise Exception("not found")
def list(self, *args, **kwargs):
return []
def run(self, image, **kwargs):
self.calls.append((image, kwargs))
return SimpleNamespace(id="container-empty-command")
fake_containers = FakeContainers()
fake_docker = SimpleNamespace(containers=fake_containers)
monkeypatch.setattr(_ecs, "_get_docker", lambda: fake_docker)
_ecs._register_task_definition({
"family": "empty-cmd-override-td",
"containerDefinitions": [
{
"name": "web",
"image": "busybox",
"command": ["echo", "default"],
},
],
})
_ecs._run_task({
"cluster": "empty-cmd-override-c",
"taskDefinition": "empty-cmd-override-td",
"overrides": {
"containerOverrides": [
{"name": "web", "command": []},
],
},
})
_wait_until(lambda: fake_containers.calls)
assert fake_containers.calls[0][1]["command"] == []
def test_ecs_run_task_injects_secrets_manager_secrets(monkeypatch):
"""RunTask must resolve containerDefinitions[].secrets (Secrets Manager
valueFrom) and inject them into the container environment, including the
json-key form."""
from ministack.services import ecs as _ecs
from ministack.services import secretsmanager as _sm
_sm._create_secret({"Name": "ecs-secret-plain", "SecretString": "s3cr3t"})
_sm._create_secret({"Name": "ecs-secret-json",
"SecretString": json.dumps({"password": "pa55"})})
plain_arn = _sm._resolve("ecs-secret-plain")[1]["ARN"]
json_arn = _sm._resolve("ecs-secret-json")[1]["ARN"]
class FakeContainers:
def __init__(self):
self.calls = []
def get(self, _name):
raise Exception("not found")
def list(self, *args, **kwargs):
return []
def run(self, image, **kwargs):
self.calls.append((image, kwargs))
return SimpleNamespace(id=f"container-{len(self.calls):012d}")
fake_containers = FakeContainers()
monkeypatch.setattr(_ecs, "_get_docker",
lambda: SimpleNamespace(containers=fake_containers))
_ecs._register_task_definition({
"family": "secrets-td",
"containerDefinitions": [
{
"name": "app",
"image": "busybox",
"environment": [{"name": "FOO", "value": "bar"}],
"secrets": [
{"name": "SECRET_VAL", "valueFrom": plain_arn},
{"name": "DB_PASS", "valueFrom": f"{json_arn}:password::"},
],
},
],
})
_ecs._run_task({"cluster": "secrets-c", "taskDefinition": "secrets-td"})
_wait_until(lambda: fake_containers.calls)
env = fake_containers.calls[0][1]["environment"]
assert env["FOO"] == "bar"
assert env["SECRET_VAL"] == "s3cr3t"
assert env["DB_PASS"] == "pa55"
def test_ecs_service(ecs):
ecs.create_service(
cluster="test-cluster",
serviceName="test-service",
taskDefinition="test-task",
desiredCount=1,
)
resp = ecs.describe_services(cluster="test-cluster", services=["test-service"])
assert len(resp["services"]) == 1
assert resp["services"][0]["serviceName"] == "test-service"
def test_ecs_create_cluster_v2(ecs):
resp = ecs.create_cluster(clusterName="ecs-cc-v2")
assert resp["cluster"]["clusterName"] == "ecs-cc-v2"
assert resp["cluster"]["status"] == "ACTIVE"
assert "clusterArn" in resp["cluster"]
def test_ecs_list_clusters_v2(ecs):
ecs.create_cluster(clusterName="ecs-lc-v2a")
ecs.create_cluster(clusterName="ecs-lc-v2b")
resp = ecs.list_clusters()
arns = resp["clusterArns"]
assert any("ecs-lc-v2a" in a for a in arns)
assert any("ecs-lc-v2b" in a for a in arns)
def test_ecs_register_task_def_v2(ecs):
resp = ecs.register_task_definition(
family="ecs-td-v2",
containerDefinitions=[
{
"name": "web",
"image": "nginx:alpine",
"cpu": 256,
"memory": 512,
"portMappings": [{"containerPort": 80, "hostPort": 8080}],
},
{"name": "sidecar", "image": "envoy:latest", "cpu": 128, "memory": 256},
],
requiresCompatibilities=["EC2"],
cpu="512",
memory="1024",
)
td = resp["taskDefinition"]
assert td["family"] == "ecs-td-v2"
assert td["revision"] == 1
assert td["status"] == "ACTIVE"
assert len(td["containerDefinitions"]) == 2
resp2 = ecs.register_task_definition(
family="ecs-td-v2",
containerDefinitions=[{"name": "web", "image": "nginx:alpine", "cpu": 256, "memory": 512}],
)
assert resp2["taskDefinition"]["revision"] == 2
def test_ecs_list_task_defs_v2(ecs):
ecs.register_task_definition(
family="ecs-ltd-v2",
containerDefinitions=[{"name": "app", "image": "img", "cpu": 64, "memory": 128}],
)
resp = ecs.list_task_definitions(familyPrefix="ecs-ltd-v2")
assert len(resp["taskDefinitionArns"]) >= 1
assert all("ecs-ltd-v2" in a for a in resp["taskDefinitionArns"])
def test_ecs_create_service_v2(ecs):
ecs.create_cluster(clusterName="ecs-svc-v2c")
ecs.register_task_definition(
family="ecs-svc-v2td",
containerDefinitions=[{"name": "w", "image": "alpine:latest", "command": ["sleep", "3600"], "cpu": 64, "memory": 128}],
)
resp = ecs.create_service(
cluster="ecs-svc-v2c",
serviceName="ecs-svc-v2",
taskDefinition="ecs-svc-v2td",
desiredCount=2,
)
svc = resp["service"]
assert svc["serviceName"] == "ecs-svc-v2"
assert svc["status"] == "ACTIVE"
assert svc["desiredCount"] == 2
def test_ecs_describe_services_v2(ecs):
ecs.create_cluster(clusterName="ecs-ds-v2c")
ecs.register_task_definition(
family="ecs-ds-v2td",
containerDefinitions=[{"name": "w", "image": "alpine:latest", "command": ["sleep", "3600"], "cpu": 64, "memory": 128}],
)
ecs.create_service(
cluster="ecs-ds-v2c",
serviceName="ecs-ds-v2a",
taskDefinition="ecs-ds-v2td",
desiredCount=1,
)
ecs.create_service(
cluster="ecs-ds-v2c",
serviceName="ecs-ds-v2b",
taskDefinition="ecs-ds-v2td",
desiredCount=3,
)
resp = ecs.describe_services(cluster="ecs-ds-v2c", services=["ecs-ds-v2a", "ecs-ds-v2b"])
assert len(resp["services"]) == 2
svc_map = {s["serviceName"]: s for s in resp["services"]}
assert svc_map["ecs-ds-v2a"]["desiredCount"] == 1
assert svc_map["ecs-ds-v2b"]["desiredCount"] == 3
def test_ecs_update_service_v2(ecs):
ecs.create_cluster(clusterName="ecs-us-v2c")
ecs.register_task_definition(
family="ecs-us-v2td",
containerDefinitions=[{"name": "w", "image": "alpine:latest", "command": ["sleep", "3600"], "cpu": 64, "memory": 128}],
)
ecs.create_service(
cluster="ecs-us-v2c",
serviceName="ecs-us-v2",
taskDefinition="ecs-us-v2td",
desiredCount=1,
)
ecs.update_service(cluster="ecs-us-v2c", service="ecs-us-v2", desiredCount=5)
resp = ecs.describe_services(cluster="ecs-us-v2c", services=["ecs-us-v2"])
assert resp["services"][0]["desiredCount"] == 5
def test_ecs_tags_v2(ecs):
resp = ecs.create_cluster(
clusterName="ecs-tag-v2c",
tags=[{"key": "env", "value": "staging"}],
)
arn = resp["cluster"]["clusterArn"]
tags = ecs.list_tags_for_resource(resourceArn=arn)["tags"]
assert any(t["key"] == "env" and t["value"] == "staging" for t in tags)
ecs.tag_resource(resourceArn=arn, tags=[{"key": "team", "value": "platform"}])
tags2 = ecs.list_tags_for_resource(resourceArn=arn)["tags"]
tag_map = {t["key"]: t["value"] for t in tags2}
assert tag_map["env"] == "staging"
assert tag_map["team"] == "platform"
ecs.untag_resource(resourceArn=arn, tagKeys=["env"])
tags3 = ecs.list_tags_for_resource(resourceArn=arn)["tags"]
assert not any(t["key"] == "env" for t in tags3)
assert any(t["key"] == "team" for t in tags3)
def test_ecs_capacity_provider(ecs):
resp = ecs.create_capacity_provider(
name="test-cp",
autoScalingGroupProvider={
"autoScalingGroupArn": "arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:xxx:autoScalingGroupName/asg-1",
"managedScaling": {"status": "ENABLED"},
},
)
assert resp["capacityProvider"]["name"] == "test-cp"
desc = ecs.describe_capacity_providers(capacityProviders=["test-cp"])
assert any(cp["name"] == "test-cp" for cp in desc["capacityProviders"])
ecs.delete_capacity_provider(capacityProvider="test-cp")
def test_ecs_cluster_arn_parser_does_not_tail_resolve_invalid_arns(ecs):
resp = ecs.create_cluster(clusterName="ecs-arn-cluster")
cluster_arn = resp["cluster"]["clusterArn"]
valid = ecs.describe_clusters(clusters=[cluster_arn])
assert valid["clusters"][0]["clusterName"] == "ecs-arn-cluster"
wrong_service = _replace_arn_section(cluster_arn, 2, "lambda")
wrong_partition = _replace_arn_section(cluster_arn, 1, "aws-cn")
wrong_region = _replace_arn_region(cluster_arn)
wrong_account = _replace_arn_section(cluster_arn, 4, "111111111111")
wrong_resource = cluster_arn.replace(":cluster/", ":service/")
malformed_resource = f"{cluster_arn}/extra"
malformed = "arn:aws:ecs:us-east-1"
for ref in [wrong_service, wrong_partition, wrong_region, wrong_account, wrong_resource, malformed_resource, malformed]:
resp = ecs.describe_clusters(clusters=[ref])
assert resp["clusters"] == []
assert resp["failures"] == [{"arn": ref, "reason": "MISSING"}]
def test_ecs_service_arn_parser_does_not_tail_resolve_invalid_arns(ecs):
cluster = "ecs-arn-service-cluster"
cluster_arn = ecs.create_cluster(clusterName=cluster)["cluster"]["clusterArn"]
ecs.register_task_definition(
family="ecs-arn-service-td",
containerDefinitions=[{"name": "app", "image": "alpine:latest", "command": ["sleep", "3600"], "cpu": 64, "memory": 128}],
)
created = ecs.create_service(
cluster=cluster,
serviceName="ecs-arn-service",
taskDefinition="ecs-arn-service-td",
desiredCount=0,
)
service_arn = created["service"]["serviceArn"]
valid = ecs.describe_services(cluster=cluster, services=[service_arn])
assert valid["services"][0]["serviceName"] == "ecs-arn-service"
ecs.create_service(
cluster=cluster,
serviceName="None",
taskDefinition="ecs-arn-service-td",
desiredCount=0,
)
ecs.create_cluster(clusterName="None")
ecs.create_service(
cluster="None",
serviceName="ecs-arn-service",
taskDefinition="ecs-arn-service-td",
desiredCount=0,
)
other_cluster = "ecs-arn-other-service-cluster"
ecs.create_cluster(clusterName=other_cluster)
other_service = ecs.create_service(
cluster=other_cluster,
serviceName="ecs-arn-service",
taskDefinition="ecs-arn-service-td",
desiredCount=0,
)["service"]
wrong_service = _replace_arn_section(service_arn, 2, "lambda")
wrong_partition = _replace_arn_section(service_arn, 1, "aws-cn")
wrong_region = _replace_arn_region(service_arn)
wrong_account = _replace_arn_section(service_arn, 4, "111111111111")
wrong_resource = service_arn.replace(":service/", ":cluster/")
wrong_cluster_service = other_service["serviceArn"]
malformed_resource = service_arn.replace(f":service/{cluster}/", f":service/extra/{cluster}/")
malformed = "arn:aws:ecs:us-east-1"
for ref in [
wrong_service,
wrong_partition,
wrong_region,
wrong_account,
wrong_resource,
wrong_cluster_service,
malformed_resource,
malformed,
]:
resp = ecs.describe_services(cluster=cluster, services=[ref])
assert resp["services"] == []
assert resp["failures"] == [{"arn": ref, "reason": "MISSING"}]
wrong_cluster = _replace_arn_region(cluster_arn)
with pytest.raises(ClientError) as exc:
ecs.describe_services(cluster=wrong_cluster, services=["ecs-arn-service"])
assert exc.value.response["Error"]["Code"] == "ClusterNotFoundException"
with pytest.raises(ClientError) as exc:
ecs.update_service(cluster=cluster, service=wrong_service, desiredCount=1)
assert exc.value.response["Error"]["Code"] == "ServiceNotFoundException"
none_service = ecs.describe_services(cluster=cluster, services=["None"])
assert none_service["services"][0]["desiredCount"] == 0
with pytest.raises(ClientError) as exc:
ecs.delete_service(cluster=cluster, service=wrong_service, force=True)
assert exc.value.response["Error"]["Code"] == "ServiceNotFoundException"
none_service = ecs.describe_services(cluster=cluster, services=["None"])
assert none_service["services"][0]["status"] == "ACTIVE"
with pytest.raises(ClientError) as exc:
ecs.update_service(cluster=cluster, service=wrong_cluster_service, desiredCount=1)
assert exc.value.response["Error"]["Code"] == "ServiceNotFoundException"
service = ecs.describe_services(cluster=cluster, services=["ecs-arn-service"])
assert service["services"][0]["desiredCount"] == 0
with pytest.raises(ClientError) as exc:
ecs.delete_service(cluster=cluster, service=wrong_cluster_service, force=True)
assert exc.value.response["Error"]["Code"] == "ServiceNotFoundException"
service = ecs.describe_services(cluster=cluster, services=["ecs-arn-service"])
assert service["services"][0]["status"] == "ACTIVE"
def test_ecs_task_definition_arn_parser_does_not_tail_resolve_invalid_arns(ecs):
resp = ecs.register_task_definition(
family="ecs-arn-td",
containerDefinitions=[{"name": "app", "image": "alpine:latest", "command": ["sleep", "3600"], "cpu": 64, "memory": 128}],
)
task_definition_arn = resp["taskDefinition"]["taskDefinitionArn"]
valid = ecs.describe_task_definition(taskDefinition=task_definition_arn)
assert valid["taskDefinition"]["family"] == "ecs-arn-td"
wrong_service = _replace_arn_section(task_definition_arn, 2, "lambda")
wrong_partition = _replace_arn_section(task_definition_arn, 1, "aws-cn")
wrong_region = _replace_arn_region(task_definition_arn)
wrong_account = _replace_arn_section(task_definition_arn, 4, "111111111111")
wrong_resource = task_definition_arn.replace(":task-definition/", ":cluster/")
malformed_resource = f"{task_definition_arn}/extra"
malformed = "arn:aws:ecs:us-east-1"
for ref in [wrong_service, wrong_partition, wrong_region, wrong_account, wrong_resource, malformed_resource, malformed]:
with pytest.raises(ClientError) as exc:
ecs.describe_task_definition(taskDefinition=ref)
assert exc.value.response["Error"]["Code"] == "ClientException"
delete_resp = ecs.delete_task_definitions(taskDefinitions=[wrong_service])
assert delete_resp["taskDefinitions"] == []
assert delete_resp["failures"] == [
{"arn": wrong_service, "reason": "TASK_DEFINITION_NOT_FOUND"},
]
delete_resp = ecs.delete_task_definitions(taskDefinitions=["ecs-arn-td"])
assert delete_resp["taskDefinitions"] == []
assert delete_resp["failures"] == [
{"arn": "ecs-arn-td", "reason": "TASK_DEFINITION_NOT_FOUND"},
]
valid = ecs.describe_task_definition(taskDefinition=task_definition_arn)
assert valid["taskDefinition"]["status"] == "ACTIVE"
cluster = "ecs-arn-td-service-cluster"
ecs.create_cluster(clusterName=cluster)
with pytest.raises(ClientError) as exc:
ecs.create_service(
cluster=cluster,
serviceName="ecs-arn-invalid-td-service",
taskDefinition=wrong_region,
desiredCount=0,
)
assert exc.value.response["Error"]["Code"] == "ClientException"
created = ecs.create_service(
cluster=cluster,
serviceName="ecs-arn-valid-td-service",
taskDefinition=task_definition_arn,
desiredCount=0,
)
assert created["service"]["taskDefinition"] == task_definition_arn
with pytest.raises(ClientError) as exc:
ecs.update_service(
cluster=cluster,
service="ecs-arn-valid-td-service",
taskDefinition=wrong_region,