Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps.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 argparse
8 import json
9 import os
10 import shutil
11 import subprocess
12 import sys
13 import tarfile
14 import tempfile
15
16 # We don't import cache.create_cache directly as the facebook
17 # specific import below may monkey patch it, and we want to
18 # observe the patched version of this function!
19 import getdeps.cache as cache_module
20 from getdeps.buildopts import setup_build_options
21 from getdeps.dyndeps import create_dyn_dep_munger
22 from getdeps.errors import TransientFailure
23 from getdeps.fetcher import (
24 file_name_is_cmake_file,
25 list_files_under_dir_newer_than_timestamp,
26 SystemPackageFetcher,
27 )
28 from getdeps.load import ManifestLoader
29 from getdeps.manifest import ManifestParser
30 from getdeps.platform import HostType
31 from getdeps.runcmd import run_cmd
32 from getdeps.subcmd import add_subcommands, cmd, SubCmd
33
34 try:
35 import getdeps.facebook # noqa: F401
36 except ImportError:
37 # we don't ship the facebook specific subdir,
38 # so allow that to fail silently
39 pass
40
41
42 sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "getdeps"))
43
44
45 class UsageError(Exception):
46 pass
47
48
49 @cmd("validate-manifest", "parse a manifest and validate that it is correct")
50 class ValidateManifest(SubCmd):
51 def run(self, args):
52 try:
53 ManifestParser(file_name=args.file_name)
54 print("OK", file=sys.stderr)
55 return 0
56 except Exception as exc:
57 print("ERROR: %s" % str(exc), file=sys.stderr)
58 return 1
59
60 def setup_parser(self, parser):
61 parser.add_argument("file_name", help="path to the manifest file")
62
63
64 @cmd("show-host-type", "outputs the host type tuple for the host machine")
65 class ShowHostType(SubCmd):
66 def run(self, args):
67 host = HostType()
68 print("%s" % host.as_tuple_string())
69 return 0
70
71
72 class ProjectCmdBase(SubCmd):
73 def run(self, args):
74 opts = setup_build_options(args)
75
76 if args.current_project is not None:
77 opts.repo_project = args.current_project
78 if args.project is None:
79 if opts.repo_project is None:
80 raise UsageError(
81 "no project name specified, and no .projectid file found"
82 )
83 if opts.repo_project == "fbsource":
84 # The fbsource repository is a little special. There is no project
85 # manifest file for it. A specific project must always be explicitly
86 # specified when building from fbsource.
87 raise UsageError(
88 "no project name specified (required when building in fbsource)"
89 )
90 args.project = opts.repo_project
91
92 ctx_gen = opts.get_context_generator()
93 if args.test_dependencies:
94 ctx_gen.set_value_for_all_projects("test", "on")
95 if args.enable_tests:
96 ctx_gen.set_value_for_project(args.project, "test", "on")
97 else:
98 ctx_gen.set_value_for_project(args.project, "test", "off")
99
100 if opts.shared_libs:
101 ctx_gen.set_value_for_all_projects("shared_libs", "on")
102
103 loader = ManifestLoader(opts, ctx_gen)
104 self.process_project_dir_arguments(args, loader)
105
106 manifest = loader.load_manifest(args.project)
107
108 self.run_project_cmd(args, loader, manifest)
109
110 def process_project_dir_arguments(self, args, loader):
111 def parse_project_arg(arg, arg_type):
112 parts = arg.split(":")
113 if len(parts) == 2:
114 project, path = parts
115 elif len(parts) == 1:
116 project = args.project
117 path = parts[0]
118 # On Windows path contains colon, e.g. C:\open
119 elif os.name == "nt" and len(parts) == 3:
120 project = parts[0]
121 path = parts[1] + ":" + parts[2]
122 else:
123 raise UsageError(
124 "invalid %s argument; too many ':' characters: %s" % (arg_type, arg)
125 )
126
127 return project, os.path.abspath(path)
128
129 # If we are currently running from a project repository,
130 # use the current repository for the project sources.
131 build_opts = loader.build_opts
132 if build_opts.repo_project is not None and build_opts.repo_root is not None:
133 loader.set_project_src_dir(build_opts.repo_project, build_opts.repo_root)
134
135 for arg in args.src_dir:
136 project, path = parse_project_arg(arg, "--src-dir")
137 loader.set_project_src_dir(project, path)
138
139 for arg in args.build_dir:
140 project, path = parse_project_arg(arg, "--build-dir")
141 loader.set_project_build_dir(project, path)
142
143 for arg in args.install_dir:
144 project, path = parse_project_arg(arg, "--install-dir")
145 loader.set_project_install_dir(project, path)
146
147 for arg in args.project_install_prefix:
148 project, path = parse_project_arg(arg, "--install-prefix")
149 loader.set_project_install_prefix(project, path)
150
151 def setup_parser(self, parser):
152 parser.add_argument(
153 "project",
154 nargs="?",
155 help=(
156 "name of the project or path to a manifest "
157 "file describing the project"
158 ),
159 )
160 parser.add_argument(
161 "--no-tests",
162 action="store_false",
163 dest="enable_tests",
164 default=True,
165 help="Disable building tests for this project.",
166 )
167 parser.add_argument(
168 "--test-dependencies",
169 action="store_true",
170 help="Enable building tests for dependencies as well.",
171 )
172 parser.add_argument(
173 "--current-project",
174 help="Specify the name of the fbcode_builder manifest file for the "
175 "current repository. If not specified, the code will attempt to find "
176 "this in a .projectid file in the repository root.",
177 )
178 parser.add_argument(
179 "--src-dir",
180 default=[],
181 action="append",
182 help="Specify a local directory to use for the project source, "
183 "rather than fetching it.",
184 )
185 parser.add_argument(
186 "--build-dir",
187 default=[],
188 action="append",
189 help="Explicitly specify the build directory to use for the "
190 "project, instead of the default location in the scratch path. "
191 "This only affects the project specified, and not its dependencies.",
192 )
193 parser.add_argument(
194 "--install-dir",
195 default=[],
196 action="append",
197 help="Explicitly specify the install directory to use for the "
198 "project, instead of the default location in the scratch path. "
199 "This only affects the project specified, and not its dependencies.",
200 )
201 parser.add_argument(
202 "--project-install-prefix",
203 default=[],
204 action="append",
205 help="Specify the final deployment installation path for a project",
206 )
207
208 self.setup_project_cmd_parser(parser)
209
210 def setup_project_cmd_parser(self, parser):
211 pass
212
213
214 class CachedProject(object):
215 """A helper that allows calling the cache logic for a project
216 from both the build and the fetch code"""
217
218 def __init__(self, cache, loader, m):
219 self.m = m
220 self.inst_dir = loader.get_project_install_dir(m)
221 self.project_hash = loader.get_project_hash(m)
222 self.ctx = loader.ctx_gen.get_context(m.name)
223 self.loader = loader
224 self.cache = cache
225
226 self.cache_file_name = "-".join(
227 (
228 m.name,
229 self.ctx.get("os"),
230 self.ctx.get("distro") or "none",
231 self.ctx.get("distro_vers") or "none",
232 self.project_hash,
233 "buildcache.tgz",
234 )
235 )
236
237 def is_cacheable(self):
238 """We only cache third party projects"""
239 return self.cache and self.m.shipit_project is None
240
241 def was_cached(self):
242 cached_marker = os.path.join(self.inst_dir, ".getdeps-cached-build")
243 return os.path.exists(cached_marker)
244
245 def download(self):
246 if self.is_cacheable() and not os.path.exists(self.inst_dir):
247 print("check cache for %s" % self.cache_file_name)
248 dl_dir = os.path.join(self.loader.build_opts.scratch_dir, "downloads")
249 if not os.path.exists(dl_dir):
250 os.makedirs(dl_dir)
251 try:
252 target_file_name = os.path.join(dl_dir, self.cache_file_name)
253 if self.cache.download_to_file(self.cache_file_name, target_file_name):
254 tf = tarfile.open(target_file_name, "r")
255 print(
256 "Extracting %s -> %s..." % (self.cache_file_name, self.inst_dir)
257 )
258 tf.extractall(self.inst_dir)
259
260 cached_marker = os.path.join(self.inst_dir, ".getdeps-cached-build")
261 with open(cached_marker, "w") as f:
262 f.write("\n")
263
264 return True
265 except Exception as exc:
266 print("%s" % str(exc))
267
268 return False
269
270 def upload(self):
271 if self.is_cacheable():
272 # We can prepare an archive and stick it in LFS
273 tempdir = tempfile.mkdtemp()
274 tarfilename = os.path.join(tempdir, self.cache_file_name)
275 print("Archiving for cache: %s..." % tarfilename)
276 tf = tarfile.open(tarfilename, "w:gz")
277 tf.add(self.inst_dir, arcname=".")
278 tf.close()
279 try:
280 self.cache.upload_from_file(self.cache_file_name, tarfilename)
281 except Exception as exc:
282 print(
283 "Failed to upload to cache (%s), continue anyway" % str(exc),
284 file=sys.stderr,
285 )
286 shutil.rmtree(tempdir)
287
288
289 @cmd("fetch", "fetch the code for a given project")
290 class FetchCmd(ProjectCmdBase):
291 def setup_project_cmd_parser(self, parser):
292 parser.add_argument(
293 "--recursive",
294 help="fetch the transitive deps also",
295 action="store_true",
296 default=False,
297 )
298 parser.add_argument(
299 "--host-type",
300 help=(
301 "When recursively fetching, fetch deps for "
302 "this host type rather than the current system"
303 ),
304 )
305
306 def run_project_cmd(self, args, loader, manifest):
307 if args.recursive:
308 projects = loader.manifests_in_dependency_order()
309 else:
310 projects = [manifest]
311
312 cache = cache_module.create_cache()
313 for m in projects:
314 cached_project = CachedProject(cache, loader, m)
315 if cached_project.download():
316 continue
317
318 inst_dir = loader.get_project_install_dir(m)
319 built_marker = os.path.join(inst_dir, ".built-by-getdeps")
320 if os.path.exists(built_marker):
321 with open(built_marker, "r") as f:
322 built_hash = f.read().strip()
323
324 project_hash = loader.get_project_hash(m)
325 if built_hash == project_hash:
326 continue
327
328 # We need to fetch the sources
329 fetcher = loader.create_fetcher(m)
330 fetcher.update()
331
332
333 @cmd("install-system-deps", "Install system packages to satisfy the deps for a project")
334 class InstallSysDepsCmd(ProjectCmdBase):
335 def setup_project_cmd_parser(self, parser):
336 parser.add_argument(
337 "--recursive",
338 help="install the transitive deps also",
339 action="store_true",
340 default=False,
341 )
342 parser.add_argument(
343 "--dry-run",
344 action="store_true",
345 default=False,
346 help="Don't install, just print the commands specs we would run",
347 )
348 parser.add_argument(
349 "--os-type",
350 help="Filter to just this OS type to run",
351 choices=["linux", "darwin", "windows"],
352 action="store",
353 dest="ostype",
354 default=None,
355 )
356 parser.add_argument(
357 "--distro",
358 help="Filter to just this distro to run",
359 choices=["ubuntu", "centos_stream"],
360 action="store",
361 dest="distro",
362 default=None,
363 )
364 parser.add_argument(
365 "--distro-version",
366 help="Filter to just this distro version",
367 action="store",
368 dest="distrovers",
369 default=None,
370 )
371
372 def run_project_cmd(self, args, loader, manifest):
373 if args.recursive:
374 projects = loader.manifests_in_dependency_order()
375 else:
376 projects = [manifest]
377
378 rebuild_ctx_gen = False
379 if args.ostype:
380 loader.build_opts.host_type.ostype = args.ostype
381 loader.build_opts.host_type.distro = None
382 loader.build_opts.host_type.distrovers = None
383 rebuild_ctx_gen = True
384
385 if args.distro:
386 loader.build_opts.host_type.distro = args.distro
387 loader.build_opts.host_type.distrovers = None
388 rebuild_ctx_gen = True
389
390 if args.distrovers:
391 loader.build_opts.host_type.distrovers = args.distrovers
392 rebuild_ctx_gen = True
393
394 if rebuild_ctx_gen:
395 loader.ctx_gen = loader.build_opts.get_context_generator()
396
397 manager = loader.build_opts.host_type.get_package_manager()
398
399 all_packages = {}
400 for m in projects:
401 ctx = loader.ctx_gen.get_context(m.name)
402 packages = m.get_required_system_packages(ctx)
403 for k, v in packages.items():
404 merged = all_packages.get(k, [])
405 merged += v
406 all_packages[k] = merged
407
408 cmd_args = None
409 if manager == "rpm":
410 packages = sorted(set(all_packages["rpm"]))
411 if packages:
412 cmd_args = ["sudo", "dnf", "install", "-y"] + packages
413 elif manager == "deb":
414 packages = sorted(set(all_packages["deb"]))
415 if packages:
416 cmd_args = ["sudo", "apt", "install", "-y"] + packages
417 elif manager == "homebrew":
418 packages = sorted(set(all_packages["homebrew"]))
419 if packages:
420 cmd_args = ["brew", "install"] + packages
421
422 else:
423 host_tuple = loader.build_opts.host_type.as_tuple_string()
424 print(
425 f"I don't know how to install any packages on this system {host_tuple}"
426 )
427 return
428
429 if cmd_args:
430 if args.dry_run:
431 print(" ".join(cmd_args))
432 else:
433 run_cmd(cmd_args)
434 else:
435 print("no packages to install")
436
437
438 @cmd("list-deps", "lists the transitive deps for a given project")
439 class ListDepsCmd(ProjectCmdBase):
440 def run_project_cmd(self, args, loader, manifest):
441 for m in loader.manifests_in_dependency_order():
442 print(m.name)
443 return 0
444
445 def setup_project_cmd_parser(self, parser):
446 parser.add_argument(
447 "--host-type",
448 help=(
449 "Produce the list for the specified host type, "
450 "rather than that of the current system"
451 ),
452 )
453
454
455 def clean_dirs(opts):
456 for d in ["build", "installed", "extracted", "shipit"]:
457 d = os.path.join(opts.scratch_dir, d)
458 print("Cleaning %s..." % d)
459 if os.path.exists(d):
460 shutil.rmtree(d)
461
462
463 @cmd("clean", "clean up the scratch dir")
464 class CleanCmd(SubCmd):
465 def run(self, args):
466 opts = setup_build_options(args)
467 clean_dirs(opts)
468
469
470 @cmd("show-build-dir", "print the build dir for a given project")
471 class ShowBuildDirCmd(ProjectCmdBase):
472 def run_project_cmd(self, args, loader, manifest):
473 if args.recursive:
474 manifests = loader.manifests_in_dependency_order()
475 else:
476 manifests = [manifest]
477
478 for m in manifests:
479 inst_dir = loader.get_project_build_dir(m)
480 print(inst_dir)
481
482 def setup_project_cmd_parser(self, parser):
483 parser.add_argument(
484 "--recursive",
485 help="print the transitive deps also",
486 action="store_true",
487 default=False,
488 )
489
490
491 @cmd("show-inst-dir", "print the installation dir for a given project")
492 class ShowInstDirCmd(ProjectCmdBase):
493 def run_project_cmd(self, args, loader, manifest):
494 if args.recursive:
495 manifests = loader.manifests_in_dependency_order()
496 else:
497 manifests = [manifest]
498
499 for m in manifests:
500 fetcher = loader.create_fetcher(m)
501 if isinstance(fetcher, SystemPackageFetcher):
502 # We are guaranteed that if the fetcher is set to
503 # SystemPackageFetcher then this item is completely
504 # satisfied by the appropriate system packages
505 continue
506 inst_dir = loader.get_project_install_dir_respecting_install_prefix(m)
507 print(inst_dir)
508
509 def setup_project_cmd_parser(self, parser):
510 parser.add_argument(
511 "--recursive",
512 help="print the transitive deps also",
513 action="store_true",
514 default=False,
515 )
516
517
518 @cmd("show-source-dir", "print the source dir for a given project")
519 class ShowSourceDirCmd(ProjectCmdBase):
520 def run_project_cmd(self, args, loader, manifest):
521 if args.recursive:
522 manifests = loader.manifests_in_dependency_order()
523 else:
524 manifests = [manifest]
525
526 for m in manifests:
527 fetcher = loader.create_fetcher(m)
528 print(fetcher.get_src_dir())
529
530 def setup_project_cmd_parser(self, parser):
531 parser.add_argument(
532 "--recursive",
533 help="print the transitive deps also",
534 action="store_true",
535 default=False,
536 )
537
538
539 @cmd("build", "build a given project")
540 class BuildCmd(ProjectCmdBase):
541 def run_project_cmd(self, args, loader, manifest):
542 if args.clean:
543 clean_dirs(loader.build_opts)
544
545 print("Building on %s" % loader.ctx_gen.get_context(args.project))
546 projects = loader.manifests_in_dependency_order()
547
548 cache = cache_module.create_cache() if args.use_build_cache else None
549
550 # Accumulate the install directories so that the build steps
551 # can find their dep installation
552 install_dirs = []
553
554 for m in projects:
555 fetcher = loader.create_fetcher(m)
556
557 if isinstance(fetcher, SystemPackageFetcher):
558 # We are guaranteed that if the fetcher is set to
559 # SystemPackageFetcher then this item is completely
560 # satisfied by the appropriate system packages
561 continue
562
563 if args.clean:
564 fetcher.clean()
565
566 build_dir = loader.get_project_build_dir(m)
567 inst_dir = loader.get_project_install_dir(m)
568
569 if (
570 m == manifest
571 and not args.only_deps
572 or m != manifest
573 and not args.no_deps
574 ):
575 print("Assessing %s..." % m.name)
576 project_hash = loader.get_project_hash(m)
577 ctx = loader.ctx_gen.get_context(m.name)
578 built_marker = os.path.join(inst_dir, ".built-by-getdeps")
579
580 cached_project = CachedProject(cache, loader, m)
581
582 reconfigure, sources_changed = self.compute_source_change_status(
583 cached_project, fetcher, m, built_marker, project_hash
584 )
585
586 if os.path.exists(built_marker) and not cached_project.was_cached():
587 # We've previously built this. We may need to reconfigure if
588 # our deps have changed, so let's check them.
589 dep_reconfigure, dep_build = self.compute_dep_change_status(
590 m, built_marker, loader
591 )
592 if dep_reconfigure:
593 reconfigure = True
594 if dep_build:
595 sources_changed = True
596
597 extra_cmake_defines = (
598 json.loads(args.extra_cmake_defines)
599 if args.extra_cmake_defines
600 else {}
601 )
602
603 extra_b2_args = args.extra_b2_args or []
604
605 if sources_changed or reconfigure or not os.path.exists(built_marker):
606 if os.path.exists(built_marker):
607 os.unlink(built_marker)
608 src_dir = fetcher.get_src_dir()
609 # Prepare builders write out config before the main builder runs
610 prepare_builders = m.create_prepare_builders(
611 loader.build_opts,
612 ctx,
613 src_dir,
614 build_dir,
615 inst_dir,
616 loader,
617 )
618 for preparer in prepare_builders:
619 preparer.prepare(install_dirs, reconfigure=reconfigure)
620
621 builder = m.create_builder(
622 loader.build_opts,
623 src_dir,
624 build_dir,
625 inst_dir,
626 ctx,
627 loader,
628 final_install_prefix=loader.get_project_install_prefix(m),
629 extra_cmake_defines=extra_cmake_defines,
630 cmake_target=args.cmake_target if m == manifest else "install",
631 extra_b2_args=extra_b2_args,
632 )
633 builder.build(install_dirs, reconfigure=reconfigure)
634
635 # If we are building the project (not dependency) and a specific
636 # cmake_target (not 'install') has been requested, then we don't
637 # set the built_marker. This allows subsequent runs of getdeps.py
638 # for the project to run with different cmake_targets to trigger
639 # cmake
640 has_built_marker = False
641 if not (m == manifest and args.cmake_target != "install"):
642 with open(built_marker, "w") as f:
643 f.write(project_hash)
644 has_built_marker = True
645
646 # Only populate the cache from continuous build runs, and
647 # only if we have a built_marker.
648 if args.schedule_type == "continuous" and has_built_marker:
649 cached_project.upload()
650 elif args.verbose:
651 print("found good %s" % built_marker)
652
653 # Paths are resolved from front. We prepend rather than append as
654 # the last project in topo order is the project itself, which
655 # should be first in the path, then its deps and so on.
656 install_dirs.insert(0, inst_dir)
657
658 def compute_dep_change_status(self, m, built_marker, loader):
659 reconfigure = False
660 sources_changed = False
661 st = os.lstat(built_marker)
662
663 ctx = loader.ctx_gen.get_context(m.name)
664 dep_list = m.get_dependencies(ctx)
665 for dep in dep_list:
666 if reconfigure and sources_changed:
667 break
668
669 dep_manifest = loader.load_manifest(dep)
670 dep_root = loader.get_project_install_dir(dep_manifest)
671 for dep_file in list_files_under_dir_newer_than_timestamp(
672 dep_root, st.st_mtime
673 ):
674 if os.path.basename(dep_file) == ".built-by-getdeps":
675 continue
676 if file_name_is_cmake_file(dep_file):
677 if not reconfigure:
678 reconfigure = True
679 print(
680 f"Will reconfigure cmake because {dep_file} is newer than {built_marker}"
681 )
682 else:
683 if not sources_changed:
684 sources_changed = True
685 print(
686 f"Will run build because {dep_file} is newer than {built_marker}"
687 )
688
689 if reconfigure and sources_changed:
690 break
691
692 return reconfigure, sources_changed
693
694 def compute_source_change_status(
695 self, cached_project, fetcher, m, built_marker, project_hash
696 ):
697 reconfigure = False
698 sources_changed = False
699 if cached_project.download():
700 if not os.path.exists(built_marker):
701 fetcher.update()
702 else:
703 check_fetcher = True
704 if os.path.exists(built_marker):
705 check_fetcher = False
706 with open(built_marker, "r") as f:
707 built_hash = f.read().strip()
708 if built_hash == project_hash:
709 if cached_project.is_cacheable():
710 # We can blindly trust the build status
711 reconfigure = False
712 sources_changed = False
713 else:
714 # Otherwise, we may have changed the source, so let's
715 # check in with the fetcher layer
716 check_fetcher = True
717 else:
718 # Some kind of inconsistency with a prior build,
719 # let's run it again to be sure
720 os.unlink(built_marker)
721 reconfigure = True
722 sources_changed = True
723 # While we don't need to consult the fetcher for the
724 # status in this case, we may still need to have eg: shipit
725 # run in order to have a correct source tree.
726 fetcher.update()
727
728 if check_fetcher:
729 change_status = fetcher.update()
730 reconfigure = change_status.build_changed()
731 sources_changed = change_status.sources_changed()
732
733 return reconfigure, sources_changed
734
735 def setup_project_cmd_parser(self, parser):
736 parser.add_argument(
737 "--clean",
738 action="store_true",
739 default=False,
740 help=(
741 "Clean up the build and installation area prior to building, "
742 "causing the projects to be built from scratch"
743 ),
744 )
745 parser.add_argument(
746 "--no-deps",
747 action="store_true",
748 default=False,
749 help=(
750 "Only build the named project, not its deps. "
751 "This is most useful after you've built all of the deps, "
752 "and helps to avoid waiting for relatively "
753 "slow up-to-date-ness checks"
754 ),
755 )
756 parser.add_argument(
757 "--only-deps",
758 action="store_true",
759 default=False,
760 help=(
761 "Only build the named project's deps. "
762 "This is most useful when you want to separate out building "
763 "of all of the deps and your project"
764 ),
765 )
766 parser.add_argument(
767 "--no-build-cache",
768 action="store_false",
769 default=True,
770 dest="use_build_cache",
771 help="Do not attempt to use the build cache.",
772 )
773 parser.add_argument(
774 "--schedule-type", help="Indicates how the build was activated"
775 )
776 parser.add_argument(
777 "--extra-cmake-defines",
778 help=(
779 "Input json map that contains extra cmake defines to be used "
780 "when compiling the current project and all its deps. "
781 'e.g: \'{"CMAKE_CXX_FLAGS": "--bla"}\''
782 ),
783 )
784 parser.add_argument(
785 "--cmake-target",
786 help=("Target for cmake build."),
787 default="install",
788 )
789 parser.add_argument(
790 "--extra-b2-args",
791 help=(
792 "Repeatable argument that contains extra arguments to pass "
793 "to b2, which compiles boost. "
794 "e.g.: 'cxxflags=-fPIC' 'cflags=-fPIC'"
795 ),
796 action="append",
797 )
798 parser.add_argument(
799 "--shared-libs",
800 help="Build shared libraries if possible",
801 action="store_true",
802 default=False,
803 )
804 parser.add_argument(
805 "--free-up-disk",
806 help="Remove unused tools and clean up intermediate files if possible to maximise space for the build",
807 action="store_true",
808 default=False,
809 )
810
811
812 @cmd("fixup-dyn-deps", "Adjusts dynamic dependencies for packaging purposes")
813 class FixupDeps(ProjectCmdBase):
814 def run_project_cmd(self, args, loader, manifest):
815 projects = loader.manifests_in_dependency_order()
816
817 # Accumulate the install directories so that the build steps
818 # can find their dep installation
819 install_dirs = []
820
821 for m in projects:
822 inst_dir = loader.get_project_install_dir_respecting_install_prefix(m)
823 install_dirs.append(inst_dir)
824
825 if m == manifest:
826 dep_munger = create_dyn_dep_munger(
827 loader.build_opts, install_dirs, args.strip
828 )
829 if dep_munger is None:
830 print(f"dynamic dependency fixups not supported on {sys.platform}")
831 else:
832 dep_munger.process_deps(args.destdir, args.final_install_prefix)
833
834 def setup_project_cmd_parser(self, parser):
835 parser.add_argument("destdir", help="Where to copy the fixed up executables")
836 parser.add_argument(
837 "--final-install-prefix", help="specify the final installation prefix"
838 )
839 parser.add_argument(
840 "--strip",
841 action="store_true",
842 default=False,
843 help="Strip debug info while processing executables",
844 )
845
846
847 @cmd("test", "test a given project")
848 class TestCmd(ProjectCmdBase):
849 def run_project_cmd(self, args, loader, manifest):
850 projects = loader.manifests_in_dependency_order()
851
852 # Accumulate the install directories so that the test steps
853 # can find their dep installation
854 install_dirs = []
855
856 for m in projects:
857 inst_dir = loader.get_project_install_dir(m)
858
859 if m == manifest or args.test_dependencies:
860 built_marker = os.path.join(inst_dir, ".built-by-getdeps")
861 if not os.path.exists(built_marker):
862 print("project %s has not been built" % m.name)
863 # TODO: we could just go ahead and build it here, but I
864 # want to tackle that as part of adding build-for-test
865 # support.
866 return 1
867 fetcher = loader.create_fetcher(m)
868 src_dir = fetcher.get_src_dir()
869 ctx = loader.ctx_gen.get_context(m.name)
870 build_dir = loader.get_project_build_dir(m)
871 builder = m.create_builder(
872 loader.build_opts, src_dir, build_dir, inst_dir, ctx, loader
873 )
874
875 builder.run_tests(
876 install_dirs,
877 schedule_type=args.schedule_type,
878 owner=args.test_owner,
879 test_filter=args.filter,
880 retry=args.retry,
881 no_testpilot=args.no_testpilot,
882 )
883
884 install_dirs.append(inst_dir)
885
886 def setup_project_cmd_parser(self, parser):
887 parser.add_argument(
888 "--schedule-type", help="Indicates how the build was activated"
889 )
890 parser.add_argument("--test-owner", help="Owner for testpilot")
891 parser.add_argument("--filter", help="Only run the tests matching the regex")
892 parser.add_argument(
893 "--retry",
894 type=int,
895 default=3,
896 help="Number of immediate retries for failed tests "
897 "(noop in continuous and testwarden runs)",
898 )
899 parser.add_argument(
900 "--no-testpilot",
901 help="Do not use Test Pilot even when available",
902 action="store_true",
903 )
904
905
906 @cmd("generate-github-actions", "generate a GitHub actions configuration")
907 class GenerateGitHubActionsCmd(ProjectCmdBase):
908 RUN_ON_ALL = """ [push, pull_request]"""
909
910 def run_project_cmd(self, args, loader, manifest):
911 platforms = [
912 HostType("linux", "ubuntu", "18"),
913 HostType("darwin", None, None),
914 HostType("windows", None, None),
915 ]
916
917 for p in platforms:
918 if args.os_types and p.ostype not in args.os_types:
919 continue
920 self.write_job_for_platform(p, args)
921
922 def get_run_on(self, args):
923 if args.run_on_all_branches:
924 return self.RUN_ON_ALL
925 return f"""
926 push:
927 branches:
928 - {args.main_branch}
929 pull_request:
930 branches:
931 - {args.main_branch}"""
932
933 # TODO: Break up complex function
934 def write_job_for_platform(self, platform, args): # noqa: C901
935 build_opts = setup_build_options(args, platform)
936 ctx_gen = build_opts.get_context_generator()
937 loader = ManifestLoader(build_opts, ctx_gen)
938 manifest = loader.load_manifest(args.project)
939 manifest_ctx = loader.ctx_gen.get_context(manifest.name)
940 run_on = self.get_run_on(args)
941
942 # Some projects don't do anything "useful" as a leaf project, only
943 # as a dep for a leaf project. Check for those here; we don't want
944 # to waste the effort scheduling them on CI.
945 # We do this by looking at the builder type in the manifest file
946 # rather than creating a builder and checking its type because we
947 # don't know enough to create the full builder instance here.
948 builder_name = manifest.get("build", "builder", ctx=manifest_ctx)
949 if builder_name == "nop":
950 return None
951
952 # We want to be sure that we're running things with python 3
953 # but python versioning is honestly a bit of a frustrating mess.
954 # `python` may be version 2 or version 3 depending on the system.
955 # python3 may not be a thing at all!
956 # Assume an optimistic default
957 py3 = "python3"
958
959 if build_opts.is_linux():
960 artifacts = "linux"
961 runs_on = f"ubuntu-{args.ubuntu_version}"
962 elif build_opts.is_windows():
963 artifacts = "windows"
964 runs_on = "windows-2019"
965 # The windows runners are python 3 by default; python2.exe
966 # is available if needed.
967 py3 = "python"
968 else:
969 artifacts = "mac"
970 runs_on = "macOS-latest"
971
972 os.makedirs(args.output_dir, exist_ok=True)
973
974 job_file_prefix = "getdeps_"
975 if args.job_file_prefix:
976 job_file_prefix = args.job_file_prefix
977
978 output_file = os.path.join(args.output_dir, f"{job_file_prefix}{artifacts}.yml")
979
980 if args.job_name_prefix:
981 job_name = args.job_name_prefix + artifacts.capitalize()
982 else:
983 job_name = artifacts
984
985 with open(output_file, "w") as out:
986 # Deliberate line break here because the @ and the generated
987 # symbols are meaningful to our internal tooling when they
988 # appear in a single token
989 out.write("# This file was @")
990 out.write("generated by getdeps.py\n")
991 out.write(
992 f"""
993 name: {job_name}
994
995 on:{run_on}
996
997 permissions:
998 contents: read # to fetch code (actions/checkout)
999
1000 jobs:
1001 """
1002 )
1003
1004 getdepscmd = f"{py3} build/fbcode_builder/getdeps.py"
1005
1006 out.write(" build:\n")
1007 out.write(" runs-on: %s\n" % runs_on)
1008 out.write(" steps:\n")
1009
1010 if build_opts.is_windows():
1011 # cmake relies on BOOST_ROOT but GH deliberately don't set it in order
1012 # to avoid versioning issues:
1013 # https://github.com/actions/virtual-environments/issues/319
1014 # Instead, set the version we think we need; this is effectively
1015 # coupled with the boost manifest
1016 # This is the unusual syntax for setting an env var for the rest of
1017 # the steps in a workflow:
1018 # https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/
1019 out.write(" - name: Export boost environment\n")
1020 out.write(
1021 ' run: "echo BOOST_ROOT=%BOOST_ROOT_1_83_0% >> %GITHUB_ENV%"\n'
1022 )
1023 out.write(" shell: cmd\n")
1024
1025 # The git installation may not like long filenames, so tell it
1026 # that we want it to use them!
1027 out.write(" - name: Fix Git config\n")
1028 out.write(" run: git config --system core.longpaths true\n")
1029 out.write(" - name: Disable autocrlf\n")
1030 out.write(" run: git config --system core.autocrlf false\n")
1031
1032 out.write(" - uses: actions/checkout@v4\n")
1033
1034 if build_opts.free_up_disk:
1035 free_up_disk = "--free-up-disk "
1036 if not build_opts.is_windows():
1037 out.write(" - name: Show disk space at start\n")
1038 out.write(" run: df -h\n")
1039 # remove the unused github supplied android dev tools
1040 out.write(" - name: Free up disk space\n")
1041 out.write(" run: sudo rm -rf /usr/local/lib/android\n")
1042 out.write(" - name: Show disk space after freeing up\n")
1043 out.write(" run: df -h\n")
1044 else:
1045 free_up_disk = ""
1046
1047 allow_sys_arg = ""
1048 if (
1049 build_opts.allow_system_packages
1050 and build_opts.host_type.get_package_manager()
1051 ):
1052 sudo_arg = "sudo "
1053 allow_sys_arg = " --allow-system-packages"
1054 if build_opts.host_type.get_package_manager() == "deb":
1055 out.write(" - name: Update system package info\n")
1056 out.write(f" run: {sudo_arg}apt-get update\n")
1057
1058 out.write(" - name: Install system deps\n")
1059 if build_opts.is_darwin():
1060 # brew is installed as regular user
1061 sudo_arg = ""
1062 out.write(
1063 f" run: {sudo_arg}python3 build/fbcode_builder/getdeps.py --allow-system-packages install-system-deps --recursive {manifest.name}\n"
1064 )
1065 if build_opts.is_linux() or build_opts.is_freebsd():
1066 out.write(" - name: Install packaging system deps\n")
1067 out.write(
1068 f" run: {sudo_arg}python3 build/fbcode_builder/getdeps.py --allow-system-packages install-system-deps --recursive patchelf\n"
1069 )
1070
1071 projects = loader.manifests_in_dependency_order()
1072
1073 main_repo_url = manifest.get_repo_url(manifest_ctx)
1074 has_same_repo_dep = False
1075
1076 # Add the rust dep which doesn't have a manifest
1077 for m in projects:
1078 if m == manifest:
1079 continue
1080 mbuilder_name = m.get("build", "builder", ctx=manifest_ctx)
1081 if (
1082 m.name == "rust"
1083 or builder_name == "cargo"
1084 or mbuilder_name == "cargo"
1085 ):
1086 out.write(" - name: Install Rust Stable\n")
1087 out.write(" uses: dtolnay/rust-toolchain@stable\n")
1088 break
1089
1090 # Normal deps that have manifests
1091 for m in projects:
1092 if m == manifest or m.name == "rust":
1093 continue
1094 ctx = loader.ctx_gen.get_context(m.name)
1095 if m.get_repo_url(ctx) != main_repo_url:
1096 out.write(" - name: Fetch %s\n" % m.name)
1097 out.write(
1098 f" run: {getdepscmd}{allow_sys_arg} fetch --no-tests {m.name}\n"
1099 )
1100
1101 for m in projects:
1102 if m != manifest:
1103 if m.name == "rust":
1104 continue
1105 else:
1106 src_dir_arg = ""
1107 ctx = loader.ctx_gen.get_context(m.name)
1108 if main_repo_url and m.get_repo_url(ctx) == main_repo_url:
1109 # Its in the same repo, so src-dir is also .
1110 src_dir_arg = "--src-dir=. "
1111 has_same_repo_dep = True
1112 out.write(" - name: Build %s\n" % m.name)
1113 out.write(
1114 f" run: {getdepscmd}{allow_sys_arg} build {src_dir_arg}{free_up_disk}--no-tests {m.name}\n"
1115 )
1116
1117 out.write(" - name: Build %s\n" % manifest.name)
1118
1119 project_prefix = ""
1120 if not build_opts.is_windows():
1121 project_prefix = (
1122 " --project-install-prefix %s:/usr/local" % manifest.name
1123 )
1124
1125 # If we have dep from same repo, we already built it and don't want to rebuild it again
1126 no_deps_arg = ""
1127 if has_same_repo_dep:
1128 no_deps_arg = "--no-deps "
1129
1130 no_tests_arg = ""
1131 if not args.enable_tests:
1132 no_tests_arg = "--no-tests "
1133
1134 out.write(
1135 f" run: {getdepscmd}{allow_sys_arg} build {no_tests_arg}{no_deps_arg}--src-dir=. {manifest.name} {project_prefix}\n"
1136 )
1137
1138 out.write(" - name: Copy artifacts\n")
1139 if build_opts.is_linux():
1140 # Strip debug info from the binaries, but only on linux.
1141 # While the `strip` utility is also available on macOS,
1142 # attempting to strip there results in an error.
1143 # The `strip` utility is not available on Windows.
1144 strip = " --strip"
1145 else:
1146 strip = ""
1147
1148 out.write(
1149 f" run: {getdepscmd}{allow_sys_arg} fixup-dyn-deps{strip} "
1150 f"--src-dir=. {manifest.name} _artifacts/{artifacts} {project_prefix} "
1151 f"--final-install-prefix /usr/local\n"
1152 )
1153
1154 out.write(" - uses: actions/upload-artifact@v2\n")
1155 out.write(" with:\n")
1156 out.write(" name: %s\n" % manifest.name)
1157 out.write(" path: _artifacts\n")
1158
1159 if (
1160 args.enable_tests
1161 and manifest.get("github.actions", "run_tests", ctx=manifest_ctx)
1162 != "off"
1163 ):
1164 out.write(" - name: Test %s\n" % manifest.name)
1165 out.write(
1166 f" run: {getdepscmd}{allow_sys_arg} test --src-dir=. {manifest.name} {project_prefix}\n"
1167 )
1168 if build_opts.free_up_disk and not build_opts.is_windows():
1169 out.write(" - name: Show disk space at end\n")
1170 out.write(" run: df -h\n")
1171
1172 def setup_project_cmd_parser(self, parser):
1173 parser.add_argument(
1174 "--disallow-system-packages",
1175 help="Disallow satisfying third party deps from installed system packages",
1176 action="store_true",
1177 default=False,
1178 )
1179 parser.add_argument(
1180 "--output-dir", help="The directory that will contain the yml files"
1181 )
1182 parser.add_argument(
1183 "--run-on-all-branches",
1184 action="store_true",
1185 help="Allow CI to fire on all branches - Handy for testing",
1186 )
1187 parser.add_argument(
1188 "--ubuntu-version", default="20.04", help="Version of Ubuntu to use"
1189 )
1190 parser.add_argument(
1191 "--main-branch",
1192 default="main",
1193 help="Main branch to trigger GitHub Action on",
1194 )
1195 parser.add_argument(
1196 "--os-type",
1197 help="Filter to just this OS type to run",
1198 choices=["linux", "darwin", "windows"],
1199 action="append",
1200 dest="os_types",
1201 default=[],
1202 )
1203 parser.add_argument(
1204 "--job-file-prefix",
1205 type=str,
1206 help="add a prefix to all job file names",
1207 default=None,
1208 )
1209 parser.add_argument(
1210 "--job-name-prefix",
1211 type=str,
1212 help="add a prefix to all job names",
1213 default=None,
1214 )
1215 parser.add_argument(
1216 "--free-up-disk",
1217 help="Remove unused tools and clean up intermediate files if possible to maximise space for the build",
1218 action="store_true",
1219 default=False,
1220 )
1221
1222
1223 def get_arg_var_name(args):
1224 for arg in args:
1225 if arg.startswith("--"):
1226 return arg[2:].replace("-", "_")
1227
1228 raise Exception("unable to determine argument variable name from %r" % (args,))
1229
1230
1231 def parse_args():
1232 # We want to allow common arguments to be specified either before or after
1233 # the subcommand name. In order to do this we add them to the main parser
1234 # and to subcommand parsers. In order for this to work, we need to tell
1235 # argparse that the default value is SUPPRESS, so that the default values
1236 # from the subparser arguments won't override values set by the user from
1237 # the main parser. We maintain our own list of desired defaults in the
1238 # common_defaults dictionary, and manually set those if the argument wasn't
1239 # present at all.
1240 common_args = argparse.ArgumentParser(add_help=False)
1241 common_defaults = {}
1242
1243 def add_common_arg(*args, **kwargs):
1244 var_name = get_arg_var_name(args)
1245 default_value = kwargs.pop("default", None)
1246 common_defaults[var_name] = default_value
1247 kwargs["default"] = argparse.SUPPRESS
1248 common_args.add_argument(*args, **kwargs)
1249
1250 add_common_arg("--scratch-path", help="Where to maintain checkouts and build dirs")
1251 add_common_arg(
1252 "--vcvars-path", default=None, help="Path to the vcvarsall.bat on Windows."
1253 )
1254 add_common_arg(
1255 "--install-prefix",
1256 help=(
1257 "Where the final build products will be installed "
1258 "(default is [scratch-path]/installed)"
1259 ),
1260 )
1261 add_common_arg(
1262 "--num-jobs",
1263 type=int,
1264 help=(
1265 "Number of concurrent jobs to use while building. "
1266 "(default=number of cpu cores)"
1267 ),
1268 )
1269 add_common_arg(
1270 "--use-shipit",
1271 help="use the real ShipIt instead of the simple shipit transformer",
1272 action="store_true",
1273 default=False,
1274 )
1275 add_common_arg(
1276 "--facebook-internal",
1277 help="Setup the build context as an FB internal build",
1278 action="store_true",
1279 default=None,
1280 )
1281 add_common_arg(
1282 "--no-facebook-internal",
1283 help="Perform a non-FB internal build, even when in an fbsource repository",
1284 action="store_false",
1285 dest="facebook_internal",
1286 )
1287 add_common_arg(
1288 "--allow-system-packages",
1289 help="Allow satisfying third party deps from installed system packages",
1290 action="store_true",
1291 default=False,
1292 )
1293 add_common_arg(
1294 "-v",
1295 "--verbose",
1296 help="Print more output",
1297 action="store_true",
1298 default=False,
1299 )
1300 add_common_arg(
1301 "--lfs-path",
1302 help="Provide a parent directory for lfs when fbsource is unavailable",
1303 default=None,
1304 )
1305
1306 ap = argparse.ArgumentParser(
1307 description="Get and build dependencies and projects", parents=[common_args]
1308 )
1309 sub = ap.add_subparsers(
1310 # metavar suppresses the long and ugly default list of subcommands on a
1311 # single line. We still render the nicer list below where we would
1312 # have shown the nasty one.
1313 metavar="",
1314 title="Available commands",
1315 help="",
1316 )
1317
1318 add_subcommands(sub, common_args)
1319
1320 args = ap.parse_args()
1321 for var_name, default_value in common_defaults.items():
1322 if not hasattr(args, var_name):
1323 setattr(args, var_name, default_value)
1324
1325 return ap, args
1326
1327
1328 def main():
1329 ap, args = parse_args()
1330 if getattr(args, "func", None) is None:
1331 ap.print_help()
1332 return 0
1333 try:
1334 return args.func(args)
1335 except UsageError as exc:
1336 ap.error(str(exc))
1337 return 1
1338 except TransientFailure as exc:
1339 print("TransientFailure: %s" % str(exc))
1340 # This return code is treated as a retryable transient infrastructure
1341 # error by Facebook's internal CI, rather than eg: a build or code
1342 # related error that needs to be fixed before progress can be made.
1343 return 128
1344 except subprocess.CalledProcessError as exc:
1345 print("%s" % str(exc), file=sys.stderr)
1346 print("!! Failed", file=sys.stderr)
1347 return 1
1348
1349
1350 if __name__ == "__main__":
1351 sys.exit(main())