cmvr-visual/scripts/local_dev.py

571 lines
22 KiB
Python
Raw Normal View History

"""Run the CMVR business API and Vite locally on Windows; never starts SSH/models.
Usage: backend/.venv/Scripts/python.exe scripts/local_dev.py start|status|stop
Only .env.local is loaded. Values are literal, never executed or expanded.
"""
from __future__ import annotations
import argparse
from contextlib import contextmanager
import ctypes
from ctypes import wintypes
from dataclasses import dataclass
import json
import os
from pathlib import Path
import re
import shutil
import socket
import subprocess
import sys
import threading
import time
import uuid
from urllib.error import HTTPError, URLError
from urllib.request import Request, build_opener, ProxyHandler
ROOT = Path(__file__).resolve().parents[1]
STATE_NAME = "dev-processes.json"
@dataclass
class Service:
name: str
command: list[str]
cwd: Path
url: str
stop_file: Path | None = None
identity_file: Path | None = None
def read_env(path: Path) -> dict[str, str]:
"""Small literal dotenv subset: KEY=value, optional quotes/comments; no expansion."""
# 私有配置只按字面值解析,不能把密码中的 $ 或反引号当作脚本执行。
values = {}
for number, line in enumerate(path.read_text(encoding="utf-8-sig").splitlines(), 1):
line = line.strip()
if not line or line.startswith("#"):
continue
match = re.fullmatch(r"([A-Za-z_][A-Za-z_0-9]*)\s*=\s*(.*)", line)
if not match:
raise ValueError(f"Invalid environment assignment at line {number}")
key, value = match.groups()
if value.startswith('"'):
try:
decoded, end = json.JSONDecoder().raw_decode(value)
except ValueError:
raise ValueError(f"Invalid quoted environment value at line {number}") from None
if value[end:].strip() and not value[end:].lstrip().startswith("#"):
raise ValueError(f"Invalid quoted environment value at line {number}")
value = decoded
elif value.startswith("'"):
end = value.find("'", 1)
if end < 0 or (
value[end + 1 :].strip() and not value[end + 1 :].lstrip().startswith("#")
):
raise ValueError(f"Invalid quoted environment value at line {number}")
value = value[1:end]
else:
value = re.split(r"\s+#", value, maxsplit=1)[0].rstrip()
values[key] = value
return values
def _kernel():
if os.name != "nt":
raise RuntimeError("This local process manager requires Windows")
k = ctypes.WinDLL("kernel32", use_last_error=True)
k.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
k.OpenProcess.restype = wintypes.HANDLE
k.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4
k.GetProcessTimes.restype = wintypes.BOOL
k.QueryFullProcessImageNameW.argtypes = [
wintypes.HANDLE,
wintypes.DWORD,
wintypes.LPWSTR,
ctypes.POINTER(wintypes.DWORD),
]
k.QueryFullProcessImageNameW.restype = wintypes.BOOL
k.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
k.WaitForSingleObject.restype = wintypes.DWORD
k.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
k.TerminateProcess.restype = wintypes.BOOL
k.CloseHandle.argtypes = [wintypes.HANDLE]
k.CloseHandle.restype = wintypes.BOOL
return k
def _handle_identity(k, handle, pid):
if k.WaitForSingleObject(handle, 0) != 258: # WAIT_TIMEOUT = still running
return None
times = [wintypes.FILETIME() for _ in range(4)]
if not k.GetProcessTimes(handle, *(ctypes.byref(value) for value in times)):
raise OSError("Cannot read local process creation time")
size = wintypes.DWORD(32768)
executable = ctypes.create_unicode_buffer(size.value)
if not k.QueryFullProcessImageNameW(handle, 0, executable, ctypes.byref(size)):
raise OSError("Cannot read local process executable")
return {
"pid": pid,
"created": (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime,
"executable": os.path.normcase(executable.value),
}
def process_identity(pid: int):
k = _kernel()
handle = k.OpenProcess(0x1000 | 0x100000, False, int(pid))
if not handle:
# ERROR_INVALID_PARAMETER indicates a PID that no longer exists.
if ctypes.get_last_error() == 87:
return None
raise OSError("Cannot inspect local process; it may belong to another user")
try:
return _handle_identity(k, handle, int(pid))
finally:
k.CloseHandle(handle)
def record_process(pid, command, name):
identity = process_identity(pid)
if identity is None:
raise RuntimeError(f"{name} exited before its process identity could be recorded")
return {**identity, "command": [str(part) for part in command], "name": name}
def _matches(identity, record):
return identity is not None and all(
identity.get(key) == record.get(key) for key in ("pid", "created", "executable")
)
def process_matches(record):
return _matches(process_identity(record["pid"]), record)
def stop_owned(record, root, timeout=20):
# PID 会被系统复用,必须连同创建时间及可执行文件身份核对后才允许停止。
"""Use one verified process handle, eliminating PID-reuse races at termination."""
k = _kernel()
handle = k.OpenProcess(0x1000 | 0x100000 | 1, False, int(record["pid"]))
if not handle:
if ctypes.get_last_error() == 87:
return False
raise OSError("Cannot open local process for shutdown")
try:
if not _matches(_handle_identity(k, handle, record["pid"]), record):
return False
stop_file = record.get("stop_file")
if stop_file:
target = Path(stop_file).resolve()
if not target.is_relative_to((Path(root) / ".local").resolve()):
raise ValueError("API shutdown marker must stay inside .local")
target.touch()
# Let uvicorn execute its lifespan shutdown, including coordinator cleanup.
if k.WaitForSingleObject(handle, int(timeout * 1000)) == 0:
target.unlink(missing_ok=True)
return True
raise RuntimeError("API graceful shutdown timed out; process retained for inspection")
if not k.TerminateProcess(handle, 0):
raise OSError("Could not stop the verified local process")
if k.WaitForSingleObject(handle, max(1000, int(timeout * 1000))) != 0:
raise RuntimeError("Local process did not exit after shutdown")
return True
finally:
k.CloseHandle(handle)
def http_health(url):
"""Bypass ambient proxy settings for loopback and never return raw response/errors."""
try:
opener = build_opener(ProxyHandler({}))
try:
response = opener.open(Request(url), timeout=4)
except HTTPError as error:
response = error
with response:
raw = response.read(256 * 1024)
try:
payload = json.loads(raw)
except (ValueError, UnicodeError):
payload = None
return response.code, payload
except (OSError, URLError, TimeoutError):
return None, None
def service_status(record, url, kind):
result = {"running": False, "ready": False, "upstream_ready": None}
if not record or not process_matches(record):
return result
result["running"] = True
code, body = http_health(url)
if kind == "api":
checks = body.get("checks", {}) if isinstance(body, dict) else {}
result["checks"] = {
name: checks.get(name) is True
for name in ("database", "coordinator", "accepting", "upstream_protocol")
}
result["ready"] = code in (200, 503) and all(
result["checks"][name] for name in ("database", "coordinator", "accepting")
)
result["upstream_ready"] = checks.get("upstream_protocol") is True
else:
result["ready"] = code == 200
# A child may have exited while the request was in flight.
if not process_matches(record):
result.update(running=False, ready=False, upstream_ready=None)
return result
def _write_state(root, state):
directory = Path(root) / ".local"
directory.mkdir(parents=True, exist_ok=True)
path = directory / STATE_NAME
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
temporary.replace(path)
def read_state(root):
path = Path(root) / ".local" / STATE_NAME
if not path.exists():
return {"version": 1, "root": str(Path(root).resolve()), "processes": {}}
state = json.loads(path.read_text(encoding="utf-8"))
if state.get("version") != 1 or state.get("root") != str(Path(root).resolve()):
raise ValueError("Local process state belongs to a different workspace or version")
for name, record in state.get("processes", {}).items():
if (
name not in {"api", "frontend"}
or record.get("name") != name
or not isinstance(record.get("command"), list)
):
raise ValueError("Invalid local process state")
return state
@contextmanager
def launcher_lock(root):
import msvcrt
directory = Path(root) / ".local"
directory.mkdir(parents=True, exist_ok=True)
with (directory / "launcher.lock").open("a+b") as stream:
stream.seek(0)
stream.write(b"0")
stream.flush()
stream.seek(0)
try:
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
except OSError:
raise RuntimeError("Another local start/stop/status command is running") from None
try:
yield
finally:
stream.seek(0)
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
def start_services(root, services, env, timeout=45):
state = read_state(root)
if any(process_matches(record) for record in state["processes"].values()):
raise RuntimeError(
"Owned local processes already exist; run status, then stop before starting again"
)
state["processes"] = {}
logs = Path(root) / ".local/logs"
logs.mkdir(parents=True, exist_ok=True)
started = []
try:
for service in services:
with (logs / f"{service.name}.log").open("ab", buffering=0) as log:
log.write(f"\n--- local start {time.strftime('%Y-%m-%d %H:%M:%S')} ---\n".encode())
process = subprocess.Popen(
service.command,
cwd=service.cwd,
env=env,
stdin=subprocess.DEVNULL,
stdout=log,
stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW,
)
started.append(process)
deadline = time.monotonic() + timeout
# Record the bootstrap immediately: a failed interpreter handshake must
# still request graceful shutdown rather than leak the child.
record = record_process(process.pid, service.command, service.name)
if service.stop_file:
record["stop_file"] = str(service.stop_file)
record["url"] = service.url
state["processes"][service.name] = record
_write_state(root, state)
pid = process.pid
if service.identity_file:
while not service.identity_file.exists():
if process.poll() is not None:
raise RuntimeError(
f"{service.name} exited during startup; inspect .local/logs/{service.name}.log"
)
if time.monotonic() >= deadline:
raise RuntimeError(f"{service.name} did not report its interpreter PID")
time.sleep(0.1)
pid = int(service.identity_file.read_text())
service.identity_file.unlink()
record = record_process(pid, service.command, service.name)
if process.pid != pid:
record["bootstrap"] = record_process(process.pid, service.command, service.name)
if service.stop_file:
record["stop_file"] = str(service.stop_file)
record["url"] = service.url
state["processes"][service.name] = record
_write_state(root, state)
while True:
if process.poll() is not None or not process_matches(record):
raise RuntimeError(
f"{service.name} exited during startup; inspect .local/logs/{service.name}.log"
)
status = service_status(record, service.url, service.name)
if status["ready"]:
break
if time.monotonic() >= deadline:
raise RuntimeError(
f"{service.name} readiness timed out; inspect .local/logs/{service.name}.log"
)
time.sleep(0.3)
# Recheck the API after Vite starts; an early API crash is not a successful start.
statuses = {
service.name: service_status(
state["processes"][service.name], service.url, service.name
)
for service in services
}
if not all(value["ready"] for value in statuses.values()):
raise RuntimeError("A local service lost readiness during startup; inspect .local/logs")
return statuses
except BaseException:
retained = {}
for name, record in reversed(list(state["processes"].items())):
try:
stop_owned(record, root)
except (OSError, RuntimeError):
retained[name] = record
state["processes"] = retained
_write_state(root, state)
for process in started:
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass # A timed-out graceful shutdown remains recorded for inspection.
raise
def local_environment(root):
path = Path(root) / ".env.local"
if not path.exists():
raise ValueError("Create private .env.local from .env.local.example before starting")
env = dict(os.environ)
env.update(read_env(path))
workspace = Path(env.get("WORKSPACE_ROOT") or Path(root) / ".local/workspace")
if not workspace.is_absolute():
workspace = Path(root) / workspace
workspace = workspace.resolve()
workspace.mkdir(parents=True, exist_ok=True)
env["WORKSPACE_ROOT"] = str(workspace)
env.setdefault("COOKIE_SECURE", "false")
env.setdefault("PUBLIC_ACCESS", "false")
env["VITE_API_PROXY"] = "http://127.0.0.1:8000"
# This is the real-service helper; SQLite preview remains an explicit separate path.
if env.get("CMVR_MODE") != "production":
raise ValueError("Local real-service launcher requires CMVR_MODE=production")
if env.get("COOKIE_SECURE", "").lower() not in {"false", "0", "no", "off"}:
raise ValueError("Loopback HTTP requires COOKIE_SECURE=false")
if env.get("PUBLIC_ACCESS", "").lower() not in {"false", "0", "no", "off"}:
raise ValueError("Local development requires PUBLIC_ACCESS=false")
env["PYTHONUTF8"] = "1"
return env
def build_services(root, env):
root = Path(root).resolve()
python = root / "backend/.venv/Scripts/python.exe"
if not python.is_file():
raise ValueError("Create backend/.venv and install backend/requirements.txt first")
node = (
env.get("NODE_BIN")
or env.get("CMVR_NODE_EXE")
or shutil.which("node", path=env.get("PATH"))
)
if not node and Path("E:/developmentTool/nodejs/node.exe").is_file():
node = "E:/developmentTool/nodejs/node.exe"
if not node or not Path(node).is_file():
raise ValueError("Node is missing; set NODE_BIN to node.exe or add Node to PATH")
vite = root / "frontend/node_modules/vite/bin/vite.js"
if not vite.is_file():
raise ValueError("Install frontend dependencies with pnpm install --frozen-lockfile first")
run_id = uuid.uuid4().hex
local = root / ".local"
stop_file = local / f"api-{run_id}.stop"
identity_file = local / f"api-{run_id}.pid"
return [
Service(
"api",
[
str(python),
str(root / "scripts/local_dev.py"),
"_serve-api",
"--stop-file",
str(stop_file),
"--identity-file",
str(identity_file),
],
root,
"http://127.0.0.1:8000/api/ready",
stop_file,
identity_file,
),
Service(
"frontend",
[
str(Path(node).resolve()),
str(vite),
"--host",
"127.0.0.1",
"--port",
"5173",
"--strictPort",
],
root / "frontend",
"http://127.0.0.1:5173/",
),
]
def require_free_ports():
for port in (8000, 5173):
with socket.socket() as listener:
try:
listener.bind(("127.0.0.1", port))
except OSError:
raise RuntimeError(
f"127.0.0.1:{port} is already in use; inspect its owner before starting"
) from None
def print_status(root):
state = read_state(root)
results = {}
for name, url in (
("api", "http://127.0.0.1:8000/api/ready"),
("frontend", "http://127.0.0.1:5173/"),
):
status = service_status(state["processes"].get(name), url, name)
results[name] = status
text = (
"ready"
if status["ready"]
else "running, not ready"
if status["running"]
else "stopped (or recorded identity no longer matches)"
)
print(f"{name}: {text}")
if name == "api" and status["running"]:
print(
" "
+ ", ".join(
f"{key}={'ok' if value else 'unavailable'}"
for key, value in status.get("checks", {}).items()
)
)
print("Frontend: http://127.0.0.1:5173 | API: http://127.0.0.1:8000")
print(f"Logs: {Path(root) / '.local/logs'}")
return results
def serve_api(stop_file, identity_file, port=8000):
# The Windows venv redirector creates a second interpreter. Report the actual
# interpreter PID so stop never mistakes the redirector for the uvicorn server.
identity_path = Path(identity_file)
temporary = identity_path.with_suffix(".tmp")
temporary.write_text(str(os.getpid()), encoding="ascii")
temporary.replace(identity_path)
sys.path.insert(0, str(ROOT / "backend"))
import uvicorn
# SSE 连接可以一直打开,限制连接排空时间,让 API 正常进入 lifespan 回收。
# 关闭的仅是本机 HTTP 客户端与协调器,不取消持久任务,也不停止共享 Qwen。
server = uvicorn.Server(
uvicorn.Config(
"app.main:app", host="127.0.0.1", port=port, workers=1, timeout_graceful_shutdown=8
)
)
def watch_stop():
while not server.should_exit:
if Path(stop_file).exists():
server.should_exit = True
return
time.sleep(0.2)
threading.Thread(target=watch_stop, daemon=True).start()
server.run()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("start", "status", "stop", "_serve-api"))
parser.add_argument(
"--timeout", type=float, default=45, help="startup readiness timeout per service (seconds)"
)
parser.add_argument("--stop-file", help=argparse.SUPPRESS)
parser.add_argument("--identity-file", help=argparse.SUPPRESS)
args = parser.parse_args(argv)
if args.action == "_serve-api":
serve_api(args.stop_file, args.identity_file)
return 0
if os.name != "nt":
parser.error("This local helper requires Windows")
try:
with launcher_lock(ROOT):
if args.action == "start":
env = local_environment(ROOT)
services = build_services(ROOT, env)
require_free_ports()
statuses = start_services(ROOT, services, env, timeout=max(1, args.timeout))
print("Local API and frontend started.")
if not statuses["api"]["upstream_ready"]:
print(
"Inference protocol unavailable: local website is running; check the separately managed model tunnel/service."
)
print_status(ROOT)
elif args.action == "status":
statuses = print_status(ROOT)
return 0 if all(item["ready"] for item in statuses.values()) else 1
else:
state = read_state(ROOT)
retained = {}
for name, record in reversed(list(state["processes"].items())):
try:
stopped = stop_owned(record, ROOT)
print(
f"{name}: {'stopped' if stopped else 'already stopped or identity changed; untouched'}"
)
except (OSError, RuntimeError, ValueError) as error:
retained[name] = record
print(f"{name}: {error}", file=sys.stderr)
state["processes"] = retained
_write_state(ROOT, state)
if not retained:
print(
"Owned local web processes stopped. Model/SSH services are managed separately."
)
return 1 if retained else 0
return 0
except (ValueError, RuntimeError, OSError) as error:
print(f"Local development: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())