Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 18dc4603da docs(pkg-cache): spell out the canary conf needed before the first sync
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6
2026-11-29 07:32:18 -08:00
shadowdaoandClaude Sonnet 5.5 ebe635501d 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6
2026-11-29 07:31:56 -08:00
shadowdaoandClaude Sonnet 5.5 b28e561387 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6
2026-11-29 07:23:46 -08:00
jknapp a971412243 Merge pull request 'mariadb client: ssl-verify-server-cert=0 drop-in (cac, cac-fpm)' (#66) from fix/client-ssl-verify-off into trunk
Cloud Apache Container / plan (push) Successful in 9s
Cloud Apache Container / Shell-Checks (push) Successful in 1m52s
Cloud Apache Container / Build-and-Push (82) (push) Failing after 3m38s
Cloud Apache Container / Build-Shared-httpd (push) Failing after 3m15s
Cloud Apache Container / Build-LiteSpeed-Images (82) (push) Successful in 4m53s
Cloud Apache Container / Build-Shared-OLS (push) Successful in 4m0s
Cloud Apache Container / Build-LSPHP-Images (82) (push) Successful in 5m26s
Cloud Apache Container / Build-LiteSpeed-Images (83) (push) Successful in 3m48s
Cloud Apache Container / Build-LiteSpeed-Images (84) (push) Failing after 3m36s
Cloud Apache Container / Build-LiteSpeed-Images (85) (push) Failing after 3m55s
Cloud Apache Container / Build-LSPHP-Images (83) (push) Failing after 3m53s
Cloud Apache Container / Build-LSPHP-Images (85) (push) Failing after 3m53s
Cloud Apache Container / Build-FPM-Images (82) (push) Successful in 9m34s
Cloud Apache Container / Build-FPM-Images (83) (push) Successful in 9m33s
Cloud Apache Container / Build-and-Push (84) (push) Failing after 3m26s
Cloud Apache Container / Build-and-Push (83) (push) Successful in 16m11s
Cloud Apache Container / Build-and-Push (85) (push) Failing after 3m5s
Cloud Apache Container / Build-FPM-Images (84) (push) Successful in 8m58s
Cloud Apache Container / Build-FPM-Images (85) (push) Successful in 9m22s
Cloud Apache Container / Build-and-Push (86) (push) Failing after 3m16s
Cloud Apache Container / Build-FPM-Images (86) (push) Successful in 10m0s
Cloud Apache Container / Build-LSPHP-Images (84) (push) Failing after 1h14m34s
2026-11-29 05:43:45 +00:00
shadowdaoandClaude Opus 5.5 89547c395f mariadb client: ssl-verify-server-cert=0 drop-in (cac, cac-fpm)
An 11.x client fails against a 10.11 server ("ERROR 2026: SSL is required,
but the server does not support it") and against 11.x with a passwordless
account ("self-signed certificate"). Ship /etc/my.cnf.d/zz-whp-client.cnf with
[client] ssl-verify-server-cert=0 so the client series does not matter; TLS is
still negotiated where the server offers it. Measured: mariadb:11.8 client
with the drop-in vs 10.11.18 and 11.8 servers, 10.11 client vs both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6
2026-11-28 11:03:30 -08:00
jknappandClaude Opus 5.5 89aef8100b Merge pull request 'ci: run amd64 jobs on the ephemeral runners only' (#65) [skip ci]
Workflow-only change; [skip ci] so the merge does not rebuild/publish images.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6
2026-11-26 18:13:31 +00:00
8 changed files with 418 additions and 32 deletions

No files matched your search

+2
View File
@@ -80,6 +80,8 @@ COPY ./configs/prod-php.ini /etc/php.ini
COPY ./configs/zz-php2shell-mitigation.ini /etc/php.d/zz-php2shell-mitigation.ini COPY ./configs/zz-php2shell-mitigation.ini /etc/php.d/zz-php2shell-mitigation.ini
COPY ./configs/phpinfo.php /var/www/html/ COPY ./configs/phpinfo.php /var/www/html/
COPY ./configs/mariadb.repo /etc/yum.repos.d/ COPY ./configs/mariadb.repo /etc/yum.repos.d/
# MariaDB client defaults: connect to the WHP mysql container whatever the client/server series.
COPY ./configs/whp-mariadb-client.cnf /etc/my.cnf.d/zz-whp-client.cnf
# mirror.mariadb.org names the arch dir amd64/aarch64 (not $basearch); amd64 result is byte-identical. # mirror.mariadb.org names the arch dir amd64/aarch64 (not $basearch); amd64 result is byte-identical.
RUN sed -i "s/rhel\$releasever-amd64/rhel\$releasever-$(uname -m | sed s/x86_64/amd64/)/" /etc/yum.repos.d/mariadb.repo RUN sed -i "s/rhel\$releasever-amd64/rhel\$releasever-$(uname -m | sed s/x86_64/amd64/)/" /etc/yum.repos.d/mariadb.repo
COPY ./configs/index.php /var/www/html/ COPY ./configs/index.php /var/www/html/
+2
View File
@@ -77,6 +77,8 @@ COPY ./configs/prod-php.ini /etc/php.ini
# all images ship PHP >= 8.2.35 / 8.3.36 / 8.4.27 / 8.5.12. # all images ship PHP >= 8.2.35 / 8.3.36 / 8.4.27 / 8.5.12.
COPY ./configs/zz-php2shell-mitigation.ini /etc/php.d/zz-php2shell-mitigation.ini COPY ./configs/zz-php2shell-mitigation.ini /etc/php.d/zz-php2shell-mitigation.ini
COPY ./configs/mariadb.repo /etc/yum.repos.d/ COPY ./configs/mariadb.repo /etc/yum.repos.d/
# MariaDB client defaults: connect to the WHP mysql container whatever the client/server series.
COPY ./configs/whp-mariadb-client.cnf /etc/my.cnf.d/zz-whp-client.cnf
# mirror.mariadb.org names the arch dir amd64/aarch64 (not $basearch); amd64 result is byte-identical. # mirror.mariadb.org names the arch dir amd64/aarch64 (not $basearch); amd64 result is byte-identical.
RUN sed -i "s/rhel\$releasever-amd64/rhel\$releasever-$(uname -m | sed s/x86_64/amd64/)/" /etc/yum.repos.d/mariadb.repo RUN sed -i "s/rhel\$releasever-amd64/rhel\$releasever-$(uname -m | sed s/x86_64/amd64/)/" /etc/yum.repos.d/mariadb.repo
+19
View File
@@ -0,0 +1,19 @@
# Client defaults for the mariadb/mysql/mariadb-dump CLIs in this image.
#
# The MariaDB server runs in WHP's separate `mysql` container, reached over
# the docker bridge. An 11.x client defaults to "TLS required, verify the
# certificate": against a 10.11 server it fails with
# ERROR 2026: SSL is required, but the server does not support it
# and against an 11.x server with a passwordless account with "self-signed
# certificate". This image ships a 10.11 client today (no effect), but WP-CLI
# `wp db ...`, mysqldump and any client a customer adds would break the day the
# client series differs from the server's.
#
# ssl-verify-server-cert=0 (measured on mariadb:11.8 and 10.11.18 clients vs
# 10.11.18 and 11.8 servers) keeps TLS negotiated when the server offers it and
# stops the verification/"required" failure, so a customer who points the CLI at
# a remote TLS database is not downgraded to plaintext. A customer who wants
# verification passes --ssl-verify-server-cert or sets it in ~/.my.cnf (later
# files and the command line win).
[client]
ssl-verify-server-cert=0
+37 -12
View File
@@ -217,17 +217,45 @@ 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 The script is canonical here (`.gitea/scripts/resolve-base-image.sh`); other repos
carry byte-identical copies. 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: The package cache is **not** part of the stock WHP setup. A host uses the
- backs up every `/etc/yum.repos.d/*.repo` to `/root/pkgcache-repo-backup-<UTC>/`; distro repos unless its server setting turns the cache on. The setting is
- installs the name-constrained CA as a system anchor; `/etc/pkgcache-host.conf` (template: `scripts/host/conf.example`):
- rewrites the AlmaLinux, EPEL and Remi sections to `baseurl=<cache>/... <origin>/...`;
- comments out mirrorlist/metalink in those sections;
- sets `gpgcheck=1`, plus `repo_gpgcheck=1` for AlmaLinux and Remi.
`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://<cache host>
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-<UTC>/`;
- installs the CA as a system anchor;
- rewrites the AlmaLinux, EPEL and Remi sections to `baseurl=<cache>/... <origin>/...`;
- 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`.
**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=<path to ca.crt>`. A `sync` without that file reverts it to the stock repos.
**Why not "cache first, mirrorlist as fallback":** measured on AL10, with **Why not "cache first, mirrorlist as fallback":** measured on AL10, with
mirrorlist/metalink left in place dnf **ignores `baseurl` completely** (0 cache mirrorlist/metalink left in place dnf **ignores `baseurl` completely** (0 cache
@@ -244,9 +272,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 **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) | | 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) ## Operating the cache (CT130)
+4
View File
@@ -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
+145
View File
@@ -0,0 +1,145 @@
#!/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 <cache>/<repo path>/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=<cache>/(almalinux|epel|remi)/... <origin>/...
## 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=<origin>/... — 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; }
# "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"
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
+114 -20
View File
@@ -3,9 +3,25 @@
## AppStream/CRB/extras/..., EPEL, Remi) at the internal package cache, with the ## 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). ## 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 ## OPT-IN, default OFF. The package cache is not part of the stock WHP setup: a host
## pkgcache-host-repos.sh status ## uses the distro repos unless its server setting turns the cache on. The setting
## pkgcache-host-repos.sh revert [BACKUP_DIR] # default: newest backup ## 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://<cache host> 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): ## Fallback design (measured 2026-10-21 on AlmaLinux 10.2):
## * each rewritten section gets baseurl=<cache>/<prefix>/<path> <origin>/<path> ## * each rewritten section gets baseurl=<cache>/<prefix>/<path> <origin>/<path>
@@ -23,9 +39,50 @@
set -euo pipefail set -euo pipefail
MODE="${1:-status}" MODE="${1:-status}"
CA_SRC="$(dirname "$0")/pkg-cache-ca.crt" HERE="$(cd "$(dirname "$0")" && pwd)"
ANCHOR=/etc/pki/ca-trust/source/anchors/pkg-cache-ca.crt 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" <<UNIT
[Unit]
Description=Package-cache health check (falls dnf back to the origin repos if the cache is broken)
[Service]
Type=oneshot
ExecStart=$HEALTH run
TimeoutStartSec=120
UNIT
cat >"$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; } 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 same() { [ "$(sha256sum < "$1")" = "$(sha256sum < "$2")" ]; } # cmp/diffutils is not on minimal hosts
rewrite() { # $1 file $2 cache url rewrite() { # $1 file $2 cache url
@@ -69,39 +126,76 @@ for line in open(f).read().split('\n'):
break break
sec.append(line) sec.append(line)
flush() 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 PY
} }
case "$MODE" in 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) apply)
C="${2:?usage: apply https://<cache>}"; 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 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)" [ -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" 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" [ -e "$ANCHOR" ] && cp -a "$ANCHOR" "$B/" || touch "$B/.no-anchor-before"
install -m 0644 "$CA_SRC" "$ANCHOR" && update-ca-trust install -m 0644 "$CA_SRC" "$ANCHOR" && update_ca
for f in /etc/yum.repos.d/almalinux*.repo /etc/yum.repos.d/epel*.repo /etc/yum.repos.d/remi*.repo; do rewrite_all_repos() {
for f in "$REPOS"/almalinux*.repo "$REPOS"/epel*.repo "$REPOS"/remi*.repo; do
[ -f "$f" ] || continue [ -f "$f" ] || continue
grep -q -E '^#?\s*baseurl\s*=\s*https?://(repo\.almalinux\.org|download\.example|rpms\.remirepo\.net)/' "$f" && rewrite "$f" "$C" if grep -q -E '^#?\s*baseurl\s*=\s*https?://(repo\.almalinux\.org|download\.example|rpms\.remirepo\.net)/' "$f"; then rewrite "$f" "$C"; fi
done done
}
with_lock rewrite_all_repos
install_timer
echo "backup: $B" 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) 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)" [ -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 restore_repos() {
if [ -e "$B/.no-anchor-before" ]; then rm -f "$ANCHOR"; update-ca-trust; echo "removed $ANCHOR"; fi for f in "$B"/yum.repos.d/*.repo; do
dnf clean metadata -q || true 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" echo "reverted from $B"
;; ;;
status) 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" echo "setting: $([ "$(conf_get PKGCACHE_ENABLED)" = 1 ] && echo "ON (url $(conf_get PKGCACHE_URL))" || echo OFF)"
ls -d /root/pkgcache-repo-backup-* 2>/dev/null | sed 's/^/backup: /' || true 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" [ -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 esac
+95
View File
@@ -0,0 +1,95 @@
#!/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 '<repomd/>\n200';;
ok) case "$u" in *.asc) printf -- '-----BEGIN PGP SIGNATURE-----\nx\n200';; *) printf '<repomd/>\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"
# 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
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