From d8da3d7b94391ca7771cb2498496ded48eaf8f20 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:08:58 +0100 Subject: [PATCH] Bound staging retention with six-build policy and shared publication coordination --- website/ops/STAGING-RETENTION.md | 81 ++++++ website/ops/dunerealms-build-release | 31 +++ website/ops/dunerealms-ci-trigger | 15 ++ .../ops/dunerealms-staging-build-lock.conf | 5 + website/ops/dunerealms-staging-retention.conf | 3 + website/ops/prune-staging-builds.py | 245 ++++++++++++++++++ website/ops/test_staging_retention.py | 138 ++++++++++ 7 files changed, 518 insertions(+) create mode 100644 website/ops/STAGING-RETENTION.md create mode 100644 website/ops/dunerealms-build-release create mode 100644 website/ops/dunerealms-ci-trigger create mode 100644 website/ops/dunerealms-staging-build-lock.conf create mode 100644 website/ops/dunerealms-staging-retention.conf create mode 100644 website/ops/prune-staging-builds.py create mode 100644 website/ops/test_staging_retention.py diff --git a/website/ops/STAGING-RETENTION.md b/website/ops/STAGING-RETENTION.md new file mode 100644 index 00000000..741522ee --- /dev/null +++ b/website/ops/STAGING-RETENTION.md @@ -0,0 +1,81 @@ +# Staging build retention + +This bounds only `/mnt/HC_Volume_107481500/dunegit/ci/deploy-user/ci-deploy/artifacts`. +It does not operate on Git repositories, databases, uploads, backups or swap. +Default execution and `--dry-run` report JSON without deleting anything. +`--apply` is a separate explicit operation. Nothing in the website build installs +or enables this retention automatically. + +## Policy + +- Keep the six newest completed builds, plus active production, rollback, + pending/built commits, retained releases and their transitive staging dependencies. +- Inspect process working directories, executables, open descriptors, mappings + and absolute argv references. Unreadable process/release/state information + retains everything and reports the uncertainty. +- Future builds write a completion timestamp only after install/build/tests pass. + Legacy SHA directories are recognised from the existing builder's atomic final + rename contract and its four required release files; their directory timestamp + is the legacy completion-order approximation. Unknown or partial directories stay. +- An abandoned `.SHA.tmp.PID` directory additionally needs age >=24 hours, + an absent PID and a complete process/dependency inventory. +- Never descend into nested mounts. Root aliases, top-level symlinks and unknown + names cannot become deletion targets. Deletion uses a no-follow root descriptor + and Python's symlink-attack-resistant rmtree. Revalidate identity, publication + state and processes before each removal. +- Reclaim estimates use allocated blocks; multiply-linked files are excluded. + They are conservative estimates, not a promise of the final filesystem delta. + +## Integration — review before installation + +Use the existing hourly `dunerealms-prune-web-releases.service` and its timer; +install `dunerealms-staging-retention.conf` as that service's drop-in only after +the initial dry-run is accepted. It runs after release retention, outside CI. +Do not put it in the build workflow or promoter's ExecStartPost. + +All actors use the existing promotion `safe-lock`. Before enabling cleanup, +install both writer updates and the build service retry drop-in together: + +| Repository file | Installed target | +| --- | --- | +| `prune-staging-builds.py` | `/usr/local/sbin/dunerealms-prune-staging-builds` | +| `dunerealms-build-release` | `/usr/local/bin/dunerealms-build-release` | +| `dunerealms-ci-trigger` | `/usr/local/bin/dunerealms-ci-trigger` | +| `dunerealms-staging-build-lock.conf` | `/etc/systemd/system/dunerealms-ci-build.service.d/staging-lock.conf` | +| `dunerealms-staging-retention.conf` | `/etc/systemd/system/dunerealms-prune-web-releases.service.d/staging.conf` | + +Builder/request registration take a shared publication lock; cleanup and +promotion take the exclusive lock. Cleanup never waits for a busy mutex. +Expensive inventory runs outside the mutex, and cleanup leases it for only one +directory deletion at a time. The builder uses nonblocking acquisition and exit +75 for a temporary collision; systemd retries only 75, without waiting inside +the build or rerunning cleanup. Ordinary build errors are not retried by this +drop-in. Request registration locks only its atomic pending-commit write. + +Preflight: ensure `dunedeploy` can traverse the lock's parent path and read the +existing lock file, without granting it general access to promotion state. +Never replace the lock inode while any actor can use it. Verify this and the +retry configuration before enabling the retention hook; do not install only +the cleaner while leaving the old uncoordinated builder running. + +The reviewed deployed baselines on 19 November 2026 were: + +``` +5059e3fb5e7ca0ef3744642c32247d7c7f8ee0eca8d4386ad83b2f48930be4de /usr/local/bin/dunerealms-build-release +a5231da5f442bd7950ae36cc5cdf895081c6e8a38a8ea4e2d0f4c406e62cfa89 /usr/local/bin/dunerealms-ci-trigger +599c8dbf07a14651a19b50c26e44f23df1b662e2cba4386f00e4743883c9fd67 /usr/local/sbin/dunerealms-promote-safe-v3 +``` + +If these differ, review and merge newer server changes instead of overwriting +them. The existing promoter is not replaced by this patch. Reload systemd only +after installing the complete reviewed set; do not restart a running build or +publication to install it. + +## Verification + +`python3 -m unittest discover -s website/ops -p 'test_*.py'` exercises temporary +Linux fixtures, including real candidate removal, older protected versions, +transitive dependencies, stale/live temporary builds, pending state changes, +unreadable inventories, nested mounts and a separate concurrent publisher. +These are simulations; a production dry-run is separately required. Initial +production deletion remains outside this change and requires explicit approval. diff --git a/website/ops/dunerealms-build-release b/website/ops/dunerealms-build-release new file mode 100644 index 00000000..831111e3 --- /dev/null +++ b/website/ops/dunerealms-build-release @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +BASE=/home/dunedeploy/ci-deploy +REPO=/home/dunedeploy/web-deployment +# Share the publication mutex; no cleanup command is part of a build. +exec 9< /mnt/HC_Volume_107481500/dunegit/ci/promotion/safe-lock +flock --shared --nonblock 9 || { echo 'Publication mutex busy; build deferred to systemd retry'; exit 75; } +SHA=$(cat "$BASE/pending-commit") +[[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || exit 1 +cd "$REPO" +git fetch -q origin main +MAIN=$(git rev-parse FETCH_HEAD) +[[ "$SHA" == "$MAIN" ]] || { echo 'Not current main'; exit 1; } +DEST="$BASE/artifacts/$SHA" +TMP="$BASE/artifacts/.${SHA}.tmp.$$" +trap 'rm -rf "$TMP"' EXIT +mkdir -p "$TMP" +git archive "$SHA" website tools | tar -x -C "$TMP" +cd "$TMP/website" +corepack pnpm install --frozen-lockfile +corepack pnpm build +corepack pnpm test +[[ -f dist/server/index.js ]] || { echo 'Missing server build'; exit 1; } +python3 - "$SHA" "$TMP" <<'PY' +import json,pathlib,sys,time +(pathlib.Path(sys.argv[2])/'.staging-complete.json').write_text(json.dumps({'version':1,'sha':sys.argv[1],'completedAt':time.time()})) +PY +if [[ ! -d "$DEST" ]]; then mv "$TMP" "$DEST"; fi +printf '%s\n' "$SHA" > "$BASE/built-commit.tmp" +mv -f "$BASE/built-commit.tmp" "$BASE/built-commit" +echo "Built CI release: $SHA; production unchanged" diff --git a/website/ops/dunerealms-ci-trigger b/website/ops/dunerealms-ci-trigger new file mode 100644 index 00000000..f4e567fb --- /dev/null +++ b/website/ops/dunerealms-ci-trigger @@ -0,0 +1,15 @@ +#!/bin/bash +set -euo pipefail +SHA="${SSH_ORIGINAL_COMMAND:-}" +[[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "Ongeldige commit"; exit 1; } +REPO=/home/dunedeploy/web-deployment +git -C "$REPO" fetch -q origin main +MAIN=$(git -C "$REPO" rev-parse FETCH_HEAD) +if [ "$SHA" != "$MAIN" ]; then echo "Geweigerd: commit is niet de huidige main"; exit 1; fi +exec 9< /mnt/HC_Volume_107481500/dunegit/ci/promotion/safe-lock +flock --shared 9 +TMP=/home/dunedeploy/ci-deploy/.pending-commit.$$ +trap 'rm -f "$TMP"' EXIT +printf '%s\n' "$SHA" > "$TMP" +mv -f "$TMP" /home/dunedeploy/ci-deploy/pending-commit +echo "CI-goedgekeurde commit geregistreerd: $SHA" diff --git a/website/ops/dunerealms-staging-build-lock.conf b/website/ops/dunerealms-staging-build-lock.conf new file mode 100644 index 00000000..019abc05 --- /dev/null +++ b/website/ops/dunerealms-staging-build-lock.conf @@ -0,0 +1,5 @@ +# Drop-in for the existing dunerealms-ci-build.service. +# Only a temporary mutex conflict (75) is retried; actual build failures are not. +[Service] +RestartForceExitStatus=75 +RestartSec=2s diff --git a/website/ops/dunerealms-staging-retention.conf b/website/ops/dunerealms-staging-retention.conf new file mode 100644 index 00000000..864fcce5 --- /dev/null +++ b/website/ops/dunerealms-staging-retention.conf @@ -0,0 +1,3 @@ +# Drop-in for dunerealms-prune-web-releases.service, NOT the CI/promoter service. +[Service] +ExecStartPost=/usr/bin/python3 /usr/local/sbin/dunerealms-prune-staging-builds --apply diff --git a/website/ops/prune-staging-builds.py b/website/ops/prune-staging-builds.py new file mode 100644 index 00000000..8480ceb6 --- /dev/null +++ b/website/ops/prune-staging-builds.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""Bounded staging retention. Dry-run by default; never follows deletion targets.""" +import argparse, fcntl, json, os, pathlib, re, shutil, stat, time +from contextlib import contextmanager +ROOT=pathlib.Path('/mnt/HC_Volume_107481500/dunegit/ci/deploy-user/ci-deploy/artifacts') +CI=pathlib.Path('/home/dunedeploy/ci-deploy') +APP=pathlib.Path('/home/dunerealms/apps/dunerealms') +STATE=pathlib.Path('/mnt/HC_Volume_107481500/dunegit/ci/promotion') +SHA=re.compile(r'[0-9a-f]{40}') +TEMP=re.compile(r'\.([0-9a-f]{40})\.tmp\.([1-9][0-9]*)') +REQUIRED=('dist/server/index.js','node/start.mjs','control-panel/start.mjs','package.json') + +@contextmanager +def publication_lock(state): + path=state/'safe-lock' + fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW) + try: + try:fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError: + yield False + else:yield True + finally:os.close(fd) + +def walk_metadata(directory,mountpoints=()): + """No symlink traversal; allocated bytes with multiply-linked files excluded.""" + total=0;links=[];devices=set() + def failure(error):raise error + device=directory.stat().st_dev + for base,dirs,files in os.walk(directory,followlinks=False,onerror=failure): + for name in list(dirs)+files: + p=pathlib.Path(base)/name;s=p.lstat();devices.add(s.st_dev) + if stat.S_ISLNK(s.st_mode):links.append(p) + elif name in dirs and (s.st_dev!=device or p in mountpoints or os.path.ismount(p)): + dirs.remove(name) + elif s.st_nlink<=1:total+=getattr(s,'st_blocks',0)*512 + return total,links,devices + +def process_paths(proc): + """Return paths only, never process command lines or environment secrets.""" + paths=[];warnings=[] + def reference(p): + try:paths.append(pathlib.Path(os.readlink(p).removesuffix(' (deleted)'))) + except FileNotFoundError:pass + except OSError as e: + if p.parent.exists():warnings.append('process inspection denied: '+str(p)) + for pid in proc.iterdir(): + if not pid.name.isdecimal():continue + for key in ('cwd','root','exe'):reference(pid/key) + try: + for fd in (pid/'fd').iterdir():reference(fd) + text=(pid/'maps').read_text() + for line in text.splitlines(): + parts=line.split(None,5) + if len(parts)==6 and parts[5].startswith('/'):paths.append(pathlib.Path(parts[5].removesuffix(' (deleted)'))) + # Absolute argv paths may be referenced before a file is opened. + for arg in (pid/'cmdline').read_bytes().split(b'\0'): + value=arg.decode('utf8','surrogateescape') + if value.startswith('/'):paths.append(pathlib.Path(value)) + elif '=/' in value:paths.append(pathlib.Path(value.split('=',1)[1])) + except FileNotFoundError:pass + except OSError: + if pid.exists():warnings.append('process inspection incomplete: '+pid.name) + return paths,warnings + +def mounts(proc): + text=(proc/'self/mountinfo').read_text() + return [pathlib.Path(re.sub(r'\\([0-7]{3})',lambda m:chr(int(m[1],8)),line.split()[4])) for line in text.splitlines()] + +def plan(root=ROOT,ci=CI,app=APP,state=STATE,proc=pathlib.Path('/proc'),now=None): + now=time.time() if now is None else now + try:mountpoints=mounts(proc);mount_errors=[] + except (OSError,ValueError,IndexError):mountpoints=[];mount_errors=['mount inventory incomplete'] + guards=[] + for p in (ci/'pending-commit',ci/'built-commit',state/'deployed',state/'previous-release',app/'current',app/'releases'): + try: + s=p.lstat();identity=[s.st_dev,s.st_ino,s.st_mtime_ns] + except OSError:identity=None + guards.append({'path':str(p),'identity':identity}) + metadata={} + def inspect(p): + if p not in metadata:metadata[p]=walk_metadata(p,mountpoints) + return metadata[p] + if root.is_symlink() or root.resolve(strict=True)!=root:raise RuntimeError('Staging root must be the exact canonical directory') + root_stat=root.stat();entries={};warnings=list(mount_errors) + for p in sorted(root.iterdir()): + s=p.lstat();entry={'name':p.name,'reasons':[],'bytes':0,'identity':[s.st_dev,s.st_ino,s.st_mtime_ns]} + entries[p.name]=entry + if p.is_symlink() or not stat.S_ISDIR(s.st_mode):entry['reasons'].append('not a regular staging directory');continue + if s.st_dev!=root_stat.st_dev:entry['reasons'].append('different filesystem');continue + temp=TEMP.fullmatch(p.name) + if not SHA.fullmatch(p.name) and not temp:entry['reasons'].append('unknown staging name');continue + entry['temporary']=bool(temp) + if temp: + if now-s.st_mtime<86400:entry['reasons'].append('temporary build younger than 24h') + if (proc/temp[2]).exists():entry['reasons'].append('temporary build PID still exists') + entry['completedAt']=s.st_mtime + else: + if not all((p/'website'/f).is_file() for f in REQUIRED):entry['reasons'].append('completion not established');continue + entry['completedAt']=s.st_mtime + marker=p/'.staging-complete.json' + if marker.exists(): + try: + if marker.is_symlink():raise ValueError('symlink marker') + m=json.loads(marker.read_text()) + if m['sha']!=p.name or m['version']!=1 or not isinstance(m['completedAt'],(int,float)) or not 0