-
Notifications
You must be signed in to change notification settings - Fork 7.4k
Expand file tree
/
Copy pathscripts.py
More file actions
2896 lines (2659 loc) · 91.2 KB
/
scripts.py
File metadata and controls
2896 lines (2659 loc) · 91.2 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 json
import logging
import os
import platform
import shutil
import signal
import subprocess
import sys
import time
import urllib
import urllib.parse
import warnings
from datetime import datetime
from typing import List, Optional, Set, Tuple
import click
import colorama
import requests
import ray
import ray._common.usage.usage_constants as usage_constant
import ray._private.ray_constants as ray_constants
import ray._private.services as services
from ray._common.network_utils import build_address, parse_address
from ray._common.usage import usage_lib
from ray._common.utils import load_class
from ray._private.authentication.authentication_token_setup import (
ensure_token_if_auth_enabled,
)
from ray._private.internal_api import memory_summary
from ray._private.label_utils import (
parse_node_labels_from_yaml_file,
parse_node_labels_json,
parse_node_labels_string,
)
from ray._private.log import format_returncode, setup_process_exit_logger
from ray._private.resource_isolation_config import ResourceIsolationConfig
from ray._private.utils import (
get_ray_client_dependency_error,
parse_resources_json,
)
from ray.autoscaler._private.cli_logger import add_click_logging_options, cf, cli_logger
from ray.autoscaler._private.commands import (
RUN_ENV_TYPES,
attach_cluster,
create_or_update_cluster,
debug_status,
exec_cluster,
get_cluster_dump_archive,
get_head_node_ip,
get_local_dump_archive,
get_worker_node_ips,
kill_node,
monitor_cluster,
rsync,
teardown_cluster,
)
from ray.autoscaler._private.constants import RAY_PROCESSES
from ray.autoscaler._private.fake_multi_node.node_provider import FAKE_HEAD_NODE_ID
from ray.core.generated import autoscaler_pb2
from ray.dashboard.modules.metrics import install_and_start_prometheus
from ray.scripts.symmetric_run import symmetric_run
from ray.util.annotations import PublicAPI
from ray.util.check_open_ports import check_open_ports
import psutil
logger = logging.getLogger(__name__)
def _check_ray_version(gcs_client):
import ray._common.usage.usage_lib as ray_usage_lib
cluster_metadata = ray_usage_lib.get_cluster_metadata(gcs_client)
if cluster_metadata and cluster_metadata["ray_version"] != ray.__version__:
raise RuntimeError(
"Ray version mismatch: cluster has Ray version "
f"{cluster_metadata['ray_version']} "
f"but local Ray version is {ray.__version__}"
)
@click.group()
@click.option(
"--logging-level",
required=False,
default=ray_constants.LOGGER_LEVEL,
type=str,
help=ray_constants.LOGGER_LEVEL_HELP,
)
@click.option(
"--logging-format",
required=False,
default=ray_constants.LOGGER_FORMAT,
type=str,
help=ray_constants.LOGGER_FORMAT_HELP,
)
@click.version_option()
def cli(logging_level, logging_format):
level = logging.getLevelName(logging_level.upper())
ray._private.ray_logging.setup_logger(level, logging_format)
cli_logger.set_format(format_tmpl=logging_format)
@click.command()
@click.argument("cluster_config_file", required=True, type=str)
@click.option(
"--cluster-name",
"-n",
required=False,
type=str,
help="Override the configured cluster name.",
)
@click.option(
"--port",
"-p",
required=False,
type=int,
default=ray_constants.DEFAULT_DASHBOARD_PORT,
help="The local port to forward to the dashboard",
)
@click.option(
"--remote-port",
required=False,
type=int,
default=ray_constants.DEFAULT_DASHBOARD_PORT,
help="The remote port your dashboard runs on",
)
@click.option(
"--no-config-cache",
is_flag=True,
default=False,
help="Disable the local cluster config cache.",
)
@PublicAPI
def dashboard(cluster_config_file, cluster_name, port, remote_port, no_config_cache):
"""Port-forward a Ray cluster's dashboard to the local machine."""
# Sleeping in a loop is preferable to `sleep infinity` because the latter
# only works on linux.
# Find the first open port sequentially from `remote_port`.
try:
port_forward = [
(port, remote_port),
]
click.echo(
"Attempting to establish dashboard locally at"
" http://localhost:{}/ connected to"
" remote port {}".format(port, remote_port)
)
# We want to probe with a no-op that returns quickly to avoid
# exceptions caused by network errors.
exec_cluster(
cluster_config_file,
override_cluster_name=cluster_name,
port_forward=port_forward,
no_config_cache=no_config_cache,
)
click.echo("Successfully established connection.")
except Exception as e:
raise click.ClickException(
"Failed to forward dashboard from remote port {1} to local port "
"{0}. There are a couple possibilities: \n 1. The remote port is "
"incorrectly specified \n 2. The local port {0} is already in "
"use.\n The exception is: {2}".format(port, remote_port, e)
) from None
def continue_debug_session(live_jobs: Set[str]):
"""Continue active debugging session.
This function will connect 'ray debug' to the right debugger
when a user is stepping between Ray tasks.
"""
active_sessions = ray.experimental.internal_kv._internal_kv_list(
"RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB
)
for active_session in active_sessions:
if active_session.startswith(b"RAY_PDB_CONTINUE"):
# Check to see that the relevant job is still alive.
data = ray.experimental.internal_kv._internal_kv_get(
active_session, namespace=ray_constants.KV_NAMESPACE_PDB
)
if json.loads(data)["job_id"] not in live_jobs:
ray.experimental.internal_kv._internal_kv_del(
active_session, namespace=ray_constants.KV_NAMESPACE_PDB
)
continue
print("Continuing pdb session in different process...")
key = b"RAY_PDB_" + active_session[len("RAY_PDB_CONTINUE_") :]
while True:
data = ray.experimental.internal_kv._internal_kv_get(
key, namespace=ray_constants.KV_NAMESPACE_PDB
)
if data:
session = json.loads(data)
if "exit_debugger" in session or session["job_id"] not in live_jobs:
ray.experimental.internal_kv._internal_kv_del(
key, namespace=ray_constants.KV_NAMESPACE_PDB
)
return
host, port = parse_address(session["pdb_address"])
ray.util.rpdb._connect_pdb_client(host, int(port))
ray.experimental.internal_kv._internal_kv_del(
key, namespace=ray_constants.KV_NAMESPACE_PDB
)
continue_debug_session(live_jobs)
return
time.sleep(1.0)
def none_to_empty(s):
if s is None:
return ""
return s
def format_table(table):
"""Format a table as a list of lines with aligned columns."""
result = []
col_width = [max(len(x) for x in col) for col in zip(*table)]
for line in table:
result.append(
" | ".join("{0:{1}}".format(x, col_width[i]) for i, x in enumerate(line))
)
return result
@cli.command()
@click.option(
"--address", required=False, type=str, help="Override the address to connect to."
)
@click.option(
"-v",
"--verbose",
required=False,
is_flag=True,
help="Shows additional fields in breakpoint selection page.",
)
def debug(address: str, verbose: bool):
"""Show all active breakpoints and exceptions in the Ray debugger."""
address = services.canonicalize_bootstrap_address_or_die(address)
logger.info(f"Connecting to Ray instance at {address}.")
ray.init(address=address, log_to_driver=False)
if os.environ.get("RAY_DEBUG", "1") != "legacy":
print(
f"{colorama.Fore.YELLOW}NOTE: The distributed debugger "
"https://docs.ray.io/en/latest/ray-observability"
"/ray-distributed-debugger.html is now the default "
"due to better interactive debugging support. If you want "
"to keep using 'ray debug' please set RAY_DEBUG=legacy "
f"in your cluster (e.g. via runtime environment).{colorama.Fore.RESET}"
)
while True:
# Used to filter out and clean up entries from dead jobs.
live_jobs = {
job["JobID"] for job in ray._private.state.jobs() if not job["IsDead"]
}
continue_debug_session(live_jobs)
active_sessions = ray.experimental.internal_kv._internal_kv_list(
"RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB
)
print("Active breakpoints:")
sessions_data = []
for active_session in active_sessions:
data = json.loads(
ray.experimental.internal_kv._internal_kv_get(
active_session, namespace=ray_constants.KV_NAMESPACE_PDB
)
)
# Check that the relevant job is alive, else clean up the entry.
if data["job_id"] in live_jobs:
sessions_data.append(data)
else:
ray.experimental.internal_kv._internal_kv_del(
active_session, namespace=ray_constants.KV_NAMESPACE_PDB
)
sessions_data = sorted(
sessions_data, key=lambda data: data["timestamp"], reverse=True
)
if verbose:
table = [
[
"index",
"timestamp",
"Ray task",
"filename:lineno",
"Task ID",
"Worker ID",
"Actor ID",
"Node ID",
]
]
for i, data in enumerate(sessions_data):
date = datetime.utcfromtimestamp(data["timestamp"]).strftime(
"%Y-%m-%d %H:%M:%S"
)
table.append(
[
str(i),
date,
data["proctitle"],
data["filename"] + ":" + str(data["lineno"]),
data["task_id"],
data["worker_id"],
none_to_empty(data["actor_id"]),
data["node_id"],
]
)
else:
# Non verbose mode: no IDs.
table = [["index", "timestamp", "Ray task", "filename:lineno"]]
for i, data in enumerate(sessions_data):
date = datetime.utcfromtimestamp(data["timestamp"]).strftime(
"%Y-%m-%d %H:%M:%S"
)
table.append(
[
str(i),
date,
data["proctitle"],
data["filename"] + ":" + str(data["lineno"]),
]
)
for i, line in enumerate(format_table(table)):
print(line)
if i >= 1 and not sessions_data[i - 1]["traceback"].startswith(
"NoneType: None"
):
print(sessions_data[i - 1]["traceback"])
inp = input("Enter breakpoint index or press enter to refresh: ")
if inp == "":
print()
continue
else:
index = int(inp)
session = json.loads(
ray.experimental.internal_kv._internal_kv_get(
active_sessions[index], namespace=ray_constants.KV_NAMESPACE_PDB
)
)
host, port = parse_address(session["pdb_address"])
ray.util.rpdb._connect_pdb_client(host, int(port))
@cli.command()
@click.option(
"--node-ip-address", required=False, type=str, help="the IP address of this node"
)
@click.option("--address", required=False, type=str, help="the address to use for Ray")
@click.option(
"--port",
type=int,
required=False,
help=f"the port of the head ray process. If not provided, defaults to "
f"{ray_constants.DEFAULT_PORT}; if port is set to 0, we will"
f" allocate an available port.",
)
@click.option(
"--node-name",
required=False,
hidden=True,
type=str,
help="the user-provided identifier or name for this node. "
"Defaults to the node's ip_address",
)
@click.option(
"--redis-username",
required=False,
hidden=True,
type=str,
default=ray_constants.REDIS_DEFAULT_USERNAME,
help="If provided, secure Redis ports with this username",
)
@click.option(
"--redis-password",
required=False,
hidden=True,
type=str,
default=ray_constants.REDIS_DEFAULT_PASSWORD,
help="If provided, secure Redis ports with this password",
)
@click.option(
"--redis-shard-ports",
required=False,
hidden=True,
type=str,
help="the port to use for the Redis shards other than the primary Redis shard",
)
@click.option(
"--object-manager-port",
required=False,
type=int,
help="the port to use for starting the object manager",
)
@click.option(
"--node-manager-port",
required=False,
type=int,
default=0,
help="the port to use for starting the node manager",
)
@click.option(
"--min-worker-port",
required=False,
type=int,
default=10002,
help="the lowest port number that workers will bind on. If not set, "
"random ports will be chosen.",
)
@click.option(
"--max-worker-port",
required=False,
type=int,
default=19999,
help="the highest port number that workers will bind on. If set, "
"'--min-worker-port' must also be set.",
)
@click.option(
"--worker-port-list",
required=False,
help="a comma-separated list of open ports for workers to bind on. "
"Overrides '--min-worker-port' and '--max-worker-port'.",
)
@click.option(
"--ray-client-server-port",
required=False,
type=int,
default=None,
help="the port number the ray client server binds on, default to 10001, "
"or None if ray[client] is not installed.",
)
@click.option(
"--memory",
required=False,
hidden=True,
type=int,
help="The amount of memory (in bytes) to make available to workers. "
"By default, this is set to the available memory on the node.",
)
@click.option(
"--object-store-memory",
required=False,
type=int,
help="The amount of memory (in bytes) to start the object store with. "
"By default, this is 30% of available system memory capped by "
"the shm size and 200G but can be set higher.",
)
@click.option(
"--num-cpus", required=False, type=int, help="the number of CPUs on this node"
)
@click.option(
"--num-gpus", required=False, type=int, help="the number of GPUs on this node"
)
@click.option(
"--resources",
required=False,
default="{}",
type=str,
help="A JSON serialized dictionary mapping resource name to resource quantity."
+ (
r"""
Windows command prompt users must ensure to double quote command line arguments. Because
JSON requires the use of double quotes you must escape these arguments as well, for
example:
ray start --head --resources="{\"special_hardware\":1, \"custom_label\":1}"
Windows powershell users need additional escaping:
ray start --head --resources="{\""special_hardware\"":1, \""custom_label\"":1}"
"""
if platform.system() == "Windows"
else ""
),
)
@click.option(
"--head",
is_flag=True,
default=False,
help="provide this argument for the head node",
)
@click.option(
"--include-dashboard",
default=None,
type=bool,
help="provide this argument to start the Ray dashboard GUI",
)
@click.option(
"--dashboard-host",
required=False,
default=ray_constants.DEFAULT_DASHBOARD_IP,
help="the host to bind the dashboard server to, either localhost "
"(127.0.0.1) or 0.0.0.0 (available from all interfaces). By default, this "
"is 127.0.0.1",
)
@click.option(
"--dashboard-port",
required=False,
type=int,
default=ray_constants.DEFAULT_DASHBOARD_PORT,
help="the port to bind the dashboard server to--defaults to {}".format(
ray_constants.DEFAULT_DASHBOARD_PORT
),
)
@click.option(
"--dashboard-agent-listen-port",
type=int,
default=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT,
help="the port for dashboard agents to listen for http on.",
)
@click.option(
"--dashboard-agent-grpc-port",
type=int,
default=None,
help="the port for dashboard agents to listen for grpc on.",
)
@click.option(
"--runtime-env-agent-port",
type=int,
default=None,
help="The port for the runtime environment agents to listen for http on.",
)
@click.option(
"--block",
is_flag=True,
default=False,
help="provide this argument to block forever in this command."
"Process exit logs will be saved to ray_process_exit.log in the logs directory.",
)
@click.option(
"--plasma-directory",
required=False,
type=str,
help="object store directory for memory mapped files",
)
@click.option(
"--object-spilling-directory",
required=False,
type=str,
help="The path to spill objects to. This path will also be used as the fallback directory when the object store is full of in-use objects and cannot spill.",
)
@click.option(
"--autoscaling-config",
required=False,
type=str,
help="the file that contains the autoscaling config",
)
@click.option(
"--no-redirect-output",
is_flag=True,
default=False,
help="do not redirect non-worker stdout and stderr to files",
)
@click.option(
"--temp-dir",
default=None,
help="manually specify the root temporary dir of the Ray process. Can be "
"specified per node.",
)
@click.option(
"--system-config",
default=None,
hidden=True,
type=json.loads,
help="Override system configuration defaults.",
)
@click.option(
"--enable-object-reconstruction",
is_flag=True,
default=False,
hidden=True,
help="Specify whether object reconstruction will be used for this cluster.",
)
@click.option(
"--metrics-export-port",
type=int,
default=None,
help="the port to use to expose Ray metrics through a Prometheus endpoint.",
)
@click.option(
"--no-monitor",
is_flag=True,
hidden=True,
default=False,
help="If True, the ray autoscaler monitor for this cluster will not be started.",
)
@click.option(
"--tracing-startup-hook",
type=str,
hidden=True,
default=None,
help="The function that sets up tracing with a tracing provider, remote "
"span processor, and additional instruments. See docs.ray.io/tracing.html "
"for more info.",
)
@click.option(
"--ray-debugger-external",
is_flag=True,
default=False,
help="Make the Ray debugger available externally to the node. This is only "
"safe to activate if the node is behind a firewall.",
)
@click.option(
"--disable-usage-stats",
is_flag=True,
default=False,
help="If True, the usage stats collection will be disabled.",
)
@click.option(
"--labels",
required=False,
hidden=True,
default="",
type=str,
help="a string list of key-value pairs mapping label name to label value."
"These values take precedence over conflicting keys passed in from --labels-file."
'Ex: --labels "key1=val1,key2=val2"',
)
@click.option(
"--labels-file",
required=False,
hidden=True,
default="",
type=str,
help="a path to a YAML file containing a dictionary mapping of label keys to values.",
)
@click.option(
"--include-log-monitor",
default=None,
type=bool,
help="If set to True or left unset, a log monitor will start monitoring "
"the log files of all processes on this node and push their contents to GCS. "
"Only one log monitor should be started per physical host to avoid log "
"duplication on the driver process.",
)
@click.option(
"--enable-resource-isolation",
required=False,
is_flag=True,
default=False,
help="Enable resource isolation through cgroupv2 by reserving memory and cpu "
"resources for ray system processes. To use, only cgroupv2 (not cgroupv1) must "
"be enabled with read and write permissions for the raylet. Cgroup memory and "
"cpu controllers must also be enabled.",
)
@click.option(
"--system-reserved-cpu",
required=False,
type=float,
help=" The number of cpu cores to reserve for ray system processes. "
"Cores can be fractional i.e. 1.5 means one and a half a cpu core. "
"By default, the value will be atleast 1 core, and at maximum 3 cores. The default value "
"is calculated using the formula min(3.0, max(1.0, 0.05 * num_cores_on_the_system)) "
"This option only works if --enable_resource_isolation is set.",
)
@click.option(
"--system-reserved-memory",
required=False,
type=int,
help="The amount of memory (in bytes) to reserve for ray system processes. "
"By default, the value will be atleast 500MB, and at most 10GB. The default value is "
"calculated using the formula min(10GB, max(500MB, 0.10 * memory_available_on_the_system)) "
"This option only works if --enable_resource_isolation is set.",
)
@click.option(
"--cgroup-path",
required=False,
type=str,
help="The path for the cgroup the raylet should use to enforce resource isolation. "
"By default, the cgroup used for resource isolation will be /sys/fs/cgroup. "
"The process starting ray must have read/write permissions to this path. "
"Cgroup memory and cpu controllers be enabled for this cgroup. "
"This option only works if enable_resource_isolation is True.",
)
@click.option(
"--proxy-server-url",
required=False,
type=str,
help="[Experimental] The server url to redirect dashboard backend requests to. "
"By default, the dashboard requests will be directed to the Ray api server. "
"If you have a custom server to serve the dashboard requests, "
"you can set this option to override the server url. "
"Ex: --proxy-server-url=http://historyserver:8080 ",
)
@add_click_logging_options
@PublicAPI
def start(
node_ip_address,
address,
port,
node_name,
redis_username,
redis_password,
redis_shard_ports,
object_manager_port,
node_manager_port,
min_worker_port,
max_worker_port,
worker_port_list,
ray_client_server_port,
memory,
object_store_memory,
num_cpus,
num_gpus,
resources,
head,
include_dashboard,
dashboard_host,
dashboard_port,
dashboard_agent_listen_port,
dashboard_agent_grpc_port,
runtime_env_agent_port,
block,
plasma_directory,
object_spilling_directory,
autoscaling_config,
no_redirect_output,
temp_dir,
system_config,
enable_object_reconstruction,
metrics_export_port,
no_monitor,
tracing_startup_hook,
ray_debugger_external,
disable_usage_stats,
labels,
labels_file,
include_log_monitor,
enable_resource_isolation,
system_reserved_cpu,
system_reserved_memory,
cgroup_path,
proxy_server_url,
):
"""Start Ray processes manually on the local machine."""
# Whether the original arguments include node_ip_address.
include_node_ip_address = False
if node_ip_address is not None:
include_node_ip_address = True
node_ip_address = services.resolve_ip_for_localhost(node_ip_address)
resources = parse_resources_json(resources, cli_logger, cf)
# Compose labels passed in with `--labels` and `--labels-file`.
# In the case of duplicate keys, the values from `--labels` take precedence.
try:
labels_from_file = parse_node_labels_from_yaml_file(labels_file)
except Exception as e:
cli_logger.abort(
"The file at `{}` is not a valid YAML file, detailed error: {} "
"Valid values look like this: `{}`",
cf.bold(f"--labels-file={labels_file}"),
str(e),
cf.bold("--labels-file='gpu_type: A100\nregion: us'"),
)
try:
# Attempt to parse labels from new string format first.
labels_from_string = parse_node_labels_string(labels)
except Exception as e:
try:
# Fall back to JSON format if parsing from string fails.
labels_from_string = parse_node_labels_json(labels)
warnings.warn(
"passing node labels with `--labels` in JSON format is "
"deprecated and will be removed in a future version of Ray.",
DeprecationWarning,
stacklevel=2,
)
except Exception:
# If parsing labels from both formats fails, return the original error message.
cli_logger.abort(
"`{}` is not a valid string of key-value pairs, detailed error: {} "
"Valid values look like this: `{}`",
cf.bold(f"--labels={labels}"),
str(e),
cf.bold('--labels="key1=val1,key2=val2"'),
)
labels_dict = {**labels_from_file, **labels_from_string}
available_memory_bytes = ray._private.utils.estimate_available_memory()
object_store_memory = ray._private.utils.resolve_object_store_memory(
available_memory_bytes, object_store_memory
)
resource_isolation_config = ResourceIsolationConfig(
enable_resource_isolation=enable_resource_isolation,
cgroup_path=cgroup_path,
system_reserved_cpu=system_reserved_cpu,
system_reserved_memory=system_reserved_memory,
object_store_memory=object_store_memory,
)
# - For non-worker processes, thread the behavior explicitly via RayParams.log_to_stderr.
# - For worker processes, stdout/stderr redirection is controlled in C++ via
# `RAY_LOG_TO_STDERR`, so we pass it to the raylet/worker subprocess env via
# RayParams.env_vars (without touching os.environ).
if no_redirect_output:
log_to_stderr = True
env_vars = {
ray_constants.LOGGING_REDIRECT_STDERR_ENVIRONMENT_VARIABLE: "1",
}
else:
log_to_stderr = None
env_vars = None
# no client, no port -> ok
# no port, has client -> default to 10001
# has port, no client -> value error
# has port, has client -> ok, check port validity
has_ray_client = get_ray_client_dependency_error() is None
if has_ray_client and ray_client_server_port is None:
ray_client_server_port = 10001
ray_params = ray._private.parameter.RayParams(
node_ip_address=node_ip_address,
node_name=node_name if node_name else node_ip_address,
min_worker_port=min_worker_port,
max_worker_port=max_worker_port,
worker_port_list=worker_port_list,
ray_client_server_port=ray_client_server_port,
object_manager_port=object_manager_port,
node_manager_port=node_manager_port,
memory=memory,
available_memory_bytes=available_memory_bytes,
object_store_memory=object_store_memory,
redis_username=redis_username,
redis_password=redis_password,
log_to_stderr=log_to_stderr,
num_cpus=num_cpus,
num_gpus=num_gpus,
resources=resources,
labels=labels_dict,
autoscaling_config=autoscaling_config,
plasma_directory=plasma_directory,
object_spilling_directory=object_spilling_directory,
huge_pages=False,
temp_dir=temp_dir,
include_dashboard=include_dashboard,
dashboard_host=dashboard_host,
dashboard_port=dashboard_port,
dashboard_agent_listen_port=dashboard_agent_listen_port,
metrics_agent_port=dashboard_agent_grpc_port,
runtime_env_agent_port=runtime_env_agent_port,
_system_config=system_config,
enable_object_reconstruction=enable_object_reconstruction,
metrics_export_port=metrics_export_port,
no_monitor=no_monitor,
tracing_startup_hook=tracing_startup_hook,
ray_debugger_external=ray_debugger_external,
include_log_monitor=include_log_monitor,
resource_isolation_config=resource_isolation_config,
proxy_server_url=proxy_server_url,
env_vars=env_vars,
)
if ray_constants.RAY_START_HOOK in os.environ:
load_class(os.environ[ray_constants.RAY_START_HOOK])(ray_params, head)
if head:
# Start head node.
if disable_usage_stats:
usage_lib.set_usage_stats_enabled_via_env_var(False)
usage_lib.show_usage_stats_prompt(cli=True)
cli_logger.newline()
if port is None:
port = ray_constants.DEFAULT_PORT
# Set bootstrap port.
assert ray_params.redis_port is None
assert ray_params.gcs_server_port is None
ray_params.gcs_server_port = port
if os.environ.get("RAY_FAKE_CLUSTER"):
ray_params.env_vars = {
**(ray_params.env_vars or {}),
"RAY_OVERRIDE_NODE_ID_FOR_TESTING": FAKE_HEAD_NODE_ID,
}
if (
usage_constant.KUBERAY_ENV in os.environ # KubeRay exclusive.
and "RAY_CLOUD_INSTANCE_ID" in os.environ # required by autoscaler v2.
and "RAY_NODE_TYPE_NAME" in os.environ # required by autoscaler v2.
):
# If this Ray cluster is managed by KubeRay and RAY_CLOUD_INSTANCE_ID and RAY_NODE_TYPE_NAME are set,
# we enable the v2 autoscaler by default if RAY_enable_autoscaler_v2 is not set.
os.environ.setdefault("RAY_enable_autoscaler_v2", "1")
num_redis_shards = None
# Start Ray on the head node.
if redis_shard_ports is not None and address is None:
redis_shard_ports = redis_shard_ports.split(",")
# Infer the number of Redis shards from the ports if the number is
# not provided.
num_redis_shards = len(redis_shard_ports)
# This logic is deprecated and will be removed later.
if address is not None:
cli_logger.warning(
"Specifying {} for external Redis address is deprecated. "
"Please specify environment variable {}={} instead.",
cf.bold("--address"),
cf.bold("RAY_REDIS_ADDRESS"),
address,
)
external_addresses = address.split(",")
# We reuse primary redis as sharding when there's only one
# instance provided.
if len(external_addresses) == 1:
external_addresses.append(external_addresses[0])
ray_params.update_if_absent(external_addresses=external_addresses)
num_redis_shards = len(external_addresses) - 1
if redis_username == ray_constants.REDIS_DEFAULT_USERNAME:
cli_logger.warning(
"`{}` should not be specified as empty string if "
"external Redis server(s) `{}` points to requires "
"username.",
cf.bold("--redis-username"),
cf.bold("--address"),
)
if redis_password == ray_constants.REDIS_DEFAULT_PASSWORD:
cli_logger.warning(
"`{}` should not be specified as empty string if "
"external redis server(s) `{}` points to requires "
"password.",
cf.bold("--redis-password"),
cf.bold("--address"),
)
# Get the node IP address if one is not provided.
ray_params.update_if_absent(node_ip_address=services.get_node_ip_address())
cli_logger.labeled_value("Local node IP", ray_params.node_ip_address)
# Initialize Redis settings.
ray_params.update_if_absent(
redis_shard_ports=redis_shard_ports,
num_redis_shards=num_redis_shards,
redis_max_clients=None,
)
# Fail early when starting a new cluster when one is already running
if address is None:
default_address = build_address(ray_params.node_ip_address, port)
bootstrap_address = services.find_bootstrap_address(temp_dir)
if (
default_address == bootstrap_address
and bootstrap_address in services.find_gcs_addresses()
):
# The default address is already in use by a local running GCS
# instance.
raise ConnectionError(
f"Ray is trying to start at {default_address}, "
f"but is already running at {bootstrap_address}. "
"Please specify a different port using the `--port`"
" flag of `ray start` command."
)
# Ensure auth token is available if authentication mode is token
ensure_token_if_auth_enabled(system_config, create_token_if_missing=False)
node = ray._private.node.Node(
ray_params, head=True, shutdown_at_exit=block, spawn_reaper=block
)
bootstrap_address = node.address
# this is a noop if new-style is not set, so the old logger calls
# are still in place
cli_logger.newline()
startup_msg = "Ray runtime started."
cli_logger.success("-" * len(startup_msg))
cli_logger.success(startup_msg)
cli_logger.success("-" * len(startup_msg))
cli_logger.newline()
with cli_logger.group("Next steps"):
dashboard_url = node.address_info["webui_url"]
if ray_constants.ENABLE_RAY_CLUSTER:
cli_logger.print("To add another node to this Ray cluster, run")
# NOTE(kfstorm): Java driver rely on this line to get the address
# of the cluster. Please be careful when updating this line.
cli_logger.print(
cf.bold(" {} ray start --address='{}'"),
(
f" {ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR}=1"
if ray_constants.IS_WINDOWS_OR_OSX
else ""
),
bootstrap_address,
)
cli_logger.newline()
cli_logger.print("To connect to this Ray cluster:")