forked from ray-project/ray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_gcs_ft_on_k8s.py
427 lines (373 loc) · 12 KB
/
run_gcs_ft_on_k8s.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
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
import enum
import json
import subprocess
from kubernetes import client, config, watch
import requests
import random
import uuid
import pathlib
import time
import ray
import os
# global variables for the cluster informations
CLUSTER_ID = None
RAY_CLUSTER_NAME = None
RAY_SERVICE_NAME = None
LOCUST_ID = None
# Kill node type
class TestScenario(enum.Enum):
KILL_WORKER_NODE = "kill_worker_node"
KILL_HEAD_NODE = "kill_head_node"
if os.environ.get("RAY_IMAGE") is not None:
ray_image = os.environ.get("RAY_IMAGE")
elif ray.__version__ != "3.0.0.dev0":
ray_image = f"rayproject/ray:{ray.__version__}"
elif ray.__commit__ == "{{RAY_COMMIT_SHA}}":
ray_image = "rayproject/ray:nightly"
else:
ray_image = f"rayproject/ray:{ray.__commit__[:6]}"
config.load_kube_config()
cli = client.CoreV1Api()
yaml_path = pathlib.Path("/tmp/ray_v1alpha1_rayservice.yaml")
def generate_cluster_variable():
global CLUSTER_ID
global RAY_CLUSTER_NAME
global RAY_SERVICE_NAME
global LOCUST_ID
CLUSTER_ID = str(uuid.uuid4()).split("-")[0]
RAY_CLUSTER_NAME = "cluster-" + CLUSTER_ID
RAY_SERVICE_NAME = "service-" + CLUSTER_ID
LOCUST_ID = "ray-locust-" + CLUSTER_ID
def check_kuberay_installed():
# Make sure the ray namespace exists
KUBERAY_VERSION = "v0.5.0"
uri = (
"github.com/ray-project/kuberay/manifests"
f"/base?ref={KUBERAY_VERSION}&timeout=90s"
)
print(
subprocess.check_output(
[
"kubectl",
"apply",
"-k",
uri,
]
).decode()
)
pods = subprocess.check_output(
["kubectl", "get", "pods", "--namespace", "ray-system", "--no-headers"]
).decode()
assert pods.split("\n") != 0
def start_rayservice():
# step-1: generate the yaml file
print(f"Using ray image: {ray_image}")
solution = "\n".join(
[
f" {line}"
for line in pathlib.Path("./solution.py").read_text().splitlines()
]
)
locustfile = "\n".join(
[
f" {line}"
for line in pathlib.Path("./locustfile.py").read_text().splitlines()
]
)
template = (
pathlib.Path("ray_v1alpha1_rayservice_template.yaml")
.read_text()
.format(
cluster_id=CLUSTER_ID,
ray_image=ray_image,
solution=solution,
locustfile=locustfile,
)
)
print("=== YamlFile ===")
print(template)
tmp_yaml = pathlib.Path("/tmp/ray_v1alpha1_rayservice.yaml")
tmp_yaml.write_text(template)
print("=== Get Pods from ray-system ===")
print(
subprocess.check_output(
["kubectl", "get", "pods", "--namespace", "ray-system", "--no-headers"]
).decode()
)
# step-2: create the cluter
print(f"Creating cluster with id: {CLUSTER_ID}")
print(subprocess.check_output(["kubectl", "create", "-f", str(tmp_yaml)]).decode())
# step-3: make sure the ray cluster is up
w = watch.Watch()
start_time = time.time()
head_pod_name = None
for event in w.stream(
func=cli.list_namespaced_pod,
namespace="default",
label_selector=f"rayCluster={RAY_CLUSTER_NAME},ray.io/node-type=head",
timeout_seconds=60,
):
if event["object"].status.phase == "Running":
assert event["object"].kind == "Pod"
head_pod_name = event["object"].metadata.name
end_time = time.time()
print(f"{CLUSTER_ID} started in {end_time-start_time} sec")
print(f"head pod {head_pod_name}")
break
assert head_pod_name is not None
# step-4: e2e check it's alive
cmd = """
import requests
print(requests.get('http:https://localhost:8000/?val=123').text)
"""
while True:
try:
resp = (
subprocess.check_output(
f'kubectl exec {head_pod_name} -- python -c "{cmd}"', shell=True
)
.decode()
.strip()
)
if resp == "375":
print("Service is up now!")
break
else:
print(f"Failed with msg {resp}")
except Exception as e:
print("Error", e)
time.sleep(2)
def start_port_forward():
proc = None
proc = subprocess.Popen(
[
"kubectl",
"port-forward",
f"svc/{RAY_SERVICE_NAME}-serve-svc",
"8000:8000",
"--address=0.0.0.0",
]
)
while True:
try:
resp = requests.get(
"http:https://localhost:8000/",
timeout=1,
params={
"val": 10,
},
)
if resp.status_code == 200:
print("The ray service is ready!!!")
break
except requests.exceptions.Timeout:
pass
except requests.exceptions.ConnectionError:
pass
print("Waiting for the proxy to be alive")
time.sleep(1)
return proc
def warmup_cluster(num_reqs):
for _ in range(num_reqs):
resp = requests.get(
"http:https://localhost:8000/",
timeout=1,
params={
"val": 10,
},
)
assert resp.status_code == 200
def start_sending_traffics(duration, users):
print("=== Install locust by helm ===")
yaml_config = (
pathlib.Path("locust-run.yaml")
.read_text()
.format(users=users, cluster_id=CLUSTER_ID, duration=int(duration))
)
print("=== Locust YAML ===")
print(yaml_config)
pathlib.Path("/tmp/locust-run-config.yaml").write_text(yaml_config)
helm_install_logs = subprocess.check_output(
[
"helm",
"install",
LOCUST_ID,
"deliveryhero/locust",
"-f",
"/tmp/locust-run-config.yaml",
]
)
print(helm_install_logs)
timeout_wait_for_locust_s = 300
while timeout_wait_for_locust_s > 0:
labels = [
f"app.kubernetes.io/instance=ray-locust-{CLUSTER_ID}",
"app.kubernetes.io/name=locust,component=master",
]
pods = cli.list_namespaced_pod("default", label_selector=",".join(labels))
assert len(pods.items) == 1
if pods.items[0].status.phase == "Pending":
print("Waiting for the locust pod to be ready...")
time.sleep(30)
timeout_wait_for_locust_s -= 30
else:
break
proc = subprocess.Popen(
[
"kubectl",
"port-forward",
f"svc/ray-locust-{CLUSTER_ID}",
"8080:8089",
"--address=0.0.0.0",
]
)
return proc
def dump_pods_actors(pod_name):
print(
subprocess.run(
f"kubectl exec {pod_name} -- ps -ef | grep ::",
shell=True,
capture_output=True,
).stdout.decode()
)
def kill_head():
pods = cli.list_namespaced_pod(
"default",
label_selector=f"rayCluster={RAY_CLUSTER_NAME},ray.io/node-type=head",
)
if pods.items[0].status.phase == "Running":
print(f"Killing header {pods.items[0].metadata.name}")
dump_pods_actors(pods.items[0].metadata.name)
cli.delete_namespaced_pod(pods.items[0].metadata.name, "default")
def kill_worker():
pods = cli.list_namespaced_pod(
"default",
label_selector=f"rayCluster={RAY_CLUSTER_NAME},ray.io/node-type=worker",
)
alive_pods = [
(p.status.start_time, p.metadata.name)
for p in pods.items
if p.status.phase == "Running"
]
# sorted(alive_pods)
# We kill the oldest nodes for now given the memory leak in serve.
# to_be_killed = alive_pods[-1][1]
to_be_killed = random.choice(alive_pods)[1]
print(f"Killing worker {to_be_killed}")
dump_pods_actors(pods.items[0].metadata.name)
cli.delete_namespaced_pod(to_be_killed, "default")
def start_killing_nodes(duration, kill_interval, kill_node_type):
"""Kill the nodes in ray cluster.
duration: How long does we run the test (seconds)
kill_interval: The interval between two kills (seconds)
kill_head_every_n: For every n kills, we kill a head node
kill_node_type: kill either worker node or head node
"""
for kill_idx in range(1, int(duration / kill_interval)):
while True:
try:
# kill
if kill_node_type == TestScenario.KILL_HEAD_NODE:
kill_head()
elif kill_node_type == TestScenario.KILL_WORKER_NODE:
kill_worker()
break
except Exception as e:
from time import sleep
print(f"Fail to kill node, retry in 5 seconds: {e}")
sleep(5)
time.sleep(kill_interval)
def get_stats():
labels = [
f"app.kubernetes.io/instance=ray-locust-{CLUSTER_ID}",
"app.kubernetes.io/name=locust,component=master",
]
pods = cli.list_namespaced_pod("default", label_selector=",".join(labels))
assert len(pods.items) == 1
pod_name = pods.items[0].metadata.name
subprocess.check_output(
[
"kubectl",
"cp",
f"{pod_name}:/home/locust/test_result_{CLUSTER_ID}_stats_history.csv",
"./stats_history.csv",
]
)
data = []
with open("stats_history.csv") as f:
import csv
reader = csv.reader(f)
for d in reader:
data.append(d)
# The first 5mins is for warming up
offset = 300
start_time = int(data[offset][0])
end_time = int(data[-1][0])
# 17 is the index for total requests
# 18 is the index for total failed requests
total = float(data[-1][17]) - float(data[offset][17])
failures = float(data[-1][18]) - float(data[offset][18])
# Available, through put
return (total - failures) / total, total / (end_time - start_time), data
def main():
result = {
TestScenario.KILL_WORKER_NODE.value: {"rate": None},
TestScenario.KILL_HEAD_NODE.value: {"rate": None},
}
expected_result = {
TestScenario.KILL_HEAD_NODE: 0.99,
TestScenario.KILL_HEAD_NODE: 0.99,
}
check_kuberay_installed()
users = 60
exception = None
for kill_node_type, kill_interval, test_duration in [
(TestScenario.KILL_WORKER_NODE, 60, 600),
(TestScenario.KILL_HEAD_NODE, 300, 1200),
]:
try:
generate_cluster_variable()
procs = []
start_rayservice()
procs.append(start_port_forward())
warmup_cluster(200)
procs.append(start_sending_traffics(test_duration * 1.1, users))
start_killing_nodes(test_duration, kill_interval, kill_node_type)
rate, qps, data = get_stats()
print("Raw Data", data, qps)
result[kill_node_type.value]["rate"] = rate
assert expected_result[kill_node_type] <= rate
assert qps > users * 10 * 0.8
except Exception as e:
print(f"{kill_node_type} HA test failed, {e}")
exception = e
finally:
print("=== Cleanup ===")
subprocess.run(
["kubectl", "delete", "-f", str(yaml_path)],
capture_output=True,
)
subprocess.run(
["helm", "uninstall", LOCUST_ID],
capture_output=True,
)
for p in procs:
p.kill()
print("==== Cleanup done ===")
if exception:
raise exception
print("Result:", result)
test_output_json_path = os.environ.get(
"TEST_OUTPUT_JSON", "/tmp/release_test_output.json"
)
with open(test_output_json_path, "wt") as f:
json.dump(result, f)
if __name__ == "__main__":
try:
# Connect to ray so that the auto suspense
# will not start.
ray.init("auto")
except Exception:
# It doesnt' matter if it failed.
pass
main()