misc.python.materialize.mzbuild

The implementation of the mzbuild system for Docker images.

For an overview of what mzbuild is and why it exists, see the user-facing documentation.

   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
  10"""The implementation of the mzbuild system for Docker images.
  11
  12For an overview of what mzbuild is and why it exists, see the [user-facing
  13documentation][user-docs].
  14
  15[user-docs]: https://github.com/MaterializeInc/materialize/blob/main/doc/developer/mzbuild.md
  16"""
  17
  18import argparse
  19import base64
  20import collections
  21import fcntl
  22import hashlib
  23import io
  24import json
  25import multiprocessing
  26import os
  27import platform
  28import re
  29import selectors
  30import shutil
  31import stat
  32import subprocess
  33import sys
  34import time
  35from collections import OrderedDict
  36from collections.abc import Callable, Iterable, Iterator, Sequence
  37from concurrent.futures import ThreadPoolExecutor, as_completed
  38from enum import Enum, auto
  39from functools import cache
  40from pathlib import Path
  41from tempfile import TemporaryFile
  42from threading import Lock
  43from typing import IO, Any, NoReturn, cast
  44
  45import requests
  46import yaml
  47from requests.auth import HTTPBasicAuth
  48
  49from materialize import MZ_ROOT, cargo, git, rustc_flags, spawn, ui, xcompile
  50from materialize.docker import image_registry
  51from materialize.rustc_flags import Sanitizer
  52from materialize.xcompile import Arch, target
  53
  54GHCR_PREFIX = "ghcr.io/materializeinc/"
  55
  56
  57class RustIncrementalBuildFailure(Exception):
  58    """A build failure that corrupted incremental artifacts explain. Recovering
  59    requires clearing the cargo target directories before retrying."""
  60
  61
  62class CargoRegistryFetchFailure(Exception):
  63    """A crates.io fetch that failed for transport reasons. Retrying recovers,
  64    and the target directories must be kept: nothing in them is corrupted."""
  65
  66
  67def raise_if_retryable_build_failure(output: str) -> None:
  68    """Raises `RustIncrementalBuildFailure` or `CargoRegistryFetchFailure` if
  69    the output of a failed cargo invocation matches a known signature."""
  70    incremental_build_failure_msgs = [
  71        "panicked at compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs",
  72        "Found unstable fingerprints for",
  73        "ld.lld: error: undefined symbol",
  74        "truncated or malformed archive",
  75        "signal: 11, SIGSEGV",
  76    ]
  77    registry_fetch_failure_msgs = [
  78        "unable to update registry",
  79    ]
  80    # A cached build-script binary poisoned by cargo cache corruption dies
  81    # with a bare ENOENT before doing any work. Both halves are required,
  82    # and the error must be the exact bare line: "failed to run custom
  83    # build command" alone is any build-script bug, which a retry cannot
  84    # fix, and a build script that fails on a missing file with an error
  85    # context of its own produces the ENOENT in a "Caused by:" detail line
  86    # instead of the bare "Error:" line.
  87    custom_build_script_enoent = "failed to run custom build command" in output and any(
  88        line.strip() == "Error: No such file or directory (os error 2)"
  89        for line in output.splitlines()
  90    )
  91    if custom_build_script_enoent or any(
  92        msg in output for msg in incremental_build_failure_msgs
  93    ):
  94        raise RustIncrementalBuildFailure()
  95    if any(msg in output for msg in registry_fetch_failure_msgs):
  96        raise CargoRegistryFetchFailure()
  97
  98
  99def exit_for_retryable_build_failure(
 100    e: RustIncrementalBuildFailure | CargoRegistryFetchFailure,
 101) -> NoReturn:
 102    """Exits with 199, which Buildkite retries automatically (see
 103    mkpipeline.py), after clearing the cargo target directories if they are
 104    corrupted."""
 105    if isinstance(e, RustIncrementalBuildFailure):
 106        print(
 107            "--- Detected incremental build failure, clearing cargo target directories"
 108        )
 109        for dir in ["target", "target-xcompile"]:
 110            shutil.rmtree(MZ_ROOT / dir, ignore_errors=True)
 111    else:
 112        # Nothing on disk is corrupted, so keep the target directories. Wiping
 113        # them would turn a network blip into a full rebuild of the workspace,
 114        # here and in every later job that shares the agent's target directory.
 115        print("--- Detected transient cargo registry failure, retrying")
 116    sys.exit(199)
 117
 118
 119def run_and_detect_retryable_build_failure(
 120    cmd: list[str],
 121    cwd: str | Path,
 122    env: dict[str, str] | None = None,
 123) -> subprocess.CompletedProcess:
 124    """This function is complex since it prints out each line immediately to
 125    stdout/stderr, but still records them at the same time so that we can scan
 126    for known retryable build failures."""
 127    stdout_result = io.StringIO()
 128    stderr_result = io.StringIO()
 129    base_env = env if env is not None else os.environ
 130    p = subprocess.Popen(
 131        cmd,
 132        cwd=cwd,
 133        stdout=subprocess.PIPE,
 134        stderr=subprocess.PIPE,
 135        text=True,
 136        bufsize=1,
 137        env={**base_env, "CARGO_TERM_COLOR": "always", "RUSTC_COLOR": "always"},
 138    )
 139
 140    sel = selectors.DefaultSelector()
 141    sel.register(p.stdout, selectors.EVENT_READ)  # type: ignore
 142    sel.register(p.stderr, selectors.EVENT_READ)  # type: ignore
 143    assert p.stdout is not None
 144    assert p.stderr is not None
 145    os.set_blocking(p.stdout.fileno(), False)
 146    os.set_blocking(p.stderr.fileno(), False)
 147    running = True
 148    while running:
 149        for key, val in sel.select():
 150            output = io.StringIO()
 151            running = False
 152            while True:
 153                new_output = key.fileobj.read(1024)  # type: ignore
 154                if not new_output:
 155                    break
 156                output.write(new_output)
 157            contents = output.getvalue()
 158            output.close()
 159            if not contents:
 160                continue
 161            # Keep running as long as stdout or stderr have any content
 162            running = True
 163            if key.fileobj is p.stdout:
 164                print(
 165                    contents,
 166                    end="",
 167                    flush=True,
 168                )
 169                stdout_result.write(contents)
 170            else:
 171                print(
 172                    contents,
 173                    end="",
 174                    file=sys.stderr,
 175                    flush=True,
 176                )
 177                stderr_result.write(contents)
 178    p.wait()
 179    retcode = p.poll()
 180    assert retcode is not None
 181    stdout_contents = stdout_result.getvalue()
 182    stdout_result.close()
 183    stderr_contents = stderr_result.getvalue()
 184    stderr_result.close()
 185    if retcode:
 186        raise_if_retryable_build_failure(stdout_contents + stderr_contents)
 187        raise subprocess.CalledProcessError(
 188            retcode, p.args, output=stdout_contents, stderr=stderr_contents
 189        )
 190    return subprocess.CompletedProcess(
 191        p.args, retcode, stdout_contents, stderr_contents
 192    )
 193
 194
 195class Fingerprint(bytes):
 196    """A SHA-1 hash of the inputs to an `Image`.
 197
 198    The string representation uses base32 encoding to distinguish mzbuild
 199    fingerprints from Git's hex encoded SHA-1 hashes while still being
 200    URL safe.
 201    """
 202
 203    def __str__(self) -> str:
 204        return base64.b32encode(self).decode()
 205
 206
 207class Profile(Enum):
 208    RELEASE = auto()
 209    OPTIMIZED = auto()
 210    DEV = auto()
 211
 212
 213class RepositoryDetails:
 214    """Immutable details about a `Repository`.
 215
 216    Used internally by mzbuild.
 217
 218    Attributes:
 219        root: The path to the root of the repository.
 220        arch: The CPU architecture to build for.
 221        profile: What profile the repository is being built with.
 222        coverage: Whether the repository has code coverage instrumentation
 223            enabled.
 224        sanitizer: Whether to use a sanitizer (address, hwaddress, cfi, thread, leak, memory, none)
 225        cargo_workspace: The `cargo.Workspace` associated with the repository.
 226        image_registry: The Docker image registry to pull images from and push
 227            images to.
 228        image_prefix: A prefix to apply to all Docker image names.
 229    """
 230
 231    def __init__(
 232        self,
 233        root: Path,
 234        arch: Arch,
 235        profile: Profile,
 236        coverage: bool,
 237        sanitizer: Sanitizer,
 238        image_registry: str,
 239        image_prefix: str,
 240    ):
 241        self.root = root
 242        self.arch = arch
 243        self.profile = profile
 244        self.coverage = coverage
 245        self.sanitizer = sanitizer
 246        self.cargo_workspace = cargo.Workspace(root)
 247        self.image_registry = image_registry
 248        self.image_prefix = image_prefix
 249
 250    def build(
 251        self,
 252        subcommand: str,
 253        rustflags: list[str],
 254        channel: str | None = None,
 255        extra_env: dict[str, str] = {},
 256    ) -> list[str]:
 257        """Start a build invocation for the configured architecture."""
 258        return xcompile.cargo(
 259            arch=self.arch,
 260            channel=channel,
 261            subcommand=subcommand,
 262            rustflags=rustflags,
 263            extra_env=extra_env,
 264        )
 265
 266    def tool(self, name: str) -> list[str]:
 267        """Start a binutils tool invocation for the configured architecture."""
 268        if platform.system() != "Linux":
 269            # We can't use the local tools from macOS to build a Linux executable
 270            return ["bin/ci-builder", "run", "stable", name]
 271        # If we're on Linux, trust that the tools are installed instead of
 272        # loading the slow ci-builder. If you don't have compilation tools
 273        # installed you can still run `bin/ci-builder run stable
 274        # bin/mzcompose ...`, and most likely the Cargo build will already
 275        # fail earlier if you don't have compilation tools installed and
 276        # run without the ci-builder.
 277        return [name]
 278
 279    def builder(self, args: list[str]) -> list[str]:
 280        """Start an invocation of `args` inside the ci-builder for the
 281        configured architecture, from the repository root.
 282
 283        Unlike `build`, this enters the ci-builder on macOS too, so `args` can
 284        rely on files that only the ci-builder image provides.
 285        """
 286        if "MZ_DEV_CI_BUILDER" in os.environ:
 287            return args
 288        return [
 289            "env",
 290            f"MZ_DEV_CI_BUILDER_ARCH={self.arch}",
 291            "bin/ci-builder",
 292            "run",
 293            "stable",
 294            *args,
 295        ]
 296
 297    def cargo_target_dir(self) -> Path:
 298        """Determine the path to the target directory for Cargo."""
 299        return self.root / "target-xcompile" / xcompile.target(self.arch)
 300
 301    def rewrite_builder_path_for_host(self, path: Path) -> Path:
 302        """Rewrite a path that is relative to the target directory inside the
 303        builder to a path that is relative to the target directory on the host.
 304
 305        If path does is not relative to the target directory inside the builder,
 306        it is returned unchanged.
 307        """
 308        builder_target_dir = Path("/mnt/build") / xcompile.target(self.arch)
 309        try:
 310            return self.cargo_target_dir() / path.relative_to(builder_target_dir)
 311        except ValueError:
 312            return path
 313
 314
 315@cache
 316def docker_images() -> set[str]:
 317    """List the Docker images available on the local machine."""
 318    return set(
 319        spawn.capture(["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"])
 320        .strip()
 321        .split("\n")
 322    )
 323
 324
 325KNOWN_DOCKER_IMAGES_FILE = Path(MZ_ROOT / "known-docker-images.txt")
 326_known_docker_images: set[str] | None = None
 327_known_docker_images_lock = Lock()
 328
 329
 330def is_docker_image_pushed(name: str) -> bool:
 331    """Check whether the named image is pushed to Docker Hub.
 332
 333    Note that this operation requires a rather slow network request.
 334    """
 335    global _known_docker_images
 336
 337    if _known_docker_images is None:
 338        with _known_docker_images_lock:
 339            if not KNOWN_DOCKER_IMAGES_FILE.exists():
 340                _known_docker_images = set()
 341            else:
 342                with KNOWN_DOCKER_IMAGES_FILE.open() as f:
 343                    _known_docker_images = set(line.strip() for line in f)
 344
 345    if name in _known_docker_images:
 346        return True
 347
 348    if ":" not in name:
 349        image, tag = name, "latest"
 350    else:
 351        image, tag = name.rsplit(":", 1)
 352
 353    dockerhub_username = os.getenv("DOCKERHUB_USERNAME")
 354    dockerhub_token = os.getenv("DOCKERHUB_ACCESS_TOKEN")
 355
 356    exists: bool = False
 357
 358    try:
 359        if dockerhub_username and dockerhub_token:
 360            response = requests.head(
 361                f"https://registry-1.docker.io/v2/{image}/manifests/{tag}",
 362                headers={
 363                    "Accept": "application/vnd.docker.distribution.manifest.v2+json",
 364                },
 365                auth=HTTPBasicAuth(dockerhub_username, dockerhub_token),
 366                timeout=10,
 367            )
 368        else:
 369            token = requests.get(
 370                "https://auth.docker.io/token",
 371                params={
 372                    "service": "registry.docker.io",
 373                    "scope": f"repository:{image}:pull",
 374                },
 375                timeout=10,
 376            ).json()["token"]
 377            response = requests.head(
 378                f"https://registry-1.docker.io/v2/{image}/manifests/{tag}",
 379                headers={
 380                    "Accept": "application/vnd.docker.distribution.manifest.v2+json",
 381                    "Authorization": f"Bearer {token}",
 382                },
 383                timeout=10,
 384            )
 385
 386        if response.status_code in (401, 429, 500, 502, 503, 504):
 387            # Fall back to 5x slower method
 388            proc = subprocess.run(
 389                ["docker", "manifest", "inspect", name],
 390                stdout=subprocess.DEVNULL,
 391                stderr=subprocess.DEVNULL,
 392                env=dict(os.environ, DOCKER_CLI_EXPERIMENTAL="enabled"),
 393            )
 394            exists = proc.returncode == 0
 395        else:
 396            exists = response.status_code == 200
 397
 398    except Exception as e:
 399        print(f"Error checking Docker image: {e}")
 400        return False
 401
 402    if exists:
 403        with _known_docker_images_lock:
 404            _known_docker_images.add(name)
 405            with KNOWN_DOCKER_IMAGES_FILE.open("a") as f:
 406                print(name, file=f)
 407
 408    return exists
 409
 410
 411def is_ghcr_image_pushed(name: str) -> bool:
 412    global _known_docker_images
 413
 414    if _known_docker_images is None:
 415        with _known_docker_images_lock:
 416            if not KNOWN_DOCKER_IMAGES_FILE.exists():
 417                _known_docker_images = set()
 418            else:
 419                with KNOWN_DOCKER_IMAGES_FILE.open() as f:
 420                    _known_docker_images = set(line.strip() for line in f)
 421
 422    name_without_ghcr = name.removeprefix("ghcr.io/")
 423    if name in _known_docker_images:
 424        return True
 425
 426    if ":" not in name_without_ghcr:
 427        image, tag = name_without_ghcr, "latest"
 428    else:
 429        image, tag = name_without_ghcr.rsplit(":", 1)
 430
 431    exists: bool = False
 432
 433    try:
 434        token = requests.get(
 435            "https://ghcr.io/token",
 436            params={
 437                "scope": f"repository:{image}:pull",
 438            },
 439            timeout=10,
 440        ).json()["token"]
 441        response = requests.head(
 442            f"https://ghcr.io/v2/{image}/manifests/{tag}",
 443            headers={"Authorization": f"Bearer {token}"},
 444            timeout=10,
 445        )
 446
 447        if response.status_code in (401, 429, 500, 502, 503, 504):
 448            # Fall back to 5x slower method
 449            proc = subprocess.run(
 450                ["docker", "manifest", "inspect", name],
 451                stdout=subprocess.DEVNULL,
 452                stderr=subprocess.DEVNULL,
 453                env=dict(os.environ, DOCKER_CLI_EXPERIMENTAL="enabled"),
 454            )
 455            exists = proc.returncode == 0
 456        else:
 457            exists = response.status_code == 200
 458
 459    except Exception as e:
 460        print(f"Error checking Docker image: {e}")
 461        return False
 462
 463    if exists:
 464        with _known_docker_images_lock:
 465            _known_docker_images.add(name)
 466            with KNOWN_DOCKER_IMAGES_FILE.open("a") as f:
 467                print(name, file=f)
 468
 469    return exists
 470
 471
 472# Registry HTTP statuses that indicate a transient problem rather than a
 473# definitive answer about visibility, so the public check retries instead of
 474# concluding the image is private.
 475_TRANSIENT_REGISTRY_STATUSES = frozenset({429, 500, 502, 503, 504})
 476
 477
 478def _get_with_retries(url: str, **kwargs: Any) -> requests.Response | None:
 479    """GET `url`, retrying transient failures; returns None if all retries fail."""
 480    for sleep_time in [2, 5, 10, None]:
 481        try:
 482            response = requests.get(url, timeout=10, **kwargs)
 483        except requests.RequestException as e:
 484            if sleep_time is None:
 485                print(f"Error requesting {url}: {e}")
 486                return None
 487        else:
 488            if response.status_code not in _TRANSIENT_REGISTRY_STATUSES:
 489                return response
 490        if sleep_time is not None:
 491            time.sleep(sleep_time)
 492    return None
 493
 494
 495# These intentionally do *not* share code with `is_*_image_pushed`: those check
 496# existence, authenticate when possible, and cache hits in `known-docker-images`.
 497# These check *public visibility*, so they must stay anonymous (no auth
 498# fallback) and uncached. They return a tri-state so callers can tell a private
 499# repo (actionable) apart from a registry blip (retry the build), see
 500# `_get_with_retries` returning None:
 501#   True  -> definitively public
 502#   False -> definitively not public (private, or repo does not exist)
 503#   None  -> could not determine (transient registry/network error)
 504
 505
 506def _json_dict_or_none(response: requests.Response) -> dict[str, Any] | None:
 507    """Parse `response` as a JSON object, or None if the body isn't one.
 508
 509    A malformed body must read as "couldn't determine" (None), not crash the
 510    caller out of the tri-state handling and fail the whole build.
 511    """
 512    try:
 513        body = response.json()
 514    except ValueError:
 515        return None
 516    return body if isinstance(body, dict) else None
 517
 518
 519def is_docker_image_public(name: str) -> bool | None:
 520    """Whether the Docker Hub repository for `name` is public (tri-state).
 521
 522    Reads repository metadata (`is_private`) via the Hub API rather than the
 523    registry, which both avoids the registry's anonymous pull-rate limit (see
 524    `mz_image_tag_exists`) and is tag-independent. A 404 means the repo is
 525    private or absent; transient errors yield None rather than a false "private".
 526    """
 527    repo = name.rsplit(":", 1)[0]
 528    response = _get_with_retries(f"https://hub.docker.com/v2/repositories/{repo}/")
 529    if response is None:
 530        return None
 531    if response.status_code == 404:
 532        return False
 533    if response.status_code != 200:
 534        return None
 535    body = _json_dict_or_none(response)
 536    return None if body is None else not body.get("is_private", True)
 537
 538
 539def is_ghcr_image_public(name: str) -> bool | None:
 540    """Whether the GHCR repository for `name` is public (tri-state).
 541
 542    Requests an *anonymous* pull token and lists tags: a public repo authorizes
 543    the anonymous client (200), a private or missing one rejects it (401/403/404).
 544    Like the Docker Hub check, this is tag-independent.
 545    """
 546    image = name.removeprefix("ghcr.io/").rsplit(":", 1)[0]
 547    token_response = _get_with_retries(
 548        "https://ghcr.io/token", params={"scope": f"repository:{image}:pull"}
 549    )
 550    if token_response is None:
 551        return None
 552    if token_response.status_code in (401, 403):
 553        return False
 554    if token_response.status_code != 200:
 555        return None
 556    body = _json_dict_or_none(token_response)
 557    if body is None or "token" not in body:
 558        return None
 559    token = body["token"]
 560    response = _get_with_retries(
 561        f"https://ghcr.io/v2/{image}/tags/list",
 562        params={"n": 1},
 563        headers={"Authorization": f"Bearer {token}"},
 564    )
 565    if response is None:
 566        return None
 567    if response.status_code == 200:
 568        return True
 569    if response.status_code in (401, 403, 404):
 570        return False
 571    return None
 572
 573
 574def chmod_x(path: Path) -> None:
 575    """Set the executable bit on a file or directory."""
 576    # https://stackoverflow.com/a/30463972/1122351
 577    mode = os.stat(path).st_mode
 578    mode |= (mode & 0o444) >> 2  # copy R bits to X
 579    os.chmod(path, mode)
 580
 581
 582class PreImage:
 583    """An action to run before building a Docker image.
 584
 585    Args:
 586        rd: The `RepositoryDetails` for the repository.
 587        path: The path to the `Image` associated with this action.
 588    """
 589
 590    def __init__(self, rd: RepositoryDetails, path: Path):
 591        self.rd = rd
 592        self.path = path
 593
 594    @classmethod
 595    def prepare_batch(cls, instances: list["PreImage"]) -> Any:
 596        """Prepare a batch of actions.
 597
 598        This is useful for `PreImage` actions that are more efficient when
 599        their actions are applied to several images in bulk.
 600
 601        Returns an arbitrary output that is passed to `PreImage.run`.
 602        """
 603        pass
 604
 605    def run(self, prep: Any) -> None:
 606        """Perform the action.
 607
 608        Args:
 609            prep: Any prep work returned by `prepare_batch`.
 610        """
 611        pass
 612
 613    def inputs(self) -> set[str]:
 614        """Return the files which are considered inputs to the action."""
 615        raise NotImplementedError
 616
 617    def extra(self) -> str:
 618        """Returns additional data for incorporation in the fingerprint."""
 619        return ""
 620
 621
 622class Copy(PreImage):
 623    """A `PreImage` action which copies files from a directory.
 624
 625    See doc/developer/mzbuild.md for an explanation of the user-facing
 626    parameters.
 627    """
 628
 629    def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
 630        super().__init__(rd, path)
 631
 632        self.source = config.pop("source", None)
 633        if self.source is None:
 634            raise ValueError("mzbuild config is missing 'source' argument")
 635
 636        self.destination = config.pop("destination", None)
 637        if self.destination is None:
 638            raise ValueError("mzbuild config is missing 'destination' argument")
 639
 640        self.matching = config.pop("matching", "*")
 641
 642    def run(self, prep: Any) -> None:
 643        super().run(prep)
 644        for src in self._source_files():
 645            dst = self.path / self.destination / src
 646            dst.parent.mkdir(parents=True, exist_ok=True)
 647            shutil.copy(self.rd.root / self.source / src, dst)
 648
 649    def _source_files(self) -> set[str]:
 650        """The files to copy, relative to `source`."""
 651        return set(git.expand_globs(self.rd.root / self.source, self.matching))
 652
 653    def inputs(self) -> set[str]:
 654        return {str(Path(self.source) / src) for src in self._source_files()}
 655
 656
 657class CargoPreImage(PreImage):
 658    """A `PreImage` action that uses Cargo."""
 659
 660    @staticmethod
 661    @cache
 662    def _cargo_shared_inputs() -> frozenset[str]:
 663        """Resolve shared Cargo inputs once and cache the result.
 664
 665        This expands the 'ci/builder' directory glob and filters out
 666        non-existent files like '.cargo/config', avoiding repeated
 667        git subprocess calls in fingerprint().
 668        """
 669        inputs: set[str] = set()
 670        inputs |= git.expand_globs(Path("."), "ci/builder/**")
 671        inputs.add("Cargo.toml")
 672        inputs.add("Cargo.lock")
 673        if Path(".cargo/config").exists():
 674            inputs.add(".cargo/config")
 675        return frozenset(inputs)
 676
 677    def inputs(self) -> set[str]:
 678        return set(CargoPreImage._cargo_shared_inputs())
 679
 680    def extra(self) -> str:
 681        # Cargo images depend on the release mode and whether
 682        # coverage/sanitizer is enabled.
 683        flags: list[str] = []
 684        if self.rd.profile == Profile.RELEASE:
 685            flags += "release"
 686        if self.rd.profile == Profile.OPTIMIZED:
 687            flags += "optimized"
 688        if self.rd.coverage:
 689            flags += "coverage"
 690        if self.rd.sanitizer != Sanitizer.none:
 691            flags += self.rd.sanitizer.value
 692        flags.sort()
 693        return ",".join(flags)
 694
 695
 696class CargoBuild(CargoPreImage):
 697    """A `PreImage` action that builds a single binary with Cargo.
 698
 699    See doc/developer/mzbuild.md for an explanation of the user-facing
 700    parameters.
 701    """
 702
 703    def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
 704        super().__init__(rd, path)
 705        bin = config.pop("bin", [])
 706        self.bins = bin if isinstance(bin, list) else [bin]
 707        example = config.pop("example", [])
 708        self.examples = example if isinstance(example, list) else [example]
 709        self.strip = config.pop("strip", True)
 710        self.extract = config.pop("extract", {})
 711        self.builder_files = config.pop("builder-files", {})
 712        features = config.pop("features", [])
 713        self.features = features if isinstance(features, list) else [features]
 714
 715        if len(self.bins) == 0 and len(self.examples) == 0:
 716            raise ValueError("mzbuild config is missing pre-build target")
 717
 718    @staticmethod
 719    def generate_cargo_build_command(
 720        rd: RepositoryDetails,
 721        bins: list[str],
 722        examples: list[str],
 723        features: list[str] | None = None,
 724    ) -> list[str]:
 725        rustflags = (
 726            rustc_flags.coverage
 727            if rd.coverage
 728            else (
 729                rustc_flags.sanitizer[rd.sanitizer]
 730                if rd.sanitizer != Sanitizer.none
 731                else ["--cfg=tokio_unstable"]
 732            )
 733        )
 734        cflags = (
 735            [
 736                f"--target={target(rd.arch)}",
 737                "-fuse-ld=lld",
 738            ]
 739            + rustc_flags.sanitizer_cflags[rd.sanitizer]
 740            if rd.sanitizer != Sanitizer.none
 741            else []
 742        )
 743        extra_env = (
 744            {
 745                "CFLAGS": " ".join(cflags),
 746                "CXXFLAGS": " ".join(cflags),
 747                "LDFLAGS": " ".join(cflags),
 748                "CXXSTDLIB": "stdc++",
 749                "CC": "cc",
 750                "CXX": "c++",
 751                "CPP": "clang-cpp-19",
 752                "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER": "cc",
 753                "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER": "cc",
 754                "PATH": "/sanshim:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
 755                "TSAN_OPTIONS": "report_bugs=0",  # build-scripts fail
 756            }
 757            if rd.sanitizer != Sanitizer.none
 758            else {}
 759        )
 760
 761        # clang/lld `-22` suffixes must match the LLVM version of the rustc in
 762        # rust-version (root Cargo.toml) and the apt.llvm.org release in
 763        # ci/builder/Dockerfile.
 764        if (
 765            rd.profile == Profile.RELEASE
 766            and rd.sanitizer == Sanitizer.none
 767            and not rd.coverage
 768        ):
 769            rustflags += [
 770                "-Clinker-plugin-lto",
 771            ]
 772            extra_env = {
 773                "CC": "clang-22",
 774                "CXX": "clang++-22",
 775                "AR": "llvm-ar-22",
 776                "RANLIB": "llvm-ranlib-22",
 777                "CFLAGS": "-flto=thin",
 778                "CXXFLAGS": "-flto=thin",
 779                # `-static-libstdc++` is unused when clang links a C program,
 780                # and jemalloc's configure runs its `strerror_r` link checks
 781                # with `-Werror`. Without `-Wno-unused-command-line-argument`
 782                # both checks fail and configure aborts with "cannot determine
 783                # return type of strerror_r".
 784                "LDFLAGS": "--ld-path=/usr/bin/ld.lld-22 -static-libstdc++ -Wno-unused-command-line-argument",
 785                "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER": "/usr/local/bin/clang-lld-22",
 786                "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER": "/usr/local/bin/clang-lld-22",
 787            }
 788
 789        cargo_build = rd.build(
 790            "build", channel=None, rustflags=rustflags, extra_env=extra_env
 791        )
 792
 793        packages = set()
 794        for bin in bins:
 795            cargo_build.extend(["--bin", bin])
 796            packages.add(rd.cargo_workspace.crate_for_bin(bin).name)
 797        for example in examples:
 798            cargo_build.extend(["--example", example])
 799            packages.add(rd.cargo_workspace.crate_for_example(example).name)
 800        cargo_build.extend(f"--package={p}" for p in packages)
 801
 802        if rd.profile == Profile.RELEASE:
 803            cargo_build.append("--release")
 804        if rd.profile == Profile.OPTIMIZED:
 805            cargo_build.extend(["--profile", "optimized"])
 806        if rd.sanitizer != Sanitizer.none:
 807            # ASan doesn't work with jemalloc
 808            cargo_build.append("--no-default-features")
 809            # Uses more memory, so reduce the number of jobs
 810            cargo_build.extend(
 811                ["--jobs", str(round(multiprocessing.cpu_count() * 2 / 3))]
 812            )
 813        if features:
 814            cargo_build.append(f"--features={','.join(features)}")
 815
 816        return cargo_build
 817
 818    @classmethod
 819    def prepare_batch(cls, instances: list["PreImage"]) -> dict[str, Any]:
 820        super().prepare_batch(instances)
 821
 822        if not instances:
 823            return {}
 824
 825        # Building all binaries and examples in the same `cargo build` command
 826        # allows Cargo to link in parallel with other work, which can
 827        # meaningfully speed up builds.
 828
 829        rd: RepositoryDetails | None = None
 830        builds = cast(list[CargoBuild], instances)
 831        bins = set()
 832        examples = set()
 833        features = set()
 834        for build in builds:
 835            if not rd:
 836                rd = build.rd
 837            bins.update(build.bins)
 838            examples.update(build.examples)
 839            features.update(build.features)
 840        assert rd
 841
 842        ui.section(f"Common build for: {', '.join(bins | examples)}")
 843
 844        cargo_build = cls.generate_cargo_build_command(
 845            rd, list(bins), list(examples), list(features) if features else None
 846        )
 847
 848        run_and_detect_retryable_build_failure(cargo_build, cwd=rd.root)
 849
 850        # Re-run with JSON-formatted messages and capture the output so we can
 851        # later analyze the build artifacts in `run`. This should be nearly
 852        # instantaneous since we just compiled above with the same crates and
 853        # features. (We don't want to do the compile above with JSON-formatted
 854        # messages because it wouldn't be human readable.)
 855        json_output = spawn.capture(
 856            cargo_build + ["--message-format=json"],
 857            cwd=rd.root,
 858        )
 859        prep = {"cargo": json_output}
 860
 861        return prep
 862
 863    def build(self, build_output: dict[str, Any]) -> None:
 864        cargo_profile = (
 865            "release"
 866            if self.rd.profile == Profile.RELEASE
 867            else "optimized" if self.rd.profile == Profile.OPTIMIZED else "debug"
 868        )
 869
 870        def copy(src: Path, relative_dst: Path) -> None:
 871            exe_path = self.path / relative_dst
 872            exe_path.parent.mkdir(parents=True, exist_ok=True)
 873            shutil.copy(src, exe_path)
 874
 875            if self.strip:
 876                # The debug information is large enough that it slows down CI,
 877                # since we're packaging these binaries up into Docker images and
 878                # shipping them around.
 879                spawn.runv(
 880                    [*self.rd.tool("strip"), "--strip-debug", exe_path],
 881                    cwd=self.rd.root,
 882                )
 883            else:
 884                # Even if we've been asked not to strip the binary, remove the
 885                # `.debug_pubnames` and `.debug_pubtypes` sections. These are just
 886                # indexes that speed up launching a debugger against the binary,
 887                # and we're happy to have slower debugger start up in exchange for
 888                # smaller binaries. Plus the sections have been obsoleted by a
 889                # `.debug_names` section in DWARF 5, and so debugger support for
 890                # `.debug_pubnames`/`.debug_pubtypes` is minimal anyway.
 891                # See: https://github.com/rust-lang/rust/issues/46034
 892                spawn.runv(
 893                    [
 894                        *self.rd.tool("objcopy"),
 895                        "-R",
 896                        ".debug_pubnames",
 897                        "-R",
 898                        ".debug_pubtypes",
 899                        exe_path,
 900                    ],
 901                    cwd=self.rd.root,
 902                )
 903
 904        for bin in self.bins:
 905            src_path = self.rd.cargo_target_dir() / cargo_profile / bin
 906            copy(src_path, bin)
 907        for example in self.examples:
 908            src_path = (
 909                self.rd.cargo_target_dir() / cargo_profile / Path("examples") / example
 910            )
 911            copy(src_path, Path("examples") / example)
 912
 913        for src, dst in self.builder_files.items():
 914            dst_path = self.path / dst
 915            dst_path.parent.mkdir(parents=True, exist_ok=True)
 916            spawn.runv(
 917                self.rd.builder(["cp", src, str(dst_path.relative_to(self.rd.root))]),
 918                cwd=self.rd.root,
 919            )
 920
 921        if self.extract:
 922            cargo_build_json_output = build_output["cargo"]
 923
 924            target_dir = self.rd.cargo_target_dir()
 925            for line in cargo_build_json_output.split("\n"):
 926                if line.strip() == "" or not line.startswith("{"):
 927                    continue
 928                message = json.loads(line)
 929                if message["reason"] != "build-script-executed":
 930                    continue
 931                out_dir = self.rd.rewrite_builder_path_for_host(
 932                    Path(message["out_dir"])
 933                )
 934                if not out_dir.is_relative_to(target_dir):
 935                    # Some crates are built for both the host and the target.
 936                    # Ignore the built-for-host out dir.
 937                    continue
 938                # parse the package name from a package_id that looks like one of:
 939                # git+https://github.com/MaterializeInc/rust-server-sdk#launchdarkly-server-sdk@1.0.0
 940                # path+file:///Users/roshan/materialize/src/catalog#mz-catalog@0.0.0
 941                # registry+https://github.com/rust-lang/crates.io-index#num-rational@0.4.0
 942                # file:///path/to/my-package#0.1.0
 943                package_id = message["package_id"]
 944                if "@" in package_id:
 945                    package = package_id.split("@")[0].split("#")[-1]
 946                else:
 947                    package = message["package_id"].split("#")[0].split("/")[-1]
 948                for src, dst in self.extract.get(package, {}).items():
 949                    spawn.runv(["cp", "-R", out_dir / src, self.path / dst])
 950
 951        self.acquired = True
 952
 953    def run(self, prep: dict[str, Any]) -> None:
 954        super().run(prep)
 955        self.build(prep)
 956
 957    @cache
 958    def inputs(self) -> set[str]:
 959        deps = set()
 960
 961        for bin in self.bins:
 962            crate = self.rd.cargo_workspace.crate_for_bin(bin)
 963            deps |= self.rd.cargo_workspace.transitive_path_dependencies(crate)
 964        for example in self.examples:
 965            crate = self.rd.cargo_workspace.crate_for_example(example)
 966            deps |= self.rd.cargo_workspace.transitive_path_dependencies(
 967                crate, dev=True
 968            )
 969
 970        inputs = super().inputs() | set(inp for dep in deps for inp in dep.inputs())
 971        return inputs
 972
 973
 974class Image:
 975    """A Docker image whose build and dependencies are managed by mzbuild.
 976
 977    An image corresponds to a directory in a repository that contains a
 978    `mzbuild.yml` file. This directory is called an "mzbuild context."
 979
 980    Attributes:
 981        name: The name of the image.
 982        publish: Whether the image should be pushed to Docker Hub.
 983        depends_on: The names of the images upon which this image depends.
 984        root: The path to the root of the associated `Repository`.
 985        path: The path to the directory containing the `mzbuild.yml`
 986            configuration file.
 987        pre_images: Optional actions to perform before running `docker build`.
 988        build_args: An optional list of --build-arg to pass to the dockerfile
 989    """
 990
 991    _DOCKERFILE_MZFROM_RE = re.compile(rb"^MZFROM\s*(\S+)")
 992
 993    _context_files_cache: set[str] | None
 994
 995    def __init__(self, rd: RepositoryDetails, path: Path):
 996        self.rd = rd
 997        self.path = path
 998        self._context_files_cache = None
 999        self.pre_images: list[PreImage] = []
