infrastructure/pipeline/release-cycle.py

290 lines
19 KiB
Python

#!/usr/bin/env python3
"""Bounded daily Core -> GNOME -> installed-VM checks -> signed publication.
This driver publishes the hardware-test channel. Stable/testing admission is a
separate contract; the one-build D-079 exception must never be reused here.
"""
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 urllib.request
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 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('--existing', help='JSON mapping core/gnome to existing worker build directories')
parser.add_argument('--archive', type=Path, help='Reuse matching archived inputs; seed delta transfer when rebuilding Purpose')
parser.add_argument('--core-build', help='Reuse a completed worker Core build; rebuild only Purpose and repeat both VM checks')
args = parser.parse_args()
if args.core_build and (args.existing or not Path(args.core_build).is_absolute()):
parser.error('--core-build requires an absolute path and cannot accompany --existing')
if args.archive and (not (args.existing or args.core_build) or not args.archive.is_absolute()):
parser.error('--archive requires --existing or --core-build and an absolute coordinator path')
config = json.loads(Path(args.config).read_text())
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
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
run = parent / stamp
run.mkdir()
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', ignore=shutil.ignore_patterns('__pycache__'))
atomic(run / 'config.json', config)
worker = config['worker']
remote_root = config['worker_root'] + '/build/release-cycle/' + stamp
state = dict(version=1, run=stamp, started=datetime.now(timezone.utc).isoformat(),
state='starting', published=False, channel='hardware-test',
invocation_id=os.environ.get('INVOCATION_ID'),
reason=os.environ.get('ARCHIPELAGO_RELEASE_REASON', 'Daily release cycle'))
step = 0
worker_units = []
def phase(name, **extra):
state.update(state=name, updated=datetime.now(timezone.utc).isoformat(), **extra)
atomic(run / 'state.json', state)
atomic(parent / 'latest.json', state)
atomic(base / 'data/public/pipeline.json', state)
print(json.dumps(state), flush=True)
def call(argv, timeout=14400):
subprocess.run([str(x) for x in argv], check=True, timeout=timeout)
def remote(script, timeout=14400):
nonlocal step
step += 1
unit = 'archipelago-cycle-' + stamp + '-' + str(step)
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 - 30),
'bash', '-euo', 'pipefail', '-c', script])], timeout)
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', '--network=none', '--env', 'ARCHIPELAGO_RELEASE_REASON',
*mounts, config['coordinator_tools_image'], *map(str, argv)]
def interrupted(signum, frame):
raise InterruptedError('Coordinator received signal ' + str(signum))
signal.signal(signal.SIGTERM, interrupted)
signal.signal(signal.SIGINT, interrupted)
builds = None
vm_unit = 'archipelago-cycle-gnome-' + stamp
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]+', u) for u in units):
raise ValueError('Invalid previous worker unit identity')
call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker,
'set -e; for unit in ' + shlex.join([*units, 'archipelago-cycle-gnome-' + 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)
phase('preflight')
remote(f'mkdir -p {shlex.quote(remote_root)}; test -c /dev/kvm; command -v qemu-system-x86_64; python3 -c "import pexpect"')
# Compile from the frozen source tree, not a possibly stale deployed CLI.
phase('freezing-and-compiling-source')
remote(f'''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
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
sha256sum {remote_root}/archipelago > {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''')
if args.existing:
builds = json.loads(Path(args.existing).read_text())
if set(builds) != {'core', 'gnome'} or any(not Path(x).is_absolute() for x in builds.values()):
raise ValueError('Existing inputs must name absolute Core and GNOME build paths')
atomic(run / 'existing-inputs.json', builds)
else:
phase('building-core')
builds = {v: remote_root + '/' + v + '/build' for v in ('core', 'gnome')}
env = 'env ' + ' '.join(shlex.quote(k + '=' + v) for k, v in config['build_environment'].items())
if args.core_build:
builds['core'] = args.core_build
atomic(run / 'reused-core-build.json', {'path': args.core_build})
remote(f'mkdir -p {remote_root}/gnome; test -s {shlex.quote(args.core_build)}/output/SHA256SUMS')
else:
remote(f'''test "$(df -PB1 {remote_root} | awk 'NR==2 {{print $4}}')" -ge {config.get('minimum_build_free_bytes', 45000000000)}
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''', 10800)
phase('building-gnome-purpose-and-iso')
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', 10800)
phase('archiving-artifacts')
for variant in ('core', 'gnome'):
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.
if args.archive and (args.existing or variant == 'core'):
archived = args.archive / variant / 'build'
names = ['output/' + ('archipelago-core-latest.iso' if variant == 'core' else 'archipelago-gnome-probe.iso'),
'repo/refs/heads/core', 'repo/refs/heads/layers/core']
if variant == 'gnome':
names.append('repo/refs/heads/layers/purpose/desktop/gnome')
expected = []
for name in names:
with (archived / name).open('rb') as stream:
expected.append(hashlib.file_digest(stream, 'sha256').hexdigest())
actual = subprocess.check_output(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker,
'cd ' + shlex.quote(builds[variant]) + ' && ' + shlex.join(['sha256sum', *names])],
text=True, timeout=300)
if [line.split()[0] for line in actual.splitlines()] != expected:
raise ValueError('Archived ISO or refs differ from worker: ' + variant)
for part in ('repo', 'output', 'evidence'):
call(['cp', '-a', '--reflink=auto', archived / part, dest])
atomic(run / (variant + '-archive-reuse.json'), {'archive': str(archived), 'files': dict(zip(names, expected))})
elif args.archive:
# Seed from prior immutable bytes, then transfer only differences.
# Checksums (not mtime) decide reuse; delete stale refs/files only
# in this new run's private copy. fsck below validates the result.
archived = args.archive / variant / 'build'
for part in ('repo', 'output', 'evidence'):
call(['cp', '-a', '--reflink=auto', archived / part, dest])
call(['rsync', '-a', '--checksum', '--delete',
f'{worker}:{builds[variant]}/{part}/', str(dest / part) + '/'])
else:
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) + '/'])
# Fresh builds have no future consumers of scratch trees. Keep artifacts
# and all diagnostics; remove only documented generated work directories.
if not args.existing:
remote('\n'.join('rm -rf ' + ' '.join(shlex.quote(builds[v] + '/' + name) for name in
('iso-work', 'profile', 'extractor', 'tools', 'core', 'layer', 'composed', 'core-base', 'flatpak-seed'))
for v in (('gnome',) if args.core_build else ('core', 'gnome'))))
phase('core-installed-acceptance')
remote(f'''mkdir -p {remote_root}/core/vms
python3 {remote_root}/probes/core_iso_acceptance.py --iso {shlex.quote(builds['core'])}/output/archipelago-core-latest.iso --workdir {remote_root}/core/vms --production-cli --extensions-sequence --firmware --ovmf-code {shlex.quote(config['ovmf_code'])} --ovmf-vars {shlex.quote(config['ovmf_vars'])} > {remote_root}/core/acceptance.log 2>&1''', 7200)
call(['rsync', '-a', '--include=*/', '--include=*.json', '--include=*.jsonl', '--include=*.serial', '--exclude=*',
f'{worker}:{remote_root}/core/vms/', str(run / 'core/vms') + '/'])
call(['rsync', '-a', f'{worker}:{remote_root}/core/acceptance.log', str(run / 'core') + '/'])
# The Core VM has exited. Release only its disposable disk after evidence
# archival, so the following GNOME VM fits on the same worker.
remote(f'find {remote_root}/core/vms -name core.qcow2 -type f -delete')
phase('gnome-installed-acceptance')
remote(shlex.join(['python3', remote_root + '/probes/gnome_native_acceptance.py',
'--iso', builds['gnome'] + '/output/archipelago-gnome-probe.iso',
'--workdir', remote_root + '/gnome/acceptance', '--unit', vm_unit,
'--ovmf-code', config['ovmf_code'], '--ovmf-vars', config['ovmf_vars']]), 7200)
call(['rsync', '-a', '--include=*/', '--include=*.json', '--include=*.log', '--include=*.serial',
'--include=*.png', '--exclude=*', f'{worker}:{remote_root}/gnome/acceptance/', str(run / 'gnome/acceptance') + '/'])
phase('preparing-publication')
core_summaries = list((run / 'core/vms').glob('*/summary.json'))
if len(core_summaries) != 1:
raise ValueError('Missing or ambiguous Core acceptance')
review = {'output': str(run / 'candidates.json'), 'candidates': [
dict(variant='core', version=stamp, directory=str(run / 'core'), iso_name='archipelago-core-latest.iso',
core_summary=str(core_summaries[0]), checks=[{'path': str(core_summaries[0])}]),
dict(variant='gnome', version=stamp, directory=str(run / 'gnome'), iso_name='archipelago-gnome-probe.iso',
native_summary=str(run / 'gnome/acceptance/native-acceptance.json'),
checks=[{'path': str(run / 'gnome/acceptance/native-acceptance.json')},
{'path': str(run / 'gnome/acceptance/guest.log')}]) ]}
for item in review['candidates']:
item['limitations'] = ['Experimental daily channel; not stable/testing admission',
'General Managed Overlay release gate, full reproducibility and GUI OS-update acceptance remain open']
atomic(run / 'review.json', review)
call(tools(['python3', '/pipeline/prepare-hardware-pair.py', run / 'review.json']))
phase('signing-and-publishing')
call(tools(['python3', '/pipeline/publish-hardware.py', base / 'data/public', run / 'candidates.json',
'--gpg-home', '/signing', '--gpg-key', config['signing_key'], '--url-prefix', '/archipelago',
'--channel', 'hardware-test', '--core-ref', 'hardware-test/core', '--gnome-ref', 'hardware-test/gnome'], True))
phase('verifying-public-endpoints', published=True)
url = config['public_url'].rstrip('/')
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']]
if len(current) != 2 or any(r['version'] != stamp for r in current):
raise ValueError('Published catalog does not match this cycle')
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')
phase('cleaning-worker', releases=current)
remote('systemctl stop ' + shlex.quote(vm_unit) + '; rm -rf ' + shlex.quote(remote_root))
phase('complete', finished=datetime.now(timezone.utc).isoformat())
completed = sorted(p for p in parent.iterdir() if p.is_dir() and (p / 'state.json').exists()
and json.loads((p / 'state.json').read_text()).get('state') == 'complete')
for old in completed[:-3]:
for variant in ('core', 'gnome'):
# Keep evidence/source/status, expire only archived artifact bytes.
for name in ('repo', 'output'):
shutil.rmtree(old / variant / 'build' / name, ignore_errors=True)
except BaseException as error:
phase('failed', error=str(error), failed_phase=state['state'])
# Stop this run's VM before archiving diagnostics; never select host VMs
# by broad process/name patterns. Preserve artifact bytes and evidence,
# not disposable unpacked trees that would fill the worker every day.
subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', worker,
shlex.join(['systemctl', 'stop', vm_unit, *worker_units])], timeout=120)
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']
if state.get('artifacts_archived'):
excluded += ['/core/build', '/gnome/build']
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 = subprocess.run(['bash', '-o', 'pipefail', '-c', transfer + ' | ' +
shlex.join(['tar', '-C', str(destination), '-xf', '-'])], timeout=1800)
if archived.returncode == 0:
remote('rm -rf ' + shlex.quote(remote_root))
raise
finally:
subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', worker,
'systemctl stop ' + shlex.quote(vm_unit)], timeout=120)
if __name__ == '__main__':
main()