infrastructure/pipeline/daily-core.py

132 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""Experimental daily Core driver. Private results; no release/channel publishing.
The backend remains the tested monolithic CLI ISO experiment. Independent layer
composition and installed-host registry updates are subsequent implementation work.
"""
from datetime import datetime, timezone
import fcntl
import hashlib
import json
import os
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import tempfile
def digest(path):
with Path(path).open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def atomic(path, value):
with tempfile.NamedTemporaryFile(mode='w', dir=path.parent, delete=False) as stream:
json.dump(value, stream, sort_keys=True, indent=2)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
os.replace(stream.name, path)
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
def main():
config = json.loads(Path(sys.argv[1]).read_text())
root = Path(config['private_root'])
root.mkdir(parents=True, exist_ok=True, mode=0o700)
now = datetime.now(timezone.utc)
attempt = now.strftime('%Y%m%dT%H%M%S.%fZ')
lock = (root / 'daily-core.lock').open('a')
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
atomic(root / ('skipped-' + attempt + '.json'), {'state': 'skipped-overlap', 'time': now.isoformat()})
return
run = root / attempt
run.mkdir(mode=0o700)
state = {'attempt': attempt, 'started': now.isoformat(), 'state': 'queued', 'public_release': False}
def stage(name):
state['state'] = name
atomic(run / 'run.json', state)
def call(args, logfile, timeout=3600, env=None):
with (run / logfile).open('ab') as log:
process = subprocess.Popen([str(a) for a in args], stdout=log, stderr=subprocess.STDOUT,
env=env, start_new_session=True)
try:
status = process.wait(timeout=timeout)
except BaseException:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=30)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
raise
if status:
raise subprocess.CalledProcessError(status, args)
try:
stage('pinning-sources')
source = run / 'source'
source.mkdir()
for component in ['cli', 'builder', 'contracts', 'composer', 'installer', 'registry', 'system', 'rfc', 'test-lab', 'purposes']:
shutil.copytree(Path(config['source_root']) / component, source / component,
ignore=shutil.ignore_patterns('.git', 'target', '__pycache__', '*.pyc'))
call(['git', 'clone', '--depth=1', 'https://git.fasoley.net/Archipelago/core.git', source / 'core'], 'source.log')
state['core_commit'] = subprocess.check_output(['git', '-C', str(source / 'core'), 'rev-parse', 'HEAD'], text=True).strip()
# This backend supports only its reviewed Core profile. New YAML content
# fails explicitly until the builder is adapted; it is never ignored.
manifest = source / 'core/layers/arch.yaml'
if digest(manifest) != config['supported_core_sha256']:
raise ValueError('Core YAML changed: this experimental backend requires profile review')
hashes = {str(p.relative_to(source)): digest(p) for p in sorted(source.rglob('*'))
if p.is_file() and '.git' not in p.parts}
atomic(run / 'source-files.json', hashes)
state['source_identity'] = hashlib.sha256(json.dumps(hashes, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
state['tools_image'] = config['tools_image']
stage('compiling-cli')
call(['docker', 'run', '--rm', '--network=none', '--cap-drop=ALL', '--security-opt=no-new-privileges',
'--mount', f'type=bind,src={source},dst=/src,readonly',
'--mount', f'type=bind,src={config["build_cache"]},dst=/build',
'--mount', f'type=bind,src={config["cargo_cache"]},dst=/usr/local/cargo/registry,readonly',
config['tools_image'], 'cargo', 'build', '--manifest-path', '/src/cli/Cargo.toml', '--offline', '--locked', '--release'], 'compile.log')
binary = run / 'archipelago'
shutil.copy2(Path(config['build_cache']) / 'target/release/archipelago', binary)
state['binary_sha256'] = digest(binary)
call([binary, 'layer', 'validate', manifest], 'manifest.log')
bootstrap = Path(config['bootstrap'])
if digest(bootstrap) != '655bc99849b80859173fa39338a6c910185e952173f6a1a61526cfa34ab8339c':
raise ValueError('Bootstrap checksum mismatch')
stage('building-iso')
env = dict(os.environ, ARCHIPELAGO_PACKAGE_CACHE=config['package_cache'])
call([binary, 'build', 'iso', run / 'build', bootstrap], 'build.log', timeout=21600, env=env)
iso = run / 'build/output/archipelago-core-latest.iso'
state['iso_sha256'] = digest(iso)
state['image_commit'] = subprocess.check_output([
'docker', 'run', '--rm', '--network=none', '--read-only', '--cap-drop=ALL',
'--mount', f'type=bind,src={run / "build/repo"},dst=/repo,readonly',
config['tools_image'], 'ostree', '--repo=/repo', 'rev-parse', 'core'], text=True).strip()
stage('validating-vm')
vms = run / 'vms'
vms.mkdir()
call(['python3', source / 'test-lab/probes/core_iso_acceptance.py', '--iso', iso,
'--workdir', vms, '--extensions-sequence', '--firmware',
'--ovmf-code', config['ovmf_code'], '--ovmf-vars', config['ovmf_vars']], 'acceptance.log', timeout=10800)
stage('candidate-ready')
# Local evidence pointer only, not an authenticated release/channel manifest.
atomic(root / 'latest-candidate.json', state | {'directory': str(run), 'iso': str(iso)})
except BaseException as error:
state['error'] = str(error)
stage('failed')
raise
finally:
lock.close()
if __name__ == '__main__':
main()