From e8432647ffbd17db3cb2525eef428d71a5bbe545 Mon Sep 17 00:00:00 2001 From: Bifang <915779419@qq.com> Date: Fri, 16 Oct 2026 15:20:34 +0800 Subject: [PATCH] first commit --- .gitignore | 9 + README.md | 72 ++ backend/.env.example | 19 + backend/app/__init__.py | 1 + backend/app/main.py | 614 +++++++++++++++++ backend/requirements.txt | 5 + .../compute-service-manager.service.example | 18 + deploy/install.sh | 158 +++++ deploy/nginx.conf.example | 21 + frontend/index.html | 15 + frontend/package.json | 24 + frontend/src/App.tsx | 631 ++++++++++++++++++ frontend/src/main.tsx | 11 + frontend/src/styles.css | 483 ++++++++++++++ frontend/src/vite-env.d.ts | 1 + frontend/tsconfig.json | 21 + frontend/vite.config.ts | 13 + 17 files changed, 2116 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 backend/.env.example create mode 100644 backend/app/__init__.py create mode 100644 backend/app/main.py create mode 100644 backend/requirements.txt create mode 100644 deploy/compute-service-manager.service.example create mode 100644 deploy/install.sh create mode 100644 deploy/nginx.conf.example create mode 100644 frontend/index.html create mode 100644 frontend/package.json create mode 100644 frontend/src/App.tsx create mode 100644 frontend/src/main.tsx create mode 100644 frontend/src/styles.css create mode 100644 frontend/src/vite-env.d.ts create mode 100644 frontend/tsconfig.json create mode 100644 frontend/vite.config.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9496837 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +__pycache__/ +*.py[cod] +.env +backend/.venv/ +backend/data/ +frontend/node_modules/ +frontend/dist/ +*.log + diff --git a/README.md b/README.md new file mode 100644 index 0000000..db547da --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# 本机算力服务台 + +前后端分离的 Python 服务管理面板。管理 API 和前端部署在被管理的 Linux 服务器上,API 使用当前 Linux 用户的 `systemd --user` 管理服务,不需要 SSH 或容器化模型。 + +## 功能 + +- 登记已有的 Conda 或 `.venv` Python 解释器、脚本、工作目录、启动参数和环境变量。 +- 通过应用卡片启动、停止、重启服务,并读取状态、PID 和 journal 日志。 +- 后端内置本机资源采集,监控 CPU、内存、磁盘、NVIDIA GPU、网络、温度与运行时间;不依赖 Nezha Agent 或远程监控 API。 +- 每个应用有独立的 systemd user unit;面板 API 重启后,服务状态仍由 systemd 托管。 +- 前端只发送结构化配置和固定操作;后端不接受任意 shell 命令。 + +## 目录 + +```text +backend/ FastAPI API、本机 systemd 管理和 SQLite 配置存储 +frontend/ React + Vite 管理面板 +``` + +## Linux 服务器部署 + +推荐使用交互式部署脚本。以将来运行服务的普通 Linux 账号,在项目目录执行: + +```bash +bash deploy/install.sh +``` + +脚本会引导设置部署目录、访问端口和监听地址,创建 Python 虚拟环境、构建前端、生成管理密钥,并安装和启动 `systemd --user` 服务。默认监听 `0.0.0.0:8199`,用于可信内网访问;如需公网访问,请放在 HTTPS 反向代理后面并通过防火墙限制来源。面板和 API 同源提供,无需单独配置 Nginx 才能启动。 + +登记的应用服务与管理面板以同一个 Linux 账号运行。脚本会询问是否启用 linger,使面板在退出 SSH 后继续运行;也可以稍后手动执行 `sudo loginctl enable-linger "$USER"`。 + +```bash +systemctl --user status compute-service-manager +systemctl --user restart compute-service-manager +journalctl --user -u compute-service-manager -f +``` + +管理密钥保存在 `~/.config/compute-service-manager/manager.env`,权限为 `600`。首次打开面板后,在「设置」页填入部署时显示的密钥。服务进程读取该文件,前端构建产物由后端同源提供。 + +资源监控直接运行在本机后端:CPU、内存、磁盘和网络由 `psutil` 读取;NVIDIA GPU 指标在本机存在 `nvidia-smi` 时自动采集,其余 GPU 或不可用的传感器显示为空。指标字段参考 Nezha 的 [`Host` / `HostState`](https://github.com/nezhahq/nezha/blob/master/model/host.go) 语义,采集和展示均由本项目负责,无需部署 Nezha Agent 或配置 Nezha API。 + +如需手动配置 systemd、Nginx,可继续参考 `deploy/compute-service-manager.service.example` 和 `deploy/nginx.conf.example`。 + +前端构建和开发: + +```bash +cd frontend +npm install +npm run dev +``` + +Vite 开发服务器默认将 `/api` 代理到 `127.0.0.1:8000`。Linux 部署脚本会先生成 `frontend/dist`,再由 FastAPI 后端同源托管静态页面与 API;源代码仍保持前后端分离。 + +## 添加服务示例 + +假设环境解释器是 `/opt/conda/envs/gemma/bin/python`,启动程序位于 `/dep/Bfmodeltest/gemma4_31b_deploy/serve.py`: + +- Python 解释器:`/opt/conda/envs/gemma/bin/python` +- 启动脚本:`/dep/Bfmodeltest/gemma4_31b_deploy/serve.py` +- 工作目录:`/dep/Bfmodeltest/gemma4_31b_deploy` +- 参数 JSON:`["--port", "8000"]` +- 环境变量 JSON:`{"CUDA_VISIBLE_DEVICES": "0"}` + +首次访问页面时,在侧边栏「设置」页填入 `PANEL_API_TOKEN`。应用登记后即可从卡片启停。 + +## 当前 MVP 边界 + +- 管理权限采用单个共享 API 密钥,持有密钥的人可以登记并以服务账号身份启动任意可访问的 Python 程序;适合信任使用者的内网试用,尚未实现用户账号、团队角色和操作审计。 +- 服务以运行面板的 Linux 用户身份启动,不支持为不同应用选择不同 Linux 用户。 +- 本机资源采集不可用时,资源监控显示为空。HTTP 健康探测和应用分组尚未实现。 +- 环境变量会写入本机应用启动器和 SQLite 配置,文件权限限制为当前用户;环境文件也应限制为服务账号可读。 +- `systemd --user` 需要登录会话管理器可用;服务器部署时应启用 linger 并设置运行时总线环境变量。 diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..da4f6d6 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,19 @@ +# Set this to a long random value before exposing the panel to your team. +PANEL_API_TOKEN=replace-with-a-long-random-token + +# SQLite database location. The account running the API must be able to write here. +PANEL_DATABASE_PATH=./data/panel.db + +# systemd user manager runtime. Replace 1000 with the Linux account UID. +XDG_RUNTIME_DIR=/run/user/1000 +DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus + +# Comma-separated browser origins allowed to call the API. +PANEL_CORS_ORIGINS=http://localhost:5173 + +# Optional Nezha V2 monitor source. Use a read-only PAT with +# nezha:inventory:read and restrict it to the target server ID when possible. +NEZHA_URL=https://nezha.example.com +NEZHA_TOKEN=nzp_replace-with-read-only-token +NEZHA_SERVER_ID=1 + diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/app/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..b85b03a --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,614 @@ +"""Local service manager API backed by the current user's systemd instance.""" + +from __future__ import annotations + +import asyncio +import csv +import hmac +import json +import os +import platform +import re +import shlex +import shutil +import sqlite3 +import socket +import subprocess +import time +import uuid +from contextlib import asynccontextmanager +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Literal + +import psutil +from fastapi import Depends, FastAPI, Header, HTTPException, Query, Response +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import FileResponse +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel, Field, field_validator + + +BASE_DIR = Path(__file__).resolve().parents[1] +DATABASE_PATH = Path(os.getenv("PANEL_DATABASE_PATH", str(Path.home() / ".local" / "share" / "compute-service-manager" / "panel.db"))) +SERVICE_HOME = Path(os.getenv("PANEL_SERVICE_HOME", str(Path.home() / ".local" / "share" / "compute-service-manager"))) +UNIT_DIR = Path(os.getenv("PANEL_UNIT_DIR", str(Path.home() / ".config" / "systemd" / "user"))) +API_TOKEN = os.getenv("PANEL_API_TOKEN", "") +ENV_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +_operation_lock = asyncio.Lock() + + +class AppInput(BaseModel): + """Fields needed to run a Python service without accepting arbitrary shell text.""" + + name: str = Field(min_length=1, max_length=80) + description: str = Field(default="", max_length=240) + python_path: str = Field(min_length=1, max_length=1000) + script_path: str = Field(min_length=1, max_length=1000) + working_dir: str = Field(min_length=1, max_length=1000) + args: list[str] = Field(default_factory=list, max_length=100) + env: dict[str, str] = Field(default_factory=dict, max_length=100) + + @field_validator("name") + @classmethod + def trim_name(cls, value: str) -> str: + value = value.strip() + if not value or any(ord(char) < 32 for char in value): + raise ValueError("应用名称不能为空,也不能包含控制字符") + return value + + @field_validator("python_path", "script_path", "working_dir") + @classmethod + def require_absolute_path(cls, value: str) -> str: + if any(ord(char) < 32 for char in value): + raise ValueError("路径不能包含控制字符") + candidate = Path(value).expanduser() + if not candidate.is_absolute(): + raise ValueError("路径必须是绝对路径") + return str(candidate) + + @field_validator("env") + @classmethod + def validate_environment(cls, value: dict[str, str]) -> dict[str, str]: + for key in value: + if not ENV_KEY_PATTERN.fullmatch(key): + raise ValueError(f"无效的环境变量名:{key}") + if "\x00" in value[key]: + raise ValueError(f"环境变量 {key} 不能包含 NUL 字符") + return value + + @field_validator("args") + @classmethod + def validate_args(cls, value: list[str]) -> list[str]: + if any("\x00" in part for part in value): + raise ValueError("启动参数不能包含 NUL 字符") + return value + + +class AppRecord(AppInput): + id: str + status: Literal["running", "stopped", "failed", "unknown"] = "stopped" + pid: int | None = None + active_since: str | None = None + created_at: str + updated_at: str + + +class AppAction(BaseModel): + action: Literal["start", "stop", "restart"] + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +class LocalSystemMonitor: + """Collect host metrics in-process using local OS counters, not a remote monitor API.""" + + def __init__(self) -> None: + self.latest: dict[str, Any] | None = None + self.error: str | None = None + self._last_network = psutil.net_io_counters() + self._last_network_at = time.monotonic() + + @staticmethod + def _cpu_names() -> list[str]: + name = platform.processor().strip() + if not name and Path("/proc/cpuinfo").exists(): + try: + for line in Path("/proc/cpuinfo").read_text(errors="replace").splitlines(): + if line.lower().startswith(("model name", "hardware")) and ":" in line: + name = line.split(":", 1)[1].strip() + if name: + break + except OSError: + pass + return [name or platform.machine() or "CPU"] + + @staticmethod + def _gpu_metrics() -> tuple[list[str], list[dict[str, Any]]]: + """Read NVIDIA telemetry when the vendor utility is installed; other GPUs stay empty.""" + command = shutil.which("nvidia-smi") + if not command: + return [], [] + try: + result = subprocess.run( + [command, "--query-gpu=index,name,utilization.gpu,memory.used,memory.total", "--format=csv,noheader,nounits"], + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=3, + ) + except (OSError, subprocess.TimeoutExpired): + return [], [] + if result.returncode != 0: + return [], [] + names: list[str] = [] + gpus: list[dict[str, Any]] = [] + for row in csv.reader(result.stdout.splitlines(), skipinitialspace=True): + if len(row) < 5: + continue + try: + index = int(row[0].strip()) + utilization = float(row[2].strip()) + memory_used = float(row[3].strip()) + memory_total = float(row[4].strip()) + except ValueError: + continue + name = row[1].strip() + names.append(name) + gpus.append({ + "index": index, + "name": name, + "utilization": utilization, + "memory_used_mb": memory_used, + "memory_total_mb": memory_total, + }) + return names, gpus + + def collect(self) -> dict[str, Any]: + """Build a Nezha-shaped local snapshot so the existing dashboard can render it.""" + # A short blocking sample is safe here because collect() runs in a worker thread. + cpu_percent = psutil.cpu_percent(interval=0.25) + captured_at = datetime.now(timezone.utc) + memory = psutil.virtual_memory() + disk_path = Path.home().anchor or os.path.abspath(os.sep) + disk = psutil.disk_usage(disk_path) + network = psutil.net_io_counters() + now = time.monotonic() + elapsed = max(now - self._last_network_at, 0.001) + incoming = max(network.bytes_recv - self._last_network.bytes_recv, 0) + outgoing = max(network.bytes_sent - self._last_network.bytes_sent, 0) + self._last_network, self._last_network_at = network, now + cpu_names = self._cpu_names() + gpu_names, gpus = self._gpu_metrics() + try: + load_1m = os.getloadavg()[0] + except (AttributeError, OSError): + load_1m = None + try: + temperatures = [ + {"name": name, "temperature": entry.current} + for name, entries in psutil.sensors_temperatures(fahrenheit=False).items() + for entry in entries + if entry.current is not None + ] + except (AttributeError, NotImplementedError, OSError): + temperatures = [] + host_name = socket.gethostname() + uptime = max(int(time.time() - psutil.boot_time()), 0) + return { + "source": "local", + "connection_status": "connected", + "captured_at": captured_at.isoformat(), + "server": { + "id": None, + "name": host_name, + "platform": f"{platform.system()} {platform.release()}".strip(), + "cpu_names": cpu_names, + "gpu_names": gpu_names, + "uptime_seconds": uptime, + "last_active": captured_at.isoformat(), + "is_online": True, + }, + "cpu": { + "percent": cpu_percent, + "load_1m": load_1m, + "cores": psutil.cpu_count(logical=True), + "cpu_names": cpu_names, + }, + "memory": {"used_bytes": memory.used, "total_bytes": memory.total, "percent": memory.percent}, + "disk": {"path": disk_path, "used_bytes": disk.used, "total_bytes": disk.total, "percent": disk.percent}, + "gpus": gpus, + "network": {"in_bytes_per_second": incoming / elapsed, "out_bytes_per_second": outgoing / elapsed}, + "temperatures": temperatures, + "error": None, + } + + async def run(self) -> None: + """Sample outside the event loop and refresh the snapshot every five seconds.""" + while True: + try: + self.latest = await asyncio.to_thread(self.collect) + self.error = None + except asyncio.CancelledError: + raise + except Exception as exc: + self.latest = None + self.error = f"本机资源采集失败:{str(exc)[:240]}" + await asyncio.sleep(5) + + def snapshot(self) -> dict[str, Any]: + if self.latest is not None: + return dict(self.latest) + return { + "source": "local", + "connection_status": "unavailable" if self.error else "sampling", + "captured_at": None, + "server": None, + "cpu": None, + "memory": None, + "disk": None, + "gpus": [], + "network": None, + "temperatures": [], + "error": self.error, + } + + +system_monitor = LocalSystemMonitor() + + +def connect_db() -> sqlite3.Connection: + DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True) + connection = sqlite3.connect(DATABASE_PATH, timeout=10) + connection.row_factory = sqlite3.Row + return connection + + +def initialize_database() -> None: + with connect_db() as connection: + connection.execute( + """CREATE TABLE IF NOT EXISTS apps ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + python_path TEXT NOT NULL, + script_path TEXT NOT NULL, + working_dir TEXT NOT NULL, + args_json TEXT NOT NULL, + env_json TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + )""" + ) + # SQLite 配置包含应用环境变量,限制数据库文件只对管理账号可读写。 + DATABASE_PATH.chmod(0o600) + + +def require_token(authorization: str | None = Header(default=None)) -> None: + # API 操作统一使用服务端密钥鉴权,密钥不进入服务配置或日志。 + if not API_TOKEN: + raise HTTPException(status_code=503, detail="请先配置 PANEL_API_TOKEN") + supplied = authorization.removeprefix("Bearer ") if authorization else "" + if not supplied or not hmac.compare_digest(supplied, API_TOKEN): + raise HTTPException(status_code=401, detail="管理密钥无效") + + +def unit_name(app_id: str) -> str: + return f"compute-app-{app_id}.service" + + +def service_paths(app_id: str) -> tuple[Path, Path]: + return UNIT_DIR / unit_name(app_id), SERVICE_HOME / "launchers" / f"{app_id}.sh" + + +def fetch_row(app_id: str) -> sqlite3.Row: + with connect_db() as connection: + row = connection.execute("SELECT * FROM apps WHERE id = ?", (app_id,)).fetchone() + if row is None: + raise HTTPException(status_code=404, detail="应用不存在") + return row + + +def to_record(row: sqlite3.Row, service_state: dict[str, str] | None = None) -> AppRecord: + state = service_state or {} + active = state.get("ActiveState", "unknown") + status: Literal["running", "stopped", "failed", "unknown"] + if active == "active": + status = "running" + elif active in {"inactive", "deactivating"}: + status = "stopped" + elif active == "failed": + status = "failed" + else: + status = "unknown" + return AppRecord( + id=row["id"], + name=row["name"], + description=row["description"], + python_path=row["python_path"], + script_path=row["script_path"], + working_dir=row["working_dir"], + args=json.loads(row["args_json"]), + env=json.loads(row["env_json"]), + status=status, + pid=int(state["MainPID"]) if state.get("MainPID", "0").isdigit() and state["MainPID"] != "0" else None, + active_since=state.get("ActiveEnterTimestamp"), + created_at=row["created_at"], + updated_at=row["updated_at"], + ) + + +def systemctl(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]: + command = ["systemctl", "--user", *args] + try: + result = subprocess.run(command, text=True, capture_output=True, timeout=30, check=False) + except FileNotFoundError as exc: + raise HTTPException(status_code=503, detail="当前系统找不到 systemctl") from exc + except subprocess.TimeoutExpired as exc: + raise HTTPException(status_code=504, detail="systemd 操作超时") from exc + if check and result.returncode != 0: + message = (result.stderr or result.stdout).strip() or "systemd 操作失败" + raise HTTPException(status_code=409, detail=message[-1200:]) + return result + + +def journalctl(*args: str) -> subprocess.CompletedProcess[str]: + try: + return subprocess.run( + ["journalctl", "--user", *args], + text=True, + capture_output=True, + timeout=20, + check=False, + ) + except FileNotFoundError as exc: + raise HTTPException(status_code=503, detail="当前系统找不到 journalctl") from exc + except subprocess.TimeoutExpired as exc: + raise HTTPException(status_code=504, detail="读取服务日志超时") from exc + + +def read_unit_state(app_id: str) -> dict[str, str]: + result = systemctl( + "show", + unit_name(app_id), + "--property=ActiveState,MainPID,ActiveEnterTimestamp", + check=False, + ) + if result.returncode != 0: + return {"ActiveState": "inactive", "MainPID": "0"} + return dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line) + + +def check_runtime(app: AppInput) -> tuple[Path, Path, Path]: + python = Path(app.python_path).expanduser().resolve() + script = Path(app.script_path).expanduser().resolve() + working_dir = Path(app.working_dir).expanduser().resolve() + if not python.is_file() or not os.access(python, os.X_OK): + raise HTTPException(status_code=422, detail="Python 解释器不存在或不可执行") + if not script.is_file(): + raise HTTPException(status_code=422, detail="启动脚本不存在") + if not working_dir.is_dir(): + raise HTTPException(status_code=422, detail="工作目录不存在") + return python, script, working_dir + + +def write_service_files(app_id: str, app: AppInput) -> None: + python, script, working_dir = check_runtime(app) + unit_path, launcher_path = service_paths(app_id) + unit_path.parent.mkdir(parents=True, exist_ok=True) + launcher_path.parent.mkdir(parents=True, exist_ok=True) + + # 用 argv 列表和 shlex 转义生成启动器,不拼接用户提供的 shell 片段。 + command = [str(python), str(script), *app.args] + lines = ["#!/usr/bin/env bash", "set -euo pipefail", f"cd -- {shlex.quote(str(working_dir))}"] + lines.extend(f"export {key}={shlex.quote(value)}" for key, value in app.env.items()) + lines.append("exec " + " ".join(shlex.quote(part) for part in command)) + launcher_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + launcher_path.chmod(0o700) + + # 每个应用使用独立 user unit;重启面板进程不会丢失服务的托管状态。 + unit_path.write_text( + "\n".join( + [ + "[Unit]", + f"Description=Managed app: {app.name.replace('%', '%%')}", + "After=network.target", + "", + "[Service]", + "Type=simple", + f"WorkingDirectory={systemd_quote(str(working_dir))}", + f"ExecStart=/usr/bin/bash {systemd_quote(str(launcher_path))}", + "Restart=on-failure", + "RestartSec=5s", + "TimeoutStopSec=30s", + "KillMode=control-group", + "", + "[Install]", + "WantedBy=default.target", + "", + ] + ), + encoding="utf-8", + ) + unit_path.chmod(0o600) + + +def systemd_quote(value: str) -> str: + """Quote a single systemd unit argument, including spaces and quote marks.""" + return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%") + '"' + + +def save_app(app_id: str, app: AppInput) -> None: + timestamp = utc_now() + with connect_db() as connection: + connection.execute( + """INSERT INTO apps + (id, name, description, python_path, script_path, working_dir, args_json, env_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + app_id, + app.name, + app.description, + app.python_path, + app.script_path, + app.working_dir, + json.dumps(app.args), + json.dumps(app.env), + timestamp, + timestamp, + ), + ) + + +def update_app(app_id: str, app: AppInput) -> None: + with connect_db() as connection: + connection.execute( + """UPDATE apps SET name=?, description=?, python_path=?, script_path=?, working_dir=?, + args_json=?, env_json=?, updated_at=? WHERE id=?""", + ( + app.name, + app.description, + app.python_path, + app.script_path, + app.working_dir, + json.dumps(app.args), + json.dumps(app.env), + utc_now(), + app_id, + ), + ) + + +@asynccontextmanager +async def lifespan(_: FastAPI): + initialize_database() + monitor_task = asyncio.create_task(system_monitor.run()) + try: + yield + finally: + monitor_task.cancel() + await asyncio.gather(monitor_task, return_exceptions=True) + + +app = FastAPI(title="Compute Service Manager API", version="0.1.0", lifespan=lifespan) +origins = [item.strip() for item in os.getenv("PANEL_CORS_ORIGINS", "http://localhost:5173").split(",") if item.strip()] +app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials=False, + allow_methods=["GET", "POST", "PUT", "DELETE"], + allow_headers=["Authorization", "Content-Type"], +) + +# Production deployments serve the separately built frontend from the same origin. +FRONTEND_DIST = BASE_DIR.parent / "frontend" / "dist" +if (FRONTEND_DIST / "index.html").is_file(): + app.mount("/assets", StaticFiles(directory=FRONTEND_DIST / "assets"), name="frontend-assets") + + +@app.get("/api/health") +def health() -> dict[str, str]: + return {"status": "ok"} + + +@app.get("/api/system/metrics", dependencies=[Depends(require_token)]) +def system_metrics() -> dict[str, Any]: + """Return the latest local system-monitor snapshot without calling another service.""" + return system_monitor.snapshot() + + +@app.get("/api/apps", response_model=list[AppRecord], dependencies=[Depends(require_token)]) +def list_apps() -> list[AppRecord]: + with connect_db() as connection: + rows = connection.execute("SELECT * FROM apps ORDER BY created_at DESC").fetchall() + return [to_record(row, read_unit_state(row["id"])) for row in rows] + + +@app.post("/api/apps", response_model=AppRecord, status_code=201, dependencies=[Depends(require_token)]) +async def create_app(payload: AppInput) -> AppRecord: + check_runtime(payload) + app_id = str(uuid.uuid4()) + async with _operation_lock: + await asyncio.to_thread(save_app, app_id, payload) + await asyncio.to_thread(write_service_files, app_id, payload) + await asyncio.to_thread(systemctl, "daemon-reload") + return to_record(fetch_row(app_id), {"ActiveState": "inactive", "MainPID": "0"}) + + +@app.put("/api/apps/{app_id}", response_model=AppRecord, dependencies=[Depends(require_token)]) +async def edit_app(app_id: str, payload: AppInput) -> AppRecord: + row = fetch_row(app_id) + if read_unit_state(app_id).get("ActiveState") == "active": + raise HTTPException(status_code=409, detail="请先停止应用,再修改配置") + check_runtime(payload) + async with _operation_lock: + await asyncio.to_thread(update_app, app_id, payload) + await asyncio.to_thread(write_service_files, app_id, payload) + await asyncio.to_thread(systemctl, "daemon-reload") + return to_record(fetch_row(app_id), {"ActiveState": "inactive", "MainPID": "0"}) + + +@app.post("/api/apps/{app_id}/actions", response_model=AppRecord, dependencies=[Depends(require_token)]) +async def app_action(app_id: str, payload: AppAction) -> AppRecord: + row = fetch_row(app_id) + async with _operation_lock: + if payload.action in {"start", "restart"}: + saved = AppInput( + name=row["name"], + description=row["description"], + python_path=row["python_path"], + script_path=row["script_path"], + working_dir=row["working_dir"], + args=json.loads(row["args_json"]), + env=json.loads(row["env_json"]), + ) + await asyncio.to_thread(write_service_files, app_id, saved) + await asyncio.to_thread(systemctl, "daemon-reload") + if payload.action == "restart": + await asyncio.to_thread(systemctl, "restart", unit_name(app_id)) + elif payload.action == "start": + await asyncio.to_thread(systemctl, "start", unit_name(app_id)) + else: + await asyncio.to_thread(systemctl, "stop", unit_name(app_id), check=False) + return to_record(fetch_row(app_id), read_unit_state(app_id)) + + +@app.get("/api/apps/{app_id}/logs", dependencies=[Depends(require_token)]) +def app_logs(app_id: str, lines: int = Query(default=120, ge=1, le=1000)) -> dict[str, Any]: + fetch_row(app_id) + result = journalctl("--no-pager", "--output=short-iso", "-u", unit_name(app_id), "-n", str(lines)) + return {"lines": result.stdout.splitlines(), "error": result.stderr.strip() if result.returncode else None} + + +@app.delete("/api/apps/{app_id}", status_code=204, dependencies=[Depends(require_token)]) +async def delete_app(app_id: str) -> Response: + fetch_row(app_id) + if read_unit_state(app_id).get("ActiveState") == "active": + raise HTTPException(status_code=409, detail="请先停止应用,再删除") + unit_path, launcher_path = service_paths(app_id) + async with _operation_lock: + await asyncio.to_thread(unit_path.unlink, missing_ok=True) + await asyncio.to_thread(launcher_path.unlink, missing_ok=True) + + def remove_row() -> None: + with connect_db() as connection: + connection.execute("DELETE FROM apps WHERE id = ?", (app_id,)) + + await asyncio.to_thread(remove_row) + await asyncio.to_thread(systemctl, "daemon-reload") + return Response(status_code=204) + + +@app.get("/{frontend_path:path}", include_in_schema=False) +def frontend_fallback(frontend_path: str) -> FileResponse: + """Return the SPA entry for browser routes after API routes have been matched.""" + if frontend_path == "api" or frontend_path.startswith("api/"): + raise HTTPException(status_code=404, detail="Not Found") + index_file = FRONTEND_DIST / "index.html" + if not index_file.is_file(): + raise HTTPException(status_code=404, detail="前端尚未构建") + return FileResponse(index_file) diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..6135b82 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,5 @@ +fastapi>=0.115,<1.0 +uvicorn[standard]>=0.30,<1.0 +pydantic>=2.8,<3.0 +psutil>=6.0,<8.0 + diff --git a/deploy/compute-service-manager.service.example b/deploy/compute-service-manager.service.example new file mode 100644 index 0000000..1d990ad --- /dev/null +++ b/deploy/compute-service-manager.service.example @@ -0,0 +1,18 @@ +[Unit] +Description=Compute Service Manager API +After=network.target + +[Service] +Type=simple +User=REPLACE_WITH_SERVICE_ACCOUNT +WorkingDirectory=/opt/compute-service-manager/backend +EnvironmentFile=/etc/compute-service-manager.env +Environment=XDG_RUNTIME_DIR=/run/user/REPLACE_WITH_UID +Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/REPLACE_WITH_UID/bus +ExecStart=/opt/compute-service-manager/backend/.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8000 +Restart=on-failure +RestartSec=3 + +[Install] +WantedBy=multi-user.target + diff --git a/deploy/install.sh b/deploy/install.sh new file mode 100644 index 0000000..5202649 --- /dev/null +++ b/deploy/install.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Guided, per-user deployment for the Compute Service Manager on Linux. +set -Eeuo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +CURRENT_USER="$(id -un)" +DEFAULT_INSTALL_DIR="$SCRIPT_DIR" + +color() { + local code="$1" + shift + printf '\033[%sm%s\033[0m\n' "$code" "$*" +} + +info() { color '36' "$*"; } +success() { color '32' "$*"; } +warn() { color '33' "$*"; } +fail() { color '31' "$*" >&2; exit 1; } + +ask() { + local prompt="$1" default="$2" answer + read -r -p "$prompt [$default]: " answer + printf '%s' "${answer:-$default}" +} + +confirm() { + local prompt="$1" answer + read -r -p "$prompt [Y/n]: " answer + [[ -z "$answer" || "$answer" =~ ^[Yy]$ ]] +} + +version_at_least() { + local actual="$1" required="$2" + [[ "$(printf '%s\n%s\n' "$required" "$actual" | sort -V | head -n1)" == "$required" ]] +} + +[[ "$(uname -s)" == "Linux" ]] || fail '该脚本仅支持 Linux。' +[[ "$EUID" -ne 0 ]] || fail '请使用普通 Linux 账号运行;不要以 root 运行。' +[[ -t 0 ]] || fail '该脚本需要交互式终端,请通过 SSH 登录后直接执行。' +[[ -f "$SCRIPT_DIR/backend/app/main.py" && -f "$SCRIPT_DIR/frontend/package.json" ]] || fail '请从项目 deploy/install.sh 执行,或确保脚本位于项目 deploy 目录。' +command -v systemctl >/dev/null || fail '未找到 systemctl;当前系统需要 systemd。' +command -v python3 >/dev/null || fail '未找到 python3,请先安装 Python 3.10 或更高版本。' +command -v node >/dev/null || fail '未找到 node,请先安装 Node.js 18 或更高版本。' +command -v npm >/dev/null || fail '未找到 npm,请先安装 Node.js 18 或更高版本。' +systemctl --user show-environment >/dev/null 2>&1 || fail '当前账号的 systemd user manager 不可用。请通过正常 SSH 登录后重试,并确认 PAM/systemd-logind 已启动用户会话。' + +PYTHON_VERSION="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')" +NODE_VERSION="$(node --version | sed 's/^v//')" +version_at_least "$PYTHON_VERSION" '3.10' || fail "Python 版本过低:$PYTHON_VERSION(需要 3.10+)。" +version_at_least "$NODE_VERSION" '18.0' || fail "Node.js 版本过低:$NODE_VERSION(需要 18+)。" + +printf '\n' +color '32' 'Compute Service Manager · Linux 引导式部署' +printf '运行账号:%s\n项目来源:%s\n\n' "$CURRENT_USER" "$SCRIPT_DIR" + +INSTALL_DIR="$(ask '部署目录' "$DEFAULT_INSTALL_DIR")" +INSTALL_DIR="${INSTALL_DIR/#\~/$HOME}" +INSTALL_DIR="$(mkdir -p -- "$INSTALL_DIR" && cd -- "$INSTALL_DIR" && pwd)" +[[ "$INSTALL_DIR" != *[[:space:]%\\]* ]] || fail '部署目录不能包含空格、百分号或反斜杠(systemd unit 路径限制)。' +[[ "$INSTALL_DIR" != "$SCRIPT_DIR/"* ]] || fail '部署目录不能位于项目源码目录内部。' +if [[ "$INSTALL_DIR" != "$SCRIPT_DIR" ]]; then + if [[ -n "$(find "$INSTALL_DIR" -mindepth 1 -maxdepth 1 -print -quit)" ]] && ! confirm "部署目录已有文件,是否更新覆盖同名项目文件?"; then + fail '用户取消部署。' + fi + mkdir -p "$INSTALL_DIR/backend" "$INSTALL_DIR/frontend" "$INSTALL_DIR/deploy" + # Exclude machine-specific build/runtime files while copying the project source. + tar -C "$SCRIPT_DIR" \ + --exclude='./backend/.venv' --exclude='./backend/__pycache__' \ + --exclude='./frontend/node_modules' --exclude='./frontend/dist' \ + -cf - backend frontend deploy README.md .gitignore | tar -C "$INSTALL_DIR" -xf - +fi + +DEFAULT_PORT='8199' +PORT="$(ask '面板端口' "$DEFAULT_PORT")" +[[ "$PORT" =~ ^[0-9]{1,5}$ ]] && (( PORT >= 1 && PORT <= 65535 )) || fail '端口必须是 1 到 65535 之间的数字。' +BIND_HOST="$(ask '监听地址(0.0.0.0 可供内网团队访问)' '0.0.0.0')" +[[ "$BIND_HOST" =~ ^[A-Za-z0-9.:_-]+$ ]] || fail '监听地址格式无效。' + +ENV_DIR="$HOME/.config/compute-service-manager" +ENV_FILE="$ENV_DIR/manager.env" +UNIT_DIR="$HOME/.config/systemd/user" +UNIT_FILE="$UNIT_DIR/compute-service-manager.service" +mkdir -p "$ENV_DIR" "$UNIT_DIR" + +TOKEN="" +read -r -s -p '管理密钥(留空则自动生成):' TOKEN +printf '\n' +if [[ -z "$TOKEN" ]]; then + if command -v openssl >/dev/null; then + TOKEN="$(openssl rand -hex 32)" + else + TOKEN="$(python3 -c 'import secrets; print(secrets.token_urlsafe(48))')" + fi +fi +[[ "$TOKEN" =~ ^[A-Za-z0-9._~+/=-]+$ ]] || fail '管理密钥仅可包含字母、数字及 . _ ~ + / = - 字符。' + +info '安装后端 Python 依赖…' +python3 -m venv "$INSTALL_DIR/backend/.venv" +"$INSTALL_DIR/backend/.venv/bin/python" -m pip install --upgrade pip +"$INSTALL_DIR/backend/.venv/bin/pip" install -r "$INSTALL_DIR/backend/requirements.txt" + +info '安装前端依赖并构建生产页面…' +if [[ -f "$INSTALL_DIR/frontend/package-lock.json" ]]; then + (cd "$INSTALL_DIR/frontend" && npm ci) +else + (cd "$INSTALL_DIR/frontend" && npm install) +fi +(cd "$INSTALL_DIR/frontend" && npm run build) + +# Keep the shared API secret out of the unit file and restrict it to this account. +umask 077 +cat > "$ENV_FILE" <> "$ENV_FILE" +chmod 600 "$ENV_FILE" + +cat > "$UNIT_FILE" </dev/null && loginctl show-user "$CURRENT_USER" -p Linger --value 2>/dev/null | grep -qx 'no'; then + if command -v sudo >/dev/null && confirm '启用 linger,使面板在退出 SSH 后仍持续运行?(需要 sudo 权限)'; then + sudo loginctl enable-linger "$CURRENT_USER" || warn 'linger 启用失败;面板可能会在退出登录后停止。' + else + warn '尚未启用 linger;面板可能会在退出登录后停止。稍后可执行:sudo loginctl enable-linger '"$CURRENT_USER" + fi +fi + +HOST_IP="$(hostname -I 2>/dev/null | awk '{print $1}')" +printf '\n' +success '部署完成。' +printf '本机访问: http://127.0.0.1:%s\n' "$PORT" +if [[ -n "$HOST_IP" ]]; then + printf '内网访问: http://%s:%s\n' "$HOST_IP" "$PORT" +fi +printf '管理密钥: %s\n' "$TOKEN" +printf '密钥文件: %s(权限 600)\n' "$ENV_FILE" +printf '\n服务管理命令:\n systemctl --user status compute-service-manager\n systemctl --user restart compute-service-manager\n journalctl --user -u compute-service-manager -f\n' +warn '请通过防火墙限制访问来源;直接 HTTP 部署适用于可信内网,公网访问应配置 HTTPS 反向代理。' diff --git a/deploy/nginx.conf.example b/deploy/nginx.conf.example new file mode 100644 index 0000000..a6a2f23 --- /dev/null +++ b/deploy/nginx.conf.example @@ -0,0 +1,21 @@ +server { + listen 443 ssl; + server_name compute.example.internal; + + root /opt/compute-service-manager/frontend/dist; + index index.html; + + location /api/ { + proxy_pass http://127.0.0.1:8000/api/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location / { + try_files $uri $uri/ /index.html; + } +} + diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..0982178 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,15 @@ + + + + + + + + ComputeOS · 算力控制中心 + + +
+ + + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..f68f691 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,24 @@ +{ + "name": "compute-service-manager-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@vitejs/plugin-react": "^4.3.4", + "lucide-react": "^0.468.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "vite": "^6.0.0" + }, + "devDependencies": { + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "typescript": "^5.7.2" + } +} + diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000..fcb96fd --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,631 @@ +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { FormEvent, ReactNode } from "react"; +import { + Activity, + AlertCircle, + Check, + CircleHelp, + Cpu, + FileCode2, + Gauge, + HardDrive, + KeyRound, + ListChecks, + LoaderCircle, + MemoryStick, + MoreHorizontal, + Play, + Plus, + RefreshCw, + Search, + Server, + Settings2, + Square, + TerminalSquare, + Trash2, + X, +} from "lucide-react"; + +type AppStatus = "running" | "stopped" | "failed" | "unknown"; +type ManagedApp = { + id: string; + name: string; + description: string; + python_path: string; + script_path: string; + working_dir: string; + args: string[]; + env: Record; + status: AppStatus; + pid: number | null; + active_since: string | null; + created_at: string; + updated_at: string; +}; +type AppDraft = Pick & { + args_text: string; + env_text: string; +}; +type SystemMetrics = { + source: "local"; + connection_status: "connected" | "unavailable" | "sampling"; + captured_at: string | null; + server: { id: number | null; name: string; platform: string; cpu_names: string[]; gpu_names: string[]; uptime_seconds: number | null; last_active: string | null; is_online: boolean } | null; + cpu: { percent: number; cores: number | null; cpu_names?: string[]; load_1m: number | null } | null; + memory: { used_bytes: number; total_bytes: number; percent: number } | null; + disk: { path: string; used_bytes: number; total_bytes: number; percent: number } | null; + gpus: Array<{ + index: number; + name: string; + utilization: number | null; + memory_used_mb?: number | null; + memory_total_mb?: number | null; + }>; + network: { in_bytes_per_second: number; out_bytes_per_second: number } | null; + temperatures: Array<{ name: string; temperature: number }>; + error: string | null; +}; +type MetricSample = { time: number; cpu: number; memory: number; gpu: number }; +type PageKey = "compute" | "services" | "runtime" | "settings"; + +function pageFromHash(): PageKey { + const page = window.location.hash.slice(1); + return page === "compute" || page === "runtime" || page === "services" || page === "settings" ? page : "compute"; +} + +const API_BASE = import.meta.env.VITE_API_BASE_URL ?? ""; +const TOKEN_KEY = "compute-service-manager-token"; +const emptyDraft: AppDraft = { + name: "", + description: "", + python_path: "", + script_path: "", + working_dir: "", + args_text: "", + env_text: "{}", +}; + +async function request(path: string, token: string, init?: RequestInit): Promise { + const response = await fetch(`${API_BASE}${path}`, { + ...init, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + ...init?.headers, + }, + }); + if (!response.ok) { + const body = await response.json().catch(() => ({})); + throw new Error(body.detail ?? `请求失败 (${response.status})`); + } + if (response.status === 204) return undefined as T; + return response.json() as Promise; +} + +function formatTime(value: string | null): string { + if (!value) return "—"; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? value : date.toLocaleString("zh-CN", { hour12: false }); +} + +function formatBytes(value: number): string { + const units = ["B", "KB", "MB", "GB", "TB"]; + let size = value; + let unit = 0; + while (size >= 1024 && unit < units.length - 1) { + size /= 1024; + unit += 1; + } + return `${size.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`; +} + +function boundedPercent(value: number | null | undefined): number { + return Math.min(100, Math.max(0, value ?? 0)); +} + +function formatUptime(seconds: number | null | undefined): string { + if (!seconds) return "—"; + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + return days ? `${days} 天 ${hours} 小时` : `${hours} 小时 ${Math.floor((seconds % 3600) / 60)} 分钟`; +} + +function MetricTrend({ samples }: { samples: MetricSample[] }) { + const line = (field: "cpu" | "memory" | "gpu") => samples.map((sample, index) => { + const x = samples.length < 2 ? 50 : (index / (samples.length - 1)) * 100; + const y = 38 - boundedPercent(sample[field]) * 0.34; + return `${x},${y}`; + }).join(" "); + return ( +
+
RESOURCE ACTIVITY

资源使用趋势

{samples.length ? `最近 ${samples.length * 5} 秒` : "暂无数据"}
+
CPU内存GPU
+
+
100%50%0%
+ + {[4, 21, 38].map((y) => )} + {samples.length > 1 && <> + + + + } + + {samples.length < 2 &&
暂无本机监控数据
} +
+
约 2 分钟滚动窗口{samples.length ? new Date(samples[samples.length - 1].time).toLocaleTimeString("zh-CN", { hour12: false }) : "等待数据"}
+
+ ); +} + +function ResourceCard({ icon, label, value, detail, percent, tone }: { + icon: ReactNode; + label: string; + value: string; + detail: string; + percent: number; + tone: "green" | "violet" | "blue" | "amber"; +}) { + return ( +
+
+
{icon}
+ {label} + {value} +
+
+ {detail} +
+ ); +} + +function RuntimeStatusTable({ apps }: { apps: ManagedApp[] }) { + const statusLabels: Record = { + running: "运行中", + stopped: "已停止", + failed: "启动失败", + unknown: "状态未知", + }; + + return ( +
+
+
PROCESS SUPERVISION

进程运行明细

+ 每 5 秒自动刷新 +
+ {apps.length ? ( +
+ + + {apps.map((item) => ( + + + + + + + + ))} +
服务状态进程 ID启动时间入口脚本
{item.name}{item.description || "Python 服务"}{statusLabels[item.status]}{item.pid ?? "—"}{item.active_since ? formatTime(item.active_since) : "—"}{item.script_path}
+
+ ) :
尚无已登记的服务运行状态
} +
+ ); +} + +function App() { + const [activePage, setActivePage] = useState(pageFromHash); + const [token, setToken] = useState(() => sessionStorage.getItem(TOKEN_KEY) ?? ""); + const [apps, setApps] = useState([]); + const [metrics, setMetrics] = useState(null); + const [metricSamples, setMetricSamples] = useState([]); + const [loading, setLoading] = useState(false); + const [notice, setNotice] = useState(""); + const [error, setError] = useState(""); + const [search, setSearch] = useState(""); + const [modal, setModal] = useState<"add" | "edit" | "logs" | null>(null); + const [selected, setSelected] = useState(null); + const [draft, setDraft] = useState(emptyDraft); + const [busyId, setBusyId] = useState(""); + const [logLines, setLogLines] = useState([]); + + useEffect(() => { + // Keep the visible page in sync with browser back/forward navigation. + const syncPage = () => setActivePage(pageFromHash()); + window.addEventListener("hashchange", syncPage); + return () => window.removeEventListener("hashchange", syncPage); + }, []); + + function navigateTo(page: PageKey) { + if (window.location.hash === `#${page}`) setActivePage(page); + else window.location.hash = page; + } + + const loadApps = useCallback(async () => { + if (!token) return; + setLoading(true); + try { + const result = await request("/api/apps", token); + setApps(result); + setError(""); + } catch (reason) { + setError(reason instanceof Error ? reason.message : "无法连接管理服务"); + } finally { + setLoading(false); + } + }, [token]); + + const loadMetrics = useCallback(async () => { + if (!token) return; + try { + setMetrics(await request("/api/system/metrics", token)); + } catch { + // 资源监控暂时不可用时保留最近一次数据,不影响服务启停操作。 + } + }, [token]); + + useEffect(() => { + if (token) { + sessionStorage.setItem(TOKEN_KEY, token); + void loadApps(); + void loadMetrics(); + } + }, [token, loadApps, loadMetrics]); + + useEffect(() => { + if (!token) return; + // 定时刷新卡片状态,后端仍由 systemd 负责进程托管。 + const timer = window.setInterval(() => { + void loadApps(); + void loadMetrics(); + }, 5000); + return () => window.clearInterval(timer); + }, [token, loadApps, loadMetrics]); + + const filteredApps = useMemo(() => { + const needle = search.trim().toLowerCase(); + if (!needle) return apps; + return apps.filter((item) => `${item.name} ${item.description} ${item.script_path}`.toLowerCase().includes(needle)); + }, [apps, search]); + const runningCount = apps.filter((item) => item.status === "running").length; + const failedCount = apps.filter((item) => item.status === "failed").length; + const primaryGpu = metrics?.gpus[0]; + const gpuPercent = primaryGpu?.utilization ?? null; + const gpuMemoryText = primaryGpu?.memory_used_mb != null && primaryGpu.memory_total_mb != null + ? `${primaryGpu.memory_used_mb.toFixed(0)} / ${primaryGpu.memory_total_mb.toFixed(0)} MiB` + : primaryGpu ? "本机采集未提供显存数据" : "暂无 GPU 数据"; + + useEffect(() => { + if (!metrics?.cpu || !metrics.memory || !metrics.captured_at) { + setMetricSamples([]); + return; + } + const now = new Date(metrics.captured_at).getTime(); + setMetricSamples((previous) => [ + ...previous.filter((sample) => now - sample.time < 120_000), + { time: now, cpu: metrics.cpu.percent, memory: metrics.memory.percent, gpu: gpuPercent ?? 0 }, + ].slice(-24)); + }, [metrics, gpuPercent]); + + async function runAction(item: ManagedApp, action: "start" | "stop" | "restart") { + setBusyId(item.id); + setError(""); + setNotice(""); + try { + await request(`/api/apps/${item.id}/actions`, token, { + method: "POST", + body: JSON.stringify({ action }), + }); + setNotice(`${item.name}:${action === "start" ? "启动请求已发送" : action === "stop" ? "停止请求已发送" : "重启请求已发送"}`); + await loadApps(); + } catch (reason) { + setError(reason instanceof Error ? reason.message : "操作失败"); + } finally { + setBusyId(""); + } + } + + function openAdd() { + setSelected(null); + setDraft(emptyDraft); + setModal("add"); + } + + function openEdit(item: ManagedApp) { + setSelected(item); + setDraft({ + name: item.name, + description: item.description, + python_path: item.python_path, + script_path: item.script_path, + working_dir: item.working_dir, + args_text: JSON.stringify(item.args, null, 2), + env_text: JSON.stringify(item.env, null, 2), + }); + setModal("edit"); + } + + async function saveApp(event: FormEvent) { + event.preventDefault(); + setError(""); + try { + const env = JSON.parse(draft.env_text || "{}") as Record; + const args = JSON.parse(draft.args_text || "[]") as unknown; + if (!Array.isArray(args) || !args.every((value) => typeof value === "string")) { + throw new Error("启动参数必须是字符串数组,例如 [\"--port\", \"8000\"]"); + } + const payload = { + name: draft.name, + description: draft.description, + python_path: draft.python_path, + script_path: draft.script_path, + working_dir: draft.working_dir, + args, + env, + }; + const path = selected ? `/api/apps/${selected.id}` : "/api/apps"; + await request(path, token, { method: selected ? "PUT" : "POST", body: JSON.stringify(payload) }); + setModal(null); + setNotice(selected ? "应用配置已更新" : "应用已添加"); + await loadApps(); + } catch (reason) { + setError(reason instanceof Error ? reason.message : "配置格式不正确"); + } + } + + async function showLogs(item: ManagedApp) { + setSelected(item); + setLogLines([]); + setModal("logs"); + try { + const result = await request<{ lines: string[]; error: string | null }>(`/api/apps/${item.id}/logs`, token); + setLogLines(result.lines); + if (result.error) setError(result.error); + } catch (reason) { + setError(reason instanceof Error ? reason.message : "读取日志失败"); + } + } + + async function deleteApp(item: ManagedApp) { + if (!window.confirm(`确认删除“${item.name}”的登记配置?`)) return; + try { + await request(`/api/apps/${item.id}`, token, { method: "DELETE" }); + setNotice("应用配置已删除"); + await loadApps(); + } catch (reason) { + setError(reason instanceof Error ? reason.message : "删除失败"); + } + } + + function saveToken(value: string) { + const nextToken = value.trim(); + if (!nextToken) return; + setToken(nextToken); + sessionStorage.setItem(TOKEN_KEY, nextToken); + setError(""); + setNotice("管理密钥已保存在当前会话"); + } + + function clearToken() { + sessionStorage.removeItem(TOKEN_KEY); + setToken(""); + setApps([]); + setMetrics(null); + setMetricSamples([]); + setNotice("已清除当前浏览器会话中的管理密钥"); + } + + const pageTitles: Record = { compute: "算力监控", services: "服务管理", runtime: "运行状态", settings: "设置" }; + + return ( +
+ + +
+
+
工作空间/{pageTitles[activePage]}
+
+
{metrics?.server?.name ?? "本机节点"}
+ + +
+
+ +
+ {error &&
{error}
} + {notice &&
{notice}
} + + {activePage === "services" && <> +
+
SERVICE CONTROL

服务管理

管理已登记的服务,按需启动、停止或查看日志。

+ +
+ } + + {activePage === "compute" && <> +
+
COMPUTE MONITORING

算力监控

查看节点资源占用、硬件信息与近期变化趋势。

+
{!token ? "请在设置中配置管理密钥" : metrics?.connection_status === "connected" ? "本机采集正常" : metrics?.connection_status === "unavailable" ? "本机采集不可用" : "正在采集"}
+
+
+ } label="CPU 利用率" value={metrics?.cpu ? `${metrics.cpu.percent.toFixed(1)}%` : "暂无数据"} detail={metrics?.cpu ? `1 分钟负载 ${metrics.cpu.load_1m?.toFixed(2) ?? "—"}` : "等待本机采集"} percent={metrics?.cpu?.percent ?? 0} tone="green" /> + } label="系统内存" value={metrics?.memory ? `${metrics.memory.percent.toFixed(1)}%` : "暂无数据"} detail={metrics?.memory ? `${formatBytes(metrics.memory.used_bytes)} / ${formatBytes(metrics.memory.total_bytes)}` : "等待本机采集"} percent={metrics?.memory?.percent ?? 0} tone="violet" /> + } label={primaryGpu ? `GPU ${primaryGpu.index} · ${primaryGpu.name}` : "GPU 利用率"} value={gpuPercent == null ? "暂无数据" : `${gpuPercent.toFixed(1)}%`} detail={gpuMemoryText} percent={gpuPercent ?? 0} tone="blue" /> + } label="系统磁盘" value={metrics?.disk ? `${metrics.disk.percent.toFixed(1)}%` : "暂无数据"} detail={metrics?.disk ? `${formatBytes(metrics.disk.used_bytes)} / ${formatBytes(metrics.disk.total_bytes)}` : "等待本机采集"} percent={metrics?.disk?.percent ?? 0} tone="amber" /> +
+
数据来源 · 本机系统采集·每 5 秒刷新{metrics?.captured_at ? ` · 更新于 ${new Date(metrics.captured_at).toLocaleTimeString("zh-CN", { hour12: false })}` : ""}
+ {metrics?.error &&
{metrics.error}
} +
+ +
+
NODE PROFILE

