mzbuild.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. """The implementation of the mzbuild system for Docker images.
  10. For an overview of what mzbuild is and why it exists, see the [user-facing
  11. documentation][user-docs].
  12. [user-docs]: https://github.com/MaterializeInc/materialize/blob/main/doc/developer/mzbuild.md
  13. """
  14. import argparse
  15. import base64
  16. import collections
  17. import hashlib
  18. import json
  19. import multiprocessing
  20. import os
  21. import re
  22. import shutil
  23. import stat
  24. import subprocess
  25. import sys
  26. import tarfile
  27. import time
  28. from collections import OrderedDict
  29. from collections.abc import Callable, Iterable, Iterator, Sequence
  30. from concurrent.futures import ThreadPoolExecutor, as_completed
  31. from enum import Enum, auto
  32. from functools import cache
  33. from pathlib import Path
  34. from tempfile import TemporaryFile
  35. from threading import Lock
  36. from typing import IO, Any, cast
  37. import requests
  38. import yaml
  39. from requests.auth import HTTPBasicAuth
  40. from materialize import MZ_ROOT, buildkite, cargo, git, rustc_flags, spawn, ui, xcompile
  41. from materialize import bazel as bazel_utils
  42. from materialize.rustc_flags import Sanitizer
  43. from materialize.xcompile import Arch, target
  44. class Fingerprint(bytes):
  45. """A SHA-1 hash of the inputs to an `Image`.
  46. The string representation uses base32 encoding to distinguish mzbuild
  47. fingerprints from Git's hex encoded SHA-1 hashes while still being
  48. URL safe.
  49. """
  50. def __str__(self) -> str:
  51. return base64.b32encode(self).decode()
  52. class Profile(Enum):
  53. RELEASE = auto()
  54. OPTIMIZED = auto()
  55. DEV = auto()
  56. class RepositoryDetails:
  57. """Immutable details about a `Repository`.
  58. Used internally by mzbuild.
  59. Attributes:
  60. root: The path to the root of the repository.
  61. arch: The CPU architecture to build for.
  62. profile: What profile the repository is being built with.
  63. coverage: Whether the repository has code coverage instrumentation
  64. enabled.
  65. sanitizer: Whether to use a sanitizer (address, hwaddress, cfi, thread, leak, memory, none)
  66. cargo_workspace: The `cargo.Workspace` associated with the repository.
  67. image_registry: The Docker image registry to pull images from and push
  68. images to.
  69. image_prefix: A prefix to apply to all Docker image names.
  70. bazel: Whether or not to use Bazel as the build system instead of Cargo.
  71. bazel_remote_cache: URL of a Bazel Remote Cache that we can build with.
  72. bazel_lto: Force LTO build
  73. """
  74. def __init__(
  75. self,
  76. root: Path,
  77. arch: Arch,
  78. profile: Profile,
  79. coverage: bool,
  80. sanitizer: Sanitizer,
  81. image_registry: str,
  82. image_prefix: str,
  83. bazel: bool,
  84. bazel_remote_cache: str | None,
  85. bazel_lto: bool,
  86. ):
  87. self.root = root
  88. self.arch = arch
  89. self.profile = profile
  90. self.coverage = coverage
  91. self.sanitizer = sanitizer
  92. self.cargo_workspace = cargo.Workspace(root)
  93. self.image_registry = image_registry
  94. self.image_prefix = image_prefix
  95. self.bazel = bazel
  96. self.bazel_remote_cache = bazel_remote_cache
  97. self.bazel_lto = (
  98. bazel_lto
  99. or ui.env_is_truthy("BUILDKITE_TAG")
  100. or ui.env_is_truthy("CI_RELEASE_LTO_BUILD")
  101. )
  102. def build(
  103. self,
  104. subcommand: str,
  105. rustflags: list[str],
  106. channel: str | None = None,
  107. extra_env: dict[str, str] = {},
  108. ) -> list[str]:
  109. """Start a build invocation for the configured architecture."""
  110. if self.bazel:
  111. assert not channel, "Bazel doesn't support building for multiple channels."
  112. return xcompile.bazel(
  113. arch=self.arch,
  114. subcommand=subcommand,
  115. rustflags=rustflags,
  116. extra_env=extra_env,
  117. )
  118. else:
  119. return xcompile.cargo(
  120. arch=self.arch,
  121. channel=channel,
  122. subcommand=subcommand,
  123. rustflags=rustflags,
  124. extra_env=extra_env,
  125. )
  126. def tool(self, name: str) -> list[str]:
  127. """Start a binutils tool invocation for the configured architecture."""
  128. if self.bazel:
  129. return ["bazel", "run", f"@//misc/bazel/tools:{name}", "--"]
  130. else:
  131. return [name]
  132. def cargo_target_dir(self) -> Path:
  133. """Determine the path to the target directory for Cargo."""
  134. return self.root / "target-xcompile" / xcompile.target(self.arch)
  135. def bazel_workspace_dir(self) -> Path:
  136. """Determine the path to the root of the Bazel workspace."""
  137. return self.root
  138. def bazel_config(self) -> list[str]:
  139. """Returns a set of Bazel config flags to set for the build."""
  140. flags = []
  141. if self.profile == Profile.RELEASE:
  142. # If we're a tagged build, then we'll use stamping to update our
  143. # build info, otherwise we'll use our side channel/best-effort
  144. # approach to update it.
  145. if self.bazel_lto:
  146. flags.append("--config=release-tagged")
  147. else:
  148. flags.append("--config=release-dev")
  149. bazel_utils.write_git_hash()
  150. elif self.profile == Profile.OPTIMIZED:
  151. flags.append("--config=optimized")
  152. if self.bazel_remote_cache:
  153. flags.append(f"--remote_cache={self.bazel_remote_cache}")
  154. if ui.env_is_truthy("CI"):
  155. flags.append("--config=ci")
  156. # Building with sanitizers causes the intermediate artifacts to be
  157. # quite large so we'll skip using the RAM backed sandbox.
  158. if self.sanitizer == Sanitizer.none:
  159. flags.append("--config=in-mem-sandbox")
  160. # Add flags for the Sanitizer
  161. flags.extend(self.sanitizer.bazel_flags())
  162. return flags
  163. def rewrite_builder_path_for_host(self, path: Path) -> Path:
  164. """Rewrite a path that is relative to the target directory inside the
  165. builder to a path that is relative to the target directory on the host.
  166. If path does is not relative to the target directory inside the builder,
  167. it is returned unchanged.
  168. """
  169. builder_target_dir = Path("/mnt/build") / xcompile.target(self.arch)
  170. try:
  171. return self.cargo_target_dir() / path.relative_to(builder_target_dir)
  172. except ValueError:
  173. return path
  174. def docker_images() -> set[str]:
  175. """List the Docker images available on the local machine."""
  176. return set(
  177. spawn.capture(["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"])
  178. .strip()
  179. .split("\n")
  180. )
  181. KNOWN_DOCKER_IMAGES_FILE = Path(MZ_ROOT / "known-docker-images.txt")
  182. _known_docker_images: set[str] | None = None
  183. _known_docker_images_lock = Lock()
  184. def is_docker_image_pushed(name: str) -> bool:
  185. """Check whether the named image is pushed to Docker Hub.
  186. Note that this operation requires a rather slow network request.
  187. """
  188. global _known_docker_images
  189. if _known_docker_images is None:
  190. with _known_docker_images_lock:
  191. if not KNOWN_DOCKER_IMAGES_FILE.exists():
  192. _known_docker_images = set()
  193. else:
  194. with KNOWN_DOCKER_IMAGES_FILE.open() as f:
  195. _known_docker_images = set(line.strip() for line in f)
  196. if name in _known_docker_images:
  197. return True
  198. if ":" not in name:
  199. image, tag = name, "latest"
  200. else:
  201. image, tag = name.rsplit(":", 1)
  202. dockerhub_username = os.getenv("DOCKERHUB_USERNAME")
  203. dockerhub_token = os.getenv("DOCKERHUB_ACCESS_TOKEN")
  204. exists: bool = False
  205. try:
  206. if dockerhub_username and dockerhub_token:
  207. response = requests.head(
  208. f"https://registry-1.docker.io/v2/{image}/manifests/{tag}",
  209. headers={
  210. "Accept": "application/vnd.docker.distribution.manifest.v2+json",
  211. },
  212. auth=HTTPBasicAuth(dockerhub_username, dockerhub_token),
  213. )
  214. else:
  215. token = requests.get(
  216. "https://auth.docker.io/token",
  217. params={
  218. "service": "registry.docker.io",
  219. "scope": f"repository:{image}:pull",
  220. },
  221. ).json()["token"]
  222. response = requests.head(
  223. f"https://registry-1.docker.io/v2/{image}/manifests/{tag}",
  224. headers={
  225. "Accept": "application/vnd.docker.distribution.manifest.v2+json",
  226. "Authorization": f"Bearer {token}",
  227. },
  228. )
  229. if response.status_code in (401, 429, 500, 502, 503, 504):
  230. # Fall back to 5x slower method
  231. proc = subprocess.run(
  232. ["docker", "manifest", "inspect", name],
  233. stdout=subprocess.DEVNULL,
  234. stderr=subprocess.DEVNULL,
  235. env=dict(os.environ, DOCKER_CLI_EXPERIMENTAL="enabled"),
  236. )
  237. exists = proc.returncode == 0
  238. else:
  239. exists = response.status_code == 200
  240. except Exception as e:
  241. print(f"Error checking Docker image: {e}")
  242. return False
  243. if exists:
  244. with _known_docker_images_lock:
  245. _known_docker_images.add(name)
  246. with KNOWN_DOCKER_IMAGES_FILE.open("a") as f:
  247. print(name, file=f)
  248. return exists
  249. def chmod_x(path: Path) -> None:
  250. """Set the executable bit on a file or directory."""
  251. # https://stackoverflow.com/a/30463972/1122351
  252. mode = os.stat(path).st_mode
  253. mode |= (mode & 0o444) >> 2 # copy R bits to X
  254. os.chmod(path, mode)
  255. class PreImage:
  256. """An action to run before building a Docker image.
  257. Args:
  258. rd: The `RepositoryDetails` for the repository.
  259. path: The path to the `Image` associated with this action.
  260. """
  261. def __init__(self, rd: RepositoryDetails, path: Path):
  262. self.rd = rd
  263. self.path = path
  264. @classmethod
  265. def prepare_batch(cls, instances: list["PreImage"]) -> Any:
  266. """Prepare a batch of actions.
  267. This is useful for `PreImage` actions that are more efficient when
  268. their actions are applied to several images in bulk.
  269. Returns an arbitrary output that is passed to `PreImage.run`.
  270. """
  271. pass
  272. def run(self, prep: Any) -> None:
  273. """Perform the action.
  274. Args:
  275. prep: Any prep work returned by `prepare_batch`.
  276. """
  277. pass
  278. def inputs(self) -> set[str]:
  279. """Return the files which are considered inputs to the action."""
  280. raise NotImplementedError
  281. def extra(self) -> str:
  282. """Returns additional data for incorporation in the fingerprint."""
  283. return ""
  284. class Copy(PreImage):
  285. """A `PreImage` action which copies files from a directory.
  286. See doc/developer/mzbuild.md for an explanation of the user-facing
  287. parameters.
  288. """
  289. def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
  290. super().__init__(rd, path)
  291. self.source = config.pop("source", None)
  292. if self.source is None:
  293. raise ValueError("mzbuild config is missing 'source' argument")
  294. self.destination = config.pop("destination", None)
  295. if self.destination is None:
  296. raise ValueError("mzbuild config is missing 'destination' argument")
  297. self.matching = config.pop("matching", "*")
  298. def run(self, prep: Any) -> None:
  299. super().run(prep)
  300. for src in self.inputs():
  301. dst = self.path / self.destination / src
  302. dst.parent.mkdir(parents=True, exist_ok=True)
  303. shutil.copy(self.rd.root / self.source / src, dst)
  304. def inputs(self) -> set[str]:
  305. return set(git.expand_globs(self.rd.root / self.source, self.matching))
  306. class CargoPreImage(PreImage):
  307. """A `PreImage` action that uses Cargo."""
  308. def inputs(self) -> set[str]:
  309. inputs = {
  310. "ci/builder",
  311. "Cargo.toml",
  312. # TODO(benesch): we could in theory fingerprint only the subset of
  313. # Cargo.lock that applies to the crates at hand, but that is a
  314. # *lot* of work.
  315. "Cargo.lock",
  316. ".cargo/config",
  317. # Even though we are not always building with Bazel, consider its
  318. # inputs so that developers with CI_BAZEL_BUILD=0 can still
  319. # download the images from Dockerhub
  320. ".bazelrc",
  321. "WORKSPACE",
  322. }
  323. # Bazel has some rules and additive files that aren't directly
  324. # associated with a crate, but can change how it's built.
  325. additive_path = self.rd.root / "misc" / "bazel"
  326. additive_files = ["*.bazel", "*.bzl"]
  327. inputs |= {
  328. f"misc/bazel/{path}"
  329. for path in git.expand_globs(additive_path, *additive_files)
  330. }
  331. return inputs
  332. def extra(self) -> str:
  333. # Cargo images depend on the release mode and whether
  334. # coverage/sanitizer is enabled.
  335. flags: list[str] = []
  336. if self.rd.profile == Profile.RELEASE:
  337. flags += "release"
  338. if self.rd.profile == Profile.OPTIMIZED:
  339. flags += "optimized"
  340. if self.rd.coverage:
  341. flags += "coverage"
  342. if self.rd.sanitizer != Sanitizer.none:
  343. flags += self.rd.sanitizer.value
  344. flags.sort()
  345. return ",".join(flags)
  346. class CargoBuild(CargoPreImage):
  347. """A `PreImage` action that builds a single binary with Cargo.
  348. See doc/developer/mzbuild.md for an explanation of the user-facing
  349. parameters.
  350. """
  351. def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
  352. super().__init__(rd, path)
  353. bin = config.pop("bin", [])
  354. self.bins = bin if isinstance(bin, list) else [bin]
  355. example = config.pop("example", [])
  356. self.examples = example if isinstance(example, list) else [example]
  357. self.strip = config.pop("strip", True)
  358. self.extract = config.pop("extract", {})
  359. bazel_bins = config.pop("bazel-bin")
  360. self.bazel_bins = (
  361. bazel_bins if isinstance(bazel_bins, dict) else {self.bins[0]: bazel_bins}
  362. )
  363. self.bazel_tars = config.pop("bazel-tar", {})
  364. if len(self.bins) == 0 and len(self.examples) == 0:
  365. raise ValueError("mzbuild config is missing pre-build target")
  366. for bin in self.bins:
  367. if bin not in self.bazel_bins:
  368. raise ValueError(
  369. f"need to specify a 'bazel-bin' for '{bin}' at '{path}'"
  370. )
  371. @staticmethod
  372. def generate_bazel_build_command(
  373. rd: RepositoryDetails,
  374. bins: list[str],
  375. examples: list[str],
  376. bazel_bins: dict[str, str],
  377. bazel_tars: dict[str, str],
  378. ) -> list[str]:
  379. assert (
  380. rd.bazel
  381. ), "Programming error, tried to invoke Bazel when it is not enabled."
  382. assert not rd.coverage, "Bazel doesn't support building with coverage."
  383. rustflags = []
  384. if rd.sanitizer == Sanitizer.none:
  385. rustflags += ["--cfg=tokio_unstable"]
  386. extra_env = {
  387. "TSAN_OPTIONS": "report_bugs=0", # build-scripts fail
  388. }
  389. bazel_build = rd.build(
  390. "build",
  391. channel=None,
  392. rustflags=rustflags,
  393. extra_env=extra_env,
  394. )
  395. for bin in bins:
  396. bazel_build.append(bazel_bins[bin])
  397. for tar in bazel_tars:
  398. bazel_build.append(tar)
  399. # TODO(parkmycar): Make sure cargo-gazelle generates rust_binary targets for examples.
  400. assert len(examples) == 0, "Bazel doesn't support building examples."
  401. # Add extra Bazel config flags.
  402. bazel_build.extend(rd.bazel_config())
  403. return bazel_build
  404. @staticmethod
  405. def generate_cargo_build_command(
  406. rd: RepositoryDetails,
  407. bins: list[str],
  408. examples: list[str],
  409. ) -> list[str]:
  410. assert (
  411. not rd.bazel
  412. ), "Programming error, tried to invoke Cargo when Bazel is enabled."
  413. rustflags = (
  414. rustc_flags.coverage
  415. if rd.coverage
  416. else (
  417. rustc_flags.sanitizer[rd.sanitizer]
  418. if rd.sanitizer != Sanitizer.none
  419. else ["--cfg=tokio_unstable"]
  420. )
  421. )
  422. cflags = (
  423. [
  424. f"--target={target(rd.arch)}",
  425. f"--gcc-toolchain=/opt/x-tools/{target(rd.arch)}/",
  426. "-fuse-ld=lld",
  427. f"--sysroot=/opt/x-tools/{target(rd.arch)}/{target(rd.arch)}/sysroot",
  428. f"-L/opt/x-tools/{target(rd.arch)}/{target(rd.arch)}/lib64",
  429. ]
  430. + rustc_flags.sanitizer_cflags[rd.sanitizer]
  431. if rd.sanitizer != Sanitizer.none
  432. else []
  433. )
  434. extra_env = (
  435. {
  436. "CFLAGS": " ".join(cflags),
  437. "CXXFLAGS": " ".join(cflags),
  438. "LDFLAGS": " ".join(cflags),
  439. "CXXSTDLIB": "stdc++",
  440. "CC": "cc",
  441. "CXX": "c++",
  442. "CPP": "clang-cpp-18",
  443. "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER": "cc",
  444. "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER": "cc",
  445. "PATH": f"/sanshim:/opt/x-tools/{target(rd.arch)}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  446. "TSAN_OPTIONS": "report_bugs=0", # build-scripts fail
  447. }
  448. if rd.sanitizer != Sanitizer.none
  449. else {}
  450. )
  451. cargo_build = rd.build(
  452. "build", channel=None, rustflags=rustflags, extra_env=extra_env
  453. )
  454. packages = set()
  455. for bin in bins:
  456. cargo_build.extend(["--bin", bin])
  457. packages.add(rd.cargo_workspace.crate_for_bin(bin).name)
  458. for example in examples:
  459. cargo_build.extend(["--example", example])
  460. packages.add(rd.cargo_workspace.crate_for_example(example).name)
  461. cargo_build.extend(f"--package={p}" for p in packages)
  462. if rd.profile == Profile.RELEASE:
  463. cargo_build.append("--release")
  464. if rd.profile == Profile.OPTIMIZED:
  465. cargo_build.extend(["--profile", "optimized"])
  466. if rd.sanitizer != Sanitizer.none:
  467. # ASan doesn't work with jemalloc
  468. cargo_build.append("--no-default-features")
  469. # Uses more memory, so reduce the number of jobs
  470. cargo_build.extend(
  471. ["--jobs", str(round(multiprocessing.cpu_count() * 2 / 3))]
  472. )
  473. return cargo_build
  474. @classmethod
  475. def prepare_batch(cls, cargo_builds: list["PreImage"]) -> dict[str, Any]:
  476. super().prepare_batch(cargo_builds)
  477. if not cargo_builds:
  478. return {}
  479. # Building all binaries and examples in the same `cargo build` command
  480. # allows Cargo to link in parallel with other work, which can
  481. # meaningfully speed up builds.
  482. rd: RepositoryDetails | None = None
  483. builds = cast(list[CargoBuild], cargo_builds)
  484. bins = set()
  485. examples = set()
  486. bazel_bins = dict()
  487. bazel_tars = dict()
  488. for build in builds:
  489. if not rd:
  490. rd = build.rd
  491. bins.update(build.bins)
  492. examples.update(build.examples)
  493. bazel_bins.update(build.bazel_bins)
  494. bazel_tars.update(build.bazel_tars)
  495. assert rd
  496. ui.section(f"Common build for: {', '.join(bins | examples)}")
  497. if rd.bazel:
  498. cargo_build = cls.generate_bazel_build_command(
  499. rd, list(bins), list(examples), bazel_bins, bazel_tars
  500. )
  501. else:
  502. cargo_build = cls.generate_cargo_build_command(
  503. rd, list(bins), list(examples)
  504. )
  505. spawn.runv(cargo_build, cwd=rd.root)
  506. # Re-run with JSON-formatted messages and capture the output so we can
  507. # later analyze the build artifacts in `run`. This should be nearly
  508. # instantaneous since we just compiled above with the same crates and
  509. # features. (We don't want to do the compile above with JSON-formatted
  510. # messages because it wouldn't be human readable.)
  511. if rd.bazel:
  512. # TODO(parkmycar): Having to assign the same compilation flags as the build process
  513. # is a bit brittle. It would be better if the Bazel build process itself could
  514. # output the file to a known location.
  515. options = rd.bazel_config()
  516. paths_to_binaries = {}
  517. for bin in bins:
  518. paths = bazel_utils.output_paths(bazel_bins[bin], options)
  519. assert len(paths) == 1, f"{bazel_bins[bin]} output more than 1 file"
  520. paths_to_binaries[bin] = paths[0]
  521. for tar in bazel_tars:
  522. paths = bazel_utils.output_paths(tar, options)
  523. assert len(paths) == 1, f"more than one output path found for '{tar}'"
  524. paths_to_binaries[tar] = paths[0]
  525. prep = {"bazel": paths_to_binaries}
  526. else:
  527. json_output = spawn.capture(
  528. cargo_build + ["--message-format=json"],
  529. cwd=rd.root,
  530. )
  531. prep = {"cargo": json_output}
  532. return prep
  533. def build(self, build_output: dict[str, Any]) -> None:
  534. cargo_profile = (
  535. "release"
  536. if self.rd.profile == Profile.RELEASE
  537. else "optimized" if self.rd.profile == Profile.OPTIMIZED else "debug"
  538. )
  539. def copy(src: Path, relative_dst: Path) -> None:
  540. exe_path = self.path / relative_dst
  541. exe_path.parent.mkdir(parents=True, exist_ok=True)
  542. shutil.copy(src, exe_path)
  543. # Bazel doesn't add write or exec permissions for built binaries
  544. # but `strip` and `objcopy` need write permissions and we add exec
  545. # permissions for the built Docker images.
  546. current_perms = os.stat(exe_path).st_mode
  547. new_perms = (
  548. current_perms
  549. # chmod +wx
  550. | stat.S_IWUSR
  551. | stat.S_IWGRP
  552. | stat.S_IWOTH
  553. | stat.S_IXUSR
  554. | stat.S_IXGRP
  555. | stat.S_IXOTH
  556. )
  557. os.chmod(exe_path, new_perms)
  558. if self.strip:
  559. # The debug information is large enough that it slows down CI,
  560. # since we're packaging these binaries up into Docker images and
  561. # shipping them around.
  562. spawn.runv(
  563. [*self.rd.tool("strip"), "--strip-debug", exe_path],
  564. cwd=self.rd.root,
  565. )
  566. else:
  567. # Even if we've been asked not to strip the binary, remove the
  568. # `.debug_pubnames` and `.debug_pubtypes` sections. These are just
  569. # indexes that speed up launching a debugger against the binary,
  570. # and we're happy to have slower debugger start up in exchange for
  571. # smaller binaries. Plus the sections have been obsoleted by a
  572. # `.debug_names` section in DWARF 5, and so debugger support for
  573. # `.debug_pubnames`/`.debug_pubtypes` is minimal anyway.
  574. # See: https://github.com/rust-lang/rust/issues/46034
  575. spawn.runv(
  576. [
  577. *self.rd.tool("objcopy"),
  578. "-R",
  579. ".debug_pubnames",
  580. "-R",
  581. ".debug_pubtypes",
  582. exe_path,
  583. ],
  584. cwd=self.rd.root,
  585. )
  586. for bin in self.bins:
  587. if "bazel" in build_output:
  588. src_path = self.rd.bazel_workspace_dir() / build_output["bazel"][bin]
  589. else:
  590. src_path = self.rd.cargo_target_dir() / cargo_profile / bin
  591. copy(src_path, bin)
  592. for example in self.examples:
  593. src_path = (
  594. self.rd.cargo_target_dir() / cargo_profile / Path("examples") / example
  595. )
  596. copy(src_path, Path("examples") / example)
  597. # Bazel doesn't support 'extract', instead you need to use 'bazel-tar'
  598. if self.extract and "bazel" not in build_output:
  599. cargo_build_json_output = build_output["cargo"]
  600. target_dir = self.rd.cargo_target_dir()
  601. for line in cargo_build_json_output.split("\n"):
  602. if line.strip() == "" or not line.startswith("{"):
  603. continue
  604. message = json.loads(line)
  605. if message["reason"] != "build-script-executed":
  606. continue
  607. out_dir = self.rd.rewrite_builder_path_for_host(
  608. Path(message["out_dir"])
  609. )
  610. if not out_dir.is_relative_to(target_dir):
  611. # Some crates are built for both the host and the target.
  612. # Ignore the built-for-host out dir.
  613. continue
  614. # parse the package name from a package_id that looks like one of:
  615. # git+https://github.com/MaterializeInc/rust-server-sdk#launchdarkly-server-sdk@1.0.0
  616. # path+file:///Users/roshan/materialize/src/catalog#mz-catalog@0.0.0
  617. # registry+https://github.com/rust-lang/crates.io-index#num-rational@0.4.0
  618. # file:///path/to/my-package#0.1.0
  619. package_id = message["package_id"]
  620. if "@" in package_id:
  621. package = package_id.split("@")[0].split("#")[-1]
  622. else:
  623. package = message["package_id"].split("#")[0].split("/")[-1]
  624. for src, dst in self.extract.get(package, {}).items():
  625. spawn.runv(["cp", "-R", out_dir / src, self.path / dst])
  626. if self.bazel_tars and "bazel" in build_output:
  627. ui.section("Extracing 'bazel-tar'")
  628. for tar in self.bazel_tars:
  629. # Where Bazel built the tarball.
  630. tar_path = self.rd.bazel_workspace_dir() / build_output["bazel"][tar]
  631. # Where we need to extract it into.
  632. tar_dest = self.path / self.bazel_tars[tar]
  633. ui.say(f"extracing {tar_path} to {tar_dest}")
  634. with tarfile.open(tar_path, "r") as tar_file:
  635. os.makedirs(tar_dest, exist_ok=True)
  636. tar_file.extractall(path=tar_dest)
  637. self.acquired = True
  638. def run(self, prep: dict[str, Any]) -> None:
  639. super().run(prep)
  640. self.build(prep)
  641. @cache
  642. def inputs(self) -> set[str]:
  643. deps = set()
  644. for bin in self.bins:
  645. crate = self.rd.cargo_workspace.crate_for_bin(bin)
  646. deps |= self.rd.cargo_workspace.transitive_path_dependencies(crate)
  647. for example in self.examples:
  648. crate = self.rd.cargo_workspace.crate_for_example(example)
  649. deps |= self.rd.cargo_workspace.transitive_path_dependencies(
  650. crate, dev=True
  651. )
  652. inputs = super().inputs() | set(inp for dep in deps for inp in dep.inputs())
  653. # Even though we are not always building with Bazel, consider its
  654. # inputs so that developers with CI_BAZEL_BUILD=0 can still
  655. # download the images from Dockerhub
  656. inputs |= {"BUILD.bazel"}
  657. return inputs
  658. class Image:
  659. """A Docker image whose build and dependencies are managed by mzbuild.
  660. An image corresponds to a directory in a repository that contains a
  661. `mzbuild.yml` file. This directory is called an "mzbuild context."
  662. Attributes:
  663. name: The name of the image.
  664. publish: Whether the image should be pushed to Docker Hub.
  665. depends_on: The names of the images upon which this image depends.
  666. root: The path to the root of the associated `Repository`.
  667. path: The path to the directory containing the `mzbuild.yml`
  668. configuration file.
  669. pre_images: Optional actions to perform before running `docker build`.
  670. build_args: An optional list of --build-arg to pass to the dockerfile
  671. """
  672. _DOCKERFILE_MZFROM_RE = re.compile(rb"^MZFROM\s*(\S+)")
  673. def __init__(self, rd: RepositoryDetails, path: Path):
  674. self.rd = rd
  675. self.path = path
  676. self.pre_images: list[PreImage] = []
  677. with open(self.path / "mzbuild.yml") as f:
  678. data = yaml.safe_load(f)
  679. self.name: str = data.pop("name")
  680. self.publish: bool = data.pop("publish", True)
  681. self.description: str | None = data.pop("description", None)
  682. self.mainline: bool = data.pop("mainline", True)
  683. for pre_image in data.pop("pre-image", []):
  684. typ = pre_image.pop("type", None)
  685. if typ == "cargo-build":
  686. self.pre_images.append(CargoBuild(self.rd, self.path, pre_image))
  687. elif typ == "copy":
  688. self.pre_images.append(Copy(self.rd, self.path, pre_image))
  689. else:
  690. raise ValueError(
  691. f"mzbuild config in {self.path} has unknown pre-image type"
  692. )
  693. self.build_args = data.pop("build-args", {})
  694. if re.search(r"[^A-Za-z0-9\-]", self.name):
  695. raise ValueError(
  696. f"mzbuild image name {self.name} contains invalid character; only alphanumerics and hyphens allowed"
  697. )
  698. self.depends_on: list[str] = []
  699. with open(self.path / "Dockerfile", "rb") as f:
  700. for line in f:
  701. match = self._DOCKERFILE_MZFROM_RE.match(line)
  702. if match:
  703. self.depends_on.append(match.group(1).decode())
  704. def sync_description(self) -> None:
  705. """Sync the description to Docker Hub if the image is publishable
  706. and a README.md file exists."""
  707. if not self.publish:
  708. ui.say(f"{self.name} is not publishable")
  709. return
  710. readme_path = self.path / "README.md"
  711. has_readme = readme_path.exists()
  712. if not has_readme:
  713. ui.say(f"{self.name} has no README.md or description")
  714. return
  715. docker_config = os.getenv("DOCKER_CONFIG")
  716. spawn.runv(
  717. [
  718. "docker",
  719. "pushrm",
  720. f"--file={readme_path}",
  721. *([f"--config={docker_config}/config.json"] if docker_config else []),
  722. *([f"--short={self.description}"] if self.description else []),
  723. self.docker_name(),
  724. ]
  725. )
  726. def docker_name(self, tag: str | None = None) -> str:
  727. """Return the name of the image on Docker Hub at the given tag."""
  728. name = f"{self.rd.image_registry}/{self.rd.image_prefix}{self.name}"
  729. if tag:
  730. name += f":{tag}"
  731. return name
  732. class ResolvedImage:
  733. """An `Image` whose dependencies have been resolved.
  734. Attributes:
  735. image: The underlying `Image`.
  736. acquired: Whether the image is available locally.
  737. dependencies: A mapping from dependency name to `ResolvedImage` for
  738. each of the images that `image` depends upon.
  739. """
  740. def __init__(self, image: Image, dependencies: Iterable["ResolvedImage"]):
  741. self.image = image
  742. self.acquired = False
  743. self.dependencies = {}
  744. for d in dependencies:
  745. self.dependencies[d.name] = d
  746. def __repr__(self) -> str:
  747. return f"ResolvedImage<{self.spec()}>"
  748. @property
  749. def name(self) -> str:
  750. """The name of the underlying image."""
  751. return self.image.name
  752. @property
  753. def publish(self) -> bool:
  754. """Whether the underlying image should be pushed to Docker Hub."""
  755. return self.image.publish
  756. @cache
  757. def spec(self) -> str:
  758. """Return the "spec" for the image.
  759. A spec is the unique identifier for the image given its current
  760. fingerprint. It is a valid Docker Hub name.
  761. """
  762. return self.image.docker_name(tag=f"mzbuild-{self.fingerprint()}")
  763. def write_dockerfile(self) -> IO[bytes]:
  764. """Render the Dockerfile without mzbuild directives.
  765. Returns:
  766. file: A handle to a temporary file containing the adjusted
  767. Dockerfile."""
  768. with open(self.image.path / "Dockerfile", "rb") as f:
  769. lines = f.readlines()
  770. f = TemporaryFile()
  771. for line in lines:
  772. match = Image._DOCKERFILE_MZFROM_RE.match(line)
  773. if match:
  774. image = match.group(1).decode()
  775. spec = self.dependencies[image].spec()
  776. line = Image._DOCKERFILE_MZFROM_RE.sub(b"FROM %b" % spec.encode(), line)
  777. f.write(line)
  778. f.seek(0)
  779. return f
  780. def build(self, prep: dict[type[PreImage], Any], push: bool = False) -> None:
  781. """Build the image from source.
  782. Requires that the caller has already acquired all dependencies and
  783. prepared all `PreImage` actions via `PreImage.prepare_batch`.
  784. """
  785. ui.section(f"Building {self.spec()}")
  786. spawn.runv(["git", "clean", "-ffdX", self.image.path])
  787. for pre_image in self.image.pre_images:
  788. pre_image.run(prep[type(pre_image)])
  789. build_args = {
  790. **self.image.build_args,
  791. "ARCH_GCC": str(self.image.rd.arch),
  792. "ARCH_GO": self.image.rd.arch.go_str(),
  793. "CI_SANITIZER": str(self.image.rd.sanitizer),
  794. }
  795. f = self.write_dockerfile()
  796. try:
  797. spawn.capture(["docker", "buildx", "version"])
  798. except subprocess.CalledProcessError:
  799. if push:
  800. print(
  801. "docker buildx not found, required to push images. Installation: https://github.com/docker/buildx?tab=readme-ov-file#installing"
  802. )
  803. raise
  804. print(
  805. "docker buildx not found, you can install it to build faster. Installation: https://github.com/docker/buildx?tab=readme-ov-file#installing"
  806. )
  807. print("Falling back to docker build")
  808. cmd: Sequence[str] = [
  809. "docker",
  810. "build",
  811. "-f",
  812. "-",
  813. *(f"--build-arg={k}={v}" for k, v in build_args.items()),
  814. "-t",
  815. self.spec(),
  816. f"--platform=linux/{self.image.rd.arch.go_str()}",
  817. str(self.image.path),
  818. ]
  819. else:
  820. cmd: Sequence[str] = [
  821. "docker",
  822. "buildx",
  823. "build",
  824. "--progress=plain", # less noisy
  825. "-f",
  826. "-",
  827. *(f"--build-arg={k}={v}" for k, v in build_args.items()),
  828. "-t",
  829. self.spec(),
  830. f"--platform=linux/{self.image.rd.arch.go_str()}",
  831. str(self.image.path),
  832. *(("--push",) if push else ()),
  833. ]
  834. spawn.runv(cmd, stdin=f, stdout=sys.stderr.buffer)
  835. def try_pull(self, max_retries: int) -> bool:
  836. """Download the image if it does not exist locally. Returns whether it was found."""
  837. ui.header(f"Acquiring {self.spec()}")
  838. command = ["docker", "pull"]
  839. # --quiet skips printing the progress bar, which does not display well in CI.
  840. if ui.env_is_truthy("CI"):
  841. command.append("--quiet")
  842. command.append(self.spec())
  843. if not self.acquired:
  844. sleep_time = 1
  845. for retry in range(1, max_retries + 1):
  846. try:
  847. spawn.runv(
  848. command,
  849. stdout=sys.stderr.buffer,
  850. )
  851. self.acquired = True
  852. break
  853. except subprocess.CalledProcessError:
  854. if retry < max_retries:
  855. # There seems to be no good way to tell what error
  856. # happened based on error code
  857. # (https://github.com/docker/cli/issues/538) and we
  858. # want to print output directly to terminal.
  859. print(f"Retrying in {sleep_time}s ...")
  860. time.sleep(sleep_time)
  861. sleep_time = min(sleep_time * 2, 10)
  862. if build := os.getenv("CI_WAITING_FOR_BUILD"):
  863. if buildkite.is_build_failed(build):
  864. print(
  865. f"Build {build} has been marked as failed, exiting hard"
  866. )
  867. sys.exit(1)
  868. continue
  869. else:
  870. break
  871. return self.acquired
  872. def is_published_if_necessary(self) -> bool:
  873. """Report whether the image exists on Docker Hub if it is publishable."""
  874. if self.publish and is_docker_image_pushed(self.spec()):
  875. ui.say(f"{self.spec()} already exists")
  876. return True
  877. return False
  878. def run(
  879. self,
  880. args: list[str] = [],
  881. docker_args: list[str] = [],
  882. env: dict[str, str] = {},
  883. ) -> None:
  884. """Run a command in the image.
  885. Creates a container from the image and runs the command described by
  886. `args` in the image.
  887. """
  888. envs = []
  889. for key, val in env.items():
  890. envs.extend(["--env", f"{key}={val}"])
  891. spawn.runv(
  892. [
  893. "docker",
  894. "run",
  895. "--tty",
  896. "--rm",
  897. *envs,
  898. "--init",
  899. *docker_args,
  900. self.spec(),
  901. *args,
  902. ],
  903. )
  904. def list_dependencies(self, transitive: bool = False) -> set[str]:
  905. out = set()
  906. for dep in self.dependencies.values():
  907. out.add(dep.name)
  908. if transitive:
  909. out |= dep.list_dependencies(transitive)
  910. return out
  911. @cache
  912. def inputs(self, transitive: bool = False) -> set[str]:
  913. """List the files tracked as inputs to the image.
  914. These files are used to compute the fingerprint for the image. See
  915. `ResolvedImage.fingerprint` for details.
  916. Returns:
  917. inputs: A list of input files, relative to the root of the
  918. repository.
  919. """
  920. paths = set(git.expand_globs(self.image.rd.root, f"{self.image.path}/**"))
  921. if not paths:
  922. # While we could find an `mzbuild.yml` file for this service, expland_globs didn't
  923. # return any files that matched this service. At the very least, the `mzbuild.yml`
  924. # file itself should have been returned. We have a bug if paths is empty.
  925. raise AssertionError(
  926. f"{self.image.name} mzbuild exists but its files are unknown to git"
  927. )
  928. for pre_image in self.image.pre_images:
  929. paths |= pre_image.inputs()
  930. if transitive:
  931. for dep in self.dependencies.values():
  932. paths |= dep.inputs(transitive)
  933. return paths
  934. @cache
  935. def fingerprint(self) -> Fingerprint:
  936. """Fingerprint the inputs to the image.
  937. Compute the fingerprint of the image. Changing the contents of any of
  938. the files or adding or removing files to the image will change the
  939. fingerprint, as will modifying the inputs to any of its dependencies.
  940. The image considers all non-gitignored files in its mzbuild context to
  941. be inputs. If it has a pre-image action, that action may add additional
  942. inputs via `PreImage.inputs`.
  943. """
  944. self_hash = hashlib.sha1()
  945. for rel_path in sorted(
  946. set(git.expand_globs(self.image.rd.root, *self.inputs()))
  947. ):
  948. abs_path = self.image.rd.root / rel_path
  949. file_hash = hashlib.sha1()
  950. raw_file_mode = os.lstat(abs_path).st_mode
  951. # Compute a simplified file mode using the same rules as Git.
  952. # https://github.com/git/git/blob/3bab5d562/Documentation/git-fast-import.txt#L610-L616
  953. if stat.S_ISLNK(raw_file_mode):
  954. file_mode = 0o120000
  955. elif raw_file_mode & stat.S_IXUSR:
  956. file_mode = 0o100755
  957. else:
  958. file_mode = 0o100644
  959. with open(abs_path, "rb") as f:
  960. file_hash.update(f.read())
  961. self_hash.update(file_mode.to_bytes(2, byteorder="big"))
  962. self_hash.update(rel_path.encode())
  963. self_hash.update(file_hash.digest())
  964. self_hash.update(b"\0")
  965. for pre_image in self.image.pre_images:
  966. self_hash.update(pre_image.extra().encode())
  967. self_hash.update(b"\0")
  968. self_hash.update(f"profile={self.image.rd.profile}".encode())
  969. self_hash.update(f"arch={self.image.rd.arch}".encode())
  970. self_hash.update(f"coverage={self.image.rd.coverage}".encode())
  971. self_hash.update(f"sanitizer={self.image.rd.sanitizer}".encode())
  972. full_hash = hashlib.sha1()
  973. full_hash.update(self_hash.digest())
  974. for dep in sorted(self.dependencies.values(), key=lambda d: d.name):
  975. full_hash.update(dep.name.encode())
  976. full_hash.update(dep.fingerprint())
  977. full_hash.update(b"\0")
  978. return Fingerprint(full_hash.digest())
  979. class DependencySet:
  980. """A set of `ResolvedImage`s.
  981. Iterating over a dependency set yields the contained images in an arbitrary
  982. order. Indexing a dependency set yields the image with the specified name.
  983. """
  984. def __init__(self, dependencies: Iterable[Image]):
  985. """Construct a new `DependencySet`.
  986. The provided `dependencies` must be topologically sorted.
  987. """
  988. self._dependencies: dict[str, ResolvedImage] = {}
  989. known_images = docker_images()
  990. for d in dependencies:
  991. image = ResolvedImage(
  992. image=d,
  993. dependencies=(self._dependencies[d0] for d0 in d.depends_on),
  994. )
  995. image.acquired = image.spec() in known_images
  996. self._dependencies[d.name] = image
  997. def _prepare_batch(self, images: list[ResolvedImage]) -> dict[type[PreImage], Any]:
  998. pre_images = collections.defaultdict(list)
  999. for image in images:
  1000. for pre_image in image.image.pre_images:
  1001. pre_images[type(pre_image)].append(pre_image)
  1002. pre_image_prep = {}
  1003. for cls, instances in pre_images.items():
  1004. pre_image = cast(PreImage, cls)
  1005. pre_image_prep[cls] = pre_image.prepare_batch(instances)
  1006. return pre_image_prep
  1007. def acquire(self, max_retries: int | None = None) -> None:
  1008. """Download or build all of the images in the dependency set that do not
  1009. already exist locally.
  1010. Args:
  1011. max_retries: Number of retries on failure.
  1012. """
  1013. # Only retry in CI runs since we struggle with flaky docker pulls there
  1014. if not max_retries:
  1015. max_retries = (
  1016. 90
  1017. if os.getenv("CI_WAITING_FOR_BUILD")
  1018. else 5 if ui.env_is_truthy("CI") else 1
  1019. )
  1020. assert max_retries > 0
  1021. deps_to_check = [dep for dep in self if dep.publish]
  1022. deps_to_build = [dep for dep in self if not dep.publish]
  1023. if len(deps_to_check):
  1024. with ThreadPoolExecutor(max_workers=len(deps_to_check)) as executor:
  1025. futures = [
  1026. executor.submit(dep.try_pull, max_retries) for dep in deps_to_check
  1027. ]
  1028. for dep, future in zip(deps_to_check, futures):
  1029. try:
  1030. if not future.result():
  1031. deps_to_build.append(dep)
  1032. except Exception:
  1033. deps_to_build.append(dep)
  1034. # Don't attempt to build in CI, as our timeouts and small machines won't allow it anyway
  1035. if ui.env_is_truthy("CI"):
  1036. expected_deps = [dep for dep in deps_to_build if dep.publish]
  1037. if expected_deps:
  1038. print(
  1039. f"+++ Expected builds to be available, the build probably failed, so not proceeding: {expected_deps}"
  1040. )
  1041. sys.exit(5)
  1042. prep = self._prepare_batch(deps_to_build)
  1043. for dep in deps_to_build:
  1044. dep.build(prep)
  1045. def ensure(self, post_build: Callable[[ResolvedImage], None] | None = None):
  1046. """Ensure all publishable images in this dependency set exist on Docker
  1047. Hub.
  1048. Images are pushed using their spec as their tag.
  1049. Args:
  1050. post_build: A callback to invoke with each dependency that was built
  1051. locally.
  1052. """
  1053. num_deps = len(list(self))
  1054. if not num_deps:
  1055. deps_to_build = []
  1056. else:
  1057. with ThreadPoolExecutor(max_workers=num_deps) as executor:
  1058. futures = list(
  1059. executor.map(
  1060. lambda dep: (dep, not dep.is_published_if_necessary()), self
  1061. )
  1062. )
  1063. deps_to_build = [dep for dep, should_build in futures if should_build]
  1064. prep = self._prepare_batch(deps_to_build)
  1065. lock = Lock()
  1066. built_deps: set[str] = set([dep.name for dep in self]) - set(
  1067. [dep.name for dep in deps_to_build]
  1068. )
  1069. def build_dep(dep):
  1070. end_time = time.time() + 600
  1071. while True:
  1072. if time.time() > end_time:
  1073. raise TimeoutError(
  1074. f"Timed out in {dep.name} waiting for {[dep2.name for dep2 in dep.dependencies if dep2 not in built_deps]}"
  1075. )
  1076. with lock:
  1077. if all(dep2 in built_deps for dep2 in dep.dependencies):
  1078. break
  1079. time.sleep(0.01)
  1080. for attempts_remaining in reversed(range(3)):
  1081. try:
  1082. dep.build(prep, push=dep.publish)
  1083. with lock:
  1084. built_deps.add(dep.name)
  1085. break
  1086. except Exception:
  1087. if not dep.publish or attempts_remaining == 0:
  1088. raise
  1089. if post_build:
  1090. post_build(dep)
  1091. if deps_to_build:
  1092. with ThreadPoolExecutor(max_workers=len(deps_to_build)) as executor:
  1093. futures = [executor.submit(build_dep, dep) for dep in deps_to_build]
  1094. for future in as_completed(futures):
  1095. future.result()
  1096. def check(self) -> bool:
  1097. """Check all publishable images in this dependency set exist on Docker
  1098. Hub. Don't try to download or build them."""
  1099. num_deps = len(list(self))
  1100. if num_deps == 0:
  1101. return True
  1102. with ThreadPoolExecutor(max_workers=num_deps) as executor:
  1103. results = list(
  1104. executor.map(lambda dep: dep.is_published_if_necessary(), list(self))
  1105. )
  1106. return all(results)
  1107. def __iter__(self) -> Iterator[ResolvedImage]:
  1108. return iter(self._dependencies.values())
  1109. def __getitem__(self, key: str) -> ResolvedImage:
  1110. return self._dependencies[key]
  1111. class Repository:
  1112. """A collection of mzbuild `Image`s.
  1113. Creating a repository will walk the filesystem beneath `root` to
  1114. automatically discover all contained `Image`s.
  1115. Iterating over a repository yields the contained images in an arbitrary
  1116. order.
  1117. Args:
  1118. root: The path to the root of the repository.
  1119. arch: The CPU architecture to build for.
  1120. profile: What profile to build the repository in.
  1121. coverage: Whether to enable code coverage instrumentation.
  1122. sanitizer: Whether to a sanitizer (address, thread, leak, memory, none)
  1123. image_registry: The Docker image registry to pull images from and push
  1124. images to.
  1125. image_prefix: A prefix to apply to all Docker image names.
  1126. Attributes:
  1127. images: A mapping from image name to `Image` for all contained images.
  1128. compose_dirs: The set of directories containing a `mzcompose.py` file.
  1129. """
  1130. def __init__(
  1131. self,
  1132. root: Path,
  1133. arch: Arch = Arch.host(),
  1134. profile: Profile = (
  1135. Profile.RELEASE if ui.env_is_truthy("CI_BAZEL_LTO") else Profile.OPTIMIZED
  1136. ),
  1137. coverage: bool = False,
  1138. sanitizer: Sanitizer = Sanitizer.none,
  1139. image_registry: str = "materialize",
  1140. image_prefix: str = "",
  1141. bazel: bool = False,
  1142. bazel_remote_cache: str | None = None,
  1143. bazel_lto: bool = False,
  1144. ):
  1145. self.rd = RepositoryDetails(
  1146. root,
  1147. arch,
  1148. profile,
  1149. coverage,
  1150. sanitizer,
  1151. image_registry,
  1152. image_prefix,
  1153. bazel,
  1154. bazel_remote_cache,
  1155. bazel_lto,
  1156. )
  1157. self.images: dict[str, Image] = {}
  1158. self.compositions: dict[str, Path] = {}
  1159. for path, dirs, files in os.walk(self.root, topdown=True):
  1160. if path == str(root / "misc"):
  1161. dirs.remove("python")
  1162. # Filter out some particularly massive ignored directories to keep
  1163. # things snappy. Not required for correctness.
  1164. dirs[:] = set(dirs) - {
  1165. ".git",
  1166. ".mypy_cache",
  1167. "target",
  1168. "target-ra",
  1169. "target-xcompile",
  1170. "mzdata",
  1171. "node_modules",
  1172. "venv",
  1173. }
  1174. if "mzbuild.yml" in files:
  1175. image = Image(self.rd, Path(path))
  1176. if not image.name:
  1177. raise ValueError(f"config at {path} missing name")
  1178. if image.name in self.images:
  1179. raise ValueError(f"image {image.name} exists twice")
  1180. self.images[image.name] = image
  1181. if "mzcompose.py" in files:
  1182. name = Path(path).name
  1183. if name in self.compositions:
  1184. raise ValueError(f"composition {name} exists twice")
  1185. self.compositions[name] = Path(path)
  1186. # Validate dependencies.
  1187. for image in self.images.values():
  1188. for d in image.depends_on:
  1189. if d not in self.images:
  1190. raise ValueError(
  1191. f"image {image.name} depends on non-existent image {d}"
  1192. )
  1193. @staticmethod
  1194. def install_arguments(parser: argparse.ArgumentParser) -> None:
  1195. """Install options to configure a repository into an argparse parser.
  1196. This function installs the following options:
  1197. * The mutually-exclusive `--dev`/`--optimized`/`--release` options to control the
  1198. `profile` repository attribute.
  1199. * The `--coverage` boolean option to control the `coverage` repository
  1200. attribute.
  1201. Use `Repository.from_arguments` to construct a repository from the
  1202. parsed command-line arguments.
  1203. """
  1204. build_mode = parser.add_mutually_exclusive_group()
  1205. build_mode.add_argument(
  1206. "--dev",
  1207. action="store_true",
  1208. help="build Rust binaries with the dev profile",
  1209. )
  1210. build_mode.add_argument(
  1211. "--release",
  1212. action="store_true",
  1213. help="build Rust binaries with the release profile (default)",
  1214. )
  1215. build_mode.add_argument(
  1216. "--optimized",
  1217. action="store_true",
  1218. help="build Rust binaries with the optimized profile (optimizations, no LTO, no debug symbols)",
  1219. )
  1220. parser.add_argument(
  1221. "--coverage",
  1222. help="whether to enable code coverage compilation flags",
  1223. default=ui.env_is_truthy("CI_COVERAGE_ENABLED"),
  1224. action="store_true",
  1225. )
  1226. parser.add_argument(
  1227. "--sanitizer",
  1228. help="whether to enable a sanitizer",
  1229. default=Sanitizer[os.getenv("CI_SANITIZER", "none")],
  1230. type=Sanitizer,
  1231. choices=Sanitizer,
  1232. )
  1233. parser.add_argument(
  1234. "--arch",
  1235. default=Arch.host(),
  1236. help="the CPU architecture to build for",
  1237. type=Arch,
  1238. choices=Arch,
  1239. )
  1240. parser.add_argument(
  1241. "--image-registry",
  1242. default="materialize",
  1243. help="the Docker image registry to pull images from and push images to",
  1244. )
  1245. parser.add_argument(
  1246. "--image-prefix",
  1247. default="",
  1248. help="a prefix to apply to all Docker image names",
  1249. )
  1250. parser.add_argument(
  1251. "--bazel",
  1252. default=ui.env_is_truthy("CI_BAZEL_BUILD"),
  1253. action="store_true",
  1254. )
  1255. parser.add_argument(
  1256. "--bazel-remote-cache",
  1257. default=os.getenv("CI_BAZEL_REMOTE_CACHE"),
  1258. action="store",
  1259. )
  1260. parser.add_argument(
  1261. "--bazel-lto",
  1262. default=ui.env_is_truthy("CI_BAZEL_LTO"),
  1263. action="store",
  1264. )
  1265. @classmethod
  1266. def from_arguments(cls, root: Path, args: argparse.Namespace) -> "Repository":
  1267. """Construct a repository from command-line arguments.
  1268. The provided namespace must contain the options installed by
  1269. `Repository.install_arguments`.
  1270. """
  1271. if args.release:
  1272. profile = Profile.RELEASE
  1273. elif args.optimized:
  1274. profile = Profile.OPTIMIZED
  1275. elif args.dev:
  1276. profile = Profile.DEV
  1277. else:
  1278. profile = (
  1279. Profile.RELEASE
  1280. if ui.env_is_truthy("CI_BAZEL_LTO")
  1281. else Profile.OPTIMIZED
  1282. )
  1283. return cls(
  1284. root,
  1285. profile=profile,
  1286. coverage=args.coverage,
  1287. sanitizer=args.sanitizer,
  1288. image_registry=args.image_registry,
  1289. image_prefix=args.image_prefix,
  1290. arch=args.arch,
  1291. bazel=args.bazel,
  1292. bazel_remote_cache=args.bazel_remote_cache,
  1293. bazel_lto=args.bazel_lto,
  1294. )
  1295. @property
  1296. def root(self) -> Path:
  1297. """The path to the root directory for the repository."""
  1298. return self.rd.root
  1299. def resolve_dependencies(self, targets: Iterable[Image]) -> DependencySet:
  1300. """Compute the dependency set necessary to build target images.
  1301. The dependencies of `targets` will be crawled recursively until the
  1302. complete set of transitive dependencies is determined or a circular
  1303. dependency is discovered. The returned dependency set will be sorted
  1304. in topological order.
  1305. Raises:
  1306. ValueError: A circular dependency was discovered in the images
  1307. in the repository.
  1308. """
  1309. resolved = OrderedDict()
  1310. visiting = set()
  1311. def visit(image: Image, path: list[str] = []) -> None:
  1312. if image.name in resolved:
  1313. return
  1314. if image.name in visiting:
  1315. diagram = " -> ".join(path + [image.name])
  1316. raise ValueError(f"circular dependency in mzbuild: {diagram}")
  1317. visiting.add(image.name)
  1318. for d in sorted(image.depends_on):
  1319. visit(self.images[d], path + [image.name])
  1320. resolved[image.name] = image
  1321. for target_image in sorted(targets, key=lambda image: image.name):
  1322. visit(target_image)
  1323. return DependencySet(resolved.values())
  1324. def __iter__(self) -> Iterator[Image]:
  1325. return iter(self.images.values())
  1326. def publish_multiarch_images(
  1327. tag: str, dependency_sets: Iterable[Iterable[ResolvedImage]]
  1328. ) -> None:
  1329. """Publishes a set of docker images under a given tag."""
  1330. for images in zip(*dependency_sets):
  1331. names = set(image.image.name for image in images)
  1332. assert len(names) == 1, "dependency sets did not contain identical images"
  1333. name = images[0].image.docker_name(tag)
  1334. spawn.runv(
  1335. ["docker", "manifest", "create", name, *(image.spec() for image in images)]
  1336. )
  1337. spawn.runv(["docker", "manifest", "push", name])
  1338. print(f"--- Nofifying for tag {tag}")
  1339. markdown = f"""Pushed images with Docker tag `{tag}`"""
  1340. spawn.runv(
  1341. [
  1342. "buildkite-agent",
  1343. "annotate",
  1344. "--style=info",
  1345. f"--context=build-tags-{tag}",
  1346. ],
  1347. stdin=markdown.encode(),
  1348. )