-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
1092 lines (921 loc) · 38.5 KB
/
utils.py
File metadata and controls
1092 lines (921 loc) · 38.5 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 ipaddress
import os
import re
from typing import Dict, List, Optional
import platform
import subprocess
import re
from functools import lru_cache
import socket
import json
import ray
# Stores the most recent return value from ray.init(), for extracting web UI info
_LAST_RAY_ADDRESS_INFO: Optional[dict] = None
# Stores the most recent known dashboard URL (e.g., ClientContext.dashboard_url)
_LAST_RAY_DASHBOARD_URL: Optional[str] = None
def parse_n_gpus_from_env() -> Optional[float]:
"""Parse n_gpus from environment variables (supports 'n_gpus' or 'N_GPUS').
Returns:
GPU count as float, or None if not specified or invalid
"""
gpu_env = os.environ.get("n_gpus") or os.environ.get("N_GPUS")
if gpu_env is not None and gpu_env != "":
try:
gpu_count = float(gpu_env)
if gpu_count < 0:
raise ValueError("GPU count must be >= 0")
return gpu_count
except Exception:
return None
return None
def parse_require_constraints_from_env() -> Dict[str, float]:
"""Parse require constraints from environment variable.
Parses the 'require' or 'requires' environment variable in format:
'accelerator_type:H20,some_other_resource=0.0001'
Environment variables checked (in order):
- require, REQUIRE, requires, REQUIRES
Rules:
- Comma-separated resource specifications
- If no '=<number>' is specified, defaults to 0.0001
Returns:
Dict mapping resource names to quantities for Ray actor options
Examples:
require='accelerator_type:H20' -> {'accelerator_type:H20': 0.0001}
requires='memory_type:HBM,accelerator_type:V100,memory_gb=100' ->
{'memory_type:HBM': 0.0001, 'accelerator_type:V100': 0.0001, 'memory_gb': 100}
"""
require_env = (
os.environ.get("require")
or os.environ.get("REQUIRE")
or os.environ.get("requires")
or os.environ.get("REQUIRES")
)
if not require_env or require_env.strip() == "":
return {}
constraints = {}
try:
# Split by comma to get individual resource specs
specs = [spec.strip() for spec in require_env.split(",") if spec.strip()]
for spec in specs:
if "=" in spec:
# Format: resource_name=quantity
resource_name, quantity_str = spec.split("=", 1)
resource_name = resource_name.strip()
try:
quantity = float(quantity_str.strip())
if quantity < 0:
print(
f"⚠️ Warning: Negative quantity {quantity} for resource '{resource_name}', using 0.0001"
)
quantity = 0.0001
except ValueError:
print(
f"⚠️ Warning: Invalid quantity '{quantity_str}' for resource '{resource_name}', using 0.0001"
)
quantity = 0.0001
else:
# Format: resource_name (use default quantity)
resource_name = spec.strip()
quantity = 0.0001
if resource_name:
constraints[resource_name] = quantity
except Exception as e:
print(f"⚠️ Warning: Failed to parse require constraints '{require_env}': {e}")
return {}
return constraints
def apply_require_constraints_to_actor_options(actor_options: Dict) -> None:
"""Apply require constraints from environment to actor options dict.
Modifies the actor_options dict in-place by adding resource constraints
from the 'require' environment variable.
Args:
actor_options: Dict that will be passed to Ray actor .options(**actor_options)
"""
require_constraints = parse_require_constraints_from_env()
if require_constraints:
if "resources" not in actor_options:
actor_options["resources"] = {}
actor_options["resources"].update(require_constraints)
print(f"🎯 Applied additional constraints: {require_constraints}")
def select_worker_node(
n_gpus: Optional[float] = None, prefer_ip: Optional[str] = None
) -> Dict:
"""Select an appropriate worker node for actor placement.
Args:
n_gpus: Number of GPUs required (None for no GPU requirement)
prefer_ip: Preferred node IP (will be used if available and suitable)
Returns:
Selected node dict with NodeID, NodeManagerAddress, etc.
Raises:
RuntimeError: If no suitable worker nodes are available
"""
# Ensure Ray is initialized to get cluster state
if not ray.is_initialized():
raise RuntimeError("Ray must be initialized before selecting nodes")
# Get require constraints from environment
require_constraints = parse_require_constraints_from_env()
nodes, head_node_id = fetch_cluster_nodes()
if not nodes:
raise RuntimeError("No alive Ray nodes found in the cluster")
# Filter to worker nodes only (exclude head node)
worker_nodes = []
for node in nodes:
node_id = node.get("NodeID")
if not node_id or node_id == head_node_id:
continue
if not node.get("Alive", False):
continue
worker_nodes.append(node)
if not worker_nodes:
raise RuntimeError("No worker nodes available")
# Filter nodes by resource requirements (GPU + require constraints)
suitable_nodes = []
for node in worker_nodes:
resources = node.get("Resources", {})
# Check GPU requirements
if n_gpus is not None and n_gpus > 0:
available_gpus = resources.get("GPU", 0)
if available_gpus < n_gpus:
continue
# Check require constraints
meets_constraints = True
for resource_name, required_quantity in require_constraints.items():
available_quantity = resources.get(resource_name, 0)
if available_quantity < required_quantity:
meets_constraints = False
break
if meets_constraints:
suitable_nodes.append(node)
if not suitable_nodes:
constraint_info = []
if n_gpus is not None and n_gpus > 0:
constraint_info.append(f"GPUs >= {n_gpus}")
if require_constraints:
for resource_name, quantity in require_constraints.items():
constraint_info.append(f"{resource_name} >= {quantity}")
constraints_str = ", ".join(constraint_info) if constraint_info else "none"
raise RuntimeError(
f"No worker nodes meet resource constraints: {constraints_str}"
)
# If user prefers a specific IP, check if it's in suitable nodes
if prefer_ip:
for node in suitable_nodes:
if node.get("NodeManagerAddress") == prefer_ip:
print(f"🎯 Using preferred node {prefer_ip} (meets all constraints)")
return node
print(f"⚠️ Preferred node {prefer_ip} does not meet resource constraints")
# Select node with most available resources (simple heuristic)
def node_score(node):
resources = node.get("Resources", {})
cpu = resources.get("CPU", 0)
memory = resources.get("memory", 0)
gpu = resources.get("GPU", 0)
# Simple scoring: prioritize nodes with more total resources
return cpu + memory / (1024**3) + gpu * 10 # Weight GPUs higher
selected_node = max(suitable_nodes, key=node_score)
return selected_node
def is_valid_ip(ip_str: str) -> bool:
"""Check if the given string is a valid IP address."""
try:
ipaddress.ip_address(ip_str)
return True
except ValueError:
return False
def is_valid_node_id(node_id: str) -> bool:
"""Check if the given string is a valid Ray node ID format."""
# Ray node IDs are typically hex strings, allow minimum 6 chars for prefix matching
return bool(re.match(r"^[a-fA-F0-9]+$", node_id)) and len(node_id) >= 6
def parse_node_argument(node_arg: str) -> tuple[str, str]:
"""
Parse the node argument to determine if it's an IP address or node ID.
Returns (type, value) where type is either 'ip' or 'node_id'.
"""
# Handle special cases like localhost
if node_arg.lower() in ["localhost", "127.0.0.1", "::1"]:
return ("ip", "127.0.0.1") # Normalize to 127.0.0.1
elif is_valid_ip(node_arg):
return ("ip", node_arg)
elif is_valid_node_id(node_arg):
return ("node_id", node_arg)
else:
raise ValueError(
f"Invalid node argument: {node_arg}. \nUsage: rayssh <node|file> or rayssh -q <file>"
)
def get_ray_cluster_nodes() -> List[Dict]:
"""Get information about all nodes in the Ray cluster (alive only), normalized.
Uses Ray's public nodes() API via our helper.
Assumes Ray has already been initialized by the caller.
"""
nodes, _ = fetch_cluster_nodes()
return nodes
def find_node_by_ip(
target_ip: str, resource_constraints: Dict = None
) -> Optional[Dict]:
"""Find a Ray node by its IP address.
Args:
target_ip: Target node IP address
resource_constraints: Optional dict of resource requirements to check
Returns:
Node dict if found and meets constraints, None otherwise
"""
nodes, _ = fetch_cluster_nodes()
for node in nodes:
# Check both NodeManagerAddress and internal/external IPs
node_ip = node.get("NodeManagerAddress")
if node_ip != target_ip:
# Also check if the target IP matches any of the node's addresses
resources = node.get("Resources", {})
if ("node:" + target_ip) not in resources:
continue
# Check resource constraints if provided
if resource_constraints:
resources = node.get("Resources", {})
meets_constraints = True
for resource_name, required_quantity in resource_constraints.items():
available_quantity = resources.get(resource_name, 0)
if available_quantity < required_quantity:
# print(f"⚠️ Node {node_ip} has insufficient {resource_name}: {available_quantity} < {required_quantity}")
meets_constraints = False
break
if not meets_constraints:
continue
return node
return None
def find_node_by_id(target_node_id: str) -> Optional[Dict]:
"""Find a Ray node by its node ID."""
nodes, _ = fetch_cluster_nodes()
for node in nodes:
node_id = node.get("NodeID")
if node_id and (
node_id == target_node_id or node_id.startswith(target_node_id)
):
return node
return None
def find_ip_by_node_id(target_node_id: str) -> Optional[str]:
"""Return the NodeManagerAddress for the given NodeID if alive."""
nodes, _ = fetch_cluster_nodes()
for node in nodes:
node_id = node.get("NodeID")
if node_id and node_id == target_node_id:
return node.get("NodeManagerAddress")
return None
def find_target_node(node_arg: str, resource_constraints: Dict = None) -> Dict:
"""
Find the target Ray node based on IP address or node ID.
Args:
node_arg: IP address or node ID to find
resource_constraints: Optional resource constraints to check
Returns:
Node information dict
Raises:
ValueError: If node not found or doesn't meet constraints
"""
arg_type, value = parse_node_argument(node_arg)
# Get require constraints from environment if not explicitly provided
if resource_constraints is None:
resource_constraints = parse_require_constraints_from_env()
if arg_type == "ip":
node = find_node_by_ip(value, resource_constraints=resource_constraints)
if not node:
constraint_info = ""
if resource_constraints:
constraint_strs = [
f"{name}>={qty}" for name, qty in resource_constraints.items()
]
constraint_info = f" meeting constraints: {', '.join(constraint_strs)}"
raise ValueError(
f"No Ray node found with IP address: {value}{constraint_info}"
)
else: # node_id
node = find_node_by_id(value)
if not node:
raise ValueError(f"No Ray node found with node ID: {value}")
# Check resource constraints for node ID lookup too
if resource_constraints:
resources = node.get("Resources", {})
for resource_name, required_quantity in resource_constraints.items():
available_quantity = resources.get(resource_name, 0)
if available_quantity < required_quantity:
raise ValueError(
f"Node {value} has insufficient {resource_name}: {available_quantity} < {required_quantity}"
)
# Check if node is alive
if not node.get("Alive", False):
raise ValueError(f"Target node is not alive: {value}")
return node
def _extract_dashboard_info_from_init(
addr_info, ray_address: Optional[str] = None
) -> None:
"""Extract and store dashboard info from ray.init() result.
Args:
addr_info: Result from ray.init()
ray_address: Optional Ray address (used for deriving dashboard URL)
"""
global _LAST_RAY_ADDRESS_INFO, _LAST_RAY_DASHBOARD_URL
try:
# Try to extract from addr_info
info_dict = None
if isinstance(addr_info, dict):
info_dict = addr_info
else:
dash = getattr(addr_info, "dashboard_url", None)
if dash:
_LAST_RAY_DASHBOARD_URL = dash
info_dict = getattr(addr_info, "address_info", None)
if info_dict and isinstance(info_dict, dict):
_LAST_RAY_ADDRESS_INFO = info_dict
except Exception:
pass
# Derive dashboard URL from ray_address if still unknown
try:
if (
ray_address
and ray_address.startswith("ray://")
and not _LAST_RAY_DASHBOARD_URL
):
addr_part = ray_address.split("://", 1)[1]
host, port_str = (
addr_part.rsplit(":", 1) if ":" in addr_part else (addr_part, "10001")
)
client_port = int(port_str)
dashboard_port = (
8265 if client_port == 10001 else max(1, client_port - 1736)
)
_LAST_RAY_DASHBOARD_URL = f"{host}:{dashboard_port}"
if not _LAST_RAY_ADDRESS_INFO:
_LAST_RAY_ADDRESS_INFO = {
"webui_url": _LAST_RAY_DASHBOARD_URL,
"address": ray_address,
}
except Exception:
pass
def ensure_ray_initialized(
ray_address: str = None, working_dir: str = None, connect_only: bool = False
):
"""Ensure Ray is initialized, initialize if not.
If connect_only is True, do not start a new local cluster. Attempt to connect
to an existing cluster (local or remote) and raise if none is available.
"""
global _LAST_RAY_ADDRESS_INFO, _LAST_RAY_DASHBOARD_URL
if ray.is_initialized():
return
ray_address = ray_address or os.environ.get("RAY_ADDRESS")
try:
# Set environment variables to suppress Ray logging
os.environ["RAY_DISABLE_IMPORT_WARNING"] = "1"
os.environ["RAY_DEDUP_LOGS"] = "0" # Reduce log deduplication overhead
os.environ["GLOG_minloglevel"] = (
"3" # Suppress glog messages (0=INFO, 1=WARNING, 2=ERROR, 3=FATAL)
)
os.environ["GLOG_logtostderr"] = "0" # Don't log to stderr
os.environ["RAY_RAYLET_LOG_LEVEL"] = "FATAL" # Suppress raylet logs
os.environ["RAY_CORE_WORKER_LOG_LEVEL"] = "FATAL" # Suppress core worker logs
# Suppress additional Ray client and worker messages
import logging
logging.getLogger("ray").setLevel(logging.WARNING)
logging.getLogger("ray.serve").setLevel(logging.WARNING)
logging.getLogger("ray.tune").setLevel(logging.WARNING)
logging.getLogger("ray.rllib").setLevel(logging.WARNING)
logging.getLogger("ray.workflow").setLevel(logging.WARNING)
# Prepare runtime environment for Ray Client
runtime_env = {}
if working_dir:
runtime_env["working_dir"] = working_dir
# Add required modules for RaySSH actors
try:
# Ship the entire project root so remote workers import the same code
import agent
import terminal
import utils
runtime_env["py_modules"] = [agent, terminal, utils]
# watchfiles contains .so libraries, so it must be installed via pip
runtime_env["pip"] = ["watchfiles"]
except ImportError as e:
# If modules can't be imported, continue without py_modules
print(f"Error importing modules: {e}")
pass
# Build common init_kwargs for all Ray initialization modes
init_kwargs = {
"logging_level": "FATAL",
"log_to_driver": False,
"ignore_reinit_error": True,
}
# Initialize Ray (either local cluster, connect-only, or Ray Client)
if ray_address and ray_address.startswith("ray://"):
# Ray Client connection
init_kwargs["address"] = ray_address
if runtime_env:
init_kwargs["runtime_env"] = runtime_env
print(f"🌐 Connecting to Ray cluster: {ray_address}")
if working_dir is not None:
try:
print(f"📦 Uploading working dir: {os.path.abspath(working_dir)}")
except Exception:
print("📦 Uploading working dir")
try:
addr_info = ray.init(**init_kwargs)
_extract_dashboard_info_from_init(addr_info, ray_address)
except Exception as e:
msg = str(e)
# Tolerate repeated client init attempts
if (
"already connected" in msg
or "Ray Client is already connected" in msg
):
print("ℹ️ Ray Client already connected; continuing")
# Capture from existing client context if available
try:
ctx = ray.util.client._default_context
if ctx and getattr(ctx, "dashboard_url", None):
_LAST_RAY_DASHBOARD_URL = ctx.dashboard_url
except Exception:
pass
# Try to extract dashboard URL from ray_address
_extract_dashboard_info_from_init(None, ray_address)
return
raise
elif connect_only:
# Connect to an existing Ray cluster without starting one
init_kwargs["address"] = "auto"
init_kwargs["include_dashboard"] = False
init_kwargs["configure_logging"] = False
init_kwargs["_temp_dir"] = "/tmp/ray"
print("🌐 Connecting to existing Ray cluster...")
addr_info = ray.init(**init_kwargs)
_extract_dashboard_info_from_init(addr_info)
else:
# Local Ray cluster (may start one if none exists)
# Include current working directory so remote workers can import local modules
local_runtime_env = {"working_dir": os.getcwd()}
# Add required modules for local cluster as well
try:
# Ship the entire project root so local workers import the same code
import agent
import terminal
import utils
local_runtime_env["py_modules"] = [agent, terminal, utils]
# watchfiles contains .so libraries, so it must be installed via pip
local_runtime_env["pip"] = ["watchfiles"]
except ImportError as e:
print(f"Error importing modules: {e}")
pass
init_kwargs["runtime_env"] = local_runtime_env
init_kwargs["include_dashboard"] = False
init_kwargs["configure_logging"] = False
init_kwargs["_temp_dir"] = "/tmp/ray"
print(f"🌐 Connecting to Ray cluster...")
addr_info = ray.init(**init_kwargs)
_extract_dashboard_info_from_init(addr_info)
print("🌐 Ray initialized")
except Exception as e:
raise RuntimeError(f"Failed to initialize Ray: {e}") from e
def get_node_resources(node_info: Dict) -> Dict:
"""Extract useful resource information from node info."""
resources = node_info.get("Resources", {})
return {
"CPU": resources.get("CPU", 0),
"memory": resources.get("memory", 0),
"node_id": node_info.get("NodeID", ""),
"node_ip": node_info.get("NodeManagerAddress", ""),
"alive": node_info.get("Alive", False),
}
def get_head_node_id() -> Optional[str]:
"""Return the head node's NodeID by resolving RAY_ADDRESS host to IP.
Assumes Ray has already been initialized by the caller.
"""
try:
if not ray.is_initialized():
raise RuntimeError(
"Ray must be initialized before calling get_head_node_id()"
)
# Try to derive head IP from RAY_ADDRESS
head_ip: Optional[str] = None
addr = os.environ.get("RAY_ADDRESS")
if addr:
try:
host_port = addr.split("://", 1)[1] if "://" in addr else addr
host = host_port.split(":", 1)[0]
# Resolve hostname to IP if necessary
head_ip = socket.gethostbyname(host)
except Exception:
head_ip = None
node_dicts = [n for n in ray.nodes() if n.get("Alive")]
if not node_dicts:
return None
# Match by IP if we resolved one
if head_ip:
for d in node_dicts:
node_ip = d.get("NodeManagerAddress") or d.get("node_ip")
if node_ip == head_ip:
return d.get("NodeID") or d.get("node_id")
# Fallbacks: flags or first alive node
for d in node_dicts:
if (
d.get("is_head_node")
or d.get("IsHead")
or (
str(d.get("node_type") or d.get("NodeType") or "").lower() == "head"
)
):
return d.get("NodeID") or d.get("node_id")
return node_dicts[0].get("NodeID") or node_dicts[0].get("node_id")
except Exception as e:
print(f"Failed to determine head node: {e}")
raise RuntimeError(f"Failed to determine head node: {e}")
@lru_cache(maxsize=1)
def fetch_cluster_nodes() -> tuple[list[Dict], Optional[str]]:
"""Fetch Ray nodes (no State API) and return (normalized_nodes, head_node_id).
- Assumes Ray has already been initialized by the caller.
- Normalizes each node to keys: 'NodeID', 'NodeManagerAddress', 'Alive', 'Resources'.
- Determines head_node_id from the same list by checking common flags.
"""
if not ray.is_initialized():
raise RuntimeError(
"Ray must be initialized before calling fetch_cluster_nodes()"
)
try:
raw_nodes = [n for n in ray.nodes() if n.get("Alive")]
except Exception as e:
raise RuntimeError(f"Failed to list nodes: {e}") from e
if not raw_nodes:
return [], None
# Detect head, prefer matching RAY_ADDRESS host to IP
head_node_id: Optional[str] = None
head_ip: Optional[str] = None
addr = os.environ.get("RAY_ADDRESS")
if addr:
try:
host_port = addr.split("://", 1)[1] if "://" in addr else addr
host = host_port.split(":", 1)[0]
head_ip = socket.gethostbyname(host)
except Exception:
head_ip = None
if head_ip:
for d in raw_nodes:
node_ip = d.get("NodeManagerAddress") or d.get("node_ip")
if node_ip == head_ip:
head_node_id = d.get("NodeID") or d.get("node_id")
break
# Fallback to flags
for d in raw_nodes:
if head_node_id:
break
if (
d.get("is_head_node")
or d.get("IsHead")
or (str(d.get("node_type") or d.get("NodeType") or "").lower() == "head")
):
head_node_id = d.get("NodeID") or d.get("node_id")
break
nodes: list[Dict] = []
for d in raw_nodes:
node_id = d.get("NodeID") or d.get("node_id")
node_ip = d.get("NodeManagerAddress") or d.get("node_ip")
resources = d.get("Resources") or d.get("resources_total") or {}
nodes.append(
{
"NodeID": node_id,
"NodeManagerAddress": node_ip,
"NodeName": node_ip,
"Alive": True,
"Resources": resources,
}
)
return nodes, head_node_id
# ============ Common helpers for service actors ============
def detect_accessible_ip() -> str:
return ray.util.get_node_ip_address()
def _fallback_detect_accessible_ip() -> str:
"""Determine an accessible IP address without internet calls
or querying the Ray runtime.
Linux: use `ip route get` to extract src IP.
macOS: use `route -n get default` -> `ipconfig getifaddr`.
"""
try:
system = platform.system()
if system == "Darwin":
cmd = (
"IFACE=$(route -n get default 2>/dev/null | awk '/interface:/{print $2}') && "
"ipconfig getifaddr $IFACE"
)
else:
cmd = (
"ip -o -4 route get 192.0.2.1 | "
"awk '{for(i=1;i<=NF;i++) if($i==\"src\"){print $(i+1)}}'"
)
output = subprocess.check_output(
["bash", "-lc", cmd], stderr=subprocess.DEVNULL
)
ip = output.decode().strip().splitlines()[0].strip()
if ip:
return ip
except Exception:
pass
return "127.0.0.1"
def adjust_port_for_macos(requested_port: int, fallback_port: int = 8888) -> int:
"""On macOS, avoid privileged port 80 during development."""
try:
if platform.system() == "Darwin" and int(requested_port) == 80:
return int(fallback_port)
return int(requested_port)
except Exception:
return requested_port
def quote_shell_single(path: str) -> str:
"""Safely single-quote a path for bash -lc string."""
return path.replace("'", "'\"'\"'")
def sanitize_env_for_jupyter(env: dict) -> dict:
"""Remove env variables that would disable auth inadvertently."""
new_env = dict(env)
try:
if new_env.get("JUPYTER_TOKEN", None) in ("", "''", '""'):
new_env.pop("JUPYTER_TOKEN", None)
if new_env.get("JUPYTER_PASSWORD", None) in ("", "''", '""'):
new_env.pop("JUPYTER_PASSWORD", None)
except Exception:
pass
return new_env
# ============ CLI/interactive helpers ============
def is_interactive_command(command: str) -> bool:
"""Heuristic to decide if a command needs an interactive session (stdin).
Includes a curated set of known interactive programs and flag checks.
"""
interactive_programs = {
"python",
"python3",
"node",
"nodejs",
"ruby",
"irb",
"php",
"mysql",
"psql",
"sqlite3",
"redis-cli",
"mongo",
"bc",
"ftp",
"telnet",
"ssh",
"less",
"more",
"top",
"htop",
"vi",
"nano",
"emacs",
"pico",
"bash",
"pip",
"uv",
"jupyter",
"jupyter-lab",
"code-server",
}
cmd_parts = command.strip().split()
if not cmd_parts:
return False
base_cmd = cmd_parts[0].split("/")[-1]
if base_cmd in interactive_programs:
return True
lowered = command.lower()
if ("-i " in lowered) or ("--interactive" in lowered):
return True
return False
def filter_raylet_warnings(text: str) -> str:
"""Filter out noisy raylet file_system_monitor warnings from output text."""
if not text:
return text
raylet_warning_pattern = r"\(raylet\) \[.*?\] \(raylet\) file_system_monitor\.cc.*?Object creation will fail if spilling is required\.\s*"
return re.sub(raylet_warning_pattern, "", text, flags=re.MULTILINE | re.DOTALL)
# ============ Last session preference helpers ============
def _last_session_path() -> str:
return os.path.expanduser("~/.rayssh/last_session.json")
def load_last_session_preferred_ip() -> Optional[str]:
try:
path = _last_session_path()
if not os.path.isfile(path):
return None
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
ip = data.get("node_ip")
return ip if isinstance(ip, str) and ip else None
except Exception:
return None
def write_last_session_node_ip(node_ip: str) -> None:
try:
os.makedirs(os.path.expanduser("~/.rayssh"), exist_ok=True)
payload = {"node_ip": node_ip}
with open(_last_session_path(), "w", encoding="utf-8") as f:
json.dump(payload, f)
except Exception:
pass
def download_code_server_if_needed(os_name: str, arch: str) -> Optional[str]:
"""Download code-server for specified target platform if not cached.
Args:
os_name: 'linux' or 'macos' (code-server naming)
arch: 'amd64' or 'arm64'
Returns:
Path to the downloaded archive, or None if download failed
"""
import urllib.request
import json
import sys
import re
def _find_latest_cached(cache_dir: str) -> Optional[str]:
"""Find the newest cached archive for the given target (by semantic version)."""
try:
if not os.path.isdir(cache_dir):
return None
pattern = re.compile(
rf"^code-server-(\d+\.\d+\.\d+)-{os_name}-{arch}\.tar\.gz$"
)
candidates: list[tuple[tuple[int, int, int], str]] = []
for fname in os.listdir(cache_dir):
m = pattern.match(fname)
if not m:
continue
ver_str = m.group(1)
try:
parts = tuple(int(x) for x in ver_str.split("."))
if len(parts) == 3:
candidates.append((parts, os.path.join(cache_dir, fname)))
except Exception:
continue
if not candidates:
return None
candidates.sort(reverse=True) # highest version first
return candidates[0][1]
except Exception:
return None
try:
cache_dir = os.path.expanduser("~/.rayssh/client_cache")
os.makedirs(cache_dir, exist_ok=True)
# Try to get latest version from GitHub API
version: Optional[str] = None
print("🔍 Fetching latest code-server version for target...")
api_url = "https://api.github.com/repos/coder/code-server/releases/latest"
try:
with urllib.request.urlopen(api_url, timeout=10) as response:
release_data = json.loads(response.read().decode())
tag = release_data.get("tag_name") or release_data.get("name")
if tag:
version = str(tag).lstrip("v")
except Exception as e:
print(f"⚠️ Could not contact GitHub API: {e}")
# If API failed, fall back to the newest cached archive (if any)
if not version:
cached_latest = _find_latest_cached(cache_dir)
if cached_latest and os.path.exists(cached_latest):
fname = os.path.basename(cached_latest)
print(f"✅ Using newest cached code-server archive: {fname}")
return cached_latest
print(
"❌ No cached code-server archive found for target and API is unreachable"
)
return None
filename = f"code-server-{version}-{os_name}-{arch}.tar.gz"
cached_file = os.path.join(cache_dir, filename)
# Use cache if present
if os.path.exists(cached_file):
print(f"✅ Using cached code-server v{version} for {os_name}-{arch}")
return cached_file
# Download with progress
download_url = f"https://github.com/coder/code-server/releases/download/v{version}/{filename}"
print(f"⬇️ Downloading code-server v{version} for {os_name}-{arch}...")
print(f" URL: {download_url}")
def _progress(count, block_size, total_size):
downloaded = count * block_size
if total_size > 0:
pct = min(100, int(downloaded * 100 / total_size))
total_mb = total_size / (1024 * 1024)
done_mb = downloaded / (1024 * 1024)
sys.stdout.write(
f"\r Progress: {done_mb:.1f}/{total_mb:.1f} MB ({pct}%)"
)
else:
done_mb = downloaded / (1024 * 1024)
sys.stdout.write(f"\r Progress: {done_mb:.1f} MB")
sys.stdout.flush()
temp_file = cached_file + ".tmp"
try:
urllib.request.urlretrieve(download_url, temp_file, _progress)
sys.stdout.write("\n")
os.rename(temp_file, cached_file)
print(f"✅ Downloaded code-server to {cached_file}")
return cached_file
except Exception as e:
# On download failure, fall back to newest cached if available
print(f"⚠️ Download failed: {e}")
try:
if os.path.exists(temp_file):
os.remove(temp_file)
except Exception:
pass
cached_latest = _find_latest_cached(cache_dir)
if cached_latest and os.path.exists(cached_latest):
fname = os.path.basename(cached_latest)
print(f"✅ Falling back to newest cached archive: {fname}")
return cached_latest
print("❌ No cached archive available to fall back to")
return None
except Exception as e:
print(f"❌ Error preparing code-server: {e}")
return None
def get_ray_dashboard_info() -> dict:
"""
Extract Ray dashboard information from the Ray context.
Returns:
dict: Contains 'dashboard_url', 'host', and 'port' keys if available.
Returns empty dict if no dashboard info is available.
"""
import ray
dashboard_info = {"dashboard_url": None, "host": None, "port": None}
# Prefer the dashboard URL obtained from ensure_ray_initialized()
try:
global _LAST_RAY_ADDRESS_INFO, _LAST_RAY_DASHBOARD_URL
dash = _LAST_RAY_DASHBOARD_URL
if not dash and isinstance(_LAST_RAY_ADDRESS_INFO, dict):
dash = _LAST_RAY_ADDRESS_INFO.get("webui_url") or (
(_LAST_RAY_ADDRESS_INFO.get("address_info") or {}).get("webui_url")
if isinstance(_LAST_RAY_ADDRESS_INFO.get("address_info"), dict)
else None