147 lines
6.6 KiB
Python
147 lines
6.6 KiB
Python
"""启动、检查并验证远端 d3-nano 服务;由 tools/Deploy-D3Nano.ps1 通过 SSH 调用。
|
||
|
||
start 用虚拟环境的 python 拉起服务(分离进程,脱离 SSH 会话),等待 /health 就绪。
|
||
status 打印当前 /health、监听端口与显存占用。
|
||
probe 用真实相机 JPEG 发送 noul 请求,核对结果与耗时。
|
||
"""
|
||
import argparse
|
||
import json
|
||
import os
|
||
import runpy
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import urllib.request
|
||
from pathlib import Path
|
||
|
||
HEALTH_TIMEOUT_SECONDS = 300
|
||
|
||
|
||
def get_json(url, timeout=10):
|
||
with urllib.request.urlopen(url, timeout=timeout) as response:
|
||
return json.loads(response.read().decode("utf-8"))
|
||
|
||
|
||
def health(port):
|
||
try:
|
||
data = get_json(f"http://127.0.0.1:{port}/health")
|
||
except Exception:
|
||
return {"status": "missing"}
|
||
modalities = data.get("modalities", [])
|
||
ready = data.get("status") == "ready" and data.get("model") == "d3-nano" and "image" in modalities
|
||
data["ready"] = bool(ready)
|
||
return data
|
||
|
||
|
||
def nvidia_memory():
|
||
try:
|
||
out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used,memory.total", "--format=csv,noheader"],
|
||
capture_output=True, text=True, timeout=20).stdout.strip()
|
||
except Exception as error:
|
||
return {"error": repr(error)}
|
||
return {"nvidia_smi": out}
|
||
|
||
|
||
def start(root, port, script, log_dir, verify=None):
|
||
"""验收模式在同一会话持有测试进程;复用已有服务时只做验证。"""
|
||
state = health(port)
|
||
if state.get("ready"):
|
||
if verify:
|
||
verify()
|
||
return {"action": "reuse", "health": state}
|
||
python = Path(root) / ".venv" / "Scripts" / "python.exe"
|
||
if not python.exists():
|
||
raise SystemExit(f"缺少虚拟环境解释器:{python}")
|
||
if not Path(script).exists():
|
||
raise SystemExit(f"缺少服务脚本:{script}(请先部署 SopHelper win-x64 包)")
|
||
Path(log_dir).mkdir(parents=True, exist_ok=True)
|
||
stdout = (Path(log_dir) / "djev-service.stdout.log").open("w", encoding="utf-8")
|
||
stderr = (Path(log_dir) / "djev-service.stderr.log").open("w", encoding="utf-8")
|
||
creationflags = 0
|
||
if os.name == "nt":
|
||
creationflags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
|
||
process = subprocess.Popen([str(python), "-u", str(script), "--root", str(root), "--port", str(port),
|
||
"--log-dir", str(log_dir)], cwd=str(root), stdout=stdout, stderr=stderr,
|
||
stdin=subprocess.DEVNULL, creationflags=creationflags, close_fds=True)
|
||
try:
|
||
if verify is None:
|
||
(Path(root) / "server.pid").write_text(str(process.pid), encoding="ascii")
|
||
deadline = time.monotonic() + HEALTH_TIMEOUT_SECONDS
|
||
last = {"status": "starting"}
|
||
while time.monotonic() < deadline:
|
||
last = health(port)
|
||
if last.get("ready"):
|
||
if verify:
|
||
verify()
|
||
return {"action": "started", "pid": process.pid, "health": last, "logs": str(log_dir)}
|
||
if process.poll() is not None:
|
||
raise SystemExit(f"d3-nano 启动失败,退出码 {process.returncode},日志:{log_dir}")
|
||
time.sleep(2)
|
||
raise SystemExit(f"等待 d3-nano 就绪超时({HEALTH_TIMEOUT_SECONDS}s),日志:{log_dir},最后状态:{last}")
|
||
finally:
|
||
# 仅回收本次验收创建的进程树,包含 Windows 虚拟环境派生的 Python 子进程。
|
||
if verify and process.poll() is None:
|
||
subprocess.run(["taskkill", "/pid", str(process.pid), "/t", "/f"], check=True)
|
||
process.wait(timeout=10)
|
||
|
||
|
||
def probe(port, image_root, repeat):
|
||
script = Path(__file__).with_name("probe-d3nano.py")
|
||
if not script.exists():
|
||
raise SystemExit(f"缺少验证脚本:{script}")
|
||
if not Path(image_root).exists():
|
||
raise SystemExit(f"缺少验证图片目录:{image_root}")
|
||
environment = dict(os.environ, PYTHONIOENCODING="utf-8")
|
||
result = subprocess.run([sys.executable, str(script), "--port", str(port), "--image-root", str(image_root),
|
||
"--repeat", str(repeat)], capture_output=True, text=True, encoding="utf-8",
|
||
errors="replace", env=environment, timeout=900)
|
||
if result.returncode:
|
||
print((result.stdout or "")[-2000:])
|
||
print((result.stderr or "")[-4000:])
|
||
raise SystemExit("真实图片请求验证失败")
|
||
print(result.stdout.strip())
|
||
|
||
|
||
def serve(root, port, script, log_dir):
|
||
"""前台运行模型服务,供计划任务承载(SSH 会话结束时子进程会被作业对象回收,不能用分离进程)。"""
|
||
if not Path(script).exists():
|
||
raise SystemExit(f"缺少服务脚本:{script}(请先部署 SopHelper win-x64 包)")
|
||
Path(log_dir).mkdir(parents=True, exist_ok=True)
|
||
(Path(root) / "server.pid").write_text(str(os.getpid()), encoding="ascii")
|
||
sys.argv = [str(script), "--root", str(root), "--port", str(port), "--log-dir", str(log_dir)]
|
||
runpy.run_path(str(script), run_name="__main__")
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument("command", choices=["serve", "start", "status", "probe", "verify"])
|
||
parser.add_argument("--root", default=r"C:\sophelper\current\D3Nano")
|
||
parser.add_argument("--port", type=int, default=8766)
|
||
parser.add_argument("--script", default=r"C:\sophelper\current\services\start_d3_lite_local.py")
|
||
parser.add_argument("--log-dir")
|
||
parser.add_argument("--image-root", default=r"C:\sophelper\current\D3Nano\benchmark")
|
||
parser.add_argument("--repeat", type=int, default=3)
|
||
args = parser.parse_args()
|
||
log_dir = args.log_dir or str(Path(args.root) / "logs")
|
||
if args.command == "serve":
|
||
serve(args.root, args.port, args.script, log_dir)
|
||
return
|
||
if args.command == "start":
|
||
report = start(args.root, args.port, args.script, log_dir)
|
||
elif args.command == "verify":
|
||
report = start(args.root, args.port, args.script, log_dir,
|
||
lambda: probe(args.port, args.image_root, args.repeat))
|
||
elif args.command == "status":
|
||
report = {"health": health(args.port), "pid_file": (Path(args.root) / "server.pid").read_text(encoding="ascii")
|
||
if (Path(args.root) / "server.pid").exists() else None}
|
||
report.update(nvidia_memory())
|
||
else:
|
||
probe(args.port, args.image_root, args.repeat)
|
||
report = {"health": health(args.port)}
|
||
report.update(nvidia_memory())
|
||
print(json.dumps(report, ensure_ascii=False))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|