Files
leleka/scripts/smoke-service-unit.py
T

109 lines
5.0 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):
return subprocess.run(args, check=check, text=True, capture_output=True, timeout=60)
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-service-smoke-') 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
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:
ctl('link', str(unit))
ctl('start', unit_name)
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 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_symlink() and link.resolve() == unit:
link.unlink()
ctl('daemon-reload', check=False)
ctl('reset-failed', unit_name, check=False)
if __name__ == '__main__':
main()