#!/usr/bin/env python3 """从已锁定的本地组件生成 Firecracker 依赖包;不发布、不安装宿主。""" import argparse import gzip import hashlib import io import json import os from pathlib import Path import stat import struct import tarfile import tempfile ROOT = Path(__file__).resolve().parents[1] NAMES = { 'firecracker': 0o755, 'jailer': 0o755, 'kernel': 0o644, 'umoci': 0o755, 'mke2fs': 0o755, 'monkeyai-guest': 0o755, 'monkeyai-selftest': 0o755, 'guest-bootstrap': 0o755, 'monkeyai-guest.service': 0o644, } MAX_FILE = 256 << 20 def digest(path): h = hashlib.sha256() with path.open('rb') as f: while data := f.read(1 << 20): h.update(data) return h.hexdigest() def static_elf(path, architecture): with path.open('rb') as f: header = f.read(64) if len(header) != 64 or header[:7] != b'\x7fELF\x02\x01\x01': raise ValueError(f'{path.name} 不是 Linux 64位小端 ELF') expected = {'amd64': 62, 'arm64': 183}[architecture] if struct.unpack_from(' 256 or count and size < 56: raise ValueError('ELF program header 无效') for index in range(count): f.seek(offset + index * size) entry = f.read(56) if len(entry) != 56 or struct.unpack_from(' 16 << 10 or path.parent.resolve() != destination.resolve(): raise ValueError('父发行清单必须为同目录有界普通文件') raw = path.read_bytes() parent = json.loads(raw) if (parent.get('architecture') != architecture or not parent.get('version') or not isinstance(parent.get('files'), dict) or 'firecracker' in parent): raise ValueError('父清单架构、版本或既有VM声明不匹配') for name, checksum in parent['files'].items(): if Path(name).name != name or not name or name in ('.', '..'): raise ValueError('父清单包含非普通组件名称') component = destination / name if (component.is_symlink() or not component.is_file() or not 0 < component.stat().st_size <= MAX_FILE or digest(component) != checksum): raise ValueError('父清单组件摘要不匹配') if digest(destination / 'firecracker.tgz') != record['archive_sha256']: raise ValueError('VM归档摘要不符') parent['firecracker'] = record encoded = json.dumps(parent, ensure_ascii=False, sort_keys=True, indent=2).encode() + b'\n' if len(encoded) > 16 << 10: raise ValueError('合并后的父清单超过上限') with tempfile.NamedTemporaryFile(dir=path.parent, prefix='.vm-manifest-', delete=False) as output: temporary = Path(output.name) try: output.write(encoded) output.flush() os.fsync(output.fileno()) if path.read_bytes() != raw: raise ValueError('父清单在合并期间发生变化') os.chmod(temporary, 0o644) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True) fd = os.open(path.parent, os.O_RDONLY) try: os.fsync(fd) finally: os.close(fd) return parent def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--components', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--arch', choices=['amd64', 'arm64'], required=True) parser.add_argument('--manifest', type=Path, help='可选的同目录engine父清单,仅在发布前合并VM描述') args = parser.parse_args() record = package(args.components, args.output, args.arch) if args.manifest: attach_manifest(args.manifest, record, args.arch, args.output) if __name__ == '__main__': main()