1000        with open(self.path / "mzbuild.yml") as f:
1001            data = yaml.safe_load(f)
1002            self.name: str = data.pop("name")
1003            self.publish: bool = data.pop("publish", True)
1004            self.description: str | None = data.pop("description", None)
1005            self.mainline: bool = data.pop("mainline", True)
1006            for pre_image in data.pop("pre-image", []):
1007                typ = pre_image.pop("type", None)
1008                if typ == "cargo-build":
1009                    self.pre_images.append(CargoBuild(self.rd, self.path, pre_image))
1010                elif typ == "copy":
1011                    self.pre_images.append(Copy(self.rd, self.path, pre_image))
1012                else:
1013                    raise ValueError(
1014                        f"mzbuild config in {self.path} has unknown pre-image type"
1015                    )
1016            self.build_args = data.pop("build-args", {})
1017
1018        if re.search(r"[^A-Za-z0-9\-]", self.name):
1019            raise ValueError(
1020                f"mzbuild image name {self.name} contains invalid character; only alphanumerics and hyphens allowed"
1021            )
1022
1023        self.depends_on: list[str] = []
1024        with open(self.path / "Dockerfile", "rb") as f:
1025            for line in f:
1026                match = self._DOCKERFILE_MZFROM_RE.match(line)
1027                if match:
1028                    self.depends_on.append(match.group(1).decode())
1029
1030    def sync_description(self) -> None:
1031        """Sync the description to Docker Hub if the image is publishable
1032        and a README.md file exists."""
1033
1034        if not self.publish:
1035            ui.say(f"{self.name} is not publishable")
1036            return
1037
1038        readme_path = self.path / "README.md"
1039        has_readme = readme_path.exists()
1040        if not has_readme:
1041            ui.say(f"{self.name} has no README.md or description")
1042            return
1043
1044        docker_config = os.getenv("DOCKER_CONFIG")
1045        spawn.runv(
1046            [
1047                "docker",
1048                "pushrm",
1049                f"--file={readme_path}",
1050                *([f"--config={docker_config}/config.json"] if docker_config else []),
1051                *([f"--short={self.description}"] if self.description else []),
1052                self.docker_name(),
1053            ]
1054        )
1055
1056    def docker_name(self, tag: str | None = None) -> str:
1057        """Return the name of the image on Docker Hub at the given tag."""
1058        name = f"{self.rd.image_registry}/{self.rd.image_prefix}{self.name}"
1059        if tag:
1060            name += f":{tag}"
1061        return name
1062
1063
1064class ResolvedImage:
1065    """An `Image` whose dependencies have been resolved.
1066
1067    Attributes:
1068        image: The underlying `Image`.
1069        acquired: Whether the image is available locally.
1070        dependencies: A mapping from dependency name to `ResolvedImage` for
1071            each of the images that `image` depends upon.
1072    """
1073
1074    def __init__(self, image: Image, dependencies: Iterable["ResolvedImage"]):
1075        self.image = image
1076        self.acquired = False
1077        self.dependencies = {}
1078        for d in dependencies:
1079            self.dependencies[d.name] = d
1080
1081    def __repr__(self) -> str:
1082        return f"ResolvedImage<{self.spec()}>"
1083
1084    @property
1085    def name(self) -> str:
1086        """The name of the underlying image."""
1087        return self.image.name
1088
1089    @property
1090    def publish(self) -> bool:
1091        """Whether the underlying image should be pushed to Docker Hub."""
1092        return self.image.publish
1093
1094    @cache
1095    def spec(self) -> str:
1096        """Return the "spec" for the image.
1097
1098        A spec is the unique identifier for the image given its current
1099        fingerprint. It is a valid Docker Hub name.
1100        """
1101        return self.image.docker_name(tag=f"mzbuild-{self.fingerprint()}")
1102
1103    def write_dockerfile(self) -> IO[bytes]:
1104        """Render the Dockerfile without mzbuild directives.
1105
1106        Returns:
1107            file: A handle to a temporary file containing the adjusted
1108                Dockerfile."""
1109        with open(self.image.path / "Dockerfile", "rb") as f:
1110            lines = f.readlines()
1111        f = TemporaryFile()
1112        for line in lines:
1113            match = Image._DOCKERFILE_MZFROM_RE.match(line)
1114            if match:
1115                image = match.group(1).decode()
1116                spec = self.dependencies[image].spec()
1117                line = Image._DOCKERFILE_MZFROM_RE.sub(b"FROM %b" % spec.encode(), line)
1118            f.write(line)
1119        f.seek(0)
1120        return f
1121
1122    def build(self, prep: dict[type[PreImage], Any], push: bool = False) -> None:
1123        """Build the image from source.
1124
1125        Requires that the caller has already acquired all dependencies and
1126        prepared all `PreImage` actions via `PreImage.prepare_batch`.
1127        """
1128        # Use a file lock to prevent parallel mzcompose processes from
1129        # racing on git clean / copy / strip for the same image directory.
1130        lock_dir = self.image.rd.root / "target" / "mzbuild-locks"
1131        lock_dir.mkdir(parents=True, exist_ok=True)
1132        profile = self.image.rd.profile.name.lower()
1133        lock_path = lock_dir / f"{self.image.name}-{profile}.lock"
1134        with open(lock_path, "w") as lock_file:
1135            ui.say(f"Acquiring lock for {self.spec()}")
1136            fcntl.flock(lock_file, fcntl.LOCK_EX)
1137            try:
1138                self._build_locked(prep, push)
1139            finally:
1140                fcntl.flock(lock_file, fcntl.LOCK_UN)
1141        self.acquired = True
1142        docker_images().add(self.spec())
1143
1144    def _build_locked(
1145        self, prep: dict[type[PreImage], Any], push: bool = False
1146    ) -> None:
1147        ui.section(f"Building {self.spec()}")
1148        spawn.runv(["git", "clean", "-ffdX", self.image.path])
1149
1150        for pre_image in self.image.pre_images:
1151            pre_image.run(prep[type(pre_image)])
1152        build_args = {
1153            **self.image.build_args,
1154            "BUILD_PROFILE": self.image.rd.profile.name,
1155            "ARCH_GCC": str(self.image.rd.arch),
1156            "ARCH_GO": self.image.rd.arch.go_str(),
1157            "CI_SANITIZER": str(self.image.rd.sanitizer),
1158        }
1159        f = self.write_dockerfile()
1160
1161        try:
1162            spawn.capture(["docker", "buildx", "version"])
1163        except subprocess.CalledProcessError:
1164            if push:
1165                print(
1166                    "docker buildx not found, required to push images. Installation: https://github.com/docker/buildx?tab=readme-ov-file#installing"
1167                )
1168                raise
1169            print(
1170                "docker buildx not found, you can install it to build faster. Installation: https://github.com/docker/buildx?tab=readme-ov-file#installing"
1171            )
1172            print("Falling back to docker build")
1173            cmd: Sequence[str] = [
1174                "docker",
1175                "build",
1176                "-f",
1177                "-",
1178                *(f"--build-arg={k}={v}" for k, v in build_args.items()),
1179                "-t",
1180                self.spec(),
1181                f"--platform=linux/{self.image.rd.arch.go_str()}",
1182                str(self.image.path),
1183            ]
1184        else:
1185            # `self.spec()` may already be ghcr-qualified (MZ_GHCR), so strip the
1186            # prefix before re-deriving each tag. Otherwise they double-prefix and
1187            # a dependent image's `FROM self.spec()` can't resolve the local build.
1188            spec = self.spec()
1189            if spec.startswith(GHCR_PREFIX):
1190                spec = spec.removeprefix(GHCR_PREFIX)
1191            docker_tag = f"docker.io/{spec}"
1192            ghcr_tag = f"{GHCR_PREFIX}{spec}"
1193            cmd: Sequence[str] = [
1194                "docker",
1195                "buildx",
1196                "build",
1197                "--progress=plain",  # less noisy
1198                "-f",
1199                "-",
1200                *(f"--build-arg={k}={v}" for k, v in build_args.items()),
1201                "-t",
1202                docker_tag,
1203                "-t",
1204                ghcr_tag,
1205                f"--platform=linux/{self.image.rd.arch.go_str()}",
1206                str(self.image.path),
1207                "--load",
1208            ]
1209
1210        if token := os.getenv("GITHUB_GHCR_TOKEN"):
1211            spawn.runv(
1212                [
1213                    "docker",
1214                    "login",
1215                    "ghcr.io",
1216                    "-u",
1217                    "materialize-bot",
1218                    "--password-stdin",
1219                ],
1220                stdin=token.encode(),
1221            )
1222
1223        spawn.runv(cmd, stdin=f, stdout=sys.stderr.buffer)
1224
1225        if push:
1226            # Push to both registries in parallel. With the docker driver,
1227            # the image is already in the local daemon after --load, so
1228            # docker push is the same mechanism buildx --push uses internally.
1229            pending = [docker_tag, ghcr_tag]
1230            for sleep_time in [5, 10, 20, 40, 60, None]:
1231                procs = [
1232                    subprocess.Popen(
1233                        ["docker", "push", tag],
1234                        stdout=sys.stderr,
1235                        stderr=sys.stderr,
1236                    )
1237                    for tag in pending
1238                ]
1239                pending = [tag for tag, proc in zip(pending, procs) if proc.wait() != 0]
1240                if not pending:
1241                    break
1242                if sleep_time is None:
1243                    raise subprocess.CalledProcessError(
1244                        1, ["docker", "push", pending[0]]
1245                    )
1246                print(f"docker push failed for {pending}, retrying in {sleep_time}s")
1247                time.sleep(sleep_time)
1248
1249    def try_pull(self, max_retries: int) -> bool:
1250        """Download the image if it does not exist locally. Returns whether it was found."""
1251        command = ["docker", "pull"]
1252        # --quiet skips printing the progress bar, which does not display well in CI.
1253        if ui.env_is_truthy("CI"):
1254            command.append("--quiet")
1255        command.append(self.spec())
1256        if not self.acquired:
1257            ui.header(f"Acquiring {self.spec()}")
1258            sleep_time = 1
1259            for retry in range(1, max_retries + 1):
1260                try:
1261                    spawn.runv(
1262                        command,
1263                        stdin=subprocess.DEVNULL,
1264                        stdout=sys.stderr.buffer,
1265                    )
1266                    self.acquired = True
1267                    docker_images().add(self.spec())
1268                    break
1269                except subprocess.CalledProcessError:
1270                    if retry < max_retries:
1271                        # There seems to be no good way to tell what error
1272                        # happened based on error code
1273                        # (https://github.com/docker/cli/issues/538) and we
1274                        # want to print output directly to terminal.
1275                        print(f"Retrying in {sleep_time}s ...")
1276                        time.sleep(sleep_time)
1277                        sleep_time = min(sleep_time * 2, 10)
1278                        continue
1279                    else:
1280                        break
1281        return self.acquired
1282
1283    def is_published_if_necessary(self) -> bool:
1284        """Report whether the image exists on DockerHub & GHCR if it is publishable."""
1285        if not self.publish:
1286            return False
1287        spec = self.spec()
1288        if spec.startswith(GHCR_PREFIX):
1289            spec = spec.removeprefix(GHCR_PREFIX)
1290        ghcr_spec = f"{GHCR_PREFIX}{spec}"
1291        if is_docker_image_pushed(spec) and is_ghcr_image_pushed(ghcr_spec):
1292            ui.say(f"{spec} already exists")
1293            return True
1294        return False
1295
1296    def is_public(self) -> tuple[bool | None, bool | None]:
1297        """Report whether the image's repo is public on (Docker Hub, GHCR).
1298
1299        Each element is True (public), False (private/absent), or None (could
1300        not determine). Non-publishable images are reported as public on both,
1301        since they are never pushed and so the check does not apply to them.
1302        """
1303        if not self.publish:
1304            return (True, True)
1305        spec = self.spec()
1306        if spec.startswith(GHCR_PREFIX):
1307            spec = spec.removeprefix(GHCR_PREFIX)
1308        ghcr_spec = f"{GHCR_PREFIX}{spec}"
1309        return (is_docker_image_public(spec), is_ghcr_image_public(ghcr_spec))
1310
1311    def run(
1312        self,
1313        args: list[str] = [],
1314        docker_args: list[str] = [],
1315        env: dict[str, str] = {},
1316    ) -> None:
1317        """Run a command in the image.
1318
1319        Creates a container from the image and runs the command described by
1320        `args` in the image.
1321        """
1322        envs = []
1323        for key, val in env.items():
1324            envs.extend(["--env", f"{key}={val}"])
1325        spawn.runv(
1326            [
1327                "docker",
1328                "run",
1329                "--tty",
1330                "--rm",
1331                *envs,
1332                "--init",
1333                *docker_args,
1334                self.spec(),
1335                *args,
1336            ],
1337        )
1338
1339    def list_dependencies(self, transitive: bool = False) -> set[str]:
1340        out = set()
1341        for dep in self.dependencies.values():
1342            out.add(dep.name)
1343            if transitive:
1344                out |= dep.list_dependencies(transitive)
1345        return out
1346
1347    @cache
1348    def inputs(self, transitive: bool = False) -> set[str]:
1349        """List the files tracked as inputs to the image.
1350
1351        These files are used to compute the fingerprint for the image. See
1352        `ResolvedImage.fingerprint` for details.
1353
1354        Returns:
1355            inputs: A list of input files, relative to the root of the
1356                repository.
1357        """
1358        if self.image._context_files_cache is not None:
1359            paths = set(self.image._context_files_cache)
1360        else:
1361            paths = set(git.expand_globs(self.image.rd.root, f"{self.image.path}/**"))
1362        if not paths:
1363            # While we could find an `mzbuild.yml` file for this service, expland_globs didn't
1364            # return any files that matched this service. At the very least, the `mzbuild.yml`
1365            # file itself should have been returned. We have a bug if paths is empty.
1366            raise AssertionError(
1367                f"{self.image.name} mzbuild exists but its files are unknown to git"
1368            )
1369        for pre_image in self.image.pre_images:
1370            paths |= pre_image.inputs()
1371        if transitive:
1372            for dep in self.dependencies.values():
1373                paths |= dep.inputs(transitive)
1374        return paths
1375
1376    @cache
1377    def fingerprint(self) -> Fingerprint:
1378        """Fingerprint the inputs to the image.
1379
1380        Compute the fingerprint of the image. Changing the contents of any of
1381        the files or adding or removing files to the image will change the
1382        fingerprint, as will modifying the inputs to any of its dependencies.
1383
1384        The image considers all non-gitignored files in its mzbuild context to
1385        be inputs. If it has a pre-image action, that action may add additional
1386        inputs via `PreImage.inputs`.
1387        """
1388        self_hash = hashlib.sha1()
1389        # When inputs come from precomputed sources (crate and image context
1390        # batching + resolved CargoPreImage paths), they are already individual
1391        # file paths from git. Skip the expensive expand_globs subprocess calls.
1392        inputs = self.inputs()
1393        if self.image._context_files_cache is not None:
1394            resolved_inputs = sorted(inputs)
1395        else:
1396            resolved_inputs = sorted(set(git.expand_globs(self.image.rd.root, *inputs)))
1397        for rel_path in resolved_inputs:
1398            abs_path = self.image.rd.root / rel_path
1399            file_hash = hashlib.sha1()
1400            raw_file_mode = os.lstat(abs_path).st_mode
1401            # Compute a simplified file mode using the same rules as Git.
1402            # https://github.com/git/git/blob/3bab5d562/Documentation/git-fast-import.txt#L610-L616
1403            if stat.S_ISLNK(raw_file_mode):
1404                file_mode = 0o120000
1405            elif raw_file_mode & stat.S_IXUSR:
1406                file_mode = 0o100755
1407            else:
1408                file_mode = 0o100644
1409            with open(abs_path, "rb") as f:
1410                file_hash.update(f.read())
1411            self_hash.update(file_mode.to_bytes(2, byteorder="big"))
1412            self_hash.update(rel_path.encode())
1413            self_hash.update(file_hash.digest())
1414            self_hash.update(b"\0")
1415
1416        for pre_image in self.image.pre_images:
1417            self_hash.update(pre_image.extra().encode())
1418            self_hash.update(b"\0")
1419
1420        self_hash.update(f"profile={self.image.rd.profile}".encode())
1421        self_hash.update(f"arch={self.image.rd.arch}".encode())
1422        self_hash.update(f"coverage={self.image.rd.coverage}".encode())
1423        self_hash.update(f"sanitizer={self.image.rd.sanitizer}".encode())
1424        # This exists to make sure all hashes from before we had a GHCR mirror are invalidated, so that we rebuild when an image doesn't exist on GHCR yet
1425        self_hash.update(b"mirror=ghcr")
1426
1427        full_hash = hashlib.sha1()
1428        full_hash.update(self_hash.digest())
1429        for dep in sorted(self.dependencies.values(), key=lambda d: d.name):
1430            full_hash.update(dep.name.encode())
1431            full_hash.update(dep.fingerprint())
1432            full_hash.update(b"\0")
1433
1434        return Fingerprint(full_hash.digest())
1435
1436
1437class DependencySet:
1438    """A set of `ResolvedImage`s.
1439
1440    Iterating over a dependency set yields the contained images in an arbitrary
1441    order. Indexing a dependency set yields the image with the specified name.
1442    """
1443
1444    def __init__(self, dependencies: Iterable[Image]):
1445        """Construct a new `DependencySet`.
1446
1447        The provided `dependencies` must be topologically sorted.
1448        """
1449        self._dependencies: dict[str, ResolvedImage] = {}
1450        dependencies = list(dependencies)
1451        known_images = docker_images() if dependencies else set()
1452        for d in dependencies:
1453            image = ResolvedImage(
1454                image=d,
1455                dependencies=(self._dependencies[d0] for d0 in d.depends_on),
1456            )
1457            image.acquired = image.spec() in known_images
1458            self._dependencies[d.name] = image
1459
1460    def _prepare_batch(self, images: list[ResolvedImage]) -> dict[type[PreImage], Any]:
1461        pre_images = collections.defaultdict(list)
1462        for image in images:
1463            for pre_image in image.image.pre_images:
1464                pre_images[type(pre_image)].append(pre_image)
1465        pre_image_prep = {}
1466        for cls, instances in pre_images.items():
1467            pre_image = cast(PreImage, cls)
1468            pre_image_prep[cls] = pre_image.prepare_batch(instances)
1469        return pre_image_prep
1470
1471    def acquire(self, max_retries: int | None = None) -> None:
1472        """Download or build all of the images in the dependency set that do not
1473        already exist locally.
1474
1475        Args:
1476            max_retries: Number of retries on failure.
1477        """
1478
1479        # Only retry in CI runs since we struggle with flaky docker pulls there
1480        if not max_retries:
1481            max_retries = (
1482                5
1483                if ui.env_is_truthy("CI")
1484                and not ui.env_is_truthy("CI_ALLOW_LOCAL_BUILD")
1485                else 1
1486            )
1487        assert max_retries > 0
1488
1489        deps_to_check = [dep for dep in self if dep.publish]
1490        deps_to_build = [dep for dep in self if not dep.publish]
1491        if len(deps_to_check):
1492            with ThreadPoolExecutor(max_workers=len(deps_to_check)) as executor:
1493                futures = [
1494                    executor.submit(dep.try_pull, max_retries) for dep in deps_to_check
1495                ]
1496                for dep, future in zip(deps_to_check, futures):
1497                    try:
1498                        if not future.result():
1499                            deps_to_build.append(dep)
1500                    except Exception:
1501                        deps_to_build.append(dep)
1502
1503        # Don't attempt to build in CI, as our timeouts and small machines won't allow it anyway
1504        if ui.env_is_truthy("CI") and not ui.env_is_truthy("CI_ALLOW_LOCAL_BUILD"):
1505            expected_deps = [dep for dep in deps_to_build if dep.publish]
1506            if expected_deps:
1507                print(
1508                    f"+++ Expected builds to be available, the build probably failed, so not proceeding: {expected_deps}"
1509                )
1510                sys.exit(128)
1511
1512        prep = self._prepare_batch(deps_to_build)
1513        for dep in deps_to_build:
1514            dep.build(prep)
1515
1516    def ensure(self, pre_build: Callable[[list[ResolvedImage]], None] | None = None):
1517        """Ensure all publishable images in this dependency set exist on Docker
1518        Hub.
1519
1520        Images are pushed using their spec as their tag.
1521
1522        Args:
1523            pre_build: A callback to invoke with all dependency that are going
1524                       to be built locally, invoked after their cargo build is
1525                       done, but before the Docker images are build and
1526                       uploaded to DockerHub.
1527        """
1528        num_deps = len(list(self))
1529        if not num_deps:
1530            deps_to_build = []
1531        else:
1532            with ThreadPoolExecutor(max_workers=num_deps) as executor:
1533                futures = list(
1534                    executor.map(
1535                        lambda dep: (dep, not dep.is_published_if_necessary()), self
1536                    )
1537                )
1538
1539            deps_to_build = [dep for dep, should_build in futures if should_build]
1540
1541        prep = self._prepare_batch(deps_to_build)
1542        if pre_build:
1543            pre_build(deps_to_build)
1544        lock = Lock()
1545        built_deps: set[str] = set([dep.name for dep in self]) - set(
1546            [dep.name for dep in deps_to_build]
1547        )
1548
1549        def build_dep(dep):
1550            end_time = time.time() + 1200
1551            while True:
1552                if time.time() > end_time:
1553                    raise TimeoutError(
1554                        f"Timed out in {dep.name} waiting for {[dep2 for dep2 in dep.dependencies if dep2 not in built_deps]}"
1555                    )
1556                with lock:
1557                    if all(dep2 in built_deps for dep2 in dep.dependencies):
1558                        break
1559                time.sleep(0.01)
1560            for attempts_remaining in reversed(range(3)):
1561                try:
1562                    dep.build(prep, push=dep.publish)
1563                    with lock:
1564                        built_deps.add(dep.name)
1565                    break
1566                except Exception:
1567                    if not dep.publish or attempts_remaining == 0:
1568                        raise
1569
1570        if deps_to_build:
1571            with ThreadPoolExecutor(max_workers=len(deps_to_build)) as executor:
1572                futures = [executor.submit(build_dep, dep) for dep in deps_to_build]
1573                for future in as_completed(futures):
1574                    future.result()
1575
1576    def check(self) -> bool:
1577        """Check all publishable images in this dependency set exist on Docker
1578        Hub. Don't try to download or build them."""
1579        num_deps = len(list(self))
1580        if num_deps == 0:
1581            return True
1582        with ThreadPoolExecutor(max_workers=num_deps) as executor:
1583            results = list(
1584                executor.map(lambda dep: dep.is_published_if_necessary(), list(self))
1585            )
1586        return all(results)
1587
1588    def __iter__(self) -> Iterator[ResolvedImage]:
1589        return iter(self._dependencies.values())
1590
1591    def __getitem__(self, key: str) -> ResolvedImage:
1592        return self._dependencies[key]
1593
1594
1595class Repository:
1596    """A collection of mzbuild `Image`s.
1597
1598    Creating a repository will walk the filesystem beneath `root` to
1599    automatically discover all contained `Image`s.
1600
1601    Iterating over a repository yields the contained images in an arbitrary
1602    order.
1603
1604    Args:
1605        root: The path to the root of the repository.
1606        arch: The CPU architecture to build for.
1607        profile: What profile to build the repository in.
1608        coverage: Whether to enable code coverage instrumentation.
1609        sanitizer: Whether to a sanitizer (address, thread, leak, memory, none)
1610        image_registry: The Docker image registry to pull images from and push
1611            images to.
1612        image_prefix: A prefix to apply to all Docker image names.
1613
1614    Attributes:
1615        images: A mapping from image name to `Image` for all contained images.
1616        compose_dirs: The set of directories containing a `mzcompose.py` file.
1617    """
1618
1619    def __init__(
1620        self,
1621        root: Path,
1622        arch: Arch = Arch.host(),
1623        profile: Profile = (
1624            Profile.RELEASE if ui.env_is_truthy("CI_LTO") else Profile.OPTIMIZED
1625        ),
1626        coverage: bool = False,
1627        sanitizer: Sanitizer = Sanitizer.none,
1628        image_registry: str = image_registry(),
1629        image_prefix: str = "",
1630    ):
1631        self.rd = RepositoryDetails(
1632            root,
1633            arch,
1634            profile,
1635            coverage,
1636            sanitizer,
1637            image_registry,
1638            image_prefix,
1639        )
1640        self.images: dict[str, Image] = {}
1641        self.compositions: dict[str, Path] = {}
1642        for rel_path_s in sorted(
1643            git.expand_globs(self.root, "**/mzbuild.yml", "**/mzcompose.py")
1644        ):
1645            rel_path = Path(rel_path_s)
1646            if rel_path.parts[:2] == ("misc", "python"):
1647                continue
1648
1649            parent = self.root / rel_path.parent
1650            if rel_path.name == "mzbuild.yml":
1651                image = Image(self.rd, parent)
1652                if not image.name:
1653                    raise ValueError(f"config at {parent} missing name")
1654                if image.name in self.images:
1655                    raise ValueError(f"image {image.name} exists twice")
1656                self.images[image.name] = image
1657            elif rel_path.name == "mzcompose.py":
1658                name = parent.name
1659                if name in self.compositions:
1660                    raise ValueError(f"composition {name} exists twice")
1661                self.compositions[name] = parent
1662
1663        # Validate dependencies.
1664        for image in self.images.values():
1665            for d in image.depends_on:
1666                if d not in self.images:
1667                    raise ValueError(
1668                        f"image {image.name} depends on non-existent image {d}"
1669                    )
1670
1671    @staticmethod
1672    def install_arguments(parser: argparse.ArgumentParser) -> None:
1673        """Install options to configure a repository into an argparse parser.
1674
1675        This function installs the following options:
1676
1677          * The mutually-exclusive `--dev`/`--optimized`/`--release` options to control the
1678            `profile` repository attribute.
1679          * The `--coverage` boolean option to control the `coverage` repository
1680            attribute.
1681
1682        Use `Repository.from_arguments` to construct a repository from the
1683        parsed command-line arguments.
1684        """
1685        build_mode = parser.add_mutually_exclusive_group()
1686        build_mode.add_argument(
1687            "--dev",
1688            action="store_true",
1689            help="build Rust binaries with the dev profile",
1690        )
1691        build_mode.add_argument(
1692            "--release",
1693            action="store_true",
1694            help="build Rust binaries with the release profile (default)",
1695        )
1696        build_mode.add_argument(
1697            "--optimized",
1698            action="store_true",
1699            help="build Rust binaries with the optimized profile (optimizations, no LTO, no debug symbols)",
1700        )
1701        parser.add_argument(
1702            "--coverage",
1703            help="whether to enable code coverage compilation flags",
1704            default=ui.env_is_truthy("CI_COVERAGE_ENABLED"),
1705            action="store_true",
1706        )
1707        parser.add_argument(
1708            "--sanitizer",
1709            help="whether to enable a sanitizer",
1710            default=Sanitizer[os.getenv("CI_SANITIZER", "none")],
1711            type=Sanitizer,
1712            choices=Sanitizer,
1713        )
1714
1715        def _parse_arch(s: str) -> Arch:
1716            try:
1717                return Arch(s)
1718            except ValueError:
1719                valid = ", ".join(m.value for m in Arch)
1720                raise argparse.ArgumentTypeError(
1721                    f"invalid arch: {s!r} (choose from {valid})"
1722                )
1723
1724        parser.add_argument(
1725            "--arch",
1726            default=Arch.host(),
1727            help="the CPU architecture to build for",
1728            type=_parse_arch,
1729            metavar="{" + ",".join(m.value for m in Arch) + "}",
1730        )
1731        parser.add_argument(
1732            "--image-registry",
1733            default=image_registry(),
1734            help="the Docker image registry to pull images from and push images to",
1735        )
1736        parser.add_argument(
1737            "--image-prefix",
1738            default="",
1739            help="a prefix to apply to all Docker image names",
1740        )
1741
1742    @classmethod
1743    def from_arguments(cls, root: Path, args: argparse.Namespace) -> "Repository":
1744        """Construct a repository from command-line arguments.
1745
1746        The provided namespace must contain the options installed by
1747        `Repository.install_arguments`.
1748        """
1749        if args.release:
1750            profile = Profile.RELEASE
1751        elif args.optimized:
1752            profile = Profile.OPTIMIZED
1753        elif args.dev:
1754            profile = Profile.DEV
1755        else:
1756            profile = (
1757                Profile.RELEASE if ui.env_is_truthy("CI_LTO") else Profile.OPTIMIZED
1758            )
1759
1760        return cls(
1761            root,
1762            profile=profile,
1763            coverage=args.coverage,
1764            sanitizer=args.sanitizer,
1765            image_registry=args.image_registry,
1766            image_prefix=args.image_prefix,
1767            arch=args.arch,
1768        )
1769
1770    @property
1771    def root(self) -> Path:
1772        """The path to the root directory for the repository."""
1773        return self.rd.root
1774
1775    def resolve_dependencies(self, targets: Iterable[Image]) -> DependencySet:
1776        """Compute the dependency set necessary to build target images.
1777
1778        The dependencies of `targets` will be crawled recursively until the
1779        complete set of transitive dependencies is determined or a circular
1780        dependency is discovered. The returned dependency set will be sorted
1781        in topological order.
1782
1783        Raises:
1784           ValueError: A circular dependency was discovered in the images
1785               in the repository.
1786        """
1787        # Pre-fetch all crate input files in a single batched git call,
1788        # replacing ~118 individual subprocess pairs with one pair.
1789        self.rd.cargo_workspace.precompute_crate_inputs()
1790        # Pre-fetch all image context files in a single batched git call,
1791        # replacing ~41 individual subprocess pairs with one pair.
1792        self._precompute_image_context_files()
1793
1794        resolved = OrderedDict()
1795        visiting = set()
1796
1797        def visit(image: Image, path: list[str] = []) -> None:
1798            if image.name in resolved:
1799                return
1800            if image.name in visiting:
1801                diagram = " -> ".join(path + [image.name])
1802                raise ValueError(f"circular dependency in mzbuild: {diagram}")
1803
1804            visiting.add(image.name)
1805            for d in sorted(image.depends_on):
1806                visit(self.images[d], path + [image.name])
1807            resolved[image.name] = image
1808
1809        for target_image in sorted(targets, key=lambda image: image.name):
1810            visit(target_image)
1811
1812        return DependencySet(resolved.values())
1813
1814    def _precompute_image_context_files(self) -> None:
1815        """Pre-fetch all image context files in a single batched git call.
1816
1817        This replaces ~41 individual pairs of git subprocess calls (one per
1818        image) with a single pair, then partitions the results by image path.
1819        """
1820        root = self.rd.root
1821        # Use paths relative to root for git specs and partitioning, since
1822        # git --relative outputs paths relative to cwd (root). Image paths
1823        # may be absolute when MZ_ROOT is an absolute path.
1824        image_rel_paths = sorted(
1825            set(str(img.path.relative_to(root)) for img in self.images.values())
1826        )
1827        specs = [f"{p}/**" for p in image_rel_paths]
1828
1829        empty_tree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
1830        diff_files = spawn.capture(
1831            ["git", "diff", "--name-only", "-z", "--relative", empty_tree, "--"]
1832            + specs,
1833            cwd=root,
1834        )
1835        ls_files = spawn.capture(
1836            ["git", "ls-files", "--others", "--exclude-standard", "-z", "--"] + specs,
1837            cwd=root,
1838        )
1839        all_files = set(
1840            f for f in (diff_files + ls_files).split("\0") if f.strip() != ""
1841        )
1842
1843        # Partition files by image path (longest match first for nested paths)
1844        image_file_map: dict[str, set[str]] = {p: set() for p in image_rel_paths}
1845        sorted_paths = sorted(image_rel_paths, key=len, reverse=True)
1846        for f in all_files:
1847            for ip in sorted_paths:
1848                if f.startswith(ip + "/"):
1849                    image_file_map[ip].add(f)
1850                    break
1851
1852        for img in self.images.values():
1853            rel = str(img.path.relative_to(root))
1854            img._context_files_cache = image_file_map.get(rel, set())
1855
1856    def __iter__(self) -> Iterator[Image]:
1857        return iter(self.images.values())
1858
1859
1860def publish_multiarch_images(
1861    tag: str, dependency_sets: Iterable[Iterable[ResolvedImage]]
1862) -> None:
1863    """Publishes a set of docker images under a given tag."""
1864    always_push_tags = ("latest", "unstable")
1865    if ghcr_token := os.getenv("GITHUB_GHCR_TOKEN"):
1866        spawn.runv(
1867            [
1868                "docker",
1869                "login",
1870                "ghcr.io",
1871                "-u",
1872                "materialize-bot",
1873                "--password-stdin",
1874            ],
1875            stdin=ghcr_token.encode(),
1876        )
1877    for images in zip(*dependency_sets):
1878        names = set(image.image.name for image in images)
1879        assert len(names) == 1, "dependency sets did not contain identical images"
1880        name = images[0].image.docker_name(tag)
1881        if tag in always_push_tags or not is_docker_image_pushed(name):
1882            spawn.run_with_retries(
1883                lambda: (
1884                    spawn.runv(
1885                        [
1886                            "docker",
1887                            "manifest",
1888                            "create",
1889                            "--amend",
1890                            name,
1891                            *(image.spec() for image in images),
1892                        ]
1893                    ),
1894                    spawn.runv(["docker", "manifest", "push", name]),
1895                )
1896            )
1897
1898        ghcr_name = f"{GHCR_PREFIX}{name}"
1899        if ghcr_token and (
1900            tag in always_push_tags or not is_ghcr_image_pushed(ghcr_name)
1901        ):
1902            spawn.run_with_retries(
1903                lambda: (
1904                    spawn.runv(
1905                        [
1906                            "docker",
1907                            "manifest",
1908                            "create",
1909                            "--amend",
1910                            ghcr_name,
1911                            *(f"{GHCR_PREFIX}{image.spec()}" for image in images),
1912                        ]
1913                    ),
1914                    spawn.runv(["docker", "manifest", "push", ghcr_name]),
1915                )
1916            )
1917    print(f"--- Nofifying for tag {tag}")
1918    markdown = f"""Pushed images with Docker tag `{tag}`"""
1919    spawn.runv(
1920        [
1921            "buildkite-agent",
1922            "annotate",
1923            "--style=info",
1924            f"--context=build-tags-{tag}",
1925        ],
1926        stdin=markdown.encode(),
1927    )
GHCR_PREFIX = 'ghcr.io/materializeinc/'
class RustIncrementalBuildFailure(builtins.Exception):
58class RustIncrementalBuildFailure(Exception):
59    """A build failure that corrupted incremental artifacts explain. Recovering
60    requires clearing the cargo target directories before retrying."""

