forked from ray-project/ray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utils.py
1962 lines (1628 loc) · 62.4 KB
/
test_utils.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
from datetime import datetime
import fnmatch
import functools
import io
import json
import logging
import math
import os
import pathlib
import socket
import subprocess
import sys
import tempfile
import time
import timeit
import traceback
from collections import defaultdict
from contextlib import contextmanager, redirect_stderr, redirect_stdout
from typing import Any, Callable, Dict, List, Optional
import uuid
from dataclasses import dataclass
import requests
from ray._raylet import Config
import numpy as np
import psutil # We must import psutil after ray because we bundle it with ray.
from ray._private import (
ray_constants,
)
from ray._private.worker import RayContext
import yaml
import ray
import ray._private.gcs_utils as gcs_utils
import ray._private.memory_monitor as memory_monitor
import ray._private.services
import ray._private.utils
from ray._private.internal_api import memory_summary
from ray._private.tls_utils import generate_self_signed_tls_certs
from ray._raylet import GcsClientOptions, GlobalStateAccessor
from ray.core.generated import (
gcs_pb2,
node_manager_pb2,
gcs_service_pb2,
)
from ray.util.queue import Empty, Queue, _QueueActor
from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy
logger = logging.getLogger(__name__)
EXE_SUFFIX = ".exe" if sys.platform == "win32" else ""
RAY_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
REDIS_EXECUTABLE = os.path.join(
RAY_PATH, "core/src/ray/thirdparty/redis/src/redis-server" + EXE_SUFFIX
)
try:
from prometheus_client.parser import text_string_to_metric_families, Sample
except (ImportError, ModuleNotFoundError):
Sample = None
def text_string_to_metric_families(*args, **kwargs):
raise ModuleNotFoundError("`prometheus_client` not found")
class RayTestTimeoutException(Exception):
"""Exception used to identify timeouts from test utilities."""
pass
def make_global_state_accessor(ray_context):
gcs_options = GcsClientOptions.from_gcs_address(
ray_context.address_info["gcs_address"]
)
global_state_accessor = GlobalStateAccessor(gcs_options)
global_state_accessor.connect()
return global_state_accessor
def enable_external_redis():
import os
return os.environ.get("TEST_EXTERNAL_REDIS") == "1"
def redis_replicas():
import os
return int(os.environ.get("TEST_EXTERNAL_REDIS_REPLICAS", "1"))
def get_redis_cli(port, enable_tls):
try:
# If there is no redis libs installed, skip the check.
# This could happen In minimal test, where we don't have
# redis.
import redis
except Exception:
return True
params = {}
if enable_tls:
from ray._raylet import Config
params = {"ssl": True, "ssl_cert_reqs": "required"}
if Config.REDIS_CA_CERT():
params["ssl_ca_certs"] = Config.REDIS_CA_CERT()
if Config.REDIS_CLIENT_CERT():
params["ssl_certfile"] = Config.REDIS_CLIENT_CERT()
if Config.REDIS_CLIENT_KEY():
params["ssl_keyfile"] = Config.REDIS_CLIENT_KEY()
return redis.Redis("localhost", str(port), **params)
def start_redis_instance(
session_dir_path: str,
port: int,
redis_max_clients: Optional[int] = None,
num_retries: int = 20,
stdout_file: Optional[str] = None,
stderr_file: Optional[str] = None,
password: Optional[str] = None,
redis_max_memory: Optional[int] = None,
fate_share: Optional[bool] = None,
port_denylist: Optional[List[int]] = None,
listen_to_localhost_only: bool = False,
enable_tls: bool = False,
replica_of=None,
leader_id=None,
db_dir=None,
free_port=0,
):
"""Start a single Redis server.
Notes:
We will initially try to start the Redis instance at the given port,
and then try at most `num_retries - 1` times to start the Redis
instance at successive random ports.
Args:
session_dir_path: Path to the session directory of
this Ray cluster.
port: Try to start a Redis server at this port.
redis_max_clients: If this is provided, Ray will attempt to configure
Redis with this maxclients number.
num_retries: The number of times to attempt to start Redis at
successive ports.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should happen, then this should be None.
stderr_file: A file handle opened for writing to redirect stderr to. If
no redirection should happen, then this should be None.
password: Prevents external clients without the password
from connecting to Redis if provided.
redis_max_memory: The max amount of memory (in bytes) to allow redis
to use, or None for no limit. Once the limit is exceeded, redis
will start LRU eviction of entries.
port_denylist: A set of denylist ports that shouldn't
be used when allocating a new port.
listen_to_localhost_only: Redis server only listens to
localhost (127.0.0.1) if it's true,
otherwise it listens to all network interfaces.
enable_tls: Enable the TLS/SSL in Redis or not
Returns:
A tuple of the port used by Redis and ProcessInfo for the process that
was started. If a port is passed in, then the returned port value
is the same.
Raises:
Exception: An exception is raised if Redis could not be started.
"""
assert os.path.isfile(REDIS_EXECUTABLE)
# Construct the command to start the Redis server.
command = [REDIS_EXECUTABLE]
if password:
if " " in password:
raise ValueError("Spaces not permitted in redis password.")
command += ["--requirepass", password]
if redis_replicas() > 1:
command += ["--cluster-enabled", "yes", "--cluster-config-file", f"node-{port}"]
if enable_tls:
command += [
"--tls-port",
str(port),
"--loglevel",
"warning",
"--port",
str(free_port),
]
else:
command += ["--port", str(port), "--loglevel", "warning"]
if listen_to_localhost_only:
command += ["--bind", "127.0.0.1"]
pidfile = os.path.join(session_dir_path, "redis-" + uuid.uuid4().hex + ".pid")
command += ["--pidfile", pidfile]
if enable_tls:
if Config.REDIS_CA_CERT():
command += ["--tls-ca-cert-file", Config.REDIS_CA_CERT()]
if Config.REDIS_CLIENT_CERT():
command += ["--tls-cert-file", Config.REDIS_CLIENT_CERT()]
if Config.REDIS_CLIENT_KEY():
command += ["--tls-key-file", Config.REDIS_CLIENT_KEY()]
if replica_of is not None:
command += ["--tls-replication", "yes"]
command += ["--tls-auth-clients", "no", "--tls-cluster", "yes"]
if sys.platform != "win32":
command += ["--save", "", "--appendonly", "no"]
if db_dir is not None:
command += ["--dir", str(db_dir)]
process_info = ray._private.services.start_ray_process(
command,
ray_constants.PROCESS_TYPE_REDIS_SERVER,
stdout_file=stdout_file,
stderr_file=stderr_file,
fate_share=fate_share,
)
node_id = None
if redis_replicas() > 1:
# Setup redis cluster
import redis
while True:
try:
redis_cli = get_redis_cli(port, enable_tls)
if replica_of is None:
slots = [str(i) for i in range(16384)]
redis_cli.cluster("addslots", *slots)
else:
print(redis_cli.cluster("meet", "127.0.0.1", str(replica_of)))
print(redis_cli.cluster("replicate", leader_id))
node_id = redis_cli.cluster("myid")
break
except (
redis.exceptions.ConnectionError,
redis.exceptions.ResponseError,
) as e:
from time import sleep
print(f"Waiting for redis to be up {e} ")
sleep(0.1)
return node_id, process_info
def _pid_alive(pid):
"""Check if the process with this PID is alive or not.
Args:
pid: The pid to check.
Returns:
This returns false if the process is dead. Otherwise, it returns true.
"""
alive = True
try:
proc = psutil.Process(pid)
if proc.status() == psutil.STATUS_ZOMBIE:
alive = False
except psutil.NoSuchProcess:
alive = False
return alive
def check_call_module(main, argv, capture_stdout=False, capture_stderr=False):
# We use this function instead of calling the "ray" command to work around
# some deadlocks that occur when piping ray's output on Windows
stream = io.TextIOWrapper(io.BytesIO(), encoding=sys.stdout.encoding)
old_argv = sys.argv[:]
try:
sys.argv = argv[:]
try:
with redirect_stderr(stream if capture_stderr else sys.stderr):
with redirect_stdout(stream if capture_stdout else sys.stdout):
main()
finally:
stream.flush()
except SystemExit as ex:
if ex.code:
output = stream.buffer.getvalue()
raise subprocess.CalledProcessError(ex.code, argv, output)
except Exception as ex:
output = stream.buffer.getvalue()
raise subprocess.CalledProcessError(1, argv, output, ex.args[0])
finally:
sys.argv = old_argv
if capture_stdout:
sys.stdout.buffer.write(stream.buffer.getvalue())
elif capture_stderr:
sys.stderr.buffer.write(stream.buffer.getvalue())
return stream.buffer.getvalue()
def check_call_subprocess(argv, capture_stdout=False, capture_stderr=False):
# We use this function instead of calling the "ray" command to work around
# some deadlocks that occur when piping ray's output on Windows
from ray.scripts.scripts import main as ray_main
if sys.platform == "win32":
result = check_call_module(
ray_main, argv, capture_stdout=capture_stdout, capture_stderr=capture_stderr
)
else:
stdout_redir = None
stderr_redir = None
if capture_stdout:
stdout_redir = subprocess.PIPE
if capture_stderr and capture_stdout:
stderr_redir = subprocess.STDOUT
elif capture_stderr:
stderr_redir = subprocess.PIPE
proc = subprocess.Popen(argv, stdout=stdout_redir, stderr=stderr_redir)
(stdout, stderr) = proc.communicate()
if proc.returncode:
raise subprocess.CalledProcessError(proc.returncode, argv, stdout, stderr)
result = b"".join([s for s in [stdout, stderr] if s is not None])
return result
def check_call_ray(args, capture_stdout=False, capture_stderr=False):
check_call_subprocess(["ray"] + args, capture_stdout, capture_stderr)
def wait_for_pid_to_exit(pid, timeout=20):
start_time = time.time()
while time.time() - start_time < timeout:
if not _pid_alive(pid):
return
time.sleep(0.1)
raise RayTestTimeoutException(f"Timed out while waiting for process {pid} to exit.")
def wait_for_children_names_of_pid(pid, children_names, timeout=20):
p = psutil.Process(pid)
start_time = time.time()
children_names = set(children_names)
not_found_children = []
children = []
while time.time() - start_time < timeout:
children = p.children(recursive=False)
not_found_children = set(children_names) - {c.name() for c in children}
if len(not_found_children) == 0:
return
time.sleep(0.1)
raise RayTestTimeoutException(
"Timed out while waiting for process {} children to start "
"({} not found from children {}).".format(pid, not_found_children, children)
)
def wait_for_children_of_pid(pid, num_children=1, timeout=20):
p = psutil.Process(pid)
start_time = time.time()
alive = []
while time.time() - start_time < timeout:
alive = p.children(recursive=False)
num_alive = len(alive)
if num_alive >= num_children:
return
time.sleep(0.1)
raise RayTestTimeoutException(
f"Timed out while waiting for process {pid} children to start "
f"({num_alive}/{num_children} started: {alive})."
)
def wait_for_children_of_pid_to_exit(pid, timeout=20):
children = psutil.Process(pid).children()
if len(children) == 0:
return
_, alive = psutil.wait_procs(children, timeout=timeout)
if len(alive) > 0:
raise RayTestTimeoutException(
"Timed out while waiting for process children to exit."
" Children still alive: {}.".format([p.name() for p in alive])
)
def kill_process_by_name(name, SIGKILL=False):
for p in psutil.process_iter(attrs=["name"]):
if p.info["name"] == name + ray._private.services.EXE_SUFFIX:
if SIGKILL:
p.kill()
else:
p.terminate()
def run_string_as_driver(driver_script: str, env: Dict = None, encode: str = "utf-8"):
"""Run a driver as a separate process.
Args:
driver_script: A string to run as a Python script.
env: The environment variables for the driver.
Returns:
The script's output.
"""
proc = subprocess.Popen(
[sys.executable, "-"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
)
with proc:
output = proc.communicate(driver_script.encode(encoding=encode))[0]
if proc.returncode:
print(ray._private.utils.decode(output, encode_type=encode))
raise subprocess.CalledProcessError(
proc.returncode, proc.args, output, proc.stderr
)
out = ray._private.utils.decode(output, encode_type=encode)
return out
def run_string_as_driver_nonblocking(driver_script, env: Dict = None):
"""Start a driver as a separate process and return immediately.
Args:
driver_script: A string to run as a Python script.
Returns:
A handle to the driver process.
"""
script = "; ".join(
[
"import sys",
"script = sys.stdin.read()",
"sys.stdin.close()",
"del sys",
'exec("del script\\n" + script)',
]
)
proc = subprocess.Popen(
[sys.executable, "-c", script],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
)
proc.stdin.write(driver_script.encode("ascii"))
proc.stdin.close()
return proc
def convert_actor_state(state):
if not state:
return None
return gcs_pb2.ActorTableData.ActorState.DESCRIPTOR.values_by_number[state].name
def wait_for_num_actors(num_actors, state=None, timeout=10):
state = convert_actor_state(state)
start_time = time.time()
while time.time() - start_time < timeout:
if (
len(
[
_
for _ in ray._private.state.actors().values()
if state is None or _["State"] == state
]
)
>= num_actors
):
return
time.sleep(0.1)
raise RayTestTimeoutException("Timed out while waiting for global state.")
def wait_for_num_nodes(num_nodes: int, timeout_s: int):
curr_nodes = 0
start = time.time()
next_feedback = start
max_time = start + timeout_s
while not curr_nodes >= num_nodes:
now = time.time()
if now >= max_time:
raise RuntimeError(
f"Maximum wait time reached, but only "
f"{curr_nodes}/{num_nodes} nodes came up. Aborting."
)
if now >= next_feedback:
passed = now - start
print(
f"Waiting for more nodes to come up: "
f"{curr_nodes}/{num_nodes} "
f"({passed:.0f} seconds passed)"
)
next_feedback = now + 10
time.sleep(5)
curr_nodes = len(ray.nodes())
passed = time.time() - start
print(
f"Cluster is up: {curr_nodes}/{num_nodes} nodes online after "
f"{passed:.0f} seconds"
)
def kill_actor_and_wait_for_failure(actor, timeout=10, retry_interval_ms=100):
actor_id = actor._actor_id.hex()
current_num_restarts = ray._private.state.actors(actor_id)["NumRestarts"]
ray.kill(actor)
start = time.time()
while time.time() - start <= timeout:
actor_status = ray._private.state.actors(actor_id)
if (
actor_status["State"] == convert_actor_state(gcs_utils.ActorTableData.DEAD)
or actor_status["NumRestarts"] > current_num_restarts
):
return
time.sleep(retry_interval_ms / 1000.0)
raise RuntimeError("It took too much time to kill an actor: {}".format(actor_id))
def wait_for_condition(
condition_predictor,
timeout=10,
retry_interval_ms=100,
raise_exceptions=False,
**kwargs: Any,
):
"""Wait until a condition is met or time out with an exception.
Args:
condition_predictor: A function that predicts the condition.
timeout: Maximum timeout in seconds.
retry_interval_ms: Retry interval in milliseconds.
raise_exceptions: If true, exceptions that occur while executing
condition_predictor won't be caught and instead will be raised.
Raises:
RuntimeError: If the condition is not met before the timeout expires.
"""
start = time.time()
last_ex = None
while time.time() - start <= timeout:
try:
if condition_predictor(**kwargs):
return
except Exception:
if raise_exceptions:
raise
last_ex = ray._private.utils.format_error_message(traceback.format_exc())
time.sleep(retry_interval_ms / 1000.0)
message = "The condition wasn't met before the timeout expired."
if last_ex is not None:
message += f" Last exception: {last_ex}"
raise RuntimeError(message)
async def async_wait_for_condition(
condition_predictor, timeout=10, retry_interval_ms=100, **kwargs: Any
):
"""Wait until a condition is met or time out with an exception.
Args:
condition_predictor: A function that predicts the condition.
timeout: Maximum timeout in seconds.
retry_interval_ms: Retry interval in milliseconds.
Raises:
RuntimeError: If the condition is not met before the timeout expires.
"""
start = time.time()
last_ex = None
while time.time() - start <= timeout:
try:
if condition_predictor(**kwargs):
return
except Exception as ex:
last_ex = ex
await asyncio.sleep(retry_interval_ms / 1000.0)
message = "The condition wasn't met before the timeout expired."
if last_ex is not None:
message += f" Last exception: {last_ex}"
raise RuntimeError(message)
async def async_wait_for_condition_async_predicate(
async_condition_predictor, timeout=10, retry_interval_ms=100, **kwargs: Any
):
"""Wait until a condition is met or time out with an exception.
Args:
condition_predictor: A function that predicts the condition.
timeout: Maximum timeout in seconds.
retry_interval_ms: Retry interval in milliseconds.
Raises:
RuntimeError: If the condition is not met before the timeout expires.
"""
start = time.time()
last_ex = None
while time.time() - start <= timeout:
try:
if await async_condition_predictor(**kwargs):
return
except Exception as ex:
last_ex = ex
await asyncio.sleep(retry_interval_ms / 1000.0)
message = "The condition wasn't met before the timeout expired."
if last_ex is not None:
message += f" Last exception: {last_ex}"
raise RuntimeError(message)
@dataclass
class MetricSamplePattern:
name: Optional[str] = None
value: Optional[str] = None
partial_label_match: Optional[Dict[str, str]] = None
def matches(self, sample: Sample):
if self.name is not None:
if self.name != sample.name:
return False
if self.value is not None:
if self.value != sample.value:
return False
if self.partial_label_match is not None:
for label, value in self.partial_label_match.items():
if sample.labels.get(label) != value:
return False
return True
def get_metric_check_condition(
metrics_to_check: List[MetricSamplePattern], export_addr: Optional[str] = None
) -> Callable[[], bool]:
"""A condition to check if a prometheus metrics reach a certain value.
This is a blocking check that can be passed into a `wait_for_condition`
style function.
Args:
metrics_to_check: A list of MetricSamplePattern. The fields that
aren't `None` will be matched.
Returns:
A function that returns True if all the metrics are emitted.
"""
node_info = ray.nodes()[0]
metrics_export_port = node_info["MetricsExportPort"]
addr = node_info["NodeManagerAddress"]
prom_addr = export_addr or f"{addr}:{metrics_export_port}"
def f():
for metric_pattern in metrics_to_check:
_, metric_names, metric_samples = fetch_prometheus([prom_addr])
for metric_sample in metric_samples:
if metric_pattern.matches(metric_sample):
break
else:
print(
f"Didn't find {metric_pattern}",
"all samples",
metric_samples,
)
return False
return True
return f
def wait_for_stdout(strings_to_match: List[str], timeout_s: int):
"""Returns a decorator which waits until the stdout emitted
by a function contains the provided list of strings.
Raises an exception if the stdout doesn't have the expected output in time.
Note: The decorated function should not block!
(It should return soon after being called.)
Args:
strings_to_match: Wait until stdout contains all of these string.
timeout_s: Max time to wait, in seconds, before raising a RuntimeError.
"""
def decorator(func):
@functools.wraps(func)
def decorated_func(*args, **kwargs):
success = False
try:
# Redirect stdout to an in-memory stream.
out_stream = io.StringIO()
sys.stdout = out_stream
# Execute the func. (Make sure the function doesn't block!)
out = func(*args, **kwargs)
# Check out_stream once a second until the timeout.
# Raise a RuntimeError if we timeout.
wait_for_condition(
# Does redirected stdout contain all of the expected strings?
lambda: all(
string in out_stream.getvalue() for string in strings_to_match
),
timeout=timeout_s,
retry_interval_ms=1000,
)
# out_stream has the expected strings
success = True
return out
# Exception raised on failure.
finally:
sys.stdout = sys.__stdout__
if success:
print("Confirmed expected function stdout. Stdout follows:")
else:
print("Did not confirm expected function stdout. Stdout follows:")
print(out_stream.getvalue())
out_stream.close()
return decorated_func
return decorator
def wait_until_succeeded_without_exception(
func, exceptions, *args, timeout_ms=1000, retry_interval_ms=100, raise_last_ex=False
):
"""A helper function that waits until a given function
completes without exceptions.
Args:
func: A function to run.
exceptions: Exceptions that are supposed to occur.
args: arguments to pass for a given func
timeout_ms: Maximum timeout in milliseconds.
retry_interval_ms: Retry interval in milliseconds.
raise_last_ex: Raise the last exception when timeout.
Return:
Whether exception occurs within a timeout.
"""
if type(exceptions) != tuple:
raise Exception("exceptions arguments should be given as a tuple")
time_elapsed = 0
start = time.time()
last_ex = None
while time_elapsed <= timeout_ms:
try:
func(*args)
return True
except exceptions as ex:
last_ex = ex
time_elapsed = (time.time() - start) * 1000
time.sleep(retry_interval_ms / 1000.0)
if raise_last_ex:
ex_stack = (
traceback.format_exception(type(last_ex), last_ex, last_ex.__traceback__)
if last_ex
else []
)
ex_stack = "".join(ex_stack)
raise Exception(f"Timed out while testing, {ex_stack}")
return False
def recursive_fnmatch(dirpath, pattern):
"""Looks at a file directory subtree for a filename pattern.
Similar to glob.glob(..., recursive=True) but also supports 2.7
"""
matches = []
for root, dirnames, filenames in os.walk(dirpath):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches
def generate_system_config_map(**kwargs):
ray_kwargs = {
"_system_config": kwargs,
}
return ray_kwargs
@ray.remote(num_cpus=0)
class SignalActor:
def __init__(self):
self.ready_event = asyncio.Event()
self.num_waiters = 0
def send(self, clear=False):
self.ready_event.set()
if clear:
self.ready_event.clear()
async def wait(self, should_wait=True):
if should_wait:
self.num_waiters += 1
await self.ready_event.wait()
self.num_waiters -= 1
async def cur_num_waiters(self):
return self.num_waiters
@ray.remote(num_cpus=0)
class Semaphore:
def __init__(self, value=1):
self._sema = asyncio.Semaphore(value=value)
async def acquire(self):
await self._sema.acquire()
async def release(self):
self._sema.release()
async def locked(self):
return self._sema.locked()
def dicts_equal(dict1, dict2, abs_tol=1e-4):
"""Compares to dicts whose values may be floating point numbers."""
if dict1.keys() != dict2.keys():
return False
for k, v in dict1.items():
if (
isinstance(v, float)
and isinstance(dict2[k], float)
and math.isclose(v, dict2[k], abs_tol=abs_tol)
):
continue
if v != dict2[k]:
return False
return True
def same_elements(elems_a, elems_b):
"""Checks if two iterables (such as lists) contain the same elements. Elements
do not have to be hashable (this allows us to compare sets of dicts for
example). This comparison is not necessarily efficient.
"""
a = list(elems_a)
b = list(elems_b)
for x in a:
if x not in b:
return False
for x in b:
if x not in a:
return False
return True
@ray.remote
def _put(obj):
return obj
def put_object(obj, use_ray_put):
if use_ray_put:
return ray.put(obj)
else:
return _put.remote(obj)
def wait_until_server_available(address, timeout_ms=5000, retry_interval_ms=100):
ip_port = address.split(":")
ip = ip_port[0]
port = int(ip_port[1])
time_elapsed = 0
start = time.time()
while time_elapsed <= timeout_ms:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((ip, port))
except Exception:
time_elapsed = (time.time() - start) * 1000
time.sleep(retry_interval_ms / 1000.0)
s.close()
continue
s.close()
return True
return False
def get_other_nodes(cluster, exclude_head=False):
"""Get all nodes except the one that we're connected to."""
return [
node
for node in cluster.list_all_nodes()
if node._raylet_socket_name
!= ray._private.worker._global_node._raylet_socket_name
and (exclude_head is False or node.head is False)
]
def get_non_head_nodes(cluster):
"""Get all non-head nodes."""
return list(filter(lambda x: x.head is False, cluster.list_all_nodes()))
def init_error_pubsub():
"""Initialize error info pub/sub"""
s = ray._raylet.GcsErrorSubscriber(
address=ray._private.worker.global_worker.gcs_client.address
)
s.subscribe()
return s
def get_error_message(subscriber, num=1e6, error_type=None, timeout=20):
"""Gets errors from GCS subscriber.
Returns maximum `num` error strings within `timeout`.
Only returns errors of `error_type` if specified.
"""
deadline = time.time() + timeout
msgs = []
while time.time() < deadline and len(msgs) < num:
_, error_data = subscriber.poll(timeout=deadline - time.time())
if not error_data:
# Timed out before any data is received.
break
if error_type is None or error_type == error_data["type"]:
msgs.append(error_data)
else:
time.sleep(0.01)
return msgs
def init_log_pubsub():
"""Initialize log pub/sub"""
s = ray._raylet.GcsLogSubscriber(
address=ray._private.worker.global_worker.gcs_client.address
)
s.subscribe()
return s
def get_log_data(
subscriber,
num: int = 1e6,
timeout: float = 20,
job_id: Optional[str] = None,
matcher=None,
) -> List[dict]:
deadline = time.time() + timeout
msgs = []
while time.time() < deadline and len(msgs) < num:
logs_data = subscriber.poll(timeout=deadline - time.time())
if not logs_data:
# Timed out before any data is received.
break
if job_id and job_id != logs_data["job"]:
continue
if matcher and all(not matcher(line) for line in logs_data["lines"]):
continue
msgs.append(logs_data)
return msgs
def get_log_message(
subscriber,
num: int = 1e6,
timeout: float = 20,
job_id: Optional[str] = None,
matcher=None,
) -> List[List[str]]:
"""Gets log lines through GCS subscriber.
Returns maximum `num` of log messages, within `timeout`.
If `job_id` or `match` is specified, only returns log lines from `job_id`
or when `matcher` is true.
"""
msgs = get_log_data(subscriber, num, timeout, job_id, matcher)
return [msg["lines"] for msg in msgs]
def get_log_sources(
subscriber,
num: int = 1e6,
timeout: float = 20,
job_id: Optional[str] = None,
matcher=None,