Debian Codegraph @

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

raw
1 #!/usr/bin/env python3
2 # Copyright (c) Meta Platforms, Inc. and affiliates.
3 #
4 # This source code is licensed under the MIT license found in the
5 # LICENSE file in the root directory of this source tree.
6
7 import glob
8 import json
9 import os
10 import pathlib
11 import shutil
12 import stat
13 import subprocess
14 import sys
15 import typing
16 from typing import Optional
17
18 from .dyndeps import create_dyn_dep_munger
19 from .envfuncs import add_path_entry, Env, path_search
20 from .fetcher import copy_if_different
21 from .runcmd import run_cmd
22
23 if typing.TYPE_CHECKING:
24 from .buildopts import BuildOptions
25
26
27 class BuilderBase(object):
28 def __init__(
29 self,
30 build_opts: "BuildOptions",
31 ctx,
32 manifest,
33 src_dir,
34 build_dir,
35 inst_dir,
36 env=None,
37 final_install_prefix=None,
38 ) -> None:
39 self.env = Env()
40 if env:
41 self.env.update(env)
42
43 subdir = manifest.get("build", "subdir", ctx=ctx)
44 if subdir:
45 src_dir = os.path.join(src_dir, subdir)
46
47 self.patchfile = manifest.get("build", "patchfile", ctx=ctx)
48 self.patchfile_opts = manifest.get("build", "patchfile_opts", ctx=ctx) or ""
49 self.ctx = ctx
50 self.src_dir = src_dir
51 self.build_dir = build_dir or src_dir
52 self.inst_dir = inst_dir
53 self.build_opts = build_opts
54 self.manifest = manifest
55 self.final_install_prefix = final_install_prefix
56
57 def _get_cmd_prefix(self):
58 if self.build_opts.is_windows():
59 vcvarsall = self.build_opts.get_vcvars_path()
60 if vcvarsall is not None:
61 # Since it sets rather a large number of variables we mildly abuse
62 # the cmd quoting rules to assemble a command that calls the script
63 # to prep the environment and then triggers the actual command that
64 # we wanted to run.
65 return [vcvarsall, "amd64", "&&"]
66 return []
67
68 def _run_cmd(
69 self,
70 cmd,
71 cwd=None,
72 env=None,
73 use_cmd_prefix: bool = True,
74 allow_fail: bool = False,
75 ) -> int:
76 if env:
77 e = self.env.copy()
78 e.update(env)
79 env = e
80 else:
81 env = self.env
82
83 if use_cmd_prefix:
84 cmd_prefix = self._get_cmd_prefix()
85 if cmd_prefix:
86 cmd = cmd_prefix + cmd
87
88 log_file = os.path.join(self.build_dir, "getdeps_build.log")
89 return run_cmd(
90 cmd=cmd,
91 env=env,
92 cwd=cwd or self.build_dir,
93 log_file=log_file,
94 allow_fail=allow_fail,
95 )
96
97 def _reconfigure(self, reconfigure: bool) -> bool:
98 if self.build_dir is not None:
99 if not os.path.isdir(self.build_dir):
100 os.makedirs(self.build_dir)
101 reconfigure = True
102 return reconfigure
103
104 def _apply_patchfile(self) -> None:
105 if self.patchfile is None:
106 return
107 patched_sentinel_file = pathlib.Path(self.src_dir + "/.getdeps_patched")
108 if patched_sentinel_file.exists():
109 return
110 old_wd = os.getcwd()
111 os.chdir(self.src_dir)
112 print(f"Patching {self.manifest.name} with {self.patchfile} in {self.src_dir}")
113 patchfile = os.path.join(
114 self.build_opts.fbcode_builder_dir, "patches", self.patchfile
115 )
116 patchcmd = ["git", "apply"]
117 if self.patchfile_opts:
118 patchcmd.append(self.patchfile_opts)
119 try:
120 subprocess.check_call(patchcmd + [patchfile])
121 except subprocess.CalledProcessError:
122 raise ValueError(f"Failed to apply patch to {self.manifest.name}")
123 os.chdir(old_wd)
124 patched_sentinel_file.touch()
125
126 def prepare(self, install_dirs, reconfigure: bool) -> None:
127 print("Preparing %s..." % self.manifest.name)
128 reconfigure = self._reconfigure(reconfigure)
129 self._apply_patchfile()
130 self._prepare(install_dirs=install_dirs, reconfigure=reconfigure)
131
132 def build(self, install_dirs, reconfigure: bool) -> None:
133 print("Building %s..." % self.manifest.name)
134 reconfigure = self._reconfigure(reconfigure)
135 self._apply_patchfile()
136 self._prepare(install_dirs=install_dirs, reconfigure=reconfigure)
137 self._build(install_dirs=install_dirs, reconfigure=reconfigure)
138
139 if self.build_opts.free_up_disk:
140 # don't clean --src-dir=. case as user may want to build again or run tests on the build
141 if self.src_dir.startswith(self.build_opts.scratch_dir) and os.path.isdir(
142 self.build_dir
143 ):
144 if os.path.islink(self.build_dir):
145 os.remove(self.build_dir)
146 else:
147 shutil.rmtree(self.build_dir)
148
149 # On Windows, emit a wrapper script that can be used to run build artifacts
150 # directly from the build directory, without installing them. On Windows $PATH
151 # needs to be updated to include all of the directories containing the runtime
152 # library dependencies in order to run the binaries.
153 if self.build_opts.is_windows():
154 script_path = self.get_dev_run_script_path()
155 dep_munger = create_dyn_dep_munger(self.build_opts, install_dirs)
156 dep_dirs = self.get_dev_run_extra_path_dirs(install_dirs, dep_munger)
157 # pyre-fixme[16]: Optional type has no attribute `emit_dev_run_script`.
158 dep_munger.emit_dev_run_script(script_path, dep_dirs)
159
160 @property
161 def num_jobs(self) -> int:
162 # This is a hack, but we don't have a "defaults manifest" that we can
163 # customize per platform.
164 # TODO: Introduce some sort of defaults config that can select by
165 # platform, just like manifest contexts.
166 if sys.platform.startswith("freebsd"):
167 # clang on FreeBSD is quite memory-efficient.
168 default_job_weight = 512
169 else:
170 # 1.5 GiB is a lot to assume, but it's typical of Facebook-style C++.
171 # Some manifests are even heavier and should override.
172 default_job_weight = 1536
173 return self.build_opts.get_num_jobs(
174 int(
175 self.manifest.get(
176 "build", "job_weight_mib", default_job_weight, ctx=self.ctx
177 )
178 )
179 )
180
181 def run_tests(
182 self, install_dirs, schedule_type, owner, test_filter, retry, no_testpilot
183 ) -> None:
184 """Execute any tests that we know how to run. If they fail,
185 raise an exception."""
186 pass
187
188 def _prepare(self, install_dirs, reconfigure) -> None:
189 """Prepare the build. Useful when need to generate config,
190 but builder is not the primary build system.
191 e.g. cargo when called from cmake"""
192 pass
193
194 def _build(self, install_dirs, reconfigure) -> None:
195 """Perform the build.
196 install_dirs contains the list of installation directories for
197 the dependencies of this project.
198 reconfigure will be set to true if the fetcher determined
199 that the sources have changed in such a way that the build
200 system needs to regenerate its rules."""
201 pass
202
203 def _compute_env(self, install_dirs):
204 # CMAKE_PREFIX_PATH is only respected when passed through the
205 # environment, so we construct an appropriate path to pass down
206 return self.build_opts.compute_env_for_install_dirs(
207 install_dirs, env=self.env, manifest=self.manifest
208 )
209
210 def get_dev_run_script_path(self):
211 assert self.build_opts.is_windows()
212 return os.path.join(self.build_dir, "run.ps1")
213
214 def get_dev_run_extra_path_dirs(self, install_dirs, dep_munger=None):
215 assert self.build_opts.is_windows()
216 if dep_munger is None:
217 dep_munger = create_dyn_dep_munger(self.build_opts, install_dirs)
218 return dep_munger.compute_dependency_paths(self.build_dir)
219
220
221 class MakeBuilder(BuilderBase):
222 def __init__(
223 self,
224 build_opts,
225 ctx,
226 manifest,
227 src_dir,
228 build_dir,
229 inst_dir,
230 build_args,
231 install_args,
232 test_args,
233 ) -> None:
234 super(MakeBuilder, self).__init__(
235 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
236 )
237 self.build_args = build_args or []
238 self.install_args = install_args or []
239 self.test_args = test_args
240
241 @property
242 def _make_binary(self):
243 return self.manifest.get("build", "make_binary", "make", ctx=self.ctx)
244
245 def _get_prefix(self):
246 return ["PREFIX=" + self.inst_dir, "prefix=" + self.inst_dir]
247
248 def _build(self, install_dirs, reconfigure) -> None:
249
250 env = self._compute_env(install_dirs)
251
252 # Need to ensure that PREFIX is set prior to install because
253 # libbpf uses it when generating its pkg-config file.
254 # The lowercase prefix is used by some projects.
255 cmd = (
256 [self._make_binary, "-j%s" % self.num_jobs]
257 + self.build_args
258 + self._get_prefix()
259 )
260 self._run_cmd(cmd, env=env)
261
262 install_cmd = [self._make_binary] + self.install_args + self._get_prefix()
263 self._run_cmd(install_cmd, env=env)
264
265 # bz2's Makefile doesn't install its .so properly
266 if self.manifest and self.manifest.name == "bz2":
267 libdir = os.path.join(self.inst_dir, "lib")
268 srcpattern = os.path.join(self.src_dir, "lib*.so.*")
269 print(f"copying to {libdir} from {srcpattern}")
270 for file in glob.glob(srcpattern):
271 shutil.copy(file, libdir)
272
273 def run_tests(
274 self, install_dirs, schedule_type, owner, test_filter, retry, no_testpilot
275 ) -> None:
276 if not self.test_args:
277 return
278
279 env = self._compute_env(install_dirs)
280
281 cmd = [self._make_binary] + self.test_args + self._get_prefix()
282 self._run_cmd(cmd, env=env)
283
284
285 class CMakeBootStrapBuilder(MakeBuilder):
286 def _build(self, install_dirs, reconfigure) -> None:
287 self._run_cmd(
288 [
289 "./bootstrap",
290 "--prefix=" + self.inst_dir,
291 f"--parallel={self.num_jobs}",
292 ]
293 )
294 super(CMakeBootStrapBuilder, self)._build(install_dirs, reconfigure)
295
296
297 class AutoconfBuilder(BuilderBase):
298 def __init__(
299 self,
300 build_opts,
301 ctx,
302 manifest,
303 src_dir,
304 build_dir,
305 inst_dir,
306 args,
307 conf_env_args,
308 ) -> None:
309 super(AutoconfBuilder, self).__init__(
310 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
311 )
312 self.args = args or []
313 self.conf_env_args = conf_env_args or {}
314
315 @property
316 def _make_binary(self):
317 return self.manifest.get("build", "make_binary", "make", ctx=self.ctx)
318
319 def _build(self, install_dirs, reconfigure) -> None:
320 configure_path = os.path.join(self.src_dir, "configure")
321 autogen_path = os.path.join(self.src_dir, "autogen.sh")
322
323 env = self._compute_env(install_dirs)
324
325 # Some configure scripts need additional env values passed derived from cmds
326 for (k, cmd_args) in self.conf_env_args.items():
327 out = (
328 subprocess.check_output(cmd_args, env=dict(env.items()))
329 .decode("utf-8")
330 .strip()
331 )
332 if out:
333 env.set(k, out)
334
335 if not os.path.exists(configure_path):
336 print("%s doesn't exist, so reconfiguring" % configure_path)
337 # This libtoolize call is a bit gross; the issue is that
338 # `autoreconf` as invoked by libsodium's `autogen.sh` doesn't
339 # seem to realize that it should invoke libtoolize and then
340 # error out when the configure script references a libtool
341 # related symbol.
342 self._run_cmd(["libtoolize"], cwd=self.src_dir, env=env)
343
344 # We generally prefer to call the `autogen.sh` script provided
345 # by the project on the basis that it may know more than plain
346 # autoreconf does.
347 if os.path.exists(autogen_path):
348 self._run_cmd(["bash", autogen_path], cwd=self.src_dir, env=env)
349 else:
350 self._run_cmd(["autoreconf", "-ivf"], cwd=self.src_dir, env=env)
351 configure_cmd = [configure_path, "--prefix=" + self.inst_dir] + self.args
352 self._run_cmd(configure_cmd, env=env)
353 self._run_cmd([self._make_binary, "-j%s" % self.num_jobs], env=env)
354 self._run_cmd([self._make_binary, "install"], env=env)
355
356
357 class Iproute2Builder(BuilderBase):
358 # ./configure --prefix does not work for iproute2.
359 # Thus, explicitly copy sources from src_dir to build_dir, build,
360 # and then install to inst_dir using DESTDIR
361 # lastly, also copy include from build_dir to inst_dir
362 def __init__(self, build_opts, ctx, manifest, src_dir, build_dir, inst_dir) -> None:
363 super(Iproute2Builder, self).__init__(
364 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
365 )
366
367 def _patch(self) -> None:
368 # FBOSS build currently depends on an old version of iproute2 (commit
369 # 7ca63aef7d1b0c808da0040c6b366ef7a61f38c1). This is missing a commit
370 # (ae717baf15fb4d30749ada3948d9445892bac239) needed to build iproute2
371 # successfully. Apply it viz.: include stdint.h
372 # Reference: https://fburl.com/ilx9g5xm
373 with open(self.build_dir + "/tc/tc_core.c", "r") as f:
374 data = f.read()
375
376 with open(self.build_dir + "/tc/tc_core.c", "w") as f:
377 f.write("#include <stdint.h>\n")
378 f.write(data)
379
380 def _build(self, install_dirs, reconfigure) -> None:
381 configure_path = os.path.join(self.src_dir, "configure")
382
383 env = self.env.copy()
384 self._run_cmd([configure_path], env=env)
385 shutil.rmtree(self.build_dir)
386 shutil.copytree(self.src_dir, self.build_dir)
387 self._patch()
388 self._run_cmd(["make", "-j%s" % self.num_jobs], env=env)
389 install_cmd = ["make", "install", "DESTDIR=" + self.inst_dir]
390
391 for d in ["include", "lib"]:
392 if not os.path.isdir(os.path.join(self.inst_dir, d)):
393 shutil.copytree(
394 os.path.join(self.build_dir, d), os.path.join(self.inst_dir, d)
395 )
396
397 self._run_cmd(install_cmd, env=env)
398
399
400 class CMakeBuilder(BuilderBase):
401 MANUAL_BUILD_SCRIPT = """\
402 #!{sys.executable}
403
404
405 import argparse
406 import subprocess
407 import sys
408
409 CMAKE = {cmake!r}
410 CTEST = {ctest!r}
411 SRC_DIR = {src_dir!r}
412 BUILD_DIR = {build_dir!r}
413 INSTALL_DIR = {install_dir!r}
414 CMD_PREFIX = {cmd_prefix!r}
415 CMAKE_ENV = {env_str}
416 CMAKE_DEFINE_ARGS = {define_args_str}
417
418
419 def get_jobs_argument(num_jobs_arg: int) -> str:
420 if num_jobs_arg > 0:
421 return "-j" + str(num_jobs_arg)
422
423 import multiprocessing
424 num_jobs = multiprocessing.cpu_count() // 2
425 return "-j" + str(num_jobs)
426
427
428 def main():
429 ap = argparse.ArgumentParser()
430 ap.add_argument(
431 "cmake_args",
432 nargs=argparse.REMAINDER,
433 help='Any extra arguments after an "--" argument will be passed '
434 "directly to CMake."
435 )
436 ap.add_argument(
437 "--mode",
438 choices=["configure", "build", "install", "test"],
439 default="configure",
440 help="The mode to run: configure, build, or install. "
441 "Defaults to configure",
442 )
443 ap.add_argument(
444 "--build",
445 action="store_const",
446 const="build",
447 dest="mode",
448 help="An alias for --mode=build",
449 )
450 ap.add_argument(
451 "-j",
452 "--num-jobs",
453 action="store",
454 type=int,
455 default=0,
456 help="Run the build or tests with the specified number of parallel jobs",
457 )
458 ap.add_argument(
459 "--install",
460 action="store_const",
461 const="install",
462 dest="mode",
463 help="An alias for --mode=install",
464 )
465 ap.add_argument(
466 "--test",
467 action="store_const",
468 const="test",
469 dest="mode",
470 help="An alias for --mode=test",
471 )
472 args = ap.parse_args()
473
474 # Strip off a leading "--" from the additional CMake arguments
475 if args.cmake_args and args.cmake_args[0] == "--":
476 args.cmake_args = args.cmake_args[1:]
477
478 env = CMAKE_ENV
479
480 if args.mode == "configure":
481 full_cmd = CMD_PREFIX + [CMAKE, SRC_DIR] + CMAKE_DEFINE_ARGS + args.cmake_args
482 elif args.mode in ("build", "install"):
483 target = "all" if args.mode == "build" else "install"
484 full_cmd = CMD_PREFIX + [
485 CMAKE,
486 "--build",
487 BUILD_DIR,
488 "--target",
489 target,
490 "--config",
491 "Release",
492 get_jobs_argument(args.num_jobs),
493 ] + args.cmake_args
494 elif args.mode == "test":
495 full_cmd = CMD_PREFIX + [
496 {dev_run_script}CTEST,
497 "--output-on-failure",
498 get_jobs_argument(args.num_jobs),
499 ] + args.cmake_args
500 else:
501 ap.error("unknown invocation mode: %s" % (args.mode,))
502
503 cmd_str = " ".join(full_cmd)
504 print("Running: %r" % (cmd_str,))
505 proc = subprocess.run(full_cmd, env=env, cwd=BUILD_DIR)
506 sys.exit(proc.returncode)
507
508
509 if __name__ == "__main__":
510 main()
511 """
512
513 def __init__(
514 self,
515 build_opts,
516 ctx,
517 manifest,
518 src_dir,
519 build_dir,
520 inst_dir,
521 defines,
522 loader=None,
523 final_install_prefix=None,
524 extra_cmake_defines=None,
525 cmake_target="install",
526 ) -> None:
527 super(CMakeBuilder, self).__init__(
528 build_opts,
529 ctx,
530 manifest,
531 src_dir,
532 build_dir,
533 inst_dir,
534 final_install_prefix=final_install_prefix,
535 )
536 self.defines = defines or {}
537 if extra_cmake_defines:
538 self.defines.update(extra_cmake_defines)
539 self.cmake_target = cmake_target
540
541 try:
542 from .facebook.vcvarsall import extra_vc_cmake_defines
543 except ImportError:
544 pass
545 else:
546 self.defines.update(extra_vc_cmake_defines)
547
548 self.loader = loader
549 if build_opts.shared_libs:
550 self.defines["BUILD_SHARED_LIBS"] = "ON"
551
552 def _invalidate_cache(self) -> None:
553 for name in [
554 "CMakeCache.txt",
555 "CMakeFiles/CMakeError.log",
556 "CMakeFiles/CMakeOutput.log",
557 ]:
558 name = os.path.join(self.build_dir, name)
559 if os.path.isdir(name):
560 shutil.rmtree(name)
561 elif os.path.exists(name):
562 os.unlink(name)
563
564 def _needs_reconfigure(self) -> bool:
565 for name in ["CMakeCache.txt", "build.ninja"]:
566 name = os.path.join(self.build_dir, name)
567 if not os.path.exists(name):
568 return True
569 return False
570
571 def _write_build_script(self, **kwargs) -> None:
572 env_lines = [" {!r}: {!r},".format(k, v) for k, v in kwargs["env"].items()]
573 kwargs["env_str"] = "\n".join(["{"] + env_lines + ["}"])
574
575 if self.build_opts.is_windows():
576 kwargs["dev_run_script"] = '"powershell.exe", {!r}, '.format(
577 self.get_dev_run_script_path()
578 )
579 else:
580 kwargs["dev_run_script"] = ""
581
582 define_arg_lines = ["["]
583 for arg in kwargs["define_args"]:
584 # Replace the CMAKE_INSTALL_PREFIX argument to use the INSTALL_DIR
585 # variable that we define in the MANUAL_BUILD_SCRIPT code.
586 if arg.startswith("-DCMAKE_INSTALL_PREFIX="):
587 value = " {!r}.format(INSTALL_DIR),".format(
588 "-DCMAKE_INSTALL_PREFIX={}"
589 )
590 else:
591 value = " {!r},".format(arg)
592 define_arg_lines.append(value)
593 define_arg_lines.append("]")
594 kwargs["define_args_str"] = "\n".join(define_arg_lines)
595
596 # In order to make it easier for developers to manually run builds for
597 # CMake-based projects, write out some build scripts that can be used to invoke
598 # CMake manually.
599 build_script_path = os.path.join(self.build_dir, "run_cmake.py")
600 script_contents = self.MANUAL_BUILD_SCRIPT.format(**kwargs)
601 with open(build_script_path, "wb") as f:
602 f.write(script_contents.encode())
603 os.chmod(build_script_path, 0o755)
604
605 def _compute_cmake_define_args(self, env):
606 defines = {
607 "CMAKE_INSTALL_PREFIX": self.final_install_prefix or self.inst_dir,
608 "BUILD_SHARED_LIBS": "OFF",
609 # Some of the deps (rsocket) default to UBSAN enabled if left
610 # unspecified. Some of the deps fail to compile in release mode
611 # due to warning->error promotion. RelWithDebInfo is the happy
612 # medium.
613 "CMAKE_BUILD_TYPE": "RelWithDebInfo",
614 }
615 if "SANDCASTLE" not in os.environ:
616 # We sometimes see intermittent ccache related breakages on some
617 # of the FB internal CI hosts, so we prefer to disable ccache
618 # when running in that environment.
619 ccache = path_search(env, "ccache")
620 if ccache:
621 defines["CMAKE_CXX_COMPILER_LAUNCHER"] = ccache
622 else:
623 # rocksdb does its own probing for ccache.
624 # Ensure that it is disabled on sandcastle
625 env["CCACHE_DISABLE"] = "1"
626 # Some sandcastle hosts have broken ccache related dirs, and
627 # even though we've asked for it to be disabled ccache is
628 # still invoked by rocksdb's cmake.
629 # Redirect its config directory to somewhere that is guaranteed
630 # fresh to us, and that won't have any ccache data inside.
631 env["CCACHE_DIR"] = f"{self.build_opts.scratch_dir}/ccache"
632
633 if "GITHUB_ACTIONS" in os.environ and self.build_opts.is_windows():
634 # GitHub actions: the host has both gcc and msvc installed, and
635 # the default behavior of cmake is to prefer gcc.
636 # Instruct cmake that we want it to use cl.exe; this is important
637 # because Boost prefers cl.exe and the mismatch results in cmake
638 # with gcc not being able to find boost built with cl.exe.
639 defines["CMAKE_C_COMPILER"] = "cl.exe"
640 defines["CMAKE_CXX_COMPILER"] = "cl.exe"
641
642 if self.build_opts.is_darwin():
643 # Try to persuade cmake to set the rpath to match the lib
644 # dirs of the dependencies. This isn't automatic, and to
645 # make things more interesting, cmake uses `;` as the path
646 # separator, so translate the runtime path to something
647 # that cmake will parse
648 defines["CMAKE_INSTALL_RPATH"] = ";".join(
649 env.get("DYLD_LIBRARY_PATH", "").split(":")
650 )
651 # Tell cmake that we want to set the rpath in the tree
652 # at build time. Without this the rpath is only set
653 # at the moment that the binaries are installed. That
654 # default is problematic for example when using the
655 # gtest integration in cmake which runs the built test
656 # executables during the build to discover the set of
657 # tests.
658 defines["CMAKE_BUILD_WITH_INSTALL_RPATH"] = "ON"
659
660 boost_169_is_required = False
661 if self.loader:
662 for m in self.loader.manifests_in_dependency_order():
663 preinstalled = m.get_section_as_dict("preinstalled.env", self.ctx)
664 boost_169_is_required = "BOOST_ROOT_1_69_0" in preinstalled.keys()
665 if boost_169_is_required:
666 break
667
668 if (
669 boost_169_is_required
670 and self.build_opts.allow_system_packages
671 and self.build_opts.host_type.get_package_manager()
672 and self.build_opts.host_type.get_package_manager() == "rpm"
673 ):
674 # Boost 1.69 rpms don't install cmake config to the system, so to point to them explicitly
675 defines["BOOST_INCLUDEDIR"] = "/usr/include/boost169"
676 defines["BOOST_LIBRARYDIR"] = "/usr/lib64/boost169"
677
678 defines.update(self.defines)
679 define_args = ["-D%s=%s" % (k, v) for (k, v) in defines.items()]
680
681 # if self.build_opts.is_windows():
682 # define_args += ["-G", "Visual Studio 15 2017 Win64"]
683 define_args += ["-G", "Ninja"]
684
685 return define_args
686
687 def _build(self, install_dirs, reconfigure: bool) -> None:
688 reconfigure = reconfigure or self._needs_reconfigure()
689
690 env = self._compute_env(install_dirs)
691 if not self.build_opts.is_windows() and self.final_install_prefix:
692 env["DESTDIR"] = self.inst_dir
693
694 # Resolve the cmake that we installed
695 cmake = path_search(env, "cmake")
696 if cmake is None:
697 raise Exception("Failed to find CMake")
698
699 if reconfigure:
700 define_args = self._compute_cmake_define_args(env)
701 self._write_build_script(
702 cmd_prefix=self._get_cmd_prefix(),
703 cmake=cmake,
704 ctest=path_search(env, "ctest"),
705 env=env,
706 define_args=define_args,
707 src_dir=self.src_dir,
708 build_dir=self.build_dir,
709 install_dir=self.inst_dir,
710 sys=sys,
711 )
712
713 self._invalidate_cache()
714 self._run_cmd([cmake, self.src_dir] + define_args, env=env)
715
716 self._run_cmd(
717 [
718 cmake,
719 "--build",
720 self.build_dir,
721 "--target",
722 self.cmake_target,
723 "--config",
724 "Release",
725 "-j",
726 str(self.num_jobs),
727 ],
728 env=env,
729 )
730
731 def run_tests(
732 self, install_dirs, schedule_type, owner, test_filter, retry: int, no_testpilot
733 ) -> None:
734 env = self._compute_env(install_dirs)
735 ctest = path_search(env, "ctest")
736 cmake = path_search(env, "cmake")
737
738 def require_command(path: Optional[str], name: str) -> str:
739 if path is None:
740 raise RuntimeError("unable to find command `{}`".format(name))
741 return path
742
743 # On Windows, we also need to update $PATH to include the directories that
744 # contain runtime library dependencies. This is not needed on other platforms
745 # since CMake will emit RPATH properly in the binary so they can find these
746 # dependencies.
747 if self.build_opts.is_windows():
748 path_entries = self.get_dev_run_extra_path_dirs(install_dirs)
749 path = env.get("PATH")
750 if path:
751 path_entries.insert(0, path)
752 env["PATH"] = ";".join(path_entries)
753
754 # Don't use the cmd_prefix when running tests. This is vcvarsall.bat on
755 # Windows. vcvarsall.bat is only needed for the build, not tests. It
756 # unfortunately fails if invoked with a long PATH environment variable when
757 # running the tests.
758 use_cmd_prefix = False
759
760 def get_property(test, propname, defval=None):
761 """extracts a named property from a cmake test info json blob.
762 The properties look like:
763 [{"name": "WORKING_DIRECTORY"},
764 {"value": "something"}]
765 We assume that it is invalid for the same named property to be
766 listed more than once.
767 """
768 props = test.get("properties", [])
769 for p in props:
770 if p.get("name", None) == propname:
771 return p.get("value", defval)
772 return defval
773
774 def list_tests():
775 output = subprocess.check_output(
776 [require_command(ctest, "ctest"), "--show-only=json-v1"],
777 env=env,
778 cwd=self.build_dir,
779 )
780 try:
781 data = json.loads(output.decode("utf-8"))
782 except ValueError as exc:
783 raise Exception(
784 "Failed to decode cmake test info using %s: %s. Output was: %r"
785 % (ctest, str(exc), output)
786 )
787
788 tests = []
789 machine_suffix = self.build_opts.host_type.as_tuple_string()
790 for test in data["tests"]:
791 working_dir = get_property(test, "WORKING_DIRECTORY")
792 labels = []
793 machine_suffix = self.build_opts.host_type.as_tuple_string()
794 labels.append("tpx-fb-test-type=3")
795 labels.append("tpx_test_config::buildsystem=getdeps")
796 labels.append("tpx_test_config::platform={}".format(machine_suffix))
797
798 if get_property(test, "DISABLED"):
799 labels.append("disabled")
800 command = test["command"]
801 if working_dir:
802 command = [
803 require_command(cmake, "cmake"),
804 "-E",
805 "chdir",
806 working_dir,
807 ] + command
808
809 import os
810
811 tests.append(
812 {
813 "type": "custom",
814 "target": "%s-%s-getdeps-%s"
815 % (self.manifest.name, test["name"], machine_suffix),
816 "command": command,
817 "labels": labels,
818 "env": {},
819 "required_paths": [],
820 "contacts": [],
821 "cwd": os.getcwd(),
822 }
823 )
824 return tests
825
826 if schedule_type == "continuous" or schedule_type == "testwarden":
827 # for continuous and testwarden runs, disabling retry can give up
828 # better signals for flaky tests.
829 retry = 0
830
831 tpx = path_search(env, "tpx")
832 if tpx and not no_testpilot:
833 buck_test_info = list_tests()
834 import os
835
836 from .facebook.testinfra import start_run
837
838 buck_test_info_name = os.path.join(self.build_dir, ".buck-test-info.json")
839 with open(buck_test_info_name, "w") as f:
840 json.dump(buck_test_info, f)
841
842 env.set("http_proxy", "")
843 env.set("https_proxy", "")
844 runs = []
845 from sys import platform
846
847 with start_run(env["FBSOURCE_HASH"]) as run_id:
848 testpilot_args = [
849 tpx,
850 "--force-local-execution",
851 "--buck-test-info",
852 buck_test_info_name,
853 "--retry=%d" % retry,
854 "-j=%s" % str(self.num_jobs),
855 "--print-long-results",
856 ]
857
858 if owner:
859 testpilot_args += ["--contacts", owner]
860
861 if env:
862 testpilot_args.append("--env")
863 testpilot_args.extend(f"{key}={val}" for key, val in env.items())
864
865 if run_id is not None:
866 testpilot_args += ["--run-id", run_id]
867
868 if test_filter:
869 testpilot_args += ["--", test_filter]
870
871 if schedule_type == "diff":
872 runs.append(["--collection", "oss-diff", "--purpose", "diff"])
873 elif schedule_type == "continuous":
874 runs.append(
875 [
876 "--tag-new-tests",
877 "--collection",
878 "oss-continuous",
879 "--purpose",
880 "continuous",
881 ]
882 )
883 elif schedule_type == "testwarden":
884 # One run to assess new tests
885 runs.append(
886 [
887 "--tag-new-tests",
888 "--collection",
889 "oss-new-test-stress",
890 "--stress-runs",
891 "10",
892 "--purpose",
893 "stress-run-new-test",
894 ]
895 )
896 # And another for existing tests
897 runs.append(
898 [
899 "--tag-new-tests",
900 "--collection",
901 "oss-existing-test-stress",
902 "--stress-runs",
903 "10",
904 "--purpose",
905 "stress-run",
906 ]
907 )
908 else:
909 runs.append([])
910
911 for run in runs:
912 self._run_cmd(
913 testpilot_args + run,
914 cwd=self.build_opts.fbcode_builder_dir,
915 env=env,
916 use_cmd_prefix=use_cmd_prefix,
917 )
918 else:
919 args = [
920 require_command(ctest, "ctest"),
921 "--output-on-failure",
922 "-j",
923 str(self.num_jobs),
924 ]
925 if test_filter:
926 args += ["-R", test_filter]
927
928 count = 0
929 while count <= retry:
930 retcode = self._run_cmd(
931 args, env=env, use_cmd_prefix=use_cmd_prefix, allow_fail=True
932 )
933
934 if retcode == 0:
935 break
936 if count == 0:
937 # Only add this option in the second run.
938 args += ["--rerun-failed"]
939 count += 1
940 # pyre-fixme[61]: `retcode` is undefined, or not always defined.
941 if retcode != 0:
942 # Allow except clause in getdeps.main to catch and exit gracefully
943 # This allows non-testpilot runs to fail through the same logic as failed testpilot runs, which may become handy in case if post test processing is needed in the future
944 # pyre-fixme[61]: `retcode` is undefined, or not always defined.
945 raise subprocess.CalledProcessError(retcode, args)
946
947
948 class NinjaBootstrap(BuilderBase):
949 def __init__(self, build_opts, ctx, manifest, build_dir, src_dir, inst_dir) -> None:
950 super(NinjaBootstrap, self).__init__(
951 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
952 )
953
954 def _build(self, install_dirs, reconfigure) -> None:
955 self._run_cmd([sys.executable, "configure.py", "--bootstrap"], cwd=self.src_dir)
956 src_ninja = os.path.join(self.src_dir, "ninja")
957 dest_ninja = os.path.join(self.inst_dir, "bin/ninja")
958 bin_dir = os.path.dirname(dest_ninja)
959 if not os.path.exists(bin_dir):
960 os.makedirs(bin_dir)
961 shutil.copyfile(src_ninja, dest_ninja)
962 shutil.copymode(src_ninja, dest_ninja)
963
964
965 class OpenSSLBuilder(BuilderBase):
966 def __init__(self, build_opts, ctx, manifest, build_dir, src_dir, inst_dir) -> None:
967 super(OpenSSLBuilder, self).__init__(
968 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
969 )
970
971 def _build(self, install_dirs, reconfigure) -> None:
972 configure = os.path.join(self.src_dir, "Configure")
973
974 # prefer to resolve the perl that we installed from
975 # our manifest on windows, but fall back to the system
976 # path on eg: darwin
977 env = self.env.copy()
978 for d in install_dirs:
979 bindir = os.path.join(d, "bin")
980 add_path_entry(env, "PATH", bindir, append=False)
981
982 perl = typing.cast(str, path_search(env, "perl", "perl"))
983
984 make_j_args = []
985 if self.build_opts.is_windows():
986 make = "nmake.exe"
987 args = ["VC-WIN64A-masm", "-utf-8"]
988 elif self.build_opts.is_darwin():
989 make = "make"
990 make_j_args = ["-j%s" % self.num_jobs]
991 args = (
992 ["darwin64-x86_64-cc"]
993 if not self.build_opts.is_arm()
994 else ["darwin64-arm64-cc"]
995 )
996 elif self.build_opts.is_linux():
997 make = "make"
998 make_j_args = ["-j%s" % self.num_jobs]
999 args = (
1000 ["linux-x86_64"] if not self.build_opts.is_arm() else ["linux-aarch64"]
1001 )
1002 else:
1003 raise Exception("don't know how to build openssl for %r" % self.ctx)
1004
1005 self._run_cmd(
1006 [
1007 perl,
1008 configure,
1009 "--prefix=%s" % self.inst_dir,
1010 "--openssldir=%s" % self.inst_dir,
1011 ]
1012 + args
1013 + [
1014 "enable-static-engine",
1015 "enable-capieng",
1016 "no-makedepend",
1017 "no-unit-test",
1018 "no-tests",
1019 ]
1020 )
1021 make_build = [make] + make_j_args
1022 self._run_cmd(make_build)
1023 make_install = [make, "install_sw", "install_ssldirs"]
1024 self._run_cmd(make_install)
1025
1026
1027 class Boost(BuilderBase):
1028 def __init__(
1029 self, build_opts, ctx, manifest, src_dir, build_dir, inst_dir, b2_args
1030 ) -> None:
1031 children = os.listdir(src_dir)
1032 assert len(children) == 1, "expected a single directory entry: %r" % (children,)
1033 boost_src = children[0]
1034 assert boost_src.startswith("boost")
1035 src_dir = os.path.join(src_dir, children[0])
1036 super(Boost, self).__init__(
1037 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
1038 )
1039 self.b2_args = b2_args
1040
1041 def _build(self, install_dirs, reconfigure) -> None:
1042 env = self._compute_env(install_dirs)
1043 linkage = ["static"]
1044 if self.build_opts.is_windows() or self.build_opts.shared_libs:
1045 linkage.append("shared")
1046
1047 args = []
1048 if self.build_opts.is_darwin():
1049 clang = subprocess.check_output(["xcrun", "--find", "clang"])
1050 user_config = os.path.join(self.build_dir, "project-config.jam")
1051 with open(user_config, "w") as jamfile:
1052 jamfile.write("using clang : : %s ;\n" % clang.decode().strip())
1053 args.append("--user-config=%s" % user_config)
1054
1055 for link in linkage:
1056 bootstrap_args = self.manifest.get_section_as_args(
1057 "bootstrap.args", self.ctx
1058 )
1059 if self.build_opts.is_windows():
1060 bootstrap = os.path.join(self.src_dir, "bootstrap.bat")
1061 self._run_cmd([bootstrap] + bootstrap_args, cwd=self.src_dir, env=env)
1062 args += ["address-model=64"]
1063 else:
1064 bootstrap = os.path.join(self.src_dir, "bootstrap.sh")
1065 self._run_cmd(
1066 [bootstrap, "--prefix=%s" % self.inst_dir] + bootstrap_args,
1067 cwd=self.src_dir,
1068 env=env,
1069 )
1070
1071 b2 = os.path.join(self.src_dir, "b2")
1072 self._run_cmd(
1073 [
1074 b2,
1075 "-j%s" % self.num_jobs,
1076 "--prefix=%s" % self.inst_dir,
1077 "--builddir=%s" % self.build_dir,
1078 ]
1079 + args
1080 + self.b2_args
1081 + [
1082 "link=%s" % link,
1083 "runtime-link=shared",
1084 "variant=release",
1085 "threading=multi",
1086 "debug-symbols=on",
1087 "visibility=global",
1088 "-d2",
1089 "install",
1090 ],
1091 cwd=self.src_dir,
1092 env=env,
1093 )
1094
1095
1096 class NopBuilder(BuilderBase):
1097 def __init__(self, build_opts, ctx, manifest, src_dir, inst_dir) -> None:
1098 super(NopBuilder, self).__init__(
1099 build_opts, ctx, manifest, src_dir, None, inst_dir
1100 )
1101
1102 def build(self, install_dirs, reconfigure: bool) -> None:
1103 print("Installing %s -> %s" % (self.src_dir, self.inst_dir))
1104 parent = os.path.dirname(self.inst_dir)
1105 if not os.path.exists(parent):
1106 os.makedirs(parent)
1107
1108 install_files = self.manifest.get_section_as_ordered_pairs(
1109 "install.files", self.ctx
1110 )
1111 if install_files:
1112 for src_name, dest_name in self.manifest.get_section_as_ordered_pairs(
1113 "install.files", self.ctx
1114 ):
1115 full_dest = os.path.join(self.inst_dir, dest_name)
1116 full_src = os.path.join(self.src_dir, src_name)
1117
1118 dest_parent = os.path.dirname(full_dest)
1119 if not os.path.exists(dest_parent):
1120 os.makedirs(dest_parent)
1121 if os.path.isdir(full_src):
1122 if not os.path.exists(full_dest):
1123 shutil.copytree(full_src, full_dest)
1124 else:
1125 shutil.copyfile(full_src, full_dest)
1126 shutil.copymode(full_src, full_dest)
1127 # This is a bit gross, but the mac ninja.zip doesn't
1128 # give ninja execute permissions, so force them on
1129 # for things that look like they live in a bin dir
1130 if os.path.dirname(dest_name) == "bin":
1131 st = os.lstat(full_dest)
1132 os.chmod(full_dest, st.st_mode | stat.S_IXUSR)
1133 else:
1134 if not os.path.exists(self.inst_dir):
1135 shutil.copytree(self.src_dir, self.inst_dir)
1136
1137
1138 class SqliteBuilder(BuilderBase):
1139 def __init__(self, build_opts, ctx, manifest, src_dir, build_dir, inst_dir) -> None:
1140 super(SqliteBuilder, self).__init__(
1141 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
1142 )
1143
1144 def _build(self, install_dirs, reconfigure) -> None:
1145 for f in ["sqlite3.c", "sqlite3.h", "sqlite3ext.h"]:
1146 src = os.path.join(self.src_dir, f)
1147 dest = os.path.join(self.build_dir, f)
1148 copy_if_different(src, dest)
1149
1150 cmake_lists = """
1151 cmake_minimum_required(VERSION 3.1.3 FATAL_ERROR)
1152 project(sqlite3 C)
1153 add_library(sqlite3 STATIC sqlite3.c)
1154 # These options are taken from the defaults in Makefile.msc in
1155 # the sqlite distribution
1156 target_compile_definitions(sqlite3 PRIVATE
1157 -DSQLITE_ENABLE_COLUMN_METADATA=1
1158 -DSQLITE_ENABLE_FTS3=1
1159 -DSQLITE_ENABLE_RTREE=1
1160 -DSQLITE_ENABLE_GEOPOLY=1
1161 -DSQLITE_ENABLE_JSON1=1
1162 -DSQLITE_ENABLE_STMTVTAB=1
1163 -DSQLITE_ENABLE_DBPAGE_VTAB=1
1164 -DSQLITE_ENABLE_DBSTAT_VTAB=1
1165 -DSQLITE_INTROSPECTION_PRAGMAS=1
1166 -DSQLITE_ENABLE_DESERIALIZE=1
1167 )
1168 install(TARGETS sqlite3)
1169 install(FILES sqlite3.h sqlite3ext.h DESTINATION include)
1170 """
1171
1172 with open(os.path.join(self.build_dir, "CMakeLists.txt"), "w") as f:
1173 f.write(cmake_lists)
1174
1175 defines = {
1176 "CMAKE_INSTALL_PREFIX": self.inst_dir,
1177 "BUILD_SHARED_LIBS": "ON" if self.build_opts.shared_libs else "OFF",
1178 "CMAKE_BUILD_TYPE": "RelWithDebInfo",
1179 }
1180 define_args = ["-D%s=%s" % (k, v) for (k, v) in defines.items()]
1181 define_args += ["-G", "Ninja"]
1182
1183 env = self._compute_env(install_dirs)
1184
1185 # Resolve the cmake that we installed
1186 cmake = path_search(env, "cmake")
1187
1188 self._run_cmd([cmake, self.build_dir] + define_args, env=env)
1189 self._run_cmd(
1190 [
1191 cmake,
1192 "--build",
1193 self.build_dir,
1194 "--target",
1195 "install",
1196 "--config",
1197 "Release",
1198 "-j",
1199 str(self.num_jobs),
1200 ],
1201 env=env,
1202 )