A build failure that corrupted incremental artifacts explain. Recovering requires clearing the cargo target directories before retrying.

class CargoRegistryFetchFailure(builtins.Exception):
63class CargoRegistryFetchFailure(Exception):
64    """A crates.io fetch that failed for transport reasons. Retrying recovers,
65    and the target directories must be kept: nothing in them is corrupted."""

A crates.io fetch that failed for transport reasons. Retrying recovers, and the target directories must be kept: nothing in them is corrupted.

def raise_if_retryable_build_failure(output: str) -> None:
68def raise_if_retryable_build_failure(output: str) -> None:
69    """Raises `RustIncrementalBuildFailure` or `CargoRegistryFetchFailure` if
70    the output of a failed cargo invocation matches a known signature."""
71    incremental_build_failure_msgs = [
72        "panicked at compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs",
73        "Found unstable fingerprints for",
74        "ld.lld: error: undefined symbol",
75        "truncated or malformed archive",
76        "signal: 11, SIGSEGV",
77    ]
78    registry_fetch_failure_msgs = [
79        "unable to update registry",
80    ]
81    # A cached build-script binary poisoned by cargo cache corruption dies
82    # with a bare ENOENT before doing any work. Both halves are required,
83    # and the error must be the exact bare line: "failed to run custom
84    # build command" alone is any build-script bug, which a retry cannot
85    # fix, and a build script that fails on a missing file with an error
86    # context of its own produces the ENOENT in a "Caused by:" detail line
87    # instead of the bare "Error:" line.
88    custom_build_script_enoent = "failed to run custom build command" in output and any(
89        line.strip() == "Error: No such file or directory (os error 2)"
90        for line in output.splitlines()
91    )
92    if custom_build_script_enoent or any(
93        msg in output for msg in incremental_build_failure_msgs
94    ):
95        raise RustIncrementalBuildFailure()
96    if any(msg in output for msg in registry_fetch_failure_msgs):
97        raise CargoRegistryFetchFailure()

