Fetch distfiles as the ports build, repairing failed fetches per chunk

Tools' distfiles step walks every port's whole dependency tree again,
one make at a time: 70 of 266 ports in 9 hours under emulation. It
also walks the default flavor's tree for flavored ports (QEMU's desktop
dependencies for qemu@guestagent) and fails there on a port the build
never needs (gstreamer1-plugins-bad, missing from its distinfo). The
ports step fetches what it builds anyway, so the step is dropped, and
with it the tools patch that only fixed it.

pkg's distfiles are seeded into the distfiles set (which tools
extracts into the ports chroot) before the first chunk. A chunk whose
log shows "Couldn't fetch it" or "Giving up on fetching files" has
those ports repaired with fetch-patch.sh and runs once more.
fetch_failures accepts only port names, tested against real and
crafted logs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jeremy Karst 2026-11-19 16:15:18 -05:00
parent b59c0e41ed
commit 52f795704a
5 changed files with 186 additions and 112 deletions

View file

@ -45,7 +45,6 @@ opnsense-deps/
├── rc.d/ # rc.d service scripts and syshook scripts
├── pkg/ # FreeBSD package metadata
├── patches/<series>/ # opnsense/core patches (mirror, signing key, CMM restart)
├── patches/tools/ # opnsense/tools fixes, every series
├── keys/ # mirror public key and trusted/revoked fingerprints
├── release/ # build VM, release build, device migration (+ tests)
├── mirror/ # gwmirror.py stage/verify/publish, nginx container (+ tests)

View file

