Files
leleka/scripts/smoke-service-unit.py
T
Pavlo Ratushnyi 2d53a04824 Native per-user Linux service installation (#14)
* feat: install native runtime as a per-user Linux service

* fix: verify effective systemd unit before native start
2026-10-05 00:10:34 +02:00

168 lines
8.6 KiB
Python

#!/usr/bin/env python3
"""Check native unit syntax; optionally exercise an isolated CPU-only user service.
Requires Linux/systemd. --lifecycle needs a running user manager. It never
enables the unit or touches an existing inference service.
"""
import argparse
import json
import os
from pathlib import Path
import shutil
import socket
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
def run(*args, check=True, env=None):
return subprocess.run(args, check=check, text=True, capture_output=True, timeout=60, env=env)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('binary', type=Path)
parser.add_argument('--lifecycle', action='store_true')
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='strata-next-install-') as directory:
root = Path(directory)
# Exercise literal $, systemd % specifiers, quoting and C escaping.
odd = root / 'space %n ${HOME} "quote" back\\slash'
odd.mkdir()
binary = root / 'strata-next %n ${HOME}'
shutil.copy2(args.binary.resolve(), binary)
config = odd / 'config.json'
env_file = root / 'runtime %n ${HOME} "quote".env'
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'service-smoke'}))
env_file.write_text('STRATA_CONFIG=/definitely-missing-service-smoke.json\n'
'STRATA_MODEL_ID=service-smoke-env\n')
unit_name = root.name + '.service'
unit = root / unit_name
generated = run(str(binary), 'service-unit', '--config', str(config),
'--working-dir', str(odd), '--env-file', str(env_file)).stdout
unit.write_text(generated)
verify = run('systemd-analyze', '--user', 'verify', str(unit), check=False)
assert verify.returncode == 0, verify.stderr
# The renderer must fail closed, before printing any installable unit.
bad = run(str(binary), 'service-unit', '--config', 'relative.json',
'--working-dir', str(odd), check=False)
assert bad.returncode != 0 and not bad.stdout
pattern_env = root / 'runtime[1].env'
pattern_env.write_text('')
bad = run(str(binary), 'service-unit', '--config', str(config),
'--working-dir', str(odd), '--env-file', str(pattern_env), check=False)
assert bad.returncode != 0 and not bad.stdout
# Offline fault: the unit survives a failed manager command for retry.
fake_bin = root / 'fake-bin'
fake_bin.mkdir()
fake_ctl = fake_bin / 'systemctl'
fake_ctl.write_text('#!/bin/sh\nexit 42\n')
fake_ctl.chmod(0o700)
fault_home = root / 'fault-config'
fault_env = dict(os.environ, XDG_CONFIG_HOME=str(fault_home),
PATH=str(fake_bin) + os.pathsep + os.environ['PATH'])
fault_args = (str(binary), 'service-install', '--config', str(config),
'--working-dir', str(odd), '--unit', unit_name)
failed = run(*fault_args, check=False, env=fault_env)
assert failed.returncode != 0 and 'daemon-reload' in failed.stderr and 'unit retained' in failed.stderr
fault_unit = fault_home / 'systemd/user' / unit_name
retained = fault_unit.read_bytes()
fault_inode = fault_unit.stat().st_ino
fake_ctl.write_text('#!/bin/sh\nexit 0\n')
reused = json.loads(run(*fault_args, env=fault_env).stdout)
assert reused['reused'] and fault_unit.stat().st_ino == fault_inode
fault_unit.unlink()
fault_unit.symlink_to(root / 'absent-unit')
assert run(*fault_args, env=fault_env, check=False).returncode != 0
assert fault_unit.is_symlink() and not (root / 'absent-unit').exists()
fault_unit.unlink()
fault_unit.write_bytes(retained)
fault_unit.chmod(0o600)
fake_ctl.write_text(f"""#!/bin/sh
if [ "$3" = show ]; then
echo "FragmentPath=$XDG_CONFIG_HOME/systemd/user/{unit_name}"
echo "DropInPaths="
fi
[ "$3" = start ] && exit 42
exit 0
""")
failed = run(*fault_args, '--start', env=fault_env, check=False)
assert failed.returncode != 0 and 'systemctl --user start' in failed.stderr
assert fault_unit.read_bytes() == retained
fake_ctl.write_text('#!/bin/sh\necho FragmentPath=/different.service\necho DropInPaths=\n')
failed = run(*fault_args, '--start', env=fault_env, check=False)
assert failed.returncode != 0 and 'start was not requested' in failed.stderr
assert fault_unit.read_bytes() == retained
if not args.lifecycle:
print('Native systemd unit syntax and rejected-path checks passed')
return
def ctl(*commands, check=True):
return run('systemctl', '--user', *commands, check=check)
link = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) / 'systemd/user' / unit_name
assert not link.exists() and not link.is_symlink(), 'refusing to replace a user unit'
try:
install_args = (str(binary), 'service-install', '--config', str(config),
'--working-dir', str(odd), '--env-file', str(env_file),
'--unit', unit_name)
installed = json.loads(run(*install_args, '--start').stdout)
assert installed['created'] and not installed['reused'], installed
assert installed['model_readiness'] == 'not_checked', installed
assert link.read_text() == generated and link.stat().st_mode & 0o777 == 0o600
inode = link.stat().st_ino
original_pid = ctl('show', '--property=MainPID', '--value', unit_name).stdout.strip()
repeated = json.loads(run(*install_args, '--start').stdout)
assert ctl('show', '--property=MainPID', '--value', unit_name).stdout.strip() == original_pid
assert repeated['reused'] and not repeated['created'], repeated
assert link.stat().st_ino == inode
# A different config path must not replace the active service unit.
other = odd / 'other-config.json'
other.write_text(config.read_text())
bad = run(str(binary), 'service-install', '--config', str(other),
'--working-dir', str(odd), '--unit', unit_name, '--start', check=False)
assert bad.returncode != 0 and not bad.stdout
assert link.read_text() == generated and link.stat().st_ino == inode
deadline = time.monotonic() + 15
while True:
try:
with urllib.request.urlopen(f'http://127.0.0.1:{port}/status', timeout=1) as response:
state = json.load(response)
break
except (OSError, urllib.error.URLError):
assert time.monotonic() < deadline, 'isolated service failed to listen'
time.sleep(0.05)
assert state['model'] == 'service-smoke-env', state
assert state['worker'] == 'unconfigured' and not state['ready'], state
with urllib.request.urlopen(f'http://127.0.0.1:{port}/health', timeout=1) as response:
assert response.status == 200
try:
urllib.request.urlopen(f'http://127.0.0.1:{port}/ready', timeout=1)
raise AssertionError('no-worker service must not claim inference readiness')
except urllib.error.HTTPError as error:
assert error.code == 503
error.close()
pid = int(ctl('show', '--property=MainPID', '--value', unit_name).stdout)
assert Path(f'/proc/{pid}/cwd').resolve() == odd.resolve()
assert Path(f'/proc/{pid}/exe').resolve() == binary.resolve()
ctl('stop', unit_name)
assert ctl('show', '--property=ActiveState', '--value', unit_name).stdout.strip() == 'inactive'
assert not Path(f'/proc/{pid}').exists(), 'service process still exists'
print('Native systemd install/reuse/conflict/lifecycle passed: literal paths, explicit config, environment, health, readiness and stop')
finally:
# Unlink only our randomly named unit, never any existing profile.
ctl('stop', unit_name, check=False)
if link.is_file() and not link.is_symlink() and link.read_text() == generated:
link.unlink()
ctl('daemon-reload', check=False)
ctl('reset-failed', unit_name, check=False)
if __name__ == '__main__':
main()