379 lines
20 KiB
Python
379 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""Destructive only to a newly-created lab VM disk. New runs execute on terra."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import shlex
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
from datetime import datetime, timezone
|
|
|
|
import pexpect
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--iso", required=True, type=Path)
|
|
parser.add_argument("--workdir", default="/hdd/archipelago/vms", type=Path)
|
|
parser.add_argument("--provision-console", choices=["ttyS0", "tty1"], default="ttyS0")
|
|
parser.add_argument("--extensions-sequence", action="store_true")
|
|
parser.add_argument("--production-cli", action="store_true",
|
|
help="Test shipped CLI without lab-only overlay fixture; not full stable acceptance")
|
|
parser.add_argument("--dkms", action="store_true", help="Build and activate reviewed v4l2loopback DKMS extension")
|
|
parser.add_argument("--firmware", action="store_true", help="Require D-074 firmware in live and installed systems")
|
|
parser.add_argument("--ovmf-code", default="/usr/share/edk2/ovmf/OVMF_CODE.fd")
|
|
parser.add_argument("--ovmf-vars", default="/usr/share/edk2/ovmf/OVMF_VARS.fd")
|
|
parser.add_argument("--qemu", default="qemu-system-x86_64")
|
|
args = parser.parse_args()
|
|
run = Path(tempfile.mkdtemp(prefix="core-acceptance-", dir=args.workdir))
|
|
disk = run / "core.qcow2"
|
|
variables = run / "OVMF_VARS.fd"
|
|
shutil.copyfile(args.ovmf_vars, variables)
|
|
subprocess.run(["qemu-img", "create", "-f", "qcow2", str(disk), "20G"], check=True)
|
|
password = secrets.token_hex(18)
|
|
# Private retained credential allows diagnosis of a failed guest, never in logs.
|
|
fd = os.open(run / "credential", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(fd, "w") as stream:
|
|
stream.write(password)
|
|
results = {"iso": str(args.iso.resolve()), "run": str(run),
|
|
"provision_console": args.provision_console, "checks": []}
|
|
results['overlay_fixture_tested'] = not args.production_cli
|
|
def event(stage, **details):
|
|
record = {"time": datetime.now(timezone.utc).isoformat(), "stage": stage, **details}
|
|
with (run / "events.jsonl").open("a") as stream:
|
|
stream.write(json.dumps(record) + "\n")
|
|
print(json.dumps(record), flush=True)
|
|
|
|
event("started", run=str(run), iso=str(args.iso))
|
|
with args.iso.open("rb") as stream:
|
|
digest = hashlib.sha256()
|
|
for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b""):
|
|
digest.update(chunk)
|
|
results["iso_sha256"] = digest.hexdigest()
|
|
child = None
|
|
log = None
|
|
|
|
def boot(live):
|
|
nonlocal child, log
|
|
event("boot-live" if live else "boot-installed")
|
|
command = ["-machine", "q35,accel=kvm", "-cpu", "host", "-smp", "2",
|
|
"-m", "2048", "-display", "none", "-serial", "stdio", "-monitor", "none",
|
|
"-drive", f"if=pflash,format=raw,readonly=on,file={args.ovmf_code}",
|
|
"-drive", f"if=pflash,format=raw,file={variables}",
|
|
"-drive", f"if=virtio,format=qcow2,file={disk}",
|
|
"-nic", "user,model=virtio-net-pci"]
|
|
if live:
|
|
command += ["-cdrom", str(args.iso.resolve()), "-boot", "order=d"]
|
|
else:
|
|
command += ["-qmp", f"unix:{run}/qmp.sock,server=on,wait=off"]
|
|
log = (run / ("live.serial" if live else "installed.serial")).open("w")
|
|
child = pexpect.spawn(args.qemu, command, encoding="utf-8",
|
|
codec_errors="replace", timeout=300)
|
|
child.logfile_read = log
|
|
|
|
def command(text, privileged=False):
|
|
if privileged:
|
|
child.sendline("sudo -v")
|
|
index = child.expect([r"\[sudo\] password for coretest:", r"coretest@.*[\$] "])
|
|
if index == 0:
|
|
child.sendline(password)
|
|
child.expect(r"coretest@.*[\$] ")
|
|
guest_command = ("sudo " if privileged else "") + "/bin/bash -ec " + shlex.quote(text)
|
|
child.sendline(guest_command + "; printf '\\n__ARCHIPELAGO_RESULT=%s__\\n' \"$?\"")
|
|
child.expect(r"__ARCHIPELAGO_RESULT=(\d+)__", timeout=2400 if args.dkms else 600)
|
|
code = int(child.match.group(1))
|
|
results["checks"].append({"command": text, "exit_code": code})
|
|
event("command-result", command=text, exit_code=code)
|
|
if code:
|
|
# Preserve daemon diagnostics before the VM and disk are cleaned up.
|
|
# Use the authenticated CLI as root, just like the failed operation.
|
|
child.expect(r"(?:root|coretest)@[^\r\n]*[#$] ")
|
|
if privileged:
|
|
diagnostic = """archipelago transaction list --json; python3 - <<'PY'
|
|
import json, subprocess
|
|
p = subprocess.run(['archipelago', 'transaction', 'list', '--json'], capture_output=True, text=True)
|
|
if p.returncode == 0:
|
|
data = json.loads(p.stdout)
|
|
for record in data['transactions']:
|
|
identity = record.get('id') or record.get('Id')
|
|
if identity:
|
|
subprocess.run(['archipelago', 'transaction', 'log', identity], check=False)
|
|
PY
|
|
journalctl -u archipelagod.service -n 80 --no-pager
|
|
"""
|
|
try:
|
|
# Long operations can outlive sudo's credential timestamp.
|
|
child.sendline("sudo -v")
|
|
prompt = child.expect([r"\[sudo\] password for coretest:", r"coretest@.*[\$] "], timeout=30)
|
|
if prompt == 0:
|
|
child.sendline(password)
|
|
child.expect(r"coretest@.*[\$] ", timeout=30)
|
|
child.sendline("sudo /bin/bash -c " + shlex.quote(diagnostic) +
|
|
"; printf '\\n__ARCHIPELAGO_DIAGNOSTICS_DONE__\\n'")
|
|
child.expect(r"\r*\n__ARCHIPELAGO_DIAGNOSTICS_DONE__\r*\n", timeout=120)
|
|
except (pexpect.TIMEOUT, pexpect.EOF) as diagnostic_error:
|
|
event("diagnostics-incomplete", error=str(diagnostic_error))
|
|
raise RuntimeError(f"Guest command failed ({code}): {text}")
|
|
child.expect(r"(?:root|coretest)@[^\r\n]*[#$] ")
|
|
|
|
def login():
|
|
event("waiting-for-login")
|
|
child.expect("login:", timeout=300)
|
|
child.sendline("coretest")
|
|
child.expect("Password:")
|
|
child.sendline(password)
|
|
child.expect(r"coretest@.*[\$] ")
|
|
event("login-passed")
|
|
|
|
def reboot():
|
|
event("explicit-reboot")
|
|
# The local login session can request reboot through logind directly.
|
|
# Do not introduce a sudo password prompt after lengthy composition.
|
|
child.sendline("systemctl reboot")
|
|
login()
|
|
|
|
def keyboard_setup(login_only=False):
|
|
# Real emulated keyboard input on the VGA console, never a guest shell
|
|
# backdoor. Credentials are not included in the QMP/event logs.
|
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
|
connection.settimeout(10)
|
|
connection.connect(str(run / "qmp.sock"))
|
|
with connection.makefile("rwb") as stream:
|
|
json.loads(stream.readline())
|
|
|
|
def qmp(method, arguments=None):
|
|
stream.write((json.dumps({"execute": method, "arguments": arguments or {}}) + "\n").encode())
|
|
stream.flush()
|
|
while True:
|
|
response = json.loads(stream.readline())
|
|
if "error" in response:
|
|
raise RuntimeError(f"QMP {method} failed")
|
|
if "return" in response:
|
|
return response["return"]
|
|
|
|
def keys(*codes):
|
|
qmp("send-key", {"keys": [{"type": "qcode", "data": code} for code in codes],
|
|
"hold-time": 50})
|
|
time.sleep(0.08)
|
|
|
|
def line(text):
|
|
for character in text:
|
|
keys(character)
|
|
keys("ret")
|
|
time.sleep(1)
|
|
|
|
def screen_prompt(expected):
|
|
deadline = time.monotonic() + 90
|
|
while time.monotonic() < deadline:
|
|
image = run / "tty1-current.ppm"
|
|
qmp("screendump", {"filename": str(image)})
|
|
# Tiny light-on-dark console glyphs need inversion and
|
|
# nearest-neighbour scaling for reliable prompt OCR.
|
|
with image.open("rb") as source:
|
|
assert source.readline().strip() == b"P6"
|
|
width, height = map(int, source.readline().split())
|
|
assert source.readline().strip() == b"255"
|
|
gray = source.read()[::3].translate(bytes(reversed(range(256))))
|
|
rows = [b"".join(bytes([pixel]) * 3 for pixel in gray[y*width:(y+1)*width])
|
|
for y in range(height)]
|
|
scaled = image.with_suffix(".pgm")
|
|
scaled.write_bytes(f"P5\n{width*3} {height*3}\n255\n".encode()
|
|
+ b"".join(row * 3 for row in rows))
|
|
text = subprocess.run(["tesseract", str(scaled), "stdout", "--psm", "6"],
|
|
capture_output=True, text=True, check=True).stdout
|
|
lines = [line.strip().lower().replace("passuord", "password")
|
|
.replace("usernane", "username")
|
|
for line in text.splitlines() if line.strip()]
|
|
if lines and expected in lines[-1]:
|
|
return
|
|
time.sleep(0.5)
|
|
raise RuntimeError(f"VGA console did not reach prompt: {expected}")
|
|
|
|
qmp("qmp_capabilities")
|
|
keys("ctrl", "alt", "f1")
|
|
time.sleep(2)
|
|
if login_only:
|
|
screen_prompt("login:")
|
|
line("coretest")
|
|
screen_prompt("password:")
|
|
line(password)
|
|
return
|
|
qmp("screendump", {"filename": str(run / "tty1-before.ppm")})
|
|
screen_prompt("press enter")
|
|
line("")
|
|
screen_prompt("username:")
|
|
# Compete on serial after tty1 owns the lock: it must wait.
|
|
child.sendline("")
|
|
child.expect("Setup is active on another console", timeout=30)
|
|
event("second-console-blocked")
|
|
line("coretest")
|
|
screen_prompt("new password:")
|
|
line(password)
|
|
screen_prompt("retype new password:")
|
|
line(password)
|
|
|
|
try:
|
|
boot(True)
|
|
child.expect(r"root@.*[#] ", timeout=300)
|
|
event("live-shell-ready")
|
|
command("archipelago self-check")
|
|
if args.firmware:
|
|
command("pacman -Q linux-firmware; test -n \"$(find /usr/lib/firmware -type f -print -quit)\"")
|
|
command("cp /usr/bin/archipelago /run/archipelago-check; "
|
|
"trap 'chmod 0755 /usr/bin/archipelago; rm -f /run/archipelago-check' EXIT; "
|
|
"chmod 0644 /usr/bin/archipelago; "
|
|
"if /run/archipelago-check self-check; then exit 1; fi; "
|
|
"chmod 0755 /usr/bin/archipelago; archipelago self-check")
|
|
command("test -e /run/archipelago-live; archipelago install /dev/vda --erase")
|
|
event("installation-passed")
|
|
child.sendline("systemctl poweroff")
|
|
# systemd may spend its default 90s stopping a service. Allow that grace
|
|
# period plus shutdown work; require actual QEMU exit, never force-pass.
|
|
child.expect(pexpect.EOF, timeout=180)
|
|
child.close()
|
|
log.close()
|
|
boot(False)
|
|
child.expect("Press Enter to begin Core setup on this console.", timeout=300)
|
|
event("provisioning", console=args.provision_console)
|
|
if args.provision_console == "tty1":
|
|
keyboard_setup()
|
|
else:
|
|
child.sendline("")
|
|
child.expect("Username:", timeout=300)
|
|
child.sendline("coretest")
|
|
child.expect("New password:")
|
|
child.sendline(password)
|
|
child.expect("Retype new password:")
|
|
child.sendline(password)
|
|
child.expect("ARCHIPELAGO_PROVISION_COMPLETE")
|
|
event("provisioning-passed")
|
|
login()
|
|
command("test -e /run/ostree-booted; id; test -d /var/home/coretest")
|
|
command("archipelago self-check", True)
|
|
if args.firmware:
|
|
command("pacman -Q linux-firmware; test -n \"$(find /usr/lib/firmware -type f -print -quit)\"", True)
|
|
command(f"test \"$(cat /etc/archipelago/provision-console)\" = /dev/{args.provision_console}; "
|
|
"systemctl is-active getty@tty1 serial-getty@ttyS0; "
|
|
"test \"$(getent passwd coretest | wc -l)\" = 1", True)
|
|
if args.provision_console == "tty1":
|
|
keyboard_setup(login_only=True)
|
|
command("who | grep -E '^coretest +tty1 '")
|
|
event("tty1-login-passed")
|
|
command("archipelago status; systemctl is-active systemd-networkd systemd-resolved sshd; "
|
|
"findmnt -n -o OPTIONS /usr | grep -w ro; ! touch /usr/.write-test", True)
|
|
marker_check = "grep 'Archipelago managed overlay test' /usr/share/archipelago/test-marker"
|
|
if args.production_cli:
|
|
marker_check = 'true'
|
|
event('lab-overlay-fixture-not-applicable', full_stable_acceptance=False)
|
|
else:
|
|
command("archipelago overlay apply test-marker; test ! -e /usr/share/archipelago/test-marker", True)
|
|
reboot()
|
|
command(marker_check)
|
|
command("archipelago self-check", True)
|
|
if args.production_cli:
|
|
cli_contract = Path(__file__).with_name('cli_contract_guest.py').read_text()
|
|
command("python3 -c " + shlex.quote(cli_contract) + " prepare", True)
|
|
command("archipelago extension enable; archipelago extension add nano; ! command -v nano", True)
|
|
if args.extensions_sequence:
|
|
command("archipelago extension add mc htop; ! command -v mc; ! command -v htop", True)
|
|
command("ostree admin status --json > /run/pending-before; "
|
|
"archipelago extension add nano mc; "
|
|
"ostree admin status --json > /run/pending-after; "
|
|
"cmp /run/pending-before /run/pending-after", True)
|
|
command("if archipelago extension add archipelago-nonexistent-package; then exit 1; fi; "
|
|
"ostree admin status --json > /run/pending-after; "
|
|
"cmp /run/pending-before /run/pending-after; archipelago status", True)
|
|
reboot()
|
|
command("nano --version; " + marker_check)
|
|
if args.production_cli:
|
|
command("python3 -c " + shlex.quote(cli_contract) + " verify", True)
|
|
command("archipelago self-check", True)
|
|
command("archipelago status; pacman -Q nano; systemctl is-active systemd-networkd systemd-resolved sshd", True)
|
|
if args.extensions_sequence:
|
|
command("mc --version; htop --version; pacman -Q gpm slang pcre")
|
|
if args.production_cli:
|
|
requested_check = (
|
|
"import json; d=json.load(open('/usr/lib/archipelago/extensions.json')); "
|
|
"assert d['version']==3; "
|
|
"assert sorted(d['requested'])==['htop','mc','nano'], d['requested']; "
|
|
"assert sorted(r['name'] for r in d['requests'])==sorted(d['requested'])"
|
|
)
|
|
command("python3 -c " + shlex.quote(requested_check))
|
|
else:
|
|
command("! grep -qx gpm /usr/lib/archipelago/host-extensions")
|
|
command("archipelago extension add tree; ! command -v tree", True)
|
|
reboot()
|
|
command("tree --version; mc --version; htop --version; nano --version; " + marker_check)
|
|
command("archipelago self-check; archipelago status", True)
|
|
if args.production_cli:
|
|
requested_check = (
|
|
"import json; d=json.load(open('/usr/lib/archipelago/extensions.json')); "
|
|
"assert d['version']==3; "
|
|
"assert sorted(d['requested'])==['htop','mc','nano','tree'], d['requested']; "
|
|
"assert sorted(r['name'] for r in d['requests'])==sorted(d['requested'])"
|
|
)
|
|
command("python3 -c " + shlex.quote(requested_check))
|
|
# The daemon owns durable history. An unknown catalog name is
|
|
# rejected before staging (deployment invariance checked above),
|
|
# so it must not require a legacy filesystem failure marker.
|
|
history_check = (
|
|
"import json,sys; d=json.load(sys.stdin); "
|
|
"assert not d['next_cursor'], 'Incomplete transaction history'; "
|
|
"stages=[r for r in d['transactions'] if r['Kind']=='stage']; "
|
|
"assert all(r['State']=='succeeded' for r in stages), stages; "
|
|
"outcomes=[r['Result'].get('outcome') for r in stages]; "
|
|
"assert outcomes.count('staged')==3, outcomes; "
|
|
"assert outcomes.count('no-change')==1, outcomes"
|
|
)
|
|
command("archipelago transaction list --json | python3 -c " + shlex.quote(history_check), True)
|
|
else:
|
|
command("test \"$(wc -l < /usr/lib/archipelago/host-extensions)\" = 4; "
|
|
"test \"$(find /var/lib/archipelago/host-extensions/generations -name staged | wc -l)\" = 3; "
|
|
"test \"$(find /var/lib/archipelago/host-extensions/generations -name failure | wc -l)\" = 1", True)
|
|
if args.dkms:
|
|
command("archipelago extension add v4l2loopback-dkms; "
|
|
"! modinfo v4l2loopback; ! test -e /dev/video0", True)
|
|
command("ostree admin status --json > /run/dkms-pending; "
|
|
"archipelago extension add v4l2loopback-dkms; "
|
|
"ostree admin status --json > /run/dkms-pending-after; "
|
|
"cmp /run/dkms-pending /run/dkms-pending-after; "
|
|
"if archipelago extension add archipelago-nonexistent-dkms; then exit 1; fi; "
|
|
"ostree admin status --json > /run/dkms-pending-after; "
|
|
"cmp /run/dkms-pending /run/dkms-pending-after", True)
|
|
reboot()
|
|
command("archipelago self-check; "
|
|
"test \"$(modinfo -F vermagic v4l2loopback | cut -d' ' -f1)\" = \"$(uname -r)\"; "
|
|
"modprobe v4l2loopback; test -c /dev/video0; "
|
|
"grep '^v4l2loopback ' /proc/modules; modprobe -r v4l2loopback; "
|
|
"test -s /usr/lib/archipelago/dkms-modules.tsv; "
|
|
"! grep -q -- '-headers' /usr/lib/archipelago/host-extensions; "
|
|
"test ! -d /var/lib/dkms/v4l2loopback; nano --version", True)
|
|
command("archipelago extension add strace; ! command -v strace", True)
|
|
reboot()
|
|
command("strace --version; modprobe v4l2loopback; test -c /dev/video0; "
|
|
"modprobe -r v4l2loopback; archipelago self-check; archipelago status", True)
|
|
child.sendline("systemctl poweroff")
|
|
child.expect(pexpect.EOF, timeout=180)
|
|
results["passed"] = True
|
|
event("acceptance-passed")
|
|
except Exception as error:
|
|
results.update(passed=False, error=str(error))
|
|
event("acceptance-failed", error=str(error))
|
|
finally:
|
|
if child is not None and child.isalive():
|
|
child.terminate(force=True)
|
|
if log is not None:
|
|
log.close()
|
|
(run / "summary.json").write_text(json.dumps(results, indent=2) + "\n")
|
|
print(json.dumps(results, indent=2))
|
|
return 0 if results.get("passed") else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|