setup.py 26 KB

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