Compare commits

..
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 bd685f72fb pkg-cache selfcheck: re-check nginx started by something else while stopped; fix test fake is-active
The marker branch left a manually/otherwise restarted nginx running unchecked
while the disks were still bad. Now a running nginx with our marker present is
judged like normal operation (stopped again if unhealthy). The test systemctl
fake always returned 0 for is-active, hiding the admin-stopped branch; fixed,
and the tests now pin PKGCACHE_SERVICES and cover the empty-list case.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6
2026-11-29 07:30:52 -08:00
shadowdaoandClaude Sonnet 5.5 8107b29e14 feat(pkg-cache): CT130 self-check timer (stop nginx+registry when the cache is unhealthy)
pkg-cache/pkgcache-selfcheck.{sh,service,timer}: every 60 s check rw mounts, write+fsync+delete
and a fresh fetch through nginx; on failure stop nginx + registry so clients fail over to the
origin instantly (connection refused); restart after 3 healthy runs + nginx -t. Never fsck.
Alert = Uptime Kuma monitors 53/54 going DOWN. Deployed on CT130 2026-11-29.

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
9 changed files with 282 additions and 392 deletions

No files matched your search

+17 -34
View File
@@ -217,45 +217,17 @@ 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`) — opt-in, default OFF
## WHP hosts (`scripts/host/pkgcache-host-repos.sh`)
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`):
```
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):
`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-<UTC>/`;
- installs the CA as a system anchor;
- installs the name-constrained 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.
- sets `gpgcheck=1`, plus `repo_gpgcheck=1` for AlmaLinux and Remi.
**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.
`revert [DIR]` restores byte-identical files (verified on AL9 and AL10) and
removes the anchor. `status` shows the current state.
**Why not "cache first, mirrorlist as fallback":** measured on AL10, with
mirrorlist/metalink left in place dnf **ignores `baseurl` completely** (0 cache
@@ -272,9 +244,20 @@ 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)
- **Self-check (`pkg-cache/`).** `pkgcache-selfcheck.timer` runs `/usr/local/sbin/pkgcache-selfcheck` every 60 s. Background: on 2026-11-26 the CT's ext4 images went `emergency_ro` and nginx answered an empty reply for anything uncached, so clients' dnf failed instead of falling back.
- Checks: `/` and `/srv/cache` mounted rw; write+fsync+delete on both; a refresh fetch through nginx of a tiny metadata file (10 s; one retry).
- On failure: stops nginx and `docker-registry`, so clients get connection refused and fall back within a second. It logs at `daemon.err` (`journalctl -t pkgcache-selfcheck`). If the origin is unreachable too it only warns.
- Alert: Uptime Kuma monitors 53 and 54 (https://100.123.207.73/ and :5000/v2/) go DOWN because the services are stopped. No webhook is configured on CT130.
- Recovery: only for services it stopped. 3 consecutive fully healthy runs and a good `nginx -t`, then it starts them and re-checks the fetch.
- It never runs fsck or remounts. After `emergency_ro` an operator still has to fix the disks (see the 2026-11-26 incident) and the self-check restarts the services on its own.
- Install: copy the script to `/usr/local/sbin/pkgcache-selfcheck` (0755) and the two units to `/etc/systemd/system/`, then `systemctl enable --now pkgcache-selfcheck.timer`. State is in `/run/pkgcache-selfcheck/`.
- **nginx config.**
- `/etc/nginx/conf.d/pkgcache-http.conf` holds the cache zone, maps and log format.
- `/etc/nginx/pkgcache/{server-common,meta,pkg}.conf` hold the shared settings.
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=pkg-cache self-check (stop nginx+registry when the cache is unhealthy)
Documentation=file:///usr/local/sbin/pkgcache-selfcheck
After=nginx.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/pkgcache-selfcheck
TimeoutStartSec=120
Nice=5
+139
View File
@@ -0,0 +1,139 @@
#!/bin/bash
## pkgcache-selfcheck — run ON CT130 every 60 s by pkgcache-selfcheck.timer.
##
## Why: on 2026-11-26 both ext4 images (rootfs + /srv/cache, raw files on a CIFS
## 'soft' share) went emergency_ro. nginx kept answering cached files but sent an
## EMPTY reply (curl 52) for anything uncached, so clients' dnf failed instead of
## falling back to the origin. A refused connection falls back in <1 s; a half-dead
## cache does not. So when the cache is not healthy this script STOPS nginx and the
## registry (connection refused = fast fallback) and starts them again once healthy.
##
## Checks (all must pass):
## 1. every path in CHECK_PATHS is on a filesystem mounted rw (not ro/emergency_ro)
## 2. write + fsync + delete of a small file on each path succeeds (15 s limit)
## 3. nginx can fetch a fresh object through itself: a localhost refresh request
## (X-Pkgcache-Refresh: 1 bypasses the cached copy and re-stores it) of a tiny
## metadata file must return 200 with the expected body within 10 s. If it
## fails, the origin is fetched directly: origin also unreachable = an internet
## outage, not a cache fault, so nothing is stopped (WARN only).
## On failure: stop SERVICES, drop a marker in STATE_DIR, log at daemon.err.
## Alert path: Uptime Kuma monitors 53 (https://100.123.207.73/) and 54 (:5000/v2/)
## go DOWN because the services are stopped. No webhook/secret is configured on
## CT130, none is invented here.
## Recovery: only if WE stopped them (marker). After OK_NEEDED consecutive fully
## passing runs and a good `nginx -t`, start the services, re-run the fetch check,
## and stop them again if it fails. NEVER runs fsck or remounts anything.
##
## Test knobs (env): PKGCACHE_STATE_DIR, PKGCACHE_CHECK_PATHS, PKGCACHE_SERVICES,
## PKGCACHE_PROBE_URL, PKGCACHE_ORIGIN_URL, PKGCACHE_SYSTEMCTL, PKGCACHE_NGINX_TEST.
set -uo pipefail
STATE_DIR=${PKGCACHE_STATE_DIR:-/run/pkgcache-selfcheck}
CHECK_PATHS=${PKGCACHE_CHECK_PATHS:-"/ /srv/cache"}
SERVICES=${PKGCACHE_SERVICES-"nginx docker-registry"} # empty = manage nothing (tests)
PROBE_URL=${PKGCACHE_PROBE_URL:-http://127.0.0.1/almalinux/RPM-GPG-KEY-AlmaLinux-9}
ORIGIN_URL=${PKGCACHE_ORIGIN_URL:-https://repo.almalinux.org/almalinux/RPM-GPG-KEY-AlmaLinux-9}
PROBE_MAGIC='BEGIN PGP PUBLIC KEY BLOCK'
SYSTEMCTL=${PKGCACHE_SYSTEMCTL:-systemctl}
NGINX_TEST=${PKGCACHE_NGINX_TEST:-nginx -t}
OK_NEEDED=3
log() { local p=$1; shift; logger -t pkgcache-selfcheck -p "daemon.$p" -- "$*" 2>/dev/null || true; echo "$p: $*" >&2; }
mkdir -p "$STATE_DIR" 2>/dev/null || { log err "cannot create $STATE_DIR"; exit 1; }
exec 9>"$STATE_DIR/lock"
flock -n 9 || { echo "another run in progress" >&2; exit 0; }
MARKER="$STATE_DIR/stopped"
OKFILE="$STATE_DIR/okcount"
status() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*" >"$STATE_DIR/status" 2>/dev/null || true; }
# ---- check 1 + 2: mounts and write+fsync+delete ------------------------------
check_disks() {
local p opts f
for p in $CHECK_PATHS; do
opts=$(findmnt -n -o OPTIONS --target "$p" 2>/dev/null) || { echo "$p: findmnt failed"; return 1; }
case ",$opts," in *,rw,*) ;; *) echo "$p: not mounted rw (options: $opts)"; return 1 ;; esac
case ",$opts," in *,ro,*) echo "$p: mounted ro (options: $opts)"; return 1 ;; esac
f="$p/.pkgcache-selfcheck.$$"
if ! timeout -k 2 15 dd if=/dev/zero of="$f" bs=4096 count=1 conv=fsync status=none 2>/dev/null; then
rm -f -- "$f" 2>/dev/null; echo "$p: write+fsync failed"; return 1
fi
timeout -k 2 15 rm -f -- "$f" || { echo "$p: delete failed"; return 1; }
[ -e "$f" ] && { echo "$p: test file still present after delete"; return 1; }
done
return 0
}
# ---- check 3: nginx fetches a fresh object through itself ---------------------
probe_once() {
local body
body=$(curl -sS --max-time 10 -H 'X-Pkgcache-Refresh: 1' -w '\n%{http_code}' "$PROBE_URL" 2>&1) || { echo "curl: ${body##*$'\n'}"; return 1; }
local code=${body##*$'\n'}; body=${body%$'\n'*}
[ "$code" = 200 ] || { echo "HTTP $code"; return 1; }
case "$body" in *"$PROBE_MAGIC"*) return 0 ;; *) echo "200 but unexpected body (${#body} bytes)"; return 1 ;; esac
}
# prints a reason on failure; return 2 = cache fault is NOT proven (origin unreachable too)
check_fetch() {
local why
why=$(probe_once) && return 0
sleep 3 # one retry: don't act on a single blip
why=$(probe_once) && return 0
if curl -sS -o /dev/null --max-time 10 -f "$ORIGIN_URL" 2>/dev/null; then
echo "fetch through nginx failed ($why) but the origin is reachable"; return 1
fi
echo "fetch through nginx failed ($why); origin unreachable too (upstream outage, not a cache fault)"; return 2
}
stop_services() {
local s
for s in $SERVICES; do $SYSTEMCTL stop "$s" 2>&1 | sed 's/^/stop: /' >&2; done
printf '%s %s\n' "$(date -u +%FT%TZ)" "$1" >"$MARKER" 2>/dev/null || true
echo 0 >"$OKFILE" 2>/dev/null || true
}
# ---- main ---------------------------------------------------------------------
# Something else (an admin, a package script) started nginx while our stop marker exists:
# do not "recover" on our own schedule or leave it running unchecked. Drop the marker and
# judge it like normal operation below, which stops it again if the cache is unhealthy.
if [ -e "$MARKER" ] && $SYSTEMCTL is-active --quiet nginx; then
log warning "nginx was started by something else while stopped by this script; re-checking it now"
rm -f "$MARKER" "$OKFILE"
fi
if [ -e "$MARKER" ]; then
# we stopped the services earlier: look for recovery
if why=$(check_disks); then
n=$(( $(cat "$OKFILE" 2>/dev/null || echo 0) + 1 )); echo "$n" >"$OKFILE"
if [ "$n" -lt "$OK_NEEDED" ]; then
log notice "recovering: disks healthy ($n/$OK_NEEDED), services stay stopped"; status "stopped; recovering $n/$OK_NEEDED"; exit 0
fi
if ! tout=$($NGINX_TEST 2>&1); then
log err "disks healthy but nginx config test failed, staying stopped: ${tout//$'\n'/ | }"; echo 0 >"$OKFILE"; status "stopped; nginx -t failed"; exit 1
fi
for s in $SERVICES; do $SYSTEMCTL start "$s" 2>&1 | sed 's/^/start: /' >&2; done
sleep 2
why=$(check_fetch); rc=$?
if [ $rc = 1 ]; then
log err "restarted but the fetch check fails ($why); stopping again"; stop_services "restart check failed: $why"; status "stopped; restart check failed"; exit 1
fi
rm -f "$MARKER" "$OKFILE"
log notice "RECOVERED: $OK_NEEDED consecutive healthy runs, nginx -t ok, services started"; status "ok (recovered)"; exit 0
else
echo 0 >"$OKFILE"; log err "still unhealthy, services stay stopped: $why"; status "stopped; $why"; exit 1
fi
fi
# normal operation
if ! why=$(check_disks); then
log err "UNHEALTHY: $why -> stopping ${SERVICES} so clients fall back to the origin (connection refused)"
stop_services "$why"; status "stopped; $why"; exit 1
fi
if ! $SYSTEMCTL is-active --quiet nginx; then
log warning "nginx is not active (not stopped by this script); disks fine; fetch check skipped"; status "nginx inactive (manual?)"; exit 0
fi
why=$(check_fetch); rc=$?
case $rc in
0) status ok; exit 0 ;;
2) log warning "$why"; status "warn: $why"; exit 0 ;;
*) log err "UNHEALTHY: $why -> stopping ${SERVICES}"; stop_services "$why"; status "stopped; $why"; exit 1 ;;
esac
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Run the pkg-cache self-check every 60 s
[Timer]
OnBootSec=45s
OnUnitActiveSec=60s
AccuracySec=1s
[Install]
WantedBy=timers.target
-4
View File
@@ -1,4 +0,0 @@
# /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
@@ -1,145 +0,0 @@
#!/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
+20 -114
View File
@@ -3,25 +3,9 @@
## 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://<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.
## 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
##
## Fallback design (measured 2026-10-21 on AlmaLinux 10.2):
## * each rewritten section gets baseurl=<cache>/<prefix>/<path> <origin>/<path>
@@ -39,50 +23,9 @@
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" <<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; }
CA_SRC="$(dirname "$0")/pkg-cache-ca.crt"
ANCHOR=/etc/pki/ca-trust/source/anchors/pkg-cache-ca.crt
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
@@ -126,76 +69,39 @@ for line in open(f).read().split('\n'):
break
sec.append(line)
flush()
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
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%/}"
C="${2:?usage: apply https://<cache>}"; 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)
B=/root/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/"
cp -a /etc/yum.repos.d/*.repo "$B/yum.repos.d/"
[ -e "$ANCHOR" ] && cp -a "$ANCHOR" "$B/" || touch "$B/.no-anchor-before"
install -m 0644 "$CA_SRC" "$ANCHOR" && update_ca
rewrite_all_repos() {
for f in "$REPOS"/almalinux*.repo "$REPOS"/epel*.repo "$REPOS"/remi*.repo; do
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
[ -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
grep -q -E '^#?\s*baseurl\s*=\s*https?://(repo\.almalinux\.org|download\.example|rpms\.remirepo\.net)/' "$f" && rewrite "$f" "$C"
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
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
;;
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)}"
B="${2:-$(ls -d /root/pkgcache-repo-backup-* 2>/dev/null | sort | tail -1)}"
[ -d "$B/yum.repos.d" ] || die "no backup dir ($B)"
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
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
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
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
[ -e "$ANCHOR" ] && echo "CA anchor: $ANCHOR" || echo "CA anchor: absent"
;;
*) die "usage: sync | apply [URL] | status | revert [DIR]" ;;
*) die "usage: apply URL | status | revert [DIR]" ;;
esac
-95
View File
@@ -1,95 +0,0 @@
#!/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
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
## pkgcache-selfcheck.test.sh — fixture test for pkg-cache/pkgcache-selfcheck.sh.
## Fakes findmnt/curl/systemctl/logger via PATH; one extra case uses a REAL
## read-only bind mount when `sudo -n` works (skipped otherwise).
set -euo pipefail
HERE=$(cd "$(dirname "$0")/../.." && pwd)
S="$HERE/pkg-cache/pkgcache-selfcheck.sh"
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
fail=0
ok() { echo "ok - $1"; }
bad() { echo "FAIL - $1"; fail=1; }
mkdir -p "$T/bin" "$T/disk1" "$T/disk2"
cat >"$T/bin/findmnt" <<'EOS'
#!/bin/sh
# last arg = path; $FAKE_RO = path that reports ro
for a; do p=$a; done
case "$p" in "$FAKE_RO") echo "ro,relatime" ;; *) echo "rw,relatime" ;; esac
EOS
cat >"$T/bin/curl" <<'EOS'
#!/bin/sh
# FAKE_PROBE=ok|http500|empty|refused ; FAKE_ORIGIN=ok|down
for a; do last=$a; done
case "$last" in
*probe*) case "$FAKE_PROBE" in
ok) printf -- '-----BEGIN PGP PUBLIC KEY BLOCK-----\nx\n200'; exit 0;;
http500) printf 'err\n500'; exit 0;;
empty) echo "curl: (52) Empty reply from server" >&2; exit 52;;
refused) echo "curl: (7) refused" >&2; exit 7;; esac;;
*origin*) [ "$FAKE_ORIGIN" = ok ] && exit 0 || exit 7;;
esac
EOS
cat >"$T/bin/systemctl" <<'EOS'
#!/bin/sh
echo "$*" >>"$CALLS"
case "$1" in is-active) [ -e "$ACTIVE" ]; exit $?;; start) touch "$ACTIVE";; stop) rm -f "$ACTIVE";; esac
exit 0
EOS
printf '#!/bin/sh\nexit 0\n' >"$T/bin/logger"; chmod +x "$T/bin/"*
export PATH="$T/bin:$PATH" CALLS="$T/calls" ACTIVE="$T/active"
export PKGCACHE_STATE_DIR="$T/state" PKGCACHE_CHECK_PATHS="$T/disk1 $T/disk2"
export PKGCACHE_PROBE_URL=http://probe PKGCACHE_ORIGIN_URL=http://origin
export PKGCACHE_SERVICES="nginx docker-registry" # explicit: never rely on the script default in a test
export PKGCACHE_NGINX_TEST=true FAKE_RO=none FAKE_PROBE=ok FAKE_ORIGIN=ok
run() { "$S" >"$T/out" 2>&1; }
reset() { rm -rf "$T/state" "$T/calls"; touch "$T/calls" "$ACTIVE"; }
stopped() { [ ! -e "$ACTIVE" ] && grep -q '^stop nginx' "$CALLS"; }
reset; run && ! stopped && ok "healthy: nothing stopped" || bad "healthy"
[ -z "$(ls -A "$T/disk1")" ] && ok "test file removed" || bad "test file left behind"
reset; FAKE_RO="$T/disk2" run && bad "ro disk exit" || { stopped && grep -q '^stop docker-registry' "$CALLS" && ok "ro mount: nginx+registry stopped" || bad "ro mount not stopped"; }
reset; chmod 555 "$T/disk1"; if [ "$(id -u)" != 0 ]; then run && bad "unwritable exit" || { stopped && ok "write failure: stopped" || bad "write failure not stopped"; }; fi; chmod 755 "$T/disk1"
reset; FAKE_PROBE=empty run && bad "empty reply exit" || { stopped && ok "empty reply (curl 52), origin up: stopped" || bad "empty reply not stopped"; }
reset; FAKE_PROBE=http500 run && bad "500 exit" || { stopped && ok "HTTP 500, origin up: stopped" || bad "500 not stopped"; }
reset; FAKE_PROBE=empty FAKE_ORIGIN=down run && ! stopped && ok "origin down too: warn only, not stopped" || bad "upstream outage must not stop"
# recovery: needs 3 consecutive good runs, only if WE stopped it
reset; FAKE_PROBE=empty run || true
export FAKE_PROBE=ok
run; stopped && ok "recovery 1/3: still stopped" || bad "recovery 1"
FAKE_RO="$T/disk1" run || true; run; stopped && ok "failure resets the streak (1/3 again)" || bad "streak reset"
run; stopped && ok "recovery 2/3: still stopped" || bad "recovery 2"
run && [ -e "$ACTIVE" ] && [ ! -e "$T/state/stopped" ] && grep -q '^start nginx' "$CALLS" && ok "3rd healthy run: services started, marker cleared" || bad "recovery 3"
# nginx -t failure blocks the restart
reset; FAKE_PROBE=empty run || true; export FAKE_PROBE=ok
run; run; PKGCACHE_NGINX_TEST=false run && bad "nginx -t fail exit" || { [ ! -e "$ACTIVE" ] && ok "bad nginx config: stays stopped" || bad "started despite bad config"; }
# restart whose fetch check fails is stopped again
reset; FAKE_PROBE=empty run || true; run; run; FAKE_PROBE=empty run && bad "restart-fail exit" || { [ ! -e "$ACTIVE" ] && [ -e "$T/state/stopped" ] && ok "restart with failing fetch: stopped again" || bad "restart-fail"; }
# never start something an admin stopped
reset; rm -f "$ACTIVE"; run && ! grep -q '^start' "$CALLS" && ok "admin-stopped nginx is left alone" || bad "admin stop"
# empty services list must mean "manage nothing", never the real defaults
reset; PKGCACHE_SERVICES="" FAKE_PROBE=empty run || true
! grep -q '^stop' "$CALLS" && ok "empty PKGCACHE_SERVICES: nothing stopped" || bad "empty services list stopped something"
# something else restarts nginx while our marker exists: re-checked, stopped again if still bad
reset; FAKE_PROBE=empty run || true; touch "$ACTIVE"
FAKE_RO="$T/disk1" run || true
[ ! -e "$ACTIVE" ] && ok "nginx restarted by someone else while unhealthy: stopped again" || bad "fight: left running"
reset; FAKE_PROBE=empty run || true; touch "$ACTIVE"
run && [ -e "$ACTIVE" ] && [ ! -e "$T/state/stopped" ] && ok "nginx restarted by someone else and healthy: left running, marker cleared" || bad "fight: healthy case"
# REAL read-only bind mount
mkdir -p "$T/real" "$T/robind"
if sudo -n mount --bind "$T/real" "$T/robind" 2>/dev/null && sudo -n mount -o remount,bind,ro "$T/robind"; then
rm "$T/bin/findmnt"; reset; PKGCACHE_CHECK_PATHS="$T/robind" run && bad "real ro exit" || { stopped && ok "REAL read-only bind mount: stopped" || bad "real ro"; }
sudo -n umount "$T/robind"
else echo "skip - cannot bind-mount here, skipping the real ro bind mount case"; fi
exit $fail