infrastructure/tests/cycle-recovery.py
2026-11-21 12:20:59 +03:00

106 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""An interrupted worker is stopped before preflight; foreign units fail closed."""
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('cycle', Path(__file__).parents[1] / 'pipeline/release-cycle.py')
cycle = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cycle)
for foreign in (False, True):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
parent = root / 'data/private/release-cycle'
old_id = '20260101T000000Z'
old_dir = parent / old_id
old_dir.mkdir(parents=True)
unit = 'unrelated-workload' if foreign else 'archipelago-cycle-' + old_id + '-3'
old = dict(run=old_id, state='failed', error='Original timeout', worker_units=[unit])
for path in (old_dir / 'state.json', parent / 'latest.json'):
path.write_text(json.dumps(old))
config = root / 'config.json'
config.write_text(json.dumps(dict(coordinator_root=str(root), worker='worker', worker_root='/worker',
worker_source_root=str(root / 'source'))))
calls = []
def invoke(argv, **kwargs):
calls.append(argv)
if argv[0] == 'ssh' and 'systemd-run' in argv[-1]:
raise subprocess.CalledProcessError(1, argv)
# Keep failure artifacts rather than simulating successful archival.
return subprocess.CompletedProcess(argv, 1 if argv[0] == 'bash' else 0, stdout='', stderr='')
with patch.object(sys, 'argv', ['cycle', '--config', str(config)]), \
patch.object(cycle.subprocess, 'run', side_effect=invoke), \
patch.object(cycle.signal, 'signal'):
try:
cycle.main()
except (ValueError, subprocess.CalledProcessError):
pass
else:
raise AssertionError('Failed preflight must not succeed')
saved = json.loads((old_dir / 'state.json').read_text())
assert saved['error'] == 'Original timeout'
if foreign:
assert all('unrelated-workload' not in str(call) for call in calls)
else:
assert unit in calls[0][-1] and 'systemctl stop' in calls[0][-1]
assert 'systemd-run' in calls[1][-1]
assert 'worker_recovery_run' in saved
assert json.loads((parent / 'latest.json').read_text())['state'] == 'failed'
# A snapshot the artifact web server does not serve must stop the run before any
# build stage: the container can keep the mount view it started with and answer 404
# for a snapshot that is mounted on the host.
class Served:
def __init__(self, status):
self.status = status
def __enter__(self):
return self
def __exit__(self, *exc):
return False
url = 'https://example.invalid/archipelago/arch-repo-snapshot/2026-11-15/$repo/os/$arch'
with patch.object(cycle.urllib.request, 'urlopen', return_value=Served(200)) as opened:
cycle.verify_snapshot(url)
assert opened.call_args.args[0].full_url == \
'https://example.invalid/archipelago/arch-repo-snapshot/2026-11-15/core/os/x86_64/core.db'
with patch.object(cycle.urllib.request, 'urlopen', return_value=Served(404)), \
patch.object(cycle.time, 'sleep'):
try:
cycle.verify_snapshot(url)
except RuntimeError as error:
assert 'not served' in str(error) and 'core.db' in str(error)
else:
raise AssertionError('Unserved repository snapshot accepted')
# A portal request may pin a fresh build or ask to resume the last run, never both.
build = {'mode': 'ostree', 'snapshot': '2026-11-15', 'requested_at': 'stamp'}
assert cycle.resolve_request(build, 10, False) is build
assert cycle.resolve_request(build, 9 * 60 + 59, False) is build
assert cycle.resolve_request(build, 901, False) is None
assert cycle.resolve_request(build, None, False) is None
assert cycle.resolve_request(build, 10, True) is None
assert cycle.resolve_request({'mode': 'reboot', 'snapshot': '2026-11-15'}, 10, False) is None
assert cycle.resolve_request({'mode': 'iso', 'snapshot': 'latest'}, 10, False) is None
resume = {'resume': True, 'requested_at': 'stamp'}
assert cycle.resolve_request(resume, 10, False) is resume
assert cycle.resolve_request(resume, 901, False) is None
# A resume must not compose a Desktop image that links a plugin the workspace no
# longer has: the probe names the plugin and, for KDE, the Plasma setup package.
probe = cycle.adapter_probe('/work/20260101T000000Z', ['gnome'])
assert 'software-adapter/libgs_plugin_archipelago.so' in probe
assert 'discover-adapter' not in probe
kde_probe = cycle.adapter_probe('/work/20260101T000000Z', ['gnome', 'kde'])
assert 'discover-adapter' in kde_probe and 'plasma-setup-' in kde_probe
print('CYCLE_RECOVERY_ORDER_AND_OWNERSHIP_PASS')