Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps/buildopts.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 #
3 # This source code is licensed under the MIT license found in the
4 # LICENSE file in the root directory of this source tree.
5
6 import errno
7 import glob
8 import ntpath
9 import os
10 import subprocess
11 import sys
12 import tempfile
13 from typing import Mapping, Optional
14
15 from .copytree import containing_repo_type
16 from .envfuncs import add_flag, add_path_entry, Env
17 from .fetcher import get_fbsource_repo_data, homebrew_package_prefix
18 from .manifest import ContextGenerator
19 from .platform import get_available_ram, HostType, is_windows
20
21
22 def detect_project(path):
23 repo_type, repo_root = containing_repo_type(path)
24 if repo_type is None:
25 return None, None
26
27 # Look for a .projectid file. If it exists, read the project name from it.
28 project_id_path = os.path.join(repo_root, ".projectid")
29 try:
30 with open(project_id_path, "r") as f:
31 project_name = f.read().strip()
32 return repo_root, project_name
33 except EnvironmentError as ex:
34 if ex.errno != errno.ENOENT:
35 raise
36
37 return repo_root, None
38
39
40 class BuildOptions(object):
41 def __init__(
42 self,
43 fbcode_builder_dir,
44 scratch_dir,
45 host_type,
46 install_dir=None,
47 num_jobs: int = 0,
48 use_shipit: bool = False,
49 vcvars_path=None,
50 allow_system_packages: bool = False,
51 lfs_path=None,
52 shared_libs: bool = False,
53 facebook_internal=None,
54 free_up_disk: bool = False,
55 ) -> None:
56 """fbcode_builder_dir - the path to either the in-fbsource fbcode_builder dir,
57 or for shipit-transformed repos, the build dir that
58 has been mapped into that dir.
59 scratch_dir - a place where we can store repos and build bits.
60 This path should be stable across runs and ideally
61 should not be in the repo of the project being built,
62 but that is ultimately where we generally fall back
63 for builds outside of FB
64 install_dir - where the project will ultimately be installed
65 num_jobs - the level of concurrency to use while building
66 use_shipit - use real shipit instead of the simple shipit transformer
67 vcvars_path - Path to external VS toolchain's vsvarsall.bat
68 shared_libs - whether to build shared libraries
69 free_up_disk - take extra actions to save runner disk space
70 """
71
72 if not install_dir:
73 install_dir = os.path.join(scratch_dir, "installed")
74
75 self.project_hashes = None
76 for p in ["../deps/github_hashes", "../project_hashes"]:
77 hashes = os.path.join(fbcode_builder_dir, p)
78 if os.path.exists(hashes):
79 self.project_hashes = hashes
80 break
81
82 # Detect what repository and project we are being run from.
83 self.repo_root, self.repo_project = detect_project(os.getcwd())
84
85 # If we are running from an fbsource repository, set self.fbsource_dir
86 # to allow the ShipIt-based fetchers to use it.
87 if self.repo_project == "fbsource":
88 self.fbsource_dir: Optional[str] = self.repo_root
89 else:
90 self.fbsource_dir = None
91
92 if facebook_internal is None:
93 if self.fbsource_dir:
94 facebook_internal = True
95 else:
96 facebook_internal = False
97
98 self.facebook_internal = facebook_internal
99 self.specified_num_jobs = num_jobs
100 self.scratch_dir = scratch_dir
101 self.install_dir = install_dir
102 self.fbcode_builder_dir = fbcode_builder_dir
103 self.host_type = host_type
104 self.use_shipit = use_shipit
105 self.allow_system_packages = allow_system_packages
106 self.lfs_path = lfs_path
107 self.shared_libs = shared_libs
108 self.free_up_disk = free_up_disk
109
110 lib_path = None
111 if self.is_darwin():
112 lib_path = "DYLD_LIBRARY_PATH"
113 elif self.is_linux():
114 lib_path = "LD_LIBRARY_PATH"
115 elif self.is_windows():
116 lib_path = "PATH"
117 else:
118 lib_path = None
119 self.lib_path = lib_path
120
121 if vcvars_path is None and is_windows():
122
123 try:
124 # Allow a site-specific vcvarsall path.
125 from .facebook.vcvarsall import build_default_vcvarsall
126 except ImportError:
127 vcvarsall = []
128 else:
129 vcvarsall = (
130 build_default_vcvarsall(self.fbsource_dir)
131 if self.fbsource_dir is not None
132 else []
133 )
134
135 # On Windows, the compiler is not available in the PATH by
136 # default so we need to run the vcvarsall script to populate the
137 # environment. We use a glob to find some version of this script
138 # as deployed with Visual Studio 2017. This logic can also
139 # locate Visual Studio 2019 but note that at the time of writing
140 # the version of boost in our manifest cannot be built with
141 # VS 2019, so we're effectively tied to VS 2017 until we upgrade
142 # the boost dependency.
143 for year in ["2017", "2019"]:
144 vcvarsall += glob.glob(
145 os.path.join(
146 os.environ["ProgramFiles(x86)"],
147 "Microsoft Visual Studio",
148 year,
149 "*",
150 "VC",
151 "Auxiliary",
152 "Build",
153 "vcvarsall.bat",
154 )
155 )
156 vcvars_path = vcvarsall[0]
157
158 self.vcvars_path = vcvars_path
159
160 @property
161 def manifests_dir(self):
162 return os.path.join(self.fbcode_builder_dir, "manifests")
163
164 def is_darwin(self):
165 return self.host_type.is_darwin()
166
167 def is_windows(self):
168 return self.host_type.is_windows()
169
170 def is_arm(self):
171 return self.host_type.is_arm()
172
173 def get_vcvars_path(self):
174 return self.vcvars_path
175
176 def is_linux(self):
177 return self.host_type.is_linux()
178
179 def is_freebsd(self):
180 return self.host_type.is_freebsd()
181
182 def get_num_jobs(self, job_weight: int) -> int:
183 """Given an estimated job_weight in MiB, compute a reasonable concurrency limit."""
184 if self.specified_num_jobs:
185 return self.specified_num_jobs
186
187 available_ram = get_available_ram()
188
189 import multiprocessing
190
191 return max(1, min(multiprocessing.cpu_count(), available_ram // job_weight))
192
193 def get_context_generator(self, host_tuple=None):
194 """Create a manifest ContextGenerator for the specified target platform."""
195 if host_tuple is None:
196 host_type = self.host_type
197 elif isinstance(host_tuple, HostType):
198 host_type = host_tuple
199 else:
200 host_type = HostType.from_tuple_string(host_tuple)
201
202 return ContextGenerator(
203 {
204 "os": host_type.ostype,
205 "distro": host_type.distro,
206 "distro_vers": host_type.distrovers,
207 "fb": "on" if self.facebook_internal else "off",
208 "fbsource": "on" if self.fbsource_dir else "off",
209 "test": "off",
210 "shared_libs": "on" if self.shared_libs else "off",
211 }
212 )
213
214 def compute_env_for_install_dirs(
215 self, install_dirs, env=None, manifest=None
216 ): # noqa: C901
217 if env is not None:
218 env = env.copy()
219 else:
220 env = Env()
221
222 env["GETDEPS_BUILD_DIR"] = os.path.join(self.scratch_dir, "build")
223 env["GETDEPS_INSTALL_DIR"] = self.install_dir
224
225 # Python setuptools attempts to discover a local MSVC for
226 # building Python extensions. On Windows, getdeps already
227 # supports invoking a vcvarsall prior to compilation.
228 #
229 # Tell setuptools to bypass its own search. This fixes a bug
230 # where setuptools would fail when run from CMake on GitHub
231 # Actions with the inscrutable message 'error: Microsoft
232 # Visual C++ 14.0 is required. Get it with "Build Tools for
233 # Visual Studio"'. I suspect the actual error is that the
234 # environment or PATH is overflowing.
235 #
236 # For extra credit, someone could patch setuptools to
237 # propagate the actual error message from vcvarsall, because
238 # often it does not mean Visual C++ is not available.
239 #
240 # Related discussions:
241 # - https://github.com/pypa/setuptools/issues/2028
242 # - https://github.com/pypa/setuptools/issues/2307
243 # - https://developercommunity.visualstudio.com/t/error-microsoft-visual-c-140-is-required/409173
244 # - https://github.com/OpenMS/OpenMS/pull/4779
245 # - https://github.com/actions/virtual-environments/issues/1484
246
247 if self.is_windows() and self.get_vcvars_path():
248 env["DISTUTILS_USE_SDK"] = "1"
249
250 # On macOS we need to set `SDKROOT` when we use clang for system
251 # header files.
252 if self.is_darwin() and "SDKROOT" not in env:
253 sdkroot = subprocess.check_output(["xcrun", "--show-sdk-path"])
254 env["SDKROOT"] = sdkroot.decode().strip()
255
256 if (
257 self.is_darwin()
258 and self.allow_system_packages
259 and self.host_type.get_package_manager() == "homebrew"
260 and manifest
261 and manifest.resolved_system_packages
262 ):
263 # Homebrew packages may not be on the default PATHs
264 brew_packages = manifest.resolved_system_packages.get("homebrew", [])
265 for p in brew_packages:
266 found = self.add_homebrew_package_to_env(p, env)
267 # Try extra hard to find openssl, needed with homebrew on macOS
268 if found and p.startswith("openssl"):
269 candidate = homebrew_package_prefix("[email protected]")
270 if os.path.exists(candidate):
271 os.environ["OPENSSL_ROOT_DIR"] = candidate
272 env["OPENSSL_ROOT_DIR"] = os.environ["OPENSSL_ROOT_DIR"]
273
274 if self.fbsource_dir:
275 env["YARN_YARN_OFFLINE_MIRROR"] = os.path.join(
276 self.fbsource_dir, "xplat/third-party/yarn/offline-mirror"
277 )
278 yarn_exe = "yarn.bat" if self.is_windows() else "yarn"
279 env["YARN_PATH"] = os.path.join(
280 self.fbsource_dir, "xplat/third-party/yarn/", yarn_exe
281 )
282 node_exe = "node-win-x64.exe" if self.is_windows() else "node"
283 env["NODE_BIN"] = os.path.join(
284 self.fbsource_dir, "xplat/third-party/node/bin/", node_exe
285 )
286 env["RUST_VENDORED_CRATES_DIR"] = os.path.join(
287 self.fbsource_dir, "third-party/rust/vendor"
288 )
289 hash_data = get_fbsource_repo_data(self)
290 env["FBSOURCE_HASH"] = hash_data.hash
291 env["FBSOURCE_DATE"] = hash_data.date
292
293 # reverse as we are prepending to the PATHs
294 for d in reversed(install_dirs):
295 self.add_prefix_to_env(d, env, append=False)
296
297 # Linux is always system openssl
298 system_openssl = self.is_linux()
299
300 # For other systems lets see if package is requested
301 if not system_openssl and manifest and manifest.resolved_system_packages:
302 for _pkg_type, pkgs in manifest.resolved_system_packages.items():
303 for p in pkgs:
304 if p.startswith("openssl") or p.startswith("libssl"):
305 system_openssl = True
306 break
307
308 # Let openssl know to pick up the system certs if present
309 if system_openssl or "OPENSSL_DIR" in env:
310 for system_ssl_cfg in ["/etc/pki/tls", "/etc/ssl"]:
311 if os.path.isdir(system_ssl_cfg):
312 cert_dir = system_ssl_cfg + "/certs"
313 if os.path.isdir(cert_dir):
314 env["SSL_CERT_DIR"] = cert_dir
315 cert_file = system_ssl_cfg + "/cert.pem"
316 if os.path.isfile(cert_file):
317 env["SSL_CERT_FILE"] = cert_file
318
319 return env
320
321 def add_homebrew_package_to_env(self, package, env) -> bool:
322 prefix = homebrew_package_prefix(package)
323 if prefix and os.path.exists(prefix):
324 return self.add_prefix_to_env(
325 prefix, env, append=False, add_library_path=True
326 )
327 return False
328
329 def add_prefix_to_env(
330 self, d, env, append: bool = True, add_library_path: bool = False
331 ) -> bool: # noqa: C901
332 bindir = os.path.join(d, "bin")
333 found = False
334 pkgconfig = os.path.join(d, "lib", "pkgconfig")
335 if os.path.exists(pkgconfig):
336 found = True
337 add_path_entry(env, "PKG_CONFIG_PATH", pkgconfig, append=append)
338
339 pkgconfig = os.path.join(d, "lib64", "pkgconfig")
340 if os.path.exists(pkgconfig):
341 found = True
342 add_path_entry(env, "PKG_CONFIG_PATH", pkgconfig, append=append)
343
344 add_path_entry(env, "CMAKE_PREFIX_PATH", d, append=append)
345
346 # Tell the thrift compiler about includes it needs to consider
347 thriftdir = os.path.join(d, "include", "thrift-files")
348 if os.path.exists(thriftdir):
349 found = True
350 add_path_entry(env, "THRIFT_INCLUDE_PATH", thriftdir, append=append)
351
352 # module detection for python is old fashioned and needs flags
353 includedir = os.path.join(d, "include")
354 if os.path.exists(includedir):
355 found = True
356 ncursesincludedir = os.path.join(d, "include", "ncurses")
357 if os.path.exists(ncursesincludedir):
358 add_path_entry(env, "C_INCLUDE_PATH", ncursesincludedir, append=append)
359 add_flag(env, "CPPFLAGS", f"-I{includedir}", append=append)
360 add_flag(env, "CPPFLAGS", f"-I{ncursesincludedir}", append=append)
361 elif "/bz2-" in d:
362 add_flag(env, "CPPFLAGS", f"-I{includedir}", append=append)
363
364 # Map from FB python manifests to PYTHONPATH
365 pydir = os.path.join(d, "lib", "fb-py-libs")
366 if os.path.exists(pydir):
367 found = True
368 manifest_ext = ".manifest"
369 pymanifestfiles = [
370 f
371 for f in os.listdir(pydir)
372 if f.endswith(manifest_ext) and os.path.isfile(os.path.join(pydir, f))
373 ]
374 for f in pymanifestfiles:
375 subdir = f[: -len(manifest_ext)]
376 add_path_entry(
377 env, "PYTHONPATH", os.path.join(pydir, subdir), append=append
378 )
379
380 # Allow resolving shared objects built earlier (eg: zstd
381 # doesn't include the full path to the dylib in its linkage
382 # so we need to give it an assist)
383 if self.lib_path:
384 for lib in ["lib", "lib64"]:
385 libdir = os.path.join(d, lib)
386 if os.path.exists(libdir):
387 found = True
388 add_path_entry(env, self.lib_path, libdir, append=append)
389 # module detection for python is old fashioned and needs flags
390 if "/ncurses-" in d:
391 add_flag(env, "LDFLAGS", f"-L{libdir}", append=append)
392 elif "/bz2-" in d:
393 add_flag(env, "LDFLAGS", f"-L{libdir}", append=append)
394 if add_library_path:
395 add_path_entry(env, "LIBRARY_PATH", libdir, append=append)
396
397 # Allow resolving binaries (eg: cmake, ninja) and dlls
398 # built by earlier steps
399 if os.path.exists(bindir):
400 found = True
401 add_path_entry(env, "PATH", bindir, append=append)
402
403 # If rustc is present in the `bin` directory, set RUSTC to prevent
404 # cargo uses the rustc installed in the system.
405 if self.is_windows():
406 cargo_path = os.path.join(bindir, "cargo.exe")
407 rustc_path = os.path.join(bindir, "rustc.exe")
408 rustdoc_path = os.path.join(bindir, "rustdoc.exe")
409 else:
410 cargo_path = os.path.join(bindir, "cargo")
411 rustc_path = os.path.join(bindir, "rustc")
412 rustdoc_path = os.path.join(bindir, "rustdoc")
413
414 if os.path.isfile(rustc_path):
415 env["CARGO_BIN"] = cargo_path
416 env["RUSTC"] = rustc_path
417 env["RUSTDOC"] = rustdoc_path
418
419 openssl_include = os.path.join(d, "include", "openssl")
420 if os.path.isdir(openssl_include) and any(
421 os.path.isfile(os.path.join(d, "lib", libcrypto))
422 for libcrypto in ("libcrypto.lib", "libcrypto.so", "libcrypto.a")
423 ):
424 # This must be the openssl library, let Rust know about it
425 env["OPENSSL_DIR"] = d
426
427 return found
428
429
430 def list_win32_subst_letters():
431 output = subprocess.check_output(["subst"]).decode("utf-8")
432 # The output is a set of lines like: `F:\: => C:\open\some\where`
433 lines = output.strip().split("\r\n")
434 mapping = {}
435 for line in lines:
436 fields = line.split(": => ")
437 if len(fields) != 2:
438 continue
439 letter = fields[0]
440 path = fields[1]
441 mapping[letter] = path
442
443 return mapping
444
445
446 def find_existing_win32_subst_for_path(
447 path: str,
448 subst_mapping: Mapping[str, str],
449 ) -> Optional[str]:
450 path = ntpath.normcase(ntpath.normpath(path))
451 for letter, target in subst_mapping.items():
452 if ntpath.normcase(target) == path:
453 return letter
454 return None
455
456
457 def find_unused_drive_letter():
458 import ctypes
459
460 buffer_len = 256
461 blen = ctypes.c_uint(buffer_len)
462 rv = ctypes.c_uint()
463 bufs = ctypes.create_string_buffer(buffer_len)
464 rv = ctypes.windll.kernel32.GetLogicalDriveStringsA(blen, bufs)
465 if rv > buffer_len:
466 raise Exception("GetLogicalDriveStringsA result too large for buffer")
467 nul = "\x00".encode("ascii")
468
469 used = [drive.decode("ascii")[0] for drive in bufs.raw.strip(nul).split(nul)]
470 possible = [c for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
471 available = sorted(list(set(possible) - set(used)))
472 if len(available) == 0:
473 return None
474 # Prefer to assign later letters rather than earlier letters
475 return available[-1]
476
477
478 def create_subst_path(path: str) -> str:
479 for _attempt in range(0, 24):
480 drive = find_existing_win32_subst_for_path(
481 path, subst_mapping=list_win32_subst_letters()
482 )
483 if drive:
484 return drive
485 available = find_unused_drive_letter()
486 if available is None:
487 raise Exception(
488 (
489 "unable to make shorter subst mapping for %s; "
490 "no available drive letters"
491 )
492 % path
493 )
494
495 # Try to set up a subst mapping; note that we may be racing with
496 # other processes on the same host, so this may not succeed.
497 try:
498 subprocess.check_call(["subst", "%s:" % available, path])
499 return "%s:\\" % available
500 except Exception:
501 print("Failed to map %s -> %s" % (available, path))
502
503 raise Exception("failed to set up a subst path for %s" % path)
504
505
506 def _check_host_type(args, host_type):
507 if host_type is None:
508 host_tuple_string = getattr(args, "host_type", None)
509 if host_tuple_string:
510 host_type = HostType.from_tuple_string(host_tuple_string)
511 else:
512 host_type = HostType()
513
514 assert isinstance(host_type, HostType)
515 return host_type
516
517
518 def setup_build_options(args, host_type=None) -> BuildOptions:
519 """Create a BuildOptions object based on the arguments"""
520
521 fbcode_builder_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
522 scratch_dir = args.scratch_path
523 if not scratch_dir:
524 # TODO: `mkscratch` doesn't currently know how best to place things on
525 # sandcastle, so whip up something reasonable-ish
526 if "SANDCASTLE" in os.environ:
527 if "DISK_TEMP" not in os.environ:
528 raise Exception(
529 (
530 "I need DISK_TEMP to be set in the sandcastle environment "
531 "so that I can store build products somewhere sane"
532 )
533 )
534 scratch_dir = os.path.join(
535 os.environ["DISK_TEMP"], "fbcode_builder_getdeps"
536 )
537 if not scratch_dir:
538 try:
539 scratch_dir = (
540 subprocess.check_output(
541 ["mkscratch", "path", "--subdir", "fbcode_builder_getdeps"]
542 )
543 .strip()
544 .decode("utf-8")
545 )
546 except OSError as exc:
547 if exc.errno != errno.ENOENT:
548 # A legit failure; don't fall back, surface the error
549 raise
550 # This system doesn't have mkscratch so we fall back to
551 # something local.
552 munged = fbcode_builder_dir.replace("Z", "zZ")
553 for s in ["/", "\\", ":"]:
554 munged = munged.replace(s, "Z")
555
556 if is_windows() and os.path.isdir("c:/open"):
557 temp = "c:/open/scratch"
558 else:
559 temp = tempfile.gettempdir()
560
561 scratch_dir = os.path.join(temp, "fbcode_builder_getdeps-%s" % munged)
562 if not is_windows() and os.geteuid() == 0:
563 # Running as root; in the case where someone runs
564 # sudo getdeps.py install-system-deps
565 # and then runs as build without privs, we want to avoid creating
566 # a scratch dir that the second stage cannot write to.
567 # So we generate a different path if we are root.
568 scratch_dir += "-root"
569
570 if not os.path.exists(scratch_dir):
571 os.makedirs(scratch_dir)
572
573 if is_windows():
574 subst = create_subst_path(scratch_dir)
575 print(
576 "Mapping scratch dir %s -> %s" % (scratch_dir, subst), file=sys.stderr
577 )
578 scratch_dir = subst
579 else:
580 if not os.path.exists(scratch_dir):
581 os.makedirs(scratch_dir)
582
583 # Make sure we normalize the scratch path. This path is used as part of the hash
584 # computation for detecting if projects have been updated, so we need to always
585 # use the exact same string to refer to a given directory.
586 # But! realpath in some combinations of Windows/Python3 versions can expand the
587 # drive substitutions on Windows, so avoid that!
588 if not is_windows():
589 scratch_dir = os.path.realpath(scratch_dir)
590
591 # Save these args passed by the user in an env variable, so it
592 # can be used while hashing this build.
593 os.environ["GETDEPS_CMAKE_DEFINES"] = getattr(args, "extra_cmake_defines", "") or ""
594
595 host_type = _check_host_type(args, host_type)
596
597 build_args = {
598 k: v
599 for (k, v) in vars(args).items()
600 if k
601 in {
602 "num_jobs",
603 "use_shipit",
604 "vcvars_path",
605 "allow_system_packages",
606 "lfs_path",
607 "shared_libs",
608 "free_up_disk",
609 }
610 }
611
612 return BuildOptions(
613 fbcode_builder_dir,
614 scratch_dir,
615 host_type,
616 install_dir=args.install_prefix,
617 facebook_internal=args.facebook_internal,
618 **build_args,
619 )