81 lines
3.7 KiB
Python
81 lines
3.7 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 re
|
|
import shlex
|
|
import subprocess
|
|
|
|
PROPERTIES = ('LoadState', 'ActiveState', 'SubState', 'MainPID', 'Result')
|
|
|
|
|
|
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'strata-next(?:-[a-z0-9][a-z0-9-]{0,79})?\.service', unit):
|
|
raise ValueError('unit must be strata-next.service or strata-next-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'))
|
|
parser.add_argument('--host', default=default_host, help='existing SSH alias; no credentials are copied')
|
|
parser.add_argument('--unit', default='strata-next.service')
|
|
args = parser.parse_args(argv)
|
|
result = control(args.action, args.host, args.unit)
|
|
print(result if isinstance(result, str) else json.dumps(result, ensure_ascii=False), end='\n')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|