-
Notifications
You must be signed in to change notification settings - Fork 1
/
windows-batch-compute-dag.py
357 lines (325 loc) · 13.6 KB
/
windows-batch-compute-dag.py
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
#!/usr/bin/env python3
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import logging
import time
import datetime
from typing import Dict
import boto3
from airflow import DAG
from airflow.models import Variable
from airflow.operators.python import PythonOperator
from airflow.providers.amazon.aws.operators.ecs import EcsRunTaskOperator
from airflow.models.param import Param
from airflow.utils.dates import days_ago
# ---------------------------------- Helper Functions
def get_cluster_name(cluster_resource_tag: str) -> str:
ecs_client = boto3.client("ecs")
response_clusters = ecs_client.list_clusters()
for cluster in response_clusters["clusterArns"]:
response_tags = ecs_client.list_tags_for_resource(resourceArn=cluster)
for tag in response_tags["tags"]:
if tag["key"] == cluster_resource_tag and tag["value"] == "true":
return ecs_client.describe_clusters(clusters=[cluster])["clusters"][0][
"clusterName"
]
def get_asg_name(cluster_resource_tag: str) -> str:
autoscaling_client = boto3.client("autoscaling")
response = autoscaling_client.describe_auto_scaling_groups()
for group in response["AutoScalingGroups"]:
for tag in group["Tags"]:
if tag["Key"] == cluster_resource_tag and tag["Value"] == "true":
return group["AutoScalingGroupName"]
def get_task_definition_properties(cluster_resource_tag: str) -> Dict:
ecs_client = boto3.client("ecs")
response_list = ecs_client.list_task_definitions()
for task in response_list["taskDefinitionArns"]:
response = ecs_client.list_tags_for_resource(resourceArn=task)
for tag in response["tags"]:
if tag["key"] == cluster_resource_tag and tag["value"] == "true":
task_definition = ecs_client.describe_task_definition(
taskDefinition=task
)
return {
"taskDefinitionArn": task,
"taskCpu": task_definition["taskDefinition"]["cpu"],
"taskMemory": task_definition["taskDefinition"]["memory"],
}
def get_task_definition_arn(cluster_resource_tag: str) -> str:
ecs_client = boto3.client("ecs")
response_list = ecs_client.list_task_definitions()
for task in response_list["taskDefinitionArns"]:
response = ecs_client.list_tags_for_resource(resourceArn=task)
for tag in response["tags"]:
if tag["key"] == cluster_resource_tag and tag["value"] == "true":
return str(task)
def get_asg_resource_properties(cluster_resource_tag: str) -> Dict:
cpus = 0
mem = 0
asg_name = get_asg_name(cluster_resource_tag)
autoscaling_client = boto3.client("autoscaling")
ec2_client = boto3.client("ec2")
asg_response = autoscaling_client.describe_auto_scaling_groups(
AutoScalingGroupNames=[asg_name]
)
instance_ids = []
for i in asg_response["AutoScalingGroups"]:
for k in i["Instances"]:
instance_ids.append(k["InstanceId"])
ec2_response = ec2_client.describe_instances(
InstanceIds=instance_ids,
Filters=[{"Name": "instance-state-name", "Values": ["running"]}],
)
for reservations in ec2_response["Reservations"]:
for instances in reservations["Instances"]:
type = instances["InstanceType"]
response = ec2_client.describe_instance_types(InstanceTypes=[type])
for instance_types in response["InstanceTypes"]:
cpus += instance_types["VCpuInfo"]["DefaultVCpus"]
mem += instance_types["MemoryInfo"]["SizeInMiB"]
return {"clusterCpu": str(cpus * 1024), "clusterMemory": str(mem)}
def wait_for_container_instances(cluster_resource_tag, desired_count, timeout=300):
ecs_client = boto3.client("ecs")
start_time = time.time()
instances_online = False
while not instances_online:
response = ecs_client.list_container_instances(
cluster=get_cluster_name(cluster_resource_tag), status="ACTIVE"
)
print(
f'{len(response["containerInstanceArns"])} container instances are active and registered with the cluster'
)
if len(response["containerInstanceArns"]) == desired_count:
instances_online = True
print(
f"{desired_count} container instances are active and registered with the cluster"
)
break
elif (time.time() - start_time) > timeout:
raise TimeoutError(
f"Timeout of {timeout} seconds exceeded while waiting for instances to be active and registered with the cluster"
)
else:
time.sleep(30)
def update_scaling_group(
cluster_resource_tag: str, desired_capacity: int, timeout: int = 180
) -> None:
group_name = get_asg_name(cluster_resource_tag)
desired_capacity = desired_capacity
autoscaling_client = boto3.client("autoscaling")
response = autoscaling_client.update_auto_scaling_group(
AutoScalingGroupName=group_name, DesiredCapacity=desired_capacity
)
response = autoscaling_client.describe_auto_scaling_groups(
AutoScalingGroupNames=[group_name]
)
desired_capacity = response["AutoScalingGroups"][0]["DesiredCapacity"]
current_capacity = len(response["AutoScalingGroups"][0]["Instances"])
while desired_capacity != current_capacity:
response = autoscaling_client.describe_auto_scaling_groups(
AutoScalingGroupNames=[group_name]
)
desired_capacity = response["AutoScalingGroups"][0]["DesiredCapacity"]
current_capacity = len(response["AutoScalingGroups"][0]["Instances"])
time.sleep(30)
print(
f"Successfully reached desired capacity of {desired_capacity} for group {group_name}."
)
def scale_cluster_capacity(**kwargs: Dict) -> None:
cluster_resource_tag = kwargs["cluster_resource_tag"]
capacity = int(kwargs["desired_capacity"])
timeout_asg = int(kwargs["timeout_asg"])
timeout_ecs = int(kwargs["timeout_ecs"])
print("Scale to desired capacity ", capacity)
update_scaling_group(cluster_resource_tag, capacity, timeout_asg)
print(
"Finished with Auto Scaling Group update, waiting for ECS Control plane consistency"
)
wait_for_container_instances(
cluster_resource_tag=cluster_resource_tag,
desired_count=capacity,
timeout=timeout_ecs,
)
task_definition_properties = get_task_definition_properties(cluster_resource_tag)
asg_resource_properties = get_asg_resource_properties(cluster_resource_tag)
simulate_tasks_concurrency = max(
1,
int(
min(
int(asg_resource_properties["clusterCpu"])
/ int(task_definition_properties["taskCpu"]),
int(asg_resource_properties["clusterMemory"])
/ int(task_definition_properties["taskMemory"]),
)
),
)
print("Setting simulation task concurrency to", simulate_tasks_concurrency)
Variable.set("simulate_tasks_concurrency", str(simulate_tasks_concurrency))
def generate_params(**kwargs: Dict) -> Dict:
num_tasks = int(kwargs["num_tasks"])
num_frames = int(kwargs["num_frames"])
frame_size = int(kwargs["frame_size"])
EbN0dB = kwargs["EbN0dB"]
EbN0dB = EbN0dB.strip("][").split(", ")
EbN0dB = [float(e) for e in EbN0dB]
s3_bucket = str(kwargs["s3_bucket"])
s3_prefix_task_results = str(kwargs["s3_prefix_task_results"])
cluster_container_name = str(kwargs["cluster_container_name"])
tasks_per_snr = num_tasks // len(EbN0dB)
simulate_tasks = []
for i in range(num_tasks):
snr_index = min(i // tasks_per_snr, len(EbN0dB) - 1)
simulate_tasks.append(
{
"containerOverrides": [
{
"name": str(cluster_container_name),
"command": [
"C:/workdir/simulate.ps1",
str(num_frames),
str(frame_size),
str(EbN0dB[snr_index]),
str(snr_index),
str(i),
str(s3_bucket),
str(s3_prefix_task_results),
],
},
],
}
)
return simulate_tasks
# ---------------------------------- Airflow DAG
CLUSTER_RESOURCE_TAG_DEFAULT = "windows-batch-blog"
with DAG(
dag_id="windows-batch-compute-dag",
description="Scale an ECS cluster of MS Windows hosts",
schedule_interval=None,
start_date=days_ago(1),
tags=[""],
default_args={"retries": 3, "retry_delay": datetime.timedelta(seconds=60)},
catchup=False,
params={
"num_tasks": Param(200, type="integer"),
"num_frames": Param(300000, type="integer"),
"frame_size": Param(4096, type="integer"),
"EbN0dB": Param([0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 11.0, 12.0], type="array"),
"s3_bucket": Param("CHANGE_TO_YOUR_BUCKET_NAME", type="string"),
"s3_prefix_task_results": Param("sim/task_results", type="string"),
"s3_prefix_aggregate_results": Param("sim/aggregate_results", type="string"),
"cluster_container_name": Param("WindowsBatchContainer", type="string"),
"cluster_scale_out_size": Param(6, type="integer"),
"cluster_scale_in_size": Param(0, type="integer"),
"cluster_scale_asg_timeout": Param(180, type="integer"),
"cluster_scale_ecs_timeout": Param(600, type="integer"),
},
) as dag:
# Airflow Task to aggregate simulation results
aggregate_task = EcsRunTaskOperator(
dag=dag,
task_id="aggregate",
cluster=get_cluster_name(
str(
Variable.get(
"cluster_resource_tag", default_var=CLUSTER_RESOURCE_TAG_DEFAULT
)
)
),
task_definition=get_task_definition_arn(
str(
Variable.get(
"cluster_resource_tag", default_var=CLUSTER_RESOURCE_TAG_DEFAULT
)
)
),
aws_conn_id="aws_ecs",
overrides={
"containerOverrides": [
{
"name": "{{ params.cluster_container_name }}",
"command": [
"C:/workdir/aggregate.ps1",
"{{ params.num_tasks }}",
"{{ params.s3_bucket }}",
"{{ params.s3_prefix_task_results }}",
"{{ params.s3_prefix_aggregate_results }}",
],
},
],
},
)
# Airflow Task to parse and prepare parameters for simulation
generate_params_task = PythonOperator(
task_id="generate_params",
python_callable=generate_params,
op_kwargs={
"num_tasks": "{{ params.num_tasks }}",
"num_frames": "{{ params.num_frames }}",
"frame_size": "{{ params.frame_size }}",
"EbN0dB": "{{ params.EbN0dB }}",
"s3_bucket": "{{ params.s3_bucket }}",
"s3_prefix_task_results": "{{ params.s3_prefix_task_results }}",
"cluster_container_name": "{{ params.cluster_container_name }}",
},
dag=dag,
)
# Airflow Task to run the actual payload simulation parallelized
simulate_task = EcsRunTaskOperator.partial(
dag=dag,
task_id="simulate",
cluster=get_cluster_name(
str(
Variable.get(
"cluster_resource_tag", default_var=CLUSTER_RESOURCE_TAG_DEFAULT
)
)
),
task_definition=get_task_definition_arn(
str(
Variable.get(
"cluster_resource_tag", default_var=CLUSTER_RESOURCE_TAG_DEFAULT
)
)
),
aws_conn_id="aws_ecs",
max_active_tis_per_dag=int(
Variable.get("simulate_tasks_concurrency", default_var=2)
),
).expand(overrides=generate_params_task.output)
# Airflow Task to scale the ECS cluster out before simulation
scale_out_task = PythonOperator(
task_id="scale_out",
python_callable=scale_cluster_capacity,
op_kwargs={
"cluster_resource_tag": str(
Variable.get(
"cluster_resource_tag", default_var=CLUSTER_RESOURCE_TAG_DEFAULT
)
),
"desired_capacity": "{{ params.cluster_scale_out_size }}",
"timeout_asg": "{{ params.cluster_scale_asg_timeout }}",
"timeout_ecs": "{{ params.cluster_scale_ecs_timeout }}",
},
dag=dag,
)
# Airflow Task to scale the ECS cluster in after simulation
scale_in_task = PythonOperator(
task_id="scale_in",
python_callable=scale_cluster_capacity,
op_kwargs={
"cluster_resource_tag": str(
Variable.get(
"cluster_resource_tag", default_var=CLUSTER_RESOURCE_TAG_DEFAULT
)
),
"desired_capacity": "{{ params.cluster_scale_in_size }}",
"timeout_asg": "{{ params.cluster_scale_asg_timeout }}",
"timeout_ecs": "{{ params.cluster_scale_ecs_timeout }}",
},
dag=dag,
)
# Define DAG Task dependencies
simulate_task.set_upstream(generate_params_task)
simulate_task.set_upstream(scale_out_task)
aggregate_task.set_upstream(simulate_task)
scale_in_task.set_upstream(aggregate_task)