web/website/ops/prune-deployment-releases.py

43 lines
2.3 KiB
Python

#!/usr/bin/env python3
"""Prune only inactive web releases older than 24h, preserving rollback/dependencies."""
import argparse,fcntl,json,pathlib,re,shutil,time
APP=pathlib.Path('/home/dunerealms/apps/dunerealms')
STATE=pathlib.Path('/mnt/HC_Volume_107481500/dunegit/ci/promotion')
def candidates(app=APP,state=STATE,now=None):
root=(app/'releases').resolve(strict=True);current=(app/'current').resolve(strict=True)
if current.parent!=root:raise RuntimeError('Active release is outside release storage')
versions=[p for p in root.iterdir() if not p.is_symlink() and p.is_dir() and re.fullmatch(r'ci-[0-9a-f]{40}',p.name)]
keep={current};keep.update(sorted(versions,key=lambda p:p.stat().st_mtime,reverse=True)[:3])
previous=state/'previous-release'
if previous.exists():keep.add(pathlib.Path(previous.read_text().strip()).resolve())
for p in app.iterdir():
if p.is_symlink() and p.exists():keep.add(p.resolve())
for proc in pathlib.Path('/proc').glob('[0-9]*/cwd'):
try:
location=proc.resolve(strict=True)
if root in location.parents:keep.add(root/location.relative_to(root).parts[0])
except (OSError,RuntimeError):pass
pending=list(keep)
while pending:
directory=pending.pop()
if directory.parent!=root or not directory.is_dir():continue
for link in directory.rglob('*'):
if not link.is_symlink() or not link.exists():continue
target=link.resolve()
if root in target.parents:
owner=root/target.relative_to(root).parts[0]
if owner not in keep:keep.add(owner);pending.append(owner)
cutoff=(time.time() if now is None else now)-86400
return root,[p for p in versions if p not in keep and p.stat().st_mtime<cutoff],keep
def main():
parser=argparse.ArgumentParser();parser.add_argument('--apply',action='store_true');args=parser.parse_args()
with (STATE/'safe-lock').open('a') as lock:
try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError:return print(json.dumps({'skipped':'Promotion running'}))
root,obsolete,keep=candidates()
for p in obsolete:
if p.is_symlink() or p.resolve().parent!=root:raise RuntimeError('Unsafe cleanup target')
if args.apply:shutil.rmtree(p)
print(json.dumps({'applied':args.apply,'obsolete':[p.name for p in obsolete],'preserved':sorted(p.name for p in keep)}))
if __name__=='__main__':main()