Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps/manifest.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 configparser
7 import io
8 import os
9 from typing import List
10
11 from .builder import (
12 AutoconfBuilder,
13 Boost,
14 CMakeBootStrapBuilder,
15 CMakeBuilder,
16 Iproute2Builder,
17 MakeBuilder,
18 NinjaBootstrap,
19 NopBuilder,
20 OpenSSLBuilder,
21 SqliteBuilder,
22 )
23 from .cargo import CargoBuilder
24 from .expr import parse_expr
25 from .fetcher import (
26 ArchiveFetcher,
27 GitFetcher,
28 PreinstalledNopFetcher,
29 ShipitTransformerFetcher,
30 SimpleShipitTransformerFetcher,
31 SystemPackageFetcher,
32 )
33 from .py_wheel_builder import PythonWheelBuilder
34
35 REQUIRED = "REQUIRED"
36 OPTIONAL = "OPTIONAL"
37
38 SCHEMA = {
39 "manifest": {
40 "optional_section": False,
41 "fields": {
42 "name": REQUIRED,
43 "fbsource_path": OPTIONAL,
44 "shipit_project": OPTIONAL,
45 "shipit_fbcode_builder": OPTIONAL,
46 },
47 },
48 "dependencies": {"optional_section": True, "allow_values": False},
49 "depends.environment": {"optional_section": True},
50 "git": {
51 "optional_section": True,
52 "fields": {"repo_url": REQUIRED, "rev": OPTIONAL, "depth": OPTIONAL},
53 },
54 "download": {
55 "optional_section": True,
56 "fields": {"url": REQUIRED, "sha256": REQUIRED},
57 },
58 "build": {
59 "optional_section": True,
60 "fields": {
61 "builder": REQUIRED,
62 "subdir": OPTIONAL,
63 "make_binary": OPTIONAL,
64 "build_in_src_dir": OPTIONAL,
65 "job_weight_mib": OPTIONAL,
66 "patchfile": OPTIONAL,
67 "patchfile_opts": OPTIONAL,
68 },
69 },
70 "msbuild": {"optional_section": True, "fields": {"project": REQUIRED}},
71 "cargo": {
72 "optional_section": True,
73 "fields": {
74 "build_doc": OPTIONAL,
75 "workspace_dir": OPTIONAL,
76 "manifests_to_build": OPTIONAL,
77 # Where to write cargo config (defaults to build_dir/.cargo/config.toml)
78 "cargo_config_file": OPTIONAL,
79 },
80 },
81 "github.actions": {
82 "optional_section": True,
83 "fields": {
84 "run_tests": OPTIONAL,
85 },
86 },
87 "crate.pathmap": {"optional_section": True},
88 "cmake.defines": {"optional_section": True},
89 "autoconf.args": {"optional_section": True},
90 "autoconf.envcmd.LDFLAGS": {"optional_section": True},
91 "rpms": {"optional_section": True},
92 "debs": {"optional_section": True},
93 "homebrew": {"optional_section": True},
94 "preinstalled.env": {"optional_section": True},
95 "bootstrap.args": {"optional_section": True},
96 "b2.args": {"optional_section": True},
97 "make.build_args": {"optional_section": True},
98 "make.install_args": {"optional_section": True},
99 "make.test_args": {"optional_section": True},
100 "header-only": {"optional_section": True, "fields": {"includedir": REQUIRED}},
101 "shipit.pathmap": {"optional_section": True},
102 "shipit.strip": {"optional_section": True},
103 "install.files": {"optional_section": True},
104 # fb-only
105 "sandcastle": {"optional_section": True, "fields": {"run_tests": OPTIONAL}},
106 }
107
108 # These sections are allowed to vary for different platforms
109 # using the expression syntax to enable/disable sections
110 ALLOWED_EXPR_SECTIONS = [
111 "autoconf.args",
112 "autoconf.envcmd.LDFLAGS",
113 "build",
114 "cmake.defines",
115 "dependencies",
116 "make.build_args",
117 "make.install_args",
118 "bootstrap.args",
119 "b2.args",
120 "download",
121 "git",
122 "install.files",
123 "rpms",
124 "debs",
125 "shipit.pathmap",
126 "shipit.strip",
127 "homebrew",
128 "github.actions",
129 ]
130
131
132 def parse_conditional_section_name(name, section_def):
133 expr = name[len(section_def) + 1 :]
134 return parse_expr(expr, ManifestContext.ALLOWED_VARIABLES)
135
136
137 def validate_allowed_fields(file_name, section, config, allowed_fields):
138 for field in config.options(section):
139 if not allowed_fields.get(field):
140 raise Exception(
141 ("manifest file %s section '%s' contains " "unknown field '%s'")
142 % (file_name, section, field)
143 )
144
145 for field in allowed_fields:
146 if allowed_fields[field] == REQUIRED and not config.has_option(section, field):
147 raise Exception(
148 ("manifest file %s section '%s' is missing " "required field '%s'")
149 % (file_name, section, field)
150 )
151
152
153 def validate_allow_values(file_name, section, config):
154 for field in config.options(section):
155 value = config.get(section, field)
156 if value is not None:
157 raise Exception(
158 (
159 "manifest file %s section '%s' has '%s = %s' but "
160 "this section doesn't allow specifying values "
161 "for its entries"
162 )
163 % (file_name, section, field, value)
164 )
165
166
167 def validate_section(file_name, section, config):
168 section_def = SCHEMA.get(section)
169 if not section_def:
170 for name in ALLOWED_EXPR_SECTIONS:
171 if section.startswith(name + "."):
172 # Verify that the conditional parses, but discard it
173 try:
174 parse_conditional_section_name(section, name)
175 except Exception as exc:
176 raise Exception(
177 ("manifest file %s section '%s' has invalid " "conditional: %s")
178 % (file_name, section, str(exc))
179 )
180 section_def = SCHEMA.get(name)
181 canonical_section_name = name
182 break
183 if not section_def:
184 raise Exception(
185 "manifest file %s contains unknown section '%s'" % (file_name, section)
186 )
187 else:
188 canonical_section_name = section
189
190 allowed_fields = section_def.get("fields")
191 if allowed_fields:
192 validate_allowed_fields(file_name, section, config, allowed_fields)
193 elif not section_def.get("allow_values", True):
194 validate_allow_values(file_name, section, config)
195 return canonical_section_name
196
197
198 class ManifestParser(object):
199 def __init__(self, file_name, fp=None):
200 # allow_no_value enables listing parameters in the
201 # autoconf.args section one per line
202 config = configparser.RawConfigParser(allow_no_value=True)
203 config.optionxform = str # make it case sensitive
204 if fp is None:
205 with open(file_name, "r") as fp:
206 config.read_file(fp)
207 elif isinstance(fp, type("")):
208 # For testing purposes, parse from a string (str
209 # or unicode)
210 config.read_file(io.StringIO(fp))
211 else:
212 config.read_file(fp)
213
214 # validate against the schema
215 seen_sections = set()
216
217 for section in config.sections():
218 seen_sections.add(validate_section(file_name, section, config))
219
220 for section in SCHEMA.keys():
221 section_def = SCHEMA[section]
222 if (
223 not section_def.get("optional_section", False)
224 and section not in seen_sections
225 ):
226 raise Exception(
227 "manifest file %s is missing required section %s"
228 % (file_name, section)
229 )
230
231 self._config = config
232 self.name = config.get("manifest", "name")
233 self.fbsource_path = self.get("manifest", "fbsource_path")
234 self.shipit_project = self.get("manifest", "shipit_project")
235 self.shipit_fbcode_builder = self.get("manifest", "shipit_fbcode_builder")
236 self.resolved_system_packages = {}
237
238 if self.name != os.path.basename(file_name):
239 raise Exception(
240 "filename of the manifest '%s' does not match the manifest name '%s'"
241 % (file_name, self.name)
242 )
243
244 def get(self, section, key, defval=None, ctx=None):
245 ctx = ctx or {}
246
247 for s in self._config.sections():
248 if s == section:
249 if self._config.has_option(s, key):
250 return self._config.get(s, key)
251 return defval
252
253 if s.startswith(section + "."):
254 expr = parse_conditional_section_name(s, section)
255 if not expr.eval(ctx):
256 continue
257
258 if self._config.has_option(s, key):
259 return self._config.get(s, key)
260
261 return defval
262
263 def get_dependencies(self, ctx):
264 dep_list = list(self.get_section_as_dict("dependencies", ctx).keys())
265 dep_list.sort()
266 builder = self.get("build", "builder", ctx=ctx)
267 if builder in ("cmake", "python-wheel"):
268 dep_list.insert(0, "cmake")
269 elif builder == "autoconf" and self.name not in (
270 "autoconf",
271 "libtool",
272 "automake",
273 ):
274 # they need libtool and its deps (automake, autoconf) so add
275 # those as deps (but obviously not if we're building those
276 # projects themselves)
277 dep_list.insert(0, "libtool")
278
279 return dep_list
280
281 def get_section_as_args(self, section, ctx=None) -> List[str]:
282 """Intended for use with the make.[build_args/install_args] and
283 autoconf.args sections, this method collects the entries and returns an
284 array of strings.
285 If the manifest contains conditional sections, ctx is used to
286 evaluate the condition and merge in the values.
287 """
288 args = []
289 ctx = ctx or {}
290
291 for s in self._config.sections():
292 if s != section:
293 if not s.startswith(section + "."):
294 continue
295 expr = parse_conditional_section_name(s, section)
296 if not expr.eval(ctx):
297 continue
298 for field in self._config.options(s):
299 value = self._config.get(s, field)
300 if value is None:
301 args.append(field)
302 else:
303 args.append("%s=%s" % (field, value))
304 return args
305
306 def get_section_as_ordered_pairs(self, section, ctx=None):
307 """Used for eg: shipit.pathmap which has strong
308 ordering requirements"""
309 res = []
310 ctx = ctx or {}
311
312 for s in self._config.sections():
313 if s != section:
314 if not s.startswith(section + "."):
315 continue
316 expr = parse_conditional_section_name(s, section)
317 if not expr.eval(ctx):
318 continue
319
320 for key in self._config.options(s):
321 value = self._config.get(s, key)
322 res.append((key, value))
323 return res
324
325 def get_section_as_dict(self, section, ctx):
326 d = {}
327
328 for s in self._config.sections():
329 if s != section:
330 if not s.startswith(section + "."):
331 continue
332 expr = parse_conditional_section_name(s, section)
333 if not expr.eval(ctx):
334 continue
335 for field in self._config.options(s):
336 value = self._config.get(s, field)
337 d[field] = value
338 return d
339
340 def update_hash(self, hasher, ctx):
341 """Compute a hash over the configuration for the given
342 context. The goal is for the hash to change if the config
343 for that context changes, but not if a change is made to
344 the config only for a different platform than that expressed
345 by ctx. The hash is intended to be used to help invalidate
346 a future cache for the third party build products.
347 The hasher argument is a hash object returned from hashlib."""
348 for section in sorted(SCHEMA.keys()):
349 hasher.update(section.encode("utf-8"))
350
351 # Note: at the time of writing, nothing in the implementation
352 # relies on keys in any config section being ordered.
353 # In theory we could have conflicting flags in different
354 # config sections and later flags override earlier flags.
355 # For the purposes of computing a hash we're not super
356 # concerned about this: manifest changes should be rare
357 # enough and we'd rather that this trigger an invalidation
358 # than strive for a cache hit at this time.
359 pairs = self.get_section_as_ordered_pairs(section, ctx)
360 pairs.sort(key=lambda pair: pair[0])
361 for key, value in pairs:
362 hasher.update(key.encode("utf-8"))
363 if value is not None:
364 hasher.update(value.encode("utf-8"))
365
366 def is_first_party_project(self):
367 """returns true if this is an FB first-party project"""
368 return self.shipit_project is not None
369
370 def get_required_system_packages(self, ctx):
371 """Returns dictionary of packager system -> list of packages"""
372 return {
373 "rpm": self.get_section_as_args("rpms", ctx),
374 "deb": self.get_section_as_args("debs", ctx),
375 "homebrew": self.get_section_as_args("homebrew", ctx),
376 }
377
378 def _is_satisfied_by_preinstalled_environment(self, ctx):
379 envs = self.get_section_as_args("preinstalled.env", ctx)
380 if not envs:
381 return False
382 for key in envs:
383 val = os.environ.get(key, None)
384 print(f"Testing ENV[{key}]: {repr(val)}")
385 if val is None:
386 return False
387 if len(val) == 0:
388 return False
389
390 return True
391
392 def get_repo_url(self, ctx):
393 return self.get("git", "repo_url", ctx=ctx)
394
395 def create_fetcher(self, build_options, ctx):
396 use_real_shipit = (
397 ShipitTransformerFetcher.available() and build_options.use_shipit
398 )
399 if (
400 not use_real_shipit
401 and self.fbsource_path
402 and build_options.fbsource_dir
403 and self.shipit_project
404 ):
405 return SimpleShipitTransformerFetcher(build_options, self, ctx)
406
407 if (
408 self.fbsource_path
409 and build_options.fbsource_dir
410 and self.shipit_project
411 and ShipitTransformerFetcher.available()
412 ):
413 # We can use the code from fbsource
414 return ShipitTransformerFetcher(build_options, self.shipit_project)
415
416 # Can we satisfy this dep with system packages?
417 if build_options.allow_system_packages:
418 if self._is_satisfied_by_preinstalled_environment(ctx):
419 return PreinstalledNopFetcher()
420
421 packages = self.get_required_system_packages(ctx)
422 package_fetcher = SystemPackageFetcher(build_options, packages)
423 if package_fetcher.packages_are_installed():
424 return package_fetcher
425
426 repo_url = self.get_repo_url(ctx)
427 if repo_url:
428 rev = self.get("git", "rev")
429 depth = self.get("git", "depth")
430 return GitFetcher(build_options, self, repo_url, rev, depth)
431
432 url = self.get("download", "url", ctx=ctx)
433 if url:
434 # We need to defer this import until now to avoid triggering
435 # a cycle when the facebook/__init__.py is loaded.
436 try:
437 from .facebook.lfs import LFSCachingArchiveFetcher
438
439 return LFSCachingArchiveFetcher(
440 build_options, self, url, self.get("download", "sha256", ctx=ctx)
441 )
442 except ImportError:
443 # This FB internal module isn't shippped to github,
444 # so just use its base class
445 return ArchiveFetcher(
446 build_options, self, url, self.get("download", "sha256", ctx=ctx)
447 )
448
449 raise KeyError(
450 "project %s has no fetcher configuration matching %s" % (self.name, ctx)
451 )
452
453 def get_builder_name(self, ctx):
454 builder = self.get("build", "builder", ctx=ctx)
455 if not builder:
456 raise Exception("project %s has no builder for %r" % (self.name, ctx))
457 return builder
458
459 def create_builder( # noqa:C901
460 self,
461 build_options,
462 src_dir,
463 build_dir,
464 inst_dir,
465 ctx,
466 loader,
467 final_install_prefix=None,
468 extra_cmake_defines=None,
469 cmake_target=None,
470 extra_b2_args=None,
471 ):
472 builder = self.get_builder_name(ctx)
473 build_in_src_dir = self.get("build", "build_in_src_dir", "false", ctx=ctx)
474 if build_in_src_dir == "true":
475 # Some scripts don't work when they are configured and build in
476 # a different directory than source (or when the build directory
477 # is not a subdir of source).
478 build_dir = src_dir
479 subdir = self.get("build", "subdir", None, ctx=ctx)
480 if subdir is not None:
481 build_dir = os.path.join(build_dir, subdir)
482 print("build_dir is %s" % build_dir) # just to quiet lint
483
484 if builder == "make" or builder == "cmakebootstrap":
485 build_args = self.get_section_as_args("make.build_args", ctx)
486 install_args = self.get_section_as_args("make.install_args", ctx)
487 test_args = self.get_section_as_args("make.test_args", ctx)
488 if builder == "cmakebootstrap":
489 return CMakeBootStrapBuilder(
490 build_options,
491 ctx,
492 self,
493 src_dir,
494 None,
495 inst_dir,
496 build_args,
497 install_args,
498 test_args,
499 )
500 else:
501 return MakeBuilder(
502 build_options,
503 ctx,
504 self,
505 src_dir,
506 None,
507 inst_dir,
508 build_args,
509 install_args,
510 test_args,
511 )
512
513 if builder == "autoconf":
514 args = self.get_section_as_args("autoconf.args", ctx)
515 conf_env_args = {}
516 ldflags_cmd = self.get_section_as_args("autoconf.envcmd.LDFLAGS", ctx)
517 if ldflags_cmd:
518 conf_env_args["LDFLAGS"] = ldflags_cmd
519 return AutoconfBuilder(
520 build_options,
521 ctx,
522 self,
523 src_dir,
524 build_dir,
525 inst_dir,
526 args,
527 conf_env_args,
528 )
529
530 if builder == "boost":
531 args = self.get_section_as_args("b2.args", ctx)
532 if extra_b2_args is not None:
533 args += extra_b2_args
534 return Boost(build_options, ctx, self, src_dir, build_dir, inst_dir, args)
535
536 if builder == "cmake":
537 defines = self.get_section_as_dict("cmake.defines", ctx)
538 return CMakeBuilder(
539 build_options,
540 ctx,
541 self,
542 src_dir,
543 build_dir,
544 inst_dir,
545 defines,
546 loader,
547 final_install_prefix,
548 extra_cmake_defines,
549 cmake_target,
550 )
551
552 if builder == "python-wheel":
553 return PythonWheelBuilder(
554 build_options, ctx, self, src_dir, build_dir, inst_dir
555 )
556
557 if builder == "sqlite":
558 return SqliteBuilder(build_options, ctx, self, src_dir, build_dir, inst_dir)
559
560 if builder == "ninja_bootstrap":
561 return NinjaBootstrap(
562 build_options, ctx, self, build_dir, src_dir, inst_dir
563 )
564
565 if builder == "nop":
566 return NopBuilder(build_options, ctx, self, src_dir, inst_dir)
567
568 if builder == "openssl":
569 return OpenSSLBuilder(
570 build_options, ctx, self, build_dir, src_dir, inst_dir
571 )
572
573 if builder == "iproute2":
574 return Iproute2Builder(
575 build_options, ctx, self, src_dir, build_dir, inst_dir
576 )
577
578 if builder == "cargo":
579 return self.create_cargo_builder(
580 build_options, ctx, src_dir, build_dir, inst_dir, loader
581 )
582
583 raise KeyError("project %s has no known builder" % (self.name))
584
585 def create_prepare_builders(
586 self, build_options, ctx, src_dir, build_dir, inst_dir, loader
587 ):
588 """Create builders that have a prepare step run, e.g. to write config files"""
589 prepare_builders = []
590 builder = self.get_builder_name(ctx)
591 cargo = self.get_section_as_dict("cargo", ctx)
592 if not builder == "cargo" and cargo:
593 cargo_builder = self.create_cargo_builder(
594 build_options, ctx, src_dir, build_dir, inst_dir, loader
595 )
596 prepare_builders.append(cargo_builder)
597 return prepare_builders
598
599 def create_cargo_builder(
600 self, build_options, ctx, src_dir, build_dir, inst_dir, loader
601 ):
602 build_doc = self.get("cargo", "build_doc", False, ctx)
603 workspace_dir = self.get("cargo", "workspace_dir", None, ctx)
604 manifests_to_build = self.get("cargo", "manifests_to_build", None, ctx)
605 cargo_config_file = self.get("cargo", "cargo_config_file", None, ctx)
606 return CargoBuilder(
607 build_options,
608 ctx,
609 self,
610 src_dir,
611 build_dir,
612 inst_dir,
613 build_doc,
614 workspace_dir,
615 manifests_to_build,
616 loader,
617 cargo_config_file,
618 )
619
620
621 class ManifestContext(object):
622 """ProjectContext contains a dictionary of values to use when evaluating boolean
623 expressions in a project manifest.
624
625 This object should be passed as the `ctx` parameter in ManifestParser.get() calls.
626 """
627
628 ALLOWED_VARIABLES = {
629 "os",
630 "distro",
631 "distro_vers",
632 "fb",
633 "fbsource",
634 "test",
635 "shared_libs",
636 }
637
638 def __init__(self, ctx_dict):
639 assert set(ctx_dict.keys()) == self.ALLOWED_VARIABLES
640 self.ctx_dict = ctx_dict
641
642 def get(self, key):
643 return self.ctx_dict[key]
644
645 def set(self, key, value):
646 assert key in self.ALLOWED_VARIABLES
647 self.ctx_dict[key] = value
648
649 def copy(self):
650 return ManifestContext(dict(self.ctx_dict))
651
652 def __str__(self):
653 s = ", ".join(
654 "%s=%s" % (key, value) for key, value in sorted(self.ctx_dict.items())
655 )
656 return "{" + s + "}"
657
658
659 class ContextGenerator(object):
660 """ContextGenerator allows creating ManifestContext objects on a per-project basis.
661 This allows us to evaluate different projects with slightly different contexts.
662
663 For instance, this can be used to only enable tests for some projects."""
664
665 def __init__(self, default_ctx):
666 self.default_ctx = ManifestContext(default_ctx)
667 self.ctx_by_project = {}
668
669 def set_value_for_project(self, project_name, key, value):
670 project_ctx = self.ctx_by_project.get(project_name)
671 if project_ctx is None:
672 project_ctx = self.default_ctx.copy()
673 self.ctx_by_project[project_name] = project_ctx
674 project_ctx.set(key, value)
675
676 def set_value_for_all_projects(self, key, value):
677 self.default_ctx.set(key, value)
678 for ctx in self.ctx_by_project.values():
679 ctx.set(key, value)
680
681 def get_context(self, project_name):
682 return self.ctx_by_project.get(project_name, self.default_ctx)