Bound staging retention with six-build policy and shared publication coordination
This commit is contained in:
parent
3cd5510f03
commit
d8da3d7b94
7 changed files with 518 additions and 0 deletions
81
website/ops/STAGING-RETENTION.md
Normal file
81
website/ops/STAGING-RETENTION.md
Normal file
|
|
@ -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.
|
||||
31
website/ops/dunerealms-build-release
Normal file
31
website/ops/dunerealms-build-release
Normal file
|
|
@ -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"
|
||||
15
website/ops/dunerealms-ci-trigger
Normal file
15
website/ops/dunerealms-ci-trigger
Normal file
|
|
@ -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"
|
||||
5
website/ops/dunerealms-staging-build-lock.conf
Normal file
5
website/ops/dunerealms-staging-build-lock.conf
Normal file
|
|
@ -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
|
||||
3
website/ops/dunerealms-staging-retention.conf
Normal file
3
website/ops/dunerealms-staging-retention.conf
Normal file
|
|
@ -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
|
||||
245
website/ops/prune-staging-builds.py
Normal file
245
website/ops/prune-staging-builds.py
Normal file
|
|
@ -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<m['completedAt']<=now:raise ValueError('invalid marker')
|
||||
entry['completedAt']=m['completedAt']
|
||||
except (OSError,ValueError,KeyError,TypeError):
|
||||
entry['reasons'].append('unrecognised completion marker');continue
|
||||
entry['completed']=True
|
||||
def protect(name,reason):
|
||||
if name in entries and reason not in entries[name]['reasons']:entries[name]['reasons'].append(reason)
|
||||
complete=sorted((e for e in entries.values() if e.get('completed')),key=lambda e:(e['completedAt'],e['name']),reverse=True)
|
||||
for e in complete[:6]:protect(e['name'],'six newest completed builds')
|
||||
for path,reason in [(ci/'pending-commit','pending publication'),(ci/'built-commit','latest completed build'),(state/'deployed','active production')]:
|
||||
try:
|
||||
value=path.read_text().strip()
|
||||
if not SHA.fullmatch(value):raise ValueError('invalid commit')
|
||||
protect(value,reason)
|
||||
except (OSError,ValueError):warnings.append('cannot establish '+reason+': '+str(path))
|
||||
references=[]
|
||||
try:
|
||||
current=(app/'current').resolve(strict=True)
|
||||
if current.parent!=(app/'releases').resolve():raise ValueError('active version outside releases')
|
||||
references.append((current,'active release'))
|
||||
previous=pathlib.Path((state/'previous-release').read_text().strip()).resolve(strict=True)
|
||||
if previous.parent!=(app/'releases').resolve():raise ValueError('rollback outside releases')
|
||||
references.append((previous,'previous working release'))
|
||||
for release in (app/'releases').iterdir():
|
||||
if release.is_dir():references.append((release.resolve(strict=True),'retained release'))
|
||||
for link in app.iterdir():
|
||||
if link.is_symlink():references.append((link.resolve(strict=True),'application release link'))
|
||||
except (OSError,ValueError,RuntimeError):warnings.append('release/rollback inventory incomplete')
|
||||
try:
|
||||
paths,errors=process_paths(proc);warnings.extend(errors)
|
||||
references.extend((p,'active process') for p in paths)
|
||||
except OSError:warnings.append('process inventory incomplete')
|
||||
def owner(path):
|
||||
# resolve aliases and dependency links, including the old /home/dunedeploy path.
|
||||
try:resolved=path.resolve()
|
||||
except (OSError,RuntimeError):return None
|
||||
if root in resolved.parents:return resolved.relative_to(root).parts[0]
|
||||
return None
|
||||
scanned=set();queue=list(references)
|
||||
while queue:
|
||||
path,reason=queue.pop();name=owner(path)
|
||||
if name:protect(name,reason)
|
||||
release_name=path.name.removeprefix('ci-')
|
||||
if reason in ('active release','previous working release') and SHA.fullmatch(release_name):protect(release_name,reason)
|
||||
if reason=='retained release' and SHA.fullmatch(release_name):protect(release_name,reason)
|
||||
try:resolved=path.resolve(strict=True)
|
||||
except (OSError,RuntimeError):continue
|
||||
scan=resolved if resolved.is_dir() else resolved.parent
|
||||
if not (scan==root or root in scan.parents or scan==app/'releases' or app/'releases' in scan.parents):continue
|
||||
if scan==root:continue
|
||||
if name:scan=root/name
|
||||
if scan in scanned:continue
|
||||
scanned.add(scan)
|
||||
try:
|
||||
_,links,_=inspect(scan)
|
||||
for link in links:
|
||||
target=link.resolve(strict=True)
|
||||
if owner(target):queue.append((target,'dependency of '+str(scan)))
|
||||
except (OSError,RuntimeError):warnings.append('dependency inspection incomplete: '+str(scan))
|
||||
for e in entries.values():
|
||||
p=root/e['name']
|
||||
if not p.is_symlink() and p.is_dir():
|
||||
try:
|
||||
e['bytes'],_,devices=inspect(p)
|
||||
if devices-{root_stat.st_dev} or any(p==m or p in m.parents for m in mountpoints):protect(e['name'],'nested mount or filesystem')
|
||||
except OSError:protect(e['name'],'size/filesystem inspection incomplete')
|
||||
# A protected staging build may itself depend on another staging build.
|
||||
changed=True
|
||||
while changed:
|
||||
changed=False
|
||||
for e in list(entries.values()):
|
||||
if not e['reasons']:continue
|
||||
p=root/e['name']
|
||||
if p.is_symlink() or not p.is_dir():continue
|
||||
try:
|
||||
_,links,_=inspect(p)
|
||||
for link in links:
|
||||
name=owner(link.resolve(strict=True))
|
||||
if name and not entries[name]['reasons']:protect(name,'dependency of retained staging '+e['name']);changed=True
|
||||
except (OSError,RuntimeError):warnings.append('retained staging dependency inspection incomplete: '+e['name'])
|
||||
for guard in guards:
|
||||
try:
|
||||
s=pathlib.Path(guard['path']).lstat()
|
||||
if [s.st_dev,s.st_ino,s.st_mtime_ns]!=guard['identity']:warnings.append('publication state changed during inventory')
|
||||
except OSError:warnings.append('publication state unavailable')
|
||||
if warnings:
|
||||
for e in entries.values():protect(e['name'],'uncertain inventory; retained')
|
||||
candidates=[e for e in entries.values() if not e['reasons'] and (e.get('completed') or e.get('temporary'))]
|
||||
kept=[e for e in entries.values() if e not in candidates]
|
||||
return {'guards':guards,'root':str(root),'rootIdentity':[root_stat.st_dev,root_stat.st_ino],'candidates':candidates,'retained':kept,'estimatedBytes':sum(e['bytes'] for e in candidates),'warnings':sorted(set(warnings))}
|
||||
|
||||
def execute(*,apply=False,root=ROOT,ci=CI,app=APP,state=STATE,proc=pathlib.Path('/proc'),now=None):
|
||||
# Do expensive inventory/size work outside the mutex. Ordinary builds never run cleanup.
|
||||
with publication_lock(state) as acquired:
|
||||
if not acquired:return {'applied':False,'skipped':'publication/build lock is held','candidates':[],'retained':[],'estimatedBytes':0}
|
||||
report=plan(root,ci,app,state,proc,now);report['applied']=False;report['removed']=[]
|
||||
if not apply:return report
|
||||
if not shutil.rmtree.avoids_symlink_attacks:raise RuntimeError('Secure dir-fd deletion is unavailable')
|
||||
fd=os.open(root,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
||||
try:
|
||||
if list((os.fstat(fd).st_dev,os.fstat(fd).st_ino))!=report['rootIdentity']:raise RuntimeError('Staging root changed')
|
||||
for e in report['candidates']:
|
||||
name=e['name']
|
||||
# One directory per lock lease; builders/publication can run between deletions.
|
||||
with publication_lock(state) as acquired:
|
||||
if not acquired:
|
||||
report['retained'].append({**e,'reasons':['publication/build lock is held; retained']});continue
|
||||
changed=False
|
||||
for guard in report['guards']:
|
||||
try:
|
||||
g=pathlib.Path(guard['path']).lstat()
|
||||
if [g.st_dev,g.st_ino,g.st_mtime_ns]!=guard['identity']:changed=True
|
||||
except OSError:changed=True
|
||||
paths,errors=process_paths(proc)
|
||||
for p in paths:
|
||||
try:resolved=p.resolve()
|
||||
except (OSError,RuntimeError):changed=True;continue
|
||||
if root/name==resolved or root/name in resolved.parents:changed=True
|
||||
temp=TEMP.fullmatch(name)
|
||||
if temp and (proc/temp[2]).exists():changed=True
|
||||
try:
|
||||
if any(root/name==m or root/name in m.parents for m in mounts(proc)):changed=True
|
||||
except (OSError,ValueError,IndexError):changed=True
|
||||
if changed or errors:
|
||||
report['retained'].append({**e,'reasons':['state/process changed during cleanup; retained']});continue
|
||||
s=os.stat(name,dir_fd=fd,follow_symlinks=False)
|
||||
if not stat.S_ISDIR(s.st_mode) or [s.st_dev,s.st_ino,s.st_mtime_ns]!=e['identity']:raise RuntimeError('Unsafe or changed staging target')
|
||||
if root.lstat().st_ino!=report['rootIdentity'][1]:raise RuntimeError('Staging root replaced')
|
||||
shutil.rmtree(name,dir_fd=fd);report['removed'].append(name)
|
||||
report['applied']=True
|
||||
finally:os.close(fd)
|
||||
return report
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
mode=parser.add_mutually_exclusive_group()
|
||||
mode.add_argument('--apply',action='store_true',help='Delete only verified candidates; omitted means dry-run')
|
||||
mode.add_argument('--dry-run',action='store_true',help='Report candidates and preserve reasons without removing anything')
|
||||
args=parser.parse_args()
|
||||
print(json.dumps(execute(apply=args.apply),indent=2))
|
||||
if __name__=='__main__':main()
|
||||
138
website/ops/test_staging_retention.py
Normal file
138
website/ops/test_staging_retention.py
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
spec=importlib.util.spec_from_file_location('retention',pathlib.Path(__file__).with_name('prune-staging-builds.py'))
|
||||
retention=importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(retention)
|
||||
|
||||
def sha(n):return f'{n:040x}'
|
||||
|
||||
class StagingRetentionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
||||
self.base=pathlib.Path(self.tmp.name)
|
||||
self.root=self.base/'ci/artifacts';self.root.mkdir(parents=True)
|
||||
self.ci=self.root.parent;self.state=self.base/'state';self.state.mkdir()
|
||||
(self.state/'safe-lock').touch()
|
||||
self.app=self.base/'app';(self.app/'releases').mkdir(parents=True)
|
||||
self.proc=self.base/'proc';(self.proc/'self').mkdir(parents=True)
|
||||
(self.proc/'self/mountinfo').write_text('')
|
||||
for n in range(1,19):self.build(n)
|
||||
self.release(1);self.release(2)
|
||||
(self.app/'current').symlink_to(self.app/'releases'/('ci-'+sha(1)))
|
||||
(self.state/'previous-release').write_text(str(self.app/'releases'/('ci-'+sha(2))))
|
||||
(self.state/'deployed').write_text(sha(1))
|
||||
(self.ci/'pending-commit').write_text(sha(18))
|
||||
(self.ci/'built-commit').write_text(sha(18))
|
||||
self.args=dict(root=self.root,ci=self.ci,app=self.app,state=self.state,proc=self.proc,now=200000)
|
||||
def build(self,n):
|
||||
p=self.root/sha(n)
|
||||
for f in retention.REQUIRED:
|
||||
file=p/'website'/f;file.parent.mkdir(parents=True,exist_ok=True);file.write_bytes(b'x'*4096)
|
||||
(p/'.staging-complete.json').write_text(json.dumps({'version':1,'sha':sha(n),'completedAt':n*100}))
|
||||
os.utime(p,(n*100,n*100));return p
|
||||
def release(self,n):
|
||||
p=self.app/'releases'/('ci-'+sha(n));p.mkdir();return p
|
||||
def process(self,pid,*,cwd=None,fd=None,mapped=None,arg=None):
|
||||
p=self.proc/str(pid);p.mkdir();(p/'fd').mkdir()
|
||||
if cwd:(p/'cwd').symlink_to(cwd)
|
||||
if fd:(p/'fd/3').symlink_to(fd)
|
||||
(p/'maps').write_text('1-2 r--p 0 00:00 0 '+str(mapped)+'\n' if mapped else '')
|
||||
(p/'cmdline').write_bytes(str(arg).encode()+b'\0' if arg else b'')
|
||||
def run_cleanup(self,apply=False):return retention.execute(apply=apply,**self.args)
|
||||
def test_six_newest_plus_old_active_rollback_processes_pending_and_transitive_dependencies(self):
|
||||
self.process(123,cwd=self.root/sha(3),fd=self.root/sha(9)/'website/package.json',mapped=self.root/sha(10)/'website/package.json',arg=self.root/sha(11)/'website/package.json')
|
||||
(self.ci/'pending-commit').write_text(sha(4))
|
||||
release=self.release(5);(release/'node_modules').symlink_to(self.root/sha(6))
|
||||
(self.root/sha(6)/'dependency').symlink_to(self.root/sha(7))
|
||||
outside=self.base/'uploads';outside.mkdir();(outside/'keep').write_text('untouched')
|
||||
(self.root/sha(8)/'external').symlink_to(outside)
|
||||
dry=self.run_cleanup();self.assertFalse(dry['warnings'])
|
||||
self.assertEqual({e['name'] for e in dry['candidates']},{sha(8),sha(12)})
|
||||
self.assertGreater(dry['estimatedBytes'],0);self.assertEqual(len(list(self.root.iterdir())),18)
|
||||
result=self.run_cleanup(True);self.assertEqual(set(result['removed']),{sha(8),sha(12)})
|
||||
for n in [1,2,3,4,5,6,7,9,10,11,13,14,15,16,17,18]:self.assertTrue((self.root/sha(n)).is_dir())
|
||||
self.assertEqual((outside/'keep').read_text(),'untouched')
|
||||
def test_live_build_and_publication_locks_skip_without_waiting_or_removing(self):
|
||||
for mode in (fcntl.LOCK_EX,fcntl.LOCK_SH):
|
||||
with (self.state/'safe-lock').open() as lock:
|
||||
fcntl.flock(lock,mode)
|
||||
result=self.run_cleanup(True);self.assertIn('lock',result['skipped'])
|
||||
self.assertEqual(len(list(self.root.iterdir())),18)
|
||||
def test_concurrent_publication_process_prevents_cleanup(self):
|
||||
program="import fcntl,sys; f=open(sys.argv[1]); fcntl.flock(f,fcntl.LOCK_EX); print('locked',flush=True); sys.stdin.read()"
|
||||
child=subprocess.Popen([sys.executable,'-c',program,str(self.state/'safe-lock')],stdin=subprocess.PIPE,stdout=subprocess.PIPE,text=True)
|
||||
try:
|
||||
self.assertEqual(child.stdout.readline().strip(),'locked')
|
||||
result=self.run_cleanup(True);self.assertIn('lock',result['skipped'])
|
||||
self.assertEqual(len(list(self.root.iterdir())),18)
|
||||
finally:child.communicate('',timeout=5)
|
||||
def test_temporary_directories_need_old_age_missing_pid_and_no_process_reference(self):
|
||||
old=self.root/('.'+sha(30)+'.tmp.99999');old.mkdir();(old/'test').write_text('old');os.utime(old,(1,1))
|
||||
active=self.root/('.'+sha(31)+'.tmp.123');active.mkdir();os.utime(active,(1,1));self.process(123,cwd=active)
|
||||
recent=self.root/('.'+sha(32)+'.tmp.777');recent.mkdir();os.utime(recent,(199999,199999))
|
||||
result=self.run_cleanup(True);self.assertIn(old.name,result['removed']);self.assertTrue(active.exists());self.assertTrue(recent.exists())
|
||||
def test_unknown_incomplete_symlink_and_invalid_marker_are_retained(self):
|
||||
outside=self.base/'database';outside.mkdir();(outside/'keep').write_text('data')
|
||||
alias=self.root/sha(20);alias.symlink_to(outside)
|
||||
unknown=self.root/'not-a-build';unknown.mkdir()
|
||||
incomplete=self.root/sha(21);incomplete.mkdir()
|
||||
(self.root/sha(3)/'.staging-complete.json').write_text('{}')
|
||||
result=self.run_cleanup(True)
|
||||
for p in [alias,unknown,incomplete,self.root/sha(3)]:self.assertTrue(p.exists())
|
||||
self.assertEqual((outside/'keep').read_text(),'data')
|
||||
def test_unreadable_process_inventory_fails_closed(self):
|
||||
with patch.object(retention,'process_paths',return_value=([],['permission denied'])):
|
||||
result=self.run_cleanup(True)
|
||||
self.assertEqual(result['removed'],[]);self.assertEqual(len(result['retained']),18)
|
||||
def test_missing_rollback_fails_closed_and_reports(self):
|
||||
(self.state/'previous-release').unlink()
|
||||
result=self.run_cleanup(True);self.assertEqual(result['removed'],[]);self.assertTrue(result['warnings'])
|
||||
def test_state_change_after_inventory_prevents_deletion(self):
|
||||
original=retention.plan
|
||||
def changed(*args,**kwargs):
|
||||
result=original(*args,**kwargs);(self.ci/'pending-commit').write_text(sha(3));return result
|
||||
with patch.object(retention,'plan',side_effect=changed):result=self.run_cleanup(True)
|
||||
self.assertEqual(result['removed'],[])
|
||||
def test_mount_inside_candidate_is_never_traversed_or_deleted(self):
|
||||
mount=self.root/sha(3)/'mounted';mount.mkdir()
|
||||
(self.proc/'self/mountinfo').write_text('1 0 8:1 / '+str(mount)+' rw - ext4 /dev/test rw\n')
|
||||
visited=[];scandir=os.scandir
|
||||
def observe(path):
|
||||
visited.append(str(path));return scandir(path)
|
||||
with patch.object(retention.os,'scandir',side_effect=observe):result=self.run_cleanup(True)
|
||||
self.assertNotIn(str(mount),visited)
|
||||
self.assertNotIn(sha(3),result['removed']);self.assertTrue(mount.exists())
|
||||
def test_builder_does_not_wait_on_cleanup_and_retries_only_the_busy_code(self):
|
||||
with (self.state/'safe-lock').open() as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
command='exec 9< "$1"; flock --shared --nonblock 9 || exit 75'
|
||||
result=subprocess.run(['bash','-c',command,'lock-test',str(self.state/'safe-lock')],timeout=2)
|
||||
self.assertEqual(result.returncode,75)
|
||||
retry=pathlib.Path(__file__).with_name('dunerealms-staging-build-lock.conf').read_text()
|
||||
self.assertIn('RestartForceExitStatus=75',retry)
|
||||
def test_completion_marker_orders_finished_builds_instead_of_later_file_edits(self):
|
||||
(self.root/sha(12)/'.staging-complete.json').write_text(json.dumps({'version':1,'sha':sha(12),'completedAt':199999}))
|
||||
result=self.run_cleanup()
|
||||
newest=[e['name'] for e in result['retained'] if 'six newest completed builds' in e['reasons']]
|
||||
self.assertEqual(set(newest),{sha(n) for n in [12,14,15,16,17,18]})
|
||||
def test_symbolic_staging_root_is_rejected(self):
|
||||
alias=self.base/'alias';alias.symlink_to(self.root)
|
||||
with self.assertRaises(RuntimeError):retention.execute(root=alias,**{k:v for k,v in self.args.items() if k!='root'})
|
||||
def test_integration_uses_existing_async_task_and_same_lock_for_writers(self):
|
||||
ops=pathlib.Path(__file__).parent
|
||||
for name in ['dunerealms-build-release','dunerealms-ci-trigger']:
|
||||
source=(ops/name).read_text();self.assertIn(str(retention.STATE/'safe-lock'),source);self.assertIn('flock --shared',source)
|
||||
self.assertNotIn('prune-staging',source)
|
||||
config=(ops/'dunerealms-staging-retention.conf').read_text()
|
||||
self.assertIn('dunerealms-prune-web-releases.service',config);self.assertNotIn('dunerealms-ci-promote.service',config)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Loading…
Reference in a new issue

Staff