661 lines
43 KiB
Python
661 lines
43 KiB
Python
#!/usr/bin/env python3
|
|
"""D-098: Rust checks, Core/Purpose composition, signed OSTree; ISO on day 30."""
|
|
import argparse
|
|
from datetime import datetime, timezone
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shlex
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
import importlib.util
|
|
import monitor
|
|
|
|
cleanup_spec = importlib.util.spec_from_file_location('cleanup_cycle', Path(__file__).with_name('cleanup-cycle.py'))
|
|
cleanup_module = importlib.util.module_from_spec(cleanup_spec)
|
|
cleanup_spec.loader.exec_module(cleanup_module)
|
|
|
|
status_spec = importlib.util.spec_from_file_location('pipeline_status', Path(__file__).with_name('pipeline-status.py'))
|
|
status_module = importlib.util.module_from_spec(status_spec)
|
|
status_spec.loader.exec_module(status_module)
|
|
|
|
|
|
def atomic(path, value):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
temp = path.with_suffix('.tmp')
|
|
temp.write_text(json.dumps(value, indent=2) + '\n')
|
|
temp.replace(path)
|
|
|
|
|
|
def resolve_request(candidate, age, resume):
|
|
"""Return the portal request this run may consume, or None.
|
|
|
|
A build request pins a mode and one immutable snapshot date. A resume request
|
|
only asks to continue the last run: it carries neither, because that run keeps
|
|
its own mode and snapshot identity, and a command-line --resume wins over any
|
|
request. Requests older than 900 s are discarded so a scheduled run never
|
|
inherits a forgotten manual start.
|
|
"""
|
|
if resume or candidate is None or age is None or not 0 <= age <= 900:
|
|
return None
|
|
if candidate.get('resume') is True:
|
|
return candidate
|
|
if (candidate.get('mode') in ('iso', 'ostree')
|
|
and re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', candidate.get('snapshot', ''))):
|
|
return candidate
|
|
return None
|
|
|
|
|
|
def adapter_probe(remote_root, desktops):
|
|
"""Shell test for the Desktop plugin inputs a resumed run must still have.
|
|
|
|
The adapter outputs live in the worker workspace, which a failed run removes
|
|
after archiving its evidence. They are deterministic and cached, so a resume
|
|
rebuilds them as a cache copy instead of composing a Desktop image that links
|
|
a plugin file nobody produced.
|
|
"""
|
|
probe = 'test -f ' + shlex.quote(remote_root + '/software-adapter/libgs_plugin_archipelago.so')
|
|
if 'kde' in desktops:
|
|
probe += (' && test -f ' + shlex.quote(remote_root + '/discover-adapter/discover-version.txt'))
|
|
probe += (' && test -n "$(find ' + shlex.quote(remote_root + '/discover-adapter')
|
|
+ ' -name "plasma-setup-*.pkg.tar.zst" -print -quit 2>/dev/null)"')
|
|
return probe
|
|
|
|
|
|
def verify_snapshot(snapshot_url):
|
|
"""Refuse to build from a snapshot the public web server does not serve.
|
|
|
|
A host view can be complete while the artifact container still holds the mount
|
|
namespace it started with, so the first stage that downloads packages dies on
|
|
404 minutes into the run. Probe the exact identity the build will use and stop
|
|
here with the URL that is missing.
|
|
"""
|
|
probe = snapshot_url.replace('$repo/os/$arch', 'core/os/x86_64') + '/core.db'
|
|
problem = 'no response'
|
|
for _ in range(3):
|
|
try:
|
|
with urllib.request.urlopen(urllib.request.Request(probe, method='HEAD'),
|
|
timeout=20) as response:
|
|
if response.status == 200:
|
|
return
|
|
problem = 'HTTP ' + str(response.status)
|
|
except OSError as error:
|
|
problem = str(error)
|
|
time.sleep(2)
|
|
raise RuntimeError('Repository snapshot is not served: ' + probe + ' (' + problem + ')')
|
|
|
|
|
|
def write_status(base, state):
|
|
state.update(status_module.english_status(state))
|
|
parent = base / 'data/private/release-cycle'
|
|
run = parent / state['run']
|
|
atomic(run / 'state.json', state)
|
|
monitor.atomic(base / 'data/private/pipeline-monitor' / state['run'] / 'state.json', state)
|
|
atomic(parent / 'latest.json', state)
|
|
atomic(base / 'data/public/pipeline.json', state)
|
|
status_module.export(base)
|
|
text = f"Run: {state['run']}\nWorker: {state['worker']}\nStage: {state['stage_title']}\nUpdated: {state['updated']}\nPublished: {'yes' if state['published'] else 'no'}\n"
|
|
if state.get('flatpak'):
|
|
text += 'Flatpak: ' + state['flatpak']['state'] + '\n'
|
|
if state.get('error'):
|
|
text += 'Error: ' + state['error'] + '\n'
|
|
if state.get('recovery'):
|
|
text += 'Recovery: cleanup completed; original failure preserved in state-before-recovery.json\n'
|
|
text += f"Results and logs: {run}\n"
|
|
(parent / 'latest.txt.tmp').write_text(text)
|
|
(parent / 'latest.txt.tmp').replace(parent / 'latest.txt')
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--config', default=os.environ.get('ARCHIPELAGO_CYCLE_CONFIG', '/etc/archipelago/release-cycle.json'))
|
|
parser.add_argument('--mode', choices=('auto', 'ostree', 'iso'), default='auto')
|
|
parser.add_argument('--snapshot', default=None,
|
|
help='Repository view date, "latest", or "new" to capture one now')
|
|
parser.add_argument('--request', default=None,
|
|
help='Portal build request consumed once before the cycle starts')
|
|
parser.add_argument('--resume', action='store_true',
|
|
help='Continue the last failed run from its first incomplete phase')
|
|
args = parser.parse_args()
|
|
config = json.loads(Path(args.config).read_text())
|
|
# A portal request pins the mode and the immutable repository view. It is
|
|
# consumed exactly once and ignored if stale, so a scheduled run can never
|
|
# inherit a manual build's inputs.
|
|
request = None
|
|
request_path = Path(args.request) if args.request else Path(config['coordinator_root']) / 'data/private/release-cycle/cycle-request.json'
|
|
if request_path.exists():
|
|
try:
|
|
candidate = json.loads(request_path.read_text())
|
|
except (OSError, json.JSONDecodeError):
|
|
candidate = None
|
|
request_path.unlink(missing_ok=True)
|
|
try:
|
|
age = (datetime.now(timezone.utc) - datetime.fromisoformat(candidate['requested_at'])).total_seconds()
|
|
except (TypeError, KeyError, ValueError):
|
|
age = None
|
|
request = resolve_request(candidate, age, args.resume)
|
|
if request and request.get('resume'):
|
|
# A resume keeps the previous run's mode and snapshot, so the request
|
|
# carries neither and the run continues from its own state.
|
|
args.resume = True
|
|
elif request is None and candidate is not None:
|
|
print('discarded portal request (stale, invalid, or superseded by --resume)', flush=True)
|
|
if args.mode != 'auto':
|
|
mode = args.mode
|
|
elif request and request.get('mode'):
|
|
mode = request['mode']
|
|
else:
|
|
mode = 'iso' if datetime.now(timezone.utc).day == 1 else 'ostree'
|
|
variants = tuple(config.get('variants', ['core', 'gnome']))
|
|
if variants not in (('core', 'gnome'), ('core', 'gnome', 'kde')):
|
|
raise ValueError('Supported cycle order: core, gnome, optionally kde')
|
|
desktops = variants[1:]
|
|
# D-100: Container Runner is a regular fourth variant. Its build path is the
|
|
# explicit `--purpose container-runner` adapter, not the GNOME/KDE template.
|
|
container = bool(config.get('container_variant'))
|
|
build_variants = variants + (('container',) if container else ())
|
|
def iso_name(variant):
|
|
return {'core': 'archipelago-core-latest.iso', 'gnome': 'archipelago-gnome-probe.iso',
|
|
'kde': 'archipelago-kde-probe.iso',
|
|
'container': 'archipelago-container-runner.iso'}[variant]
|
|
base = Path(config['coordinator_root'])
|
|
parent = base / 'data/private/release-cycle'
|
|
parent.mkdir(parents=True, exist_ok=True)
|
|
lock = (parent / 'cycle.lock').open('a')
|
|
try:
|
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError:
|
|
skipped = dict(state='skipped-overlap', time=datetime.now(timezone.utc).isoformat(),
|
|
reason='Another release cycle owns the worker/publication lock')
|
|
atomic(parent / ('skipped-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ') + '.json'), skipped)
|
|
print(json.dumps(skipped), flush=True)
|
|
return
|
|
resume = bool(args.resume)
|
|
if resume:
|
|
# Continue the last failed run: keep its identity, snapshot and already
|
|
# built variants, and only re-freeze the source so fixes take effect.
|
|
last = json.loads((parent / 'latest.json').read_text())
|
|
if last.get('state') not in ('failed', 'complete'):
|
|
raise ValueError('Nothing to resume: the latest run is ' + str(last.get('state')))
|
|
stamp = last['run']
|
|
run = parent / stamp
|
|
if not run.is_dir():
|
|
raise ValueError('Resume target has no run directory: ' + stamp)
|
|
mode = last.get('output_mode', mode)
|
|
observer = monitor.Monitor(base, stamp)
|
|
previous = None
|
|
else:
|
|
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
|
|
run = parent / stamp
|
|
run.mkdir()
|
|
observer = monitor.Monitor(base, stamp)
|
|
previous = json.loads((parent / 'latest.json').read_text()) if (parent / 'latest.json').exists() else None
|
|
source = Path(__file__).resolve().parent
|
|
shutil.copytree(source, run / 'pipeline', dirs_exist_ok=True, ignore=shutil.ignore_patterns('__pycache__'))
|
|
atomic(run / 'config.json', config)
|
|
worker = config['worker']
|
|
remote_root = config['worker_root'] + '/build/release-cycle/' + stamp
|
|
resumed_state = json.loads((run / 'state.json').read_text()) if resume and (run / 'state.json').exists() else None
|
|
state = dict(version=1, run=stamp, started=datetime.now(timezone.utc).isoformat(),
|
|
state='starting', published=False, channel='stable', output_mode=mode,
|
|
invocation_id=os.environ.get('INVOCATION_ID'), worker=worker,
|
|
reason=os.environ.get('ARCHIPELAGO_RELEASE_REASON', 'D-098 Rust/manual release cycle'),
|
|
request=request)
|
|
if resumed_state:
|
|
state['snapshot_url'] = resumed_state.get('snapshot_url', '')
|
|
if resumed_state.get('snapshot'):
|
|
state['snapshot'] = resumed_state['snapshot']
|
|
state['resumed_from_phase'] = resumed_state.get('failed_phase') or resumed_state.get('state')
|
|
step = 0
|
|
worker_units = []
|
|
titles = status_module.TITLES
|
|
def phase(name, **extra):
|
|
state.update(state=name, stage_title=titles.get(name, name), updated=datetime.now(timezone.utc).isoformat(), **extra)
|
|
write_status(base, state)
|
|
observer.update(state)
|
|
print(json.dumps(state), flush=True)
|
|
def call(argv, timeout=14400):
|
|
observer.call(argv, timeout)
|
|
def remote(script, timeout=14400):
|
|
nonlocal step
|
|
step += 1
|
|
# A resumed run restarts the counter, so keep unit names unique across
|
|
# attempts; a leftover failed unit of the same name blocks systemd-run.
|
|
unit = 'archipelago-cycle-' + stamp + '-' + str(step) + '-' + os.urandom(3).hex()
|
|
worker_units.append(unit)
|
|
state['worker_units'] = list(worker_units)
|
|
atomic(run / 'state.json', state)
|
|
call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', '-o', 'ServerAliveInterval=15', worker,
|
|
shlex.join(['systemd-run', '--wait', '--pipe', '--unit=' + unit,
|
|
'--property=RuntimeMaxSec=' + str(timeout),
|
|
'bash', '-euo', 'pipefail', '-c', script])], timeout + 60)
|
|
def remote_text(script):
|
|
result = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker, script],
|
|
capture_output=True, text=True)
|
|
return result.stdout.strip() if result.returncode == 0 else ''
|
|
def tools(argv, signing=False):
|
|
mounts = ['--mount', f'type=bind,src={base}/data,dst={base}/data',
|
|
'--mount', f'type=bind,src={run}/pipeline,dst=/pipeline,readonly']
|
|
if signing:
|
|
mounts += ['--mount', f'type=bind,src={config["signing_home"]},dst=/signing']
|
|
return ['docker', 'run', '--rm', '--label', 'archipelago.release-run=' + stamp, '--network=none', '--env', 'ARCHIPELAGO_RELEASE_REASON',
|
|
*mounts, config['coordinator_tools_image'], *map(str, argv)]
|
|
def retain_logs():
|
|
roots = {'worker': Path(remote_root), 'archive': run}
|
|
for label, cache in (('flatpak-attempt', config.get('flatpak_cache')),
|
|
('kde-flatpak-attempt', config.get('kde_flatpak_cache'))):
|
|
attempts = Path(cache) / 'runs' if cache else None
|
|
if attempts and attempts.exists():
|
|
for attempt in attempts.iterdir():
|
|
if re.fullmatch(r'[0-9]{8}T[0-9]{6}Z', attempt.name) and attempt.name >= stamp:
|
|
roots[label + '/' + attempt.name] = attempt
|
|
for label in ('flatpak', 'flatpak_kde'):
|
|
if state.get(label, {}).get('log'):
|
|
roots[label] = Path(state[label]['log']).parent
|
|
observer.retain_logs(roots)
|
|
def interrupted(signum, frame):
|
|
raise InterruptedError('Coordinator received signal ' + str(signum))
|
|
signal.signal(signal.SIGTERM, interrupted)
|
|
signal.signal(signal.SIGINT, interrupted)
|
|
builds = None
|
|
try:
|
|
if previous and previous.get('state') != 'complete':
|
|
old_id = previous['run']
|
|
if not re.fullmatch(r'[0-9]{8}T[0-9]{6}Z', old_id):
|
|
raise ValueError('Invalid previous run identity')
|
|
old_path = parent / old_id / 'state.json'
|
|
old = json.loads(old_path.read_text())
|
|
units = old.get('worker_units', [])
|
|
if any(not re.fullmatch('archipelago-cycle-' + old_id + r'-[0-9]+(-[0-9a-f]{6})?', u) for u in units):
|
|
raise ValueError('Invalid previous worker unit identity')
|
|
prior_worker = json.loads((parent / old_id / 'config.json').read_text())['worker'] if (parent / old_id / 'config.json').exists() else worker
|
|
call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', prior_worker,
|
|
'set -e; for unit in ' + shlex.join([*units, 'archipelago-cycle-gnome-' + old_id, 'archipelago-cycle-kde-' + old_id]) +
|
|
'; do if systemctl is-active --quiet "$unit"; then systemctl stop "$unit"; fi; done'], 180)
|
|
if old['state'] != 'failed':
|
|
old.update(failed_phase=old['state'], state='failed',
|
|
error='Interrupted coordinator recovered by ' + stamp)
|
|
old['worker_recovery_run'] = stamp
|
|
atomic(old_path, old)
|
|
if resume:
|
|
snapshot_url = state.get('snapshot_url') or ''
|
|
if not snapshot_url:
|
|
raise ValueError('Resumed run has no repository snapshot identity')
|
|
verify_snapshot(snapshot_url)
|
|
else:
|
|
phase('preflight')
|
|
atomic(run / 'private-cleanup.json', {'removed': cleanup_module.cleanup(parent, stamp)})
|
|
remote(f'mkdir -p {shlex.quote(remote_root)}; test -f {shlex.quote(config["worker_source_root"])}/src/rfc/schemas/layer-v1.schema.json')
|
|
# D-108: the first of the month captures a new immutable repository
|
|
# snapshot; every other build reuses the current one. The installed system
|
|
# keeps the repository it was composed from (build-iso.sh writes this URL
|
|
# into the image), so a snapshot build can never silently fall back to the
|
|
# rolling mirror and lose a package that the mirror later prunes.
|
|
phase('selecting-repository')
|
|
snapshots = Path('/opt/archipelago/data/public/arch-repo-snapshot')
|
|
choice = args.snapshot or (request or {}).get('snapshot') or 'latest'
|
|
def capture_snapshot():
|
|
snapshot_proc = subprocess.run(['/usr/local/sbin/archipelago-mirror-snapshot'],
|
|
capture_output=True, text=True)
|
|
if snapshot_proc.returncode != 0:
|
|
raise RuntimeError('mirror snapshot failed: ' + snapshot_proc.stderr.strip())
|
|
return next(line.removeprefix('url=') for line
|
|
in reversed(snapshot_proc.stdout.splitlines()) if line.startswith('url='))
|
|
if choice == 'new' or (choice == 'latest' and datetime.now(timezone.utc).day == 1):
|
|
snapshot_url = capture_snapshot()
|
|
elif choice == 'latest':
|
|
views = sorted(p.name for p in snapshots.iterdir() if p.is_dir()) if snapshots.is_dir() else []
|
|
if not views:
|
|
raise RuntimeError('No repository snapshot available; run the cycle on the 1st to capture one')
|
|
snapshot_url = (config['public_url'].rstrip('/') + '/arch-repo-snapshot/'
|
|
+ views[-1] + '/$repo/os/$arch')
|
|
else:
|
|
if not re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', choice):
|
|
raise ValueError('Invalid repository snapshot date: ' + choice)
|
|
if not (snapshots / choice / 'core/os/x86_64/core.db').is_file():
|
|
raise RuntimeError('Requested repository snapshot is missing: ' + choice)
|
|
snapshot_url = config['public_url'].rstrip('/') + '/arch-repo-snapshot/' + choice + '/$repo/os/$arch'
|
|
verify_snapshot(snapshot_url)
|
|
state['snapshot'] = snapshot_url.split('/arch-repo-snapshot/')[1].split('/')[0]
|
|
state['snapshot_url'] = snapshot_url
|
|
write_status(base, state)
|
|
# Compile from the frozen source tree, not a possibly stale deployed CLI.
|
|
previous_binary = ''
|
|
if resume:
|
|
previous_binary = remote_text('sha256sum ' + shlex.quote(remote_root + '/archipelago')
|
|
+ " | cut -d' ' -f1")
|
|
phase('freezing-and-compiling-source')
|
|
remote(f'''mkdir -p {shlex.quote(remote_root)}
|
|
tar --exclude=.git --exclude=target --exclude=__pycache__ -C {shlex.quote(config['worker_source_root'])} -cf {remote_root}/source.tar src
|
|
mkdir -p {remote_root}/source
|
|
tar -xf {remote_root}/source.tar -C {remote_root}/source
|
|
cp -a {remote_root}/source/src/test-lab/probes {remote_root}/probes
|
|
mkdir -p {shlex.quote(config['worker_source_root'])}/target {shlex.quote(config['worker_root'])}/cache/cargo
|
|
docker run --rm --network=none --mount type=bind,src={remote_root}/source/src,dst=/build/src,readonly --mount type=bind,src={shlex.quote(config['worker_source_root'])}/target,dst=/build/target --mount type=bind,src={shlex.quote(config['worker_root'])}/cache/cargo,dst=/usr/local/cargo/registry {shlex.quote(config['worker_tools_image'])} cargo build --manifest-path /build/src/cli/Cargo.toml --offline --locked --release
|
|
cp {shlex.quote(config['worker_source_root'])}/target/release/archipelago {remote_root}/archipelago
|
|
cp {shlex.quote(config['worker_source_root'])}/target/release/archipelagod {remote_root}/archipelagod
|
|
docker run --rm --network=none --mount type=bind,src={remote_root}/source/src,dst=/build/src,readonly --mount type=bind,src={shlex.quote(config['worker_source_root'])}/target,dst=/build/target --mount type=bind,src={shlex.quote(config['worker_root'])}/cache/cargo,dst=/usr/local/cargo/registry {shlex.quote(config['worker_tools_image'])} cargo test --manifest-path /build/src/cli/Cargo.toml --offline --locked --release -p archipelago -p archipelago-system -p archipelago-contracts -p archipelago-composer -p archipelago-builder -p archipelago-installer -p archipelago-registry > {remote_root}/service-contract-checks.log 2>&1
|
|
python3 {remote_root}/source/src/infrastructure/tests/control_portal.py > {remote_root}/control-portal-checks.log 2>&1
|
|
sha256sum {remote_root}/archipelago > {remote_root}/inputs.sha256
|
|
sha256sum {remote_root}/archipelagod >> {remote_root}/inputs.sha256
|
|
sha256sum {remote_root}/source.tar >> {remote_root}/inputs.sha256
|
|
find {remote_root}/probes -type f -name '*.py' -exec sha256sum {{}} + >> {remote_root}/inputs.sha256''')
|
|
binary_changed = False
|
|
if resume and previous_binary:
|
|
current_binary = remote_text('sha256sum ' + shlex.quote(remote_root + '/archipelago')
|
|
+ " | cut -d' ' -f1")
|
|
binary_changed = bool(current_binary) and current_binary != previous_binary
|
|
if binary_changed:
|
|
print(json.dumps({'event': 'core-rebuild-required',
|
|
'reason': 'CLI binary changed since the previous attempt'}), flush=True)
|
|
call(['rsync', '-a', f'{worker}:{remote_root}/service-contract-checks.log', str(run / 'service-contract-checks.log')])
|
|
call(['rsync', '-a', f'{worker}:{remote_root}/control-portal-checks.log', str(run / 'control-portal-checks.log')])
|
|
# D-098 amendment (2026-11-10): Flatpak seeds change only with the monthly
|
|
# ISO. Three-day OSTree cycles reuse the last verified seed instead of
|
|
# spending hours on a refresh whose result is only shipped in ISO media.
|
|
if mode == 'iso' and config.get('flatpak_cache') and not resume:
|
|
remote(f'test "$(df -PB1 {remote_root} | awk \'NR==2 {{print $4}}\')" -ge {config.get("minimum_build_free_bytes", 60000000000)}')
|
|
phase('updating-flatpak-cache')
|
|
refresh = int(config.get('flatpak_refresh_seconds', 14400))
|
|
initial_fill = int(config.get('flatpak_initial_fill_seconds', 14400))
|
|
if refresh <= 0 or initial_fill < refresh:
|
|
raise ValueError('Initial Flatpak fill timeout must be at least the positive refresh timeout')
|
|
remote(shlex.join(['bash', remote_root + '/source/src/infrastructure/pipeline/flatpak-cache.sh',
|
|
remote_root + '/source/src', config['flatpak_cache'], config['bootstrap'],
|
|
config['build_environment']['ARCHIPELAGO_PACKAGE_CACHE'], str(refresh), 'gnome', str(initial_fill)]) +
|
|
' > ' + shlex.quote(remote_root + '/flatpak.log') + ' 2>&1', 14400)
|
|
call(['rsync', '-a', f"{worker}:{config['flatpak_cache']}/status.json", str(run / 'flatpak-status.json')])
|
|
state['flatpak'] = json.loads((run / 'flatpak-status.json').read_text())
|
|
if 'kde' in desktops:
|
|
phase('updating-kde-flatpak-cache')
|
|
kde_cache = config['kde_flatpak_cache']
|
|
if Path(kde_cache) == Path(config['flatpak_cache']):
|
|
raise ValueError('KDE must use a separate Flatpak cache')
|
|
relay = config.get('kde_flatpak_download_worker')
|
|
adapter = 'flatpak-relay.sh' if relay else 'flatpak-cache.sh'
|
|
remote(shlex.join(['bash', remote_root + '/source/src/infrastructure/pipeline/' + adapter,
|
|
remote_root + '/source/src', kde_cache, config['bootstrap'],
|
|
config['build_environment']['ARCHIPELAGO_PACKAGE_CACHE'], str(refresh), 'kde', str(initial_fill)] +
|
|
([relay] if relay else [])) +
|
|
' > ' + shlex.quote(remote_root + '/flatpak-kde.log') + ' 2>&1', 14400)
|
|
call(['rsync', '-a', f'{worker}:{kde_cache}/status.json', str(run / 'flatpak-kde-status.json')])
|
|
state['flatpak_kde'] = json.loads((run / 'flatpak-kde-status.json').read_text())
|
|
def adapters_ready():
|
|
if not resume:
|
|
return False
|
|
return subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker,
|
|
adapter_probe(remote_root, desktops)],
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
|
|
if not adapters_ready():
|
|
phase('building-software-adapter')
|
|
if config.get('flatpak_cache'):
|
|
remote(shlex.join(['bash', remote_root + '/source/src/infrastructure/pipeline/prepare-flatpak-tools.sh',
|
|
config['flatpak_cache'], config['bootstrap']]) +
|
|
' > ' + shlex.quote(remote_root + '/flatpak-tools.log') + ' 2>&1', 14400)
|
|
remote(shlex.join(['env', 'ARCHIPELAGO_MIRROR_URL=' + snapshot_url,
|
|
'bash', remote_root + '/source/src/infrastructure/pipeline/build-software-adapter.sh',
|
|
remote_root + '/source/src', config['flatpak_cache'] + '/tools/root.x86_64',
|
|
config['build_environment']['ARCHIPELAGO_PACKAGE_CACHE'], remote_root + '/software-adapter']) +
|
|
' > ' + shlex.quote(remote_root + '/software-adapter.log') + ' 2>&1', 14400)
|
|
call(['rsync', '-a', f'{worker}:{remote_root}/software-adapter/', str(run / 'software-adapter') + '/'])
|
|
if 'kde' in desktops:
|
|
phase('building-discover-adapter')
|
|
remote(shlex.join(['env', 'ARCHIPELAGO_MIRROR_URL=' + snapshot_url,
|
|
'bash', remote_root + '/source/src/infrastructure/pipeline/build-discover-adapter.sh',
|
|
remote_root + '/source/src', config['flatpak_cache'] + '/tools/root.x86_64',
|
|
config['build_environment']['ARCHIPELAGO_PACKAGE_CACHE'], remote_root + '/discover-adapter']) +
|
|
' > ' + shlex.quote(remote_root + '/discover-adapter.log') + ' 2>&1', 14400)
|
|
call(['rsync', '-a', f'{worker}:{remote_root}/discover-adapter/', str(run / 'discover-adapter') + '/'])
|
|
discover_version = ((run / 'discover-adapter' / 'discover-version.txt').read_text().strip()
|
|
if 'kde' in desktops else None)
|
|
builds = {v: remote_root + '/' + v + '/build' for v in build_variants}
|
|
build_env = dict(config['build_environment'], ARCHIPELAGO_SOFTWARE_PLUGIN=remote_root + '/software-adapter/libgs_plugin_archipelago.so',
|
|
ARCHIPELAGO_MIRROR_URL=snapshot_url,
|
|
ARCHIPELAGO_BUILD_OUTPUT=mode,
|
|
ARCHIPELAGO_LOG_DIR=remote_root + '/cli-logs')
|
|
if 'kde' in desktops:
|
|
packages = sorted(Path(remote_root + '/discover-adapter').glob('plasma-setup-*.pkg.tar.zst'))
|
|
if len(packages) != 1:
|
|
raise RuntimeError('expected exactly one plasma-setup package in discover-adapter, found '
|
|
+ str(len(packages)))
|
|
build_env['ARCHIPELAGO_PLASMA_SETUP_PACKAGE'] = str(packages[0])
|
|
if not discover_version:
|
|
raise RuntimeError('missing Discover identity from the adapter build')
|
|
build_env['ARCHIPELAGO_DISCOVER_VERSION'] = discover_version
|
|
if 'kde' in desktops and build_env.get('ARCHIPELAGO_UPDATE_PROFILE'):
|
|
original_profile = build_env['ARCHIPELAGO_UPDATE_PROFILE']
|
|
generated_profile = remote_root + '/update.json'
|
|
remote(shlex.join(['python3', '-c',
|
|
'import json,sys; p=json.load(open(sys.argv[1])); '
|
|
'assert p["version"] == 1; '
|
|
'p["refs"].setdefault("kde", "stable/kde"); '
|
|
'open(sys.argv[2], "w").write(json.dumps(p, indent=2)+"\\n")',
|
|
original_profile, generated_profile]))
|
|
build_env['ARCHIPELAGO_UPDATE_PROFILE'] = generated_profile
|
|
env = 'env ' + ' '.join(shlex.quote(k + '=' + v) for k, v in build_env.items())
|
|
|
|
def variant_done(variant):
|
|
# A changed CLI invalidates every existing variant: the purpose layer
|
|
# asserts byte identity between the Core payload and this binary.
|
|
if not resume or binary_changed:
|
|
return False
|
|
probe = ('test -d ' + shlex.quote(builds[variant]) + '/output && test -d '
|
|
+ shlex.quote(builds[variant]) + '/repo')
|
|
return subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker, probe],
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
|
|
|
|
if not variant_done('core'):
|
|
phase('building-core')
|
|
remote(f'''test "$(df -PB1 {remote_root} | awk 'NR==2 {{print $4}}')" -ge {config.get('minimum_build_free_bytes', 60000000000)}
|
|
mkdir -p {remote_root}/core {remote_root}/gnome
|
|
{env} {remote_root}/archipelago build iso {builds['core']} {shlex.quote(config['bootstrap'])} > {remote_root}/core/build.log 2>&1
|
|
rm -rf {builds['core']}/iso-work {builds['core']}/profile {builds['core']}/extractor {builds['core']}/tools {builds['core']}/composed {builds['core']}/layer''', 14400)
|
|
if not variant_done('gnome'):
|
|
phase('building-gnome-purpose')
|
|
remote(f'{env} ARCHIPELAGO_CORE_BUILD={builds["core"]} {remote_root}/archipelago build iso --purpose gnome {builds["gnome"]} {shlex.quote(config["bootstrap"])} > {remote_root}/gnome/build.log 2>&1', 14400)
|
|
if 'kde' in desktops:
|
|
phase('building-kde-purpose')
|
|
remote('rm -rf ' + ' '.join(shlex.quote(builds['gnome'] + '/' + name) for name in
|
|
('iso-work', 'profile', 'extractor', 'tools', 'core', 'layer', 'composed', 'core-base', 'flatpak-seed')))
|
|
kde_env = dict(build_env,
|
|
ARCHIPELAGO_DISCOVER_PLUGIN=remote_root + '/discover-adapter/archipelago-backend.so',
|
|
ARCHIPELAGO_FLATPAK_SEED=config['kde_flatpak_cache'] + '/current',
|
|
ARCHIPELAGO_FLATPAK_POLICY=remote_root + '/source/src/purposes/proposals/kde-flatpak-apps.json')
|
|
kde_env.pop('ARCHIPELAGO_SOFTWARE_PLUGIN', None)
|
|
kde_command = shlex.join(['env', *[k + '=' + v for k, v in kde_env.items()],
|
|
'ARCHIPELAGO_CORE_BUILD=' + builds['core'], remote_root + '/archipelago',
|
|
'build', 'iso', '--purpose', 'kde', builds['kde'], config['bootstrap']])
|
|
# A resumed run may find a partial tree from the interrupted attempt;
|
|
# build-iso.sh expects a clean directory.
|
|
remote('rm -rf ' + shlex.quote(builds['kde']) + f'; mkdir -p {remote_root}/kde')
|
|
remote(f'{kde_command} > {remote_root}/kde/build.log 2>&1', 14400)
|
|
if container:
|
|
phase('building-container-runner')
|
|
container_env = dict(build_env)
|
|
container_env.pop('ARCHIPELAGO_SOFTWARE_PLUGIN', None)
|
|
container_env.pop('ARCHIPELAGO_PLASMA_SETUP_PACKAGE', None)
|
|
container_env.pop('ARCHIPELAGO_DISCOVER_VERSION', None)
|
|
container_command = shlex.join(['env', *[k + '=' + v for k, v in container_env.items()],
|
|
'ARCHIPELAGO_CORE_BUILD=' + builds['core'], remote_root + '/archipelago',
|
|
'build', 'iso', '--purpose', 'container-runner', builds['container'], config['bootstrap']])
|
|
remote('rm -rf ' + shlex.quote(builds['container']) + f'; mkdir -p {remote_root}/container')
|
|
remote(f'{container_command} > {remote_root}/container/build.log 2>&1', 14400)
|
|
state['vm_acceptance'] = {'state': 'manual-only', 'policy': 'D-098'}
|
|
phase('archiving-artifacts')
|
|
if shutil.disk_usage(base / 'data').free < config.get('minimum_coordinator_free_bytes', 50000000000):
|
|
raise ValueError('Insufficient coordinator space for artifact archive and publication')
|
|
for variant in build_variants:
|
|
dest = run / variant / 'build'
|
|
dest.mkdir(parents=True)
|
|
# Stream immutable completed trees: rsync's per-file round trips are
|
|
# disproportionately expensive for OSTree's many small objects.
|
|
transfer = shlex.join(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker,
|
|
shlex.join(['tar', '-C', builds[variant], '-cf', '-', 'repo', 'output', 'evidence'])])
|
|
call(['bash', '-o', 'pipefail', '-c', transfer + ' | ' +
|
|
shlex.join(['tar', '-C', str(dest), '-xf', '-'])])
|
|
call(tools(['ostree', '--repo=' + str(dest / 'repo'), 'fsck']))
|
|
state['artifacts_archived'] = True
|
|
call(['rsync', '-a', f'{worker}:{remote_root}/inputs.sha256', str(run) + '/'])
|
|
call(['rsync', '-a', f'{worker}:{remote_root}/source.tar', f'{worker}:{remote_root}/archipelago', str(run) + '/'])
|
|
call(['rsync', '-a', f'{worker}:{remote_root}/cli-logs/', str(run / 'cli-logs') + '/'])
|
|
phase('preparing-publication')
|
|
def digest(path):
|
|
with Path(path).open('rb') as stream:
|
|
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
|
evidence = run / 'rust-evidence.json'
|
|
atomic(evidence, dict(policy='D-098', passed=True, source=str(run / 'source.tar'),
|
|
source_sha256=digest(run / 'source.tar'),
|
|
checks=[dict(path=str(run / name), sha256=digest(run / name)) for name in
|
|
('service-contract-checks.log', 'control-portal-checks.log')]))
|
|
review = {'output': str(run / 'candidates.json'), 'candidates': [dict(
|
|
variant=v, version=stamp, directory=str(run / v),
|
|
iso_name=iso_name(v) if mode == 'iso' else None,
|
|
rust_evidence=str(evidence), checks=[{'path': str(evidence)}],
|
|
limitations=['D-098: boot, hardware and GUI scenarios are user manual checks; no VM acceptance',
|
|
'Rust and adapter checks do not establish full bitwise reproducibility']) for v in variants]}
|
|
atomic(run / 'review.json', review)
|
|
call(tools(['python3', '/pipeline/prepare-hardware-pair.py', run / 'review.json']))
|
|
records = json.loads((run / 'candidates.json').read_text())
|
|
publish_variants = variants if config.get('kde_release_decision') else ('core', 'gnome')
|
|
publication_records = [r for r in records if r['variant'] in publish_variants]
|
|
atomic(run / 'publication-candidates.json', publication_records)
|
|
state['private_candidates'] = [{k: r.get(k) for k in ('variant', 'version', 'sha256', 'image_commit', 'layer_commit')}
|
|
for r in records if r['variant'] not in publish_variants]
|
|
atomic(run / 'release-authorization.json', {
|
|
'channel': 'stable', 'decision': 'D-098',
|
|
'reason': 'User-approved Rust/manual policy and separate OSTree/ISO cadence',
|
|
'limitations': review['candidates'][0]['limitations'],
|
|
'candidates': [{k: r.get(k) for k in ('variant', 'version', 'sha256', 'image_commit', 'layer_commit')}
|
|
for r in publication_records]})
|
|
phase('signing-and-publishing')
|
|
call(tools(['python3', '/pipeline/publish-hardware.py', base / 'data/public', run / 'publication-candidates.json',
|
|
'--gpg-home', '/signing', '--gpg-key', config['signing_key'], '--url-prefix', '/archipelago',
|
|
'--channel', 'stable', '--core-ref', 'stable/core', '--gnome-ref', 'stable/gnome',
|
|
'--release-exception', run / 'release-authorization.json'] +
|
|
(['--kde-ref', 'stable/kde'] if 'kde' in publish_variants else []), True))
|
|
phase('verifying-public-endpoints', published=True)
|
|
url = config['public_url'].rstrip('/')
|
|
for record in publication_records:
|
|
for kind, key in (('images', 'image_commit'), ('layers', 'layer_commit')):
|
|
with urllib.request.urlopen(url + '/ostree/' + kind + '/refs/heads/stable/' + record['variant'], timeout=60) as response:
|
|
if response.read().decode().strip() != record[key]:
|
|
raise ValueError('Public OSTree ref identity mismatch')
|
|
current = []
|
|
if mode == 'iso':
|
|
with urllib.request.urlopen(url + '/v1/releases.json', timeout=60) as response:
|
|
releases = json.load(response)['releases']
|
|
current = [r for r in releases if r['current']]
|
|
# Container Runner has its own current card, which may still point at
|
|
# the previous month's ISO on an OSTree or desktop-ISO cycle.
|
|
desktop_current = [r for r in current if r.get('variant') != 'container']
|
|
if ({r['variant'] for r in desktop_current} != set(publish_variants)
|
|
or len(desktop_current) != len(publish_variants)
|
|
or any(r['version'] != stamp for r in desktop_current)):
|
|
raise ValueError('Published catalog does not match this cycle')
|
|
current = desktop_current
|
|
for item in current:
|
|
address = url.split('/archipelago')[0] + item['url']
|
|
with urllib.request.urlopen(urllib.request.Request(address, method='HEAD'), timeout=60) as response:
|
|
if response.status != 200 or int(response.headers['Content-Length']) != item['size_bytes']:
|
|
raise ValueError('Public ISO size mismatch')
|
|
with urllib.request.urlopen(address + '.sha256', timeout=60) as response:
|
|
if response.read().decode().split()[0] != item['sha256']:
|
|
raise ValueError('Public checksum mismatch')
|
|
if container:
|
|
phase('publishing-container-runner')
|
|
iso_arguments = []
|
|
if mode == 'iso':
|
|
iso_arguments = ['--iso', str(run / 'container/build/output' / iso_name('container'))]
|
|
call(tools(['python3', '/pipeline/publish-container-runner.py', str(base / 'data/public'),
|
|
str(run / 'container/build'), '--version', stamp, '--gpg-home', '/signing',
|
|
'--gpg-key', config['signing_key'], *iso_arguments], True))
|
|
with urllib.request.urlopen(url + '/v1/container-runner.json', timeout=60) as response:
|
|
container_record = json.load(response)
|
|
for kind, key in (('images', 'image_commit'), ('layers', 'layer_commit')):
|
|
with urllib.request.urlopen(url + '/ostree/' + kind + '/refs/heads/stable/container', timeout=60) as response:
|
|
if response.read().decode().strip() != container_record[key]:
|
|
raise ValueError('Container Runner ref identity mismatch')
|
|
with urllib.request.urlopen(url + '/ostree/layers/refs/heads/purpose/server/container-runner', timeout=60) as response:
|
|
if response.read().decode().strip() != container_record['purpose_layer_commit']:
|
|
raise ValueError('Container Runner purpose ref mismatch')
|
|
if mode == 'iso':
|
|
address = url.split('/archipelago')[0] + container_record['url']
|
|
with urllib.request.urlopen(urllib.request.Request(address, method='HEAD'), timeout=60) as response:
|
|
if response.status != 200 or int(response.headers['Content-Length']) != container_record['size_bytes']:
|
|
raise ValueError('Container Runner ISO size mismatch')
|
|
with urllib.request.urlopen(address + '.sha256', timeout=60) as response:
|
|
if response.read().decode().split()[0] != container_record['sha256']:
|
|
raise ValueError('Container Runner checksum mismatch')
|
|
if mode == 'iso':
|
|
with urllib.request.urlopen(url + '/v1/releases.json', timeout=60) as response:
|
|
catalog = json.load(response)['releases']
|
|
cards = [item for item in catalog
|
|
if item.get('current') and item.get('variant') == 'container']
|
|
if len(cards) != 1 or cards[0]['version'] != stamp:
|
|
raise ValueError('Container Runner catalog card does not match this cycle')
|
|
state['container'] = container_record
|
|
phase('cleaning-worker', releases=current)
|
|
# Local terra worker logs must survive removal of the build workspace.
|
|
# Preserve every nested build/CLI/guest/serial log, not just log tails.
|
|
retain_logs()
|
|
remote('rm -rf ' + shlex.quote(remote_root))
|
|
phase('complete', finished=datetime.now(timezone.utc).isoformat())
|
|
cleanup_module.cleanup(parent, None)
|
|
except BaseException as error:
|
|
detail = str(error)
|
|
concise = ('Stage command exited with code ' + str(error.returncode)) if isinstance(error, subprocess.CalledProcessError) else detail
|
|
phase('failed', error=concise, error_details=detail, failed_phase=state['state'])
|
|
containers = subprocess.check_output(['docker', 'ps', '-q', '--filter', 'label=archipelago.release-run=' + stamp], text=True).split()
|
|
if containers:
|
|
observer.call(['docker', 'stop', '--timeout', '20', *containers], timeout=60, check=False)
|
|
# Never select host units by broad process/name patterns. Preserve artifact
|
|
# bytes and evidence, not disposable unpacked trees that would fill the worker.
|
|
observer.call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', worker,
|
|
shlex.join(['systemctl', 'stop', *worker_units])], timeout=120, check=False)
|
|
retain_logs()
|
|
if isinstance(error, (InterruptedError, KeyboardInterrupt)):
|
|
# A stop means stop, not another multi-gigabyte artifact transfer.
|
|
# Worker artifacts stay in place; logs are already retained.
|
|
raise
|
|
excluded = ['tools', 'iso-work', 'profile', 'extractor', 'core-base', 'purpose-stage',
|
|
'composed', 'layer', 'purpose-layer', 'purpose-input', 'flatpak-seed', '*.qcow2',
|
|
'/core/build/core', '/gnome/build/core', '/kde/build/core', '/container/build/core',
|
|
# An OSTree repo is a rebuildable duplicate of the run's layers and
|
|
# dominates the archive (gigabytes); it also kept the transfer alive
|
|
# long after the run had ended.
|
|
'/core/build/repo', '/gnome/build/repo', '/kde/build/repo',
|
|
'/container/build/repo']
|
|
if state.get('artifacts_archived'):
|
|
excluded += ['/core/build', '/gnome/build', '/kde/build', '/container/build']
|
|
# Retention of a newer cycle must not delete these trees while tar is
|
|
# still writing them; cleanup-cycle.py takes the same per-run lock.
|
|
archive_lock = cleanup_module.lock_run(run)
|
|
try:
|
|
destination = run / 'failure-evidence'
|
|
destination.mkdir(parents=True, exist_ok=True)
|
|
archive_command = ['tar', '-C', remote_root,
|
|
*['--exclude=' + ('.' + x if x.startswith('/') else x) for x in excluded],
|
|
'-cf', '-', '.']
|
|
transfer = shlex.join(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker,
|
|
shlex.join(archive_command)])
|
|
archived = observer.call(['bash', '-o', 'pipefail', '-c', transfer + ' | ' +
|
|
shlex.join(['tar', '-C', str(destination), '-xf', '-'])], timeout=1800, check=False)
|
|
if archived.returncode == 0:
|
|
remote('rm -rf ' + shlex.quote(remote_root))
|
|
finally:
|
|
archive_lock.close()
|
|
raise
|
|
finally:
|
|
if state.get('invocation_id'):
|
|
observer.call(['journalctl', '_SYSTEMD_INVOCATION_ID=' + state['invocation_id'],
|
|
'--no-pager', '--output=short-iso-precise'], timeout=60, check=False)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|