#!/usr/bin/env python3 """Bounded daily Core -> GNOME -> installed-VM checks -> signed publication. This driver publishes stable under the explicit daily authorization D-087. Outstanding admission evidence remains recorded; D-079 is not reused. """ 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 import importlib.util 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) 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='stable', invocation_id=os.environ.get('INVOCATION_ID'), worker=worker, reason=os.environ.get('ARCHIPELAGO_RELEASE_REASON', 'Daily release cycle')) step = 0 worker_units = [] titles = {'preflight': 'Проверка стенда', 'freezing-and-compiling-source': 'Подготовка исходников и CLI', 'updating-flatpak-cache': 'Обновление кэша Flatpak', 'building-core': 'Сборка Core', 'building-software-adapter': 'Сборка адаптера GNOME Software', 'building-gnome-purpose-and-iso': 'Сборка GNOME', 'archiving-artifacts': 'Передача артефактов на terra', 'core-installed-acceptance': 'Приёмка Core в VM', 'gnome-installed-acceptance': 'Приёмка GNOME в VM', 'preparing-publication': 'Проверка результатов', 'signing-and-publishing': 'Подпись и публикация', 'verifying-public-endpoints': 'Проверка сайта', 'cleaning-worker': 'Очистка временных файлов', 'complete': 'Готово', 'failed': 'Ошибка'} def phase(name, **extra): state.update(state=name, stage_title=titles.get(name, 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) text = f"Прогон: {stamp}\nСтенд: {worker}\nЭтап: {state['stage_title']}\nОбновлено: {state['updated']}\nОпубликовано: {'да' if state['published'] else 'нет'}\n" if state.get('flatpak'): text += 'Flatpak: ' + state['flatpak']['state'] + '\n' if state.get('error'): text += 'Причина: ' + state['error'] + '\n' text += f"Логи сборки/проверок: {worker}:{remote_root}\nРезультаты: {run}\n" (parent / 'latest.txt.tmp').write_text(text) (parent / 'latest.txt.tmp').replace(parent / 'latest.txt') 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 def validate_pair(): for variant in ('core', 'gnome'): (run / variant).mkdir(exist_ok=True) 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') + '/']) 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') + '/']) remote('systemctl stop ' + shlex.quote(vm_unit)) 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') 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]) + '; 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') atomic(run / 'private-cleanup.json', {'removed': cleanup_module.cleanup(parent, stamp)}) remote(f'mkdir -p {shlex.quote(remote_root)}; test -c /dev/kvm; command -v qemu-system-x86_64; python3 -c "import pexpect"; test -f {shlex.quote(config["worker_source_root"])}/src/rfc/schemas/layer-v1.schema.json') # 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 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 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 config.get('flatpak_cache') and not args.existing: remote(f'test "$(df -PB1 {remote_root} | awk \'NR==2 {{print $4}}\')" -ge {config.get("minimum_build_free_bytes", 45000000000)}') phase('updating-flatpak-cache') refresh = int(config.get('flatpak_refresh_seconds', 1800)) 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)]) + ' > ' + shlex.quote(remote_root + '/flatpak.log') + ' 2>&1', refresh + 600) 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 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-software-adapter') remote(shlex.join(['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', 3600) call(['rsync', '-a', f'{worker}:{remote_root}/software-adapter/', str(run / 'software-adapter') + '/']) phase('building-core') builds = {v: remote_root + '/' + v + '/build' for v in ('core', 'gnome')} build_env = dict(config['build_environment'], ARCHIPELAGO_SOFTWARE_PLUGIN=remote_root + '/software-adapter/libgs_plugin_archipelago.so') env = 'env ' + ' '.join(shlex.quote(k + '=' + v) for k, v in build_env.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) validate_pair() 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 ('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) + '/']) 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'] = ['Daily stable publication authorized by D-087; outstanding admission evidence remains open', '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'])) records = json.loads((run / 'candidates.json').read_text()) atomic(run / 'release-authorization.json', { 'channel': 'stable', 'decision': 'D-087', 'reason': 'Explicit user authorization for daily stable publication and installed-ISO update continuity', 'limitations': review['candidates'][0]['limitations'], 'candidates': [{k: r[k] for k in ('variant', 'version', 'sha256', 'image_commit', 'layer_commit')} for r in records]}) 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', 'stable', '--core-ref', 'stable/core', '--gnome-ref', 'stable/gnome', '--release-exception', run / 'release-authorization.json'], 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) reused = [dict(path=builds[item['variant']], variant=item['variant'], sha256=item['sha256']) for item in current if not Path(builds[item['variant']]).is_relative_to(remote_root) and re.fullmatch(re.escape(config['worker_root'] + '/build/release-cycle/') + r'[0-9]{8}T[0-9]{6}Z/(core|gnome)/build', builds[item['variant']])] if reused: # Preserve original build sources as well as the acceptance run sources. for index, item in enumerate(reused): original = Path(item['path']).parent.parent call(['rsync', '-a', f'{worker}:{original}/source.tar', str(run / f'reused-source-{index}.tar')]) remote(shlex.join(['python3', remote_root + '/source/src/infrastructure/pipeline/cleanup-worker-inputs.py', config['worker_root'], json.dumps(reused)])) 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 = ('Команда этапа завершилась с кодом ' + str(error.returncode)) if isinstance(error, subprocess.CalledProcessError) else detail phase('failed', error=concise, error_details=detail, 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, 'if systemctl is-active --quiet ' + shlex.quote(vm_unit) + '; then systemctl stop ' + shlex.quote(vm_unit) + '; fi'], timeout=120) if __name__ == '__main__': main()