setup.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. import argparse
  2. import errno
  3. import glob
  4. import io
  5. import logging
  6. import os
  7. import pathlib
  8. import re
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tarfile
  13. import tempfile
  14. import urllib.error
  15. import urllib.parse
  16. import urllib.request
  17. import zipfile
  18. from enum import Enum
  19. from itertools import chain
  20. # Workaround for setuptools_scm (used on macos) adding junk files
  21. # https://stackoverflow.com/a/61274968/8162137
  22. try:
  23. import setuptools_scm.integration
  24. setuptools_scm.integration.find_files = lambda _: []
  25. except ImportError:
  26. pass
  27. logger = logging.getLogger(__name__)
  28. SUPPORTED_PYTHONS = [(3, 7), (3, 8), (3, 9), (3, 10), (3, 11)]
  29. # When the bazel version is updated, make sure to update it
  30. # in WORKSPACE file as well.
  31. SUPPORTED_BAZEL = (5, 4, 0)
  32. ROOT_DIR = os.path.dirname(__file__)
  33. BUILD_JAVA = os.getenv("RAY_INSTALL_JAVA") == "1"
  34. SKIP_BAZEL_BUILD = os.getenv("SKIP_BAZEL_BUILD") == "1"
  35. BAZEL_LIMIT_CPUS = os.getenv("BAZEL_LIMIT_CPUS")
  36. PICKLE5_SUBDIR = os.path.join("ray", "pickle5_files")
  37. THIRDPARTY_SUBDIR = os.path.join("ray", "thirdparty_files")
  38. CLEANABLE_SUBDIRS = [PICKLE5_SUBDIR, THIRDPARTY_SUBDIR]
  39. # In automated builds, we do a few adjustments before building. For instance,
  40. # the bazel environment is set up slightly differently, and symlinks are
  41. # replaced with junctions in Windows. This variable is set e.g. in our conda
  42. # feedstock.
  43. is_automated_build = bool(int(os.environ.get("IS_AUTOMATED_BUILD", "0")))
  44. exe_suffix = ".exe" if sys.platform == "win32" else ""
  45. # .pyd is the extension Python requires on Windows for shared libraries.
  46. # https://docs.python.org/3/faq/windows.html#is-a-pyd-file-the-same-as-a-dll
  47. pyd_suffix = ".pyd" if sys.platform == "win32" else ".so"
  48. pickle5_url = (
  49. "https://github.com/pitrou/pickle5-backport/archive/"
  50. "e6117502435aba2901585cc6c692fb9582545f08.tar.gz"
  51. )
  52. def find_version(*filepath):
  53. # Extract version information from filepath
  54. with open(os.path.join(ROOT_DIR, *filepath)) as fp:
  55. version_match = re.search(
  56. r"^__version__ = ['\"]([^'\"]*)['\"]", fp.read(), re.M
  57. )
  58. if version_match:
  59. return version_match.group(1)
  60. raise RuntimeError("Unable to find version string.")
  61. class SetupType(Enum):
  62. RAY = 1
  63. RAY_CPP = 2
  64. class BuildType(Enum):
  65. DEFAULT = 1
  66. DEBUG = 2
  67. ASAN = 3
  68. TSAN = 4
  69. class SetupSpec:
  70. def __init__(
  71. self, type: SetupType, name: str, description: str, build_type: BuildType
  72. ):
  73. self.type: SetupType = type
  74. self.name: str = name
  75. version = find_version("ray", "__init__.py")
  76. # add .dbg suffix if debug mode is on.
  77. if build_type == BuildType.DEBUG:
  78. self.version: str = f"{version}+dbg"
  79. elif build_type == BuildType.ASAN:
  80. self.version: str = f"{version}+asan"
  81. elif build_type == BuildType.TSAN:
  82. self.version: str = f"{version}+tsan"
  83. else:
  84. self.version = version
  85. self.description: str = description
  86. self.build_type: BuildType = build_type
  87. self.files_to_include: list = []
  88. self.install_requires: list = []
  89. self.extras: dict = {}
  90. def get_packages(self):
  91. if self.type == SetupType.RAY:
  92. return setuptools.find_packages(exclude=("tests", "*.tests", "*.tests.*"))
  93. else:
  94. return []
  95. build_type = os.getenv("RAY_DEBUG_BUILD")
  96. if build_type == "debug":
  97. BUILD_TYPE = BuildType.DEBUG
  98. elif build_type == "asan":
  99. BUILD_TYPE = BuildType.ASAN
  100. elif build_type == "tsan":
  101. BUILD_TYPE = BuildType.TSAN
  102. else:
  103. BUILD_TYPE = BuildType.DEFAULT
  104. if os.getenv("RAY_INSTALL_CPP") == "1":
  105. # "ray-cpp" wheel package.
  106. setup_spec = SetupSpec(
  107. SetupType.RAY_CPP,
  108. "ray-cpp",
  109. "A subpackage of Ray which provides the Ray C++ API.",
  110. BUILD_TYPE,
  111. )
  112. else:
  113. # "ray" primary wheel package.
  114. setup_spec = SetupSpec(
  115. SetupType.RAY,
  116. "ray",
  117. "Ray provides a simple, "
  118. "universal API for building distributed applications.",
  119. BUILD_TYPE,
  120. )
  121. RAY_EXTRA_CPP = True
  122. # Disable extra cpp for the development versions.
  123. if "dev" in setup_spec.version or os.getenv("RAY_DISABLE_EXTRA_CPP") == "1":
  124. RAY_EXTRA_CPP = False
  125. # Ideally, we could include these files by putting them in a
  126. # MANIFEST.in or using the package_data argument to setup, but the
  127. # MANIFEST.in gets applied at the very beginning when setup.py runs
  128. # before these files have been created, so we have to move the files
  129. # manually.
  130. # NOTE: The lists below must be kept in sync with ray/BUILD.bazel.
  131. ray_files = [
  132. "ray/_raylet" + pyd_suffix,
  133. "ray/core/src/ray/gcs/gcs_server" + exe_suffix,
  134. "ray/core/src/ray/raylet/raylet" + exe_suffix,
  135. ]
  136. if BUILD_JAVA or os.path.exists(os.path.join(ROOT_DIR, "ray/jars/ray_dist.jar")):
  137. ray_files.append("ray/jars/ray_dist.jar")
  138. if setup_spec.type == SetupType.RAY_CPP:
  139. setup_spec.files_to_include += ["ray/cpp/default_worker" + exe_suffix]
  140. # C++ API library and project template files.
  141. setup_spec.files_to_include += [
  142. os.path.join(dirpath, filename)
  143. for dirpath, dirnames, filenames in os.walk("ray/cpp")
  144. for filename in filenames
  145. ]
  146. # These are the directories where automatically generated Python protobuf
  147. # bindings are created.
  148. generated_python_directories = [
  149. "ray/core/generated",
  150. "ray/serve/generated",
  151. ]
  152. ray_files.append("ray/nightly-wheels.yaml")
  153. # Autoscaler files.
  154. ray_files += [
  155. "ray/autoscaler/aws/defaults.yaml",
  156. "ray/autoscaler/aws/cloudwatch/prometheus.yml",
  157. "ray/autoscaler/aws/cloudwatch/ray_prometheus_waiter.sh",
  158. "ray/autoscaler/azure/defaults.yaml",
  159. "ray/autoscaler/_private/_azure/azure-vm-template.json",
  160. "ray/autoscaler/_private/_azure/azure-config-template.json",
  161. "ray/autoscaler/gcp/defaults.yaml",
  162. "ray/autoscaler/local/defaults.yaml",
  163. "ray/autoscaler/ray-schema.json",
  164. ]
  165. # Dashboard files.
  166. ray_files += [
  167. os.path.join(dirpath, filename)
  168. for dirpath, dirnames, filenames in os.walk("ray/dashboard/client/build")
  169. for filename in filenames
  170. ]
  171. # Dashboard metrics files.
  172. ray_files += [
  173. os.path.join(dirpath, filename)
  174. for dirpath, dirnames, filenames in os.walk("ray/dashboard/modules/metrics/export")
  175. for filename in filenames
  176. ]
  177. ray_files += [
  178. os.path.join(dirpath, filename)
  179. for dirpath, dirnames, filenames in os.walk(
  180. "ray/dashboard/modules/metrics/dashboards"
  181. )
  182. for filename in filenames
  183. if filename.endswith(".json")
  184. ]
  185. # html templates for notebook integration
  186. ray_files += [
  187. p.as_posix() for p in pathlib.Path("ray/widgets/templates/").glob("*.html.j2")
  188. ]
  189. # If you're adding dependencies for ray extras, please
  190. # also update the matching section of requirements/requirements.txt
  191. # in this directory
  192. if setup_spec.type == SetupType.RAY:
  193. pandas_dep = "pandas >= 1.3"
  194. numpy_dep = "numpy >= 1.20"
  195. if sys.platform != "win32":
  196. pyarrow_dep = "pyarrow >= 6.0.1"
  197. else:
  198. # Serialization workaround for pyarrow 7.0.0+ doesn't work for Windows.
  199. pyarrow_dep = "pyarrow >= 6.0.1, < 7.0.0"
  200. setup_spec.extras = {
  201. "data": [
  202. numpy_dep,
  203. pandas_dep,
  204. pyarrow_dep,
  205. "fsspec",
  206. ],
  207. "default": [
  208. # If adding dependencies necessary to launch the dashboard api server,
  209. # please add it to dashboard/optional_deps.py as well.
  210. "aiohttp >= 3.7",
  211. "aiohttp_cors",
  212. "colorful",
  213. "py-spy >= 0.2.0",
  214. "requests",
  215. "gpustat >= 1.0.0", # for windows
  216. "opencensus",
  217. "pydantic",
  218. "prometheus_client >= 0.7.1",
  219. "smart_open",
  220. "virtualenv >=20.0.24, < 20.21.1", # For pip runtime env.
  221. ],
  222. "serve": ["uvicorn", "requests", "starlette", "fastapi", "aiorwlock"],
  223. "tune": ["pandas", "tensorboardX>=1.9", "requests", pyarrow_dep],
  224. "k8s": ["kubernetes", "urllib3"],
  225. "observability": [
  226. "opentelemetry-api",
  227. "opentelemetry-sdk",
  228. "opentelemetry-exporter-otlp",
  229. ],
  230. }
  231. # Ray Serve depends on the Ray dashboard components.
  232. setup_spec.extras["serve"] = list(
  233. set(setup_spec.extras["serve"] + setup_spec.extras["default"])
  234. )
  235. if RAY_EXTRA_CPP:
  236. setup_spec.extras["cpp"] = ["ray-cpp==" + setup_spec.version]
  237. setup_spec.extras["rllib"] = setup_spec.extras["tune"] + [
  238. "dm_tree",
  239. "gymnasium==0.26.3",
  240. "lz4",
  241. "scikit-image",
  242. "pyyaml",
  243. "scipy",
  244. "typer",
  245. "rich",
  246. ]
  247. setup_spec.extras["train"] = setup_spec.extras["tune"]
  248. # Ray AI Runtime should encompass Data, Tune, and Serve.
  249. setup_spec.extras["air"] = list(
  250. set(
  251. setup_spec.extras["tune"]
  252. + setup_spec.extras["data"]
  253. + setup_spec.extras["train"]
  254. + setup_spec.extras["serve"]
  255. )
  256. )
  257. setup_spec.extras["all"] = list(
  258. set(chain.from_iterable(setup_spec.extras.values()))
  259. )
  260. # These are the main dependencies for users of ray. This list
  261. # should be carefully curated. If you change it, please reflect
  262. # the change in the matching section of requirements/requirements.txt
  263. #
  264. # NOTE: if you add any unbounded dependency, please also update
  265. # install-core-prerelease-dependencies.sh so we can test
  266. # new releases candidates.
  267. if setup_spec.type == SetupType.RAY:
  268. setup_spec.install_requires = [
  269. "attrs",
  270. "click >= 7.0",
  271. "dataclasses; python_version < '3.7'",
  272. "filelock",
  273. # Tracking issue: https://github.com/ray-project/ray/issues/30984
  274. "grpcio >= 1.32.0, <= 1.49.1; python_version < '3.10' and sys_platform == 'darwin'", # noqa:E501
  275. "grpcio >= 1.42.0, <= 1.49.1; python_version >= '3.10' and sys_platform == 'darwin'", # noqa:E501
  276. # Original issue: https://github.com/ray-project/ray/issues/33833
  277. "grpcio >= 1.32.0, <= 1.51.3; python_version < '3.10' and sys_platform != 'darwin'", # noqa:E501
  278. "grpcio >= 1.42.0, <= 1.51.3; python_version >= '3.10' and sys_platform != 'darwin'", # noqa:E501
  279. "jsonschema",
  280. "msgpack >= 1.0.0, < 2.0.0",
  281. "numpy >= 1.16; python_version < '3.9'",
  282. "numpy >= 1.19.3; python_version >= '3.9'",
  283. "packaging",
  284. "protobuf >= 3.15.3, != 3.19.5",
  285. "pyyaml",
  286. "aiosignal",
  287. "frozenlist",
  288. "requests",
  289. # Light weight requirement, can be replaced with "typing" once
  290. # we deprecate Python 3.7 (this will take a while).
  291. "typing_extensions; python_version < '3.8'",
  292. ]
  293. def is_native_windows_or_msys():
  294. """Check to see if we are running on native Windows,
  295. but NOT WSL (which is seen as Linux)."""
  296. return sys.platform == "msys" or sys.platform == "win32"
  297. def is_invalid_windows_platform():
  298. # 'GCC' check is how you detect MinGW:
  299. # https://github.com/msys2/MINGW-packages/blob/abd06ca92d876b9db05dd65f27d71c4ebe2673a9/mingw-w64-python2/0410-MINGW-build-extensions-with-GCC.patch#L53
  300. platform = sys.platform
  301. ver = sys.version
  302. return platform == "msys" or (platform == "win32" and ver and "GCC" in ver)
  303. # Calls Bazel in PATH, falling back to the standard user installatation path
  304. # (~/.bazel/bin/bazel) if it isn't found.
  305. def bazel_invoke(invoker, cmdline, *args, **kwargs):
  306. home = os.path.expanduser("~")
  307. first_candidate = os.getenv("BAZEL_PATH", "bazel")
  308. candidates = [first_candidate]
  309. if sys.platform == "win32":
  310. mingw_dir = os.getenv("MINGW_DIR")
  311. if mingw_dir:
  312. candidates.append(mingw_dir + "/bin/bazel.exe")
  313. else:
  314. candidates.append(os.path.join(home, ".bazel", "bin", "bazel"))
  315. result = None
  316. for i, cmd in enumerate(candidates):
  317. try:
  318. result = invoker([cmd] + cmdline, *args, **kwargs)
  319. break
  320. except IOError:
  321. if i >= len(candidates) - 1:
  322. raise
  323. return result
  324. def download(url):
  325. try:
  326. result = urllib.request.urlopen(url).read()
  327. except urllib.error.URLError:
  328. # This fallback is necessary on Python 3.5 on macOS due to TLS 1.2.
  329. curl_args = ["curl", "-s", "-L", "-f", "-o", "-", url]
  330. result = subprocess.check_output(curl_args)
  331. return result
  332. # Installs pickle5-backport into the local subdirectory.
  333. def download_pickle5(pickle5_dir):
  334. pickle5_file = urllib.parse.unquote(urllib.parse.urlparse(pickle5_url).path)
  335. pickle5_name = re.sub("\\.tar\\.gz$", ".tgz", pickle5_file, flags=re.I)
  336. url_path_parts = os.path.splitext(pickle5_name)[0].split("/")
  337. (project, commit) = (url_path_parts[2], url_path_parts[4])
  338. pickle5_archive = download(pickle5_url)
  339. with tempfile.TemporaryDirectory() as work_dir:
  340. tf = tarfile.open(None, "r", io.BytesIO(pickle5_archive))
  341. try:
  342. tf.extractall(work_dir)
  343. finally:
  344. tf.close()
  345. src_dir = os.path.join(work_dir, project + "-" + commit)
  346. args = [sys.executable, "setup.py", "-q", "bdist_wheel"]
  347. subprocess.check_call(args, cwd=src_dir)
  348. for wheel in glob.glob(os.path.join(src_dir, "dist", "*.whl")):
  349. wzf = zipfile.ZipFile(wheel, "r")
  350. try:
  351. wzf.extractall(pickle5_dir)
  352. finally:
  353. wzf.close()
  354. def patch_isdir():
  355. """
  356. Python on Windows is having hard times at telling if a symlink is
  357. a directory - it can "guess" wrong at times, which bites when
  358. finding packages. Replace with a fixed version which unwraps links first.
  359. """
  360. orig_isdir = os.path.isdir
  361. def fixed_isdir(path):
  362. while os.path.islink(path):
  363. try:
  364. link = os.readlink(path)
  365. except OSError:
  366. break
  367. path = os.path.abspath(os.path.join(os.path.dirname(path), link))
  368. return orig_isdir(path)
  369. os.path.isdir = fixed_isdir
  370. def replace_symlinks_with_junctions():
  371. """
  372. Per default Windows requires admin access to create symlinks, while
  373. junctions (which behave similarly) can be created by users.
  374. This function replaces symlinks (which might be broken when checked
  375. out without admin rights) with junctions so Ray can be built both
  376. with and without admin access.
  377. """
  378. assert is_native_windows_or_msys()
  379. # Update this list if new symlinks are introduced to the source tree
  380. _LINKS = {
  381. r"ray\dashboard": "../../dashboard",
  382. r"ray\rllib": "../../rllib",
  383. }
  384. root_dir = os.path.dirname(__file__)
  385. for link, default in _LINKS.items():
  386. path = os.path.join(root_dir, link)
  387. try:
  388. out = subprocess.check_output(
  389. "DIR /A:LD /B", shell=True, cwd=os.path.dirname(path)
  390. )
  391. except subprocess.CalledProcessError:
  392. out = b""
  393. if os.path.basename(path) in out.decode("utf8").splitlines():
  394. logger.info(f"'{link}' is already converted to junction point")
  395. else:
  396. logger.info(f"Converting '{link}' to junction point...")
  397. if os.path.isfile(path):
  398. with open(path) as inp:
  399. target = inp.read()
  400. os.unlink(path)
  401. elif os.path.isdir(path):
  402. target = default
  403. try:
  404. # unlink() works on links as well as on regular files,
  405. # and links to directories are considered directories now
  406. os.unlink(path)
  407. except OSError as err:
  408. # On Windows attempt to unlink a regular directory results
  409. # in a PermissionError with errno set to errno.EACCES.
  410. if err.errno != errno.EACCES:
  411. raise
  412. # For regular directories deletion is done with rmdir call.
  413. os.rmdir(path)
  414. else:
  415. raise ValueError(f"Unexpected type of entry: '{path}'")
  416. target = os.path.abspath(os.path.join(os.path.dirname(path), target))
  417. logger.info("Setting {} -> {}".format(link, target))
  418. subprocess.check_call(
  419. f'MKLINK /J "{os.path.basename(link)}" "{target}"',
  420. shell=True,
  421. cwd=os.path.dirname(path),
  422. )
  423. if is_automated_build and is_native_windows_or_msys():
  424. # Automated replacements should only happen in automatic build
  425. # contexts for now
  426. patch_isdir()
  427. replace_symlinks_with_junctions()
  428. def build(build_python, build_java, build_cpp):
  429. if tuple(sys.version_info[:2]) not in SUPPORTED_PYTHONS:
  430. msg = (
  431. "Detected Python version {}, which is not supported. "
  432. "Only Python {} are supported."
  433. ).format(
  434. ".".join(map(str, sys.version_info[:2])),
  435. ", ".join(".".join(map(str, v)) for v in SUPPORTED_PYTHONS),
  436. )
  437. raise RuntimeError(msg)
  438. if is_invalid_windows_platform():
  439. msg = (
  440. "Please use official native CPython on Windows,"
  441. " not Cygwin/MSYS/MSYS2/MinGW/etc.\n"
  442. + "Detected: {}\n at: {!r}".format(sys.version, sys.executable)
  443. )
  444. raise OSError(msg)
  445. bazel_env = dict(os.environ, PYTHON3_BIN_PATH=sys.executable)
  446. if is_native_windows_or_msys():
  447. SHELL = bazel_env.get("SHELL")
  448. if SHELL:
  449. bazel_env.setdefault("BAZEL_SH", os.path.normpath(SHELL))
  450. BAZEL_SH = bazel_env.get("BAZEL_SH", "")
  451. SYSTEMROOT = os.getenv("SystemRoot")
  452. wsl_bash = os.path.join(SYSTEMROOT, "System32", "bash.exe")
  453. if (not BAZEL_SH) and SYSTEMROOT and os.path.isfile(wsl_bash):
  454. msg = (
  455. "You appear to have Bash from WSL,"
  456. " which Bazel may invoke unexpectedly. "
  457. "To avoid potential problems,"
  458. " please explicitly set the {name!r}"
  459. " environment variable for Bazel."
  460. ).format(name="BAZEL_SH")
  461. raise RuntimeError(msg)
  462. # Check if the current Python already has pickle5 (either comes with newer
  463. # Python versions, or has been installed by us before).
  464. pickle5 = None
  465. if sys.version_info >= (3, 8, 2):
  466. import pickle as pickle5
  467. else:
  468. try:
  469. import pickle5
  470. except ImportError:
  471. pass
  472. if not pickle5:
  473. download_pickle5(os.path.join(ROOT_DIR, PICKLE5_SUBDIR))
  474. # Note: We are passing in sys.executable so that we use the same
  475. # version of Python to build packages inside the build.sh script. Note
  476. # that certain flags will not be passed along such as --user or sudo.
  477. # TODO(rkn): Fix this.
  478. if not os.getenv("SKIP_THIRDPARTY_INSTALL"):
  479. pip_packages = ["psutil", "setproctitle==1.2.2", "colorama"]
  480. subprocess.check_call(
  481. [
  482. sys.executable,
  483. "-m",
  484. "pip",
  485. "install",
  486. "-q",
  487. "--target=" + os.path.join(ROOT_DIR, THIRDPARTY_SUBDIR),
  488. ]
  489. + pip_packages,
  490. env=dict(os.environ, CC="gcc"),
  491. )
  492. bazel_flags = ["--verbose_failures"]
  493. if BAZEL_LIMIT_CPUS:
  494. n = int(BAZEL_LIMIT_CPUS) # the value must be an int
  495. bazel_flags.append(f"--local_cpu_resources={n}")
  496. if not is_automated_build:
  497. bazel_precmd_flags = []
  498. if is_automated_build:
  499. root_dir = os.path.join(
  500. os.path.abspath(os.environ["SRC_DIR"]), "..", "bazel-root"
  501. )
  502. out_dir = os.path.join(os.path.abspath(os.environ["SRC_DIR"]), "..", "b-o")
  503. for d in (root_dir, out_dir):
  504. if not os.path.exists(d):
  505. os.makedirs(d)
  506. bazel_precmd_flags = [
  507. "--output_user_root=" + root_dir,
  508. "--output_base=" + out_dir,
  509. ]
  510. if is_native_windows_or_msys():
  511. bazel_flags.append("--enable_runfiles=false")
  512. bazel_targets = []
  513. bazel_targets += ["//:ray_pkg"] if build_python else []
  514. bazel_targets += ["//cpp:ray_cpp_pkg"] if build_cpp else []
  515. bazel_targets += ["//java:ray_java_pkg"] if build_java else []
  516. if setup_spec.build_type == BuildType.DEBUG:
  517. bazel_flags.extend(["--config", "debug"])
  518. if setup_spec.build_type == BuildType.ASAN:
  519. bazel_flags.extend(["--config=asan-build"])
  520. if setup_spec.build_type == BuildType.TSAN:
  521. bazel_flags.extend(["--config=tsan"])
  522. return bazel_invoke(
  523. subprocess.check_call,
  524. bazel_precmd_flags + ["build"] + bazel_flags + ["--"] + bazel_targets,
  525. env=bazel_env,
  526. )
  527. def walk_directory(directory):
  528. file_list = []
  529. for (root, dirs, filenames) in os.walk(directory):
  530. for name in filenames:
  531. file_list.append(os.path.join(root, name))
  532. return file_list
  533. def copy_file(target_dir, filename, rootdir):
  534. # TODO(rkn): This feels very brittle. It may not handle all cases. See
  535. # https://github.com/apache/arrow/blob/master/python/setup.py for an
  536. # example.
  537. # File names can be absolute paths, e.g. from walk_directory().
  538. source = os.path.relpath(filename, rootdir)
  539. destination = os.path.join(target_dir, source)
  540. # Create the target directory if it doesn't already exist.
  541. os.makedirs(os.path.dirname(destination), exist_ok=True)
  542. if not os.path.exists(destination):
  543. if sys.platform == "win32":
  544. # Does not preserve file mode (needed to avoid read-only bit)
  545. shutil.copyfile(source, destination, follow_symlinks=True)
  546. else:
  547. # Preserves file mode (needed to copy executable bit)
  548. shutil.copy(source, destination, follow_symlinks=True)
  549. return 1
  550. return 0
  551. def add_system_dlls(dlls, target_dir):
  552. """
  553. Copy any required dlls required by the c-extension module and not already
  554. provided by python. They will end up in the wheel next to the c-extension
  555. module which will guarentee they are available at runtime.
  556. """
  557. for dll in dlls:
  558. # Installing Visual Studio will copy the runtime dlls to system32
  559. src = os.path.join(r"c:\Windows\system32", dll)
  560. assert os.path.exists(src)
  561. shutil.copy(src, target_dir)
  562. def pip_run(build_ext):
  563. if SKIP_BAZEL_BUILD:
  564. build(False, False, False)
  565. else:
  566. build(True, BUILD_JAVA, True)
  567. if setup_spec.type == SetupType.RAY:
  568. setup_spec.files_to_include += ray_files
  569. # We also need to install pickle5 along with Ray, so make sure that the
  570. # relevant non-Python pickle5 files get copied.
  571. pickle5_dir = os.path.join(ROOT_DIR, PICKLE5_SUBDIR)
  572. setup_spec.files_to_include += walk_directory(
  573. os.path.join(pickle5_dir, "pickle5")
  574. )
  575. thirdparty_dir = os.path.join(ROOT_DIR, THIRDPARTY_SUBDIR)
  576. setup_spec.files_to_include += walk_directory(thirdparty_dir)
  577. # Copy over the autogenerated protobuf Python bindings.
  578. for directory in generated_python_directories:
  579. for filename in os.listdir(directory):
  580. if filename[-3:] == ".py":
  581. setup_spec.files_to_include.append(
  582. os.path.join(directory, filename)
  583. )
  584. copied_files = 0
  585. for filename in setup_spec.files_to_include:
  586. copied_files += copy_file(build_ext.build_lib, filename, ROOT_DIR)
  587. if sys.platform == "win32":
  588. # _raylet.pyd links to some MSVC runtime DLLS, this one may not be
  589. # present on a user's machine. While vcruntime140.dll and
  590. # vcruntime140_1.dll are also required, they are provided by CPython.
  591. runtime_dlls = ["msvcp140.dll"]
  592. add_system_dlls(runtime_dlls, os.path.join(build_ext.build_lib, "ray"))
  593. copied_files += len(runtime_dlls)
  594. print("# of files copied to {}: {}".format(build_ext.build_lib, copied_files))
  595. def api_main(program, *args):
  596. parser = argparse.ArgumentParser()
  597. choices = ["build", "bazel_version", "python_versions", "clean", "help"]
  598. parser.add_argument("command", type=str, choices=choices)
  599. parser.add_argument(
  600. "-l",
  601. "--language",
  602. default="python,cpp",
  603. type=str,
  604. help="A list of languages to build native libraries. "
  605. 'Supported languages include "python" and "java". '
  606. "If not specified, only the Python library will be built.",
  607. )
  608. parsed_args = parser.parse_args(args)
  609. result = None
  610. if parsed_args.command == "build":
  611. kwargs = dict(build_python=False, build_java=False, build_cpp=False)
  612. for lang in parsed_args.language.split(","):
  613. if "python" in lang:
  614. kwargs.update(build_python=True)
  615. elif "java" in lang:
  616. kwargs.update(build_java=True)
  617. elif "cpp" in lang:
  618. kwargs.update(build_cpp=True)
  619. else:
  620. raise ValueError("invalid language: {!r}".format(lang))
  621. result = build(**kwargs)
  622. elif parsed_args.command == "bazel_version":
  623. print(".".join(map(str, SUPPORTED_BAZEL)))
  624. elif parsed_args.command == "python_versions":
  625. for version in SUPPORTED_PYTHONS:
  626. # NOTE: On Windows this will print "\r\n" on the command line.
  627. # Strip it out by piping to tr -d "\r".
  628. print(".".join(map(str, version)))
  629. elif parsed_args.command == "clean":
  630. def onerror(function, path, excinfo):
  631. nonlocal result
  632. if excinfo[1].errno != errno.ENOENT:
  633. msg = excinfo[1].strerror
  634. logger.error("cannot remove {}: {}".format(path, msg))
  635. result = 1
  636. for subdir in CLEANABLE_SUBDIRS:
  637. shutil.rmtree(os.path.join(ROOT_DIR, subdir), onerror=onerror)
  638. elif parsed_args.command == "help":
  639. parser.print_help()
  640. else:
  641. raise ValueError("Invalid command: {!r}".format(parsed_args.command))
  642. return result
  643. if __name__ == "__api__":
  644. api_main(*sys.argv)
  645. if __name__ == "__main__":
  646. import setuptools
  647. import setuptools.command.build_ext
  648. class build_ext(setuptools.command.build_ext.build_ext):
  649. def run(self):
  650. return pip_run(self)
  651. class BinaryDistribution(setuptools.Distribution):
  652. def has_ext_modules(self):
  653. return True
  654. # Ensure no remaining lib files.
  655. build_dir = os.path.join(ROOT_DIR, "build")
  656. if os.path.isdir(build_dir):
  657. shutil.rmtree(build_dir)
  658. setuptools.setup(
  659. name=setup_spec.name,
  660. version=setup_spec.version,
  661. author="Ray Team",
  662. author_email="ray-dev@googlegroups.com",
  663. description=(setup_spec.description),
  664. long_description=io.open(
  665. os.path.join(ROOT_DIR, os.path.pardir, "README.rst"), "r", encoding="utf-8"
  666. ).read(),
  667. url="https://github.com/ray-project/ray",
  668. keywords=(
  669. "ray distributed parallel machine-learning hyperparameter-tuning"
  670. "reinforcement-learning deep-learning serving python"
  671. ),
  672. classifiers=[
  673. "Programming Language :: Python :: 3.7",
  674. "Programming Language :: Python :: 3.8",
  675. "Programming Language :: Python :: 3.9",
  676. "Programming Language :: Python :: 3.10",
  677. ],
  678. packages=setup_spec.get_packages(),
  679. cmdclass={"build_ext": build_ext},
  680. # The BinaryDistribution argument triggers build_ext.
  681. distclass=BinaryDistribution,
  682. install_requires=setup_spec.install_requires,
  683. setup_requires=["cython >= 0.29.32", "wheel"],
  684. extras_require=setup_spec.extras,
  685. entry_points={
  686. "console_scripts": [
  687. "ray=ray.scripts.scripts:main",
  688. "rllib=ray.rllib.scripts:cli [rllib]",
  689. "tune=ray.tune.cli.scripts:cli",
  690. "serve=ray.serve.scripts:cli",
  691. ]
  692. },
  693. package_data={
  694. "ray": ["includes/*.pxd", "*.pxd"],
  695. },
  696. include_package_data=True,
  697. exclude_package_data={
  698. # Empty string means "any package".
  699. # Therefore, exclude BUILD from every package:
  700. "": ["BUILD"],
  701. },
  702. zip_safe=False,
  703. license="Apache 2.0",
  704. ) if __name__ == "__main__" else None