test-lab/probes/gnome_native_acceptance.py

296 lines
16 KiB
Python

#!/usr/bin/env python3
"""Deterministic native-GIS fixture creation. No LLM, OCR or operator prompts.
Coordinates bind the reviewed 1280x800 GNOME profile. UI drift/timeout fails the
run; screenshots are diagnostics, never an implicit acceptance decision.
"""
import argparse
import json
import os
from pathlib import Path
import pexpect
import secrets
import re
import shlex
import subprocess
import time
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--iso', type=Path, required=True)
p.add_argument('--workdir', type=Path, required=True)
p.add_argument('--ovmf-code', required=True)
p.add_argument('--ovmf-vars', required=True)
p.add_argument('--ssh-port', type=int, default=22296)
p.add_argument('--unit', default='archipelago-native-gnome-vm')
p.add_argument('--variant', choices=('gnome', 'kde'), default='gnome')
p.add_argument('--ui-actions', type=Path, help='Reviewed KDE QMP action list for the selected package/input profile')
p.add_argument('--calibrate-ui', action='store_true', help='First-image calibration: await real native onboarding; never bypass account/session checks')
p.add_argument('--rtc-base')
p.add_argument('--require-time-sync', action='store_true')
args = p.parse_args()
scripts = Path(__file__).resolve().parent
args.workdir.mkdir(parents=True, exist_ok=True)
result = {'passed': False, 'scope': 'native-' + args.variant + '-and-extension-baseline'}
vm = None
try:
with (args.workdir / 'prepare.log').open('w') as log:
subprocess.run(['python3', str(scripts / 'gnome_vm_prepare.py'), '--iso', str(args.iso),
'--workdir', str(args.workdir), '--vm-unit', args.unit, '--ovmf-code', args.ovmf_code,
'--ovmf-vars', args.ovmf_vars, '--variant', args.variant] + (['--rtc-base', args.rtc_base] if args.rtc_base else []),
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=1800)
prepared = list(args.workdir.glob(args.variant + '-*/preparation.json'))
if len(prepared) != 1: raise RuntimeError('Ambiguous VM preparation')
vm = prepared[0].parent
result.update(vm=str(vm), ssh_port=args.ssh_port,
iso_sha256=json.loads(prepared[0].read_text())['iso_sha256'])
subprocess.run(['python3', str(scripts / 'qmp_command.py'), str(vm / 'qmp.sock'),
'human-monitor-command', json.dumps({'command-line': f'hostfwd_add tcp:127.0.0.1:{args.ssh_port}-:22'})], check=True)
password = secrets.token_hex(18)
with os.fdopen(os.open(vm / 'credential', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as f:
f.write(password)
def ui(label, *commands):
subprocess.run(['python3', str(scripts / 'gnome_vm_input.py'), str(vm), *commands,
'--screen', label + '.png'], check=True)
time.sleep(10)
time.sleep(30)
def check_zram():
guest('''set -e
systemctl is-active systemd-zram-setup@zram0.service dev-zram0.swap
grep -qx '\\[zram0\\]' /usr/lib/systemd/zram-generator.conf.d/20-archipelago-desktop.conf
swapon --show=NAME --noheadings | grep -qx /dev/zram0
test "$(cat /sys/block/zram0/disksize)" -gt 0
zramctl /dev/zram0
cat /sys/block/zram0/comp_algorithm
''')
if args.variant == 'kde':
ui('00-plasma-setup')
if not args.ui_actions and not args.calibrate_ui:
raise RuntimeError('KDE UI action profile is required; initial Plasma Setup screenshot retained for calibration')
if args.ui_actions:
import hashlib
actions = json.loads(args.ui_actions.read_text())
if actions.get('version') != 1 or actions.get('variant') != 'kde':
raise RuntimeError('Unsupported KDE UI action profile')
result['ui_actions_sha256'] = hashlib.sha256(args.ui_actions.read_bytes()).hexdigest()
result['ui_mode'] = 'frozen-actions'
for index, action in enumerate(actions['actions']):
command = list(action)
command = [str(vm / 'credential') if part == '@credential@' else part for part in command]
ui(f'kde-{index:02d}', *command)
if args.calibrate_ui:
result['ui_mode'] = 'manual-calibration'
print('Awaiting native Plasma Setup and SDDM login for coretest; VM: ' + str(vm), flush=True)
else:
ui('01-language', '--click', '500', '388')
ui('02-typing', '--click', '1095', '55')
# Explicitly choose English (US) in the native XKB selector.
ui('02a-layouts', '--click', '640', '383')
ui('02b-us-search', '--click', '500', '330', '--text', 'english us')
ui('02c-us-selected', '--click', '500', '478')
ui('03-privacy', '--click', '1095', '55')
ui('04-timezone', '--click', '1095', '55')
ui('05-city', '--click', '500', '326', '--text', 'moscow')
ui('06-city-selected', '--click', '500', '362')
ui('07-account', '--click', '1095', '55')
ui('08-name', '--text', 'coretest')
ui('09-password', '--click', '1095', '55')
ui('10-password-entered', '--text-file', str(vm / 'credential'))
ui('11-confirmed', '--click', '550', '492', '--text-file', str(vm / 'credential'))
ui('12-complete', '--click', '1095', '55')
ui('13-session', '--click', '640', '572')
def guest(script, timeout=300, disconnect=False):
c = pexpect.spawn('ssh', ['-tt', '-o', 'ConnectTimeout=5', '-o', 'StrictHostKeyChecking=accept-new', '-o',
'UserKnownHostsFile=' + str(vm / 'known_hosts'), '-p', str(args.ssh_port),
'coretest@127.0.0.1', 'sudo -p SUDO_AUTH: bash -ec ' + shlex.quote(script)], encoding='utf-8', timeout=timeout)
try:
c.expect('[Pp]assword:', timeout=15); c.sendline(password)
auth = c.expect(['SUDO_AUTH:', 'Permission denied', '[Pp]assword:'], timeout=15)
if auth != 0: raise RuntimeError('Native account authentication rejected')
c.sendline(password)
with (args.workdir / 'guest.log').open('a') as log:
c.logfile_read = log; c.expect(pexpect.EOF)
text = c.before
c.close()
if c.exitstatus != 0 and not (disconnect and c.exitstatus == 255):
raise RuntimeError('Guest check failed: ' + str(c.exitstatus))
return text
finally:
if c.isalive(): c.close(force=True)
onboarding_timeout = 1800 if args.variant == 'kde' and args.calibrate_ui else 180
deadline = time.monotonic() + onboarding_timeout
while time.monotonic() < deadline:
try:
guest('true', timeout=15)
break
except (pexpect.ExceptionPexpect, RuntimeError):
time.sleep(3)
else:
raise RuntimeError(f'Native onboarding did not provide authenticated SSH/sudo within {onboarding_timeout} seconds')
check_zram()
result['zram'] = {'active_after_install': True, 'configuration': 'generator-defaults'}
if args.require_time_sync:
guest('''set -e
systemctl is-enabled systemd-timesyncd.service
systemctl is-active systemd-timesyncd.service
timeout 180 bash -c 'until [ "$(timedatectl show -p NTPSynchronized --value)" = yes ]; do sleep 3; done'
timeout 90 bash -c 'until systemctl is-active --quiet archipelago-keyring.service; do sleep 3; done'
''', timeout=290)
result['clock_regression'] = {'rtc_base': args.rtc_base, 'synchronized': True}
if args.variant == 'kde':
guest('''set -e
test -f /etc/plasma-setup-done
test "$(cat /usr/lib/archipelago/purpose)" = purpose/desktop/kde
systemctl is-active sddm NetworkManager
test -f /usr/lib/qt6/plugins/discover/archipelago-backend.so
pacman --config /dev/null --dbpath /usr/lib/archipelago/package-db -Q sddm-kcm
pacman --config /dev/null --dbpath /usr/lib/archipelago/package-db -Q kinfocenter
! ldd /usr/lib/qt6/plugins/discover/archipelago-backend.so | grep 'not found'
''')
provisioning_timeout = 1800 if args.variant == 'kde' and args.calibrate_ui else 180
guest('set -e\ntimeout ' + str(provisioning_timeout) + ''' sh -c 'until test -f /etc/archipelago/provisioned; do sleep 2; done'
test "$(cat /etc/archipelago/provisioned)" = coretest
archipelago self-check
pacman --config /dev/null --dbpath /usr/lib/archipelago/package-db -Qq > /run/desktop-package-names.txt
if grep -Ei '^(packagekit($|-)|libpackagekit)' /run/desktop-package-names.txt; then
echo 'D-095: unexpected PackageKit dependency' >&2
exit 1
fi
archipelago status --json
systemctl is-active archipelagod.service
systemctl is-active display-manager NetworkManager ostree-finalize-staged.service
runuser -u coretest -- sh -c 'echo "clean dropin candidate" > /var/home/coretest/.archipelago-clean-persistence'
archipelago extension enable
''', timeout=provisioning_timeout + 1800)
cli_contract = Path(__file__).with_name('cli_contract_guest.py').read_text()
guest('python3 -c ' + shlex.quote(cli_contract) + ' prepare', timeout=1800)
guest('archipelago extension add nano', timeout=1800)
wayland = '''until loginctl list-sessions --no-legend | awk '$3=="coretest" {print $1}' | xargs -r -n1 loginctl show-session -p Type --value | grep -qx wayland; do sleep 3; done'''
guest('timeout 120 bash -c ' + shlex.quote(wayland), timeout=150)
if args.variant == 'kde':
startup_qml = Path(__file__).with_name('discover_startup.qml').read_text()
guest('printf %s ' + shlex.quote(startup_qml) + ' > /var/tmp/archipelago-discover-startup.qml')
guest('''set -e
uid=$(id -u coretest)
probe=$(mktemp -d /var/tmp/archipelago-discover.XXXXXX)
trap 'rm -rf "$probe"; rm -f /var/tmp/archipelago-discover-startup.qml' EXIT
chmod 755 "$probe"
mkdir "$probe/discover"
ln -s /usr/lib/qt6/plugins/discover/archipelago-backend.so "$probe/discover/dummy-backend.so"
runuser -u coretest -- env XDG_RUNTIME_DIR=/run/user/$uid DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus \
systemd-run --user --wait --pipe --collect --unit=archipelago-discover-acceptance --property=RuntimeMaxSec=80 \
env QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME=generic QT_FORCE_STDERR_LOGGING=1 QT_PLUGIN_PATH="$probe" \
dbus-run-session -- plasma-discover --test /var/tmp/archipelago-discover-startup.qml > /var/tmp/archipelago-discover-startup.log 2>&1
cat /var/tmp/archipelago-discover-startup.log
grep -q ARCHIPELAGO_DISCOVER_READY /var/tmp/archipelago-discover-startup.log
! grep -E 'ARCHIPELAGO_DISCOVER_ERROR|ARCHIPELAGO_DISCOVER_TIMEOUT' /var/tmp/archipelago-discover-startup.log
''', timeout=100)
result['discover_startup'] = {'native_backend': True, 'refresh_completed': True, 'manual_refresh': False}
guest('''set -e
uid=$(id -u coretest)
runuser -u coretest -- env XDG_RUNTIME_DIR=/run/user/$uid toolbox list
runuser -u coretest -- env XDG_RUNTIME_DIR=/run/user/$uid toolbox create --assumeyes
python3 - <<'PY'
import json, pwd, subprocess, tomllib
with open('/etc/containers/toolbox.conf', 'rb') as stream:
image_ref = tomllib.load(stream)['general']['image']
uid = pwd.getpwnam('coretest').pw_uid
image = json.loads(subprocess.check_output(['runuser', '-u', 'coretest', '--', 'env',
f'XDG_RUNTIME_DIR=/run/user/{uid}', 'podman', 'image', 'inspect', image_ref], text=True))[0]
assert any(d.startswith('quay.io/toolbx/arch-toolbox@sha256:') for d in image['RepoDigests']), 'Toolbx default did not resolve to the upstream Arch image'
PY
runuser -u coretest -- env XDG_RUNTIME_DIR=/run/user/$uid toolbox run sh -ec 'test "$(id -u)" != 0; test -w "$HOME"; . /etc/os-release; test "$ID" = arch; printf "toolbox-persistence\\n" > "$HOME/.archipelago-toolbox-persistence"'
''', timeout=1800)
result['toolbox'] = {'created_and_entered': True, 'upstream_unpatched': True}
def boot_id():
text = guest('printf "BOOT_ID="; cat /proc/sys/kernel/random/boot_id', timeout=15)
match = re.search(r'BOOT_ID=([0-9a-f-]{36})', text)
if not match: raise RuntimeError('Missing guest boot identity')
return match.group(1)
old_boot = boot_id()
guest('systemctl reboot', disconnect=True)
deadline = time.monotonic() + 360
while time.monotonic() < deadline:
try:
new_boot = boot_id()
if new_boot != old_boot:
break
except (pexpect.ExceptionPexpect, RuntimeError):
pass
time.sleep(3)
else:
raise RuntimeError('Guest did not complete reboot within 360 seconds')
check_zram()
result['zram']['active_after_extension_reboot'] = True
guest('python3 -c ' + shlex.quote(cli_contract) + ' verify', timeout=180)
result['cli_contract'] = {'human': True, 'json': True, 'debug_json': True, 'kernel_arguments_activated': True}
guest('''set -e
uid=$(id -u coretest)
runuser -u coretest -- env XDG_RUNTIME_DIR=/run/user/$uid toolbox run sh -ec 'grep -qx toolbox-persistence "$HOME/.archipelago-toolbox-persistence"; test "$(id -u)" != 0'
''', timeout=180)
result['toolbox']['survived_deployment_change'] = True
guest('''set -e
pacman-conf --repo-list | grep -qx multilib
test -s /usr/lib/archipelago/package-db/sync/multilib.db
pacman --config /dev/null --dbpath /usr/lib/archipelago/package-db -Q lib32-glibc lib32-gcc-libs lib32-mesa lib32-libglvnd lib32-vulkan-icd-loader lib32-vulkan-intel lib32-vulkan-radeon lib32-alsa-lib lib32-alsa-plugins lib32-libpulse lib32-pipewire lib32-libx11 lib32-libxcomposite lib32-libxrandr lib32-fontconfig lib32-nss lib32-gtk3
flatpak install --system --noninteractive flathub com.valvesoftware.Steam
python3 - <<'PY'
import configparser, pwd, subprocess
def output(*args):
return subprocess.check_output(args, text=True).strip()
app = 'com.valvesoftware.Steam'
runtime = output('flatpak', 'info', '--system', '--show-runtime', app)
assert runtime.startswith('org.freedesktop.Platform/x86_64/'), runtime
branch = runtime.rsplit('/', 1)[1]
# Use the installed stable application's branch, never upstream master's branch.
output('flatpak', 'info', '--system', 'org.freedesktop.Platform.Compat.i386/x86_64/' + branch)
uid = pwd.getpwnam('coretest').pw_uid
info = output('runuser', '-u', 'coretest', '--', 'env', f'XDG_RUNTIME_DIR=/run/user/{uid}',
'flatpak', 'run', '--command=sh', app, '-ec',
'test -e /lib/ld-linux.so.2; /lib/ld-linux.so.2 --verify /lib/i386-linux-gnu/libc.so.6; cat /.flatpak-info')
metadata = configparser.ConfigParser(interpolation=None)
metadata.read_string(info)
extensions = ';'.join(metadata.get('Instance', key, fallback='')
for key in ('runtime-extensions', 'app-extensions'))
assert 'org.freedesktop.Platform.GL32.' in extensions, extensions
assert 'org.freedesktop.Platform.Compat.i386' in extensions, extensions
print('Verified Steam runtime:', runtime, extensions)
PY
''', timeout=1800)
result['steam_flatpak'] = {'stable_runtime_and_i386_loader': True, 'gl32_mounted': True}
guest('''set -e
nano --version
archipelago self-check
python3 - <<'PY'
import json, subprocess
policy = json.load(open('/usr/share/archipelago/desktop/flatpak-apps.json'))
assert policy['delivery'] == 'installation-media'
for ref in policy['applications']:
subprocess.run(['flatpak', 'info', '--system', ref], check=True)
runtime = subprocess.check_output(['flatpak', 'info', '--system', '--show-runtime', ref], text=True).strip()
subprocess.run(['flatpak', 'info', '--system', runtime], check=True)
PY
''', timeout=960)
result['passed'] = True
except BaseException as error:
result['error'] = str(error)
if vm is not None:
try:
ui('failure-screen')
except Exception:
pass
if 'guest' in locals():
try:
guest('loginctl list-sessions; loginctl list-sessions --no-legend | awk \'{print $1}\' | xargs -r -n1 loginctl show-session; journalctl -b -u archipelago-kde-onboarding.service -u sddm --no-pager -n 100', timeout=30)
except Exception:
pass
raise
finally:
(args.workdir / 'native-acceptance.json').write_text(json.dumps(result, indent=2) + '\n')
if not result['passed'] and vm is not None:
subprocess.run(['python3', str(scripts / 'qmp_command.py'), str(vm / 'qmp.sock'),
'system_powerdown'], check=False, timeout=20)
for _ in range(30):
if subprocess.run(['systemctl', 'is-active', '--quiet', args.unit]).returncode:
break
time.sleep(2)
subprocess.run(['systemctl', 'stop', args.unit], check=False, timeout=90)