utils.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  1. import contextlib
  2. import importlib
  3. import json
  4. import logging
  5. import multiprocessing
  6. import os
  7. import platform
  8. import re
  9. import signal
  10. import subprocess
  11. import sys
  12. import threading
  13. import time
  14. from collections import defaultdict
  15. from pathlib import Path
  16. from subprocess import list2cmdline
  17. from typing import (
  18. TYPE_CHECKING,
  19. Dict,
  20. List,
  21. Mapping,
  22. Optional,
  23. Tuple,
  24. Union,
  25. )
  26. from google.protobuf import json_format
  27. import ray
  28. import ray._private.ray_constants as ray_constants
  29. from ray._common.utils import (
  30. PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME,
  31. get_ray_address_file,
  32. get_system_memory,
  33. )
  34. from ray.core.generated.runtime_environment_pb2 import (
  35. RuntimeEnvInfo as ProtoRuntimeEnvInfo,
  36. )
  37. # Import psutil after ray so the packaged version is used.
  38. import psutil
  39. if TYPE_CHECKING:
  40. from ray.runtime_env import RuntimeEnv
  41. INT32_MAX = (2**31) - 1
  42. pwd = None
  43. if sys.platform != "win32":
  44. import pwd
  45. logger = logging.getLogger(__name__)
  46. # Linux can bind child processes' lifetimes to that of their parents via prctl.
  47. # prctl support is detected dynamically once, and assumed thereafter.
  48. linux_prctl = None
  49. # Windows can bind processes' lifetimes to that of kernel-level "job objects".
  50. # We keep a global job object to tie its lifetime to that of our own process.
  51. win32_job = None
  52. win32_AssignProcessToJobObject = None
  53. ENV_DISABLE_DOCKER_CPU_WARNING = "RAY_DISABLE_DOCKER_CPU_WARNING" in os.environ
  54. # This global variable is used for testing only
  55. _CALLED_FREQ = defaultdict(lambda: 0)
  56. _CALLED_FREQ_LOCK = threading.Lock()
  57. PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN = re.compile(
  58. r"(.+)_group_(\d+)_([0-9a-zA-Z]+)"
  59. )
  60. PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN = re.compile(r"(.+)_group_([0-9a-zA-Z]+)")
  61. def write_ray_address(ray_address: str, temp_dir: Optional[str] = None):
  62. address_file = get_ray_address_file(temp_dir)
  63. if os.path.exists(address_file):
  64. with open(address_file, "r") as f:
  65. prev_address = f.read()
  66. if prev_address == ray_address:
  67. return
  68. logger.info(
  69. f"Overwriting previous Ray address ({prev_address}). "
  70. "Running ray.init() on this node will now connect to the new "
  71. f"instance at {ray_address}. To override this behavior, pass "
  72. f"address={prev_address} to ray.init()."
  73. )
  74. with open(address_file, "w+") as f:
  75. f.write(ray_address)
  76. def read_ray_address(temp_dir: Optional[str] = None) -> str:
  77. address_file = get_ray_address_file(temp_dir)
  78. if not os.path.exists(address_file):
  79. return None
  80. with open(address_file, "r") as f:
  81. return f.read().strip()
  82. def format_error_message(exception_message: str, task_exception: bool = False):
  83. """Improve the formatting of an exception thrown by a remote function.
  84. This method takes a traceback from an exception and makes it nicer by
  85. removing a few uninformative lines and adding some space to indent the
  86. remaining lines nicely.
  87. Args:
  88. exception_message: A message generated by traceback.format_exc().
  89. Returns:
  90. A string of the formatted exception message.
  91. """
  92. lines = exception_message.split("\n")
  93. if task_exception:
  94. # For errors that occur inside of tasks, remove lines 1 and 2 which are
  95. # always the same, they just contain information about the worker code.
  96. lines = lines[0:1] + lines[3:]
  97. pass
  98. return "\n".join(lines)
  99. def push_error_to_driver(
  100. worker, error_type: str, message: str, job_id: Optional[str] = None
  101. ):
  102. """Push an error message to the driver to be printed in the background.
  103. Args:
  104. worker: The worker to use.
  105. error_type: The type of the error.
  106. message: The message that will be printed in the background
  107. on the driver.
  108. job_id: The ID of the driver to push the error message to. If this
  109. is None, then the message will be pushed to all drivers.
  110. """
  111. if job_id is None:
  112. job_id = ray.JobID.nil()
  113. assert isinstance(job_id, ray.JobID)
  114. worker.core_worker.push_error(job_id, error_type, message, time.time())
  115. def publish_error_to_driver(
  116. error_type: str,
  117. message: str,
  118. gcs_client,
  119. job_id=None,
  120. ):
  121. """Push an error message to the driver to be printed in the background.
  122. Normally the push_error_to_driver function should be used. However, in some
  123. instances, the raylet client is not available, e.g., because the
  124. error happens in Python before the driver or worker has connected to the
  125. backend processes.
  126. Args:
  127. error_type: The type of the error.
  128. message: The message that will be printed in the background
  129. on the driver.
  130. gcs_client: The GCS client to use.
  131. job_id: The ID of the driver to push the error message to. If this
  132. is None, then the message will be pushed to all drivers.
  133. """
  134. if job_id is None:
  135. job_id = ray.JobID.nil()
  136. assert isinstance(job_id, ray.JobID)
  137. try:
  138. gcs_client.publish_error(job_id.hex().encode(), error_type, message, job_id, 60)
  139. except Exception:
  140. logger.exception(f"Failed to publish error: {message} [type {error_type}]")
  141. def ensure_str(s, encoding="utf-8", errors="strict"):
  142. """Coerce *s* to `str`.
  143. - `str` -> `str`
  144. - `bytes` -> decoded to `str`
  145. """
  146. if isinstance(s, str):
  147. return s
  148. else:
  149. assert isinstance(s, bytes), f"Expected str or bytes, got {type(s)}"
  150. return s.decode(encoding, errors)
  151. def binary_to_object_ref(binary_object_ref):
  152. return ray.ObjectRef(binary_object_ref)
  153. def binary_to_task_id(binary_task_id):
  154. return ray.TaskID(binary_task_id)
  155. # TODO(qwang): Remove these hepler functions
  156. # once we separate `WorkerID` from `UniqueID`.
  157. def compute_job_id_from_driver(driver_id):
  158. assert isinstance(driver_id, ray.WorkerID)
  159. return ray.JobID(driver_id.binary()[0 : ray.JobID.size()])
  160. def compute_driver_id_from_job(job_id):
  161. assert isinstance(job_id, ray.JobID)
  162. rest_length = ray_constants.ID_SIZE - job_id.size()
  163. driver_id_str = job_id.binary() + (rest_length * b"\xff")
  164. return ray.WorkerID(driver_id_str)
  165. def get_visible_accelerator_ids() -> Mapping[str, Optional[List[str]]]:
  166. """Get the mapping from accelerator resource name
  167. to the visible ids."""
  168. from ray._private.accelerators import (
  169. get_accelerator_manager_for_resource,
  170. get_all_accelerator_resource_names,
  171. )
  172. return {
  173. accelerator_resource_name: get_accelerator_manager_for_resource(
  174. accelerator_resource_name
  175. ).get_current_process_visible_accelerator_ids()
  176. for accelerator_resource_name in get_all_accelerator_resource_names()
  177. }
  178. def set_omp_num_threads_if_unset() -> bool:
  179. """Set the OMP_NUM_THREADS to default to num cpus assigned to the worker
  180. This function sets the environment variable OMP_NUM_THREADS for the worker,
  181. if the env is not previously set and it's running in worker (WORKER_MODE).
  182. Returns True if OMP_NUM_THREADS is set in this function.
  183. """
  184. num_threads_from_env = os.environ.get("OMP_NUM_THREADS")
  185. if num_threads_from_env is not None:
  186. # No ops if it's set
  187. return False
  188. # If unset, try setting the correct CPU count assigned.
  189. runtime_ctx = ray.get_runtime_context()
  190. if runtime_ctx.worker.mode != ray._private.worker.WORKER_MODE:
  191. # Non worker mode, no ops.
  192. return False
  193. num_assigned_cpus = runtime_ctx.get_assigned_resources().get("CPU")
  194. if num_assigned_cpus is None:
  195. # This is an actor task w/o any num_cpus specified, set it to 1
  196. logger.debug(
  197. "[ray] Forcing OMP_NUM_THREADS=1 to avoid performance "
  198. "degradation with many workers (issue #6998). You can override this "
  199. "by explicitly setting OMP_NUM_THREADS, or changing num_cpus."
  200. )
  201. num_assigned_cpus = 1
  202. import math
  203. # For num_cpu < 1: Set to 1.
  204. # For num_cpus >= 1: Set to the floor of the actual assigned cpus.
  205. omp_num_threads = max(math.floor(num_assigned_cpus), 1)
  206. os.environ["OMP_NUM_THREADS"] = str(omp_num_threads)
  207. return True
  208. def set_visible_accelerator_ids() -> Mapping[str, Optional[str]]:
  209. """Set (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, HIP_VISIBLE_DEVICES,
  210. NEURON_RT_VISIBLE_CORES, TPU_VISIBLE_CHIPS , HABANA_VISIBLE_MODULES ,...)
  211. environment variables based on the accelerator runtime. Return the original
  212. environment variables.
  213. """
  214. from ray._private.ray_constants import env_bool
  215. original_visible_accelerator_env_vars = {}
  216. override_on_zero = env_bool(
  217. ray._private.accelerators.RAY_ACCEL_ENV_VAR_OVERRIDE_ON_ZERO_ENV_VAR,
  218. True,
  219. )
  220. for resource_name, accelerator_ids in (
  221. ray.get_runtime_context().get_accelerator_ids().items()
  222. ):
  223. # If no accelerator ids are set, skip overriding the environment variable.
  224. if not override_on_zero and len(accelerator_ids) == 0:
  225. continue
  226. env_var = ray._private.accelerators.get_accelerator_manager_for_resource(
  227. resource_name
  228. ).get_visible_accelerator_ids_env_var()
  229. original_visible_accelerator_env_vars[env_var] = os.environ.get(env_var, None)
  230. ray._private.accelerators.get_accelerator_manager_for_resource(
  231. resource_name
  232. ).set_current_process_visible_accelerator_ids(accelerator_ids)
  233. return original_visible_accelerator_env_vars
  234. def reset_visible_accelerator_env_vars(
  235. original_visible_accelerator_env_vars: Mapping[str, Optional[str]]
  236. ) -> None:
  237. """Reset the visible accelerator env vars to the original values."""
  238. for env_var, env_value in original_visible_accelerator_env_vars.items():
  239. if env_value is None:
  240. os.environ.pop(env_var, None)
  241. else:
  242. os.environ[env_var] = env_value
  243. class Unbuffered(object):
  244. """There's no "built-in" solution to programatically disabling buffering of
  245. text files. Ray expects stdout/err to be text files, so creating an
  246. unbuffered binary file is unacceptable.
  247. See
  248. https://mail.python.org/pipermail/tutor/2003-November/026645.html.
  249. https://docs.python.org/3/library/functions.html#open
  250. """
  251. def __init__(self, stream):
  252. self.stream = stream
  253. def write(self, data):
  254. self.stream.write(data)
  255. self.stream.flush()
  256. def writelines(self, datas):
  257. self.stream.writelines(datas)
  258. self.stream.flush()
  259. def __getattr__(self, attr):
  260. # Avoid endless loop when get `stream` attribute
  261. if attr == "stream":
  262. return super().__getattribute__("stream")
  263. return getattr(self.stream, attr)
  264. def open_log(path, unbuffered=False, **kwargs):
  265. """
  266. Opens the log file at `path`, with the provided kwargs being given to
  267. `open`.
  268. """
  269. # Disable buffering, see test_advanced_3.py::test_logging_to_driver
  270. kwargs.setdefault("buffering", 1)
  271. kwargs.setdefault("mode", "a")
  272. kwargs.setdefault("encoding", "utf-8")
  273. stream = open(path, **kwargs)
  274. if unbuffered:
  275. return Unbuffered(stream)
  276. else:
  277. return stream
  278. def _get_docker_cpus(
  279. cpu_quota_file_name="/sys/fs/cgroup/cpu/cpu.cfs_quota_us",
  280. cpu_period_file_name="/sys/fs/cgroup/cpu/cpu.cfs_period_us",
  281. cpuset_file_name="/sys/fs/cgroup/cpuset/cpuset.cpus",
  282. cpu_max_file_name="/sys/fs/cgroup/cpu.max",
  283. ) -> Optional[float]:
  284. # TODO (Alex): Don't implement this logic oursleves.
  285. # Docker has 2 underyling ways of implementing CPU limits:
  286. # https://docs.docker.com/config/containers/resource_constraints/#configure-the-default-cfs-scheduler
  287. # 1. --cpuset-cpus 2. --cpus or --cpu-quota/--cpu-period (--cpu-shares is a
  288. # soft limit so we don't worry about it). For Ray's purposes, if we use
  289. # docker, the number of vCPUs on a machine is whichever is set (ties broken
  290. # by smaller value).
  291. cpu_quota = None
  292. # See: https://bugs.openjdk.java.net/browse/JDK-8146115
  293. if os.path.exists(cpu_quota_file_name) and os.path.exists(cpu_period_file_name):
  294. try:
  295. with (
  296. open(cpu_quota_file_name, "r") as quota_file,
  297. open(cpu_period_file_name, "r") as period_file,
  298. ):
  299. cpu_quota = float(quota_file.read()) / float(period_file.read())
  300. except Exception:
  301. logger.exception("Unexpected error calculating docker cpu quota.")
  302. # Look at cpu.max for cgroups v2
  303. elif os.path.exists(cpu_max_file_name):
  304. try:
  305. max_file = open(cpu_max_file_name).read()
  306. quota_str, period_str = max_file.split()
  307. if quota_str.isnumeric() and period_str.isnumeric():
  308. cpu_quota = float(quota_str) / float(period_str)
  309. else:
  310. # quota_str is "max" meaning the cpu quota is unset
  311. cpu_quota = None
  312. except Exception:
  313. logger.exception("Unexpected error calculating docker cpu quota.")
  314. if (cpu_quota is not None) and (cpu_quota < 0):
  315. cpu_quota = None
  316. elif cpu_quota == 0:
  317. # Round up in case the cpu limit is less than 1.
  318. cpu_quota = 1
  319. cpuset_num = None
  320. if os.path.exists(cpuset_file_name):
  321. try:
  322. with open(cpuset_file_name) as cpuset_file:
  323. ranges_as_string = cpuset_file.read()
  324. ranges = ranges_as_string.split(",")
  325. cpu_ids = []
  326. for num_or_range in ranges:
  327. if "-" in num_or_range:
  328. start, end = num_or_range.split("-")
  329. cpu_ids.extend(list(range(int(start), int(end) + 1)))
  330. else:
  331. cpu_ids.append(int(num_or_range))
  332. cpuset_num = len(cpu_ids)
  333. except Exception:
  334. logger.exception("Unexpected error calculating docker cpuset ids.")
  335. # Possible to-do: Parse cgroups v2's cpuset.cpus.effective for the number
  336. # of accessible CPUs.
  337. if cpu_quota and cpuset_num:
  338. return min(cpu_quota, cpuset_num)
  339. return cpu_quota or cpuset_num
  340. def get_num_cpus(
  341. override_docker_cpu_warning: bool = ENV_DISABLE_DOCKER_CPU_WARNING,
  342. truncate: bool = True,
  343. ) -> float:
  344. """
  345. Get the number of CPUs available on this node.
  346. Depending on the situation, use multiprocessing.cpu_count() or cgroups.
  347. Args:
  348. override_docker_cpu_warning: An extra flag to explicitly turn off the Docker
  349. warning. Setting this flag True has the same effect as setting the env
  350. RAY_DISABLE_DOCKER_CPU_WARNING. By default, whether or not to log
  351. the warning is determined by the env variable
  352. RAY_DISABLE_DOCKER_CPU_WARNING.
  353. truncate: truncates the return value and drops the decimal part.
  354. """
  355. cpu_count = multiprocessing.cpu_count()
  356. if os.environ.get("RAY_USE_MULTIPROCESSING_CPU_COUNT"):
  357. logger.info(
  358. "Detected RAY_USE_MULTIPROCESSING_CPU_COUNT=1: Using "
  359. "multiprocessing.cpu_count() to detect the number of CPUs. "
  360. "This may be inconsistent when used inside docker. "
  361. "To correctly detect CPUs, unset the env var: "
  362. "`RAY_USE_MULTIPROCESSING_CPU_COUNT`."
  363. )
  364. return cpu_count
  365. try:
  366. # Not easy to get cpu count in docker, see:
  367. # https://bugs.python.org/issue36054
  368. docker_count = _get_docker_cpus()
  369. if docker_count is not None and docker_count != cpu_count:
  370. # Don't log this warning if we're on K8s or if the warning is
  371. # explicitly disabled.
  372. if (
  373. "KUBERNETES_SERVICE_HOST" not in os.environ
  374. and not ENV_DISABLE_DOCKER_CPU_WARNING
  375. and not override_docker_cpu_warning
  376. ):
  377. logger.warning(
  378. "Detecting docker specified CPUs. In "
  379. "previous versions of Ray, CPU detection in containers "
  380. "was incorrect. Please ensure that Ray has enough CPUs "
  381. "allocated. As a temporary workaround to revert to the "
  382. "prior behavior, set "
  383. "`RAY_USE_MULTIPROCESSING_CPU_COUNT=1` as an env var "
  384. "before starting Ray. Set the env var: "
  385. "`RAY_DISABLE_DOCKER_CPU_WARNING=1` to mute this warning."
  386. )
  387. # TODO (Alex): We should probably add support for fractional cpus.
  388. if int(docker_count) != float(docker_count):
  389. logger.warning(
  390. f"Ray currently does not support initializing Ray "
  391. f"with fractional cpus. Your num_cpus will be "
  392. f"truncated from {docker_count} to "
  393. f"{int(docker_count)}."
  394. )
  395. if truncate:
  396. docker_count = int(docker_count)
  397. cpu_count = docker_count
  398. except Exception:
  399. # `nproc` and cgroup are linux-only. If docker only works on linux
  400. # (will run in a linux VM on other platforms), so this is fine.
  401. pass
  402. return cpu_count
  403. # TODO(clarng): merge code with c++
  404. def get_cgroup_used_memory(
  405. memory_stat_filename: str,
  406. memory_usage_filename: str,
  407. inactive_file_key: str,
  408. active_file_key: str,
  409. ):
  410. """
  411. The calculation logic is the same with `GetCGroupMemoryUsedBytes`
  412. in `memory_monitor.cc` file.
  413. """
  414. inactive_file_bytes = -1
  415. active_file_bytes = -1
  416. with open(memory_stat_filename, "r") as f:
  417. lines = f.readlines()
  418. for line in lines:
  419. if f"{inactive_file_key} " in line:
  420. inactive_file_bytes = int(line.split()[1])
  421. elif f"{active_file_key} " in line:
  422. active_file_bytes = int(line.split()[1])
  423. with open(memory_usage_filename, "r") as f:
  424. lines = f.readlines()
  425. cgroup_usage_in_bytes = int(lines[0].strip())
  426. if (
  427. inactive_file_bytes == -1
  428. or cgroup_usage_in_bytes == -1
  429. or active_file_bytes == -1
  430. ):
  431. return None
  432. return cgroup_usage_in_bytes - inactive_file_bytes - active_file_bytes
  433. def resolve_object_store_memory(
  434. available_memory_bytes: int,
  435. object_store_memory: Optional[int] = None,
  436. ) -> int:
  437. """Resolve the object store memory size.
  438. This function determines the appropriate object store memory size based on
  439. the provided value or calculates a default based on available system memory.
  440. Args:
  441. available_memory_bytes: The memory available for this node.
  442. object_store_memory: The user-specified object store memory size in bytes.
  443. If None, a default size will be calculated.
  444. Returns:
  445. The resolved object store memory size in bytes.
  446. """
  447. # Derive default object store memory if not specified
  448. if object_store_memory is None:
  449. object_store_memory_cap = ray_constants.DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES
  450. # Cap by shm size by default to avoid low performance, but don't
  451. # go lower than REQUIRE_SHM_SIZE_THRESHOLD.
  452. if sys.platform == "linux" or sys.platform == "linux2":
  453. # Multiple by 0.95 to give a bit of wiggle-room.
  454. # https://github.com/ray-project/ray/pull/23034/files
  455. shm_avail = get_shared_memory_bytes() * 0.95
  456. shm_cap = max(ray_constants.REQUIRE_SHM_SIZE_THRESHOLD, shm_avail)
  457. object_store_memory_cap = min(object_store_memory_cap, shm_cap)
  458. object_store_memory = int(
  459. available_memory_bytes
  460. * ray_constants.DEFAULT_OBJECT_STORE_MEMORY_PROPORTION
  461. )
  462. # Set the object_store_memory size to 2GB on Mac
  463. # to avoid degraded performance.
  464. # (https://github.com/ray-project/ray/issues/20388)
  465. if sys.platform == "darwin":
  466. object_store_memory = min(
  467. object_store_memory, ray_constants.MAC_DEGRADED_PERF_MMAP_SIZE_LIMIT
  468. )
  469. # Cap memory to avoid memory waste and perf issues on large nodes
  470. if object_store_memory > object_store_memory_cap:
  471. logger.debug(
  472. "Warning: Capping object memory store to {}GB. ".format(
  473. object_store_memory_cap // 1e9
  474. )
  475. + "To increase this further, specify `object_store_memory` "
  476. "when calling ray.init() or ray start."
  477. )
  478. object_store_memory = object_store_memory_cap
  479. return object_store_memory
  480. def get_used_memory():
  481. """Return the currently used system memory in bytes
  482. Returns:
  483. The total amount of used memory
  484. """
  485. # Try to accurately figure out the memory usage if we are in a docker
  486. # container.
  487. docker_usage = None
  488. # For cgroups v1:
  489. memory_usage_filename_v1 = "/sys/fs/cgroup/memory/memory.usage_in_bytes"
  490. memory_stat_filename_v1 = "/sys/fs/cgroup/memory/memory.stat"
  491. # For cgroups v2:
  492. memory_usage_filename_v2 = "/sys/fs/cgroup/memory.current"
  493. memory_stat_filename_v2 = "/sys/fs/cgroup/memory.stat"
  494. if os.path.exists(memory_usage_filename_v1) and os.path.exists(
  495. memory_stat_filename_v1
  496. ):
  497. docker_usage = get_cgroup_used_memory(
  498. memory_stat_filename_v1,
  499. memory_usage_filename_v1,
  500. "total_inactive_file",
  501. "total_active_file",
  502. )
  503. elif os.path.exists(memory_usage_filename_v2) and os.path.exists(
  504. memory_stat_filename_v2
  505. ):
  506. docker_usage = get_cgroup_used_memory(
  507. memory_stat_filename_v2,
  508. memory_usage_filename_v2,
  509. "inactive_file",
  510. "active_file",
  511. )
  512. if docker_usage is not None:
  513. return docker_usage
  514. return psutil.virtual_memory().used
  515. def estimate_available_memory():
  516. """Return the currently available amount of system memory in bytes.
  517. Returns:
  518. The total amount of available memory in bytes. Based on the used
  519. and total memory.
  520. """
  521. return get_system_memory() - get_used_memory()
  522. def get_shared_memory_bytes():
  523. """Get the size of the shared memory file system.
  524. Returns:
  525. The size of the shared memory file system in bytes.
  526. """
  527. # Make sure this is only called on Linux.
  528. assert sys.platform == "linux" or sys.platform == "linux2"
  529. shm_fd = os.open("/dev/shm", os.O_RDONLY)
  530. try:
  531. shm_fs_stats = os.fstatvfs(shm_fd)
  532. # The value shm_fs_stats.f_bsize is the block size and the
  533. # value shm_fs_stats.f_bavail is the number of available
  534. # blocks.
  535. shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail
  536. finally:
  537. os.close(shm_fd)
  538. return shm_avail
  539. def check_oversized_function(
  540. pickled: bytes, name: str, obj_type: str, worker: "ray.Worker"
  541. ) -> None:
  542. """Send a warning message if the pickled function is too large.
  543. Args:
  544. pickled: the pickled function.
  545. name: name of the pickled object.
  546. obj_type: type of the pickled object, can be 'function',
  547. 'remote function', or 'actor'.
  548. worker: the worker used to send warning message. message will be logged
  549. locally if None.
  550. """
  551. length = len(pickled)
  552. if length <= ray_constants.FUNCTION_SIZE_WARN_THRESHOLD:
  553. return
  554. elif length < ray_constants.FUNCTION_SIZE_ERROR_THRESHOLD:
  555. warning_message = (
  556. "The {} {} is very large ({} MiB). "
  557. "Check that its definition is not implicitly capturing a large "
  558. "array or other object in scope. Tip: use ray.put() to put large "
  559. "objects in the Ray object store."
  560. ).format(obj_type, name, length // (1024 * 1024))
  561. if worker:
  562. push_error_to_driver(
  563. worker,
  564. ray_constants.PICKLING_LARGE_OBJECT_PUSH_ERROR,
  565. "Warning: " + warning_message,
  566. job_id=worker.current_job_id,
  567. )
  568. else:
  569. error = (
  570. "The {} {} is too large ({} MiB > FUNCTION_SIZE_ERROR_THRESHOLD={}"
  571. " MiB). Check that its definition is not implicitly capturing a "
  572. "large array or other object in scope. Tip: use ray.put() to "
  573. "put large objects in the Ray object store."
  574. ).format(
  575. obj_type,
  576. name,
  577. length // (1024 * 1024),
  578. ray_constants.FUNCTION_SIZE_ERROR_THRESHOLD // (1024 * 1024),
  579. )
  580. raise ValueError(error)
  581. def is_main_thread():
  582. return threading.current_thread().getName() == "MainThread"
  583. def detect_fate_sharing_support_win32():
  584. global win32_job, win32_AssignProcessToJobObject
  585. if win32_job is None and sys.platform == "win32":
  586. import ctypes
  587. try:
  588. from ctypes.wintypes import BOOL, DWORD, HANDLE, LPCWSTR, LPVOID
  589. kernel32 = ctypes.WinDLL("kernel32")
  590. kernel32.CreateJobObjectW.argtypes = (LPVOID, LPCWSTR)
  591. kernel32.CreateJobObjectW.restype = HANDLE
  592. sijo_argtypes = (HANDLE, ctypes.c_int, LPVOID, DWORD)
  593. kernel32.SetInformationJobObject.argtypes = sijo_argtypes
  594. kernel32.SetInformationJobObject.restype = BOOL
  595. kernel32.AssignProcessToJobObject.argtypes = (HANDLE, HANDLE)
  596. kernel32.AssignProcessToJobObject.restype = BOOL
  597. kernel32.IsDebuggerPresent.argtypes = ()
  598. kernel32.IsDebuggerPresent.restype = BOOL
  599. except (AttributeError, TypeError, ImportError):
  600. kernel32 = None
  601. job = kernel32.CreateJobObjectW(None, None) if kernel32 else None
  602. job = subprocess.Handle(job) if job else job
  603. if job:
  604. from ctypes.wintypes import DWORD, LARGE_INTEGER, ULARGE_INTEGER
  605. class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
  606. _fields_ = [
  607. ("PerProcessUserTimeLimit", LARGE_INTEGER),
  608. ("PerJobUserTimeLimit", LARGE_INTEGER),
  609. ("LimitFlags", DWORD),
  610. ("MinimumWorkingSetSize", ctypes.c_size_t),
  611. ("MaximumWorkingSetSize", ctypes.c_size_t),
  612. ("ActiveProcessLimit", DWORD),
  613. ("Affinity", ctypes.c_size_t),
  614. ("PriorityClass", DWORD),
  615. ("SchedulingClass", DWORD),
  616. ]
  617. class IO_COUNTERS(ctypes.Structure):
  618. _fields_ = [
  619. ("ReadOperationCount", ULARGE_INTEGER),
  620. ("WriteOperationCount", ULARGE_INTEGER),
  621. ("OtherOperationCount", ULARGE_INTEGER),
  622. ("ReadTransferCount", ULARGE_INTEGER),
  623. ("WriteTransferCount", ULARGE_INTEGER),
  624. ("OtherTransferCount", ULARGE_INTEGER),
  625. ]
  626. class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
  627. _fields_ = [
  628. ("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),
  629. ("IoInfo", IO_COUNTERS),
  630. ("ProcessMemoryLimit", ctypes.c_size_t),
  631. ("JobMemoryLimit", ctypes.c_size_t),
  632. ("PeakProcessMemoryUsed", ctypes.c_size_t),
  633. ("PeakJobMemoryUsed", ctypes.c_size_t),
  634. ]
  635. debug = kernel32.IsDebuggerPresent()
  636. # Defined in <WinNT.h>; also available here:
  637. # https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/nf-jobapi2-setinformationjobobject
  638. JobObjectExtendedLimitInformation = 9
  639. JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800
  640. JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = 0x00000400
  641. JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
  642. buf = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
  643. buf.BasicLimitInformation.LimitFlags = (
  644. (0 if debug else JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE)
  645. | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION
  646. | JOB_OBJECT_LIMIT_BREAKAWAY_OK
  647. )
  648. infoclass = JobObjectExtendedLimitInformation
  649. if not kernel32.SetInformationJobObject(
  650. job, infoclass, ctypes.byref(buf), ctypes.sizeof(buf)
  651. ):
  652. job = None
  653. win32_AssignProcessToJobObject = (
  654. kernel32.AssignProcessToJobObject if kernel32 is not None else False
  655. )
  656. win32_job = job if job else False
  657. return bool(win32_job)
  658. def detect_fate_sharing_support_linux():
  659. global linux_prctl
  660. if linux_prctl is None and sys.platform.startswith("linux"):
  661. try:
  662. from ctypes import CDLL, c_int, c_ulong
  663. prctl = CDLL(None).prctl
  664. prctl.restype = c_int
  665. prctl.argtypes = [c_int, c_ulong, c_ulong, c_ulong, c_ulong]
  666. except (AttributeError, TypeError):
  667. prctl = None
  668. linux_prctl = prctl if prctl else False
  669. return bool(linux_prctl)
  670. def detect_fate_sharing_support():
  671. result = None
  672. if sys.platform == "win32":
  673. result = detect_fate_sharing_support_win32()
  674. elif sys.platform.startswith("linux"):
  675. result = detect_fate_sharing_support_linux()
  676. return result
  677. def set_kill_on_parent_death_linux():
  678. """Ensures this process dies if its parent dies (fate-sharing).
  679. Linux-only. Must be called in preexec_fn (i.e. by the child).
  680. """
  681. if detect_fate_sharing_support_linux():
  682. import signal
  683. PR_SET_PDEATHSIG = 1
  684. if linux_prctl(PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0) != 0:
  685. import ctypes
  686. raise OSError(ctypes.get_errno(), "prctl(PR_SET_PDEATHSIG) failed")
  687. else:
  688. assert False, "PR_SET_PDEATHSIG used despite being unavailable"
  689. def set_kill_child_on_death_win32(child_proc):
  690. """Ensures the child process dies if this process dies (fate-sharing).
  691. Windows-only. Must be called by the parent, after spawning the child.
  692. Args:
  693. child_proc: The subprocess.Popen or subprocess.Handle object.
  694. """
  695. if isinstance(child_proc, subprocess.Popen):
  696. child_proc = child_proc._handle
  697. assert isinstance(child_proc, subprocess.Handle)
  698. if detect_fate_sharing_support_win32():
  699. if not win32_AssignProcessToJobObject(win32_job, int(child_proc)):
  700. import ctypes
  701. raise OSError(ctypes.get_last_error(), "AssignProcessToJobObject() failed")
  702. else:
  703. assert False, "AssignProcessToJobObject used despite being unavailable"
  704. def set_sigterm_handler(sigterm_handler):
  705. """Registers a handler for SIGTERM in a platform-compatible manner."""
  706. if sys.platform == "win32":
  707. # Note that these signal handlers only work for console applications.
  708. # TODO(mehrdadn): implement graceful process termination mechanism
  709. # SIGINT is Ctrl+C, SIGBREAK is Ctrl+Break.
  710. signal.signal(signal.SIGBREAK, sigterm_handler)
  711. else:
  712. signal.signal(signal.SIGTERM, sigterm_handler)
  713. def try_to_symlink(symlink_path, target_path):
  714. """Attempt to create a symlink.
  715. If the symlink path exists and isn't a symlink, the symlink will not be
  716. created. If a symlink exists in the path, it will be attempted to be
  717. removed and replaced.
  718. Args:
  719. symlink_path: The path at which to create the symlink.
  720. target_path: The path the symlink should point to.
  721. """
  722. symlink_path = os.path.expanduser(symlink_path)
  723. target_path = os.path.expanduser(target_path)
  724. if os.path.exists(symlink_path):
  725. if os.path.islink(symlink_path):
  726. # Try to remove existing symlink.
  727. try:
  728. os.remove(symlink_path)
  729. except OSError:
  730. return
  731. else:
  732. # There's an existing non-symlink file, don't overwrite it.
  733. return
  734. try:
  735. os.symlink(target_path, symlink_path)
  736. except OSError:
  737. return
  738. def get_user():
  739. if pwd is None:
  740. return ""
  741. try:
  742. return pwd.getpwuid(os.getuid()).pw_name
  743. except Exception:
  744. return ""
  745. def get_conda_bin_executable(executable_name):
  746. """
  747. Return path to the specified executable, assumed to be discoverable within
  748. the 'bin' subdirectory of a conda installation. Adapted from
  749. https://github.com/mlflow/mlflow.
  750. """
  751. # Use CONDA_EXE as per https://github.com/conda/conda/issues/7126
  752. if "CONDA_EXE" in os.environ:
  753. conda_bin_dir = os.path.dirname(os.environ["CONDA_EXE"])
  754. return os.path.join(conda_bin_dir, executable_name)
  755. return executable_name
  756. def get_conda_env_dir(env_name):
  757. """Find and validate the conda directory for a given conda environment.
  758. For example, given the environment name `tf1`, this function checks
  759. the existence of the corresponding conda directory, e.g.
  760. `/Users/scaly/anaconda3/envs/tf1`, and returns it.
  761. """
  762. conda_prefix = os.environ.get("CONDA_PREFIX")
  763. if conda_prefix is None:
  764. # The caller is neither in a conda env or in (base) env. This is rare
  765. # because by default, new terminals start in (base), but we can still
  766. # support this case.
  767. conda_exe = os.environ.get("CONDA_EXE")
  768. if conda_exe is None:
  769. raise ValueError(
  770. "Cannot find environment variables set by conda. "
  771. "Please verify conda is installed."
  772. )
  773. # Example: CONDA_EXE=$HOME/anaconda3/bin/python
  774. # Strip out /bin/python by going up two parent directories.
  775. conda_prefix = str(Path(conda_exe).parent.parent)
  776. # There are two cases:
  777. # 1. We are in a conda (base) env: CONDA_DEFAULT_ENV=base and
  778. # CONDA_PREFIX=$HOME/anaconda3
  779. # 2. We are in a user-created conda env: CONDA_DEFAULT_ENV=$env_name and
  780. # CONDA_PREFIX=$HOME/anaconda3/envs/$current_env_name
  781. if os.environ.get("CONDA_DEFAULT_ENV") == "base":
  782. # Caller's curent environment is (base).
  783. # Not recommended by conda, but we can still support it.
  784. if env_name == "base":
  785. # Desired environment is (base), located at e.g. $HOME/anaconda3
  786. env_dir = conda_prefix
  787. else:
  788. # Desired environment is user-created, e.g.
  789. # $HOME/anaconda3/envs/$env_name
  790. env_dir = os.path.join(conda_prefix, "envs", env_name)
  791. else:
  792. # Now `conda_prefix` should be something like
  793. # $HOME/anaconda3/envs/$current_env_name
  794. # We want to replace the last component with the desired env name.
  795. conda_envs_dir = os.path.split(conda_prefix)[0]
  796. env_dir = os.path.join(conda_envs_dir, env_name)
  797. if not os.path.isdir(env_dir):
  798. raise ValueError(
  799. "conda env "
  800. + env_name
  801. + " not found in conda envs directory. Run `conda env list` to "
  802. + "verify the name is correct."
  803. )
  804. return env_dir
  805. def get_ray_doc_version():
  806. """Get the docs.ray.io version corresponding to the ray.__version__."""
  807. # The ray.__version__ can be official Ray release (such as 1.12.0), or
  808. # dev (3.0.0dev0) or release candidate (2.0.0rc0). For the later we map
  809. # to the master doc version at docs.ray.io.
  810. if re.match(r"^\d+\.\d+\.\d+$", ray.__version__) is None:
  811. return "master"
  812. # For the former (official Ray release), we have corresponding doc version
  813. # released as well.
  814. return f"releases-{ray.__version__}"
  815. # Used to only print a deprecation warning once for a given function if we
  816. # don't wish to spam the caller.
  817. def get_wheel_filename(
  818. sys_platform: str = sys.platform,
  819. ray_version: str = ray.__version__,
  820. py_version: Tuple[int, int] = (sys.version_info.major, sys.version_info.minor),
  821. architecture: Optional[str] = None,
  822. ) -> str:
  823. """Returns the filename used for the nightly Ray wheel.
  824. Args:
  825. sys_platform: The platform as returned by sys.platform. Examples:
  826. "darwin", "linux", "win32"
  827. ray_version: The Ray version as returned by ray.__version__ or
  828. `ray --version`. Examples: "3.0.0.dev0"
  829. py_version: The Python version as returned by sys.version_info. A
  830. tuple of (major, minor). Examples: (3, 8)
  831. architecture: Architecture, e.g. ``x86_64`` or ``aarch64``. If None, will
  832. be determined by calling ``platform.processor()``.
  833. Returns:
  834. The wheel file name. Examples:
  835. ray-3.0.0.dev0-cp38-cp38-manylinux2014_x86_64.whl
  836. """
  837. assert py_version in ray_constants.RUNTIME_ENV_CONDA_PY_VERSIONS, py_version
  838. py_version_str = "".join(map(str, py_version))
  839. architecture = architecture or platform.processor()
  840. assert sys_platform in ["darwin", "linux", "win32"], sys_platform
  841. if sys_platform == "darwin":
  842. if architecture == "x86_64":
  843. os_string = "macosx_12_0_x86_64"
  844. else:
  845. os_string = "macosx_12_0_arm64"
  846. elif sys_platform == "linux":
  847. if architecture == "aarch64" or architecture == "arm64":
  848. os_string = "manylinux2014_aarch64"
  849. else:
  850. os_string = "manylinux2014_x86_64"
  851. elif sys_platform == "win32":
  852. os_string = "win_amd64"
  853. wheel_filename = (
  854. f"ray-{ray_version}-cp{py_version_str}-"
  855. f"cp{py_version_str}{'m' if py_version_str in ['37'] else ''}"
  856. f"-{os_string}.whl"
  857. )
  858. return wheel_filename
  859. def get_master_wheel_url(
  860. ray_commit: str = ray.__commit__,
  861. sys_platform: str = sys.platform,
  862. ray_version: str = ray.__version__,
  863. py_version: Tuple[int, int] = sys.version_info[:2],
  864. ) -> str:
  865. """Return the URL for the wheel from a specific commit."""
  866. filename = get_wheel_filename(
  867. sys_platform=sys_platform, ray_version=ray_version, py_version=py_version
  868. )
  869. return (
  870. f"https://s3-us-west-2.amazonaws.com/ray-wheels/master/"
  871. f"{ray_commit}/{filename}"
  872. )
  873. def get_release_wheel_url(
  874. ray_commit: str = ray.__commit__,
  875. sys_platform: str = sys.platform,
  876. ray_version: str = ray.__version__,
  877. py_version: Tuple[int, int] = sys.version_info[:2],
  878. ) -> str:
  879. """Return the URL for the wheel for a specific release."""
  880. filename = get_wheel_filename(
  881. sys_platform=sys_platform, ray_version=ray_version, py_version=py_version
  882. )
  883. return (
  884. f"https://ray-wheels.s3-us-west-2.amazonaws.com/releases/"
  885. f"{ray_version}/{ray_commit}/{filename}"
  886. )
  887. # e.g. https://ray-wheels.s3-us-west-2.amazonaws.com/releases/1.4.0rc1/e7c7
  888. # f6371a69eb727fa469e4cd6f4fbefd143b4c/ray-1.4.0rc1-cp36-cp36m-manylinux201
  889. # 4_x86_64.whl
  890. def validate_namespace(namespace: str):
  891. if not isinstance(namespace, str):
  892. raise TypeError("namespace must be None or a string.")
  893. elif namespace == "":
  894. raise ValueError(
  895. '"" is not a valid namespace. ' "Pass None to not specify a namespace."
  896. )
  897. def get_dashboard_dependency_error() -> Optional[ImportError]:
  898. """Returns the exception error if Ray Dashboard dependencies are not installed.
  899. None if they are installed.
  900. Checks to see if we should start the dashboard agent or not based on the
  901. Ray installation version the user has installed (ray vs. ray[default]).
  902. Unfortunately there doesn't seem to be a cleaner way to detect this other
  903. than just blindly importing the relevant packages.
  904. """
  905. try:
  906. import ray.dashboard.optional_deps # noqa: F401
  907. return None
  908. except ImportError as e:
  909. return e
  910. def get_ray_client_dependency_error() -> Optional[ImportError]:
  911. """Returns the exception error if Ray Client dependencies are not installed.
  912. None if they are installed.
  913. """
  914. try:
  915. import grpc # noqa: F401
  916. return None
  917. except ImportError as e:
  918. return e
  919. connect_error = (
  920. "Unable to connect to GCS (ray head) at {}. "
  921. "Check that (1) Ray with matching version started "
  922. "successfully at the specified address, (2) this "
  923. "node can reach the specified address, and (3) there is "
  924. "no firewall setting preventing access."
  925. )
  926. def internal_kv_list_with_retry(gcs_client, prefix, namespace, num_retries=20):
  927. result = None
  928. if isinstance(prefix, str):
  929. prefix = prefix.encode()
  930. if isinstance(namespace, str):
  931. namespace = namespace.encode()
  932. for _ in range(num_retries):
  933. try:
  934. result = gcs_client.internal_kv_keys(prefix, namespace)
  935. except Exception as e:
  936. if isinstance(e, ray.exceptions.RpcError) and e.rpc_code in (
  937. ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE,
  938. ray._raylet.GRPC_STATUS_CODE_UNKNOWN,
  939. ):
  940. logger.warning(connect_error.format(gcs_client.address))
  941. else:
  942. logger.exception("Internal KV List failed")
  943. result = None
  944. if result is not None:
  945. break
  946. else:
  947. logger.debug(f"Fetched {prefix}=None from KV. Retrying.")
  948. time.sleep(2)
  949. if result is None:
  950. raise ConnectionError(
  951. f"Could not list '{prefix}' from GCS. Did GCS start successfully?"
  952. )
  953. return result
  954. def internal_kv_get_with_retry(gcs_client, key, namespace, num_retries=20):
  955. result = None
  956. if isinstance(key, str):
  957. key = key.encode()
  958. for _ in range(num_retries):
  959. try:
  960. result = gcs_client.internal_kv_get(key, namespace)
  961. except Exception as e:
  962. if isinstance(e, ray.exceptions.RpcError) and e.rpc_code in (
  963. ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE,
  964. ray._raylet.GRPC_STATUS_CODE_UNKNOWN,
  965. ):
  966. logger.warning(connect_error.format(gcs_client.address))
  967. else:
  968. logger.exception("Internal KV Get failed")
  969. result = None
  970. if result is not None:
  971. break
  972. else:
  973. logger.debug(f"Fetched {key}=None from KV. Retrying.")
  974. time.sleep(2)
  975. if not result:
  976. raise ConnectionError(
  977. f"Could not read '{key.decode()}' from GCS. Did GCS start successfully?"
  978. )
  979. return result
  980. def parse_resources_json(
  981. resources: str, cli_logger, cf, command_arg="--resources"
  982. ) -> Dict[str, float]:
  983. try:
  984. resources = json.loads(resources)
  985. if not isinstance(resources, dict):
  986. raise ValueError("The format after deserialization is not a dict")
  987. except Exception as e:
  988. cli_logger.error(
  989. "`{}` is not a valid JSON string, detail error:{}",
  990. cf.bold(f"{command_arg}={resources}"),
  991. str(e),
  992. )
  993. cli_logger.abort(
  994. "Valid values look like this: `{}`",
  995. cf.bold(
  996. f'{command_arg}=\'{{"CustomResource3": 1, "CustomResource2": 2}}\''
  997. ),
  998. )
  999. return resources
  1000. def parse_metadata_json(
  1001. metadata: str, cli_logger, cf, command_arg="--metadata-json"
  1002. ) -> Dict[str, str]:
  1003. try:
  1004. metadata = json.loads(metadata)
  1005. if not isinstance(metadata, dict):
  1006. raise ValueError("The format after deserialization is not a dict")
  1007. except Exception as e:
  1008. cli_logger.error(
  1009. "`{}` is not a valid JSON string, detail error:{}",
  1010. cf.bold(f"{command_arg}={metadata}"),
  1011. str(e),
  1012. )
  1013. cli_logger.abort(
  1014. "Valid values look like this: `{}`",
  1015. cf.bold(f'{command_arg}=\'{{"key1": "value1", "key2": "value2"}}\''),
  1016. )
  1017. return metadata
  1018. def internal_kv_put_with_retry(gcs_client, key, value, namespace, num_retries=20):
  1019. if isinstance(key, str):
  1020. key = key.encode()
  1021. if isinstance(value, str):
  1022. value = value.encode()
  1023. if isinstance(namespace, str):
  1024. namespace = namespace.encode()
  1025. error = None
  1026. for _ in range(num_retries):
  1027. try:
  1028. return gcs_client.internal_kv_put(
  1029. key, value, overwrite=True, namespace=namespace
  1030. )
  1031. except ray.exceptions.RpcError as e:
  1032. if e.rpc_code in (
  1033. ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE,
  1034. ray._raylet.GRPC_STATUS_CODE_UNKNOWN,
  1035. ):
  1036. logger.warning(connect_error.format(gcs_client.address))
  1037. else:
  1038. logger.exception("Internal KV Put failed")
  1039. time.sleep(2)
  1040. error = e
  1041. # Reraise the last error.
  1042. raise error
  1043. def compute_version_info():
  1044. """Compute the versions of Python, and Ray.
  1045. Returns:
  1046. A tuple containing the version information.
  1047. """
  1048. ray_version = ray.__version__
  1049. python_version = ".".join(map(str, sys.version_info[:3]))
  1050. return ray_version, python_version
  1051. def get_directory_size_bytes(path: Union[str, Path] = ".") -> int:
  1052. """Get the total size of a directory in bytes, including subdirectories."""
  1053. total_size_bytes = 0
  1054. for dirpath, dirnames, filenames in os.walk(path):
  1055. for f in filenames:
  1056. fp = os.path.join(dirpath, f)
  1057. # skip if it is a symbolic link or a .pyc file
  1058. if not os.path.islink(fp) and not f.endswith(".pyc"):
  1059. total_size_bytes += os.path.getsize(fp)
  1060. return total_size_bytes
  1061. def check_version_info(
  1062. cluster_metadata,
  1063. this_process_address,
  1064. raise_on_mismatch=True,
  1065. python_version_match_level=None,
  1066. ):
  1067. """Check if the Python and Ray versions stored in GCS matches this process.
  1068. Args:
  1069. cluster_metadata: Ray cluster metadata from GCS.
  1070. this_process_address: Informational only. The address of this process.
  1071. e.g. "node address:port" or "Ray Client".
  1072. raise_on_mismatch: Raise an exception on True, log a warning otherwise.
  1073. python_version_match_level: "minor" or "patch". To which python version level we
  1074. try to match. Note if "minor" and the patch is different, we will still log
  1075. a warning. Default value is `RAY_DEFAULT_PYTHON_VERSION_MATCH_LEVEL` if it
  1076. exists, otherwise "patch"
  1077. Behavior:
  1078. - We raise or log a warning, based on raise_on_mismatch, if:
  1079. - Ray versions do not match; OR
  1080. - Python (major, minor) versions do not match,
  1081. if python_version_match_level == 'minor'; OR
  1082. - Python (major, minor, patch) versions do not match,
  1083. if python_version_match_level == 'patch'.
  1084. - We also log a warning if:
  1085. - Python (major, minor) versions match, AND
  1086. - Python patch versions do not match, AND
  1087. - python_version_match_level == 'minor' AND
  1088. - raise_on_mismatch == False.
  1089. Raises:
  1090. Exception: An exception is raised if there is a version mismatch.
  1091. """
  1092. if python_version_match_level is None:
  1093. python_version_match_level = os.environ.get(
  1094. "RAY_DEFAULT_PYTHON_VERSION_MATCH_LEVEL", "patch"
  1095. )
  1096. cluster_version_info = (
  1097. cluster_metadata["ray_version"],
  1098. cluster_metadata["python_version"],
  1099. )
  1100. my_version_info = compute_version_info()
  1101. # Calculate: ray_matches, python_matches, python_full_matches
  1102. ray_matches = cluster_version_info[0] == my_version_info[0]
  1103. python_full_matches = cluster_version_info[1] == my_version_info[1]
  1104. if python_version_match_level == "patch":
  1105. python_matches = cluster_version_info[1] == my_version_info[1]
  1106. elif python_version_match_level == "minor":
  1107. my_python_versions = my_version_info[1].split(".")
  1108. cluster_python_versions = cluster_version_info[1].split(".")
  1109. python_matches = my_python_versions[:2] == cluster_python_versions[:2]
  1110. else:
  1111. raise ValueError(
  1112. f"Invalid python_version_match_level: {python_version_match_level}, "
  1113. "want: 'minor' or 'patch'"
  1114. )
  1115. mismatch_msg = (
  1116. "The cluster was started with:\n"
  1117. f" Ray: {cluster_version_info[0]}\n"
  1118. f" Python: {cluster_version_info[1]}\n"
  1119. f"This process on {this_process_address} was started with:\n"
  1120. f" Ray: {my_version_info[0]}\n"
  1121. f" Python: {my_version_info[1]}\n"
  1122. )
  1123. if ray_matches and python_matches:
  1124. if not python_full_matches:
  1125. logger.warning(f"Python patch version mismatch: {mismatch_msg}")
  1126. else:
  1127. error_message = f"Version mismatch: {mismatch_msg}"
  1128. if raise_on_mismatch:
  1129. raise RuntimeError(error_message)
  1130. else:
  1131. logger.warning(error_message)
  1132. def get_runtime_env_info(
  1133. runtime_env: "RuntimeEnv",
  1134. *,
  1135. is_job_runtime_env: bool = False,
  1136. serialize: bool = False,
  1137. ):
  1138. """Create runtime env info from runtime env.
  1139. In the user interface, the argument `runtime_env` contains some fields
  1140. which not contained in `ProtoRuntimeEnv` but in `ProtoRuntimeEnvInfo`,
  1141. such as `eager_install`. This function will extract those fields from
  1142. `RuntimeEnv` and create a new `ProtoRuntimeEnvInfo`, and serialize it
  1143. into json format.
  1144. """
  1145. from ray.runtime_env import RuntimeEnvConfig
  1146. proto_runtime_env_info = ProtoRuntimeEnvInfo()
  1147. if runtime_env.working_dir_uri():
  1148. proto_runtime_env_info.uris.working_dir_uri = runtime_env.working_dir_uri()
  1149. if len(runtime_env.py_modules_uris()) > 0:
  1150. proto_runtime_env_info.uris.py_modules_uris[:] = runtime_env.py_modules_uris()
  1151. # TODO(Catch-Bull): overload `__setitem__` for `RuntimeEnv`, change the
  1152. # runtime_env of all internal code from dict to RuntimeEnv.
  1153. runtime_env_config = runtime_env.get("config")
  1154. if runtime_env_config is None:
  1155. runtime_env_config = RuntimeEnvConfig.default_config()
  1156. else:
  1157. runtime_env_config = RuntimeEnvConfig.parse_and_validate_runtime_env_config(
  1158. runtime_env_config
  1159. )
  1160. proto_runtime_env_info.runtime_env_config.CopyFrom(
  1161. runtime_env_config.build_proto_runtime_env_config()
  1162. )
  1163. # Normally, `RuntimeEnv` should guarantee the accuracy of field eager_install,
  1164. # but so far, the internal code has not completely prohibited direct
  1165. # modification of fields in RuntimeEnv, so we should check it for insurance.
  1166. eager_install = (
  1167. runtime_env_config.get("eager_install")
  1168. if runtime_env_config is not None
  1169. else None
  1170. )
  1171. if is_job_runtime_env or eager_install is not None:
  1172. if eager_install is None:
  1173. eager_install = True
  1174. elif not isinstance(eager_install, bool):
  1175. raise TypeError(
  1176. f"eager_install must be a boolean. got {type(eager_install)}"
  1177. )
  1178. proto_runtime_env_info.runtime_env_config.eager_install = eager_install
  1179. proto_runtime_env_info.serialized_runtime_env = runtime_env.serialize()
  1180. if not serialize:
  1181. return proto_runtime_env_info
  1182. return json_format.MessageToJson(proto_runtime_env_info)
  1183. def parse_runtime_env_for_task_or_actor(
  1184. runtime_env: Optional[Union[Dict, "RuntimeEnv"]]
  1185. ):
  1186. from ray.runtime_env import RuntimeEnv
  1187. from ray.runtime_env.runtime_env import _validate_no_local_paths
  1188. # Parse local pip/conda config files here. If we instead did it in
  1189. # .remote(), it would get run in the Ray Client server, which runs on
  1190. # a remote node where the files aren't available.
  1191. if runtime_env:
  1192. if isinstance(runtime_env, dict):
  1193. runtime_env = RuntimeEnv(**(runtime_env or {}))
  1194. _validate_no_local_paths(runtime_env)
  1195. return runtime_env
  1196. raise TypeError(
  1197. "runtime_env must be dict or RuntimeEnv, ",
  1198. f"but got: {type(runtime_env)}",
  1199. )
  1200. else:
  1201. # Keep the new_runtime_env as None. In .remote(), we need to know
  1202. # if runtime_env is None to know whether or not to fall back to the
  1203. # runtime_env specified in the @ray.remote decorator.
  1204. return None
  1205. def split_address(address: str) -> Tuple[str, str]:
  1206. """Splits address into a module string (scheme) and an inner_address.
  1207. We use a custom splitting function instead of urllib because
  1208. PEP allows "underscores" in a module names, while URL schemes do not
  1209. allow them.
  1210. Args:
  1211. address: The address to split.
  1212. Returns:
  1213. A tuple of (scheme, inner_address).
  1214. Raises:
  1215. ValueError: If the address does not contain '://'.
  1216. Examples:
  1217. >>> split_address("ray://my_cluster")
  1218. ('ray', 'my_cluster')
  1219. """
  1220. if "://" not in address:
  1221. raise ValueError("Address must contain '://'")
  1222. module_string, inner_address = address.split("://", maxsplit=1)
  1223. return (module_string, inner_address)
  1224. def get_entrypoint_name():
  1225. """Get the entrypoint of the current script."""
  1226. prefix = ""
  1227. try:
  1228. curr = psutil.Process()
  1229. # Prepend `interactive_shell` for interactive shell scripts.
  1230. # https://stackoverflow.com/questions/2356399/tell-if-python-is-in-interactive-mode # noqa
  1231. if hasattr(sys, "ps1"):
  1232. prefix = "(interactive_shell) "
  1233. return prefix + list2cmdline(curr.cmdline())
  1234. except Exception:
  1235. return "unknown"
  1236. class DeferSigint(contextlib.AbstractContextManager):
  1237. """Context manager that defers SIGINT signals until the context is left."""
  1238. # This is used by Ray's task cancellation to defer cancellation interrupts during
  1239. # problematic areas, e.g. task argument deserialization.
  1240. def __init__(self):
  1241. # Whether a SIGINT signal was received during the context.
  1242. self.signal_received = False
  1243. # The overridden SIGINT handler
  1244. self.overridden_sigint_handler = None
  1245. # The original signal method.
  1246. self.orig_signal = None
  1247. @classmethod
  1248. def create_if_main_thread(cls) -> contextlib.AbstractContextManager:
  1249. """Creates a DeferSigint context manager if running on the main thread,
  1250. returns a no-op context manager otherwise.
  1251. """
  1252. if threading.current_thread() == threading.main_thread():
  1253. return cls()
  1254. else:
  1255. return contextlib.nullcontext()
  1256. def _set_signal_received(self, signum, frame):
  1257. """SIGINT handler that defers the signal."""
  1258. self.signal_received = True
  1259. def _signal_monkey_patch(self, signum, handler):
  1260. """Monkey patch for signal.signal that defers the setting of new signal
  1261. handler after the DeferSigint context exits."""
  1262. # Only handle it in the main thread because if setting a handler in a non-main
  1263. # thread, signal.signal will raise an error because Python doesn't allow it.
  1264. if (
  1265. threading.current_thread() == threading.main_thread()
  1266. and signum == signal.SIGINT
  1267. ):
  1268. orig_sigint_handler = self.overridden_sigint_handler
  1269. self.overridden_sigint_handler = handler
  1270. return orig_sigint_handler
  1271. return self.orig_signal(signum, handler)
  1272. def __enter__(self):
  1273. # Save original SIGINT handler for later restoration.
  1274. self.overridden_sigint_handler = signal.getsignal(signal.SIGINT)
  1275. # Set SIGINT signal handler that defers the signal.
  1276. signal.signal(signal.SIGINT, self._set_signal_received)
  1277. # Monkey patch signal.signal to raise an error if a SIGINT handler is registered
  1278. # within the context.
  1279. self.orig_signal = signal.signal
  1280. signal.signal = self._signal_monkey_patch
  1281. return self
  1282. def __exit__(self, exc_type, exc, exc_tb):
  1283. assert self.overridden_sigint_handler is not None
  1284. assert self.orig_signal is not None
  1285. # Restore original signal.signal function.
  1286. signal.signal = self.orig_signal
  1287. # Restore overridden SIGINT handler.
  1288. signal.signal(signal.SIGINT, self.overridden_sigint_handler)
  1289. if exc_type is None and self.signal_received:
  1290. # No exception raised in context, call the original SIGINT handler.
  1291. # By default, this means raising KeyboardInterrupt.
  1292. self.overridden_sigint_handler(signal.SIGINT, None)
  1293. else:
  1294. # If exception was raised in context, returning False will cause it to be
  1295. # reraised.
  1296. return False
  1297. def try_import_each_module(module_names_to_import: List[str]) -> None:
  1298. """
  1299. Make a best-effort attempt to import each named Python module.
  1300. This is used by the Python default_worker.py to preload modules.
  1301. """
  1302. for module_to_preload in module_names_to_import:
  1303. try:
  1304. importlib.import_module(module_to_preload)
  1305. except ImportError:
  1306. logger.exception(f'Failed to preload the module "{module_to_preload}"')
  1307. def remove_ray_internal_flags_from_env(env: dict):
  1308. """
  1309. Remove Ray internal flags from `env`.
  1310. Defined in ray/common/ray_internal_flag_def.h
  1311. """
  1312. for flag in ray_constants.RAY_INTERNAL_FLAGS:
  1313. env.pop(flag, None)
  1314. def update_envs(env_vars: Dict[str, str]):
  1315. """
  1316. When updating the environment variable, if there is ${X},
  1317. it will be replaced with the current environment variable.
  1318. """
  1319. if not env_vars:
  1320. return
  1321. for key, value in env_vars.items():
  1322. expanded = os.path.expandvars(value)
  1323. # Replace non-existant env vars with an empty string.
  1324. result = re.sub(r"\$\{[A-Z0-9_]+\}", "", expanded)
  1325. os.environ[key] = result
  1326. def parse_pg_formatted_resources_to_original(
  1327. pg_formatted_resources: Dict[str, float]
  1328. ) -> Dict[str, float]:
  1329. original_resources = {}
  1330. for key, value in pg_formatted_resources.items():
  1331. result = PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN.match(key)
  1332. if result and len(result.groups()) == 3:
  1333. # Filter out resources that have bundle_group_[pg_id] since
  1334. # it is an implementation detail.
  1335. # This resource is automatically added to the resource
  1336. # request for all tasks that require placement groups.
  1337. if result.group(1) == PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME:
  1338. continue
  1339. original_resources[result.group(1)] = value
  1340. continue
  1341. result = PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN.match(key)
  1342. if result and len(result.groups()) == 2:
  1343. if result.group(1) == "bundle":
  1344. continue
  1345. original_resources[result.group(1)] = value
  1346. continue
  1347. original_resources[key] = value
  1348. return original_resources
  1349. def validate_actor_state_name(actor_state_name):
  1350. if actor_state_name is None:
  1351. return
  1352. actor_state_names = [
  1353. "DEPENDENCIES_UNREADY",
  1354. "PENDING_CREATION",
  1355. "ALIVE",
  1356. "RESTARTING",
  1357. "DEAD",
  1358. ]
  1359. if actor_state_name not in actor_state_names:
  1360. raise ValueError(
  1361. f'"{actor_state_name}" is not a valid actor state name, '
  1362. 'it must be one of the following: "DEPENDENCIES_UNREADY", '
  1363. '"PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD"'
  1364. )
  1365. def get_current_node_cpu_model_name() -> Optional[str]:
  1366. if not sys.platform.startswith("linux"):
  1367. return None
  1368. try:
  1369. """
  1370. /proc/cpuinfo content example:
  1371. processor : 0
  1372. vendor_id : GenuineIntel
  1373. cpu family : 6
  1374. model : 85
  1375. model name : Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
  1376. stepping : 7
  1377. """
  1378. with open("/proc/cpuinfo", "r") as f:
  1379. for line in f:
  1380. if line.startswith("model name"):
  1381. return line.split(":")[1].strip()
  1382. return None
  1383. except Exception:
  1384. logger.debug("Failed to get CPU model name", exc_info=True)
  1385. return None
  1386. def validate_socket_filepath(filepath: str):
  1387. """
  1388. Validate the provided filename is a valid Unix socket filename.
  1389. """
  1390. # Don't check for Windows as it doesn't support Unix sockets.
  1391. if sys.platform == "win32":
  1392. return
  1393. is_mac = sys.platform.startswith("darwin")
  1394. maxlen = (104 if is_mac else 108) - 1
  1395. if len(filepath.encode("utf-8")) > maxlen:
  1396. raise OSError(
  1397. f"validate_socket_filename failed: AF_UNIX path length cannot exceed {maxlen} bytes: {filepath}"
  1398. )
  1399. # Whether we're currently running in a test, either local or CI.
  1400. in_test = None
  1401. def is_in_test():
  1402. global in_test
  1403. if in_test is None:
  1404. in_test = any(
  1405. env_var in os.environ
  1406. # These environment variables are always set by pytest and Buildkite,
  1407. # respectively.
  1408. for env_var in ("PYTEST_CURRENT_TEST", "BUILDKITE")
  1409. )
  1410. return in_test