From b28e561387705c47b1b4f9a2a235f858ff893970 Mon Sep 17 00:00:00 2001 From: jknapp Date: Sun, 29 Nov 2026 07:23:46 -0800 Subject: [PATCH 1/3] feat(pkg-cache): host package cache is opt-in (default OFF) + origin fallback health check - /etc/pkgcache-host.conf setting (PKGCACHE_ENABLED, PKGCACHE_URL, PKGCACHE_CA); no cache host is built into the tool. sync/apply/revert/status; status shows mode. - pkgcache-host-health.sh + 5 min timer (installed only while ON): probes repomd.xml and .asc through the cache, 2 failures -> origin-only (reversible marker lines, atomic rename under flock), 3 successes -> cache-first. Both-down is not counted. - scripts/tests/pkgcache-host.test.sh Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- docs/pkg-cache.md | 48 +++++++--- scripts/host/conf.example | 4 + scripts/host/pkgcache-host-health.sh | 137 +++++++++++++++++++++++++++ scripts/host/pkgcache-host-repos.sh | 111 ++++++++++++++++++---- scripts/tests/pkgcache-host.test.sh | 91 ++++++++++++++++++ 5 files changed, 361 insertions(+), 30 deletions(-) create mode 100644 scripts/host/conf.example create mode 100755 scripts/host/pkgcache-host-health.sh mode change 100644 => 100755 scripts/host/pkgcache-host-repos.sh create mode 100755 scripts/tests/pkgcache-host.test.sh diff --git a/docs/pkg-cache.md b/docs/pkg-cache.md index 0b2a368..4af9fb4 100644 --- a/docs/pkg-cache.md +++ b/docs/pkg-cache.md @@ -217,17 +217,44 @@ Applied to every job here (Build-and-Push, FPM, Shared-httpd, Shared-OLS, LiteSp The script is canonical here (`.gitea/scripts/resolve-base-image.sh`); other repos carry byte-identical copies. -## WHP hosts (`scripts/host/pkgcache-host-repos.sh`) +## WHP hosts (`scripts/host/pkgcache-host-repos.sh`) — opt-in, default OFF -`pkgcache-host-repos.sh apply https://192.168.1.40` does the following: -- backs up every `/etc/yum.repos.d/*.repo` to `/root/pkgcache-repo-backup-/`; -- installs the name-constrained CA as a system anchor; -- rewrites the AlmaLinux, EPEL and Remi sections to `baseurl=/... /...`; -- comments out mirrorlist/metalink in those sections; -- sets `gpgcheck=1`, plus `repo_gpgcheck=1` for AlmaLinux and Remi. +The package cache is **not** part of the stock WHP setup. A host uses the +distro repos unless its server setting turns the cache on. The setting is +`/etc/pkgcache-host.conf` (template: `scripts/host/conf.example`): -`revert [DIR]` restores byte-identical files (verified on AL9 and AL10) and -removes the anchor. `status` shows the current state. +``` +PKGCACHE_ENABLED=0 # 1 = use the cache; absent file = off +PKGCACHE_URL=https:// +PKGCACHE_CA=/path/to/ca.crt # default: pkg-cache-ca.crt next to the script +``` + +No cache host name is built into the tool or the defaults. + +- `pkgcache-host-repos.sh sync` makes the host match the setting: ON runs `apply` and installs the health timer, OFF runs `revert` and removes it. +- `apply [URL]` (URL defaults to `PKGCACHE_URL`; without a URL it refuses while the setting is OFF): + - backs up every `/etc/yum.repos.d/*.repo` to `/root/pkgcache-repo-backup-/`; + - installs the CA as a system anchor; + - rewrites the AlmaLinux, EPEL and Remi sections to `baseurl=/... /...`; + - comments out mirrorlist/metalink in those sections; + - sets `gpgcheck=1`, plus `repo_gpgcheck=1` for AlmaLinux and Remi; + - installs and enables `pkgcache-host-health.timer`. +- `revert [DIR]` restores byte-identical files (verified on AL9 and AL10), removes the anchor and the timer, and works from either mode below. +- `status` shows the setting, the **mode** (`cache-first`, `origin-only`, `off`), the timer and the health counters. + +**Health check** (`pkgcache-host-health.sh`, timer every 5 min, only while ON). It fetches +`repodata/repomd.xml` and `repomd.xml.asc` of a managed repo through the cache (5 s connect, 10 s total; +HTTP 200, non-empty, a real PGP signature). The `.asc` is what broke on 2026-11-26. +- 2 failures in a row: the managed lines become origin-only. The cache-first line stays above as `#pkgcache-cachefirst baseurl=...`, so the change is exactly reversible. +- 3 successes in a row: cache-first again. +- If the origin fails the same probe, the host or the internet is down, not the cache: nothing is counted. +- Only lines of the exact managed shape are touched. Each file is rewritten to a temp file in the same directory and `rename(2)`d under a lock, so a running dnf sees the old or the new file, never half of one. +- Transitions are logged to the journal (`journalctl -t pkgcache-host-health`). + +**Hosts already configured by the old tool** (before the setting existed) keep working: their +repos are already cache-first with the origin as 2nd URL. They have no health timer and no +`/etc/pkgcache-host.conf`, so `sync` treats them as OFF and would revert them. To keep them +on the cache, write the config with `PKGCACHE_ENABLED=1` first. To take them off, run `revert`. **Why not "cache first, mirrorlist as fallback":** measured on AL10, with mirrorlist/metalink left in place dnf **ignores `baseurl` completely** (0 cache @@ -244,9 +271,6 @@ requests). The origin as second baseurl is the fallback dnf really performs. | cache **down** (nginx stopped): makecache --refresh / download | rc=0 **16 s** / rc=0 24 s, served by origin | | cache **silently dropped** (iptables DROP): makecache --refresh / download | rc=0 **225 s** / rc=0 59 s (dnf's 30 s connect timeout per attempt) | -**Datacenter hosts** (whp01, whp02, sdbees, TrueSelfCA) cannot reach -192.168.1.40 and are **not configured**. That needs CT130 on NetBird (see the -report: setup key / route pending). ## Operating the cache (CT130) diff --git a/scripts/host/conf.example b/scripts/host/conf.example new file mode 100644 index 0000000..33c1ff2 --- /dev/null +++ b/scripts/host/conf.example @@ -0,0 +1,4 @@ +# /etc/pkgcache-host.conf — package cache for this host. OFF unless enabled here. +PKGCACHE_ENABLED=0 +#PKGCACHE_URL=https://pkg-cache.example.net +#PKGCACHE_CA=/root/pkgcache-host/pkg-cache-ca.crt diff --git a/scripts/host/pkgcache-host-health.sh b/scripts/host/pkgcache-host-health.sh new file mode 100755 index 0000000..ba1d648 --- /dev/null +++ b/scripts/host/pkgcache-host-health.sh @@ -0,0 +1,137 @@ +#!/bin/bash +## pkgcache-host-health.sh — keep a cache-configured WHP host's dnf working when the +## package cache is down OR broken. Run every 5 min by pkgcache-host-health.timer +## (installed only while the package-cache setting is ON; see pkgcache-host-repos.sh). +## +## pkgcache-host-health.sh run # timer entry: probe, count, switch if needed +## pkgcache-host-health.sh fallback # force origin-only now (reversible) +## pkgcache-host-health.sh restore # force cache-first now +## pkgcache-host-health.sh mode # prints: cache-first | origin-only | off +## +## Probe: GET //repodata/repomd.xml AND repomd.xml.asc (the .asc +## is what broke on 2026-11-26: the cache answered an empty reply for uncached +## objects), 5 s connect / 10 s total, HTTP 200, non-empty, .asc looks like a PGP +## signature. If the cache fails the probe but the ORIGIN fails it too, the host +## (or the internet) is down, not the cache: nothing is counted. +## 2 consecutive cache failures -> origin-only. 3 consecutive successes -> cache-first. +## +## How "origin-only" is made reversible and dnf-safe: +## * only lines of the exact shape tool-managed baseurl=/(almalinux|epel|remi)/... /... +## are touched; every other repo/line is left alone. +## * the cache-first line is kept right above as "#pkgcache-cachefirst baseurl=..." +## and the live line becomes baseurl=/... — restore undoes exactly that. +## * each file is rewritten to a temp file in the same directory and rename(2)d into +## place (atomic: dnf sees the old or the new file, never half of one), under flock. +## Transitions are logged to the journal (tag pkgcache-host-health) and the state file. +set -uo pipefail + +REPO_DIR=${PKGCACHE_REPO_DIR:-/etc/yum.repos.d} +STATE_DIR=${PKGCACHE_STATE_DIR:-/var/lib/pkgcache-host} +FAIL_NEEDED=2 +OK_NEEDED=3 +MARK='#pkgcache-cachefirst ' +MANAGED_RE='^baseurl=https://[^ /]+(:[0-9]+)?/(almalinux|epel|remi)/[^ ]+ https://[^ ]+$' + +log() { logger -t pkgcache-host-health -p "daemon.$1" -- "${*:2}" 2>/dev/null || true; echo "$1: ${*:2}" >&2; } +mkdir -p "$STATE_DIR" +exec 9>"$STATE_DIR/lock"; flock -w 30 9 || { echo "lock busy" >&2; exit 0; } +SF="$STATE_DIR/state" +get() { grep -s "^$1=" "$SF" | tail -1 | cut -d= -f2; } +put() { printf 'mode=%s\nfails=%s\noks=%s\n' "$1" "$2" "$3" >"$SF.new" && mv -f "$SF.new" "$SF"; } + +have_managed() { grep -q -s -E "$MANAGED_RE" "$REPO_DIR"/*.repo 2>/dev/null; } +have_fallback() { grep -q -s -F "$MARK" "$REPO_DIR"/*.repo 2>/dev/null; } + +# python does the atomic per-file rewrite. $1 = to-origin | to-cache +rewrite_all() { + python3 - "$1" "$REPO_DIR" "$MARK" "$MANAGED_RE" <<'PY' +import glob, os, re, sys, tempfile +action, d, mark, rx = sys.argv[1:5] +rx = re.compile(rx) +for f in sorted(glob.glob(os.path.join(d, '*.repo'))): + src = open(f).read().split('\n') + out, i = [], 0 + while i < len(src): + line = src[i] + if action == 'to-origin' and rx.match(line): + cache, origin = line[len('baseurl='):].split(' ', 1) + out += [mark + line, 'baseurl=' + origin] + elif action == 'to-cache' and line.startswith(mark) and i + 1 < len(src) and src[i + 1].startswith('baseurl='): + out.append(line[len(mark):]); i += 1 + else: + out.append(line) + i += 1 + if out == src: + continue + fd, tmp = tempfile.mkstemp(dir=d, prefix='.pkgcache-', suffix='.tmp') + st = os.stat(f) + with os.fdopen(fd, 'w') as fh: + fh.write('\n'.join(out)); fh.flush(); os.fsync(fh.fileno()) + os.chmod(tmp, st.st_mode & 0o7777); os.chown(tmp, st.st_uid, st.st_gid) + os.rename(tmp, f) +PY +} + +# The managed cache-first line (live, or the stashed one while in origin-only). +first_line() { # $1 = regex prefix filter (almalinux|remi) or '' + local l + l=$( { grep -h -E "$MANAGED_RE" "$REPO_DIR"/*.repo; grep -h -F "$MARK" "$REPO_DIR"/*.repo | sed "s|^$MARK||"; } 2>/dev/null | grep -E "/${1:-(almalinux|epel|remi)}/" | head -1) + echo "${l#baseurl=}" +} +expand() { local rel=${PKGCACHE_RELEASEVER:-$(rpm -E %rhel 2>/dev/null || echo 9)}; sed -e "s|\$releasever|$rel|g" -e "s|\$basearch|$(uname -m)|g"; } +fetch() { # url file-suffix -> 0 ok + local body code + body=$(curl -sS --connect-timeout 5 --max-time 10 -w '\n%{http_code}' "$1" 2>/dev/null) || return 1 + code=${body##*$'\n'}; body=${body%$'\n'*} + [ "$code" = 200 ] && [ -n "$body" ] || return 1 + case "$1" in *.asc) case "$body" in *'BEGIN PGP SIGNATURE'*) ;; *) return 1 ;; esac ;; esac + return 0 +} +probe() { # $1 = cache|origin ; returns 0 when repomd.xml (+ .asc where the repo is signed) fetch fine + local line sig=1 base which=$1 u + line=$(first_line '(almalinux|remi)'); [ -n "$line" ] || { line=$(first_line ''); sig=0; } + [ -n "$line" ] || return 3 + if [ "$which" = cache ]; then base=${line%% *}; else base=${line#* }; fi + base=$(printf '%s' "${PKGCACHE_PROBE_BASE:-$base}" | expand); base=${base%/} + u="$base/repodata/repomd.xml" + fetch "$u" || return 1 + [ "$sig" = 1 ] && { fetch "$u.asc" || return 1; } + return 0 +} + +cmd=${1:-mode} +case "$cmd" in + mode) + if have_fallback; then echo origin-only; elif have_managed; then echo cache-first; else echo off; fi ;; + fallback) have_managed || { echo "nothing to switch" >&2; exit 0; } + rewrite_all to-origin && put origin 0 0 && log warning "FALLBACK (forced): cache-managed repos now origin-only" ;; + restore) have_fallback || { echo "not in fallback" >&2; put cache 0 0; exit 0; } + rewrite_all to-cache && put cache 0 0 && log notice "RESTORED (forced): cache-managed repos are cache-first again" ;; + run) + if ! have_managed && ! have_fallback; then echo "no cache-managed repos; nothing to do"; exit 0; fi + mode=$(get mode); [ -n "$mode" ] || { have_fallback && mode=origin || mode=cache; } + fails=$(get fails); oks=$(get oks); fails=${fails:-0}; oks=${oks:-0} + if probe cache; then + fails=0; oks=$((oks+1)) + if [ "$mode" = origin ]; then + if [ "$oks" -ge "$OK_NEEDED" ]; then + rewrite_all to-cache && { mode=cache; oks=0; log notice "RESTORED: cache healthy for $OK_NEEDED runs, repos cache-first again"; } + else log notice "cache answers again ($oks/$OK_NEEDED), staying origin-only"; fi + else oks=0; fi + else + rc=$? + if [ "$rc" = 3 ]; then log warning "cannot derive a probe URL from the managed repos"; exit 0; fi + oks=0 + if probe origin; then + fails=$((fails+1)) + log warning "cache probe failed ($fails/$FAIL_NEEDED), origin reachable" + if [ "$mode" = cache ] && [ "$fails" -ge "$FAIL_NEEDED" ]; then + rewrite_all to-origin && { mode=origin; fails=0; log err "FALLBACK: cache failed $FAIL_NEEDED runs in a row, repos switched to origin-only"; } + fi + else + log warning "cache probe failed but the origin is unreachable too: not counted (network/upstream problem)" + fi + fi + put "$mode" "$fails" "$oks" ;; + *) echo "usage: run | fallback | restore | mode" >&2; exit 2 ;; +esac diff --git a/scripts/host/pkgcache-host-repos.sh b/scripts/host/pkgcache-host-repos.sh old mode 100644 new mode 100755 index 2f44b04..fcad9df --- a/scripts/host/pkgcache-host-repos.sh +++ b/scripts/host/pkgcache-host-repos.sh @@ -3,9 +3,25 @@ ## AppStream/CRB/extras/..., EPEL, Remi) at the internal package cache, with the ## ORIGIN as automatic fallback. Not used by image builds (see pkg-cache-repos.sh). ## -## pkgcache-host-repos.sh apply https://192.168.1.40 # backs up, then rewrites -## pkgcache-host-repos.sh status -## pkgcache-host-repos.sh revert [BACKUP_DIR] # default: newest backup +## OPT-IN, default OFF. The package cache is not part of the stock WHP setup: a host +## uses the distro repos unless its server setting turns the cache on. The setting +## lives in /etc/pkgcache-host.conf (KEY=VALUE, see conf.example next to this script): +## PKGCACHE_ENABLED=0|1 default 0 (file absent = off) +## PKGCACHE_URL=https:// base URL, no default +## PKGCACHE_CA=/path/to/ca.crt CA that signed the cache cert (default: +## pkg-cache-ca.crt next to this script) +## +## pkgcache-host-repos.sh sync # make the host match the setting: +## # ON -> apply + health timer +## # OFF -> revert + remove timer +## pkgcache-host-repos.sh apply [URL] # URL defaults to PKGCACHE_URL; backs up, +## # rewrites repos, installs the health timer +## pkgcache-host-repos.sh status # shows setting, MODE and timer +## pkgcache-host-repos.sh revert [BACKUP_DIR] # default: newest backup; removes the timer +## +## While ON, pkgcache-host-health.sh (timer, every 5 min) switches the repos to +## origin-only if the cache is down or broken and back after it recovers; +## status shows mode cache-first | origin-only | off. ## ## Fallback design (measured 2026-10-21 on AlmaLinux 10.2): ## * each rewritten section gets baseurl=// / @@ -23,8 +39,45 @@ set -euo pipefail MODE="${1:-status}" -CA_SRC="$(dirname "$0")/pkg-cache-ca.crt" -ANCHOR=/etc/pki/ca-trust/source/anchors/pkg-cache-ca.crt +HERE="$(cd "$(dirname "$0")" && pwd)" +CONF="${PKGCACHE_HOST_CONF:-/etc/pkgcache-host.conf}" +conf_get() { [ -r "$CONF" ] && { grep -E "^$1=" "$CONF" | tail -1 | cut -d= -f2- | tr -d "\"'"; } || true; } +CA_SRC="$(conf_get PKGCACHE_CA)"; CA_SRC="${CA_SRC:-$HERE/pkg-cache-ca.crt}" +HEALTH="$HERE/pkgcache-host-health.sh" +UNITDIR="${PKGCACHE_UNIT_DIR:-/etc/systemd/system}" +sysctl_() { [ "${PKGCACHE_NO_SYSTEMD:-0}" = 1 ] || systemctl "$@"; } +current_mode() { "$HEALTH" mode 2>/dev/null || echo off; } +install_timer() { + cat >"$UNITDIR/pkgcache-host-health.service" <"$UNITDIR/pkgcache-host-health.timer" <<'UNIT' +[Unit] +Description=Package-cache health check every 5 minutes +[Timer] +OnBootSec=2min +OnUnitActiveSec=5min +AccuracySec=10s +[Install] +WantedBy=timers.target +UNIT + sysctl_ daemon-reload; sysctl_ enable --now pkgcache-host-health.timer +} +remove_timer() { + sysctl_ disable --now pkgcache-host-health.timer 2>/dev/null || true + rm -f "$UNITDIR/pkgcache-host-health.timer" "$UNITDIR/pkgcache-host-health.service" + sysctl_ daemon-reload +} +ANCHOR="${PKGCACHE_ANCHOR:-/etc/pki/ca-trust/source/anchors/pkg-cache-ca.crt}" +REPOS="${PKGCACHE_REPO_DIR:-/etc/yum.repos.d}" # PKGCACHE_* overrides exist for the tests +BKROOT="${PKGCACHE_BACKUP_ROOT:-/root}" +update_ca() { [ "${PKGCACHE_NO_CATRUST:-0}" = 1 ] || update-ca-trust; } +dnf_clean() { [ "${PKGCACHE_NO_CATRUST:-0}" = 1 ] || dnf clean metadata -q || true; } die() { echo "FATAL(pkgcache-host-repos): $*" >&2; exit 1; } same() { [ "$(sha256sum < "$1")" = "$(sha256sum < "$2")" ]; } # cmp/diffutils is not on minimal hosts @@ -74,34 +127,56 @@ PY } case "$MODE" in + sync) + if [ "$(conf_get PKGCACHE_ENABLED)" = 1 ]; then + if [ "$(current_mode)" = off ]; then "$0" apply; else install_timer; echo "already on ($(current_mode)); timer ensured"; fi + else + if [ "$(current_mode)" != off ]; then "$0" revert; else remove_timer; echo "package cache is OFF (stock distro repos)"; fi + fi + ;; apply) - C="${2:?usage: apply https://}"; C="${C%/}" + C="${2:-}" + if [ -z "$C" ]; then + [ "$(conf_get PKGCACHE_ENABLED)" = 1 ] || die "package cache is OFF (PKGCACHE_ENABLED!=1 in $CONF); pass a URL to override" + C="$(conf_get PKGCACHE_URL)"; [ -n "$C" ] || die "PKGCACHE_URL not set in $CONF" + fi + C="${C%/}" case "$C" in https://*) ;; *) die "cache URL must be https://" ;; esac + if [ "$(current_mode)" != off ]; then + "$HEALTH" restore >/dev/null 2>&1 || true + install_timer; echo "already applied; health timer ensured (revert first to change the URL)"; exit 0 + fi [ -s "$CA_SRC" ] || die "missing $CA_SRC (copy keys/pkg-cache/ca.crt next to this script)" - B=/root/pkgcache-repo-backup-$(date -u +%Y%m%dT%H%M%SZ) + B=$BKROOT/pkgcache-repo-backup-$(date -u +%Y%m%dT%H%M%SZ) mkdir -p "$B/yum.repos.d" - cp -a /etc/yum.repos.d/*.repo "$B/yum.repos.d/" + cp -a "$REPOS"/*.repo "$B/yum.repos.d/" [ -e "$ANCHOR" ] && cp -a "$ANCHOR" "$B/" || touch "$B/.no-anchor-before" - install -m 0644 "$CA_SRC" "$ANCHOR" && update-ca-trust - for f in /etc/yum.repos.d/almalinux*.repo /etc/yum.repos.d/epel*.repo /etc/yum.repos.d/remi*.repo; do + install -m 0644 "$CA_SRC" "$ANCHOR" && update_ca + for f in "$REPOS"/almalinux*.repo "$REPOS"/epel*.repo "$REPOS"/remi*.repo; do [ -f "$f" ] || continue grep -q -E '^#?\s*baseurl\s*=\s*https?://(repo\.almalinux\.org|download\.example|rpms\.remirepo\.net)/' "$f" && rewrite "$f" "$C" done + install_timer echo "backup: $B" - echo "changed files:"; for f in "$B"/yum.repos.d/*.repo; do same "$f" "/etc/yum.repos.d/$(basename "$f")" || echo " /etc/yum.repos.d/$(basename "$f")"; done + echo "changed files:"; for f in "$B"/yum.repos.d/*.repo; do same "$f" "$REPOS/$(basename "$f")" || echo " $REPOS/$(basename "$f")"; done ;; revert) - B="${2:-$(ls -d /root/pkgcache-repo-backup-* 2>/dev/null | sort | tail -1)}" + remove_timer; rm -f "${PKGCACHE_STATE_DIR:-/var/lib/pkgcache-host}/state" + B="${2:-$(ls -d "$BKROOT"/pkgcache-repo-backup-* 2>/dev/null | sort | tail -1)}" [ -d "$B/yum.repos.d" ] || die "no backup dir ($B)" - for f in "$B"/yum.repos.d/*.repo; do same "$f" "/etc/yum.repos.d/$(basename "$f")" || { cp -a "$f" /etc/yum.repos.d/; echo "restored /etc/yum.repos.d/$(basename "$f")"; }; done - if [ -e "$B/.no-anchor-before" ]; then rm -f "$ANCHOR"; update-ca-trust; echo "removed $ANCHOR"; fi - dnf clean metadata -q || true + for f in "$B"/yum.repos.d/*.repo; do same "$f" "$REPOS/$(basename "$f")" || { cp -a "$f" "$REPOS/"; echo "restored $REPOS/$(basename "$f")"; }; done + if [ -e "$B/.no-anchor-before" ]; then rm -f "$ANCHOR"; update_ca; echo "removed $ANCHOR"; fi + dnf_clean echo "reverted from $B" ;; status) - grep -l -E '^baseurl=https://[^ ]+/(almalinux|epel|remi)/' /etc/yum.repos.d/*.repo 2>/dev/null | sed 's/^/via cache: /' || echo "no repo uses the cache" - ls -d /root/pkgcache-repo-backup-* 2>/dev/null | sed 's/^/backup: /' || true + echo "setting: $([ "$(conf_get PKGCACHE_ENABLED)" = 1 ] && echo "ON (url $(conf_get PKGCACHE_URL))" || echo OFF)" + echo "mode: $(current_mode)" + echo "health timer: $(sysctl_ is-active pkgcache-host-health.timer 2>/dev/null || echo inactive)" + [ -r "${PKGCACHE_STATE_DIR:-/var/lib/pkgcache-host}/state" ] && sed 's/^/health state: /' "${PKGCACHE_STATE_DIR:-/var/lib/pkgcache-host}/state" + grep -l -E '^baseurl=https://[^ ]+/(almalinux|epel|remi)/' "$REPOS"/*.repo 2>/dev/null | sed 's/^/via cache: /' || echo "no repo uses the cache" + ls -d "$BKROOT"/pkgcache-repo-backup-* 2>/dev/null | sed 's/^/backup: /' || true [ -e "$ANCHOR" ] && echo "CA anchor: $ANCHOR" || echo "CA anchor: absent" ;; - *) die "usage: apply URL | status | revert [DIR]" ;; + *) die "usage: sync | apply [URL] | status | revert [DIR]" ;; esac diff --git a/scripts/tests/pkgcache-host.test.sh b/scripts/tests/pkgcache-host.test.sh new file mode 100755 index 0000000..23b16c4 --- /dev/null +++ b/scripts/tests/pkgcache-host.test.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +## pkgcache-host.test.sh — fixture test for scripts/host/pkgcache-host-repos.sh (opt-in +## setting, apply/revert/sync/status) and pkgcache-host-health.sh (fallback/restore). +## Everything runs against a temp repo dir; curl/logger are fakes; no systemd, no root. +set -euo pipefail +H=$(cd "$(dirname "$0")/../host" && pwd) +R="$H/pkgcache-host-repos.sh"; HL="$H/pkgcache-host-health.sh" +T=$(mktemp -d); trap 'rm -rf "$T"' EXIT +fail=0 +ok() { echo "ok - $1"; } +bad() { echo "FAIL - $1"; fail=1; } +check() { if "${@:2}"; then ok "$1"; else bad "$1"; fi; } +mkdir -p "$T/bin" "$T/repos" "$T/state" "$T/units" "$T/bk" +printf '#!/bin/sh\nexit 0\n' >"$T/bin/logger" +# fake curl: FAKE_CACHE=ok|empty|noasc|refused ; FAKE_ORIGIN=ok|down ; asks recorded +cat >"$T/bin/curl" <<'EOS' +#!/bin/sh +for a; do u=$a; done +echo "$u" >>"$T/curl.log" +host=${u#https://}; host=${host%%/*} +if [ "$host" = cache.test ]; then mode=$FAKE_CACHE; else [ "$FAKE_ORIGIN" = ok ] && mode=ok || mode=refused; fi +case "$mode" in + refused) exit 7;; + empty) exit 52;; + noasc) case "$u" in *.asc) printf 'garbage\n200'; exit 0;; esac; printf '\n200';; + ok) case "$u" in *.asc) printf -- '-----BEGIN PGP SIGNATURE-----\nx\n200';; *) printf '\n200';; esac;; +esac +EOS +chmod +x "$T/bin/"* +sed -i "s|\$T/curl.log|$T/curl.log|" "$T/bin/curl" +export PATH="$T/bin:$PATH" PKGCACHE_REPO_DIR="$T/repos" PKGCACHE_STATE_DIR="$T/state" PKGCACHE_UNIT_DIR="$T/units" \ + PKGCACHE_BACKUP_ROOT="$T/bk" PKGCACHE_NO_SYSTEMD=1 PKGCACHE_NO_CATRUST=1 PKGCACHE_ANCHOR="$T/anchor.crt" \ + PKGCACHE_HOST_CONF="$T/pkgcache-host.conf" PKGCACHE_RELEASEVER=9 FAKE_CACHE=ok FAKE_ORIGIN=ok +cp "$H/../../keys/pkg-cache/ca.crt" "$T/ca.crt" +cat >"$T/repos/almalinux-baseos.repo" <<'EOS' +[baseos] +name=AlmaLinux $releasever - BaseOS +mirrorlist=https://mirrors.almalinux.org/mirrorlist/$releasever/baseos +# baseurl=https://repo.almalinux.org/almalinux/$releasever/BaseOS/$basearch/os/ +enabled=1 +gpgcheck=1 +EOS +cat >"$T/repos/custom.repo" <<'EOS' +[custom] +name=custom +baseurl=https://example.org/custom/ +enabled=1 +EOS +cp "$T/repos/almalinux-baseos.repo" "$T/orig-alma"; cp "$T/repos/custom.repo" "$T/orig-custom" +st() { "$R" status >"$T/st"; grep -q "$1" "$T/st"; } +same() { cmp -s "$1" "$2"; } +echo "PKGCACHE_CA=$T/ca.crt" >"$T/pkgcache-host.conf" # no ENABLED => OFF + +# ---- default OFF ---- +st '^setting: OFF' && st '^mode: off' && ok "default: setting OFF, mode off" || bad "default status" +if "$R" apply >/dev/null 2>&1; then bad "apply without URL must refuse while OFF"; else ok "apply without URL refuses while OFF"; fi +"$R" sync >/dev/null; same "$T/repos/almalinux-baseos.repo" "$T/orig-alma" && ok "sync while OFF leaves stock repos untouched" || bad "sync OFF touched repos" +[ ! -e "$T/units/pkgcache-host-health.timer" ] && ok "sync while OFF: no health timer" || bad "timer present while OFF" + +# ---- ON via setting ---- +printf 'PKGCACHE_ENABLED=1\nPKGCACHE_URL=https://cache.test\nPKGCACHE_CA=%s\n' "$T/ca.crt" >"$T/pkgcache-host.conf" +"$R" sync >/dev/null +grep -q '^baseurl=https://cache.test/almalinux/\$releasever/BaseOS/\$basearch/os/ https://repo.almalinux.org/almalinux/' "$T/repos/almalinux-baseos.repo" && ok "sync ON: cache-first baseurl with origin as 2nd URL" || bad "sync ON rewrite" +same "$T/repos/custom.repo" "$T/orig-custom" && ok "unmanaged repo untouched" || bad "unmanaged repo changed" +[ -e "$T/units/pkgcache-host-health.timer" ] && grep -q 'OnUnitActiveSec=5min' "$T/units/pkgcache-host-health.timer" && ok "health timer installed (5 min)" || bad "timer missing" +st '^mode: cache-first' && ok "status: mode cache-first" || bad "status cache-first" +"$R" sync >/dev/null; [ "$(ls -d "$T"/bk/pkgcache-repo-backup-* | wc -l)" = 1 ] && ok "second sync does not take a 2nd (poisoned) backup" || bad "double backup" + +# ---- health: fallback after 2 failures, restore after 3 successes ---- +FAKE_CACHE=empty "$HL" run 2>/dev/null; "$HL" mode | grep -q cache-first && ok "1 failure: still cache-first" || bad "1 failure" +FAKE_CACHE=empty "$HL" run 2>/dev/null; [ "$("$HL" mode)" = origin-only ] && ok "2 failures in a row: origin-only" || bad "no fallback" +grep -q '^baseurl=https://repo.almalinux.org/almalinux/\$releasever/BaseOS/\$basearch/os/$' "$T/repos/almalinux-baseos.repo" && grep -q '^#pkgcache-cachefirst baseurl=https://cache.test/' "$T/repos/almalinux-baseos.repo" && ok "origin-only rewrite keeps the marker line" || bad "origin-only content" +same "$T/repos/custom.repo" "$T/orig-custom" && ok "fallback never touches unmanaged repos" || bad "fallback touched custom.repo" +st '^mode: origin-only' && ok "status: mode origin-only" || bad "status origin-only" +"$HL" run 2>/dev/null; "$HL" run 2>/dev/null; [ "$("$HL" mode)" = origin-only ] && ok "2 successes: still origin-only" || bad "restored too early" +FAKE_CACHE=noasc "$HL" run 2>/dev/null; "$HL" run 2>/dev/null; "$HL" run 2>/dev/null; [ "$("$HL" mode)" = origin-only ] && ok "a bad .asc resets the success streak" || bad "streak not reset" +"$HL" run 2>/dev/null; [ "$("$HL" mode)" = cache-first ] && ok "3 successes: cache-first again" || bad "no restore" +ls "$T"/repos/.pkgcache-* >/dev/null 2>&1 && bad "temp file left behind" || ok "no temp files left (atomic rename)" +grep -q 'repomd.xml.asc' "$T/curl.log" && ok "probe fetched repomd.xml.asc" || bad ".asc not probed" +# both down => not counted +FAKE_CACHE=refused FAKE_ORIGIN=down "$HL" run 2>/dev/null; FAKE_CACHE=refused FAKE_ORIGIN=down "$HL" run 2>/dev/null; FAKE_CACHE=refused FAKE_ORIGIN=down "$HL" run 2>/dev/null +[ "$("$HL" mode)" = cache-first ] && ok "cache+origin both down: no fallback" || bad "network outage caused a fallback" +FAKE_CACHE=refused "$HL" run 2>/dev/null; FAKE_CACHE=refused "$HL" run 2>/dev/null; [ "$("$HL" mode)" = origin-only ] && ok "connection refused counts as failure" || bad "refused not counted" + +# ---- OFF via setting reverts cleanly, even from origin-only ---- +echo "PKGCACHE_ENABLED=0" >"$T/pkgcache-host.conf"; printf 'PKGCACHE_CA=%s\n' "$T/ca.crt" >>"$T/pkgcache-host.conf" +"$R" sync >/dev/null +same "$T/repos/almalinux-baseos.repo" "$T/orig-alma" && same "$T/repos/custom.repo" "$T/orig-custom" && ok "setting OFF: stock repos restored byte-identical (from origin-only)" || bad "revert not identical" +[ ! -e "$T/units/pkgcache-host-health.timer" ] && [ ! -e "$T/state/state" ] && ok "setting OFF: timer + state removed" || bad "timer/state left" +st '^mode: off' && ok "status: mode off after revert" || bad "status after revert" +exit $fail From ebe635501d7210a0fad62b7d622ce6c511ed1149 Mon Sep 17 00:00:00 2001 From: jknapp Date: Sun, 29 Nov 2026 07:31:56 -0800 Subject: [PATCH 2/3] pkgcache host: lock-free 'mode', atomic apply/revert file writes, shared repo lock - health 'mode' took the 30 s flock and mkdir'd the state dir; a held lock gave an empty answer, which sync (OFF) read as 'not off' and reverted from the newest backup. mode is now read-only and lock-free. - apply's rewrite() truncated repo files in place and revert used cp -a over the file; both now write a temp file and rename(2), so a concurrent dnf never sees half a file. - apply/revert take the same lock as the health timer so a health run cannot rewrite repo files while they edit them. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- scripts/host/pkgcache-host-health.sh | 8 +++++++ scripts/host/pkgcache-host-repos.sh | 31 ++++++++++++++++++++++------ scripts/tests/pkgcache-host.test.sh | 4 ++++ 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/scripts/host/pkgcache-host-health.sh b/scripts/host/pkgcache-host-health.sh index ba1d648..87582cc 100755 --- a/scripts/host/pkgcache-host-health.sh +++ b/scripts/host/pkgcache-host-health.sh @@ -33,6 +33,14 @@ MARK='#pkgcache-cachefirst ' MANAGED_RE='^baseurl=https://[^ /]+(:[0-9]+)?/(almalinux|epel|remi)/[^ ]+ https://[^ ]+$' log() { logger -t pkgcache-host-health -p "daemon.$1" -- "${*:2}" 2>/dev/null || true; echo "$1: ${*:2}" >&2; } +# "mode" is read-only and is used by repos.sh sync/status: no lock (a 30 s wait that ends in an +# empty answer would make `sync` think the host is not OFF and revert it), no state dir needed. +if [ "${1:-mode}" = mode ]; then + if grep -q -s -F "$MARK" "$REPO_DIR"/*.repo 2>/dev/null; then echo origin-only + elif grep -q -s -E "$MANAGED_RE" "$REPO_DIR"/*.repo 2>/dev/null; then echo cache-first + else echo off; fi + exit 0 +fi mkdir -p "$STATE_DIR" exec 9>"$STATE_DIR/lock"; flock -w 30 9 || { echo "lock busy" >&2; exit 0; } SF="$STATE_DIR/state" diff --git a/scripts/host/pkgcache-host-repos.sh b/scripts/host/pkgcache-host-repos.sh index fcad9df..a1e6b5b 100755 --- a/scripts/host/pkgcache-host-repos.sh +++ b/scripts/host/pkgcache-host-repos.sh @@ -79,6 +79,10 @@ BKROOT="${PKGCACHE_BACKUP_ROOT:-/root}" update_ca() { [ "${PKGCACHE_NO_CATRUST:-0}" = 1 ] || update-ca-trust; } dnf_clean() { [ "${PKGCACHE_NO_CATRUST:-0}" = 1 ] || dnf clean metadata -q || true; } die() { echo "FATAL(pkgcache-host-repos): $*" >&2; exit 1; } +# Same lock as pkgcache-host-health.sh, so a health run can never rewrite repo files while +# apply/revert do (child processes that take the lock themselves must NOT be called inside). +with_lock() { mkdir -p "$LOCKDIR"; ( flock -w 60 8 || die "repo lock busy"; "$@" ) 8>"$LOCKDIR/lock"; } +LOCKDIR="${PKGCACHE_STATE_DIR:-/var/lib/pkgcache-host}" same() { [ "$(sha256sum < "$1")" = "$(sha256sum < "$2")" ]; } # cmp/diffutils is not on minimal hosts rewrite() { # $1 file $2 cache url @@ -122,7 +126,13 @@ for line in open(f).read().split('\n'): break sec.append(line) flush() -open(f, 'w').write('\n'.join(out)) +import os, tempfile +st = os.stat(f) +fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(f)), prefix='.pkgcache-', suffix='.tmp') +with os.fdopen(fd, 'w') as fh: + fh.write('\n'.join(out)); fh.flush(); os.fsync(fh.fileno()) +os.chmod(tmp, st.st_mode & 0o7777); os.chown(tmp, st.st_uid, st.st_gid) +os.rename(tmp, f) # atomic: a concurrent dnf sees the old or the new file, never half of one PY } @@ -152,10 +162,13 @@ case "$MODE" in cp -a "$REPOS"/*.repo "$B/yum.repos.d/" [ -e "$ANCHOR" ] && cp -a "$ANCHOR" "$B/" || touch "$B/.no-anchor-before" install -m 0644 "$CA_SRC" "$ANCHOR" && update_ca - for f in "$REPOS"/almalinux*.repo "$REPOS"/epel*.repo "$REPOS"/remi*.repo; do - [ -f "$f" ] || continue - grep -q -E '^#?\s*baseurl\s*=\s*https?://(repo\.almalinux\.org|download\.example|rpms\.remirepo\.net)/' "$f" && rewrite "$f" "$C" - done + rewrite_all_repos() { + for f in "$REPOS"/almalinux*.repo "$REPOS"/epel*.repo "$REPOS"/remi*.repo; do + [ -f "$f" ] || continue + if grep -q -E '^#?\s*baseurl\s*=\s*https?://(repo\.almalinux\.org|download\.example|rpms\.remirepo\.net)/' "$f"; then rewrite "$f" "$C"; fi + done + } + with_lock rewrite_all_repos install_timer echo "backup: $B" echo "changed files:"; for f in "$B"/yum.repos.d/*.repo; do same "$f" "$REPOS/$(basename "$f")" || echo " $REPOS/$(basename "$f")"; done @@ -164,7 +177,13 @@ case "$MODE" in remove_timer; rm -f "${PKGCACHE_STATE_DIR:-/var/lib/pkgcache-host}/state" B="${2:-$(ls -d "$BKROOT"/pkgcache-repo-backup-* 2>/dev/null | sort | tail -1)}" [ -d "$B/yum.repos.d" ] || die "no backup dir ($B)" - for f in "$B"/yum.repos.d/*.repo; do same "$f" "$REPOS/$(basename "$f")" || { cp -a "$f" "$REPOS/"; echo "restored $REPOS/$(basename "$f")"; }; done + restore_repos() { + for f in "$B"/yum.repos.d/*.repo; do + d="$REPOS/$(basename "$f")" + same "$f" "$d" || { cp -a "$f" "$d.pkgcache-restore" && mv -f "$d.pkgcache-restore" "$d"; echo "restored $d"; } # atomic for a concurrent dnf + done + } + with_lock restore_repos if [ -e "$B/.no-anchor-before" ]; then rm -f "$ANCHOR"; update_ca; echo "removed $ANCHOR"; fi dnf_clean echo "reverted from $B" diff --git a/scripts/tests/pkgcache-host.test.sh b/scripts/tests/pkgcache-host.test.sh index 23b16c4..f22c726 100755 --- a/scripts/tests/pkgcache-host.test.sh +++ b/scripts/tests/pkgcache-host.test.sh @@ -82,6 +82,10 @@ FAKE_CACHE=refused FAKE_ORIGIN=down "$HL" run 2>/dev/null; FAKE_CACHE=refused FA [ "$("$HL" mode)" = cache-first ] && ok "cache+origin both down: no fallback" || bad "network outage caused a fallback" FAKE_CACHE=refused "$HL" run 2>/dev/null; FAKE_CACHE=refused "$HL" run 2>/dev/null; [ "$("$HL" mode)" = origin-only ] && ok "connection refused counts as failure" || bad "refused not counted" +# mode must not wait for the health lock (a held lock once turned `mode` into an empty answer) +( flock 9; sleep 4 ) 9>"$T/state/lock" & sleep 0.5 +m=$(timeout 3 "$HL" mode || true); [ "$m" = origin-only ] && ok "mode answers while the health lock is held" || bad "mode blocked on the lock (got '$m')" +wait # ---- OFF via setting reverts cleanly, even from origin-only ---- echo "PKGCACHE_ENABLED=0" >"$T/pkgcache-host.conf"; printf 'PKGCACHE_CA=%s\n' "$T/ca.crt" >>"$T/pkgcache-host.conf" "$R" sync >/dev/null From 18dc4603da01878fbf542422f14e97fb578f18a6 Mon Sep 17 00:00:00 2001 From: jknapp Date: Sun, 29 Nov 2026 07:32:18 -0800 Subject: [PATCH 3/3] docs(pkg-cache): spell out the canary conf needed before the first sync Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- docs/pkg-cache.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/pkg-cache.md b/docs/pkg-cache.md index 4af9fb4..d1849f7 100644 --- a/docs/pkg-cache.md +++ b/docs/pkg-cache.md @@ -255,6 +255,7 @@ HTTP 200, non-empty, a real PGP signature). The `.asc` is what broke on 2026-11- repos are already cache-first with the origin as 2nd URL. They have no health timer and no `/etc/pkgcache-host.conf`, so `sync` treats them as OFF and would revert them. To keep them on the cache, write the config with `PKGCACHE_ENABLED=1` first. To take them off, run `revert`. +**Before the first `sync` on the canary (192.168.1.148, which must keep using the cache)**, write `/etc/pkgcache-host.conf` there with `PKGCACHE_ENABLED=1`, `PKGCACHE_URL=https://192.168.1.40` and `PKGCACHE_CA=`. A `sync` without that file reverts it to the stock repos. **Why not "cache first, mirrorlist as fallback":** measured on AL10, with mirrorlist/metalink left in place dnf **ignores `baseurl` completely** (0 cache