168 lines
8.5 KiB
Python
168 lines
8.5 KiB
Python
#!/usr/bin/env python3
|
|
# Strata Next native service client v1
|
|
"""Explicit client-side systemd control over SSH; no inference serving code."""
|
|
import argparse
|
|
import json
|
|
import ipaddress
|
|
import os
|
|
import re
|
|
import selectors
|
|
import shlex
|
|
import subprocess
|
|
import time
|
|
|
|
PROPERTIES = ('LoadState', 'ActiveState', 'SubState', 'MainPID', 'Result')
|
|
|
|
|
|
def ssh_check(host, arguments):
|
|
"""Bounded, quiet preflight transport; raw remote errors never reach logs."""
|
|
try:
|
|
with subprocess.Popen(
|
|
['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', '--', host,
|
|
shlex.join(arguments)], stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
) as process:
|
|
try:
|
|
deadline = time.monotonic() + 30
|
|
data = bytearray()
|
|
with selectors.DefaultSelector() as selector:
|
|
selector.register(process.stdout, selectors.EVENT_READ)
|
|
while True:
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0 or not selector.select(remaining):
|
|
raise ValueError('timeout')
|
|
chunk = os.read(process.stdout.fileno(), 4096)
|
|
if not chunk:
|
|
break
|
|
data.extend(chunk)
|
|
if len(data) > 65536:
|
|
raise ValueError('output limit')
|
|
if process.wait(timeout=max(0, deadline - time.monotonic())):
|
|
raise ValueError('remote failure')
|
|
return data.decode('utf-8')
|
|
except BaseException:
|
|
process.kill()
|
|
process.wait()
|
|
raise
|
|
except (OSError, ValueError, subprocess.SubprocessError):
|
|
raise RuntimeError('Native configuration check failed (SSH, timeout, output limit or invalid remote configuration)') from None
|
|
|
|
|
|
def check_config(host, binary, config, working_dir, *, runner=ssh_check):
|
|
validate(host, 'leleka-api.service')
|
|
for path in (binary, config, working_dir):
|
|
if not isinstance(path, str) or not path.startswith('/') or any(ord(c) < 32 or ord(c) == 127 for c in path):
|
|
raise ValueError('preflight paths must be absolute and contain no control characters')
|
|
arguments = ['sh', '-c', 'cd "$1" && exec "$2" check-config --config "$3"',
|
|
'strata-preflight', working_dir, binary, config]
|
|
try:
|
|
raw = runner(host, arguments)
|
|
if len(raw.encode('utf-8')) > 65536:
|
|
raise ValueError('output limit')
|
|
report = json.loads(raw)
|
|
if not isinstance(report, dict) or type(report.get('schema_version')) is not int or report['schema_version'] != 1:
|
|
raise ValueError('schema')
|
|
fields = ('configuration_valid', 'authentication_enabled', 'tokenizer_validated',
|
|
'inference_configured', 'readiness_checked')
|
|
if any(type(report.get(field)) is not bool for field in fields):
|
|
raise ValueError('flags')
|
|
if not report['configuration_valid'] or report['readiness_checked'] or report.get('platform') != 'linux':
|
|
raise ValueError('scope')
|
|
if report.get('engine') not in ('unconfigured', 'external', 'embedded'):
|
|
raise ValueError('engine')
|
|
if report['inference_configured'] != (report['engine'] != 'unconfigured' and report['tokenizer_validated']):
|
|
raise ValueError('inconsistent inference flags')
|
|
model = report.get('model')
|
|
if model is not None and (not isinstance(model, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,180}', model)):
|
|
raise ValueError('model')
|
|
address, port = report['bind'].rsplit(':', 1)
|
|
ipaddress.ip_address(address.removeprefix('[').removesuffix(']'))
|
|
if not port.isascii() or not port.isdigit() or not 0 <= int(port) <= 65535:
|
|
raise ValueError('port')
|
|
safe = {key: report[key] for key in (*fields, 'schema_version', 'platform', 'engine', 'bind')}
|
|
safe['model'] = model
|
|
except (RuntimeError, OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError):
|
|
raise RuntimeError('Native configuration check failed; inspect the candidate configuration on the host') from None
|
|
return {'host': host, 'action': 'check-config', 'configuration': safe,
|
|
'connection_changed': False, 'model_readiness': 'not_checked'}
|
|
|
|
|
|
def validate(host, unit):
|
|
# SSH aliases/DNS names only. Refuse options, user overrides and shell text.
|
|
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,252}', host):
|
|
raise ValueError('host must be an SSH alias or DNS name without options or a username')
|
|
if not re.fullmatch(r'leleka-api(?:-[a-z0-9][a-z0-9-]{0,79})?\.service', unit):
|
|
raise ValueError('unit must be leleka-api.service or leleka-api-NAME.service')
|
|
|
|
|
|
def ssh(host, arguments):
|
|
result = subprocess.run(
|
|
['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', '--', host,
|
|
shlex.join(arguments)],
|
|
text=True, capture_output=True, timeout=90,
|
|
)
|
|
if result.returncode:
|
|
raise RuntimeError('Native service SSH command failed: ' + result.stderr[-1500:].strip())
|
|
return result.stdout
|
|
|
|
|
|
def control(action, host, unit, *, runner=ssh):
|
|
validate(host, unit)
|
|
if action not in {'start', 'stop', 'status', 'logs'}:
|
|
raise ValueError('unsupported native service action')
|
|
|
|
def state():
|
|
text = runner(host, ['systemctl', '--user', 'show',
|
|
*['--property=' + p for p in PROPERTIES], '--', unit])
|
|
result = dict(line.split('=', 1) for line in text.splitlines() if '=' in line)
|
|
if result.get('LoadState') != 'loaded':
|
|
raise RuntimeError('Native unit is not loaded; provision the user service first: ' + unit)
|
|
if (result.get('ActiveState') not in {'active', 'inactive', 'failed', 'activating',
|
|
'deactivating', 'reloading', 'maintenance', 'refreshing'}
|
|
or not result.get('MainPID', '').isascii()
|
|
or not result.get('MainPID', '').isdigit()):
|
|
raise RuntimeError('Incomplete or invalid native service status')
|
|
return {key: result.get(key, '') for key in PROPERTIES}
|
|
|
|
before = state()
|
|
if action == 'logs':
|
|
return runner(host, ['journalctl', '--user', '--unit=' + unit, '--lines=100',
|
|
'--no-pager', '--output=short-iso'])
|
|
changed = False
|
|
if ((action == 'start' and before['ActiveState'] not in {'active', 'activating'})
|
|
or (action == 'stop' and before['ActiveState'] != 'inactive')):
|
|
runner(host, ['systemctl', '--user', action, '--', unit])
|
|
changed = True
|
|
after = state() if changed else before
|
|
if action == 'start' and after['ActiveState'] not in {'active', 'activating'}:
|
|
raise RuntimeError('Native service failed to start: ' + after['ActiveState'])
|
|
if action == 'stop' and after['ActiveState'] != 'inactive':
|
|
raise RuntimeError('Native service did not stop: ' + after['ActiveState'])
|
|
return {'host': host, 'unit': unit, 'action': action, 'changed': changed,
|
|
'process': after, 'model_readiness': 'not_checked',
|
|
'connection_changed': False}
|
|
|
|
|
|
def main(argv=None, *, default_host='rnr5090'):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action', choices=('start', 'stop', 'status', 'logs', 'check-config'))
|
|
parser.add_argument('--host', default=default_host, help='existing SSH alias; no credentials are copied')
|
|
parser.add_argument('--unit')
|
|
parser.add_argument('--binary', help='check-config: absolute remote candidate executable')
|
|
parser.add_argument('--config', help='check-config: absolute remote JSON configuration')
|
|
parser.add_argument('--working-dir', help='check-config: absolute remote working directory')
|
|
args = parser.parse_args(argv)
|
|
if args.action == 'check-config':
|
|
if args.unit or not all((args.binary, args.config, args.working_dir)):
|
|
parser.error('check-config requires --binary, --config and --working-dir, without --unit')
|
|
result = check_config(args.host, args.binary, args.config, args.working_dir)
|
|
else:
|
|
if any((args.binary, args.config, args.working_dir)):
|
|
parser.error('--binary, --config and --working-dir are only for check-config')
|
|
result = control(args.action, args.host, args.unit or 'leleka-api.service')
|
|
print(result if isinstance(result, str) else json.dumps(result, ensure_ascii=False), end='\n')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|