-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
test_job_manager.py
1354 lines (1102 loc) · 46.9 KB
/
test_job_manager.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
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 asyncio
import os
import signal
import sys
import tempfile
import time
import urllib.request
from uuid import uuid4
import psutil
import pytest
import ray
from ray._private.gcs_utils import GcsAioClient
from ray._private.ray_constants import (
RAY_ADDRESS_ENVIRONMENT_VARIABLE,
KV_NAMESPACE_JOB,
DEFAULT_DASHBOARD_AGENT_LISTEN_PORT,
)
from ray._private.test_utils import (
SignalActor,
async_wait_for_condition,
async_wait_for_condition_async_predicate,
wait_for_condition,
)
from ray.dashboard.modules.job.common import JOB_ID_METADATA_KEY, JOB_NAME_METADATA_KEY
from ray.dashboard.modules.job.job_manager import (
JobLogStorageClient,
JobManager,
JobSupervisor,
generate_job_id,
)
from ray.dashboard.consts import (
RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES_ENV_VAR,
RAY_JOB_START_TIMEOUT_SECONDS_ENV_VAR,
)
from ray.dashboard.modules.job.tests.conftest import (
create_ray_cluster,
create_job_manager,
_driver_script_path,
)
from ray.job_submission import JobStatus
from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy # noqa: F401
from ray.tests.conftest import call_ray_start # noqa: F401
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_ray_start",
["""ray start --head"""],
indirect=True,
)
@pytest.mark.parametrize("resources_specified", [True, False])
async def test_get_scheduling_strategy(
call_ray_start, monkeypatch, resources_specified, tmp_path # noqa: F811
):
monkeypatch.setenv(RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES_ENV_VAR, "0")
address_info = ray.init(address=call_ray_start)
gcs_aio_client = GcsAioClient(
address=address_info["gcs_address"], nums_reconnect_retry=0
)
job_manager = JobManager(gcs_aio_client, tmp_path)
# If no head node id is found, we should use "DEFAULT".
await gcs_aio_client.internal_kv_del(
"head_node_id".encode(), del_by_prefix=False, namespace=KV_NAMESPACE_JOB
)
strategy = await job_manager._get_scheduling_strategy(resources_specified)
assert strategy == "DEFAULT"
# Add a head node id to the internal KV to simulate what is done in node_head.py.
await gcs_aio_client.internal_kv_put(
"head_node_id".encode(), "123456".encode(), True, namespace=KV_NAMESPACE_JOB
)
strategy = await job_manager._get_scheduling_strategy(resources_specified)
if resources_specified:
assert strategy == "DEFAULT"
else:
expected_strategy = NodeAffinitySchedulingStrategy("123456", soft=False)
assert expected_strategy.node_id == strategy.node_id
assert expected_strategy.soft == strategy.soft
# When the env var is set to 1, we should use DEFAULT.
monkeypatch.setenv(RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES_ENV_VAR, "1")
strategy = await job_manager._get_scheduling_strategy(resources_specified)
assert strategy == "DEFAULT"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_ray_start",
["""ray start --head --resources={"TestResourceKey":123}"""],
indirect=True,
)
async def test_submit_no_ray_address(call_ray_start, tmp_path): # noqa: F811
"""Test that a job script with an unspecified Ray address works."""
address_info = ray.init(address=call_ray_start)
gcs_aio_client = GcsAioClient(
address=address_info["gcs_address"], nums_reconnect_retry=0
)
job_manager = JobManager(gcs_aio_client, tmp_path)
init_ray_no_address_script = """
import ray
ray.init()
# Check that we connected to the running test Ray cluster and didn't create a new one.
print(ray.cluster_resources())
assert ray.cluster_resources().get('TestResourceKey') == 123
"""
# The job script should work even if RAY_ADDRESS is not set on the cluster.
os.environ.pop(RAY_ADDRESS_ENVIRONMENT_VARIABLE, None)
job_id = await job_manager.submit_job(
entrypoint=f"""python -c "{init_ray_no_address_script}" """
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_ray_start",
["ray start --head"],
indirect=True,
)
async def test_get_all_job_info(call_ray_start, tmp_path): # noqa: F811
"""Test that JobInfo is correctly populated in the GCS get_all_job_info API."""
address_info = ray.init(address=call_ray_start)
gcs_aio_client = GcsAioClient(
address=address_info["gcs_address"], nums_reconnect_retry=0
)
job_manager = JobManager(gcs_aio_client, tmp_path)
# Submit a job.
submission_id = await job_manager.submit_job(
entrypoint="python -c 'import ray; ray.init()'",
)
# Wait for the job to be finished.
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=submission_id
)
found = False
for job_table_entry in (await gcs_aio_client.get_all_job_info()).values():
if job_table_entry.config.metadata.get(JOB_ID_METADATA_KEY) == submission_id:
found = True
# Check that the job info is populated correctly.
job_info = job_table_entry.job_info
assert job_info.status == "SUCCEEDED"
assert job_info.entrypoint == "python -c 'import ray; ray.init()'"
assert job_info.message == "Job finished successfully."
assert job_info.start_time > 0
assert job_info.end_time > job_info.start_time
assert job_info.entrypoint_num_cpus == 0
assert job_info.entrypoint_num_gpus == 0
assert job_info.entrypoint_memory == 0
assert job_info.driver_agent_http_address.startswith(
"http://"
) and job_info.driver_agent_http_address.endswith(
str(DEFAULT_DASHBOARD_AGENT_LISTEN_PORT)
)
assert job_info.driver_node_id != ""
assert found
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_ray_start",
["ray start --head"],
indirect=True,
)
async def test_get_all_job_info_with_is_running_tasks(call_ray_start): # noqa: F811
"""Test the is_running_tasks bit in the GCS get_all_job_info API."""
address_info = ray.init(address=call_ray_start)
gcs_aio_client = GcsAioClient(
address=address_info["gcs_address"], nums_reconnect_retry=0
)
@ray.remote
def sleep_forever():
while True:
time.sleep(1)
object_ref = sleep_forever.remote()
async def check_is_running_tasks(job_id, expected_is_running_tasks):
"""Return True if the driver indicated by job_id is currently running tasks."""
found = False
for job_table_entry in (await gcs_aio_client.get_all_job_info()).values():
if job_table_entry.job_id.hex() == job_id:
found = True
return job_table_entry.is_running_tasks == expected_is_running_tasks
assert found
# Get the job id for this driver.
job_id = ray.get_runtime_context().get_job_id()
# Task should be running.
assert await check_is_running_tasks(job_id, True)
# Kill the task.
ray.cancel(object_ref)
# Task should not be running.
await async_wait_for_condition_async_predicate(
lambda: check_is_running_tasks(job_id, False), timeout=30
)
# Shutdown and start a new driver.
ray.shutdown()
ray.init(address=call_ray_start)
old_job_id = job_id
job_id = ray.get_runtime_context().get_job_id()
assert old_job_id != job_id
new_object_ref = sleep_forever.remote()
# Tasks should still not be running for the old driver.
assert await check_is_running_tasks(old_job_id, False)
# Task should be running for the new driver.
assert await check_is_running_tasks(job_id, True)
# Start an actor that will run forever.
@ray.remote
class Actor:
pass
actor = Actor.remote()
# Cancel the task.
ray.cancel(new_object_ref)
# The actor is still running, so is_running_tasks should be true.
assert await check_is_running_tasks(job_id, True)
# Kill the actor.
ray.kill(actor)
# The actor is no longer running, so is_running_tasks should be false.
await async_wait_for_condition_async_predicate(
lambda: check_is_running_tasks(job_id, False), timeout=30
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_ray_start",
["ray start --head"],
indirect=True,
)
async def test_job_supervisor_logs_saved(
call_ray_start, tmp_path, capsys # noqa: F811
):
"""Test JobSupervisor logs are saved to jobs/supervisor-{submission_id}.log"""
address_info = ray.init(address=call_ray_start)
gcs_aio_client = GcsAioClient(
address=address_info["gcs_address"], nums_reconnect_retry=0
)
job_manager = JobManager(gcs_aio_client, tmp_path)
job_id = await job_manager.submit_job(
entrypoint="echo hello 1", submission_id="job_1"
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
# Verify logs saved to file
supervisor_log_path = os.path.join(
ray._private.worker._global_node.get_logs_dir_path(),
f"jobs/supervisor-{job_id}.log",
)
log_message = f"Job {job_id} entrypoint command exited with code 0"
with open(supervisor_log_path, "r") as f:
logs = f.read()
assert log_message in logs
# Verify logs in stderr. Run in wait_for_condition to ensure
# logs are flushed
wait_for_condition(lambda: log_message in capsys.readouterr().err)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_ray_start",
["ray start --head"],
indirect=True,
)
async def test_runtime_env_setup_logged_to_job_driver_logs(
call_ray_start, tmp_path # noqa: F811
):
"""Test runtime env setup messages are logged to jobs driver log"""
address_info = ray.init(address=call_ray_start)
gcs_aio_client = GcsAioClient(
address=address_info["gcs_address"], nums_reconnect_retry=0
)
job_manager = JobManager(gcs_aio_client, tmp_path)
job_id = await job_manager.submit_job(
entrypoint="echo hello 1", submission_id="test_runtime_env_setup_logs"
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
# Verify logs saved to file
job_driver_log_path = os.path.join(
ray._private.worker._global_node.get_logs_dir_path(),
f"job-driver-{job_id}.log",
)
start_message = "Runtime env is setting up."
with open(job_driver_log_path, "r") as f:
logs = f.read()
assert start_message in logs
@pytest.fixture(scope="module")
def shared_ray_instance():
# Remove ray address for test ray cluster in case we have
# lingering RAY_ADDRESS="http://127.0.0.1:8265" from previous local job
# submissions.
old_ray_address = os.environ.pop(RAY_ADDRESS_ENVIRONMENT_VARIABLE, None)
yield create_ray_cluster()
if old_ray_address is not None:
os.environ[RAY_ADDRESS_ENVIRONMENT_VARIABLE] = old_ray_address
@pytest.fixture
def job_manager(shared_ray_instance, tmp_path):
yield create_job_manager(shared_ray_instance, tmp_path)
async def _run_hanging_command(job_manager, tmp_dir, start_signal_actor=None):
tmp_file = os.path.join(tmp_dir, "hello")
pid_file = os.path.join(tmp_dir, "pid")
# Write subprocess pid to pid_file and block until tmp_file is present.
wait_for_file_cmd = (
f"echo $$ > {pid_file} && "
f"until [ -f {tmp_file} ]; "
"do echo 'Waiting...' && sleep 1; "
"done"
)
job_id = await job_manager.submit_job(
entrypoint=wait_for_file_cmd, _start_signal_actor=start_signal_actor
)
status = await job_manager.get_job_status(job_id)
if start_signal_actor:
for _ in range(10):
assert status == JobStatus.PENDING
await asyncio.sleep(0.01)
else:
await async_wait_for_condition_async_predicate(
check_job_running, job_manager=job_manager, job_id=job_id
)
await async_wait_for_condition(
lambda: "Waiting..." in job_manager.get_job_logs(job_id)
)
return pid_file, tmp_file, job_id
async def check_job_succeeded(job_manager, job_id):
data = await job_manager.get_job_info(job_id)
status = data.status
if status == JobStatus.FAILED:
raise RuntimeError(f"Job failed! {data.message}")
assert status in {JobStatus.PENDING, JobStatus.RUNNING, JobStatus.SUCCEEDED}
if status == JobStatus.SUCCEEDED:
assert data.driver_exit_code == 0
else:
assert data.driver_exit_code is None
return status == JobStatus.SUCCEEDED
async def check_job_failed(job_manager, job_id):
status = await job_manager.get_job_status(job_id)
assert status in {JobStatus.PENDING, JobStatus.RUNNING, JobStatus.FAILED}
return status == JobStatus.FAILED
async def check_job_stopped(job_manager, job_id):
status = await job_manager.get_job_status(job_id)
data = await job_manager.get_job_info(job_id)
assert status in {JobStatus.PENDING, JobStatus.RUNNING, JobStatus.STOPPED}
assert data.driver_exit_code is None
return status == JobStatus.STOPPED
async def check_job_running(job_manager, job_id):
status = await job_manager.get_job_status(job_id)
data = await job_manager.get_job_info(job_id)
assert status in {JobStatus.PENDING, JobStatus.RUNNING}
assert data.driver_exit_code is None
return status == JobStatus.RUNNING
def check_subprocess_cleaned(pid):
return psutil.pid_exists(pid) is False
def test_generate_job_id():
ids = set()
for _ in range(10000):
new_id = generate_job_id()
assert new_id.startswith("raysubmit_")
assert new_id.count("_") == 1
assert "-" not in new_id
assert "/" not in new_id
ids.add(new_id)
assert len(ids) == 10000
# NOTE(architkulkarni): This test must be run first in order for the job
# submission history of the shared Ray runtime to be empty.
@pytest.mark.asyncio
async def test_list_jobs_empty(job_manager: JobManager):
assert await job_manager.list_jobs() == dict()
@pytest.mark.asyncio
async def test_list_jobs(job_manager: JobManager):
await job_manager.submit_job(entrypoint="echo hi", submission_id="1")
runtime_env = {"env_vars": {"TEST": "123"}}
metadata = {"foo": "bar"}
await job_manager.submit_job(
entrypoint="echo hello",
submission_id="2",
runtime_env=runtime_env,
metadata=metadata,
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id="1"
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id="2"
)
jobs_info = await job_manager.list_jobs()
assert "1" in jobs_info
assert jobs_info["1"].status == JobStatus.SUCCEEDED
assert "2" in jobs_info
assert jobs_info["2"].status == JobStatus.SUCCEEDED
assert jobs_info["2"].message is not None
assert jobs_info["2"].end_time >= jobs_info["2"].start_time
assert jobs_info["2"].runtime_env == runtime_env
assert jobs_info["2"].metadata == metadata
@pytest.mark.asyncio
async def test_pass_job_id(job_manager):
submission_id = "my_custom_id"
returned_id = await job_manager.submit_job(
entrypoint="echo hello", submission_id=submission_id
)
assert returned_id == submission_id
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=submission_id
)
# Check that the same job_id is rejected.
with pytest.raises(ValueError):
await job_manager.submit_job(
entrypoint="echo hello", submission_id=submission_id
)
@pytest.mark.asyncio
async def test_simultaneous_submit_job(job_manager):
"""Test that we can submit multiple jobs at once."""
job_ids = await asyncio.gather(
job_manager.submit_job(entrypoint="echo hello"),
job_manager.submit_job(entrypoint="echo hello"),
job_manager.submit_job(entrypoint="echo hello"),
)
for job_id in job_ids:
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
@pytest.mark.asyncio
async def test_simultaneous_with_same_id(job_manager):
"""Test that we can submit multiple jobs at once with the same id.
The second job should raise a friendly error.
"""
with pytest.raises(ValueError) as excinfo:
await asyncio.gather(
job_manager.submit_job(entrypoint="echo hello", submission_id="1"),
job_manager.submit_job(entrypoint="echo hello", submission_id="1"),
)
assert "Job with submission_id 1 already exists" in str(excinfo.value)
# Check that the (first) job can still succeed.
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id="1"
)
@pytest.mark.asyncio
class TestShellScriptExecution:
async def test_submit_basic_echo(self, job_manager):
job_id = await job_manager.submit_job(entrypoint="echo hello")
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert "hello\n" in job_manager.get_job_logs(job_id)
async def test_submit_stderr(self, job_manager):
job_id = await job_manager.submit_job(entrypoint="echo error 1>&2")
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert "error\n" in job_manager.get_job_logs(job_id)
async def test_submit_ls_grep(self, job_manager):
grep_cmd = f"ls {os.path.dirname(__file__)} | grep test_job_manager.py"
job_id = await job_manager.submit_job(entrypoint=grep_cmd)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert "test_job_manager.py\n" in job_manager.get_job_logs(job_id)
async def test_subprocess_exception(self, job_manager):
"""
Run a python script with exception, ensure:
1) Job status is marked as failed
2) Job manager can surface exception message back to logs api
3) Job no hanging job supervisor actor
4) Empty logs
"""
run_cmd = f"python {_driver_script_path('script_with_exception.py')}"
job_id = await job_manager.submit_job(entrypoint=run_cmd)
async def cleaned_up():
data = await job_manager.get_job_info(job_id)
if data.status != JobStatus.FAILED:
return False
if "Exception: Script failed with exception !" not in data.message:
return False
return job_manager._get_actor_for_job(job_id) is None
await async_wait_for_condition_async_predicate(cleaned_up)
async def test_submit_with_s3_runtime_env(self, job_manager):
job_id = await job_manager.submit_job(
entrypoint="python script.py",
runtime_env={"working_dir": "s3://runtime-env-test/script_runtime_env.zip"},
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert "Executing main() from script.py !!\n" in job_manager.get_job_logs(
job_id
)
async def test_submit_with_file_runtime_env(self, job_manager):
with tempfile.NamedTemporaryFile(suffix=".zip") as f:
filename, _ = urllib.request.urlretrieve(
"https://runtime-env-test.s3.amazonaws.com/script_runtime_env.zip",
filename=f.name,
)
job_id = await job_manager.submit_job(
entrypoint="python script.py",
runtime_env={"working_dir": "file://" + filename},
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert "Executing main() from script.py !!\n" in job_manager.get_job_logs(
job_id
)
@pytest.mark.asyncio
class TestRuntimeEnv:
async def test_pass_env_var(self, job_manager):
"""Test we can pass env vars in the subprocess that executes job's
driver script.
"""
job_id = await job_manager.submit_job(
entrypoint="echo $TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR",
runtime_env={"env_vars": {"TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR": "233"}},
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert "233\n" in job_manager.get_job_logs(job_id)
async def test_niceness(self, job_manager):
job_id = await job_manager.submit_job(
entrypoint=f"python {_driver_script_path('check_niceness.py')}",
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
logs = job_manager.get_job_logs(job_id)
assert "driver 0" in logs
assert "worker 15" in logs
async def test_multiple_runtime_envs(self, job_manager):
# Test that you can run two jobs in different envs without conflict.
job_id_1 = await job_manager.submit_job(
entrypoint=f"python {_driver_script_path('print_runtime_env.py')}",
runtime_env={
"env_vars": {"TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR": "JOB_1_VAR"}
},
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id_1
)
logs = job_manager.get_job_logs(job_id_1)
assert "'TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR': 'JOB_1_VAR'" in logs
job_id_2 = await job_manager.submit_job(
entrypoint=f"python {_driver_script_path('print_runtime_env.py')}",
runtime_env={
"env_vars": {"TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR": "JOB_2_VAR"}
},
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id_2
)
logs = job_manager.get_job_logs(job_id_2)
assert "'TEST_SUBPROCESS_JOB_CONFIG_ENV_VAR': 'JOB_2_VAR'" in logs
async def test_failed_runtime_env_validation(self, job_manager):
"""Ensure job status is correctly set as failed if job has an invalid
runtime_env.
"""
run_cmd = f"python {_driver_script_path('override_env_var.py')}"
job_id = await job_manager.submit_job(
entrypoint=run_cmd, runtime_env={"working_dir": "path_not_exist"}
)
data = await job_manager.get_job_info(job_id)
assert data.status == JobStatus.FAILED
assert "path_not_exist is not a valid URI" in data.message
assert data.driver_exit_code is None
async def test_failed_runtime_env_setup(self, job_manager):
"""Ensure job status is correctly set as failed if job has a valid
runtime_env that fails to be set up.
"""
run_cmd = f"python {_driver_script_path('override_env_var.py')}"
job_id = await job_manager.submit_job(
entrypoint=run_cmd, runtime_env={"working_dir": "s3://does_not_exist.zip"}
)
await async_wait_for_condition_async_predicate(
check_job_failed, job_manager=job_manager, job_id=job_id
)
data = await job_manager.get_job_info(job_id)
assert "runtime_env setup failed" in data.message
assert data.driver_exit_code is None
log_path = JobLogStorageClient().get_log_file_path(job_id=job_id)
with open(log_path, "r") as f:
job_logs = f.read()
assert "Traceback (most recent call last):" in job_logs
async def test_pass_metadata(self, job_manager):
def dict_to_str(d):
return str(dict(sorted(d.items())))
print_metadata_cmd = (
'python -c"'
"import ray;"
"ray.init();"
"job_config=ray._private.worker.global_worker.core_worker.get_job_config();"
"print(dict(sorted(job_config.metadata.items())))"
'"'
)
# Check that we default to only the job ID and job name.
job_id = await job_manager.submit_job(entrypoint=print_metadata_cmd)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert dict_to_str(
{JOB_NAME_METADATA_KEY: job_id, JOB_ID_METADATA_KEY: job_id}
) in job_manager.get_job_logs(job_id)
# Check that we can pass custom metadata.
job_id = await job_manager.submit_job(
entrypoint=print_metadata_cmd, metadata={"key1": "val1", "key2": "val2"}
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert dict_to_str(
{
JOB_NAME_METADATA_KEY: job_id,
JOB_ID_METADATA_KEY: job_id,
"key1": "val1",
"key2": "val2",
}
) in job_manager.get_job_logs(job_id)
# Check that we can override job name.
job_id = await job_manager.submit_job(
entrypoint=print_metadata_cmd,
metadata={JOB_NAME_METADATA_KEY: "custom_name"},
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert dict_to_str(
{JOB_NAME_METADATA_KEY: "custom_name", JOB_ID_METADATA_KEY: job_id}
) in job_manager.get_job_logs(job_id)
@pytest.mark.parametrize(
"env_vars",
[None, {}, {"hello": "world"}],
)
@pytest.mark.parametrize(
"resource_kwarg",
[
{},
{"entrypoint_num_cpus": 1},
{"entrypoint_num_gpus": 1},
{"entrypoint_memory": 4},
{"entrypoint_resources": {"Custom": 1}},
],
)
async def test_cuda_visible_devices(self, job_manager, resource_kwarg, env_vars):
"""Check CUDA_VISIBLE_DEVICES behavior introduced in #24546.
Should not be set in the driver, but should be set in tasks.
We test a variety of `env_vars` parameters due to custom parsing logic
that caused https://github.com/ray-project/ray/issues/25086.
If the user specifies a resource, we should not use the CUDA_VISIBLE_DEVICES
logic. Instead, the behavior should match that of the user specifying
resources for any other actor. So CUDA_VISIBLE_DEVICES should be set in the
driver and tasks.
"""
run_cmd = f"python {_driver_script_path('check_cuda_devices.py')}"
runtime_env = {"env_vars": env_vars}
if resource_kwarg:
run_cmd = "RAY_TEST_RESOURCES_SPECIFIED=1 " + run_cmd
job_id = await job_manager.submit_job(
entrypoint=run_cmd,
runtime_env=runtime_env,
**resource_kwarg,
)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
@pytest.mark.asyncio
class TestAsyncAPI:
async def test_status_and_logs_while_blocking(self, job_manager):
with tempfile.TemporaryDirectory() as tmp_dir:
pid_file, tmp_file, job_id = await _run_hanging_command(
job_manager, tmp_dir
)
with open(pid_file, "r") as file:
pid = int(file.read())
assert psutil.pid_exists(pid), "driver subprocess should be running"
# Signal the job to exit by writing to the file.
with open(tmp_file, "w") as f:
print("hello", file=f)
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
# Ensure driver subprocess gets cleaned up after job reached
# termination state
await async_wait_for_condition(check_subprocess_cleaned, pid=pid)
async def test_stop_job(self, job_manager):
with tempfile.TemporaryDirectory() as tmp_dir:
_, _, job_id = await _run_hanging_command(job_manager, tmp_dir)
assert job_manager.stop_job(job_id) is True
await async_wait_for_condition_async_predicate(
check_job_stopped, job_manager=job_manager, job_id=job_id
)
# Assert re-stopping a stopped job also returns False
await async_wait_for_condition(
lambda: job_manager.stop_job(job_id) is False
)
# Assert stopping non-existent job returns False
assert job_manager.stop_job(str(uuid4())) is False
async def test_kill_job_actor_in_before_driver_finish(self, job_manager):
"""
Test submitting a long running / blocker driver script, and kill
the job supervisor actor before script returns and ensure
1) Job status is correctly marked as failed
2) No hanging subprocess from failed job
"""
with tempfile.TemporaryDirectory() as tmp_dir:
pid_file, _, job_id = await _run_hanging_command(job_manager, tmp_dir)
with open(pid_file, "r") as file:
pid = int(file.read())
assert psutil.pid_exists(pid), "driver subprocess should be running"
actor = job_manager._get_actor_for_job(job_id)
ray.kill(actor, no_restart=True)
await async_wait_for_condition_async_predicate(
check_job_failed, job_manager=job_manager, job_id=job_id
)
data = await job_manager.get_job_info(job_id)
assert data.driver_exit_code is None
# Ensure driver subprocess gets cleaned up after job reached
# termination state
await async_wait_for_condition(check_subprocess_cleaned, pid=pid)
async def test_stop_job_in_pending(self, job_manager):
"""
Kick off a job that is in PENDING state, stop the job and ensure
1) Job can correctly be stop immediately with correct JobStatus
2) No dangling subprocess left.
"""
start_signal_actor = SignalActor.remote()
with tempfile.TemporaryDirectory() as tmp_dir:
pid_file, _, job_id = await _run_hanging_command(
job_manager, tmp_dir, start_signal_actor=start_signal_actor
)
assert not os.path.exists(pid_file), (
"driver subprocess should NOT be running while job is " "still PENDING."
)
assert job_manager.stop_job(job_id) is True
# Send run signal to unblock run function
ray.get(start_signal_actor.send.remote())
await async_wait_for_condition_async_predicate(
check_job_stopped, job_manager=job_manager, job_id=job_id
)
async def test_kill_job_actor_in_pending(self, job_manager):
"""
Kick off a job that is in PENDING state, kill the job actor and ensure
1) Job can correctly be stop immediately with correct JobStatus
2) No dangling subprocess left.
"""
start_signal_actor = SignalActor.remote()
with tempfile.TemporaryDirectory() as tmp_dir:
pid_file, _, job_id = await _run_hanging_command(
job_manager, tmp_dir, start_signal_actor=start_signal_actor
)
assert not os.path.exists(pid_file), (
"driver subprocess should NOT be running while job is " "still PENDING."
)
actor = job_manager._get_actor_for_job(job_id)
ray.kill(actor, no_restart=True)
await async_wait_for_condition_async_predicate(
check_job_failed, job_manager=job_manager, job_id=job_id
)
data = await job_manager.get_job_info(job_id)
assert data.driver_exit_code is None
async def test_stop_job_subprocess_cleanup_upon_stop(self, job_manager):
"""
Ensure driver scripts' subprocess is cleaned up properly when we
stopped a running job.
SIGTERM first, SIGKILL after 3 seconds.
"""
with tempfile.TemporaryDirectory() as tmp_dir:
pid_file, _, job_id = await _run_hanging_command(job_manager, tmp_dir)
with open(pid_file, "r") as file:
pid = int(file.read())
assert psutil.pid_exists(pid), "driver subprocess should be running"
assert job_manager.stop_job(job_id) is True
await async_wait_for_condition_async_predicate(
check_job_stopped, job_manager=job_manager, job_id=job_id
)
# Ensure driver subprocess gets cleaned up after job reached
# termination state
await async_wait_for_condition(check_subprocess_cleaned, pid=pid)
@pytest.mark.asyncio
class TestTailLogs:
async def _tail_and_assert_logs(
self, job_id, job_manager, expected_log="", num_iteration=5
):
i = 0
async for lines in job_manager.tail_job_logs(job_id):
assert all(
s == expected_log or "Runtime env" in s
for s in lines.strip().split("\n")
)
print(lines, end="")
if i == num_iteration:
break
i += 1
async def test_unknown_job(self, job_manager):
with pytest.raises(RuntimeError, match="Job 'unknown' does not exist."):
async for _ in job_manager.tail_job_logs("unknown"):
pass
async def test_successful_job(self, job_manager):
"""Test tailing logs for a PENDING -> RUNNING -> SUCCESSFUL job."""
start_signal_actor = SignalActor.remote()
with tempfile.TemporaryDirectory() as tmp_dir:
_, tmp_file, job_id = await _run_hanging_command(
job_manager, tmp_dir, start_signal_actor=start_signal_actor
)
# TODO(edoakes): check we get no logs before actor starts (not sure
# how to timeout the iterator call).
job_status = await job_manager.get_job_status(job_id)
assert job_status == JobStatus.PENDING
# Signal job to start.
ray.get(start_signal_actor.send.remote())
await self._tail_and_assert_logs(
job_id, job_manager, expected_log="Waiting...", num_iteration=5
)
# Signal the job to exit by writing to the file.
with open(tmp_file, "w") as f:
print("hello", file=f)
async for lines in job_manager.tail_job_logs(job_id):
assert all(
s == "Waiting..." or "Runtime env" in s
for s in lines.strip().split("\n")
)
print(lines, end="")
await async_wait_for_condition_async_predicate(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
async def test_failed_job(self, job_manager):
"""Test tailing logs for a job that unexpectedly exits."""
with tempfile.TemporaryDirectory() as tmp_dir:
pid_file, _, job_id = await _run_hanging_command(job_manager, tmp_dir)
await self._tail_and_assert_logs(
job_id, job_manager, expected_log="Waiting...", num_iteration=5
)
# Kill the job unexpectedly.
with open(pid_file, "r") as f:
os.kill(int(f.read()), signal.SIGKILL)
async for lines in job_manager.tail_job_logs(job_id):
assert all(
s == "Waiting..." or "Runtime env" in s
for s in lines.strip().split("\n")
)
print(lines, end="")
await async_wait_for_condition_async_predicate(