节点概况

{metrics?.server ? "本机在线" : "暂无数据"}
+ {metrics?.server ? <> +
{metrics.server.name}{metrics.server.platform || "Linux compute node"}{metrics.server.id ? ` · ID ${metrics.server.id}` : ""}
+
+
处理器{metrics.server.cpu_names[0] ?? "暂无数据"}
+
加速器{metrics.server.gpu_names.join(" · ") || "暂无数据"}
+
运行时间{formatUptime(metrics.server.uptime_seconds)}
+
网络吞吐{metrics.network ? `↓ ${formatBytes(metrics.network.in_bytes_per_second)}/s ↑ ${formatBytes(metrics.network.out_bytes_per_second)}/s` : "暂无数据"}
+
+ :
暂无本机采集数据
} +
+
+ } + + {activePage === "services" && <> +
+
MANAGED SERVICES

已登记服务

{apps.length.toString().padStart(2, "0")}{runningCount} 运行中 · {failedCount} 异常
+
+ + +
+
+ {!token ? null : loading && apps.length === 0 ? ( +
正在读取本机服务…
+ ) : filteredApps.length ? ( +
+ {filteredApps.map((item) => )} + +
+ ) : ( +
+
+

{search ? "没有匹配的应用" : "还没有登记应用"}

+

{search ? "试试其他应用名称或目录。" : "添加已有的 Python 服务,即可从卡片快捷启停。"}

+ {!search && } +
+ )} + } + + {activePage === "runtime" && <> +
+
RUNTIME STATUS

运行状态

集中查看登记服务的 systemd 进程状态与启动信息。

+ +
+
+
运行中{runningCount}
+
启动异常{failedCount}
+
已登记服务{apps.length}
+
刷新频率5秒
+
+ {token ? loading && apps.length === 0 ?
正在读取本机服务…
: : null} + } + + {activePage === "settings" && <> +
+
PANEL SETTINGS

设置

配置本机管理服务的访问密钥。

+
+ + } + +
COMPUTE SERVICE MANAGER · LOCAL CONTROL PLANE
+
+
+ + {modal === "add" || modal === "edit" ? ( +
setModal(null)}> +
event.stopPropagation()}> +
SERVICE CONFIGURATION

{selected ? "编辑应用" : "添加应用"}

+
+
+ setDraft({ ...draft, name: event.target.value })} placeholder="例如:Gemma 4 31B" /> + setDraft({ ...draft, description: event.target.value })} placeholder="例如:推理服务、Embedding 或其他" /> + setDraft({ ...draft, python_path: event.target.value })} placeholder="/opt/conda/envs/gemma/bin/python" /> + setDraft({ ...draft, script_path: event.target.value })} placeholder="/dep/project/serve.py" /> + setDraft({ ...draft, working_dir: event.target.value })} placeholder="/dep/project" /> +