Restructure backend and frontend modules; add story, library, and editor schema migrations. Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews. Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
500 lines
22 KiB
Python
500 lines
22 KiB
Python
#!/usr/bin/env python3
|
||
"""Root-managed, CPU-only Qwen HTTP gateway. No CUDA or project imports.
|
||
|
||
Only fixed, administrator-configured Docker identities may be controlled.
|
||
Run one instance; the process lock is mandatory. HTTP callers cannot select
|
||
containers, executable paths, bind mounts or lifecycle commands.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import hmac
|
||
import http.client
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
import json
|
||
import logging
|
||
import math
|
||
import os
|
||
from pathlib import Path
|
||
import signal
|
||
import sqlite3
|
||
import stat
|
||
import subprocess
|
||
import threading
|
||
import time
|
||
from urllib.parse import urlsplit
|
||
import uuid
|
||
|
||
LOG = logging.getLogger('qwen-on-demand')
|
||
|
||
|
||
def read_json(path, limit=1024 * 1024):
|
||
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
|
||
with os.fdopen(fd, 'rb') as handle:
|
||
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
||
raise ValueError('Expected a regular JSON file')
|
||
raw = handle.read(limit + 1)
|
||
if len(raw) > limit:
|
||
raise ValueError('JSON file exceeds size limit')
|
||
return json.loads(raw)
|
||
|
||
|
||
def atomic_json(path, value):
|
||
path = Path(path)
|
||
temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
|
||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
|
||
try:
|
||
with os.fdopen(fd, 'w', encoding='utf-8') as handle:
|
||
json.dump(value, handle, allow_nan=False)
|
||
handle.flush()
|
||
os.fsync(handle.fileno())
|
||
os.replace(temporary, path)
|
||
if os.name == 'posix':
|
||
directory = os.open(path.parent, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
|
||
try:
|
||
os.fsync(directory)
|
||
finally:
|
||
os.close(directory)
|
||
finally:
|
||
temporary.unlink(missing_ok=True)
|
||
|
||
|
||
def fresh_timestamp(value, maximum_age, now):
|
||
return (type(value) in (int, float) and math.isfinite(value)
|
||
and -1 <= now - value <= maximum_age)
|
||
|
||
|
||
class HostAdmission:
|
||
def __init__(self, *, reservation_path, scheduler_path, gpu_status_path,
|
||
queue_db_path, gpu_uuid, wait_seconds=600, workspace_container_id=None):
|
||
self.path = Path(reservation_path)
|
||
self.scheduler_path = Path(scheduler_path)
|
||
self.gpu_status_path = Path(gpu_status_path)
|
||
self.queue_db_path = Path(queue_db_path)
|
||
self.gpu_uuid = gpu_uuid
|
||
self.wait_seconds = wait_seconds
|
||
self.workspace_container_id = workspace_container_id
|
||
self.token = None
|
||
|
||
def _write(self, hold, cutoff=0):
|
||
atomic_json(self.path, {'schema_version': 1, 'gpu_uuid': self.gpu_uuid,
|
||
'token': self.token, 'hold': hold, 'queue_seq_cutoff': cutoff})
|
||
|
||
def _gpu_idle(self, *, after=0, minimum_idle_seconds=0):
|
||
data = read_json(self.gpu_status_path)
|
||
now = time.time()
|
||
started = data.get('sample_started_at', data.get('generated_at'))
|
||
if (type(data.get('schema_version')) is not int or data.get('schema_version') != 1
|
||
or 'error' not in data or data['error'] is not None
|
||
or not fresh_timestamp(data.get('generated_at'), 20, now)
|
||
or not fresh_timestamp(started, 20, now)
|
||
or started > data['generated_at'] or started < after
|
||
or (self.workspace_container_id is not None
|
||
and data.get('container_id') != self.workspace_container_id)):
|
||
return False
|
||
matches = [g for g in data.get('gpus', []) if g.get('uuid') == self.gpu_uuid]
|
||
target = matches[0] if len(matches) == 1 else None
|
||
return bool(target is not None and target.get('external_pids') == []
|
||
and target.get('own_pids') == [] and target.get('free_gib', 0) >= 76
|
||
and fresh_timestamp(target.get('idle_since'), 86400 * 365, now)
|
||
and now - target['idle_since'] >= minimum_idle_seconds)
|
||
|
||
def _acknowledged(self, *, expected_cutoff=None, after=0):
|
||
data = read_json(self.scheduler_path)
|
||
ack = data.get('qwen_reservation', {})
|
||
return (fresh_timestamp(data.get('updated_at'), 3, time.time())
|
||
and data['updated_at'] >= after
|
||
and data.get('state') != 'blocked'
|
||
and ack.get('enabled') is True and ack.get('hold') is True
|
||
and ack.get('token') == self.token and ack.get('gpu_uuid') == self.gpu_uuid
|
||
and (expected_cutoff is None or ack.get('queue_seq_cutoff') == expected_cutoff)
|
||
and ack.get('quiesced') is True
|
||
and not any(j.get('gpu_uuid') == self.gpu_uuid for j in data.get('active_jobs', [])))
|
||
|
||
def acquire(self):
|
||
# 只读当前队列上界;后提交的媒体任务不能抢在本次预约前占回 GPU0。
|
||
with sqlite3.connect(self.queue_db_path.as_uri() + '?mode=ro', uri=True, timeout=3) as db:
|
||
cutoff = db.execute('SELECT COALESCE(MAX(queue_seq),0) FROM jobs').fetchone()[0]
|
||
self.token = uuid.uuid4().hex
|
||
self._write(True, cutoff)
|
||
sealed_at = None
|
||
deadline = time.monotonic() + self.wait_seconds
|
||
while time.monotonic() < deadline:
|
||
try:
|
||
if sealed_at is None and self._acknowledged(expected_cutoff=cutoff):
|
||
# 第二阶段由 root 持久封口:worker 重启后丢失内存确认也不能重新领卡。
|
||
self._write(True, 0)
|
||
sealed_at = time.time()
|
||
if (sealed_at is not None
|
||
and self._acknowledged(expected_cutoff=0, after=sealed_at)
|
||
and self._gpu_idle(after=sealed_at, minimum_idle_seconds=15)):
|
||
return
|
||
except (OSError, ValueError, TypeError, KeyError):
|
||
pass
|
||
time.sleep(.2)
|
||
raise TimeoutError('Timed out waiting for GPU0 handoff')
|
||
|
||
def release(self, *, engine_was_started=True):
|
||
if engine_was_started:
|
||
stopped_at = time.time()
|
||
deadline = time.monotonic() + 30
|
||
while time.monotonic() < deadline:
|
||
try:
|
||
if self._gpu_idle(after=stopped_at):
|
||
break
|
||
except (OSError, ValueError, TypeError, KeyError):
|
||
pass
|
||
time.sleep(.2)
|
||
else:
|
||
raise RuntimeError('GPU0 release is not verified; reservation retained')
|
||
self.token = self.token or uuid.uuid4().hex
|
||
self._write(False)
|
||
|
||
def needs_verification(self):
|
||
try:
|
||
return read_json(self.path, 4096).get('hold') is not False
|
||
except (OSError, ValueError, TypeError):
|
||
return True
|
||
|
||
|
||
class DockerEngine:
|
||
def __init__(self, container_id, *, upstream_port, image_id, start_seconds=600):
|
||
if len(container_id) != 64 or any(c not in '0123456789abcdef' for c in container_id):
|
||
raise ValueError('A full fixed Docker container ID is required')
|
||
self.container_id, self.image_id = container_id, image_id
|
||
self.upstream_port, self.start_seconds = upstream_port, start_seconds
|
||
|
||
def _docker(self, *args, timeout=60):
|
||
result = subprocess.run(['/usr/bin/docker', *args], check=False,
|
||
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
||
if result.returncode:
|
||
raise RuntimeError('Docker lifecycle operation failed')
|
||
return result.stdout
|
||
|
||
def _inspect(self):
|
||
data = json.loads(self._docker('inspect', self.container_id))[0]
|
||
if data['Image'] != self.image_id:
|
||
raise RuntimeError('Configured engine identity changed')
|
||
return data
|
||
|
||
def start(self):
|
||
data = self._inspect()
|
||
if data['State']['Running']:
|
||
raise RuntimeError('Unreconciled running model engine')
|
||
self._docker('start', self.container_id)
|
||
deadline = time.monotonic() + self.start_seconds
|
||
while time.monotonic() < deadline:
|
||
if not self._inspect()['State']['Running']:
|
||
raise RuntimeError('Qwen exited during cold loading')
|
||
connection = http.client.HTTPConnection('127.0.0.1', self.upstream_port, timeout=2)
|
||
try:
|
||
connection.request('GET', '/health')
|
||
response = connection.getresponse()
|
||
response.read()
|
||
if response.status == 200:
|
||
return
|
||
except (OSError, http.client.HTTPException):
|
||
pass
|
||
finally:
|
||
connection.close()
|
||
time.sleep(.5)
|
||
raise TimeoutError('Qwen cold loading timed out')
|
||
|
||
def stop(self):
|
||
if self._inspect()['State']['Running']:
|
||
self._docker('stop', '--time', '30', self.container_id, timeout=45)
|
||
if self._inspect()['State']['Running']:
|
||
raise RuntimeError('Qwen container did not stop')
|
||
|
||
def running(self):
|
||
return self._inspect()['State']['Running']
|
||
|
||
|
||
class ModelLifecycle:
|
||
def __init__(self, engine, admission):
|
||
self.engine, self.admission = engine, admission
|
||
self.condition = threading.Condition()
|
||
self.state, self.active_requests = 'stopped', 0
|
||
self.error = None
|
||
|
||
def snapshot(self):
|
||
with self.condition:
|
||
return {'state': self.state, 'active_requests': self.active_requests,
|
||
'on_demand': True}
|
||
|
||
def acquire(self):
|
||
with self.condition:
|
||
while self.state == 'stopping':
|
||
self.condition.wait()
|
||
if self.state in {'blocked', 'failed'}:
|
||
raise RuntimeError('Model lifecycle requires recovery')
|
||
self.active_requests += 1
|
||
leader = self.state == 'stopped'
|
||
if leader:
|
||
self.state = 'starting'
|
||
if leader:
|
||
attempted_start = False
|
||
try:
|
||
self.admission.acquire()
|
||
attempted_start = True
|
||
self.engine.start()
|
||
except Exception as exc:
|
||
blocked = False
|
||
try:
|
||
self.engine.stop()
|
||
self.admission.release(engine_was_started=attempted_start)
|
||
except Exception:
|
||
blocked = True
|
||
LOG.exception('Startup cleanup failed; retain GPU reservation')
|
||
with self.condition:
|
||
self.error = exc
|
||
self.state = 'blocked' if blocked else 'failed'
|
||
self.condition.notify_all()
|
||
else:
|
||
with self.condition:
|
||
self.state = 'ready'
|
||
self.error = None
|
||
self.condition.notify_all()
|
||
with self.condition:
|
||
while self.state == 'starting':
|
||
self.condition.wait()
|
||
if self.state != 'ready':
|
||
self.active_requests -= 1
|
||
if self.active_requests == 0 and self.state == 'failed':
|
||
self.state = 'stopped'
|
||
raise RuntimeError(str(self.error or 'Model lifecycle blocked'))
|
||
|
||
def release(self):
|
||
with self.condition:
|
||
if self.active_requests <= 0:
|
||
raise RuntimeError('Unbalanced Qwen request release')
|
||
self.active_requests -= 1
|
||
if self.active_requests:
|
||
return
|
||
self.state = 'stopping'
|
||
try:
|
||
self.engine.stop()
|
||
self.admission.release(engine_was_started=True)
|
||
except Exception:
|
||
with self.condition:
|
||
self.state = 'blocked'
|
||
self.condition.notify_all()
|
||
raise
|
||
with self.condition:
|
||
self.state = 'stopped'
|
||
self.condition.notify_all()
|
||
|
||
|
||
def make_server(address, lifecycle, *, upstream_port, model, api_key='', models=None,
|
||
inference_seconds=600):
|
||
metadata = models or {'object': 'list', 'data': [{'id': model, 'object': 'model', 'owned_by': 'sglang'}]}
|
||
hop_headers = {'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
||
'te', 'trailer', 'transfer-encoding', 'upgrade', 'host', 'content-length'}
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
protocol_version = 'HTTP/1.1'
|
||
|
||
def log_message(self, format, *args):
|
||
# 不记录输入、查询参数、Authorization 或上游错误正文。
|
||
pass
|
||
|
||
def setup(self):
|
||
super().setup()
|
||
self.connection.settimeout(15)
|
||
|
||
def reply(self, status, value):
|
||
blob = json.dumps(value, ensure_ascii=False).encode('utf-8')
|
||
self.send_response(status)
|
||
self.send_header('Content-Type', 'application/json; charset=utf-8')
|
||
self.send_header('Content-Length', str(len(blob)))
|
||
self.send_header('Connection', 'close')
|
||
self.end_headers()
|
||
self.close_connection = True
|
||
if self.command != 'HEAD':
|
||
self.wfile.write(blob)
|
||
|
||
def authenticated(self):
|
||
return not api_key or hmac.compare_digest(
|
||
self.headers.get('Authorization', '').encode('utf-8'), ('Bearer ' + api_key).encode('utf-8'))
|
||
|
||
def do_GET(self):
|
||
path = urlsplit(self.path).path
|
||
if path == '/health':
|
||
snapshot = lifecycle.snapshot()
|
||
self.reply(503 if snapshot['state'] == 'blocked' else 200, snapshot)
|
||
elif not self.authenticated():
|
||
self.reply(401, {'error': {'message': 'Unauthorized'}})
|
||
elif path == '/v1/models':
|
||
self.reply(200, metadata)
|
||
elif path in {'/get_model_info', '/get_server_info', '/v1/loads'}:
|
||
self.reply(200, {'model_path': model, 'served_model_name': model, **lifecycle.snapshot()})
|
||
else:
|
||
self.reply(404, {'error': {'message': 'Not found'}})
|
||
|
||
do_HEAD = do_GET
|
||
|
||
def do_POST(self):
|
||
if not self.authenticated():
|
||
self.reply(401, {'error': {'message': 'Unauthorized'}})
|
||
return
|
||
path = urlsplit(self.path).path
|
||
if path not in {'/v1/chat/completions', '/v1/completions', '/generate'}:
|
||
self.reply(404, {'error': {'message': 'Not found'}})
|
||
return
|
||
try:
|
||
length = int(self.headers.get('Content-Length', '0'))
|
||
if self.headers.get('Transfer-Encoding') or not 0 < length <= 16 * 1024 * 1024:
|
||
raise ValueError('Invalid request size')
|
||
raw = self.rfile.read(length)
|
||
if len(raw) != length:
|
||
raise ValueError('Incomplete request body')
|
||
body = json.loads(raw)
|
||
if not isinstance(body, dict) or body.get('model', model) != model:
|
||
raise ValueError('Invalid model')
|
||
if path == '/v1/chat/completions':
|
||
messages = body.get('messages')
|
||
if (not isinstance(messages, list) or not messages
|
||
or any(not isinstance(m, dict)
|
||
or m.get('role') not in {'system','developer','user','assistant','tool','function'}
|
||
or not (isinstance(m.get('content'), (str, list))
|
||
or (m.get('role') == 'assistant' and m.get('content') is None
|
||
and isinstance(m.get('tool_calls'), list)))
|
||
or (isinstance(m.get('content'), list)
|
||
and any(not isinstance(p, dict) or not isinstance(p.get('type'), str)
|
||
for p in m['content'])) for m in messages)):
|
||
raise ValueError('Invalid messages')
|
||
elif path == '/v1/completions':
|
||
prompt = body.get('prompt')
|
||
if not (isinstance(prompt, str) or (isinstance(prompt, list) and prompt
|
||
and (all(isinstance(x, str) for x in prompt)
|
||
or all(type(x) is int and x >= 0 for x in prompt)))):
|
||
raise ValueError('Invalid prompt')
|
||
else:
|
||
text, ids = body.get('text'), body.get('input_ids')
|
||
if not (isinstance(text, str)
|
||
or (isinstance(text, list) and text and all(isinstance(x, str) for x in text))
|
||
or (isinstance(ids, list) and ids and all(type(x) is int and x >= 0 for x in ids))):
|
||
raise ValueError('Invalid generation input')
|
||
if 'sampling_params' in body and not isinstance(body['sampling_params'], (dict, list)):
|
||
raise ValueError('Invalid sampling parameters')
|
||
if 'stream' in body and type(body['stream']) is not bool:
|
||
raise ValueError('Invalid stream')
|
||
for key in ('max_tokens', 'max_completion_tokens'):
|
||
if key in body and body[key] is not None and (type(body[key]) is not int or body[key] <= 0):
|
||
raise ValueError('Invalid token limit')
|
||
except (ValueError, OSError, RecursionError):
|
||
self.reply(400, {'error': {'message': 'Invalid inference request'}})
|
||
return
|
||
acquired, sent = False, False
|
||
connection = None
|
||
try:
|
||
lifecycle.acquire()
|
||
acquired = True
|
||
connection = http.client.HTTPConnection('127.0.0.1', upstream_port, timeout=inference_seconds)
|
||
headers = {k: v for k, v in self.headers.items() if k.lower() not in hop_headers}
|
||
headers['Content-Length'] = str(len(raw))
|
||
connection.request('POST', self.path, body=raw, headers=headers)
|
||
response = connection.getresponse()
|
||
disconnected = False
|
||
try:
|
||
self.send_response(response.status)
|
||
for key, value in response.getheaders():
|
||
if key.lower() not in hop_headers:
|
||
self.send_header(key, value)
|
||
self.send_header('Connection', 'close')
|
||
self.end_headers()
|
||
sent = True
|
||
except OSError:
|
||
disconnected = True
|
||
self.close_connection = True
|
||
while True:
|
||
chunk = response.read1(64 * 1024)
|
||
if not chunk:
|
||
break
|
||
if not disconnected:
|
||
try:
|
||
self.wfile.write(chunk)
|
||
self.wfile.flush()
|
||
except OSError:
|
||
# 保留引用并读完上游;客户端断开不能误停其他并发推理。
|
||
disconnected = True
|
||
except Exception:
|
||
LOG.exception('Qwen request failed')
|
||
if not sent:
|
||
try:
|
||
self.reply(503, {'error': {'message': 'Qwen loading or inference unavailable'}})
|
||
except OSError:
|
||
pass
|
||
finally:
|
||
if connection is not None:
|
||
connection.close()
|
||
if acquired:
|
||
try:
|
||
lifecycle.release()
|
||
except Exception:
|
||
LOG.exception('Model release failed; GPU0 remains reserved')
|
||
|
||
class Server(ThreadingHTTPServer):
|
||
daemon_threads = False
|
||
request_queue_size = 32
|
||
|
||
def __init__(self, *args):
|
||
self.slots = threading.BoundedSemaphore(32)
|
||
super().__init__(*args)
|
||
|
||
def process_request(self, request, client_address):
|
||
self.slots.acquire()
|
||
try:
|
||
super().process_request(request, client_address)
|
||
except BaseException:
|
||
self.slots.release()
|
||
raise
|
||
|
||
def process_request_thread(self, request, client_address):
|
||
try:
|
||
super().process_request_thread(request, client_address)
|
||
finally:
|
||
self.slots.release()
|
||
|
||
return Server(address, Handler)
|
||
|
||
|
||
def reconcile(engine, admission):
|
||
was_running = engine.running() or admission.needs_verification()
|
||
engine.stop()
|
||
admission.release(engine_was_started=was_running)
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument('--config', required=True)
|
||
args = parser.parse_args()
|
||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
|
||
config = read_json(args.config, 1024 * 1024)
|
||
import fcntl
|
||
lock_fd = os.open(config['lock_path'], os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||
engine = DockerEngine(config['container_id'], upstream_port=config['upstream_port'],
|
||
image_id=config['image_id'])
|
||
admission = HostAdmission(**config['admission'])
|
||
# 重启后先清理旧引擎;未确认停止时绝不解除遗留预约。
|
||
reconcile(engine, admission)
|
||
lifecycle = ModelLifecycle(engine, admission)
|
||
server = make_server((config['host'], config['port']), lifecycle,
|
||
upstream_port=config['upstream_port'], model=config['model'],
|
||
api_key=config.get('api_key', ''), models=config.get('models'))
|
||
def stop(signum, frame):
|
||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||
signal.signal(signal.SIGTERM, stop)
|
||
signal.signal(signal.SIGINT, stop)
|
||
try:
|
||
server.serve_forever(poll_interval=.2)
|
||
finally:
|
||
server.server_close()
|
||
reconcile(engine, admission)
|
||
os.close(lock_fd)
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|