diff --git a/.github/actions/docker-build/action.yaml b/.github/actions/docker-build/action.yaml new file mode 100644 index 00000000..dc53ca3f --- /dev/null +++ b/.github/actions/docker-build/action.yaml @@ -0,0 +1,184 @@ +# Copyright Red Hat, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Docker Build (Hermetic) +description: Build must-gather image hermetically using Hermeto (offline/reproducible build) +inputs: + imageName: + description: The full image name including registry (e.g., quay.io/rhdh-community/rhdh-must-gather) + required: true + imageTags: + description: The tags to apply to the image + required: true + imageLabels: + description: The labels for the Docker image + required: false + platform: + description: "Target given CPU platform architecture (default: linux/amd64)" + required: false + default: linux/amd64 + containerfilePath: + description: Path to the Konflux/hermetic Containerfile + required: false + default: '.rhdh/docker/Containerfile' + buildArgs: + description: Build arguments to pass to buildah (newline-separated KEY=VALUE pairs) + required: false + default: '' + skipArtifactUpload: + description: Skip uploading the built image as a GitHub artifact + required: false + default: 'false' + +runs: + using: composite + steps: + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + with: + images: ${{ inputs.imageName }} + tags: | + ${{ inputs.imageTags }} + labels: | + ${{ inputs.imageLabels }} + + - name: Ensure podman is available + shell: bash + run: | + if ! command -v podman &>/dev/null; then + echo "podman not found, installing..." + sudo apt-get -y update && sudo apt-get -y install podman + fi + podman --version + + - name: Set up hermetic build variables + id: hermeto-vars + shell: bash + run: | + # Same pin as local hermetic builds: HERMETO_IMAGE in the Makefile. + HERMETO_IMAGE=$(sed -n 's/^HERMETO_IMAGE ?= //p' Makefile | head -1) + if [[ -z "${HERMETO_IMAGE}" ]]; then + echo "HERMETO_IMAGE is not set in the Makefile" + exit 1 + fi + echo "Using ${HERMETO_IMAGE}" + echo "HERMETO_IMAGE=${HERMETO_IMAGE}" >> "$GITHUB_ENV" + echo "LOCAL_CACHE_DIR=/tmp/hermeto-cache/rhdh-must-gather" >> "$GITHUB_ENV" + # Invalidate the dependency cache when the Hermeto image tag changes. + echo "hermeto_key=${HERMETO_IMAGE##*:}" >> "$GITHUB_OUTPUT" + + - name: Restore hermeto dependency cache + id: cache-deps + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: /tmp/hermeto-cache/rhdh-must-gather + key: hermeto-deps-${{ inputs.platform }}-${{ steps.hermeto-vars.outputs.hermeto_key }}-${{ hashFiles('go.mod', 'go.sum', 'rpms.lock.yaml') }} + + - name: Fetch dependencies with hermeto + if: steps.cache-deps.outputs.cache-hit != 'true' + shell: bash + run: | + set -ex + + mkdir -p "$LOCAL_CACHE_DIR" + + echo "::group::Fetching dependencies with hermeto" + podman run --rm -v "$PWD:/source:z" -v "$LOCAL_CACHE_DIR:/cachi2:z" -w /source "$HERMETO_IMAGE" \ + --log-level DEBUG \ + fetch-deps \ + --source . \ + --output /cachi2/output \ + '[{"type": "rpm", "path": "."}, {"type": "gomod", "path": "."}]' + echo "::endgroup::" + + if [ ! -d "$LOCAL_CACHE_DIR/output" ]; then + echo "No output directory found after fetch-deps" + exit 1 + fi + + echo "::group::Generating environment file" + podman run --rm -v "$PWD:/source:z" -v "$LOCAL_CACHE_DIR:/cachi2:z" -w /source "$HERMETO_IMAGE" \ + --log-level DEBUG \ + generate-env --format env \ + --output /cachi2/cachi2.env /cachi2/output + echo "::endgroup::" + + echo "::group::Injecting files" + podman run --rm -v "$PWD:/source:z" -v "$LOCAL_CACHE_DIR:/cachi2:z" -w /source "$HERMETO_IMAGE" \ + --log-level DEBUG \ + inject-files /cachi2/output + echo "::endgroup::" + + - name: Generate env and inject files (cache hit) + if: steps.cache-deps.outputs.cache-hit == 'true' + shell: bash + run: | + set -ex + echo "::group::Generating environment file from cached deps" + podman run --rm -v "$PWD:/source:z" -v "$LOCAL_CACHE_DIR:/cachi2:z" -w /source "$HERMETO_IMAGE" \ + --log-level DEBUG \ + generate-env --format env \ + --output /cachi2/cachi2.env /cachi2/output + echo "::endgroup::" + + echo "::group::Injecting files from cached deps" + podman run --rm -v "$PWD:/source:z" -v "$LOCAL_CACHE_DIR:/cachi2:z" -w /source "$HERMETO_IMAGE" \ + --log-level DEBUG \ + inject-files /cachi2/output + echo "::endgroup::" + + - name: Fix cache ownership for non-root buildah + shell: bash + run: | + set -ex + echo "LOCAL_CACHE_DIR_REALPATH=$(realpath "$LOCAL_CACHE_DIR")" >> "$GITHUB_ENV" + sudo chown -R runner "$(realpath "$LOCAL_CACHE_DIR")" + sudo chmod -R a+rwX "$(realpath "$LOCAL_CACHE_DIR")" + + - name: Build Docker Image + id: build + uses: redhat-actions/buildah-build@719e3c40d8af9790c23eca13f7daa339f2867034 # v3.1.0 + with: + containerfiles: ${{ inputs.containerfilePath }} + context: . + platform: ${{ inputs.platform }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: ${{ inputs.buildArgs }} + extra-args: | + --network=none + --volume ${{ env.LOCAL_CACHE_DIR_REALPATH }}:/cachi2:z + + - name: Save image as artifact + if: ${{ inputs.skipArtifactUpload != 'true' }} + shell: bash + env: + TAGS_LIST: ${{ steps.meta.outputs.tags }} + run: | + mkdir -p ./podman-artifacts + echo "Saving images with tags:" + echo "$TAGS_LIST" + readarray -t tags <<< "$TAGS_LIST" + podman save "${tags[@]}" -o ./podman-artifacts/image.tar + echo "$TAGS_LIST" > ./podman-artifacts/tags.txt + + - name: Upload image artifact + if: ${{ inputs.skipArtifactUpload != 'true' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: podman-image-${{ github.event.number || github.ref_name }} + path: ./podman-artifacts/ + retention-days: 1 + if-no-files-found: error diff --git a/.github/renovate.json b/.github/renovate.json index 119cfc6a..941e06b6 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -23,6 +23,15 @@ } ], "customManagers": [ + { + "customType": "regex", + "managerFilePatterns": ["/^Makefile$/"], + "matchStrings": [ + "# renovate: datasource=docker depName=(?\\S+)\\nHERMETO_IMAGE \\?= \\S+:(?\\S+)" + ], + "datasourceTemplate": "docker", + "versioningTemplate": "docker" + }, { "customType": "regex", "managerFilePatterns": ["/^\\.github/workflows/.*\\.ya?ml$/"], diff --git a/.github/workflows/container-build.yaml b/.github/workflows/container-build.yaml index 9cf1a137..516a358f 100644 --- a/.github/workflows/container-build.yaml +++ b/.github/workflows/container-build.yaml @@ -20,6 +20,7 @@ jobs: image-publish: name: Publish Container Image runs-on: ubuntu-latest + timeout-minutes: 60 permissions: contents: read packages: write @@ -27,7 +28,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - name: Log into registry ${{ vars.REGISTRY }} uses: redhat-actions/podman-login@50c2d9a331bb67c8fdab99b86455fad05e2e3252 # v2 @@ -53,78 +54,84 @@ jobs: EXPIRATION_TIMESTAMP=$(date -u -d "+14 days" +"%s") echo "EXPIRATION_TIMESTAMP=${EXPIRATION_TIMESTAMP}" >> "$GITHUB_OUTPUT" + IMAGE_TAG="" + EXTRA_TAGS="" + VERSION="" + if [[ "${{ github.ref }}" == refs/tags/* ]]; then # Git tag: push the tag version and derive major/minor tags TAG_VERSION=${GITHUB_REF#refs/tags/} - echo "IMAGE_TAG=${TAG_VERSION}" >> "$GITHUB_OUTPUT" - echo "VERSION=${TAG_VERSION}" >> "$GITHUB_OUTPUT" - + IMAGE_TAG="${TAG_VERSION}" + VERSION="${TAG_VERSION}" + # Parse semantic version to extract major and major.minor if [[ ${TAG_VERSION} =~ ^([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then MAJOR="${BASH_REMATCH[1]}" MINOR="${BASH_REMATCH[2]}" - echo "EXTRA_TAGS=${MAJOR} ${MAJOR}.${MINOR}" >> "$GITHUB_OUTPUT" - else - echo "EXTRA_TAGS=" >> "$GITHUB_OUTPUT" + EXTRA_TAGS="${MAJOR} ${MAJOR}.${MINOR}" fi elif [[ "${{ github.ref }}" == "refs/heads/main" ]]; then # Main branch: push latest and latest-${commit} - echo "IMAGE_TAG=latest" >> "$GITHUB_OUTPUT" - echo "EXTRA_TAGS=latest-${SHORT_SHA}" >> "$GITHUB_OUTPUT" + IMAGE_TAG="latest" + EXTRA_TAGS="latest-${SHORT_SHA}" VERSION="0.0.0-$(git describe --no-match --always --abbrev=9 --dirty --broken 2>/dev/null || echo unknown)" - echo "VERSION=${VERSION}" >> "$GITHUB_OUTPUT" elif [[ "${{ github.ref }}" == refs/heads/release-* ]]; then # Release branch: extract version and push latest-1.x and latest-1.x-${commit} BRANCH_NAME=${GITHUB_REF#refs/heads/} RELEASE_VERSION=${BRANCH_NAME#release-} - echo "IMAGE_TAG=latest-${RELEASE_VERSION}" >> "$GITHUB_OUTPUT" - echo "EXTRA_TAGS=latest-${RELEASE_VERSION}-${SHORT_SHA}" >> "$GITHUB_OUTPUT" + IMAGE_TAG="latest-${RELEASE_VERSION}" + EXTRA_TAGS="latest-${RELEASE_VERSION}-${SHORT_SHA}" VERSION="0.0.0-$(git describe --no-match --always --abbrev=9 --dirty --broken 2>/dev/null || echo unknown)" - echo "VERSION=${VERSION}" >> "$GITHUB_OUTPUT" fi - # Build and push using Makefile - - name: Build and push container image + echo "IMAGE_TAG=${IMAGE_TAG}" >> "$GITHUB_OUTPUT" + echo "EXTRA_TAGS=${EXTRA_TAGS}" >> "$GITHUB_OUTPUT" + echo "VERSION=${VERSION}" >> "$GITHUB_OUTPUT" + + ALL_TAGS="${IMAGE_TAG}" + for t in ${EXTRA_TAGS}; do + ALL_TAGS="${ALL_TAGS}"$'\n'"${t}" + done + { + echo "ALL_TAGS<> "$GITHUB_OUTPUT" + + - name: Build container image (hermetic) + uses: ./.github/actions/docker-build + with: + imageName: ${{ vars.REGISTRY }}/${{ env.IMAGE_NAME }} + imageTags: | + ${{ steps.prep.outputs.ALL_TAGS }} + buildArgs: | + RHDH_MUST_GATHER_VERSION=${{ steps.prep.outputs.VERSION }} + skipArtifactUpload: 'true' + + - name: Push container image id: build-push + env: + REGISTRY: ${{ vars.REGISTRY }} + IMAGE: ${{ env.IMAGE_NAME }} + MAIN_TAG: ${{ steps.prep.outputs.IMAGE_TAG }} + EXTRA_TAGS: ${{ steps.prep.outputs.EXTRA_TAGS }} run: | - # Get the VERSION from prep step - VERSION="${{ steps.prep.outputs.VERSION }}" - - # Build and push main tag - make image-push \ - CONTAINER_TOOL=podman \ - REGISTRY=${{ vars.REGISTRY }} \ - IMAGE_NAME=${{ env.IMAGE_NAME}} \ - IMAGE_TAG=${{ steps.prep.outputs.IMAGE_TAG }} \ - BUILD_ARGS="--build-arg RHDH_MUST_GATHER_VERSION=${VERSION}" - - # Get image digest - DIGEST=$(podman inspect --format='{{index .RepoDigests 0}}' ${{ vars.REGISTRY }}/${{ env.IMAGE_NAME}}:${{ steps.prep.outputs.IMAGE_TAG }} | cut -d'@' -f2) + MAIN_REF="${REGISTRY}/${IMAGE}:${MAIN_TAG}" + podman push --digestfile=/tmp/digest "${MAIN_REF}" + DIGEST=$(cat /tmp/digest) echo "digest=${DIGEST}" >> "$GITHUB_OUTPUT" - - # Save main tag for signing - echo "${{ vars.REGISTRY }}/${{ env.IMAGE_NAME}}:${{ steps.prep.outputs.IMAGE_TAG }}" > /tmp/image-tags.txt + echo "${MAIN_REF}" > /tmp/image-tags.txt + + for TAG in ${EXTRA_TAGS}; do + REF="${REGISTRY}/${IMAGE}:${TAG}" + echo "Pushing extra tag: ${TAG}" + podman push "${REF}" - # Push extra tags if specified - - name: Push extra tags - if: steps.prep.outputs.EXTRA_TAGS != '' - run: | - # Process each extra tag (space-separated) - for TAG in ${{ steps.prep.outputs.EXTRA_TAGS }}; do - echo "Processing tag: ${TAG}" - - # All extra tags reuse the main image to preserve digest - echo "Tagging and pushing: ${TAG}" - podman tag ${{ vars.REGISTRY }}/${{ env.IMAGE_NAME}}:${{ steps.prep.outputs.IMAGE_TAG }} ${{ vars.REGISTRY }}/${{ env.IMAGE_NAME}}:${TAG} - podman push ${{ vars.REGISTRY }}/${{ env.IMAGE_NAME}}:${TAG} - - # Track commit-SHA tags for expiration if [[ ${TAG} == latest-* ]]; then echo "${TAG}" >> /tmp/expiry-tags.txt fi - - # Add tag for signing - echo "${{ vars.REGISTRY }}/${{ env.IMAGE_NAME}}:${TAG}" >> /tmp/image-tags.txt + + echo "${REF}" >> /tmp/image-tags.txt done # Set expiration on commit-SHA tags via Quay.io API @@ -184,6 +191,7 @@ jobs: echo "" >> $GITHUB_STEP_SUMMARY echo "- **Version**: ${{ steps.prep.outputs.VERSION }}" >> $GITHUB_STEP_SUMMARY echo "- **Registry**: ${{ vars.REGISTRY }}" >> $GITHUB_STEP_SUMMARY + echo "- **Build**: Hermetic (\`--network=none\`)" >> $GITHUB_STEP_SUMMARY echo "- **Main Tag**: \`${{ steps.prep.outputs.IMAGE_TAG }}\`" >> $GITHUB_STEP_SUMMARY if [ -n "${{ steps.prep.outputs.EXTRA_TAGS }}" ]; then echo "- **Extra Tags**:" >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/pr-build.yaml b/.github/workflows/pr-build.yaml index 48bdc295..171d9dab 100644 --- a/.github/workflows/pr-build.yaml +++ b/.github/workflows/pr-build.yaml @@ -18,7 +18,7 @@ jobs: pr-build: name: Build PR Container Image runs-on: ubuntu-latest - timeout-minutes: 30 + timeout-minutes: 45 permissions: contents: read outputs: @@ -39,9 +39,15 @@ jobs: with: files: | .github/workflows/pr-build.yaml + .github/workflows/pr-push.yaml + .github/actions/docker-build/** Makefile Containerfile + .rhdh/docker/** .containerignore + rpms.in.yaml + rpms.lock.yaml + scripts/local-hermeto-build.sh LICENSE go.mod go.sum @@ -77,22 +83,17 @@ jobs: echo "IMAGE_TAG=pr-${PR_NUM}" >> "$GITHUB_OUTPUT" echo "EXTRA_TAGS=pr-${PR_NUM}-${SHORT_SHA}" >> "$GITHUB_OUTPUT" - echo "BUILD_ARGS=--build-arg RHDH_MUST_GATHER_VERSION=${VERSION}" >> "$GITHUB_OUTPUT" echo "VERSION=${VERSION}" >> "$GITHUB_OUTPUT" - - name: Build image + - name: Build image (hermetic) if: steps.changed-files.outputs.any_changed == 'true' - env: - # Map outputs to environment variables here - TAG: ${{ steps.prep.outputs.IMAGE_TAG }} - ARGS: ${{ steps.prep.outputs.BUILD_ARGS }} - NAME: ${{ env.IMAGE_NAME }} - run: | - make image-build \ - CONTAINER_TOOL=podman \ - IMAGE_NAME="$NAME" \ - IMAGE_TAG="$TAG" \ - BUILD_ARGS="$ARGS" + uses: ./.github/actions/docker-build + with: + imageName: ${{ env.IMAGE_NAME }} + imageTags: ${{ steps.prep.outputs.IMAGE_TAG }} + buildArgs: | + RHDH_MUST_GATHER_VERSION=${{ steps.prep.outputs.VERSION }} + skipArtifactUpload: 'true' # Save the image as a tarball for the push workflow - name: Save image to tarball @@ -147,7 +148,8 @@ jobs: echo "" >> $GITHUB_STEP_SUMMARY echo "- **Version**: ${VERSION}" >> $GITHUB_STEP_SUMMARY echo "- **PR Number**: ${PR_NUM}" >> $GITHUB_STEP_SUMMARY - echo "- **Status**: ✅ Built and saved as artifact" >> $GITHUB_STEP_SUMMARY + echo "- **Build**: Hermetic (\`--network=none\`)" >> $GITHUB_STEP_SUMMARY + echo "- **Status**: Built and saved as artifact" >> $GITHUB_STEP_SUMMARY echo "- **Tags**: ${ALL_TAGS}" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "The image will be pushed by the PR Push workflow." >> $GITHUB_STEP_SUMMARY diff --git a/.rhdh/docker/Containerfile b/.rhdh/docker/Containerfile index 4f89cdbf..87212e8c 100644 --- a/.rhdh/docker/Containerfile +++ b/.rhdh/docker/Containerfile @@ -3,6 +3,8 @@ # Stage 1: Build Go gather binary # https://registry.access.redhat.com/ubi10/go-toolset FROM registry.access.redhat.com/ubi10/go-toolset:10.2-1790644709@sha256:290ba654458e9a269b1509d10e6ebbd3c2b2456570e73e73201adb3ee54fb244 AS go-builder +# Build as the go-toolset default user (non-root). Hermeto prefetch must chmod the +# /cachi2 cache (see local-hermeto-build.sh and CI) so this user can use gomod offline. COPY go.mod go.sum /opt/app-root/src/ COPY cmd/ /opt/app-root/src/cmd/ COPY internal/ /opt/app-root/src/internal/ @@ -10,6 +12,7 @@ WORKDIR /opt/app-root/src ARG RHDH_MUST_GATHER_VERSION="0.0.0-unknown" RUN set -eu; \ . /cachi2/cachi2.env; \ + export GOCACHE=/tmp/go-build-cache; \ CGO_ENABLED=0 go build -trimpath \ -ldflags "-X 'github.com/redhat-developer/rhdh-must-gather/internal/cli.version=${RHDH_MUST_GATHER_VERSION}'" \ -o /tmp/gather ./cmd/gather diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 59f2e81e..8a8571cf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -42,3 +42,19 @@ make image-push REGISTRY=your-registry.com IMAGE_NAME=namespace/rhdh-must-gather # Build and push with custom image name and tag make image-push REGISTRY=your-registry.com IMAGE_NAME=namespace/my-rhdh-must-gather IMAGE_TAG=v1.0.0 ``` + +#### Hermetic build (Konflux parity) + +Downstream Konflux builds use `.rhdh/docker/Containerfile` with prefetched RPM and Go modules (no network during `podman build`). CI runs the same path via Hermeto. + +```bash +# Full hermetic build (fetch deps + build with --network none; version matches make image-build) +make hermetic-build REGISTRY=localhost IMAGE_NAME=rhdh-must-gather IMAGE_TAG=hermetic-test +# Optional: make hermetic-build VERSION=2.1.0-custom + +# Or use the script directly +./scripts/local-hermeto-build.sh -d . -i localhost/rhdh-must-gather:hermetic-test +podman run --rm localhost/rhdh-must-gather:hermetic-test --help +``` + +The root `Containerfile` remains for quick local iteration (`make image-build`); production and PR CI use the hermetic Containerfile. diff --git a/Makefile b/Makefile index 95711ffe..c415fcb5 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,8 @@ HELM_SET ?= ## Additional Helm --set flags for deploy-k8s (e.g., "gather.logLeve OUTPUT_FILE ?= ## Output file for deploy-k8s (default: rhdh-must-gather-output.k8s..tar.gz) HELM_TIMEOUT ?= ## Timeout for Helm install/upgrade in deploy-k8s (default: 60m) CONTAINER_TOOL ?= podman +# renovate: datasource=docker depName=quay.io/konflux-ci/hermeto +HERMETO_IMAGE ?= quay.io/konflux-ci/hermeto:0.60.1 BUILD_ARGS ?= LABELS ?= BASE_COLLECTION_PATH ?= ./out @@ -87,6 +89,10 @@ image-build: ## Build the must-gather container image $(CONTAINER_TOOL) build $(BUILD_ARGS) $(if $(LABELS),$(LABELS)) --build-arg RHDH_MUST_GATHER_VERSION=$(RHDH_MUST_GATHER_VERSION) -t $(IMAGE_NAME):$(IMAGE_TAG) . @echo "Image built: $(IMAGE_NAME):$(IMAGE_TAG)" +.PHONY: hermetic-build +hermetic-build: ## Build must-gather image hermetically using Hermeto (matches Konflux/CI) + HERMETO_IMAGE="$(HERMETO_IMAGE)" scripts/local-hermeto-build.sh -d . -i $(FULL_IMAGE_NAME) --version "$(RHDH_MUST_GATHER_VERSION)" + .PHONY: image-push image-push: image-build ## Build and push the image to registry @echo "Tagging image for registry..." diff --git a/scripts/local-hermeto-build.sh b/scripts/local-hermeto-build.sh new file mode 100755 index 00000000..5b775914 --- /dev/null +++ b/scripts/local-hermeto-build.sh @@ -0,0 +1,228 @@ +#!/bin/bash +# +# Copyright Red Hat, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Simulates the Konflux build process locally using Hermeto. +set -euo pipefail + +readonly LOCAL_CACHE_BASEDIR='/tmp/hermeto-cache' +readonly HERMETIC_CONTAINERFILE='.rhdh/docker/Containerfile' + +# Image tag comes from HERMETO_IMAGE in the Makefile (also used by CI). +HERMETO_IMAGE="${HERMETO_IMAGE:-}" + +TARGET_PLATFORM="${TARGET_PLATFORM:-}" + +usage() { + cat << EOF + +Usage: Build a hermeto dependency cache and/or a must-gather image with --network none. + +Required: + -d, --directory Repository root (must contain go.mod and rpms.lock.yaml) + +Options: + -i, --image Image reference (e.g., localhost/rhdh-must-gather:test) + --version Value for RHDH_MUST_GATHER_VERSION build-arg (default: 0.0.0-local) + --no-cache Skip cache build (use existing cache) + --no-image Skip image build (only build cache) + -h, --help Show this help message + +Environment variables: + HERMETO_IMAGE Hermeto image (default: HERMETO_IMAGE from the Makefile) + RHDH_MUST_GATHER_VERSION Same as --version when the flag is omitted + TARGET_PLATFORM Target platform for podman (e.g., linux/arm64, linux/amd64) + +Examples: + $0 -d . --no-image + $0 -d . -i localhost/rhdh-must-gather:hermetic-test + TARGET_PLATFORM=linux/arm64 $0 -d . -i localhost/rhdh-must-gather:arm64 +EOF + exit 1 +} + +build_cache() { + local component_dir="$1" + local local_cache_dir="$2" + local platform_args=() + + if [[ -n "${TARGET_PLATFORM}" ]]; then + platform_args=("--platform" "${TARGET_PLATFORM}") + fi + + mkdir -p "${local_cache_dir}/output" + + podman pull "${platform_args[@]}" "${HERMETO_IMAGE}" + + podman run --rm \ + "${platform_args[@]}" \ + -v "${component_dir}:/source:z" \ + -v "${local_cache_dir}:/cachi2:z" \ + -w /source \ + "${HERMETO_IMAGE}" \ + --log-level DEBUG \ + fetch-deps \ + --source . \ + --output /cachi2/output \ + '[{"type": "rpm", "path": "."}, {"type": "gomod", "path": "."}]' + + podman run --rm \ + "${platform_args[@]}" \ + -v "${component_dir}:/source:z" \ + -v "${local_cache_dir}:/cachi2:z" \ + -w /source \ + "${HERMETO_IMAGE}" \ + generate-env --format env --output /cachi2/cachi2.env /cachi2/output + + podman run --rm \ + "${platform_args[@]}" \ + -v "${component_dir}:/source:z" \ + -v "${local_cache_dir}:/cachi2:z" \ + -w /source \ + "${HERMETO_IMAGE}" \ + inject-files /cachi2/output + + # Match Konflux/CI: any UID in the build container can read/write the cache. + chmod -R a+rwX "${local_cache_dir}" +} + +build_image() { + local component_dir="$1" + local local_cache_dir="$2" + local image="$3" + local version="${4:-0.0.0-local}" + local platform_args=() + + if [[ -n "${TARGET_PLATFORM}" ]]; then + platform_args=("--platform" "${TARGET_PLATFORM}") + fi + + if [[ ! -d "${local_cache_dir}/output" ]]; then + echo "Local cache dir does not exist. Run without --no-cache first." >&2 + exit 1 + fi + + EMPTY_DIR=$(mktemp -d) + trap 'rm -rf "${EMPTY_DIR}" || true' EXIT + + podman build -t "${image}" \ + "${platform_args[@]}" \ + --network none \ + --build-arg "RHDH_MUST_GATHER_VERSION=${version}" \ + -f "${component_dir}/${HERMETIC_CONTAINERFILE}" \ + -v "${local_cache_dir}:/cachi2:z" \ + -v /dev/null:/run/secrets/redhat.repo \ + -v "${EMPTY_DIR}:/run/secrets/rhsm:z" \ + -v "${EMPTY_DIR}:/run/secrets/etc-pki-entitlement:z" \ + "${component_dir}" +} + +main() { + local component_dir="" + local image="" + local version="" + local no_cache=false + local no_image=false + + while [[ $# -gt 0 ]]; do + case "$1" in + -d|--directory) + component_dir="$2" + shift 2 + ;; + -i|--image) + image="$2" + shift 2 + ;; + --version) + version="$2" + shift 2 + ;; + --no-cache) + no_cache=true + shift + ;; + --no-image) + no_image=true + shift + ;; + -h|--help) + usage + ;; + *) + echo "Error: Unknown option: $1" >&2 + usage + ;; + esac + done + + if [[ -z "${component_dir}" ]]; then + echo "Error: -d/--directory is required" >&2 + usage + fi + + if [[ "${no_cache}" == true && "${no_image}" == true ]]; then + echo "Error: Nothing to do - both cache and image builds are disabled" >&2 + exit 1 + fi + + if [[ -z "${image}" ]]; then + no_image=true + fi + + local resolved_component_dir + local local_cache_dir + + resolved_component_dir="$(realpath "${component_dir}")" + local_cache_dir="${LOCAL_CACHE_BASEDIR}/rhdh-must-gather" + mkdir -p "${LOCAL_CACHE_BASEDIR}" + + if [[ -z "${HERMETO_IMAGE}" ]]; then + HERMETO_IMAGE=$(sed -n 's/^HERMETO_IMAGE ?= //p' "${resolved_component_dir}/Makefile" | head -1) + fi + if [[ -z "${HERMETO_IMAGE}" ]]; then + echo "Error: set HERMETO_IMAGE or define it in ${resolved_component_dir}/Makefile" >&2 + exit 1 + fi + + if [[ ! -f "${resolved_component_dir}/${HERMETIC_CONTAINERFILE}" ]]; then + echo "Error: ${HERMETIC_CONTAINERFILE} not found under ${resolved_component_dir}" >&2 + exit 1 + fi + + echo "Component dir: ${resolved_component_dir}" + echo "Local cache dir: ${local_cache_dir}" + echo "Hermeto image: ${HERMETO_IMAGE}" + + if [[ "${no_cache}" == false ]]; then + echo "Building cache..." + build_cache "${resolved_component_dir}" "${local_cache_dir}" + else + echo "Skipping cache build (--no-cache specified)" + fi + + if [[ -z "${version}" ]]; then + version="${RHDH_MUST_GATHER_VERSION:-0.0.0-local}" + fi + + if [[ "${no_image}" == false ]]; then + echo "Building image (RHDH_MUST_GATHER_VERSION=${version})..." + build_image "${resolved_component_dir}" "${local_cache_dir}" "${image}" "${version}" + else + echo "Skipping image build" + fi +} + +main "$@"