Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
173 lines
8.9 KiB
Python
173 lines
8.9 KiB
Python
#!/usr/bin/env python3
|
|
# Strata Next native API client v1
|
|
"""Console client for native runtime observation and admission maintenance."""
|
|
import argparse
|
|
import http.client
|
|
import json
|
|
import math
|
|
import time
|
|
from urllib.parse import urlsplit
|
|
|
|
ACTIONS = {'status': ('GET', '/status'), 'wait-ready': ('GET', '/status'), 'metrics': ('GET', '/metrics'),
|
|
'lifecycle': ('GET', '/admin/lifecycle'), 'drain': ('POST', '/admin/drain'),
|
|
'resume': ('POST', '/admin/resume')}
|
|
LIMIT = 65536
|
|
|
|
|
|
class NativeConnectionError(RuntimeError):
|
|
"""A connection failure that read-only readiness waiting may retry."""
|
|
|
|
|
|
def endpoint(url):
|
|
if not isinstance(url, str) or not url or any(ord(c) <= 32 or ord(c) >= 127 for c in url):
|
|
raise ValueError('Native API URL must be plain ASCII without whitespace')
|
|
parsed = urlsplit(url)
|
|
if (parsed.scheme != 'http' or parsed.hostname not in {'127.0.0.1', 'localhost', '::1'}
|
|
or parsed.username is not None or parsed.password is not None
|
|
or parsed.path or parsed.query or parsed.fragment):
|
|
raise ValueError('Native API needs a plain loopback HTTP URL without credentials or path')
|
|
port = parsed.port if parsed.port is not None else 80
|
|
if not 1 <= port <= 65535:
|
|
raise ValueError('Native API port must be between 1 and 65535')
|
|
return ('127.0.0.1' if parsed.hostname == 'localhost' else parsed.hostname), port
|
|
|
|
|
|
def request(url, method, path, token, *, timeout=8):
|
|
host, port = endpoint(url)
|
|
headers = {'Accept': 'application/json'}
|
|
if token:
|
|
headers['Authorization'] = 'Bearer ' + token
|
|
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
|
try:
|
|
conn.request(method, path, headers=headers)
|
|
response = conn.getresponse()
|
|
if response.status != 200:
|
|
# Never follow a redirect or echo server error bodies/credentials.
|
|
raise RuntimeError(f'Native API returned HTTP {response.status}; check endpoint support and authentication')
|
|
if response.getheader('Content-Type', '').split(';')[0].strip() != 'application/json':
|
|
raise RuntimeError('Native API returned a non-JSON response')
|
|
data = response.read(LIMIT + 1)
|
|
if len(data) > LIMIT:
|
|
raise RuntimeError('Native API response exceeded 64 KiB')
|
|
if token and token.encode() in data:
|
|
raise RuntimeError('Native API response echoed the credential; output suppressed')
|
|
def reject_constant(_):
|
|
raise ValueError('nonfinite JSON value')
|
|
value = json.loads(data, parse_constant=reject_constant)
|
|
if not isinstance(value, dict):
|
|
raise ValueError('expected object')
|
|
if token and token in json.dumps(value, ensure_ascii=False):
|
|
raise RuntimeError('Native API response echoed the credential; output suppressed')
|
|
return value
|
|
except OSError:
|
|
raise NativeConnectionError('Native API connection failed or timed out; check endpoint availability') from None
|
|
except (http.client.HTTPException, ValueError):
|
|
raise RuntimeError('Native API transport or JSON failed; check lifecycle before retrying a mutation') from None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def lifecycle(value):
|
|
if (any(type(value.get(key)) is not bool for key in ('draining', 'drained'))
|
|
or any(type(value.get(key)) is not int or value[key] < 0
|
|
for key in ('requests_in_flight', 'generation_jobs'))
|
|
or value.get('worker') not in {'unconfigured', 'starting', 'restarting', 'ready', 'stopping', 'failed'}):
|
|
raise RuntimeError('Invalid native lifecycle response')
|
|
if value['drained'] and (not value['draining'] or value['requests_in_flight']
|
|
or value['generation_jobs'] or value['worker'] not in {'ready', 'unconfigured'}):
|
|
raise RuntimeError('Inconsistent native drained state')
|
|
return value
|
|
|
|
|
|
def wait_ready(url, token, wait, transport, clock, sleep):
|
|
deadline = clock() + wait
|
|
while True:
|
|
remaining = deadline - clock()
|
|
if wait and remaining <= 0:
|
|
raise RuntimeError('Readiness wait timed out; no runtime or connection changes were made')
|
|
try:
|
|
result = transport(url, 'GET', '/status', token, timeout=min(8, remaining) if wait else 8)
|
|
except NativeConnectionError:
|
|
result = None
|
|
if result is not None:
|
|
if (not isinstance(result, dict) or result.get('service') != 'strata-control'
|
|
or type(result.get('ready')) is not bool):
|
|
raise RuntimeError('Endpoint is not a native Strata control plane')
|
|
worker = result.get('worker')
|
|
if not isinstance(worker, str) or worker not in {'unconfigured', 'starting', 'restarting', 'ready', 'stopping', 'failed'}:
|
|
raise RuntimeError('Invalid native worker status')
|
|
if result['ready'] and worker != 'ready':
|
|
raise RuntimeError('Inconsistent native readiness status')
|
|
if worker in {'unconfigured', 'stopping', 'failed'}:
|
|
raise RuntimeError('Native worker cannot become ready in its current state: ' + worker)
|
|
if result['ready'] and (not wait or clock() < deadline):
|
|
return result
|
|
if not wait:
|
|
raise RuntimeError('Native model is not ready; use --wait SECONDS to wait without changing the runtime')
|
|
remaining = deadline - clock()
|
|
if remaining > 0:
|
|
sleep(min(0.25, remaining))
|
|
|
|
|
|
def control(action, target, read_key, *, wait=0, transport=request, clock=time.monotonic, sleep=time.sleep):
|
|
if action not in ACTIONS:
|
|
raise ValueError('Unsupported native API action')
|
|
if not math.isfinite(wait) or not 0 <= wait <= 3600 or (wait and action not in {'drain', 'wait-ready'}):
|
|
raise ValueError('--wait is only for drain or wait-ready, between 0 and 3600 seconds')
|
|
if target.get('backend') != 'strata-native':
|
|
raise ValueError('Select strata-native first or pass --url with --key-file/--no-auth')
|
|
url = target.get('url')
|
|
endpoint(url)
|
|
token = read_key(target) if target.get('key_file') else ''
|
|
if action == 'wait-ready':
|
|
result = wait_ready(url, token, wait, transport, clock, sleep)
|
|
return {'action': action, 'url': url, 'connection_changed': False, 'runtime': result}
|
|
observed = transport(url, 'GET', '/status', token)
|
|
if observed.get('service') != 'strata-control' or type(observed.get('ready')) is not bool:
|
|
raise RuntimeError('Endpoint is not a native Strata control plane')
|
|
if action == 'status':
|
|
result = observed
|
|
else:
|
|
method, path = ACTIONS[action]
|
|
result = transport(url, method, path, token)
|
|
if action in {'drain', 'resume', 'lifecycle'}:
|
|
lifecycle(result)
|
|
if action in {'drain', 'resume'} and result['draining'] != (action == 'drain'):
|
|
raise RuntimeError('Native admission changed concurrently; inspect lifecycle')
|
|
if action == 'metrics' and (result.get('schema_version') != 1 or not isinstance(result.get('generation'), dict)):
|
|
raise RuntimeError('Unsupported native metrics response')
|
|
deadline = clock() + wait
|
|
while action == 'drain' and wait and not result['drained']:
|
|
remaining = deadline - clock()
|
|
if remaining <= 0:
|
|
raise RuntimeError('Drain wait timed out; admission remains closed. Inspect lifecycle or explicitly resume.')
|
|
sleep(min(0.25, remaining))
|
|
remaining = deadline - clock()
|
|
if remaining <= 0:
|
|
continue
|
|
result = lifecycle(transport(url, 'GET', '/admin/lifecycle', token, timeout=min(8, remaining)))
|
|
if not result['draining']:
|
|
raise RuntimeError('Drain was resumed concurrently; no shutdown was performed')
|
|
return {'action': action, 'url': url, 'connection_changed': False, 'runtime': result}
|
|
|
|
|
|
def main(argv=None, *, connection, read_key):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action', choices=tuple(ACTIONS))
|
|
parser.add_argument('--url', help='explicit loopback URL; does not change the selected connection')
|
|
auth = parser.add_mutually_exclusive_group()
|
|
auth.add_argument('--key-file', help='private key file; token is never a CLI argument')
|
|
auth.add_argument('--no-auth', action='store_true')
|
|
parser.add_argument('--wait', type=float, default=0, metavar='SECONDS', help='wait for drain or model readiness; never auto-start/stop')
|
|
args = parser.parse_args(argv)
|
|
if args.url:
|
|
if not args.key_file and not args.no_auth:
|
|
parser.error('--url requires --key-file or --no-auth; credentials are never inherited for an override')
|
|
target = {'backend': 'strata-native', 'url': args.url, 'key_file': args.key_file}
|
|
else:
|
|
if args.key_file or args.no_auth:
|
|
parser.error('authentication overrides require an explicit --url')
|
|
target = connection()
|
|
result = control(args.action, target, read_key, wait=args.wait)
|
|
print(json.dumps(result, ensure_ascii=False))
|