@ -194,39 +194,41 @@ release/vm.sh pull-out 14.3 26.1 # -> /scratch/mono-opnsense/out/26.1
and a transfer that moves nothing for 10 minutes fails the build instead
of hanging.
2. Applies `patches/<series>/*.patch` to core with `git am`. Core's version
becomes `<release>_<patches>`. Applies `patches/tools/*.patch`, fixes to
tools itself, for every series (see step 4).
becomes `<release>_<patches>`.
3. Builds base, kernel and xtools, then this repository's kernel modules, as
an early check against the new kernel.
4. Fetches the distfiles of every port and its dependencies into the
distfiles set. Some no longer download as recorded in the ports tree's
distinfo, chiefly patches GitHub generates on the fly
(`github.com/<owner>/<repo>/commit/<hash>.patch`): GitHub abbreviates
the object names on their `index` lines with more digits as a repository
grows, so an old patch now differs by a few bytes. FreeBSD's distfile
cache keeps the originals of FreeBSD's ports, but nothing keeps
OPNsense's own (e.g. the patches of `ports-mgmt/pkg`). Such ports are
fetched on the build host with `release/fetch-patch.sh`, which shortens
the abbreviations until the size matches distinfo; the port's `checksum`
target then verifies the SHA256, so only the original bytes are
accepted. The results are appended to the distfiles set, which tools'
step starts from.
- `ports-mgmt/pkg` is fetched this way first: tools' chroot builds pkg
before its first fetch, so every port would fail on pkg's patches.
- Then tools' step runs. The ports it reports as failed are fetched this
way, and the step runs once more. Tools 26.1.11 (and master) cannot
report them: its fetch loop runs in the chroot but records failures in
a path outside it, so the first failure ended the loop.
`patches/tools/0001` fixes that.
- A distfile that still cannot be fetched stops the build with the
port's name.
5. Builds the ports in chunks of `PORTS_CHUNK` (default 20) ports. Tools
4. Builds the ports in chunks of `PORTS_CHUNK` (default 20) ports. Tools
adds the packages it built to the packages set only when a ports step
ends, and every run starts from that set, so a single step of several days
would lose everything to a reboot of the build host; a chunk loses only
itself. The list is tools' `ports.conf`, read the way tools reads it. A
chunk in which a port fails still saves the others, then stops the build.
A final whole ports step builds whatever the chunks missed and prunes.
5. The ports fetch their distfiles as they build. Some no longer download as
recorded in the ports tree's distinfo, chiefly patches GitHub generates
on the fly (`github.com/<owner>/<repo>/commit/<hash>.patch`): GitHub
abbreviates the object names on their `index` lines with more digits as
a repository grows, so an old patch now differs by a few bytes. FreeBSD's
distfile cache keeps the originals of FreeBSD's ports, but nothing keeps
OPNsense's own (e.g. the patches of `ports-mgmt/pkg`).
- Such ports are fetched on the build host with `release/fetch-patch.sh`,
which shortens the abbreviations until the size matches distinfo; the
port's `checksum` target then verifies the SHA256, so only the original
bytes are accepted. The results are appended to the distfiles set,
which tools extracts into every ports step's chroot.
- `ports-mgmt/pkg` is fetched this way before the first chunk: the
chroot builds pkg before anything else.
- Any other port whose distfiles fail to fetch ("Couldn't fetch it" in
the step's output, `/var/tmp/gwbuild-ports.log`) is fetched this way
and its chunk runs once more. A distfile that still cannot be fetched
stops the build with the port's name.
- Tools' own `distfiles` step, which would fetch every distfile up front
for offline rebuilds, is not run. It walks the whole dependency tree of
every port again, one `make` at a time: 70 of 266 ports in 9 hours
under emulation. For flavored ports it walks the default flavor's tree
(QEMU's desktop dependencies for `qemu@guestagent`) and fails on a port
the build never needs. Also, its fetch loop records failures at a path
outside its chroot, so the first failure ends the loop.
6. Builds plugins, core and the packages set.
7. Builds the board package against the base set's headers and our libxml2,
and puts it into the packages set.
@ -248,10 +250,11 @@ release/vm.sh pull-out 14.3 26.1 # -> /scratch/mono-opnsense/out/26.1
release/vm.sh run 14.3 pilot 26.1 26.1.11 security/suricata databases/py-duckdb@py313
```
The pilot builds base, kernel and xtools, fetches the distfiles of the given
ports, and builds those ports with their dependencies, timing each. It then
removes its partial packages set (tools would otherwise consider the ports
built); base, kernel, xtools and distfiles are kept for the full build.
The pilot builds base, kernel and xtools, then the given ports with their
dependencies (fetching and repairing distfiles as the build does), timing
each. It then removes its partial packages set (tools would otherwise
consider the ports built); base, kernel, xtools and distfiles are kept for
the full build.
### Board package version

View file

@ -1,39 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Jeremy Karst <jeremy@karsttech.com>
Date: Thu, 19 Nov 2026 06:45:01 -0500
Subject: [PATCH] build/distfiles: record fetch failures inside the chroot
The fetch loop runs in the chroot, where ${STAGEDIR} does not exist,
so recording the first failed fetch failed and, under "sh -e", ended
the loop: every later port went unfetched and the step only said that
it did not finish properly. Write /.pkg-msg in the chroot, which is
the ${STAGEDIR}/.pkg-msg the step reads afterwards, as ports.sh does.
---
build/distfiles.sh | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/build/distfiles.sh b/build/distfiles.sh
index 9ebcf6f..db9f745 100644
--- a/build/distfiles.sh
+++ b/build/distfiles.sh
@@ -81,7 +81,7 @@ echo "${PORTSLIST}" | while read PORT_ORIGIN; do
if [ -n "${PRODUCT_REBUILD}" ]; then
exit 1
fi
- echo ">>> Failed fetching \${PORT}" >> ${STAGEDIR}/.pkg-msg
+ echo ">>> Failed fetching \${PORT}" >> /.pkg-msg
fi
PORT_DEPENDS=\$(make -C ${PORTSDIR}/\${PORT} all-depends-list \
\${MAKE_ARGS})
@@ -96,7 +96,7 @@ echo "${PORTSLIST}" | while read PORT_ORIGIN; do
if [ -n "${PRODUCT_REBUILD}" ]; then
exit 1
fi
- echo ">>> Failed fetching \${PORT}" >> ${STAGEDIR}/.pkg-msg
+ echo ">>> Failed fetching \${PORT}" >> /.pkg-msg
fi
done
done
--
2.53.0

View file

@ -39,6 +39,7 @@ COMMITTER="-c user.name=gwmirror-build -c user.email=build@opnsense.karsttech.co
export GIT_TERMINAL_PROMPT=0 GIT_HTTP_LOW_SPEED_LIMIT=1 GIT_HTTP_LOW_SPEED_TIME=600
# for ports fetched on this host (make "${FETCH_PATCH}" ...)
FETCH_PATCH="FETCH_CMD=sh ${DEPS}/release/fetch-patch.sh"
PORTS_LOG=/var/tmp/gwbuild-ports.log
die()
{
@ -113,11 +114,6 @@ checkout_all()
# shellcheck disable=SC2086
git ${COMMITTER} -C /usr/core am -q --committer-date-is-author-date ${PATCHES}
echo " /usr/core: $(git -C /usr/core describe --tags) with $(echo "${PATCHES}" | wc -l | tr -d ' ') patches"
# fixes to tools itself, for every series
PATCHES=$(ls "${DEPS}"/patches/tools/*.patch) || die "no patches/tools"
# shellcheck disable=SC2086
git ${COMMITTER} -C /usr/tools am -q --committer-date-is-author-date ${PATCHES}
echo " /usr/tools: with $(echo "${PATCHES}" | wc -l | tr -d ' ') patches"
cp "${DEPS}/config/GATEWAY.conf" /usr/tools/device/
echo " /usr/deps: $(git -C "${DEPS}" describe --tags --always --dirty)"
}
@ -184,38 +180,81 @@ EOF
# the build host; a chunk loses at most itself. A chunk with a failed port still
# saves the others, then stops the build. A last, whole ports step builds whatever
# the chunks missed (nothing, unless ports_list and tools disagree) and prunes.
#
# The ports fetch their distfiles as they build. Tools' distfiles step, which would
# fetch them all beforehand for offline rebuilds, is not run: it walks the whole
# dependency tree of every port again, one make at a time, which takes days under
# emulation, and for flavored ports it walks the default flavor's tree (QEMU's
# desktop dependencies for qemu@guestagent), where it fails on ports the build
# never needs.
build_ports()
{
# the ports step's chroot builds pkg before anything else
step "distfiles of ports-mgmt/pkg"
repair_distfiles ports-mgmt/pkg
_list=$(ports_list)
_total=$(echo "${_list}" | wc -l | tr -d ' ')
_done=0
# shellcheck disable=SC2086
echo "${_list}" | xargs -n "${PORTS_CHUNK:-20}" echo | while read -r _chunk; do
_t0=$(date +%s)
_done=$((_done + $(echo "${_chunk}" | wc -w)))
step "ports ${_done}/${_total}: ${_chunk}"
# "gwchunk" names no package: nothing is removed for a rebuild
${TOOLS} ${UNSIGNED} ports-gwchunk PORTSLIST="${_chunk}" PORTSENV="DEPEND=no PRUNE=no"
ports_run ports-gwchunk PORTSLIST="${_chunk}" PORTSENV="DEPEND=no PRUNE=no"
step "ports ${_done}/${_total} took $((($(date +%s) - _t0) / 60)) minutes"
done
step "ports: whole list"
ports_run ports-gwchunk
}
# ports_run TARGET [ARG...]: a tools ports step, its output also in PORTS_LOG. The
# ports whose distfiles failed to fetch are repaired, and the step runs once more;
# it skips the packages it has already built.
ports_run()
{
ports_step "$@" && return 0
_ports=$(fetch_failures "${PORTS_LOG}")
[ -n "${_ports}" ] || die "a port failed to build (${PORTS_LOG})"
step "repairing the distfiles of:" ${_ports}
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} ports-gwchunk
repair_distfiles ${_ports}
step "the same ports again, after the repair"
ports_step "$@" || die "a port failed to build (${PORTS_LOG})"
}
ports_step()
{
# shellcheck disable=SC2086
{ _rc=0; ${TOOLS} ${UNSIGNED} "$@" 2>&1 || _rc=$?; echo "${_rc}" > "${PORTS_LOG}.rc"; } |
tee "${PORTS_LOG}"
return "$(cat "${PORTS_LOG}.rc")"
}
# fetch_failures LOG: the ports whose distfiles could not be fetched, as the ports
# framework reports them in LOG: "Couldn't fetch it" (or "Giving up on fetching
# files" after checksum mismatches), then make's "stopped in" that port's directory.
# Only port names are accepted (they become arguments): no "..", globs or paths.
fetch_failures()
{
awk '/^=> (Couldn.t fetch it|Giving up on fetching files)/ { f = 1 }
f && /stopped in \/usr\/ports\/[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9_.+-]*$/ {
sub(/.*stopped in \/usr\/ports\//, ""); print; f = 0 }' "${1}" | sort -u
}
# repair_distfiles PORT...: fetch the distfiles of the PORTs on this host with
# fetch-patch.sh, which recovers the patches GitHub now generates differently from
# the ones recorded in distinfo (the ports' checksum target verifies the results),
# and add them to the distfiles set, which tools' distfiles step starts from. They
# are appended: a file the set already has is extracted twice, both copies verified.
# and add them to the distfiles set, which tools extracts into the ports step's
# chroot. They are appended: a file the set already has is extracted twice, both
# copies verified.
repair_distfiles()
{
_set=$(ls "${SETS}"/distfiles-*.tar 2> /dev/null | head -1)
[ -n "${_set}" ] || _set=${SETS}/distfiles-${VERSION}.tar
_dir=$(mktemp -d /var/tmp/gwdistfiles.XXXXXX)
for _port; do
make -C "/usr/ports/${_port}" BATCH=yes ARCH=aarch64 DISTDIR="${_dir}/distfiles" \
"${FETCH_PATCH}" checksum || die "cannot fetch the distfiles of ${_port}"
for _rport; do
make -C "/usr/ports/${_rport}" BATCH=yes ARCH=aarch64 DISTDIR="${_dir}/distfiles" \
"${FETCH_PATCH}" checksum || die "cannot fetch the distfiles of ${_rport}"
done
mkdir -p "${SETS}"
if [ -f "${_set}" ]; then _op=-rf; else _op=-cf; fi
@ -223,31 +262,6 @@ repair_distfiles()
rm -rf "${_dir}"
}
# fetch_distfiles [PORTSLIST=...]: tools' distfiles step, which fetches every distfile
# of the ports (and their dependencies) into the distfiles set. Its chroot builds pkg
# before its first fetch, so pkg's distfiles go into the set first. The ports whose
# distfiles fail to fetch (tools lists them, patches/tools/0001) are repaired, and the
# step is run once more.
fetch_distfiles()
{
_log=/var/tmp/gwbuild-distfiles.log
step "distfiles of ports-mgmt/pkg"
repair_distfiles ports-mgmt/pkg
step "distfiles"
# shellcheck disable=SC2086
{ _rc=0; ${TOOLS} ${UNSIGNED} distfiles "$@" 2>&1 || _rc=$?; echo "${_rc}" > "${_log}.rc"; } |
tee "${_log}"
[ "$(cat "${_log}.rc")" != 0 ] || return 0
_ports=$(sed -n 's|^>>> Failed fetching \(/usr/ports/\)\{0,1\}||p' "${_log}" | sort -u)
[ -n "${_ports}" ] || die "the distfiles step failed (see above)"
step "repairing the distfiles of:" ${_ports}
# shellcheck disable=SC2086
repair_distfiles ${_ports}
step "distfiles, after the repair"
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} distfiles "$@"
}
# the board package is cross-compiled against the base set's headers and libraries
sysroot_base()
{
@ -329,7 +343,6 @@ build()
sysroot_base
step "mono-gateway kernel modules (early check against the new kernel)"
make -C "${DEPS}" -j"$(sysctl -n hw.ncpu)" modules OPS_SETTINGS="${SERIES}"
fetch_distfiles
build_ports
step "plugins core packages"
# shellcheck disable=SC2086
@ -356,14 +369,13 @@ pilot()
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} base kernel xtools
step "base kernel xtools took $((($(date +%s) - _t0) / 60)) minutes"
# the distfiles set is kept for the real build, which fetches the rest
fetch_distfiles PORTSLIST="$*"
step "distfiles of ports-mgmt/pkg"
repair_distfiles ports-mgmt/pkg
# PORTSLIST limits the build to one port (and its dependencies); naming
# the port in the target makes tools run the step again for each one
for _port in "$@"; do
_t0=$(date +%s)
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} "ports-${_port}" PORTSLIST="${_port}" PORTSENV="DEPEND=no"
ports_run "ports-${_port}" PORTSLIST="${_port}" PORTSENV="DEPEND=no"
step "${_port} (with its dependencies) took $((($(date +%s) - _t0) / 60)) minutes"
done
# the partial packages set is marked "ports done" and would make the real

View file

@ -525,5 +525,104 @@ echo direct > "${last##*/}"
self.assertFalse(os.path.exists(os.path.join(self.tmp, "evil.patch")))
BUILD = os.path.join(REPO, "release", "build.sh")
# what the ports framework prints in tools' ports chroot when a distfile cannot be
# fetched while a port is built with its dependencies (from the 26.1.11 build)
FETCH_FAIL_PKG = """===> License BSD2CLAUSE accepted by the user
=> a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch doesn't seem to exist in /usr/ports/distfiles.
=> Attempting to fetch https://github.com/opnsense/pkg/commit/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch
fetch: https://github.com/opnsense/pkg/commit/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch: size mismatch: expected 2827, actual 2831
=> Attempting to fetch http://distcache.FreeBSD.org/ports-distfiles/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch
fetch: http://distcache.FreeBSD.org/ports-distfiles/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch: Not Found
=> Couldn't fetch it - please try to retrieve this
=> port manually into /usr/ports/distfiles and try again.
*** Error code 1
Stop.
make[1]: stopped in /usr/ports/ports-mgmt/pkg
*** Error code 1
Stop.
make: stopped in /usr/ports/devel/binutils
"""
CHECKSUM_FAIL = """=> SHA256 Checksum mismatch for foo-1.0.tar.gz.
===> Refetch for 1 more times files: foo-1.0.tar.gz
=> SHA256 Checksum mismatch for foo-1.0.tar.gz.
=> Giving up on fetching files: foo-1.0.tar.gz
Make sure the Makefile and distinfo file (/usr/ports/net/foo/distinfo)
are up to date.
*** Error code 1
Stop.
make[2]: stopped in /usr/ports/net/foo
*** Error code 1
Stop.
make[1]: stopped in /usr/ports/net/foo-wrapper
"""
BUILD_FAIL = """foo.c:12:1: error: expected ';' after top level declarator
*** Error code 1
Stop.
make[1]: stopped in /usr/ports/devel/foo/work/foo-1.0
*** Error code 1
Stop.
make: stopped in /usr/ports/devel/foo
"""
class FetchFailuresTest(unittest.TestCase):
"""build.sh's fetch_failures: which ports' distfiles to repair after a ports step."""
def failures(self, log):
with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as f:
f.write(log)
self.addCleanup(os.unlink, f.name)
func = subprocess.run(["sed", "-n", "/^fetch_failures()/,/^}/p", BUILD],
capture_output=True, text=True, check=True).stdout
self.assertIn("fetch_failures()", func)
r = subprocess.run(["sh", "-c", func + '\nfetch_failures "$1"', "sh", f.name],
capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stderr)
return r.stdout.split()
def test_names_the_port_that_failed_not_the_one_depending_on_it(self):
self.assertEqual(self.failures(FETCH_FAIL_PKG), ["ports-mgmt/pkg"])
def test_checksum_mismatch(self):
self.assertEqual(self.failures(CHECKSUM_FAIL), ["net/foo"])
def test_build_failure_is_not_a_fetch_failure(self):
self.assertEqual(self.failures(BUILD_FAIL), [])
self.assertEqual(self.failures(""), [])
def test_several_failures_once_each_sorted(self):
log = FETCH_FAIL_PKG + BUILD_FAIL + CHECKSUM_FAIL + FETCH_FAIL_PKG
self.assertEqual(self.failures(log), ["net/foo", "ports-mgmt/pkg"])
def test_skips_work_directories_to_the_port(self):
log = ("=> Couldn't fetch it - please try to retrieve this\n"
"make[2]: stopped in /usr/ports/devel/foo/work/foo-1.0\n"
"make[1]: stopped in /usr/ports/devel/foo\n")
self.assertEqual(self.failures(log), ["devel/foo"])
def test_only_port_names(self):
# build output is not trusted: names become arguments of make -C /usr/ports/...
for bad in ("../..", "devel/..", "../etc", "devel/*", "devel/foo bar", "devel/$(id)",
"devel/.hidden", "Devel/foo", "devel/foo;id", "/etc/passwd"):
log = ("=> Couldn't fetch it - please try to retrieve this\n"
f"make[1]: stopped in /usr/ports/{bad}\n")
self.assertEqual(self.failures(log), [], bad)
def test_flavoured_and_plus_names(self):
log = ("=> Couldn't fetch it - please try to retrieve this\n"
"make[1]: stopped in /usr/ports/devel/py-setuptools\n"
"=> Couldn't fetch it - please try to retrieve this\n"
"make[1]: stopped in /usr/ports/devel/libstdc++_stldoc_4.2.2\n")
self.assertEqual(self.failures(log), ["devel/libstdc++_stldoc_4.2.2", "devel/py-setuptools"])
if __name__ == "__main__":
unittest.main()