Skip to content

Instantly share code, notes, and snippets.

@calebpower
Created August 9, 2026 00:33
Show Gist options
  • Select an option

  • Save calebpower/5fa7351123e77574c0f0475488aefde9 to your computer and use it in GitHub Desktop.

Select an option

Save calebpower/5fa7351123e77574c0f0475488aefde9 to your computer and use it in GitHub Desktop.
FreeBSD PKGBASE World Builder + Publisher
#!/bin/sh
# =============================================================================
# mkbase.sh — FreeBSD base (pkgbase) build/publish/sign pipeline
# =============================================================================
# Copyright (c) [year], [fullname]
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#
# Pipeline per branch:
# fetch src -> ensure datasets -> (clean) -> snapshot+update worktree ->
# verify kernel configs -> buildworld+kernel -> make packages ->
# publish to webroot -> sign -> verify.
#
# Error policy (two-tier):
# SHARED dependencies (tools, root, key, webroot, space, branch table,
# parent datasets, bare repo, upstream fetch) — first failure aborts the
# whole run outright (exit 2).
# BRANCH-LOCAL steps (worktree, symlinks, build, package, publish, sign,
# verify) — a failure kills only that branch; remaining branches still
# run, and every failure is repeated in the end-of-run summary so nothing
# has to be hunted out of the scrollback (exit 1 if any branch failed).
# No partial publishing: the webroot is only touched after a successful
# build+package, and signing failure after rsync aborts that branch loudly
# so a half-published repo is never silently left behind.
#
# Usage: sh mkbase.sh [options]
# --branch <name> only this branch (repeatable); e.g. --branch releng-14.4
# --clean make cleanworld before building
# --no-update skip git fetch/pull (build what's checked out)
# --force build even if the worktree didn't change
# --dry-run print every command; execute nothing destructive
# =============================================================================
# ----------------------------- CONFIGURATION ---------------------------------
# One line per branch: <worktree-dir>|<git-branch>|<ABI>|<KERNCONF list>
BRANCH_TABLE="
releng-14.4|releng/14.4|FreeBSD:14:amd64|IPFWKERNEL GENERIC
releng-15.1|releng/15.1|FreeBSD:15:amd64|IPFWKERNEL GENERIC
"
SRC_PARENT=/usr/local/src
SRC_DATASET=zroot/usr/local-src # '' to skip dataset management
BARE_REPO=$SRC_PARENT/freebsd.git
GIT_REMOTE=freebsd
GIT_URL=https://git.freebsd.org/src.git
OBJ_DIR=/usr/obj
OBJ_DATASET=zroot/usr/obj # '' to skip dataset management
MIN_OBJ_FREE_GB=40 # refuse to build with less free
KERNEL_CONF_DIR=/usr/local/etc/kernels
WEBROOT=/usr/local/www/apache24/data/base
SIGNING_KEY=/usr/local/etc/ssl/keys/poudriere.key
BUILD_JOBS=8
PKG_JOBS=2 # packaging OOMs before compiling does
NICENESS=10
LOG_DIR=/var/log/mkbase
LOCKFILE=/var/run/mkbase.lock
# -----------------------------------------------------------------------------
set -u
umask 022
TS=$(date +%Y%m%d-%H%M%S)
ONLY_BRANCHES=""; DO_CLEAN=no; DO_UPDATE=yes; DO_FORCE=no; DRY=no
CURRENT_BLOG="" # set per-branch so die() can show the build log tail
IN_BRANCH=no # 'yes' inside the per-branch subshell: die() there kills
# only the branch; at top level it aborts the whole run
log() { printf '%s [%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" "$2"; }
info() { log INFO "$1"; }
warn() { log WARN "$1"; }
die() {
log FATAL "$1"
if [ -n "$CURRENT_BLOG" ] && [ -s "$CURRENT_BLOG" ]; then
log FATAL "last 25 lines of $CURRENT_BLOG:"
tail -25 "$CURRENT_BLOG" | sed 's/^/ /'
fi
if [ "$IN_BRANCH" = yes ]; then
log FATAL "branch failed — continuing with remaining branches."
exit 1 # exits only the branch subshell
fi
log FATAL "shared dependency failed — aborting entire run $TS."
exit 2
}
# run "description" cmd... -> executes and DIES on nonzero exit (honors --dry-run)
run() {
_desc=$1; shift
info "$_desc"
info " \$ $*"
[ "$DRY" = yes ] && return 0
"$@" || die "step failed (exit $?): $_desc"
}
# try "description" cmd... -> executes, returns status, never dies (for probes)
try() {
_desc=$1; shift
[ "$DRY" = yes ] && { info "(dry) $_desc"; return 0; }
"$@"
}
# ------------------------------ option parsing --------------------------------
while [ $# -gt 0 ]; do
case "$1" in
--branch) [ $# -ge 2 ] || die "--branch requires an argument"
ONLY_BRANCHES="$ONLY_BRANCHES $2"; shift 2 ;;
--clean) DO_CLEAN=yes; shift ;;
--no-update) DO_UPDATE=no; shift ;;
--force) DO_FORCE=yes; shift ;;
--dry-run) DRY=yes; shift ;;
*) die "unknown option: $1" ;;
esac
done
# --------------------------------- locking ------------------------------------
# Refuse concurrent runs: two builds sharing /usr/obj corrupt each other.
if [ "$DRY" = no ]; then
if [ -e "$LOCKFILE" ]; then
OLDPID=$(cat "$LOCKFILE" 2>/dev/null)
if [ -n "$OLDPID" ] && kill -0 "$OLDPID" 2>/dev/null; then
die "another mkbase run (pid $OLDPID) holds $LOCKFILE"
fi
warn "stale lockfile (pid ${OLDPID:-unknown} gone) — taking over"
fi
echo $$ > "$LOCKFILE" || die "cannot write lockfile $LOCKFILE"
trap 'rm -f "$LOCKFILE"; log FATAL "interrupted — lock released"; exit 130' INT TERM
trap 'rm -f "$LOCKFILE"' EXIT
fi
# ------------------------------ PREFLIGHT -------------------------------------
# Validate EVERYTHING cheap before spending hours on a build.
info "run id: $TS clean=$DO_CLEAN update=$DO_UPDATE force=$DO_FORCE dry=$DRY"
# 0a. required tools
for TOOL in git zfs rsync pkg tar nice openssl make; do
command -v "$TOOL" >/dev/null 2>&1 || die "required tool missing: $TOOL"
done
# 0b. we must be root (datasets, /usr/obj, webroot)
[ "$(id -u)" = 0 ] || die "must run as root"
# 0c. log dir writable
mkdir -p "$LOG_DIR" || die "cannot create $LOG_DIR"
touch "$LOG_DIR/.wtest.$$" 2>/dev/null || die "$LOG_DIR not writable"
rm -f "$LOG_DIR/.wtest.$$"
# 0d. signing key: exists, private, parses as a valid RSA key
[ -f "$SIGNING_KEY" ] || die "signing key not found: $SIGNING_KEY"
KPERM=$(stat -f '%Lp' "$SIGNING_KEY" 2>/dev/null || echo '?')
case "$KPERM" in
?[1-7][1-7]|?[1-7]?|??[1-7]) warn "signing key mode is $KPERM — group/world access; consider chmod 400" ;;
esac
openssl rsa -in "$SIGNING_KEY" -noout -check >/dev/null 2>&1 \
|| die "signing key $SIGNING_KEY does not parse as a valid RSA private key"
# 0e. webroot exists and is writable
mkdir -p "$WEBROOT" || die "cannot create webroot $WEBROOT"
touch "$WEBROOT/.wtest.$$" 2>/dev/null || die "webroot $WEBROOT not writable"
rm -f "$WEBROOT/.wtest.$$"
# 0f. obj free space
AVAIL_GB=$(df -g "$OBJ_DIR" 2>/dev/null | awk 'NR==2 {print $4}')
[ -n "$AVAIL_GB" ] || die "cannot determine free space for $OBJ_DIR"
[ "$AVAIL_GB" -ge "$MIN_OBJ_FREE_GB" ] \
|| die "only ${AVAIL_GB}G free under $OBJ_DIR; need >= ${MIN_OBJ_FREE_GB}G (MIN_OBJ_FREE_GB)"
info "preflight: ${AVAIL_GB}G free under $OBJ_DIR"
# 0g. parse + validate the ENTIRE branch table before doing anything:
# field count, ABI shape, master kernel configs present, filter sanity.
BRANCH_LIST=""
OIFS=$IFS; IFS='
'
for LINE in $BRANCH_TABLE; do
IFS=$OIFS
[ -z "$(echo "$LINE" | tr -d ' ')" ] && { IFS='
'; continue; }
NF=$(echo "$LINE" | awk -F'|' '{print NF}')
[ "$NF" -eq 4 ] || die "malformed BRANCH_TABLE line (need 4 |-fields): $LINE"
_wt=$(echo "$LINE" | cut -d'|' -f1 | tr -d ' ')
_abi=$(echo "$LINE" | cut -d'|' -f3 | tr -d ' ')
_kcs=$(echo "$LINE" | cut -d'|' -f4 | sed 's/^ *//;s/ *$//')
[ -n "$_wt" ] || die "empty worktree name in: $LINE"
case "$_abi" in FreeBSD:*:*) : ;; *) die "ABI '$_abi' doesn't look like FreeBSD:MAJOR:ARCH" ;; esac
[ -n "$_kcs" ] || die "empty KERNCONF list in: $LINE"
for KC in $_kcs; do
[ "$KC" = GENERIC ] && continue
[ -f "$KERNEL_CONF_DIR/$KC" ] \
|| die "master kernel config missing: $KERNEL_CONF_DIR/$KC (needed by $_wt)"
done
BRANCH_LIST="$BRANCH_LIST $_wt"
IFS='
'
done
IFS=$OIFS
[ -n "$BRANCH_LIST" ] || die "BRANCH_TABLE is empty"
if [ -n "$ONLY_BRANCHES" ]; then
for B in $ONLY_BRANCHES; do
case " $BRANCH_LIST " in
*" $B "*) : ;;
*) die "--branch $B matches nothing in BRANCH_TABLE (have:$BRANCH_LIST)" ;;
esac
done
fi
info "preflight: branch table valid ($BRANCH_LIST)"
# ----------------------- datasets + source update -----------------------------
ensure_dataset() { # <dataset> <mountpoint> — create if absent; die on failure
_ds=$1; _mp=$2
[ -z "$_ds" ] && return 0
if try "zfs list $_ds" zfs list "$_ds" >/dev/null 2>&1; then
info "dataset $_ds present"
elif [ -d "$_mp" ]; then
warn "$_mp exists but is not dataset $_ds — plain directory (builds fine; no zfs ergonomics)"
else
run "creating dataset $_ds at $_mp" \
zfs create -o atime=off -o mountpoint="$_mp" "$_ds"
[ "$DRY" = yes ] || [ -d "$_mp" ] || die "dataset created but $_mp did not appear"
fi
}
ensure_dataset "$SRC_DATASET" "$SRC_PARENT"
[ -n "$OBJ_DATASET" ] && ensure_dataset "$OBJ_DATASET" "$OBJ_DIR"
if [ ! -d "$BARE_REPO" ]; then
run "bare repo missing — one-time clone (~3G)" \
git clone -o "$GIT_REMOTE" --bare "$GIT_URL" "$BARE_REPO"
fi
if [ "$DRY" = no ]; then
git -C "$BARE_REPO" rev-parse --git-dir >/dev/null 2>&1 \
|| die "$BARE_REPO exists but is not a git repository"
fi
if [ "$DO_UPDATE" = yes ]; then
run "fetching upstream" git -C "$BARE_REPO" fetch "$GIT_REMOTE" --prune
else
info "skipping upstream fetch (--no-update)"
fi
# ------------------------------ per-branch ------------------------------------
process_branch() { # <line from BRANCH_TABLE> — dies on any failure
LINE=$1
WT_NAME=$(echo "$LINE" | cut -d'|' -f1 | tr -d ' ')
GBRANCH=$(echo "$LINE" | cut -d'|' -f2 | tr -d ' ')
ABI=$(echo "$LINE" | cut -d'|' -f3 | tr -d ' ')
KERNCONFS=$(echo "$LINE" | cut -d'|' -f4 | sed 's/^ *//;s/ *$//')
WT_DIR=$SRC_PARENT/$WT_NAME
CURRENT_BLOG=$LOG_DIR/$WT_NAME-$TS.log
STATUS_FILE=$LOG_DIR/.status-$TS-$WT_NAME
# blog: append a timestamped step marker into the build log, so the raw
# make output is bracketed by date/time checkpoints
blog() {
[ "$DRY" = yes ] && return 0
printf '\n===== %s ===== %s =====\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >> "$CURRENT_BLOG"
}
info "===== $WT_NAME ($GBRANCH -> $ABI; kernels: $KERNCONFS) ====="
info "build log: $CURRENT_BLOG"
if [ "$DRY" = no ]; then
{
printf '# mkbase run %s\n' "$TS"
printf '# started: %s\n' "$(date '+%Y-%m-%d %H:%M:%S %Z')"
printf '# branch: %s (%s -> %s)\n' "$WT_NAME" "$GBRANCH" "$ABI"
printf '# kernels: %s\n' "$KERNCONFS"
printf '# options: clean=%s update=%s force=%s\n' "$DO_CLEAN" "$DO_UPDATE" "$DO_FORCE"
} > "$CURRENT_BLOG" || die "cannot write build log $CURRENT_BLOG"
fi
ensure_dataset "$SRC_DATASET/$WT_NAME" "$WT_DIR"
# worktree: create or verify
if [ ! -f "$WT_DIR/Makefile" ]; then
run "adding worktree $WT_NAME" \
git -C "$BARE_REPO" worktree add "$WT_DIR" "$GBRANCH"
fi
if [ "$DRY" = no ]; then
git -C "$WT_DIR" rev-parse HEAD >/dev/null 2>&1 \
|| die "$WT_DIR is not a usable git worktree"
# refuse to build a locally-modified tree — that's how untracked
# patches silently end up in fleet-wide packages
DIRTY=$(git -C "$WT_DIR" status --porcelain 2>/dev/null | head -5)
[ -z "$DIRTY" ] || die "worktree $WT_NAME has local modifications — commit/stash/revert first:
$DIRTY"
fi
HEAD_BEFORE=$(git -C "$WT_DIR" rev-parse HEAD 2>/dev/null || echo unknown)
if [ "$DO_UPDATE" = yes ]; then
try "pre-pull snapshot" \
zfs snapshot "$SRC_DATASET/$WT_NAME@pre-pull-$TS" 2>/dev/null \
|| warn "pre-pull snapshot failed or already exists (tree still clean; continuing)"
run "fast-forwarding to $GIT_REMOTE/$GBRANCH" \
git -C "$WT_DIR" merge --ff-only "$GIT_REMOTE/$GBRANCH"
fi
HEAD_AFTER=$(git -C "$WT_DIR" rev-parse HEAD 2>/dev/null || echo unknown)
if [ "$HEAD_BEFORE" = "$HEAD_AFTER" ] && [ "$DO_FORCE" = no ] \
&& [ "$DO_CLEAN" = no ] && [ -f "$WEBROOT/$ABI/latest/packagesite.pkg" ]; then
info "no upstream change and repo already published — skipping (--force to rebuild)"
[ "$DRY" = no ] && echo skipped > "$STATUS_FILE"
CURRENT_BLOG=""
return 0
fi
info "HEAD: $HEAD_BEFORE -> $HEAD_AFTER"
# kernel config symlinks (masters were validated in preflight)
for KC in $KERNCONFS; do
[ "$KC" = GENERIC ] && continue
LINK=$WT_DIR/sys/amd64/conf/$KC
if [ ! -e "$LINK" ]; then
run "linking $KC" ln -s "$KERNEL_CONF_DIR/$KC" "$LINK"
elif [ -L "$LINK" ]; then
TARGET=$(readlink "$LINK")
[ "$TARGET" = "$KERNEL_CONF_DIR/$KC" ] \
|| die "$LINK points at '$TARGET', expected $KERNEL_CONF_DIR/$KC — resolve manually"
else
die "$LINK is a real file, not the master symlink — if this branch diverged on purpose, move the file into $KERNEL_CONF_DIR under a branch-specific name and update BRANCH_TABLE; otherwise remove it"
fi
done
if [ "$DO_CLEAN" = yes ]; then
blog "cleanworld"
run "cleanworld" \
sh -c "cd '$WT_DIR' && make cleanworld >> '$CURRENT_BLOG' 2>&1"
fi
blog "buildworld + buildkernel KERNCONF=$KERNCONFS (-j$BUILD_JOBS)"
run "buildworld + buildkernel (-j$BUILD_JOBS, nice $NICENESS; the hours-long step)" \
sh -c "cd '$WT_DIR' && nice -n $NICENESS make -j$BUILD_JOBS \
buildworld buildkernel KERNCONF='$KERNCONFS' >> '$CURRENT_BLOG' 2>&1"
blog "make packages (-j$PKG_JOBS)"
run "make packages (-j$PKG_JOBS — low on purpose; packaging is the OOM risk)" \
sh -c "cd '$WT_DIR' && nice -n $NICENESS make -j$PKG_JOBS \
packages KERNCONF='$KERNCONFS' >> '$CURRENT_BLOG' 2>&1"
# locate the built repo — prefer 'latest', else newest version dir
SRC_REPO=$(find "$OBJ_DIR" -type d -path "*$WT_NAME*repo/$ABI/latest" 2>/dev/null | head -1)
[ -z "$SRC_REPO" ] && \
SRC_REPO=$(find "$OBJ_DIR" -type d -path "*$WT_NAME*repo/$ABI/*" 2>/dev/null | sort | tail -1)
if [ "$DRY" = no ]; then
[ -n "$SRC_REPO" ] || die "built repo for $ABI not found under $OBJ_DIR after make packages"
[ -d "$SRC_REPO/All" ] || [ -n "$(ls "$SRC_REPO"/*.pkg 2>/dev/null)" ] \
|| die "located repo dir $SRC_REPO contains no packages — refusing to publish"
info "built repo: $SRC_REPO"
# sanity: every requested custom kernel actually got packaged,
# BEFORE the webroot is touched
for KC in $KERNCONFS; do
KCLOWER=$(echo "$KC" | tr 'A-Z' 'a-z')
ls "$SRC_REPO"/All/FreeBSD-kernel-"$KCLOWER"-* >/dev/null 2>&1 \
|| ls "$SRC_REPO"/FreeBSD-kernel-"$KCLOWER"-* >/dev/null 2>&1 \
|| die "FreeBSD-kernel-$KCLOWER missing from built repo — built but not packaged?"
done
fi
run "creating $WEBROOT/$ABI/latest" mkdir -p "$WEBROOT/$ABI/latest"
run "publishing (rsync)" rsync -aL --delete "$SRC_REPO/" "$WEBROOT/$ABI/latest/"
run "signing" pkg repo "$WEBROOT/$ABI/latest" "$SIGNING_KEY"
if [ "$DRY" = no ]; then
tar -tf "$WEBROOT/$ABI/latest/packagesite.pkg" 2>/dev/null | grep -q '^signature$' \
|| die "published catalog has NO signature member — repo is live but unsigned; fix before clients update"
info "signature present in published catalog"
fi
info "$WT_NAME: published + signed at $WEBROOT/$ABI/latest"
[ "$DRY" = no ] && echo published > "$STATUS_FILE"
CURRENT_BLOG=""
return 0
}
PUBLISHED=""; SKIPPED=""; FAILED=""
OIFS=$IFS; IFS='
'
for LINE in $BRANCH_TABLE; do
IFS=$OIFS
[ -z "$(echo "$LINE" | tr -d ' ')" ] && { IFS='
'; continue; }
WT=$(echo "$LINE" | cut -d'|' -f1 | tr -d ' ')
if [ -n "$ONLY_BRANCHES" ]; then
case " $ONLY_BRANCHES " in *" $WT "*) : ;; *) IFS='
'; continue ;; esac
fi
# Branch runs in a subshell with IN_BRANCH=yes: any die() inside kills
# only this branch; the loop records the outcome and moves on.
rm -f "$LOG_DIR/.status-$TS-$WT"
( IN_BRANCH=yes; process_branch "$LINE" )
RC=$?
ST=$(cat "$LOG_DIR/.status-$TS-$WT" 2>/dev/null || echo "")
rm -f "$LOG_DIR/.status-$TS-$WT"
if [ $RC -ne 0 ]; then
FAILED="$FAILED $WT"
elif [ "$ST" = skipped ]; then
SKIPPED="$SKIPPED $WT"
else
PUBLISHED="$PUBLISHED $WT" # dry-run branches land here too
fi
IFS='
'
done
IFS=$OIFS
# ------------------------------- SUMMARY --------------------------------------
info "======================= RUN SUMMARY ($TS) ======================="
[ -n "$PUBLISHED" ] && info "published: $PUBLISHED"
[ -n "$SKIPPED" ] && info "skipped (no upstream change): $SKIPPED"
if [ -n "$FAILED" ]; then
warn "FAILED BRANCHES: $FAILED"
for B in $FAILED; do
warn " $B: see $LOG_DIR/$B-$TS.log"
done
warn "successful branches (if any) are published and signed; failed ones were NOT touched in the webroot."
exit 1
fi
info "all selected branches succeeded. Clients pick up changes via: pkg update && pkg upgrade"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment