feat(docker): reuse dependency images for fast Docker source builds (#3828)
This commit is contained in:
+2
-1
@@ -1,4 +1,5 @@
|
||||
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
|
||||
.git
|
||||
**/.git
|
||||
outputs
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
|
||||
@@ -172,7 +172,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
ref: ${{ needs.prepare.outputs.full_sha }}
|
||||
fetch-depth: 0
|
||||
submodules: false
|
||||
|
||||
@@ -193,21 +193,55 @@ jobs:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Set up uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
version: "0.11.9"
|
||||
enable-cache: false
|
||||
|
||||
- name: Resolve dependency image and package versions
|
||||
id: dependency
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
SUFFIX: ${{ matrix.suffix }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
|
||||
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
|
||||
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
|
||||
echo "image=${image}" >> "$GITHUB_OUTPUT"
|
||||
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
|
||||
bash scripts/docker-editable-pretend-versions.sh --github-output . >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push dependencies
|
||||
id: dependencies
|
||||
if: steps.dependency.outputs.digest == ''
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.cuda
|
||||
target: dependencies
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: ${{ steps.dependency.outputs.image }}
|
||||
|
||||
- name: Build and push
|
||||
id: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.cuda
|
||||
# zstd compresses the multi-GB venv layers several times faster than gzip at a
|
||||
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
|
||||
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
|
||||
# or Docker >= 23.
|
||||
target: runtime
|
||||
build-args: |
|
||||
DEPENDENCY_IMAGE=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
|
||||
VERIFIERS_PRETEND_VERSION=${{ steps.dependency.outputs.verifiers }}
|
||||
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
|
||||
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
# The per-job builder is ephemeral; mode=max caches builder-stage
|
||||
# layers so warm builds skip the dependency sync.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
|
||||
@@ -223,6 +257,8 @@ jobs:
|
||||
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
|
||||
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
|
||||
DEPENDENCY_IMAGE: ${{ steps.dependency.outputs.image }}
|
||||
DEPENDENCY_DIGEST: ${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
SUFFIX: ${{ matrix.suffix }}
|
||||
run: |
|
||||
@@ -236,6 +272,7 @@ jobs:
|
||||
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
|
||||
echo "| **Commit** | \`${IMAGE_SHA}\` |"
|
||||
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
|
||||
echo "| **Dependencies** | \`${DEPENDENCY_IMAGE}@${DEPENDENCY_DIGEST}\` |"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
manifest:
|
||||
|
||||
+51
-76
@@ -1,21 +1,27 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
|
||||
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
|
||||
|
||||
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
|
||||
ARG DEPENDENCY_IMAGE=dependencies
|
||||
|
||||
FROM ghcr.io/astral-sh/uv:0.11.9@sha256:6b6fa841d71a48fbc9e2c55651c5ad570e01104d7a7d701f57b2b22c0f58e9b1 AS uv
|
||||
|
||||
FROM ubuntu:24.04@sha256:a853f94d226358a79c740cfc7bce0c289748f3fe3488d921d038ccd752c61b60 AS python-builder
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates python3.12 python3.12-venv \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
ENV UV_PYTHON_PREFERENCE=only-system UV_LINK_MODE=copy
|
||||
|
||||
# Every pyproject.toml + uv.lock, so the dependency sync below caches
|
||||
# independently of source edits.
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
|
||||
# .git is ~735 MB, changes every commit, and would land in the registry cache.
|
||||
COPY --exclude=.git . /ctx
|
||||
FROM python-builder AS manifests
|
||||
COPY . /ctx
|
||||
RUN mkdir -p /manifests \
|
||||
&& cd /ctx \
|
||||
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
|
||||
&& cp uv.lock /manifests/
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04@sha256:8b2705ea7a8653ad3451b46ab835eced92d77b44e671b9cf3ad4f95fbb2efe5e AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
@@ -72,18 +78,12 @@ RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.
|
||||
&& make install \
|
||||
&& rm -rf /tmp/ucx
|
||||
|
||||
# Download the latest installer
|
||||
ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
|
||||
# Set install dir to location accessible to non-root users
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
# Build .venv against the system CPython, so the venv's recorded interpreter
|
||||
# matches the runtime interpreter and no bin/python relink is needed at runtime.
|
||||
ENV UV_PYTHON_PREFERENCE=only-system
|
||||
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
|
||||
# Explicity set venv dir inside /app so to ensure it gets copied over during
|
||||
# the runtime stage's `COPY /app`
|
||||
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
|
||||
|
||||
# Install Python dependencies
|
||||
@@ -91,50 +91,11 @@ WORKDIR /app
|
||||
|
||||
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
|
||||
# Third-party deps only — source edits don't bust this layer. First-party
|
||||
# editables install in the source-layer sync below. No build-context bind
|
||||
# mount here: .git would bust the cache every commit.
|
||||
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
|
||||
# The runtime dependency image contains no first-party source or editable installs.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
--no-install-package renderers \
|
||||
--no-install-package prime-pydantic-config
|
||||
|
||||
COPY pyproject.toml /app/pyproject.toml
|
||||
COPY uv.lock /app/uv.lock
|
||||
COPY README.md /app/README.md
|
||||
COPY src/ /app/src/
|
||||
COPY packages/ /app/packages/
|
||||
COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
|
||||
|
||||
# Use submodule git metadata from the build context when present. Docker copies
|
||||
# only the submodule .git pointer files into /app/deps, so we temporarily link
|
||||
# /app/.git/modules to the read-only context before resolving versions.
|
||||
ARG VERIFIERS_PRETEND_VERSION
|
||||
ARG RENDERERS_PRETEND_VERSION
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
--mount=type=bind,source=.,target=/build-context,readonly \
|
||||
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
|
||||
&& \
|
||||
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
|
||||
&& \
|
||||
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
--no-install-local
|
||||
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
|
||||
@@ -184,7 +145,7 @@ RUN find /usr/local/cuda-13.0/targets/*/lib \
|
||||
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04@sha256:f8ef28f579ea42a44b415d2c5d46f788e6a9b395c6c83f2929416e1fc192c143 AS dependencies
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -262,19 +223,12 @@ RUN userdel -r ubuntu 2>/dev/null || true; \
|
||||
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
|
||||
|
||||
# Install uv for development use
|
||||
ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
|
||||
USER appuser
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
WORKDIR /app
|
||||
# Copy the application from the builder, splitting the venv's largest trees into their
|
||||
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
|
||||
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
|
||||
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
|
||||
# per-tree copies above, or the data lands in the image twice.
|
||||
# The volatile /app remainder goes last so a source edit re-pushes one layer,
|
||||
# not all of them.
|
||||
# Split the largest dependency trees so compression and pulls can run in parallel.
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
|
||||
@@ -282,17 +236,14 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
|
||||
COPY --from=builder /opt/ucx /opt/ucx
|
||||
|
||||
# Copy and set up entrypoint script
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
COPY --from=builder --chown=appuser:appuser \
|
||||
--exclude=.venv/lib/python3.12/site-packages/nvidia \
|
||||
--exclude=.venv/lib/python3.12/site-packages/torch \
|
||||
--exclude=.venv/lib/python3.12/site-packages/vllm \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app /app
|
||||
--exclude=lib/python3.12/site-packages/nvidia \
|
||||
--exclude=lib/python3.12/site-packages/torch \
|
||||
--exclude=lib/python3.12/site-packages/vllm \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app/.venv /app/.venv
|
||||
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
@@ -303,6 +254,30 @@ ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRA
|
||||
ENV HF_HUB_ETAG_TIMEOUT=500
|
||||
ENV HF_HUB_DOWNLOAD_TIMEOUT=300
|
||||
|
||||
# Use entrypoint for setup (ulimit, etc) but default to sleep infinity
|
||||
FROM python-builder AS application-builder
|
||||
WORKDIR /app
|
||||
COPY pyproject.toml uv.lock README.md /app/
|
||||
COPY src /app/src
|
||||
COPY packages /app/packages
|
||||
COPY deps /app/deps
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
|
||||
COPY scripts/docker_application.py /build/docker_application.py
|
||||
ARG VERIFIERS_PRETEND_VERSION
|
||||
ARG RENDERERS_PRETEND_VERSION
|
||||
ARG PYDANTIC_CONFIG_PRETEND_VERSION
|
||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
|
||||
&& uv run --no-project --python /usr/bin/python3.12 /build/docker_application.py /app /out/app
|
||||
|
||||
# COPY --link and numeric ownership let source builds reuse dependency blobs without unpacking them.
|
||||
FROM ${DEPENDENCY_IMAGE} AS runtime
|
||||
ARG USER_ID=1000
|
||||
ARG GROUP_ID=1000
|
||||
COPY --link --from=application-builder --chown=${USER_ID}:${GROUP_ID} /out/app /app
|
||||
# Preserve the executable Git mode; --chmod disables BuildKit's linked-copy optimization.
|
||||
COPY --link --chown=${USER_ID}:${GROUP_ID} scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||
CMD ["sleep", "infinity"]
|
||||
|
||||
@@ -53,8 +53,8 @@ describe_tag() {
|
||||
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
|
||||
}
|
||||
|
||||
verifiers_git_version() {
|
||||
local dir="$root/deps/verifiers"
|
||||
standard_git_version() {
|
||||
local dir="$1"
|
||||
local desc tag distance
|
||||
|
||||
[ -d "$dir" ] || return 1
|
||||
@@ -64,6 +64,14 @@ verifiers_git_version() {
|
||||
next_patch_dev_version "$tag" "$distance"
|
||||
}
|
||||
|
||||
verifiers_git_version() {
|
||||
standard_git_version "$root/deps/verifiers"
|
||||
}
|
||||
|
||||
pydantic_config_git_version() {
|
||||
standard_git_version "$root/deps/pydantic-config"
|
||||
}
|
||||
|
||||
renderers_git_version() {
|
||||
local dir="$root/deps/renderers"
|
||||
local desc tag distance version
|
||||
@@ -111,22 +119,27 @@ resolve_version() {
|
||||
|
||||
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
|
||||
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
|
||||
pydantic_config_version="$(resolve_version prime-pydantic-config PYDANTIC_CONFIG_PRETEND_VERSION pydantic_config_git_version)"
|
||||
|
||||
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
|
||||
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
|
||||
printf 'Resolved pydantic-config pretend version: %s\n' "$pydantic_config_version" >&2
|
||||
|
||||
case "$mode" in
|
||||
shell)
|
||||
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
|
||||
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
|
||||
printf "export PYDANTIC_CONFIG_PRETEND_VERSION='%s'\n" "$pydantic_config_version"
|
||||
;;
|
||||
github-output)
|
||||
printf 'verifiers=%s\n' "$verifiers_version"
|
||||
printf 'renderers=%s\n' "$renderers_version"
|
||||
printf 'pydantic_config=%s\n' "$pydantic_config_version"
|
||||
;;
|
||||
env)
|
||||
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
|
||||
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
|
||||
printf 'PYDANTIC_CONFIG_PRETEND_VERSION=%s\n' "$pydantic_config_version"
|
||||
;;
|
||||
*)
|
||||
printf 'Unknown output mode: %s\n' "$mode" >&2
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def editable_paths(root: Path) -> list[Path]:
|
||||
lock = tomllib.loads((root / "uv.lock").read_text())
|
||||
paths = set()
|
||||
for package in lock["package"]:
|
||||
source = package["source"]
|
||||
if "directory" in source:
|
||||
raise ValueError(f"Non-editable local package: {package['name']}")
|
||||
if "editable" not in source:
|
||||
continue
|
||||
path = (root / source["editable"]).resolve()
|
||||
if not path.is_relative_to(root):
|
||||
raise ValueError(f"Editable package outside the application: {path}")
|
||||
paths.add(path)
|
||||
return sorted(paths)
|
||||
|
||||
|
||||
def set_fallback_version(pyproject: Path, version: str) -> None:
|
||||
if not re.fullmatch(r"[0-9][A-Za-z0-9.+-]*", version):
|
||||
raise ValueError(f"Invalid package version: {version!r}")
|
||||
content, count = re.subn(
|
||||
r'(?m)^fallback-version = "[^"]*"$', f'fallback-version = "{version}"', pyproject.read_text()
|
||||
)
|
||||
if count != 1:
|
||||
raise ValueError(f"Expected one fallback-version in {pyproject}")
|
||||
pyproject.write_text(content)
|
||||
|
||||
|
||||
def copy_installation_artifacts(venv: Path, baseline: set[Path], output: Path) -> None:
|
||||
# The runtime supplies the interpreter and third-party environment.
|
||||
for directory in (venv / "bin", venv / "lib/python3.12/site-packages"):
|
||||
for path in directory.iterdir():
|
||||
relative = path.relative_to(venv)
|
||||
if relative in baseline:
|
||||
continue
|
||||
target = output / ".venv" / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.is_dir():
|
||||
shutil.copytree(path, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
||||
else:
|
||||
shutil.copy2(path, target)
|
||||
|
||||
|
||||
def application_layer(root: Path, output: Path) -> None:
|
||||
if output.is_relative_to(root):
|
||||
raise ValueError("The output directory must be outside the application")
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
venv = root / ".venv"
|
||||
if venv.exists() or venv.is_symlink():
|
||||
raise FileExistsError(venv)
|
||||
versions = {
|
||||
"deps/verifiers": "VERIFIERS_PRETEND_VERSION",
|
||||
"deps/renderers": "RENDERERS_PRETEND_VERSION",
|
||||
"deps/pydantic-config": "PYDANTIC_CONFIG_PRETEND_VERSION",
|
||||
}
|
||||
for path, variable in versions.items():
|
||||
set_fallback_version(root / path / "pyproject.toml", os.environ[variable])
|
||||
|
||||
subprocess.run(["uv", "venv", "--python", "/usr/bin/python3.12", str(venv)], check=True)
|
||||
baseline = {path.relative_to(venv) for path in venv.rglob("*")}
|
||||
command = ["uv", "pip", "install", "--python", str(venv / "bin/python"), "--no-deps"]
|
||||
for path in editable_paths(root):
|
||||
command.extend(["--editable", str(path)])
|
||||
subprocess.run(command, check=True, cwd=root)
|
||||
|
||||
shutil.copytree(root, output, ignore=shutil.ignore_patterns(".venv", ".git", "__pycache__", "*.pyc"))
|
||||
copy_installation_artifacts(venv, baseline, output)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Build a source and editable-package Docker layer")
|
||||
parser.add_argument("root", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
args = parser.parse_args()
|
||||
application_layer(args.root.resolve(), args.output.resolve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,80 @@
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def dependency_fingerprint(root: Path) -> str:
|
||||
inputs = [root / path for path in ("Dockerfile.cuda", ".dockerignore", "uv.lock", "scripts/docker_dependencies.py")]
|
||||
for directory, children, files in os.walk(root):
|
||||
children[:] = [name for name in children if name not in {".git", ".venv", "outputs"}]
|
||||
if "pyproject.toml" in files:
|
||||
inputs.append(Path(directory) / "pyproject.toml")
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(inputs):
|
||||
name = path.relative_to(root).as_posix().encode()
|
||||
content = path.read_bytes()
|
||||
digest.update(len(name).to_bytes(8, "big"))
|
||||
digest.update(name)
|
||||
digest.update(len(content).to_bytes(8, "big"))
|
||||
digest.update(content)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def registry_digest(image: str) -> str | None:
|
||||
registry, _, reference = image.partition("/")
|
||||
if registry != "ghcr.io":
|
||||
raise ValueError("Dependency images must use ghcr.io")
|
||||
repository, separator, tag = reference.rpartition(":")
|
||||
if not separator or not repository or not tag:
|
||||
raise ValueError("Expected ghcr.io/<owner>/<image>:<tag>")
|
||||
|
||||
query = urlencode({"service": registry, "scope": f"repository:{repository}:pull"})
|
||||
headers = {}
|
||||
if token := os.environ.get("GH_TOKEN"):
|
||||
credentials = f"{os.environ['GITHUB_ACTOR']}:{token}".encode()
|
||||
headers["Authorization"] = f"Basic {base64.b64encode(credentials).decode()}"
|
||||
request = Request(f"https://{registry}/token?{query}", headers=headers)
|
||||
with urlopen(request, timeout=30) as response:
|
||||
token = json.load(response)["token"]
|
||||
request = Request(
|
||||
f"https://{registry}/v2/{repository}/manifests/{tag}",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Accept": "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json",
|
||||
},
|
||||
method="HEAD",
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=30) as response:
|
||||
digest = response.headers["Docker-Content-Digest"]
|
||||
if not digest or not digest.startswith("sha256:"):
|
||||
raise ValueError(f"Missing or invalid image digest for {image}")
|
||||
return digest
|
||||
except HTTPError as error:
|
||||
if error.code != 404:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Fingerprint and resolve Docker dependency images")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
fingerprint = commands.add_parser("fingerprint")
|
||||
fingerprint.add_argument("root", type=Path)
|
||||
resolve = commands.add_parser("resolve")
|
||||
resolve.add_argument("image")
|
||||
args = parser.parse_args()
|
||||
if args.command == "fingerprint":
|
||||
print(dependency_fingerprint(args.root.resolve()))
|
||||
else:
|
||||
print(registry_digest(args.image) or "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user