#!/bin/bash ## pkgcache-host-repos.sh — point a WHP HOST's dnf repos (AlmaLinux 9/10 BaseOS/ ## 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). ## ## 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=// / ## — dnf/librepo treats the second URL as a failover mirror. ## * the section's mirrorlist=/metalink= is COMMENTED OUT. Measured: with a ## mirrorlist/metalink present dnf ignores baseurl entirely (0 cache requests), ## so "cache first, mirrorlist as fallback" is not something dnf can do. ## * gpgcheck=1 everywhere; repo_gpgcheck=1 for AlmaLinux + Remi (both sign ## repomd.xml); EPEL has no repomd signature and relies on HTTPS end to end. ## * trust: the name-constrained pkg-cache CA is installed as a system anchor ## (/etc/pki/ca-trust/source/anchors/pkg-cache-ca.crt). Its nameConstraints ## (IP 192.168.1.40, pkg-cache.* DNS) are enforced by OpenSSL — a cert it ## signs for any other name fails ("permitted subtree violation"). ## Every changed file is copied to /root/pkgcache-repo-backup-/ first. set -euo pipefail MODE="${1:-status}" 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 rewrite() { # $1 file $2 cache url python3 - "$1" "$2" <<'PY' import re, sys f, C = sys.argv[1], sys.argv[2].rstrip('/') maps = [ # regex on a (commented or live) baseurl, cache prefix, origin base, repomd signed? (r'^#?\s*baseurl\s*=\s*https?://repo\.almalinux\.org/almalinux/(\S+)', 'almalinux', 'https://repo.almalinux.org/almalinux/', True), (r'^#?\s*baseurl\s*=\s*https?://download\.example/pub/epel/(\S+)', 'epel', 'https://dl.fedoraproject.org/pub/epel/', False), (r'^#?\s*baseurl\s*=\s*https?://rpms\.remirepo\.net/(\S+)', 'remi', 'https://rpms.remirepo.net/', True), ] out, sec = [], [] state = {'hit': False, 'sig': False} def flush(): for x in sec: if state['hit']: if re.match(r'^(mirrorlist|metalink)\s*=', x): x = '#' + x elif re.match(r'^(gpgcheck|repo_gpgcheck)\s*=', x): continue out.append(x) if state['hit']: # keep blank-line layout: insert before trailing blanks tail = [] while out and out[-1].strip() == '': tail.append(out.pop()) out.append('gpgcheck=1') if state['sig']: out.append('repo_gpgcheck=1') out.extend(tail) sec.clear(); state['hit'] = state['sig'] = False for line in open(f).read().split('\n'): if line.startswith('['): flush() for rx, prefix, origin, sig in maps: m = re.match(rx, line) if m: p = m.group(1) line = f'baseurl={C}/{prefix}/{p} {origin}{p}' state['hit'] = True; state['sig'] = state['sig'] or sig break sec.append(line) flush() open(f, 'w').write('\n'.join(out)) 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:-}" 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=$BKROOT/pkgcache-repo-backup-$(date -u +%Y%m%dT%H%M%SZ) mkdir -p "$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 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" "$REPOS/$(basename "$f")" || echo " $REPOS/$(basename "$f")"; done ;; revert) 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 if [ -e "$B/.no-anchor-before" ]; then rm -f "$ANCHOR"; update_ca; echo "removed $ANCHOR"; fi dnf_clean echo "reverted from $B" ;; status) 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: sync | apply [URL] | status | revert [DIR]" ;; esac