infrastructure/pipeline/cleanup-cycle.py

49 lines
2.3 KiB
Python

#!/usr/bin/env python3
"""Bound private artifact retention; caller must hold the coordinator cycle lock."""
import json
from pathlib import Path
import re
import shutil
def cleanup(parent, active):
runs = []
for path in sorted(Path(parent).iterdir()):
if path.is_symlink() or not path.is_dir() or not re.fullmatch(r'[0-9]{8}T[0-9]{6}Z', path.name):
continue
state_file = path / 'state.json'
if not state_file.is_file():
continue
state = json.loads(state_file.read_text())
if state.get('state') in ('complete', 'failed') and path.name != active:
runs.append((path, state))
# Keep three completed publications and one failed run's bulky artifacts.
complete = [p for p, s in runs if s['state'] == 'complete']
failed = [p for p, s in runs if s['state'] == 'failed']
keep = set(complete[-3:] + failed[-1:])
removed = []
for path, state in runs:
if path in keep:
continue
# Explicit artifact locations only. Keep source, status and evidence.
for root in (path, path / 'failure-evidence'):
for variant in ('core', 'gnome'):
build = root / variant / 'build'
if not build.resolve().is_relative_to(path.resolve()):
raise ValueError('Build directory escapes run: ' + str(build))
for name in ('repo', 'output', 'iso-work', 'profile', 'tools', 'extractor',
'core', 'core-base', 'composed', 'layer', 'purpose-stage',
'purpose-layer', 'purpose-input', 'flatpak-seed'):
target = build / name
if target.is_symlink():
target.unlink()
removed.append(str(target))
elif target.is_dir():
if not target.resolve().is_relative_to(path.resolve()):
raise ValueError('Artifact escapes run directory: ' + str(target))
shutil.rmtree(target)
removed.append(str(target))
record = path / 'artifact-cleanup.json'
record.write_text(json.dumps({'policy': 'three-complete-one-failed',
'artifacts_expired': True}, indent=2) + '\n')
return removed