Raises RustIncrementalBuildFailure or CargoRegistryFetchFailure if the output of a failed cargo invocation matches a known signature.

def exit_for_retryable_build_failure( e: RustIncrementalBuildFailure | CargoRegistryFetchFailure) -> NoReturn:
100def exit_for_retryable_build_failure(
101    e: RustIncrementalBuildFailure | CargoRegistryFetchFailure,
102) -> NoReturn:
103    """Exits with 199, which Buildkite retries automatically (see
104    mkpipeline.py), after clearing the cargo target directories if they are
105    corrupted."""
106    if isinstance(e, RustIncrementalBuildFailure):
107        print(
108            "--- Detected incremental build failure, clearing cargo target directories"
109        )
110        for dir in ["target", "target-xcompile"]:
111            shutil.rmtree(MZ_ROOT / dir, ignore_errors=True)
112    else:
113        # Nothing on disk is corrupted, so keep the target directories. Wiping
114        # them would turn a network blip into a full rebuild of the workspace,
115        # here and in every later job that shares the agent's target directory.
116        print("--- Detected transient cargo registry failure, retrying")
117    sys.exit(199)

Exits with 199, which Buildkite retries automatically (see mkpipeline.py), after clearing the cargo target directories if they are corrupted.

def run_and_detect_retryable_build_failure( cmd: list[str], cwd: str | pathlib._local.Path, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
120def run_and_detect_retryable_build_failure(
121    cmd: list[str],
122    cwd: str | Path,
123    env: dict[str, str] | None = None,
124) -> subprocess.CompletedProcess:
125    """This function is complex since it prints out each line immediately to
126    stdout/stderr, but still records them at the same time so that we can scan
127    for known retryable build failures."""
128    stdout_result = io.StringIO()
129    stderr_result = io.StringIO()
130    base_env = env if env is not None else os.environ
131    p = subprocess.Popen(
132        cmd,
133        cwd=cwd,
134        stdout=subprocess.PIPE,
135        stderr=subprocess.PIPE,
136        text=True,
137        bufsize=1,
138        env={**base_env, "CARGO_TERM_COLOR": "always", "RUSTC_COLOR": "always"},
139    )
140
141    sel = selectors.DefaultSelector()
142    sel.register(p.stdout, selectors.EVENT_READ)  # type: ignore
143    sel.register(p.stderr, selectors.EVENT_READ)  # type: ignore
144    assert p.stdout is not None
145    assert p.stderr is not None
146    os.set_blocking(p.stdout.fileno(), False)
147    os.set_blocking(p.stderr.fileno(), False)
148    running = True
149    while running:
150        for key, val in sel.select():
151            output = io.StringIO()
152            running = False
153            while True:
154                new_output = key.fileobj.read(1024)  # type: ignore
155                if not new_output:
156                    break
157                output.write(new_output)
158            contents = output.getvalue()
159            output.close()
160            if not contents:
161                continue
162            # Keep running as long as stdout or stderr have any content
163            running = True
164            if key.fileobj is p.stdout:
165                print(
166                    contents,
167                    end="",
168                    flush=True,
169                )
170                stdout_result.write(contents)
171            else:
172                print(
173                    contents,
174                    end="",
175                    file=sys.stderr,
176                    flush=True,
177                )
178                stderr_result.write(contents)
179    p.wait()
180    retcode = p.poll()
181    assert retcode is not None
182    stdout_contents = stdout_result.getvalue()
183    stdout_result.close()
184    stderr_contents = stderr_result.getvalue()
185    stderr_result.close()
186    if retcode:
187        raise_if_retryable_build_failure(stdout_contents + stderr_contents)
188        raise subprocess.CalledProcessError(
189            retcode, p.args, output=stdout_contents, stderr=stderr_contents
190        )
191    return subprocess.CompletedProcess(
192        p.args, retcode, stdout_contents, stderr_contents
193    )

This function is complex since it prints out each line immediately to stdout/stderr, but still records them at the same time so that we can scan for known retryable build failures.

class Fingerprint(builtins.bytes):
196class Fingerprint(bytes):
197    """A SHA-1 hash of the inputs to an `Image`.
198
199    The string representation uses base32 encoding to distinguish mzbuild
200    fingerprints from Git's hex encoded SHA-1 hashes while still being
201    URL safe.
202    """
203
204    def __str__(self) -> str:
205        return base64.b32encode(self).decode()

A SHA-1 hash of the inputs to an Image.

The string representation uses base32 encoding to distinguish mzbuild fingerprints from Git's hex encoded SHA-1 hashes while still being URL safe.

class Profile(enum.Enum):
208class Profile(Enum):
209    RELEASE = auto()
210    OPTIMIZED = auto()
211    DEV = auto()
RELEASE = <Profile.RELEASE: 1>
OPTIMIZED = <Profile.OPTIMIZED: 2>
DEV = <Profile.DEV: 3>
class RepositoryDetails:
214class RepositoryDetails:
215    """Immutable details about a `Repository`.
216
217    Used internally by mzbuild.
218
219    Attributes:
220        root: The path to the root of the repository.
221        arch: The CPU architecture to build for.
222        profile: What profile the repository is being built with.
223        coverage: Whether the repository has code coverage instrumentation
224            enabled.
225        sanitizer: Whether to use a sanitizer (address, hwaddress, cfi, thread, leak, memory, none)
226        cargo_workspace: The `cargo.Workspace` associated with the repository.
227        image_registry: The Docker image registry to pull images from and push
228            images to.
229        image_prefix: A prefix to apply to all Docker image names.
230    """
231
232    def __init__(
233        self,
234        root: Path,
235        arch: Arch,
236        profile: Profile,
237        coverage: bool,
238        sanitizer: Sanitizer,
239        image_registry: str,
240        image_prefix: str,
241    ):
242        self.root = root
243        self.arch = arch
244        self.profile = profile
245        self.coverage = coverage
246        self.sanitizer = sanitizer
247        self.cargo_workspace = cargo.Workspace(root)
248        self.image_registry = image_registry
249        self.image_prefix = image_prefix
250
251    def build(
252        self,
253        subcommand: str,
254        rustflags: list[str],
255        channel: str | None = None,
256        extra_env: dict[str, str] = {},
257    ) -> list[str]:
258        """Start a build invocation for the configured architecture."""
259        return xcompile.cargo(
260            arch=self.arch,
261            channel=channel,
262            subcommand=subcommand,
263            rustflags=rustflags,
264            extra_env=extra_env,
265        )
266
267    def tool(self, name: str) -> list[str]:
268        """Start a binutils tool invocation for the configured architecture."""
269        if platform.system() != "Linux":
270            # We can't use the local tools from macOS to build a Linux executable
271            return ["bin/ci-builder", "run", "stable", name]
272        # If we're on Linux, trust that the tools are installed instead of
273        # loading the slow ci-builder. If you don't have compilation tools
274        # installed you can still run `bin/ci-builder run stable
275        # bin/mzcompose ...`, and most likely the Cargo build will already
276        # fail earlier if you don't have compilation tools installed and
277        # run without the ci-builder.
278        return [name]
279
280    def builder(self, args: list[str]) -> list[str]:
281        """Start an invocation of `args` inside the ci-builder for the
282        configured architecture, from the repository root.
283
284        Unlike `build`, this enters the ci-builder on macOS too, so `args` can
285        rely on files that only the ci-builder image provides.
286        """
287        if "MZ_DEV_CI_BUILDER" in os.environ:
288            return args
289        return [
290            "env",
291            f"MZ_DEV_CI_BUILDER_ARCH={self.arch}",
292            "bin/ci-builder",
293            "run",
294            "stable",
295            *args,
296        ]
297
298    def cargo_target_dir(self) -> Path:
299        """Determine the path to the target directory for Cargo."""
300        return self.root / "target-xcompile" / xcompile.target(self.arch)
301
302    def rewrite_builder_path_for_host(self, path: Path) -> Path:
303        """Rewrite a path that is relative to the target directory inside the
304        builder to a path that is relative to the target directory on the host.
305
306        If path does is not relative to the target directory inside the builder,
307        it is returned unchanged.
308        """
309        builder_target_dir = Path("/mnt/build") / xcompile.target(self.arch)
310        try:
311            return self.cargo_target_dir() / path.relative_to(builder_target_dir)
312        except ValueError:
313            return path

Immutable details about a Repository.

Used internally by mzbuild.

Attributes: root: The path to the root of the repository. arch: The CPU architecture to build for. profile: What profile the repository is being built with. coverage: Whether the repository has code coverage instrumentation enabled. sanitizer: Whether to use a sanitizer (address, hwaddress, cfi, thread, leak, memory, none) cargo_workspace: The cargo.Workspace associated with the repository. image_registry: The Docker image registry to pull images from and push images to. image_prefix: A prefix to apply to all Docker image names.

RepositoryDetails( root: pathlib._local.Path, arch: materialize.xcompile.Arch, profile: Profile, coverage: bool, sanitizer: materialize.rustc_flags.Sanitizer, image_registry: str, image_prefix: str)
232    def __init__(
233        self,
234        root: Path,
235        arch: Arch,
236        profile: Profile,
237        coverage: bool,
238        sanitizer: Sanitizer,
239        image_registry: str,
240        image_prefix: str,
241    ):
242        self.root = root
243        self.arch = arch
244        self.profile = profile
245        self.coverage = coverage
246        self.sanitizer = sanitizer
247        self.cargo_workspace = cargo.Workspace(root)
248        self.image_registry = image_registry
249        self.image_prefix = image_prefix
root
arch
profile
coverage
sanitizer
cargo_workspace
image_registry
image_prefix
def build( self, subcommand: str, rustflags: list[str], channel: str | None = None, extra_env: dict[str, str] = {}) -> list[str]:
251    def build(
252        self,
253        subcommand: str,
254        rustflags: list[str],
255        channel: str | None = None,
256        extra_env: dict[str, str] = {},
257    ) -> list[str]:
258        """Start a build invocation for the configured architecture."""
259        return xcompile.cargo(
260            arch=self.arch,
261            channel=channel,
262            subcommand=subcommand,
263            rustflags=rustflags,
264            extra_env=extra_env,
265        )

Start a build invocation for the configured architecture.

def tool(self, name: str) -> list[str]:
267    def tool(self, name: str) -> list[str]:
268        """Start a binutils tool invocation for the configured architecture."""
269        if platform.system() != "Linux":
270            # We can't use the local tools from macOS to build a Linux executable
271            return ["bin/ci-builder", "run", "stable", name]
272        # If we're on Linux, trust that the tools are installed instead of
273        # loading the slow ci-builder. If you don't have compilation tools
274        # installed you can still run `bin/ci-builder run stable
275        # bin/mzcompose ...`, and most likely the Cargo build will already
276        # fail earlier if you don't have compilation tools installed and
277        # run without the ci-builder.
278        return [name]

Start a binutils tool invocation for the configured architecture.

def builder(self, args: list[str]) -> list[str]:
280    def builder(self, args: list[str]) -> list[str]:
281        """Start an invocation of `args` inside the ci-builder for the
282        configured architecture, from the repository root.
283
284        Unlike `build`, this enters the ci-builder on macOS too, so `args` can
285        rely on files that only the ci-builder image provides.
286        """
287        if "MZ_DEV_CI_BUILDER" in os.environ:
288            return args
289        return [
290            "env",
291            f"MZ_DEV_CI_BUILDER_ARCH={self.arch}",
292            "bin/ci-builder",
293            "run",
294            "stable",
295            *args,
296        ]

Start an invocation of args inside the ci-builder for the configured architecture, from the repository root.

Unlike build, this enters the ci-builder on macOS too, so args can rely on files that only the ci-builder image provides.

def cargo_target_dir(self) -> pathlib._local.Path:
298    def cargo_target_dir(self) -> Path:
299        """Determine the path to the target directory for Cargo."""
300        return self.root / "target-xcompile" / xcompile.target(self.arch)

Determine the path to the target directory for Cargo.

def rewrite_builder_path_for_host(self, path: pathlib._local.Path) -> pathlib._local.Path:
302    def rewrite_builder_path_for_host(self, path: Path) -> Path:
303        """Rewrite a path that is relative to the target directory inside the
304        builder to a path that is relative to the target directory on the host.
305
306        If path does is not relative to the target directory inside the builder,
307        it is returned unchanged.
308        """
309        builder_target_dir = Path("/mnt/build") / xcompile.target(self.arch)
310        try:
311            return self.cargo_target_dir() / path.relative_to(builder_target_dir)
312        except ValueError:
313            return path

Rewrite a path that is relative to the target directory inside the builder to a path that is relative to the target directory on the host.

If path does is not relative to the target directory inside the builder, it is returned unchanged.

@cache
def docker_images() -> set[str]:
316@cache
317def docker_images() -> set[str]:
318    """List the Docker images available on the local machine."""
319    return set(
320        spawn.capture(["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"])
321        .strip()
322        .split("\n")
323    )

List the Docker images available on the local machine.

KNOWN_DOCKER_IMAGES_FILE = PosixPath('/workspace/known-docker-images.txt')
def is_docker_image_pushed(name: str) -> bool:
331def is_docker_image_pushed(name: str) -> bool:
332    """Check whether the named image is pushed to Docker Hub.
333
334    Note that this operation requires a rather slow network request.
335    """
336    global _known_docker_images
337
338    if _known_docker_images is None:
339        with _known_docker_images_lock:
340            if not KNOWN_DOCKER_IMAGES_FILE.exists():
341                _known_docker_images = set()
342            else:
343                with KNOWN_DOCKER_IMAGES_FILE.open() as f:
344                    _known_docker_images = set(line.strip() for line in f)
345
346    if name in _known_docker_images:
347        return True
348
349    if ":" not in name:
350        image, tag = name, "latest"
351    else:
352        image, tag = name.rsplit(":", 1)
353
354    dockerhub_username = os.getenv("DOCKERHUB_USERNAME")
355    dockerhub_token = os.getenv("DOCKERHUB_ACCESS_TOKEN")
356
357    exists: bool = False
358
359    try:
360        if dockerhub_username and dockerhub_token:
361            response = requests.head(
362                f"https://registry-1.docker.io/v2/{image}/manifests/{tag}",
363                headers={
364                    "Accept": "application/vnd.docker.distribution.manifest.v2+json",
365                },
366                auth=HTTPBasicAuth(dockerhub_username, dockerhub_token),
367                timeout=10,
368            )
369        else:
370            token = requests.get(
371                "https://auth.docker.io/token",
372                params={
373                    "service": "registry.docker.io",
374                    "scope": f"repository:{image}:pull",
375                },
376                timeout=10,
377            ).json()["token"]
378            response = requests.head(
379                f"https://registry-1.docker.io/v2/{image}/manifests/{tag}",
380                headers={
381                    "Accept": "application/vnd.docker.distribution.manifest.v2+json",
382                    "Authorization": f"Bearer {token}",
383                },
384                timeout=10,
385            )
386
387        if response.status_code in (401, 429, 500, 502, 503, 504):
388            # Fall back to 5x slower method
389            proc = subprocess.run(
390                ["docker", "manifest", "inspect", name],
391                stdout=subprocess.DEVNULL,
392                stderr=subprocess.DEVNULL,
393                env=dict(os.environ, DOCKER_CLI_EXPERIMENTAL="enabled"),
394            )
395            exists = proc.returncode == 0
396        else:
397            exists = response.status_code == 200
398
399    except Exception as e:
400        print(f"Error checking Docker image: {e}")
401        return False
402
403    if exists:
404        with _known_docker_images_lock:
405            _known_docker_images.add(name)
406            with KNOWN_DOCKER_IMAGES_FILE.open("a") as f:
407                print(name, file=f)
408
409    return exists

Check whether the named image is pushed to Docker Hub.

Note that this operation requires a rather slow network request.

def is_ghcr_image_pushed(name: str) -> bool:
412def is_ghcr_image_pushed(name: str) -> bool:
413    global _known_docker_images
414
415    if _known_docker_images is None:
416        with _known_docker_images_lock:
417            if not KNOWN_DOCKER_IMAGES_FILE.exists():
418                _known_docker_images = set()
419            else:
420                with KNOWN_DOCKER_IMAGES_FILE.open() as f:
421                    _known_docker_images = set(line.strip() for line in f)
422
423    name_without_ghcr = name.removeprefix("ghcr.io/")
424    if name in _known_docker_images:
425        return True
426
427    if ":" not in name_without_ghcr:
428        image, tag = name_without_ghcr, "latest"
429    else:
430        image, tag = name_without_ghcr.rsplit(":", 1)
431
432    exists: bool = False
433
434    try:
435        token = requests.get(
436            "https://ghcr.io/token",
437            params={
438                "scope": f"repository:{image}:pull",
439            },
440            timeout=10,
441        ).json()["token"]
442        response = requests.head(
443            f"https://ghcr.io/v2/{image}/manifests/{tag}",
444            headers={"Authorization": f"Bearer {token}"},
445            timeout=10,
446        )
447
448        if response.status_code in (401, 429, 500, 502, 503, 504):
449            # Fall back to 5x slower method
450            proc = subprocess.run(
451                ["docker", "manifest", "inspect", name],
452                stdout=subprocess.DEVNULL,
453                stderr=subprocess.DEVNULL,
454                env=dict(os.environ, DOCKER_CLI_EXPERIMENTAL="enabled"),
455            )
456            exists = proc.returncode == 0
457        else:
458            exists = response.status_code == 200
459
460    except Exception as e:
461        print(f"Error checking Docker image: {e}")
462        return False
463
464    if exists:
465        with _known_docker_images_lock:
466            _known_docker_images.add(name)
467            with KNOWN_DOCKER_IMAGES_FILE.open("a") as f:
468                print(name, file=f)
469
470    return exists
def is_docker_image_public(name: str) -> bool | None:
520def is_docker_image_public(name: str) -> bool | None:
521    """Whether the Docker Hub repository for `name` is public (tri-state).
522
523    Reads repository metadata (`is_private`) via the Hub API rather than the
524    registry, which both avoids the registry's anonymous pull-rate limit (see
525    `mz_image_tag_exists`) and is tag-independent. A 404 means the repo is
526    private or absent; transient errors yield None rather than a false "private".
527    """
528    repo = name.rsplit(":", 1)[0]
529    response = _get_with_retries(f"https://hub.docker.com/v2/repositories/{repo}/")
530    if response is None:
531        return None
532    if response.status_code == 404:
533        return False
534    if response.status_code != 200:
535        return None
536    body = _json_dict_or_none(response)
537    return None if body is None else not body.get("is_private", True)

Whether the Docker Hub repository for name is public (tri-state).

Reads repository metadata (is_private) via the Hub API rather than the registry, which both avoids the registry's anonymous pull-rate limit (see mz_image_tag_exists) and is tag-independent. A 404 means the repo is private or absent; transient errors yield None rather than a false "private".

def is_ghcr_image_public(name: str) -> bool | None:
540def is_ghcr_image_public(name: str) -> bool | None:
541    """Whether the GHCR repository for `name` is public (tri-state).
542
543    Requests an *anonymous* pull token and lists tags: a public repo authorizes
544    the anonymous client (200), a private or missing one rejects it (401/403/404).
545    Like the Docker Hub check, this is tag-independent.
546    """
547    image = name.removeprefix("ghcr.io/").rsplit(":", 1)[0]
548    token_response = _get_with_retries(
549        "https://ghcr.io/token", params={"scope": f"repository:{image}:pull"}
550    )
551    if token_response is None:
552        return None
553    if token_response.status_code in (401, 403):
554        return False
555    if token_response.status_code != 200:
556        return None
557    body = _json_dict_or_none(token_response)
558    if body is None or "token" not in body:
559        return None
560    token = body["token"]
561    response = _get_with_retries(
562        f"https://ghcr.io/v2/{image}/tags/list",
563        params={"n": 1},
564        headers={"Authorization": f"Bearer {token}"},
565    )
566    if response is None:
567        return None
568    if response.status_code == 200:
569        return True
570    if response.status_code in (401, 403, 404):
571        return False
572    return None

Whether the GHCR repository for name is public (tri-state).

Requests an anonymous pull token and lists tags: a public repo authorizes the anonymous client (200), a private or missing one rejects it (401/403/404). Like the Docker Hub check, this is tag-independent.

def chmod_x(path: pathlib._local.Path) -> None:
575def chmod_x(path: Path) -> None:
576    """Set the executable bit on a file or directory."""
577    # https://stackoverflow.com/a/30463972/1122351
578    mode = os.stat(path).st_mode
579    mode |= (mode & 0o444) >> 2  # copy R bits to X
580    os.chmod(path, mode)

Set the executable bit on a file or directory.

class PreImage:
583class PreImage:
584    """An action to run before building a Docker image.
585
586    Args:
587        rd: The `RepositoryDetails` for the repository.
588        path: The path to the `Image` associated with this action.
589    """
590
591    def __init__(self, rd: RepositoryDetails, path: Path):
592        self.rd = rd
593        self.path = path
594
595    @classmethod
596    def prepare_batch(cls, instances: list["PreImage"]) -> Any:
597        """Prepare a batch of actions.
598
599        This is useful for `PreImage` actions that are more efficient when
600        their actions are applied to several images in bulk.
601
602        Returns an arbitrary output that is passed to `PreImage.run`.
603        """
604        pass
605
606    def run(self, prep: Any) -> None:
607        """Perform the action.
608
609        Args:
610            prep: Any prep work returned by `prepare_batch`.
611        """
612        pass
613
614    def inputs(self) -> set[str]:
615        """Return the files which are considered inputs to the action."""
616        raise NotImplementedError
617
618    def extra(self) -> str:
619        """Returns additional data for incorporation in the fingerprint."""
620        return ""

An action to run before building a Docker image.

Args: rd: The RepositoryDetails for the repository. path: The path to the Image associated with this action.

PreImage( rd: RepositoryDetails, path: pathlib._local.Path)
591    def __init__(self, rd: RepositoryDetails, path: Path):
592        self.rd = rd
593        self.path = path
rd
path
@classmethod
def prepare_batch(cls, instances: list[PreImage]) -> Any:
595    @classmethod
596    def prepare_batch(cls, instances: list["PreImage"]) -> Any:
597        """Prepare a batch of actions.
598
599        This is useful for `PreImage` actions that are more efficient when
600        their actions are applied to several images in bulk.
601
602        Returns an arbitrary output that is passed to `PreImage.run`.
603        """
604        pass

Prepare a batch of actions.

This is useful for PreImage actions that are more efficient when their actions are applied to several images in bulk.

Returns an arbitrary output that is passed to PreImage.run.

def run(self, prep: Any) -> None:
606    def run(self, prep: Any) -> None:
607        """Perform the action.
608
609        Args:
610            prep: Any prep work returned by `prepare_batch`.
611        """
612        pass

Perform the action.

Args: prep: Any prep work returned by prepare_batch.

def inputs(self) -> set[str]:
614    def inputs(self) -> set[str]:
615        """Return the files which are considered inputs to the action."""
616        raise NotImplementedError

Return the files which are considered inputs to the action.

def extra(self) -> str:
618    def extra(self) -> str:
619        """Returns additional data for incorporation in the fingerprint."""
620        return ""

Returns additional data for incorporation in the fingerprint.

class Copy(PreImage):
623class Copy(PreImage):
624    """A `PreImage` action which copies files from a directory.
625
626    See doc/developer/mzbuild.md for an explanation of the user-facing
627    parameters.
628    """
629
630    def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
631        super().__init__(rd, path)
632
633        self.source = config.pop("source", None)
634        if self.source is None:
635            raise ValueError("mzbuild config is missing 'source' argument")
636
637        self.destination = config.pop("destination", None)
638        if self.destination is None:
639            raise ValueError("mzbuild config is missing 'destination' argument")
640
641        self.matching = config.pop("matching", "*")
642
643    def run(self, prep: Any) -> None:
644        super().run(prep)
645        for src in self._source_files():
646            dst = self.path / self.destination / src
647            dst.parent.mkdir(parents=True, exist_ok=True)
648            shutil.copy(self.rd.root / self.source / src, dst)
649
650    def _source_files(self) -> set[str]:
651        """The files to copy, relative to `source`."""
652        return set(git.expand_globs(self.rd.root / self.source, self.matching))
653
654    def inputs(self) -> set[str]:
655        return {str(Path(self.source) / src) for src in self._source_files()}

A PreImage action which copies files from a directory.

See doc/developer/mzbuild.md for an explanation of the user-facing parameters.

Copy( rd: RepositoryDetails, path: pathlib._local.Path, config: dict[str, typing.Any])
630    def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
631        super().__init__(rd, path)
632
633        self.source = config.pop("source", None)
634        if self.source is None:
635            raise ValueError("mzbuild config is missing 'source' argument")
636
637        self.destination = config.pop("destination", None)
638        if self.destination is None:
639            raise ValueError("mzbuild config is missing 'destination' argument")
640
641        self.matching = config.pop("matching", "*")
source
destination
matching
def run(self, prep: Any) -> None:
643    def run(self, prep: Any) -> None:
644        super().run(prep)
645        for src in self._source_files():
646            dst = self.path / self.destination / src
647            dst.parent.mkdir(parents=True, exist_ok=True)
648            shutil.copy(self.rd.root / self.source / src, dst)

Perform the action.

Args: prep: Any prep work returned by prepare_batch.

def inputs(self) -> set[str]:
654    def inputs(self) -> set[str]:
655        return {str(Path(self.source) / src) for src in self._source_files()}

Return the files which are considered inputs to the action.

Inherited Members
PreImage
rd
path
prepare_batch
extra
class CargoPreImage(PreImage):
658class CargoPreImage(PreImage):
659    """A `PreImage` action that uses Cargo."""
660
661    @staticmethod
662    @cache
663    def _cargo_shared_inputs() -> frozenset[str]:
664        """Resolve shared Cargo inputs once and cache the result.
665
666        This expands the 'ci/builder' directory glob and filters out
667        non-existent files like '.cargo/config', avoiding repeated
668        git subprocess calls in fingerprint().
669        """
670        inputs: set[str] = set()
671        inputs |= git.expand_globs(Path("."), "ci/builder/**")
672        inputs.add("Cargo.toml")
673        inputs.add("Cargo.lock")
674        if Path(".cargo/config").exists():
675            inputs.add(".cargo/config")
676        return frozenset(inputs)
677
678    def inputs(self) -> set[str]:
679        return set(CargoPreImage._cargo_shared_inputs())
680
681    def extra(self) -> str:
682        # Cargo images depend on the release mode and whether
683        # coverage/sanitizer is enabled.
684        flags: list[str] = []
685        if self.rd.profile == Profile.RELEASE:
686            flags += "release"
687        if self.rd.profile == Profile.OPTIMIZED:
688            flags += "optimized"
689        if self.rd.coverage:
690            flags += "coverage"
691        if self.rd.sanitizer != Sanitizer.none:
692            flags += self.rd.sanitizer.value
693        flags.sort()
694        return ",".join(flags)

A PreImage action that uses Cargo.

def inputs(self) -> set[str]:
678    def inputs(self) -> set[str]:
679        return set(CargoPreImage._cargo_shared_inputs())

Return the files which are considered inputs to the action.

def extra(self) -> str:
681    def extra(self) -> str:
682        # Cargo images depend on the release mode and whether
683        # coverage/sanitizer is enabled.
684        flags: list[str] = []
685        if self.rd.profile == Profile.RELEASE:
686            flags += "release"
687        if self.rd.profile == Profile.OPTIMIZED:
688            flags += "optimized"
689        if self.rd.coverage:
690            flags += "coverage"
691        if self.rd.sanitizer != Sanitizer.none:
692            flags += self.rd.sanitizer.value
693        flags.sort()
694        return ",".join(flags)

Returns additional data for incorporation in the fingerprint.

class CargoBuild(CargoPreImage):
697class CargoBuild(CargoPreImage):
698    """A `PreImage` action that builds a single binary with Cargo.
699
700    See doc/developer/mzbuild.md for an explanation of the user-facing
701    parameters.
702    """
703
704    def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
705        super().__init__(rd, path)
706        bin = config.pop("bin", [])
707        self.bins = bin if isinstance(bin, list) else [bin]
708        example = config.pop("example", [])
709        self.examples = example if isinstance(example, list) else [example]
710        self.strip = config.pop("strip", True)
711        self.extract = config.pop("extract", {})
712        self.builder_files = config.pop("builder-files", {})
713        features = config.pop("features", [])
714        self.features = features if isinstance(features, list) else [features]
715
716        if len(self.bins) == 0 and len(self.examples) == 0:
717            raise ValueError("mzbuild config is missing pre-build target")
718
719    @staticmethod
720    def generate_cargo_build_command(
721        rd: RepositoryDetails,
722        bins: list[str],
723        examples: list[str],
724        features: list[str] | None = None,
725    ) -> list[str]:
726        rustflags = (
727            rustc_flags.coverage
728            if rd.coverage
729            else (
730                rustc_flags.sanitizer[rd.sanitizer]
731                if rd.sanitizer != Sanitizer.none
732                else ["--cfg=tokio_unstable"]
733            )
734        )
735        cflags = (
736            [
737                f"--target={target(rd.arch)}",
738                "-fuse-ld=lld",
739            ]
740            + rustc_flags.sanitizer_cflags[rd.sanitizer]
741            if rd.sanitizer != Sanitizer.none
742            else []
743        )
744        extra_env = (
745            {
746                "CFLAGS": " ".join(cflags),
747                "CXXFLAGS": " ".join(cflags),
748                "LDFLAGS": " ".join(cflags),
749                "CXXSTDLIB": "stdc++",
750                "CC": "cc",
751                "CXX": "c++",
752                "CPP": "clang-cpp-19",
753                "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER": "cc",
754                "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER": "cc",
755                "PATH": "/sanshim:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
756                "TSAN_OPTIONS": "report_bugs=0",  # build-scripts fail
757            }
758            if rd.sanitizer != Sanitizer.none
759            else {}
760        )
761
762        # clang/lld `-22` suffixes must match the LLVM version of the rustc in
763        # rust-version (root Cargo.toml) and the apt.llvm.org release in
764        # ci/builder/Dockerfile.
765        if (
766            rd.profile == Profile.RELEASE
767            and rd.sanitizer == Sanitizer.none
768            and not rd.coverage
769        ):
770            rustflags += [
771                "-Clinker-plugin-lto",
772            ]
773            extra_env = {
774                "CC": "clang-22",
775                "CXX": "clang++-22",
776                "AR": "llvm-ar-22",
777                "RANLIB": "llvm-ranlib-22",
778                "CFLAGS": "-flto=thin",
779                "CXXFLAGS": "-flto=thin",
780                # `-static-libstdc++` is unused when clang links a C program,
781                # and jemalloc's configure runs its `strerror_r` link checks
782                # with `-Werror`. Without `-Wno-unused-command-line-argument`
783                # both checks fail and configure aborts with "cannot determine
784                # return type of strerror_r".
785                "LDFLAGS": "--ld-path=/usr/bin/ld.lld-22 -static-libstdc++ -Wno-unused-command-line-argument",
786                "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER": "/usr/local/bin/clang-lld-22",
787                "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER": "/usr/local/bin/clang-lld-22",
788            }
789
790        cargo_build = rd.build(
791            "build", channel=None, rustflags=rustflags, extra_env=extra_env
792        )
793
794        packages = set()
795        for bin in bins:
796            cargo_build.extend(["--bin", bin])
797            packages.add(rd.cargo_workspace.crate_for_bin(bin).name)
798        for example in examples:
799            cargo_build.extend(["--example", example])
800            packages.add(rd.cargo_workspace.crate_for_example(example).name)
801        cargo_build.extend(f"--package={p}" for p in packages)
802
803        if rd.profile == Profile.RELEASE:
804            cargo_build.append("--release")
805        if rd.profile == Profile.OPTIMIZED:
806            cargo_build.extend(["--profile", "optimized"])
807        if rd.sanitizer != Sanitizer.none:
808            # ASan doesn't work with jemalloc
809            cargo_build.append("--no-default-features")
810            # Uses more memory, so reduce the number of jobs
811            cargo_build.extend(
812                ["--jobs", str(round(multiprocessing.cpu_count() * 2 / 3))]
813            )
814        if features:
815            cargo_build.append(f"--features={','.join(features)}")
816
817        return cargo_build
818
819    @classmethod
820    def prepare_batch(cls, instances: list["PreImage"]) -> dict[str, Any]:
821        super().prepare_batch(instances)
822
823        if not instances:
824            return {}
825
826        # Building all binaries and examples in the same `cargo build` command
827        # allows Cargo to link in parallel with other work, which can
828        # meaningfully speed up builds.
829
830        rd: RepositoryDetails | None = None
831        builds = cast(list[CargoBuild], instances)
832        bins = set()
833        examples = set()
834        features = set()
835        for build in builds:
836            if not rd:
837                rd = build.rd
838            bins.update(build.bins)
839            examples.update(build.examples)
840            features.update(build.features)
841        assert rd
842
843        ui.section(f"Common build for: {', '.join(bins | examples)}")
844
845        cargo_build = cls.generate_cargo_build_command(
846            rd, list(bins), list(examples), list(features) if features else None
847        )
848
849        run_and_detect_retryable_build_failure(cargo_build, cwd=rd.root)
850
851        # Re-run with JSON-formatted messages and capture the output so we can
852        # later analyze the build artifacts in `run`. This should be nearly
853        # instantaneous since we just compiled above with the same crates and
854        # features. (We don't want to do the compile above with JSON-formatted
855        # messages because it wouldn't be human readable.)
856        json_output = spawn.capture(
857            cargo_build + ["--message-format=json"],
858            cwd=rd.root,
859        )
860        prep = {"cargo": json_output}
861
862        return prep
863
864    def build(self, build_output: dict[str, Any]) -> None:
865        cargo_profile = (
866            "release"
867            if self.rd.profile == Profile.RELEASE
868            else "optimized" if self.rd.profile == Profile.OPTIMIZED else "debug"
869        )
870
871        def copy(src: Path, relative_dst: Path) -> None:
872            exe_path = self.path / relative_dst
873            exe_path.parent.mkdir(parents=True, exist_ok=True)
874            shutil.copy(src, exe_path)
875
876            if self.strip:
877                # The debug information is large enough that it slows down CI,
878                # since we're packaging these binaries up into Docker images and
879                # shipping them around.
880                spawn.runv(
881                    [*self.rd.tool("strip"), "--strip-debug", exe_path],
882                    cwd=self.rd.root,
883                )
884            else:
885                # Even if we've been asked not to strip the binary, remove the
886                # `.debug_pubnames` and `.debug_pubtypes` sections. These are just
887                # indexes that speed up launching a debugger against the binary,
888                # and we're happy to have slower debugger start up in exchange for
889                # smaller binaries. Plus the sections have been obsoleted by a
890                # `.debug_names` section in DWARF 5, and so debugger support for
891                # `.debug_pubnames`/`.debug_pubtypes` is minimal anyway.
892                # See: https://github.com/rust-lang/rust/issues/46034
893                spawn.runv(
894                    [
895                        *self.rd.tool("objcopy"),
896                        "-R",
897                        ".debug_pubnames",
898                        "-R",
899                        ".debug_pubtypes",
900                        exe_path,
901                    ],
902                    cwd=self.rd.root,
903                )
904
905        for bin in self.bins:
906            src_path = self.rd.cargo_target_dir() / cargo_profile / bin
907            copy(src_path, bin)
908        for example in self.examples:
909            src_path = (
910                self.rd.cargo_target_dir() / cargo_profile / Path("examples") / example
911            )
912            copy(src_path, Path("examples") / example)
913
914        for src, dst in self.builder_files.items():
915            dst_path = self.path / dst
916            dst_path.parent.mkdir(parents=True, exist_ok=True)
917            spawn.runv(
918                self.rd.builder(["cp", src, str(dst_path.relative_to(self.rd.root))]),
919                cwd=self.rd.root,
920            )
921
922        if self.extract:
923            cargo_build_json_output = build_output["cargo"]
924
925            target_dir = self.rd.cargo_target_dir()
926            for line in cargo_build_json_output.split("\n"):
927                if line.strip() == "" or not line.startswith("{"):
928                    continue
929                message = json.loads(line)
930                if message["reason"] != "build-script-executed":
931                    continue
932                out_dir = self.rd.rewrite_builder_path_for_host(
933                    Path(message["out_dir"])
934                )
935                if not out_dir.is_relative_to(target_dir):
936                    # Some crates are built for both the host and the target.
937                    # Ignore the built-for-host out dir.
938                    continue
939                # parse the package name from a package_id that looks like one of:
940                # git+https://github.com/MaterializeInc/rust-server-sdk#launchdarkly-server-sdk@1.0.0
941                # path+file:///Users/roshan/materialize/src/catalog#mz-catalog@0.0.0
942                # registry+https://github.com/rust-lang/crates.io-index#num-rational@0.4.0
943                # file:///path/to/my-package#0.1.0
944                package_id = message["package_id"]
945                if "@" in package_id:
946                    package = package_id.split("@")[0].split("#")[-1]
947                else:
948                    package = message["package_id"].split("#")[0].split("/")[-1]
949                for src, dst in self.extract.get(package, {}).items():
950                    spawn.runv(["cp", "-R", out_dir / src, self.path / dst])
951
952        self.acquired = True
953
954    def run(self, prep: dict[str, Any]) -> None:
955        super().run(prep)
956        self.build(prep)
957
958    @cache
959    def inputs(self) -> set[str]:
960        deps = set()
961
962        for bin in self.bins:
963            crate = self.rd.cargo_workspace.crate_for_bin(bin)
964            deps |= self.rd.cargo_workspace.transitive_path_dependencies(crate)
965        for example in self.examples:
966            crate = self.rd.cargo_workspace.crate_for_example(example)
967            deps |= self.rd.cargo_workspace.transitive_path_dependencies(
968                crate, dev=True
969            )
970
971        inputs = super().inputs() | set(inp for dep in deps for inp in dep.inputs())
972        return inputs

A PreImage action that builds a single binary with Cargo.

See doc/developer/mzbuild.md for an explanation of the user-facing parameters.

CargoBuild( rd: RepositoryDetails, path: pathlib._local.Path, config: dict[str, typing.Any])
704    def __init__(self, rd: RepositoryDetails, path: Path, config: dict[str, Any]):
705        super().__init__(rd, path)
706        bin = config.pop("bin", [])
707        self.bins = bin if isinstance(bin, list) else [bin]
708        example = config.pop("example", [])
709        self.examples = example if isinstance(example, list) else [example]
710        self.strip = config.pop("strip", True)
711        self.extract = config.pop("extract", {})
712        self.builder_files = config.pop("builder-files", {})
713        features = config.pop("features", [])
714        self.features = features if isinstance(features, list) else [features]
715
716        if len(self.bins) == 0 and len(self.examples) == 0:
717            raise ValueError("mzbuild config is missing pre-build target")
bins
examples
strip
extract
builder_files
features
@staticmethod
def generate_cargo_build_command( rd: RepositoryDetails, bins: list[str], examples: list[str], features: list[str] | None = None) -> list[str]:
719    @staticmethod
720    def generate_cargo_build_command(
721        rd: RepositoryDetails,
722        bins: list[str],
723        examples: list[str],
724        features: list[str] | None = None,
725    ) -> list[str]:
726        rustflags = (
727            rustc_flags.coverage
728            if rd.coverage
729            else (
730                rustc_flags.sanitizer[rd.sanitizer]
731                if rd.sanitizer != Sanitizer.none
732                else ["--cfg=tokio_unstable"]
733            )
734        )
735        cflags = (
736            [
737                f"--target={target(rd.arch)}",
738                "-fuse-ld=lld",
739            ]
740            + rustc_flags.sanitizer_cflags[rd.sanitizer]
741            if rd.sanitizer != Sanitizer.none
742            else []
743        )
744        extra_env = (
745            {
746                "CFLAGS": " ".join(cflags),
747                "CXXFLAGS": " ".join(cflags),
748                "LDFLAGS": " ".join(cflags),
749                "CXXSTDLIB": "stdc++",
750                "CC": "cc",
751                "CXX": "c++",
752                "CPP": "clang-cpp-19",
753                "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER": "cc",
754                "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER": "cc",
755                "PATH": "/sanshim:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
756                "TSAN_OPTIONS": "report_bugs=0",  # build-scripts fail
757            }
758            if rd.sanitizer != Sanitizer.none
759            else {}
760        )
761
762        # clang/lld `-22` suffixes must match the LLVM version of the rustc in
763        # rust-version (root Cargo.toml) and the apt.llvm.org release in
764        # ci/builder/Dockerfile.
765        if (
766            rd.profile == Profile.RELEASE
767            and rd.sanitizer == Sanitizer.none
768            and not rd.coverage
769        ):
770            rustflags += [
771                "-Clinker-plugin-lto",
772            ]
773            extra_env = {
774                "CC": "clang-22",
775                "CXX": "clang++-22",
776                "AR": "llvm-ar-22",
777                "RANLIB": "llvm-ranlib-22",
778                "CFLAGS": "-flto=thin",
779                "CXXFLAGS": "-flto=thin",
780                # `-static-libstdc++` is unused when clang links a C program,
781                # and jemalloc's configure runs its `strerror_r` link checks
782                # with `-Werror`. Without `-Wno-unused-command-line-argument`
783                # both checks fail and configure aborts with "cannot determine
784                # return type of strerror_r".
785                "LDFLAGS": "--ld-path=/usr/bin/ld.lld-22 -static-libstdc++ -Wno-unused-command-line-argument",
786                "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER": "/usr/local/bin/clang-lld-22",
787                "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER": "/usr/local/bin/clang-lld-22",
788            }
789
790        cargo_build = rd.build(
791            "build", channel=None, rustflags=rustflags, extra_env=extra_env
792        )
793
794        packages = set()
795        for bin in bins:
796            cargo_build.extend(["--bin", bin])
797            packages.add(rd.cargo_workspace.crate_for_bin(bin).name)
798        for example in examples:
799            cargo_build.extend(["--example", example])
800            packages.add(rd.cargo_workspace.crate_for_example(example).name)
801        cargo_build.extend(f"--package={p}" for p in packages)
802
803        if rd.profile == Profile.RELEASE:
804            cargo_build.append("--release")
805        if rd.profile == Profile.OPTIMIZED:
806            cargo_build.extend(["--profile", "optimized"])
807        if rd.sanitizer != Sanitizer.none:
808            # ASan doesn't work with jemalloc
809            cargo_build.append("--no-default-features")
810            # Uses more memory, so reduce the number of jobs
811            cargo_build.extend(
812                ["--jobs", str(round(multiprocessing.cpu_count() * 2 / 3))]
813            )
814        if features:
815            cargo_build.append(f"--features={','.join(features)}")
816
817        return cargo_build
@classmethod
def prepare_batch( cls, instances: list[PreImage]) -> dict[str, typing.Any]:
819    @classmethod
820    def prepare_batch(cls, instances: list["PreImage"]) -> dict[str, Any]:
821        super().prepare_batch(instances)
822
823        if not instances:
824            return {}
825
826        # Building all binaries and examples in the same `cargo build` command
827        # allows Cargo to link in parallel with other work, which can
828        # meaningfully speed up builds.
829
830        rd: RepositoryDetails | None = None
831        builds = cast(list[CargoBuild], instances)
832        bins = set()
833        examples = set()
834        features = set()
835        for build in builds:
836            if not rd:
837                rd = build.rd
838            bins.update(build.bins)
839            examples.update(build.examples)
840            features.update(build.features)
841        assert rd
842
843        ui.section(f"Common build for: {', '.join(bins | examples)}")
844
845        cargo_build = cls.generate_cargo_build_command(
846            rd, list(bins), list(examples), list(features) if features else None
847        )
848
849        run_and_detect_retryable_build_failure(cargo_build, cwd=rd.root)
850
851        # Re-run with JSON-formatted messages and capture the output so we can
852        # later analyze the build artifacts in `run`. This should be nearly
853        # instantaneous since we just compiled above with the same crates and
854        # features. (We don't want to do the compile above with JSON-formatted
855        # messages because it wouldn't be human readable.)
856        json_output = spawn.capture(
857            cargo_build + ["--message-format=json"],
858            cwd=rd.root,
859        )
860        prep = {"cargo": json_output}
861
862        return prep

Prepare a batch of actions.

This is useful for PreImage actions that are more efficient when their actions are applied to several images in bulk.

Returns an arbitrary output that is passed to PreImage.run.

def build(self, build_output: dict[str, typing.Any]) -> None:
864    def build(self, build_output: dict[str, Any]) -> None:
865        cargo_profile = (
866            "release"
867            if self.rd.profile == Profile.RELEASE
868            else "optimized" if self.rd.profile == Profile.OPTIMIZED else "debug"
869        )
870
871        def copy(src: Path, relative_dst: Path) -> None:
872            exe_path = self.path / relative_dst
873            exe_path.parent.mkdir(parents=True, exist_ok=True)
874            shutil.copy(src, exe_path)
875
876            if self.strip:
877                # The debug information is large enough that it slows down CI,
878                # since we're packaging these binaries up into Docker images and
879                # shipping them around.
880                spawn.runv(
881                    [*self.rd.tool("strip"), "--strip-debug", exe_path],
882                    cwd=self.rd.root,
883                )
884            else:
885                # Even if we've been asked not to strip the binary, remove the
886                # `.debug_pubnames` and `.debug_pubtypes` sections. These are just
887                # indexes that speed up launching a debugger against the binary,
888                # and we're happy to have slower debugger start up in exchange for
889                # smaller binaries. Plus the sections have been obsoleted by a
890                # `.debug_names` section in DWARF 5, and so debugger support for
891                # `.debug_pubnames`/`.debug_pubtypes` is minimal anyway.
892                # See: https://github.com/rust-lang/rust/issues/46034
893                spawn.runv(
894                    [
895                        *self.rd.tool("objcopy"),
896                        "-R",
897                        ".debug_pubnames",
898                        "-R",
899                        ".debug_pubtypes",
900                        exe_path,
901                    ],
902                    cwd=self.rd.root,
903                )
904
905        for bin in self.bins:
906            src_path = self.rd.cargo_target_dir() / cargo_profile / bin
907            copy(src_path, bin)
908        for example in self.examples:
909            src_path = (
910                self.rd.cargo_target_dir() / cargo_profile / Path("examples") / example
911            )
912            copy(src_path, Path("examples") / example)
913
914        for src, dst in self.builder_files.items():
915            dst_path = self.path / dst
916            dst_path.parent.mkdir(parents=True, exist_ok=True)
917            spawn.runv(
918                self.rd.builder(["cp", src, str(dst_path.relative_to(self.rd.root))]),
919                cwd=self.rd.root,
920            )
921
922        if self.extract:
923            cargo_build_json_output = build_output["cargo"]
924
925            target_dir = self.rd.cargo_target_dir()
926            for line in cargo_build_json_output.split("\n"):
927                if line.strip() == "" or not line.startswith("{"):
928                    continue
929                message = json.loads(line)
930                if message["reason"] != "build-script-executed":
931                    continue
932                out_dir = self.rd.rewrite_builder_path_for_host(
933                    Path(message["out_dir"])
934                )
935                if not out_dir.is_relative_to(target_dir):
936                    # Some crates are built for both the host and the target.
937                    # Ignore the built-for-host out dir.
938                    continue
939                # parse the package name from a package_id that looks like one of:
940                # git+https://github.com/MaterializeInc/rust-server-sdk#launchdarkly-server-sdk@1.0.0
941                # path+file:///Users/roshan/materialize/src/catalog#mz-catalog@0.0.0
942                # registry+https://github.com/rust-lang/crates.io-index#num-rational@0.4.0
943                # file:///path/to/my-package#0.1.0
944                package_id = message["package_id"]
945                if "@" in package_id:
946                    package = package_id.split("@")[0].split("#")[-1]
947                else:
948                    package = message["package_id"].split("#")[0].split("/")[-1]
949                for src, dst in self.extract.get(package, {}).items():
950                    spawn.runv(["cp", "-R", out_dir / src, self.path / dst])
951
952        self.acquired = True
def run(self, prep: dict[str, typing.Any]) -> None:
954    def run(self, prep: dict[str, Any]) -> None:
955        super().run(prep)
956        self.build(prep)

Perform the action.

Args: prep: Any prep work returned by prepare_batch.

@cache
def inputs(self) -> set[str]:
958    @cache
959    def inputs(self) -> set[str]:
960        deps = set()
961
962        for bin in self.bins:
963            crate = self.rd.cargo_workspace.crate_for_bin(bin)
964            deps |= self.rd.cargo_workspace.transitive_path_dependencies(crate)
965        for example in self.examples:
966            crate = self.rd.cargo_workspace.crate_for_example(example)
967            deps |= self.rd.cargo_workspace.transitive_path_dependencies(
968                crate, dev=True
969            )
970
971        inputs = super().inputs() | set(inp for dep in deps for inp in dep.inputs())
972        return inputs

Return the files which are considered inputs to the action.

Inherited Members
CargoPreImage
extra
PreImage
rd
path
class Image:
 975class Image:
 976    """A Docker image whose build and dependencies are managed by mzbuild.
 977
 978    An image corresponds to a directory in a repository that contains a
 979    `mzbuild.yml` file. This directory is called an "mzbuild context."
 980
 981    Attributes:
 982        name: The name of the image.
 983        publish: Whether the image should be pushed to Docker Hub.
 984        depends_on: The names of the images upon which this image depends.
 985        root: The path to the root of the associated `Repository`.
 986        path: The path to the directory containing the `mzbuild.yml`
 987            configuration file.
 988        pre_images: Optional actions to perform before running `docker build`.
 989        build_args: An optional list of --build-arg to pass to the dockerfile
 990    """
 991
 992    _DOCKERFILE_MZFROM_RE = re.compile(rb"^MZFROM\s*(\S+)")
 993
 994    _context_files_cache: set[str] | None
 995
 996    def __init__(self, rd: RepositoryDetails, path: Path):
 997        self.rd = rd
 998        self.path = path
 999        self._context_files_cache = None
1000        self.pre_images: list[PreImage] = []
1001        with open(self.path / "mzbuild.yml") as f:
1002            data = yaml.safe_load(f)
1003            self.name: str = data.pop("name")
1004            self.publish: bool = data.pop("publish", True)
1005            self.description: str | None = data.pop("description", None)
1006            self.mainline: bool = data.pop("mainline", True)
1007            for pre_image in data.pop("pre-image", []):
1008                typ = pre_image.pop("type", None)
1009                if typ == "cargo-build":
1010                    self.pre_images.append(CargoBuild(self.rd, self.path, pre_image))
1011                elif typ == "copy":
1012                    self.pre_images.append(Copy(self.rd, self.path, pre_image))
1013                else:
1014                    raise ValueError(
1015                        f"mzbuild config in {self.path} has unknown pre-image type"
1016                    )
1017            self.build_args = data.pop("build-args", {})
1018
1019        if re.search(r"[^A-Za-z0-9\-]", self.name):
1020            raise ValueError(
1021                f"mzbuild image name {self.name} contains invalid character; only alphanumerics and hyphens allowed"
1022            )
1023
1024        self.depends_on: list[str] = []
1025        with open(self.path / "Dockerfile", "rb") as f:
1026            for line in f:
1027                match = self._DOCKERFILE_MZFROM_RE.match(line)
1028                if match:
1029                    self.depends_on.append(match.group(1).decode())
1030
1031    def sync_description(self) -> None:
1032        """Sync the description to Docker Hub if the image is publishable
1033        and a README.md file exists."""
1034
1035        if not self.publish:
1036            ui.say(f"{self.name} is not publishable")
1037            return
1038
1039        readme_path = self.path / "README.md"
1040        has_readme = readme_path.exists()
1041        if not has_readme:
1042            ui.say(f"{self.name} has no README.md or description")
1043            return
1044
1045        docker_config = os.getenv("DOCKER_CONFIG")
1046        spawn.runv(
1047            [
1048                "docker",
1049                "pushrm",
1050                f"--file={readme_path}",
1051                *([f"--config={docker_config}/config.json"] if docker_config else []),
1052                *([f"--short={self.description}"] if self.description else []),
1053                self.docker_name(),
1054            ]
1055        )
1056
1057    def docker_name(self, tag: str | None = None) -> str:
1058        """Return the name of the image on Docker Hub at the given tag."""
1059        name = f"{self.rd.image_registry}/{self.rd.image_prefix}{self.name}"
1060        if tag:
1061            name += f":{tag}"
1062        return name

A Docker image whose build and dependencies are managed by mzbuild.

An image corresponds to a directory in a repository that contains a mzbuild.yml file. This directory is called an "mzbuild context."

Attributes: name: The name of the image. publish: Whether the image should be pushed to Docker Hub. depends_on: The names of the images upon which this image depends. root: The path to the root of the associated Repository. path: The path to the directory containing the mzbuild.yml configuration file. pre_images: Optional actions to perform before running docker build. build_args: An optional list of --build-arg to pass to the dockerfile

Image( rd: RepositoryDetails, path: pathlib._local.Path)
 996    def __init__(self, rd: RepositoryDetails, path: Path):
 997        self.rd = rd
 998        self.path = path
 999        self._context_files_cache = None
1000        self.pre_images: list[PreImage] = []
1001        with open(self.path / "mzbuild.yml") as f:
1002            data = yaml.safe_load(f)
1003            self.name: str = data.pop("name")
1004            self.publish: bool = data.pop("publish", True)
1005            self.description: str | None = data.pop("description", None)
1006            self.mainline: bool = data.pop("mainline", True)
1007            for pre_image in data.pop("pre-image", []):
1008                typ = pre_image.pop("type", None)
1009                if typ == "cargo-build":
1010                    self.pre_images.append(CargoBuild(self.rd, self.path, pre_image))
1011                elif typ == "copy":
1012                    self.pre_images.append(Copy(self.rd, self.path, pre_image))
1013                else:
1014                    raise ValueError(
1015                        f"mzbuild config in {self.path} has unknown pre-image type"
1016                    )
1017            self.build_args = data.pop("build-args", {})
1018
1019        if re.search(r"[^A-Za-z0-9\-]", self.name):
1020            raise ValueError(
1021                f"mzbuild image name {self.name} contains invalid character; only alphanumerics and hyphens allowed"
1022            )
1023
1024        self.depends_on: list[str] = []
1025        with open(self.path / "Dockerfile", "rb") as f:
1026            for line in f:
1027                match = self._DOCKERFILE_MZFROM_RE.match(line)
1028                if match:
1029                    self.depends_on.append(match.group(1).decode())
rd
path
pre_images: list[PreImage]
depends_on: list[str]
def sync_description(self) -> None:
1031    def sync_description(self) -> None:
1032        """Sync the description to Docker Hub if the image is publishable
1033        and a README.md file exists."""
1034
1035        if not self.publish:
1036            ui.say(f"{self.name} is not publishable")
1037            return
1038
1039        readme_path = self.path / "README.md"
1040        has_readme = readme_path.exists()
1041        if not has_readme:
1042            ui.say(f"{self.name} has no README.md or description")
1043            return
1044
1045        docker_config = os.getenv("DOCKER_CONFIG")
1046        spawn.runv(
1047            [
1048                "docker",
1049                "pushrm",
1050                f"--file={readme_path}",
1051                *([f"--config={docker_config}/config.json"] if docker_config else []),
1052                *([f"--short={self.description}"] if self.description else []),
1053                self.docker_name(),
1054            ]
1055        )

Sync the description to Docker Hub if the image is publishable and a README.md file exists.

def docker_name(self, tag: str | None = None) -> str:
1057    def docker_name(self, tag: str | None = None) -> str:
1058        """Return the name of the image on Docker Hub at the given tag."""
1059        name = f"{self.rd.image_registry}/{self.rd.image_prefix}{self.name}"
1060        if tag:
1061            name += f":{tag}"
1062        return name

Return the name of the image on Docker Hub at the given tag.

class ResolvedImage:
1065class ResolvedImage:
1066    """An `Image` whose dependencies have been resolved.
1067
1068    Attributes:
1069        image: The underlying `Image`.
1070        acquired: Whether the image is available locally.
1071        dependencies: A mapping from dependency name to `ResolvedImage` for
1072            each of the images that `image` depends upon.
1073    """
1074
1075    def __init__(self, image: Image, dependencies: Iterable["ResolvedImage"]):
1076        self.image = image
1077        self.acquired = False
1078        self.dependencies = {}
1079        for d in dependencies:
1080            self.dependencies[d.name] = d
1081
1082    def __repr__(self) -> str:
1083        return f"ResolvedImage<{self.spec()}>"
1084
1085    @property
1086    def name(self) -> str:
1087        """The name of the underlying image."""
1088        return self.image.name
1089
1090    @property
1091    def publish(self) -> bool:
1092        """Whether the underlying image should be pushed to Docker Hub."""
1093        return self.image.publish
1094
1095    @cache
1096    def spec(self) -> str:
1097        """Return the "spec" for the image.
1098
1099        A spec is the unique identifier for the image given its current
1100        fingerprint. It is a valid Docker Hub name.
1101        """
1102        return self.image.docker_name(tag=f"mzbuild-{self.fingerprint()}")
1103
1104    def write_dockerfile(self) -> IO[bytes]:
1105        """Render the Dockerfile without mzbuild directives.
1106
1107        Returns:
1108            file: A handle to a temporary file containing the adjusted
1109                Dockerfile."""
1110        with open(self.image.path / "Dockerfile", "rb") as f:
1111            lines = f.readlines()
1112        f = TemporaryFile()
1113        for line in lines:
1114            match = Image._DOCKERFILE_MZFROM_RE.match(line)
1115            if match:
1116                image = match.group(1).decode()
1117                spec = self.dependencies[image].spec()
1118                line = Image._DOCKERFILE_MZFROM_RE.sub(b"FROM %b" % spec.encode(), line)
1119            f.write(line)
1120        f.seek(0)
1121        return f
1122
1123    def build(self, prep: dict[type[PreImage], Any], push: bool = False) -> None:
1124        """Build the image from source.
1125
1126        Requires that the caller has already acquired all dependencies and
1127        prepared all `PreImage` actions via `PreImage.prepare_batch`.
1128        """
1129        # Use a file lock to prevent parallel mzcompose processes from
1130        # racing on git clean / copy / strip for the same image directory.
1131        lock_dir = self.image.rd.root / "target" / "mzbuild-locks"
1132        lock_dir.mkdir(parents=True, exist_ok=True)
1133        profile = self.image.rd.profile.name.lower()
1134        lock_path = lock_dir / f"{self.image.name}-{profile}.lock"
1135        with open(lock_path, "w") as lock_file:
1136            ui.say(f"Acquiring lock for {self.spec()}")
1137            fcntl.flock(lock_file, fcntl.LOCK_EX)
1138            try:
1139                self._build_locked(prep, push)
1140            finally:
1141                fcntl.flock(lock_file, fcntl.LOCK_UN)
1142        self.acquired = True
1143        docker_images().add(self.spec())
1144
1145    def _build_locked(
1146        self, prep: dict[type[PreImage], Any], push: bool = False
1147    ) -> None:
1148        ui.section(f"Building {self.spec()}")
1149        spawn.runv(["git", "clean", "-ffdX", self.image.path])
1150
1151        for pre_image in self.image.pre_images:
1152            pre_image.run(prep[type(pre_image)])
1153        build_args = {
1154            **self.image.build_args,
1155            "BUILD_PROFILE": self.image.rd.profile.name,
1156            "ARCH_GCC": str(self.image.rd.arch),
1157            "ARCH_GO": self.image.rd.arch.go_str(),
1158            "CI_SANITIZER": str(self.image.rd.sanitizer),
1159        }
1160        f = self.write_dockerfile()
1161
1162        try:
1163            spawn.capture(["docker", "buildx", "version"])
1164        except subprocess.CalledProcessError:
1165            if push:
1166                print(
1167                    "docker buildx not found, required to push images. Installation: https://github.com/docker/buildx?tab=readme-ov-file#installing"
1168                )
1169                raise
1170            print(
1171                "docker buildx not found, you can install it to build faster. Installation: https://github.com/docker/buildx?tab=readme-ov-file#installing"
1172            )
1173            print("Falling back to docker build")
1174            cmd: Sequence[str] = [
1175                "docker",
1176                "build",
1177                "-f",
1178                "-",
1179                *(f"--build-arg={k}={v}" for k, v in build_args.items()),
1180                "-t",
1181                self.spec(),
1182                f"--platform=linux/{self.image.rd.arch.go_str()}",
1183                str(self.image.path),
1184            ]
1185        else:
1186            # `self.spec()` may already be ghcr-qualified (MZ_GHCR), so strip the
1187            # prefix before re-deriving each tag. Otherwise they double-prefix and
1188            # a dependent image's `FROM self.spec()` can't resolve the local build.
1189            spec = self.spec()
1190            if spec.startswith(GHCR_PREFIX):
1191                spec = spec.removeprefix(GHCR_PREFIX)
1192            docker_tag = f"docker.io/{spec}"
1193            ghcr_tag = f"{GHCR_PREFIX}{spec}"
1194            cmd: Sequence[str] = [
1195                "docker",
1196                "buildx",
1197                "build",
1198                "--progress=plain",  # less noisy
1199                "-f",
1200                "-",
1201                *(f"--build-arg={k}={v}" for k, v in build_args.items()),
1202                "-t",
1203                docker_tag,
1204                "-t",
1205                ghcr_tag,
1206                f"--platform=linux/{self.image.rd.arch.go_str()}",
1207                str(self.image.path),
1208                "--load",
1209            ]
1210
1211        if token := os.getenv("GITHUB_GHCR_TOKEN"):
1212            spawn.runv(
1213                [
1214                    "docker",
1215                    "login",
1216                    "ghcr.io",
1217                    "-u",
1218                    "materialize-bot",
1219                    "--password-stdin",
1220                ],
1221                stdin=token.encode(),
1222            )
1223
1224        spawn.runv(cmd, stdin=f, stdout=sys.stderr.buffer)
1225
1226        if push:
1227            # Push to both registries in parallel. With the docker driver,
1228            # the image is already in the local daemon after --load, so
1229            # docker push is the same mechanism buildx --push uses internally.
1230            pending = [docker_tag, ghcr_tag]
1231            for sleep_time in [5, 10, 20, 40, 60, None]:
1232                procs = [
1233                    subprocess.Popen(
1234                        ["docker", "push", tag],
1235                        stdout=sys.stderr,
1236                        stderr=sys.stderr,
1237                    )
1238                    for tag in pending
1239                ]
1240                pending = [tag for tag, proc in zip(pending, procs) if proc.wait() != 0]
1241                if not pending:
1242                    break
1243                if sleep_time is None:
1244                    raise subprocess.CalledProcessError(
1245                        1, ["docker", "push", pending[0]]
1246                    )
1247                print(f"docker push failed for {pending}, retrying in {sleep_time}s")
1248                time.sleep(sleep_time)
1249
1250    def try_pull(self, max_retries: int) -> bool:
1251        """Download the image if it does not exist locally. Returns whether it was found."""
1252        command = ["docker", "pull"]
1253        # --quiet skips printing the progress bar, which does not display well in CI.
1254        if ui.env_is_truthy("CI"):
1255            command.append("--quiet")
1256        command.append(self.spec())
1257        if not self.acquired:
1258            ui.header(f"Acquiring {self.spec()}")
1259            sleep_time = 1
1260            for retry in range(1, max_retries + 1):
1261                try:
1262                    spawn.runv(
1263                        command,
1264                        stdin=subprocess.DEVNULL,
1265                        stdout=sys.stderr.buffer,
1266                    )
1267                    self.acquired = True
1268                    docker_images().add(self.spec())
1269                    break
1270                except subprocess.CalledProcessError:
1271                    if retry < max_retries:
1272                        # There seems to be no good way to tell what error
1273                        # happened based on error code
1274                        # (https://github.com/docker/cli/issues/538) and we
1275                        # want to print output directly to terminal.
1276                        print(f"Retrying in {sleep_time}s ...")
1277                        time.sleep(sleep_time)
1278                        sleep_time = min(sleep_time * 2, 10)
1279                        continue
1280                    else:
1281                        break
1282        return self.acquired
1283
1284    def is_published_if_necessary(self) -> bool:
1285        """Report whether the image exists on DockerHub & GHCR if it is publishable."""
1286        if not self.publish:
1287            return False
1288        spec = self.spec()
1289        if spec.startswith(GHCR_PREFIX):
1290            spec = spec.removeprefix(GHCR_PREFIX)
1291        ghcr_spec = f"{GHCR_PREFIX}{spec}"
1292        if is_docker_image_pushed(spec) and is_ghcr_image_pushed(ghcr_spec):
1293            ui.say(f"{spec} already exists")
1294            return True
1295        return False
1296
1297    def is_public(self) -> tuple[bool | None, bool | None]:
1298        """Report whether the image's repo is public on (Docker Hub, GHCR).
1299
1300        Each element is True (public), False (private/absent), or None (could
1301        not determine). Non-publishable images are reported as public on both,
1302        since they are never pushed and so the check does not apply to them.
1303        """
1304        if not self.publish:
1305            return (True, True)
1306        spec = self.spec()
1307        if spec.startswith(GHCR_PREFIX):
1308            spec = spec.removeprefix(GHCR_PREFIX)
1309        ghcr_spec = f"{GHCR_PREFIX}{spec}"
1310        return (is_docker_image_public(spec), is_ghcr_image_public(ghcr_spec))
1311
1312    def run(
1313        self,
1314        args: list[str] = [],
1315        docker_args: list[str] = [],
1316        env: dict[str, str] = {},
1317    ) -> None:
1318        """Run a command in the image.
1319
1320        Creates a container from the image and runs the command described by
1321        `args` in the image.
1322        """
1323        envs = []
1324        for key, val in env.items():
1325            envs.extend(["--env", f"{key}={val}"])
1326        spawn.runv(
1327            [
1328                "docker",
1329                "run",
1330                "--tty",
1331                "--rm",
1332                *envs,
1333                "--init",
1334                *docker_args,
1335                self.spec(),
1336                *args,
1337            ],
1338        )
1339
1340    def list_dependencies(self, transitive: bool = False) -> set[str]:
1341        out = set()
1342        for dep in self.dependencies.values():
1343            out.add(dep.name)
1344            if transitive:
1345                out |= dep.list_dependencies(transitive)
1346        return out
1347
1348    @cache
1349    def inputs(self, transitive: bool = False) -> set[str]:
1350        """List the files tracked as inputs to the image.
1351
1352        These files are used to compute the fingerprint for the image. See
1353        `ResolvedImage.fingerprint` for details.
1354
1355        Returns:
1356            inputs: A list of input files, relative to the root of the
1357                repository.
1358        """
1359        if self.image._context_files_cache is not None:
1360            paths = set(self.image._context_files_cache)
1361        else:
1362            paths = set(git.expand_globs(self.image.rd.root, f"{self.image.path}/**"))
1363        if not paths:
1364            # While we could find an `mzbuild.yml` file for this service, expland_globs didn't
1365            # return any files that matched this service. At the very least, the `mzbuild.yml`
1366            # file itself should have been returned. We have a bug if paths is empty.
1367            raise AssertionError(
1368                f"{self.image.name} mzbuild exists but its files are unknown to git"
1369            )
1370        for pre_image in self.image.pre_images:
1371            paths |= pre_image.inputs()
1372        if transitive:
1373            for dep in self.dependencies.values():
1374                paths |= dep.inputs(transitive)
1375        return paths
1376
1377    @cache
1378    def fingerprint(self) -> Fingerprint:
1379        """Fingerprint the inputs to the image.
1380
1381        Compute the fingerprint of the image. Changing the contents of any of
1382        the files or adding or removing files to the image will change the
1383        fingerprint, as will modifying the inputs to any of its dependencies.
1384
1385        The image considers all non-gitignored files in its mzbuild context to
1386        be inputs. If it has a pre-image action, that action may add additional
1387        inputs via `PreImage.inputs`.
1388        """
1389        self_hash = hashlib.sha1()
1390        # When inputs come from precomputed sources (crate and image context
1391        # batching + resolved CargoPreImage paths), they are already individual
1392        # file paths from git. Skip the expensive expand_globs subprocess calls.
1393        inputs = self.inputs()
1394        if self.image._context_files_cache is not None:
1395            resolved_inputs = sorted(inputs)
1396        else:
1397            resolved_inputs = sorted(set(git.expand_globs(self.image.rd.root, *inputs)))
1398        for rel_path in resolved_inputs:
1399            abs_path = self.image.rd.root / rel_path
1400            file_hash = hashlib.sha1()
1401            raw_file_mode = os.lstat(abs_path).st_mode
1402            # Compute a simplified file mode using the same rules as Git.
1403            # https://github.com/git/git/blob/3bab5d562/Documentation/git-fast-import.txt#L610-L616
1404            if stat.S_ISLNK(raw_file_mode):
1405                file_mode = 0o120000
1406            elif raw_file_mode & stat.S_IXUSR:
1407                file_mode = 0o100755
1408            else:
1409                file_mode = 0o100644
1410            with open(abs_path, "rb") as f:
1411                file_hash.update(f.read())
1412            self_hash.update(file_mode.to_bytes(2, byteorder="big"))
1413            self_hash.update(rel_path.encode())
1414            self_hash.update(file_hash.digest())
1415            self_hash.update(b"\0")
1416
1417        for pre_image in self.image.pre_images:
1418            self_hash.update(pre_image.extra().encode())
1419            self_hash.update(b"\0")
1420
1421        self_hash.update(f"profile={self.image.rd.profile}".encode())
1422        self_hash.update(f"arch={self.image.rd.arch}".encode())
1423        self_hash.update(f"coverage={self.image.rd.coverage}".encode())
1424        self_hash.update(f"sanitizer={self.image.rd.sanitizer}".encode())
1425        # This exists to make sure all hashes from before we had a GHCR mirror are invalidated, so that we rebuild when an image doesn't exist on GHCR yet
1426        self_hash.update(b"mirror=ghcr")
1427
1428        full_hash = hashlib.sha1()
1429        full_hash.update(self_hash.digest())
1430        for dep in sorted(self.dependencies.values(), key=lambda d: d.name):
1431            full_hash.update(dep.name.encode())
1432            full_hash.update(dep.fingerprint())
1433            full_hash.update(b"\0")
1434
1435        return Fingerprint(full_hash.digest())

An Image whose dependencies have been resolved.

Attributes: image: The underlying Image. acquired: Whether the image is available locally. dependencies: A mapping from dependency name to ResolvedImage for each of the images that image depends upon.

ResolvedImage( image: Image, dependencies: Iterable[ResolvedImage])
1075    def __init__(self, image: Image, dependencies: Iterable["ResolvedImage"]):
1076        self.image = image
1077        self.acquired = False
1078        self.dependencies = {}
1079        for d in dependencies:
1080            self.dependencies[d.name] = d
image
acquired
dependencies
name: str
1085    @property
1086    def name(self) -> str:
1087        """The name of the underlying image."""
1088        return self.image.name

The name of the underlying image.

publish: bool
1090    @property
1091    def publish(self) -> bool:
1092        """Whether the underlying image should be pushed to Docker Hub."""
1093        return self.image.publish

Whether the underlying image should be pushed to Docker Hub.

@cache
def spec(self) -> str:
1095    @cache
1096    def spec(self) -> str:
1097        """Return the "spec" for the image.
1098
1099        A spec is the unique identifier for the image given its current
1100        fingerprint. It is a valid Docker Hub name.
1101        """
1102        return self.image.docker_name(tag=f"mzbuild-{self.fingerprint()}")

Return the "spec" for the image.

A spec is the unique identifier for the image given its current fingerprint. It is a valid Docker Hub name.

def write_dockerfile(self) -> IO[bytes]:
1104    def write_dockerfile(self) -> IO[bytes]:
1105        """Render the Dockerfile without mzbuild directives.
1106
1107        Returns:
1108            file: A handle to a temporary file containing the adjusted
1109                Dockerfile."""
1110        with open(self.image.path / "Dockerfile", "rb") as f:
1111            lines = f.readlines()
1112        f = TemporaryFile()
1113        for line in lines:
1114            match = Image._DOCKERFILE_MZFROM_RE.match(line)
1115            if match:
1116                image = match.group(1).decode()
1117                spec = self.dependencies[image].spec()
1118                line = Image._DOCKERFILE_MZFROM_RE.sub(b"FROM %b" % spec.encode(), line)
1119            f.write(line)
1120        f.seek(0)
1121        return f

Render the Dockerfile without mzbuild directives.

Returns: file: A handle to a temporary file containing the adjusted Dockerfile.

def build( self, prep: dict[type[PreImage], typing.Any], push: bool = False) -> None:
1123    def build(self, prep: dict[type[PreImage], Any], push: bool = False) -> None:
1124        """Build the image from source.
1125
1126        Requires that the caller has already acquired all dependencies and
1127        prepared all `PreImage` actions via `PreImage.prepare_batch`.
1128        """
1129        # Use a file lock to prevent parallel mzcompose processes from
1130        # racing on git clean / copy / strip for the same image directory.
1131        lock_dir = self.image.rd.root / "target" / "mzbuild-locks"
1132        lock_dir.mkdir(parents=True, exist_ok=True)
1133        profile = self.image.rd.profile.name.lower()
1134        lock_path = lock_dir / f"{self.image.name}-{profile}.lock"
1135        with open(lock_path, "w") as lock_file:
1136            ui.say(f"Acquiring lock for {self.spec()}")
1137            fcntl.flock(lock_file, fcntl.LOCK_EX)
1138            try:
1139                self._build_locked(prep, push)
1140            finally:
1141                fcntl.flock(lock_file, fcntl.LOCK_UN)
1142        self.acquired = True
1143        docker_images().add(self.spec())

Build the image from source.

Requires that the caller has already acquired all dependencies and prepared all PreImage actions via PreImage.prepare_batch.

def try_pull(self, max_retries: int) -> bool:
1250    def try_pull(self, max_retries: int) -> bool:
1251        """Download the image if it does not exist locally. Returns whether it was found."""
1252        command = ["docker", "pull"]
1253        # --quiet skips printing the progress bar, which does not display well in CI.
1254        if ui.env_is_truthy("CI"):
1255            command.append("--quiet")
1256        command.append(self.spec())
1257        if not self.acquired:
1258            ui.header(f"Acquiring {self.spec()}")
1259            sleep_time = 1
1260            for retry in range(1, max_retries + 1):
1261                try:
1262                    spawn.runv(
1263                        command,
1264                        stdin=subprocess.DEVNULL,
1265                        stdout=sys.stderr.buffer,
1266                    )
1267                    self.acquired = True
1268                    docker_images().add(self.spec())
1269                    break
1270                except subprocess.CalledProcessError:
1271                    if retry < max_retries:
1272                        # There seems to be no good way to tell what error
1273                        # happened based on error code
1274                        # (https://github.com/docker/cli/issues/538) and we
1275                        # want to print output directly to terminal.
1276                        print(f"Retrying in {sleep_time}s ...")
1277                        time.sleep(sleep_time)
1278                        sleep_time = min(sleep_time * 2, 10)
1279                        continue
1280                    else:
1281                        break
1282        return self.acquired

Download the image if it does not exist locally. Returns whether it was found.

def is_published_if_necessary(self) -> bool:
1284    def is_published_if_necessary(self) -> bool:
1285        """Report whether the image exists on DockerHub & GHCR if it is publishable."""
1286        if not self.publish:
1287            return False
1288        spec = self.spec()
1289        if spec.startswith(GHCR_PREFIX):
1290            spec = spec.removeprefix(GHCR_PREFIX)
1291        ghcr_spec = f"{GHCR_PREFIX}{spec}"
1292        if is_docker_image_pushed(spec) and is_ghcr_image_pushed(ghcr_spec):
1293            ui.say(f"{spec} already exists")
1294            return True
1295        return False

Report whether the image exists on DockerHub & GHCR if it is publishable.

def is_public(self) -> tuple[bool | None, bool | None]:
1297    def is_public(self) -> tuple[bool | None, bool | None]:
1298        """Report whether the image's repo is public on (Docker Hub, GHCR).
1299
1300        Each element is True (public), False (private/absent), or None (could
1301        not determine). Non-publishable images are reported as public on both,
1302        since they are never pushed and so the check does not apply to them.
1303        """
1304        if not self.publish:
1305            return (True, True)
1306        spec = self.spec()
1307        if spec.startswith(GHCR_PREFIX):
1308            spec = spec.removeprefix(GHCR_PREFIX)
1309        ghcr_spec = f"{GHCR_PREFIX}{spec}"
1310        return (is_docker_image_public(spec), is_ghcr_image_public(ghcr_spec))

Report whether the image's repo is public on (Docker Hub, GHCR).

Each element is True (public), False (private/absent), or None (could not determine). Non-publishable images are reported as public on both, since they are never pushed and so the check does not apply to them.

def run( self, args: list[str] = [], docker_args: list[str] = [], env: dict[str, str] = {}) -> None:
1312    def run(
1313        self,
1314        args: list[str] = [],
1315        docker_args: list[str] = [],
1316        env: dict[str, str] = {},
1317    ) -> None:
1318        """Run a command in the image.
1319
1320        Creates a container from the image and runs the command described by
1321        `args` in the image.
1322        """
1323        envs = []
1324        for key, val in env.items():
1325            envs.extend(["--env", f"{key}={val}"])
1326        spawn.runv(
1327            [
1328                "docker",
1329                "run",
1330                "--tty",
1331                "--rm",
1332                *envs,
1333                "--init",
1334                *docker_args,
1335                self.spec(),
1336                *args,
1337            ],
1338        )

Run a command in the image.

Creates a container from the image and runs the command described by args in the image.

def list_dependencies(self, transitive: bool = False) -> set[str]:
1340    def list_dependencies(self, transitive: bool = False) -> set[str]:
1341        out = set()
1342        for dep in self.dependencies.values():
1343            out.add(dep.name)
1344            if transitive:
1345                out |= dep.list_dependencies(transitive)
1346        return out
@cache
def inputs(self, transitive: bool = False) -> set[str]:
1348    @cache
1349    def inputs(self, transitive: bool = False) -> set[str]:
1350        """List the files tracked as inputs to the image.
1351
1352        These files are used to compute the fingerprint for the image. See
1353        `ResolvedImage.fingerprint` for details.
1354
1355        Returns:
1356            inputs: A list of input files, relative to the root of the
1357                repository.
1358        """
1359        if self.image._context_files_cache is not None:
1360            paths = set(self.image._context_files_cache)
1361        else:
1362            paths = set(git.expand_globs(self.image.rd.root, f"{self.image.path}/**"))
1363        if not paths:
1364            # While we could find an `mzbuild.yml` file for this service, expland_globs didn't
1365            # return any files that matched this service. At the very least, the `mzbuild.yml`
1366            # file itself should have been returned. We have a bug if paths is empty.
1367            raise AssertionError(
1368                f"{self.image.name} mzbuild exists but its files are unknown to git"
1369            )
1370        for pre_image in self.image.pre_images:
1371            paths |= pre_image.inputs()
1372        if transitive:
1373            for dep in self.dependencies.values():
1374                paths |= dep.inputs(transitive)
1375        return paths

List the files tracked as inputs to the image.

These files are used to compute the fingerprint for the image. See ResolvedImage.fingerprint for details.

Returns: inputs: A list of input files, relative to the root of the repository.

@cache
def fingerprint(self) -> Fingerprint:
1377    @cache
1378    def fingerprint(self) -> Fingerprint:
1379        """Fingerprint the inputs to the image.
1380
1381        Compute the fingerprint of the image. Changing the contents of any of
1382        the files or adding or removing files to the image will change the
1383        fingerprint, as will modifying the inputs to any of its dependencies.
1384
1385        The image considers all non-gitignored files in its mzbuild context to
1386        be inputs. If it has a pre-image action, that action may add additional
1387        inputs via `PreImage.inputs`.
1388        """
1389        self_hash = hashlib.sha1()
1390        # When inputs come from precomputed sources (crate and image context
1391        # batching + resolved CargoPreImage paths), they are already individual
1392        # file paths from git. Skip the expensive expand_globs subprocess calls.
1393        inputs = self.inputs()
1394        if self.image._context_files_cache is not None:
1395            resolved_inputs = sorted(inputs)
1396        else:
1397            resolved_inputs = sorted(set(git.expand_globs(self.image.rd.root, *inputs)))
1398        for rel_path in resolved_inputs:
1399            abs_path = self.image.rd.root / rel_path
1400            file_hash = hashlib.sha1()
1401            raw_file_mode = os.lstat(abs_path).st_mode
1402            # Compute a simplified file mode using the same rules as Git.
1403            # https://github.com/git/git/blob/3bab5d562/Documentation/git-fast-import.txt#L610-L616
1404            if stat.S_ISLNK(raw_file_mode):
1405                file_mode = 0o120000
1406            elif raw_file_mode & stat.S_IXUSR:
1407                file_mode = 0o100755
1408            else:
1409                file_mode = 0o100644
1410            with open(abs_path, "rb") as f:
1411                file_hash.update(f.read())
1412            self_hash.update(file_mode.to_bytes(2, byteorder="big"))
1413            self_hash.update(rel_path.encode())
1414            self_hash.update(file_hash.digest())
1415            self_hash.update(b"\0")
1416
1417        for pre_image in self.image.pre_images:
1418            self_hash.update(pre_image.extra().encode())
1419            self_hash.update(b"\0")
1420
1421        self_hash.update(f"profile={self.image.rd.profile}".encode())
1422        self_hash.update(f"arch={self.image.rd.arch}".encode())
1423        self_hash.update(f"coverage={self.image.rd.coverage}".encode())
1424        self_hash.update(f"sanitizer={self.image.rd.sanitizer}".encode())
1425        # This exists to make sure all hashes from before we had a GHCR mirror are invalidated, so that we rebuild when an image doesn't exist on GHCR yet
1426        self_hash.update(b"mirror=ghcr")
1427
1428        full_hash = hashlib.sha1()
1429        full_hash.update(self_hash.digest())
1430        for dep in sorted(self.dependencies.values(), key=lambda d: d.name):
1431            full_hash.update(dep.name.encode())
1432            full_hash.update(dep.fingerprint())
1433            full_hash.update(b"\0")
1434
1435        return Fingerprint(full_hash.digest())

Fingerprint the inputs to the image.

Compute the fingerprint of the image. Changing the contents of any of the files or adding or removing files to the image will change the fingerprint, as will modifying the inputs to any of its dependencies.

The image considers all non-gitignored files in its mzbuild context to be inputs. If it has a pre-image action, that action may add additional inputs via PreImage.inputs.

class DependencySet:
1438class DependencySet:
1439    """A set of `ResolvedImage`s.
1440
1441    Iterating over a dependency set yields the contained images in an arbitrary
1442    order. Indexing a dependency set yields the image with the specified name.
1443    """
1444
1445    def __init__(self, dependencies: Iterable[Image]):
1446        """Construct a new `DependencySet`.
1447
1448        The provided `dependencies` must be topologically sorted.
1449        """
1450        self._dependencies: dict[str, ResolvedImage] = {}
1451        dependencies = list(dependencies)
1452        known_images = docker_images() if dependencies else set()
1453        for d in dependencies:
1454            image = ResolvedImage(
1455                image=d,
1456                dependencies=(self._dependencies[d0] for d0 in d.depends_on),
1457            )
1458            image.acquired = image.spec() in known_images
1459            self._dependencies[d.name] = image
1460
1461    def _prepare_batch(self, images: list[ResolvedImage]) -> dict[type[PreImage], Any]:
1462        pre_images = collections.defaultdict(list)
1463        for image in images:
1464            for pre_image in image.image.pre_images:
1465                pre_images[type(pre_image)].append(pre_image)
1466        pre_image_prep = {}
1467        for cls, instances in pre_images.items():
1468            pre_image = cast(PreImage, cls)
1469            pre_image_prep[cls] = pre_image.prepare_batch(instances)
1470        return pre_image_prep
1471
1472    def acquire(self, max_retries: int | None = None) -> None:
1473        """Download or build all of the images in the dependency set that do not
1474        already exist locally.
1475
1476        Args:
1477            max_retries: Number of retries on failure.
1478        """
1479
1480        # Only retry in CI runs since we struggle with flaky docker pulls there
1481        if not max_retries:
1482            max_retries = (
1483                5
1484                if ui.env_is_truthy("CI")
1485                and not ui.env_is_truthy("CI_ALLOW_LOCAL_BUILD")
1486                else 1
1487            )
1488        assert max_retries > 0
1489
1490        deps_to_check = [dep for dep in self if dep.publish]
1491        deps_to_build = [dep for dep in self if not dep.publish]
1492        if len(deps_to_check):
1493            with ThreadPoolExecutor(max_workers=len(deps_to_check)) as executor:
1494                futures = [
1495                    executor.submit(dep.try_pull, max_retries) for dep in deps_to_check
1496                ]
1497                for dep, future in zip(deps_to_check, futures):
1498                    try:
1499                        if not future.result():
1500                            deps_to_build.append(dep)
1501                    except Exception:
1502                        deps_to_build.append(dep)
1503
1504        # Don't attempt to build in CI, as our timeouts and small machines won't allow it anyway
1505        if ui.env_is_truthy("CI") and not ui.env_is_truthy("CI_ALLOW_LOCAL_BUILD"):
1506            expected_deps = [dep for dep in deps_to_build if dep.publish]
1507            if expected_deps:
1508                print(
1509                    f"+++ Expected builds to be available, the build probably failed, so not proceeding: {expected_deps}"
1510                )
1511                sys.exit(128)
1512
1513        prep = self._prepare_batch(deps_to_build)
1514        for dep in deps_to_build:
1515            dep.build(prep)
1516
1517    def ensure(self, pre_build: Callable[[list[ResolvedImage]], None] | None = None):
1518        """Ensure all publishable images in this dependency set exist on Docker
1519        Hub.
1520
1521        Images are pushed using their spec as their tag.
1522
1523        Args:
1524            pre_build: A callback to invoke with all dependency that are going
1525                       to be built locally, invoked after their cargo build is
1526                       done, but before the Docker images are build and
1527                       uploaded to DockerHub.
1528        """
1529        num_deps = len(list(self))
1530        if not num_deps:
1531            deps_to_build = []
1532        else:
1533            with ThreadPoolExecutor(max_workers=num_deps) as executor:
1534                futures = list(
1535                    executor.map(
1536                        lambda dep: (dep, not dep.is_published_if_necessary()), self
1537                    )
1538                )
1539
1540            deps_to_build = [dep for dep, should_build in futures if should_build]
1541
1542        prep = self._prepare_batch(deps_to_build)
1543        if pre_build:
1544            pre_build(deps_to_build)
1545        lock = Lock()
1546        built_deps: set[str] = set([dep.name for dep in self]) - set(
1547            [dep.name for dep in deps_to_build]
1548        )
1549
1550        def build_dep(dep):
1551            end_time = time.time() + 1200
1552            while True:
1553                if time.time() > end_time:
1554                    raise TimeoutError(
1555                        f"Timed out in {dep.name} waiting for {[dep2 for dep2 in dep.dependencies if dep2 not in built_deps]}"
1556                    )
1557                with lock:
1558                    if all(dep2 in built_deps for dep2 in dep.dependencies):
1559                        break
1560                time.sleep(0.01)
1561            for attempts_remaining in reversed(range(3)):
1562                try:
1563                    dep.build(prep, push=dep.publish)
1564                    with lock:
1565                        built_deps.add(dep.name)
1566                    break
1567                except Exception:
1568                    if not dep.publish or attempts_remaining == 0:
1569                        raise
1570
1571        if deps_to_build:
1572            with ThreadPoolExecutor(max_workers=len(deps_to_build)) as executor:
1573                futures = [executor.submit(build_dep, dep) for dep in deps_to_build]
1574                for future in as_completed(futures):
1575                    future.result()
1576
1577    def check(self) -> bool:
1578        """Check all publishable images in this dependency set exist on Docker
1579        Hub. Don't try to download or build them."""
1580        num_deps = len(list(self))
1581        if num_deps == 0:
1582            return True
1583        with ThreadPoolExecutor(max_workers=num_deps) as executor:
1584            results = list(
1585                executor.map(lambda dep: dep.is_published_if_necessary(), list(self))
1586            )
1587        return all(results)
1588
1589    def __iter__(self) -> Iterator[ResolvedImage]:
1590        return iter(self._dependencies.values())
1591
1592    def __getitem__(self, key: str) -> ResolvedImage:
1593        return self._dependencies[key]

A set of ResolvedImages.

Iterating over a dependency set yields the contained images in an arbitrary order. Indexing a dependency set yields the image with the specified name.

DependencySet(dependencies: Iterable[Image])
1445    def __init__(self, dependencies: Iterable[Image]):
1446        """Construct a new `DependencySet`.
1447
1448        The provided `dependencies` must be topologically sorted.
1449        """
1450        self._dependencies: dict[str, ResolvedImage] = {}
1451        dependencies = list(dependencies)
1452        known_images = docker_images() if dependencies else set()
1453        for d in dependencies:
1454            image = ResolvedImage(
1455                image=d,
1456                dependencies=(self._dependencies[d0] for d0 in d.depends_on),
1457            )
1458            image.acquired = image.spec() in known_images
1459            self._dependencies[d.name] = image

Construct a new DependencySet.

The provided dependencies must be topologically sorted.

def acquire(self, max_retries: int | None = None) -> None:
1472    def acquire(self, max_retries: int | None = None) -> None:
1473        """Download or build all of the images in the dependency set that do not
1474        already exist locally.
1475
1476        Args:
1477            max_retries: Number of retries on failure.
1478        """
1479
1480        # Only retry in CI runs since we struggle with flaky docker pulls there
1481        if not max_retries:
1482            max_retries = (
1483                5
1484                if ui.env_is_truthy("CI")
1485                and not ui.env_is_truthy("CI_ALLOW_LOCAL_BUILD")
1486                else 1
1487            )
1488        assert max_retries > 0
1489
1490        deps_to_check = [dep for dep in self if dep.publish]
1491        deps_to_build = [dep for dep in self if not dep.publish]
1492        if len(deps_to_check):
1493            with ThreadPoolExecutor(max_workers=len(deps_to_check)) as executor:
1494                futures = [
1495                    executor.submit(dep.try_pull, max_retries) for dep in deps_to_check
1496                ]
1497                for dep, future in zip(deps_to_check, futures):
1498                    try:
1499                        if not future.result():
1500                            deps_to_build.append(dep)
1501                    except Exception:
1502                        deps_to_build.append(dep)
1503
1504        # Don't attempt to build in CI, as our timeouts and small machines won't allow it anyway
1505        if ui.env_is_truthy("CI") and not ui.env_is_truthy("CI_ALLOW_LOCAL_BUILD"):
1506            expected_deps = [dep for dep in deps_to_build if dep.publish]
1507            if expected_deps:
1508                print(
1509                    f"+++ Expected builds to be available, the build probably failed, so not proceeding: {expected_deps}"
1510                )
1511                sys.exit(128)
1512
1513        prep = self._prepare_batch(deps_to_build)
1514        for dep in deps_to_build:
1515            dep.build(prep)

Download or build all of the images in the dependency set that do not already exist locally.

Args: max_retries: Number of retries on failure.

def ensure( self, pre_build: Callable[[list[ResolvedImage]], None] | None = None):
1517    def ensure(self, pre_build: Callable[[list[ResolvedImage]], None] | None = None):
1518        """Ensure all publishable images in this dependency set exist on Docker
1519        Hub.
1520
1521        Images are pushed using their spec as their tag.
1522
1523        Args:
1524            pre_build: A callback to invoke with all dependency that are going
1525                       to be built locally, invoked after their cargo build is
1526                       done, but before the Docker images are build and
1527                       uploaded to DockerHub.
1528        """
1529        num_deps = len(list(self))
1530        if not num_deps:
1531            deps_to_build = []
1532        else:
1533            with ThreadPoolExecutor(max_workers=num_deps) as executor:
1534                futures = list(
1535                    executor.map(
1536                        lambda dep: (dep, not dep.is_published_if_necessary()), self
1537                    )
1538                )
1539
1540            deps_to_build = [dep for dep, should_build in futures if should_build]
1541
1542        prep = self._prepare_batch(deps_to_build)
1543        if pre_build:
1544            pre_build(deps_to_build)
1545        lock = Lock()
1546        built_deps: set[str] = set([dep.name for dep in self]) - set(
1547            [dep.name for dep in deps_to_build]
1548        )
1549
1550        def build_dep(dep):
1551            end_time = time.time() + 1200
1552            while True:
1553                if time.time() > end_time:
1554                    raise TimeoutError(
1555                        f"Timed out in {dep.name} waiting for {[dep2 for dep2 in dep.dependencies if dep2 not in built_deps]}"
1556                    )
1557                with lock:
1558                    if all(dep2 in built_deps for dep2 in dep.dependencies):
1559                        break
1560                time.sleep(0.01)
1561            for attempts_remaining in reversed(range(3)):
1562                try:
1563                    dep.build(prep, push=dep.publish)
1564                    with lock:
1565                        built_deps.add(dep.name)
1566                    break
1567                except Exception:
1568                    if not dep.publish or attempts_remaining == 0:
1569                        raise
1570
1571        if deps_to_build:
1572            with ThreadPoolExecutor(max_workers=len(deps_to_build)) as executor:
1573                futures = [executor.submit(build_dep, dep) for dep in deps_to_build]
1574                for future in as_completed(futures):
1575                    future.result()

Ensure all publishable images in this dependency set exist on Docker Hub.

Images are pushed using their spec as their tag.

Args: pre_build: A callback to invoke with all dependency that are going to be built locally, invoked after their cargo build is done, but before the Docker images are build and uploaded to DockerHub.

def check(self) -> bool:
1577    def check(self) -> bool:
1578        """Check all publishable images in this dependency set exist on Docker
1579        Hub. Don't try to download or build them."""
1580        num_deps = len(list(self))
1581        if num_deps == 0:
1582            return True
1583        with ThreadPoolExecutor(max_workers=num_deps) as executor:
1584            results = list(
1585                executor.map(lambda dep: dep.is_published_if_necessary(), list(self))
1586            )
1587        return all(results)

Check all publishable images in this dependency set exist on Docker Hub. Don't try to download or build them.

class Repository:
1596class Repository:
1597    """A collection of mzbuild `Image`s.
1598
1599    Creating a repository will walk the filesystem beneath `root` to
1600    automatically discover all contained `Image`s.
1601
1602    Iterating over a repository yields the contained images in an arbitrary
1603    order.
1604
1605    Args:
1606        root: The path to the root of the repository.
1607        arch: The CPU architecture to build for.
1608        profile: What profile to build the repository in.
1609        coverage: Whether to enable code coverage instrumentation.
1610        sanitizer: Whether to a sanitizer (address, thread, leak, memory, none)
1611        image_registry: The Docker image registry to pull images from and push
1612            images to.
1613        image_prefix: A prefix to apply to all Docker image names.
1614
1615    Attributes:
1616        images: A mapping from image name to `Image` for all contained images.
1617        compose_dirs: The set of directories containing a `mzcompose.py` file.
1618    """
1619
1620    def __init__(
1621        self,
1622        root: Path,
1623        arch: Arch = Arch.host(),
1624        profile: Profile = (
1625            Profile.RELEASE if ui.env_is_truthy("CI_LTO") else Profile.OPTIMIZED
1626        ),
1627        coverage: bool = False,
1628        sanitizer: Sanitizer = Sanitizer.none,
1629        image_registry: str = image_registry(),
1630        image_prefix: str = "",
1631    ):
1632        self.rd = RepositoryDetails(
1633            root,
1634            arch,
1635            profile,
1636            coverage,
1637            sanitizer,
1638            image_registry,
1639            image_prefix,
1640        )
1641        self.images: dict[str, Image] = {}
1642        self.compositions: dict[str, Path] = {}
1643        for rel_path_s in sorted(
1644            git.expand_globs(self.root, "**/mzbuild.yml", "**/mzcompose.py")
1645        ):
1646            rel_path = Path(rel_path_s)
1647            if rel_path.parts[:2] == ("misc", "python"):
1648                continue
1649
1650            parent = self.root / rel_path.parent
1651            if rel_path.name == "mzbuild.yml":
1652                image = Image(self.rd, parent)
1653                if not image.name:
1654                    raise ValueError(f"config at {parent} missing name")
1655                if image.name in self.images:
1656                    raise ValueError(f"image {image.name} exists twice")
1657                self.images[image.name] = image
1658            elif rel_path.name == "mzcompose.py":
1659                name = parent.name
1660                if name in self.compositions:
1661                    raise ValueError(f"composition {name} exists twice")
1662                self.compositions[name] = parent
1663
1664        # Validate dependencies.
1665        for image in self.images.values():
1666            for d in image.depends_on:
1667                if d not in self.images:
1668                    raise ValueError(
1669                        f"image {image.name} depends on non-existent image {d}"
1670                    )
1671
1672    @staticmethod
1673    def install_arguments(parser: argparse.ArgumentParser) -> None:
1674        """Install options to configure a repository into an argparse parser.
1675
1676        This function installs the following options:
1677
1678          * The mutually-exclusive `--dev`/`--optimized`/`--release` options to control the
1679            `profile` repository attribute.
1680          * The `--coverage` boolean option to control the `coverage` repository
1681            attribute.
1682
1683        Use `Repository.from_arguments` to construct a repository from the
1684        parsed command-line arguments.
1685        """
1686        build_mode = parser.add_mutually_exclusive_group()
1687        build_mode.add_argument(
1688            "--dev",
1689            action="store_true",
1690            help="build Rust binaries with the dev profile",
1691        )
1692        build_mode.add_argument(
1693            "--release",
1694            action="store_true",
1695            help="build Rust binaries with the release profile (default)",
1696        )
1697        build_mode.add_argument(
1698            "--optimized",
1699            action="store_true",
1700            help="build Rust binaries with the optimized profile (optimizations, no LTO, no debug symbols)",
1701        )
1702        parser.add_argument(
1703            "--coverage",
1704            help="whether to enable code coverage compilation flags",
1705            default=ui.env_is_truthy("CI_COVERAGE_ENABLED"),
1706            action="store_true",
1707        )
1708        parser.add_argument(
1709            "--sanitizer",
1710            help="whether to enable a sanitizer",
1711            default=Sanitizer[os.getenv("CI_SANITIZER", "none")],
1712            type=Sanitizer,
1713            choices=Sanitizer,
1714        )
1715
1716        def _parse_arch(s: str) -> Arch:
1717            try:
1718                return Arch(s)
1719            except ValueError:
1720                valid = ", ".join(m.value for m in Arch)
1721                raise argparse.ArgumentTypeError(
1722                    f"invalid arch: {s!r} (choose from {valid})"
1723                )
1724
1725        parser.add_argument(
1726            "--arch",
1727            default=Arch.host(),
1728            help="the CPU architecture to build for",
1729            type=_parse_arch,
1730            metavar="{" + ",".join(m.value for m in Arch) + "}",
1731        )
1732        parser.add_argument(
1733            "--image-registry",
1734            default=image_registry(),
1735            help="the Docker image registry to pull images from and push images to",
1736        )
1737        parser.add_argument(
1738            "--image-prefix",
1739            default="",
1740            help="a prefix to apply to all Docker image names",
1741        )
1742
1743    @classmethod
1744    def from_arguments(cls, root: Path, args: argparse.Namespace) -> "Repository":
1745        """Construct a repository from command-line arguments.
1746
1747        The provided namespace must contain the options installed by
1748        `Repository.install_arguments`.
1749        """
1750        if args.release:
1751            profile = Profile.RELEASE
1752        elif args.optimized:
1753            profile = Profile.OPTIMIZED
1754        elif args.dev:
1755            profile = Profile.DEV
1756        else:
1757            profile = (
1758                Profile.RELEASE if ui.env_is_truthy("CI_LTO") else Profile.OPTIMIZED
1759            )
1760
1761        return cls(
1762            root,
1763            profile=profile,
1764            coverage=args.coverage,
1765            sanitizer=args.sanitizer,
1766            image_registry=args.image_registry,
1767            image_prefix=args.image_prefix,
1768            arch=args.arch,
1769        )
1770
1771    @property
1772    def root(self) -> Path:
1773        """The path to the root directory for the repository."""
1774        return self.rd.root
1775
1776    def resolve_dependencies(self, targets: Iterable[Image]) -> DependencySet:
1777        """Compute the dependency set necessary to build target images.
1778
1779        The dependencies of `targets` will be crawled recursively until the
1780        complete set of transitive dependencies is determined or a circular
1781        dependency is discovered. The returned dependency set will be sorted
1782        in topological order.
1783
1784        Raises:
1785           ValueError: A circular dependency was discovered in the images
1786               in the repository.
1787        """
1788        # Pre-fetch all crate input files in a single batched git call,
1789        # replacing ~118 individual subprocess pairs with one pair.
1790        self.rd.cargo_workspace.precompute_crate_inputs()
1791        # Pre-fetch all image context files in a single batched git call,
1792        # replacing ~41 individual subprocess pairs with one pair.
1793        self._precompute_image_context_files()
1794
1795        resolved = OrderedDict()
1796        visiting = set()
1797
1798        def visit(image: Image, path: list[str] = []) -> None:
1799            if image.name in resolved:
1800                return
1801            if image.name in visiting:
1802                diagram = " -> ".join(path + [image.name])
1803                raise ValueError(f"circular dependency in mzbuild: {diagram}")
1804
1805            visiting.add(image.name)
1806            for d in sorted(image.depends_on):
1807                visit(self.images[d], path + [image.name])
1808            resolved[image.name] = image
1809
1810        for target_image in sorted(targets, key=lambda image: image.name):
1811            visit(target_image)
1812
1813        return DependencySet(resolved.values())
1814
1815    def _precompute_image_context_files(self) -> None:
1816        """Pre-fetch all image context files in a single batched git call.
1817
1818        This replaces ~41 individual pairs of git subprocess calls (one per
1819        image) with a single pair, then partitions the results by image path.
1820        """
1821        root = self.rd.root
1822        # Use paths relative to root for git specs and partitioning, since
1823        # git --relative outputs paths relative to cwd (root). Image paths
1824        # may be absolute when MZ_ROOT is an absolute path.
1825        image_rel_paths = sorted(
1826            set(str(img.path.relative_to(root)) for img in self.images.values())
1827        )
1828        specs = [f"{p}/**" for p in image_rel_paths]
1829
1830        empty_tree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
1831        diff_files = spawn.capture(
1832            ["git", "diff", "--name-only", "-z", "--relative", empty_tree, "--"]
1833            + specs,
1834            cwd=root,
1835        )
1836        ls_files = spawn.capture(
1837            ["git", "ls-files", "--others", "--exclude-standard", "-z", "--"] + specs,
1838            cwd=root,
1839        )
1840        all_files = set(
1841            f for f in (diff_files + ls_files).split("\0") if f.strip() != ""
1842        )
1843
1844        # Partition files by image path (longest match first for nested paths)
1845        image_file_map: dict[str, set[str]] = {p: set() for p in image_rel_paths}
1846        sorted_paths = sorted(image_rel_paths, key=len, reverse=True)
1847        for f in all_files:
1848            for ip in sorted_paths:
1849                if f.startswith(ip + "/"):
1850                    image_file_map[ip].add(f)
1851                    break
1852
1853        for img in self.images.values():
1854            rel = str(img.path.relative_to(root))
1855            img._context_files_cache = image_file_map.get(rel, set())
1856
1857    def __iter__(self) -> Iterator[Image]:
1858        return iter(self.images.values())

A collection of mzbuild Images.

Creating a repository will walk the filesystem beneath root to automatically discover all contained Images.

Iterating over a repository yields the contained images in an arbitrary order.

Args: root: The path to the root of the repository. arch: The CPU architecture to build for. profile: What profile to build the repository in. coverage: Whether to enable code coverage instrumentation. sanitizer: Whether to a sanitizer (address, thread, leak, memory, none) image_registry: The Docker image registry to pull images from and push images to. image_prefix: A prefix to apply to all Docker image names.

Attributes: images: A mapping from image name to Image for all contained images. compose_dirs: The set of directories containing a mzcompose.py file.

Repository( root: pathlib._local.Path, arch: materialize.xcompile.Arch = <Arch.X86_64: 'x86_64'>, profile: Profile = <Profile.OPTIMIZED: 2>, coverage: bool = False, sanitizer: materialize.rustc_flags.Sanitizer = <Sanitizer.none: 'none'>, image_registry: str = 'ghcr.io/materializeinc/materialize', image_prefix: str = '')
1620    def __init__(
1621        self,
1622        root: Path,
1623        arch: Arch = Arch.host(),
1624        profile: Profile = (
1625            Profile.RELEASE if ui.env_is_truthy("CI_LTO") else Profile.OPTIMIZED
1626        ),
1627        coverage: bool = False,
1628        sanitizer: Sanitizer = Sanitizer.none,
1629        image_registry: str = image_registry(),
1630        image_prefix: str = "",
1631    ):
1632        self.rd = RepositoryDetails(
1633            root,
1634            arch,
1635            profile,
1636            coverage,
1637            sanitizer,
1638            image_registry,
1639            image_prefix,
1640        )
1641        self.images: dict[str, Image] = {}
1642        self.compositions: dict[str, Path] = {}
1643        for rel_path_s in sorted(
1644            git.expand_globs(self.root, "**/mzbuild.yml", "**/mzcompose.py")
1645        ):
1646            rel_path = Path(rel_path_s)
1647            if rel_path.parts[:2] == ("misc", "python"):
1648                continue
1649
1650            parent = self.root / rel_path.parent
1651            if rel_path.name == "mzbuild.yml":
1652                image = Image(self.rd, parent)
1653                if not image.name:
1654                    raise ValueError(f"config at {parent} missing name")
1655                if image.name in self.images:
1656                    raise ValueError(f"image {image.name} exists twice")
1657                self.images[image.name] = image
1658            elif rel_path.name == "mzcompose.py":
1659                name = parent.name
1660                if name in self.compositions:
1661                    raise ValueError(f"composition {name} exists twice")
1662                self.compositions[name] = parent
1663
1664        # Validate dependencies.
1665        for image in self.images.values():
1666            for d in image.depends_on:
1667                if d not in self.images:
1668                    raise ValueError(
1669                        f"image {image.name} depends on non-existent image {d}"
1670                    )
rd
images: dict[str, Image]
compositions: dict[str, pathlib._local.Path]
@staticmethod
def install_arguments(parser: argparse.ArgumentParser) -> None:
1672    @staticmethod
1673    def install_arguments(parser: argparse.ArgumentParser) -> None:
1674        """Install options to configure a repository into an argparse parser.
1675
1676        This function installs the following options:
1677
1678          * The mutually-exclusive `--dev`/`--optimized`/`--release` options to control the
1679            `profile` repository attribute.
1680          * The `--coverage` boolean option to control the `coverage` repository
1681            attribute.
1682
1683        Use `Repository.from_arguments` to construct a repository from the
1684        parsed command-line arguments.
1685        """
1686        build_mode = parser.add_mutually_exclusive_group()
1687        build_mode.add_argument(
1688            "--dev",
1689            action="store_true",
1690            help="build Rust binaries with the dev profile",
1691        )
1692        build_mode.add_argument(
1693            "--release",
1694            action="store_true",
1695            help="build Rust binaries with the release profile (default)",
1696        )
1697        build_mode.add_argument(
1698            "--optimized",
1699            action="store_true",
1700            help="build Rust binaries with the optimized profile (optimizations, no LTO, no debug symbols)",
1701        )
1702        parser.add_argument(
1703            "--coverage",
1704            help="whether to enable code coverage compilation flags",
1705            default=ui.env_is_truthy("CI_COVERAGE_ENABLED"),
1706            action="store_true",
1707        )
1708        parser.add_argument(
1709            "--sanitizer",
1710            help="whether to enable a sanitizer",
1711            default=Sanitizer[os.getenv("CI_SANITIZER", "none")],
1712            type=Sanitizer,
1713            choices=Sanitizer,
1714        )
1715
1716        def _parse_arch(s: str) -> Arch:
1717            try:
1718                return Arch(s)
1719            except ValueError:
1720                valid = ", ".join(m.value for m in Arch)
1721                raise argparse.ArgumentTypeError(
1722                    f"invalid arch: {s!r} (choose from {valid})"
1723                )
1724
1725        parser.add_argument(
1726            "--arch",
1727            default=Arch.host(),
1728            help="the CPU architecture to build for",
1729            type=_parse_arch,
1730            metavar="{" + ",".join(m.value for m in Arch) + "}",
1731        )
1732        parser.add_argument(
1733            "--image-registry",
1734            default=image_registry(),
1735            help="the Docker image registry to pull images from and push images to",
1736        )
1737        parser.add_argument(
1738            "--image-prefix",
1739            default="",
1740            help="a prefix to apply to all Docker image names",
1741        )

Install options to configure a repository into an argparse parser.

This function installs the following options:

  • The mutually-exclusive --dev/--optimized/--release options to control the profile repository attribute.
  • The --coverage boolean option to control the coverage repository attribute.

Use Repository.from_arguments to construct a repository from the parsed command-line arguments.

@classmethod
def from_arguments( cls, root: pathlib._local.Path, args: argparse.Namespace) -> Repository:
1743    @classmethod
1744    def from_arguments(cls, root: Path, args: argparse.Namespace) -> "Repository":
1745        """Construct a repository from command-line arguments.
1746
1747        The provided namespace must contain the options installed by
1748        `Repository.install_arguments`.
1749        """
1750        if args.release:
1751            profile = Profile.RELEASE
1752        elif args.optimized:
1753            profile = Profile.OPTIMIZED
1754        elif args.dev:
1755            profile = Profile.DEV
1756        else:
1757            profile = (
1758                Profile.RELEASE if ui.env_is_truthy("CI_LTO") else Profile.OPTIMIZED
1759            )
1760
1761        return cls(
1762            root,
1763            profile=profile,
1764            coverage=args.coverage,
1765            sanitizer=args.sanitizer,
1766            image_registry=args.image_registry,
1767            image_prefix=args.image_prefix,
1768            arch=args.arch,
1769        )

Construct a repository from command-line arguments.

The provided namespace must contain the options installed by Repository.install_arguments.

root: pathlib._local.Path
1771    @property
1772    def root(self) -> Path:
1773        """The path to the root directory for the repository."""
1774        return self.rd.root

The path to the root directory for the repository.

def resolve_dependencies( self, targets: Iterable[Image]) -> DependencySet:
1776    def resolve_dependencies(self, targets: Iterable[Image]) -> DependencySet:
1777        """Compute the dependency set necessary to build target images.
1778
1779        The dependencies of `targets` will be crawled recursively until the
1780        complete set of transitive dependencies is determined or a circular
1781        dependency is discovered. The returned dependency set will be sorted
1782        in topological order.
1783
1784        Raises:
1785           ValueError: A circular dependency was discovered in the images
1786               in the repository.
1787        """
1788        # Pre-fetch all crate input files in a single batched git call,
1789        # replacing ~118 individual subprocess pairs with one pair.
1790        self.rd.cargo_workspace.precompute_crate_inputs()
1791        # Pre-fetch all image context files in a single batched git call,
1792        # replacing ~41 individual subprocess pairs with one pair.
1793        self._precompute_image_context_files()
1794
1795        resolved = OrderedDict()
1796        visiting = set()
1797
1798        def visit(image: Image, path: list[str] = []) -> None:
1799            if image.name in resolved:
1800                return
1801            if image.name in visiting:
1802                diagram = " -> ".join(path + [image.name])
1803                raise ValueError(f"circular dependency in mzbuild: {diagram}")
1804
1805            visiting.add(image.name)
1806            for d in sorted(image.depends_on):
1807                visit(self.images[d], path + [image.name])
1808            resolved[image.name] = image
1809
1810        for target_image in sorted(targets, key=lambda image: image.name):
1811            visit(target_image)
1812
1813        return DependencySet(resolved.values())

Compute the dependency set necessary to build target images.

The dependencies of targets will be crawled recursively until the complete set of transitive dependencies is determined or a circular dependency is discovered. The returned dependency set will be sorted in topological order.

Raises: ValueError: A circular dependency was discovered in the images in the repository.

def publish_multiarch_images( tag: str, dependency_sets: Iterable[Iterable[ResolvedImage]]) -> None:
1861def publish_multiarch_images(
1862    tag: str, dependency_sets: Iterable[Iterable[ResolvedImage]]
1863) -> None:
1864    """Publishes a set of docker images under a given tag."""
1865    always_push_tags = ("latest", "unstable")
1866    if ghcr_token := os.getenv("GITHUB_GHCR_TOKEN"):
1867        spawn.runv(
1868            [
1869                "docker",
1870                "login",
1871                "ghcr.io",
1872                "-u",
1873                "materialize-bot",
1874                "--password-stdin",
1875            ],
1876            stdin=ghcr_token.encode(),
1877        )
1878    for images in zip(*dependency_sets):
1879        names = set(image.image.name for image in images)
1880        assert len(names) == 1, "dependency sets did not contain identical images"
1881        name = images[0].image.docker_name(tag)
1882        if tag in always_push_tags or not is_docker_image_pushed(name):
1883            spawn.run_with_retries(
1884                lambda: (
1885                    spawn.runv(
1886                        [
1887                            "docker",
1888                            "manifest",
1889                            "create",
1890                            "--amend",
1891                            name,
1892                            *(image.spec() for image in images),
1893                        ]
1894                    ),
1895                    spawn.runv(["docker", "manifest", "push", name]),
1896                )
1897            )
1898
1899        ghcr_name = f"{GHCR_PREFIX}{name}"
1900        if ghcr_token and (
1901            tag in always_push_tags or not is_ghcr_image_pushed(ghcr_name)
1902        ):
1903            spawn.run_with_retries(
1904                lambda: (
1905                    spawn.runv(
1906                        [
1907                            "docker",
1908                            "manifest",
1909                            "create",
1910                            "--amend",
1911                            ghcr_name,
1912                            *(f"{GHCR_PREFIX}{image.spec()}" for image in images),
1913                        ]
1914                    ),
1915                    spawn.runv(["docker", "manifest", "push", ghcr_name]),
1916                )
1917            )
1918    print(f"--- Nofifying for tag {tag}")
1919    markdown = f"""Pushed images with Docker tag `{tag}`"""
1920    spawn.runv(
1921        [
1922            "buildkite-agent",
1923            "annotate",
1924            "--style=info",
1925            f"--context=build-tags-{tag}",
1926        ],
1927        stdin=markdown.encode(),
1928    )

Publishes a set of docker images under a given tag.