Compare commits
23
Commits
v1.0.0
..
0c8ac02f82
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c8ac02f82 | ||
|
|
6449de0cdb | ||
|
|
d27cc47d8c | ||
|
|
bb6a446cad | ||
|
|
09e0996b9d | ||
|
|
97bbe3ced6 | ||
|
|
46af20e96c | ||
|
|
c3114492bb | ||
|
|
ff04cb0c1a | ||
|
|
16ece31d57 | ||
|
|
8d8b201498 | ||
|
|
5744bf5585 | ||
|
|
9a070b77af | ||
|
|
886cb2af27 | ||
|
|
0381fe3f2f | ||
|
|
c11aadaa68 | ||
|
|
80db7a482a | ||
|
|
d84db86486 | ||
|
|
d1989a7f24 | ||
|
|
3776c310e4 | ||
|
|
a7b23b760a | ||
|
|
b9a43e78ee | ||
|
|
4baa91597f |
@@ -2,6 +2,8 @@ name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
@@ -15,6 +17,53 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Determine Version Tag & Generate Notes
|
||||
id: versioning
|
||||
run: |
|
||||
PREV_TAG=$(git tag -l "v*" --sort=-v:refname | head -n1)
|
||||
echo "Previous tag: $PREV_TAG"
|
||||
|
||||
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
else
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
TAG="v1.0.0"
|
||||
else
|
||||
VER_NUM="${PREV_TAG#v}"
|
||||
IFS='.' read -r MAJOR MINOR PATCH <<< "$VER_NUM"
|
||||
PATCH=$((PATCH + 1))
|
||||
TAG="v${MAJOR}.${MINOR}.${PATCH}"
|
||||
fi
|
||||
echo "Auto incremented patch version to $TAG"
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag "$TAG"
|
||||
git push origin "$TAG"
|
||||
fi
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
# 生成详细的 Release Changelog 正文
|
||||
cat << NOTES > release_notes.md
|
||||
### 🚀 What's Changed in ${TAG}
|
||||
|
||||
NOTES
|
||||
|
||||
if [ -n "$PREV_TAG" ]; then
|
||||
git log "${PREV_TAG}..HEAD" --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md
|
||||
else
|
||||
git log -n 10 --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md
|
||||
fi
|
||||
|
||||
echo "" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
if [ -n "$PREV_TAG" ]; then
|
||||
echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${TAG}" >> release_notes.md
|
||||
fi
|
||||
cat release_notes.md
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
@@ -40,6 +89,8 @@ jobs:
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.versioning.outputs.tag }}
|
||||
name: Release ${{ steps.versioning.outputs.tag }}
|
||||
body_path: release_notes.md
|
||||
files: |
|
||||
dist/*
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -27,9 +27,17 @@
|
||||
- **零参数泄露**:全面封禁 CLI 敏感传参,凭据由 `0600` 环境变量接管,避免 `/proc/*/cmdline` 泄密。
|
||||
- **完整审计追溯**:内置本地 SQLite 存储,全量记录调用者 IP、下发节点、指令内容、退出码及精确执行耗时。
|
||||
- **执行隔离与超时回收**:内置上下文超时控制,强制清理孤儿进程,彻底杜绝僵尸进程。
|
||||
- 📊 **实时节点资源画像 (Node Profiling & Role)**:
|
||||
- **原生零依赖深度采集**:直接读取 Linux 内核指标,实时监控物理 CPU 核心数与瞬时负载、真实可用内存(`MemAvailable`)与 Swap、根分区磁盘占用、IO 压力指数(内核原生 PSI / Loadavg)及 Docker 守护进程运行状态。
|
||||
- **动态角色标签**:支持节点角色分工(如 `CONTROL` 控制中枢、`APPLICATION` 应用节点、`DATABASE` 等),为 AI Agent 自动化调度部署决策提供全维度实时依据。
|
||||
- 🛡️ **设备生命周期管理与防重连黑名单**:
|
||||
- 支持管理员在 Web 控制台一键注销并强制断开指定受控节点。
|
||||
- 持久化吊销拦截(Revocation List),彻底杜绝被下线 Agent 因 Systemd 自动重启而死灰复燃。
|
||||
- 本地主控节点(Local)强制安全锁,防误操作防护。
|
||||
- 🖥️ **内嵌极简 Web 管理面板**:
|
||||
- 静态单页面(SPA)采用 Go `embed` 完整打包进二进制文件,单文件独立运行,无需安装 Node.js、Nginx 或外部静态资源 CDN。
|
||||
- 包含设备状态感知、Actions 向导、在线调试控制台及操作审计日志。
|
||||
- **工程级双态主题**:纯手绘 SVG 极简几何微图标(太阳/弦月),支持深曜蓝黑与柔和浅灰白一键切换,完美适配系统偏好且零 FOUC 白屏闪烁。
|
||||
- **全端响应式**:彻底适配手机移动端(≤680px),宽表独立触控滑动,长节点名自动断行不穿透。
|
||||
|
||||
---
|
||||
|
||||
@@ -65,17 +73,27 @@
|
||||
|
||||
---
|
||||
|
||||
## 🚀 极速一键部署 (推荐)
|
||||
## 🚀 极速一键部署与平滑升级
|
||||
|
||||
### 1. 一键全自动安装 (推荐)
|
||||
无论是在受控端 VPS 还是中心端,只需一行命令即可交互式安装与启动:
|
||||
|
||||
```bash
|
||||
bash <(curl -sSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh)
|
||||
bash <(curl -fsSLk https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/install.sh)
|
||||
```
|
||||
|
||||
- **安装 Agent (受控 VPS)**:输入 Hub 的 WSS 地址与通信密钥,全自动配置开机自启并秒级连入集群。
|
||||
- **安装 Hub (中心服务端)**:自动生成安全 API Key / Web 面板密码并以 Systemd 托管常驻。
|
||||
|
||||
### 2. 受控端 Agent 一键平滑升级 (免重输配置)
|
||||
当新版本发布后,无需重新配置通信密钥或重新安装,在任意受控机上直接运行升级脚本:
|
||||
|
||||
```bash
|
||||
curl -fsSLk https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/upgrade-agent.sh | bash
|
||||
```
|
||||
- 自动检测并拉取 Gitea 最新版本架构包(AMD64 / ARM64);
|
||||
- 自动备份旧版本二进制(`.bak`);
|
||||
- 升级异常(校验失败或无法启动)时**自动秒级回滚**,保证节点永不失联。
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ 手动编译部署
|
||||
@@ -132,20 +150,51 @@ Agent 启动后会通过 WSS 自动连入 Hub,在 Hub 管理面板与 `/api/v1
|
||||
|
||||
---
|
||||
|
||||
## 🤖 接入 ChatGPT / AI 客户端
|
||||
## 🤖 接入 ChatGPT (新版插件 Apps & MCP 模式)
|
||||
|
||||
### 方式 1:ChatGPT Actions (推荐)
|
||||
1. 在 ChatGPT 创建自定义 GPT(GPT Builder)-> **Actions** -> **Create new action**。
|
||||
2. **Schema 导入**:在 `Import from URL` 填入 `https://your-domain.com/openapi.json`。
|
||||
3. **Authentication (身份验证)**:
|
||||
- Authentication Type 选择 **API Key**。
|
||||
- Auth Type 选择 **Bearer**。
|
||||
- 填入你配置的 `VPS_COMMANDER_API_KEY`。
|
||||
当前 ChatGPT 已升级为以 **插件 / 应用 (Apps & MCP)** 规范连接外部服务。VPS-Commander 原生内置完整的 **MCP SSE + OAuth2** 协议支持,无需部署额外适配层。
|
||||
|
||||
### 方式 2:MCP (Model Context Protocol)
|
||||
- **SSE 端点**:`https://your-domain.com/mcp/sse`
|
||||
- **消息交互**:`https://your-domain.com/mcp/message`
|
||||
- **认证**:支持 URL 参数 `?token=...` 或标准 Header `Authorization: Bearer <TOKEN>`。
|
||||
### 接入配置步骤:
|
||||
|
||||
1. **进入 ChatGPT 插件/应用配置页**:
|
||||
- 打开 ChatGPT -> **Settings (设置)** -> **Apps & Integrations (应用与集成) / Plugins** -> **Create / Add App (添加应用)**。
|
||||
2. **连接方式选择 MCP**:
|
||||
- 连接协议选择 **MCP (Model Context Protocol)** 或 **Server-Sent Events (SSE)**。
|
||||
- **MCP Server URL**:填入 Hub 的 SSE 统一入口:
|
||||
```text
|
||||
https://your-domain.com/mcp/sse
|
||||
```
|
||||
3. **身份认证 (Authentication)**:
|
||||
- **方式 A (OAuth 2.0 自动授权,推荐)**:
|
||||
- Hub 内置了标准 RFC 8414 OAuth Metadata (`/.well-known/oauth-authorization-server`);
|
||||
- 授权端点与 Token 端点由 ChatGPT 自动识别,一键点击「Authorize」即可完成免密安全绑定。
|
||||
- **方式 B (Bearer API Key)**:
|
||||
- 若选择 API Key,填入 Hub 环境变量 `VPS_COMMANDER_API_KEY` 即可。
|
||||
4. **自动发现 4 大运维工具**:
|
||||
- 握手成功后,ChatGPT 会自动加载并列出 4 个原生运维工具:
|
||||
- `list_devices`:列出受控节点、CPU/内存/磁盘剩余绝对值及 Docker 状态;
|
||||
- `exec_command`:在目标机器(如 `m4-live-agent`)执行 Shell 指令;
|
||||
- `read_file`:分页读取目标文件;
|
||||
- `write_file`:远程编辑或创建文件。
|
||||
|
||||
---
|
||||
|
||||
### 传统客户端支持 (Claude Desktop / Cursor / VS Code)
|
||||
|
||||
支持通过本地 stdio 二进制连接 Hub:
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"vps-commander": {
|
||||
"command": "/path/to/vps-commander-mcp-stdio-linux-amd64",
|
||||
"args": [
|
||||
"-hub", "https://your-domain.com",
|
||||
"-key", "YOUR_API_KEY"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -153,7 +202,8 @@ Agent 启动后会通过 WSS 自动连入 Hub,在 Hub 管理面板与 `/api/v1
|
||||
|
||||
| 接口路径 | 方法 | 功能描述 |
|
||||
| :--- | :--- | :--- |
|
||||
| `/api/v1/devices` | `GET` | 列出集群中所有受控设备及其实时状态(在线/离线、架构、系统等) |
|
||||
| `/api/v1/devices` | `GET` | 列出集群中所有受控设备状态与**实时资源画像 (CPU/Mem/Disk/IO PSI/Docker/Role)** |
|
||||
| `/panel/api/devices` | `DELETE` | 【管理员】注销并踢出指定受控节点,持久化写入防重连黑名单 |
|
||||
| `/api/v1/exec` | `POST` | 在指定受控节点执行任意 Shell 指令(支持超时截断) |
|
||||
| `/api/v1/file/read` | `POST` | 安全分页读取目标机器上的文件内容(防内存溢出) |
|
||||
| `/api/v1/file/write` | `POST` | 向目标机器指定路径覆写或创建文件 |
|
||||
|
||||
+53
-6
@@ -10,12 +10,14 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/wjyhk/vps-commander/internal/cluster"
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
"github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -68,23 +70,30 @@ func run(hub, name, token string, insecure bool) error {
|
||||
return err
|
||||
}
|
||||
exec := executor.Local{MaxOutput: 1024 * 1024}
|
||||
if err := writeJSON(cluster.Message{Event: "hello", Device: name, TS: time.Now().Unix()}); err != nil {
|
||||
mcpRuntime := cluster.NewMCPRuntime()
|
||||
|
||||
// 初始握手附带画像
|
||||
initProf := sysinfo.Collect("APPLICATION")
|
||||
if err := writeJSON(cluster.Message{Event: "hello", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &initProf, TS: time.Now().Unix()}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stopPing := make(chan struct{})
|
||||
defer close(stopPing)
|
||||
go func() {
|
||||
t := time.NewTicker(30 * time.Second)
|
||||
t := time.NewTicker(15 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
_ = writeJSON(cluster.Message{Event: "ping", Device: name, TS: time.Now().Unix()})
|
||||
prof := sysinfo.Collect("APPLICATION")
|
||||
_ = writeJSON(cluster.Message{Event: "ping", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &prof, TS: time.Now().Unix()})
|
||||
case <-stopPing:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
var msg cluster.Message
|
||||
if err := c.ReadJSON(&msg); err != nil {
|
||||
@@ -94,8 +103,23 @@ func run(hub, name, token string, insecure bool) error {
|
||||
if msg.Event == "registered" {
|
||||
continue
|
||||
}
|
||||
if msg.Event == "mcp_sync" {
|
||||
var services []cluster.MCPService
|
||||
if err := decodePayload(msg.Payload, &services); err != nil {
|
||||
log.Printf("mcp sync failed: %v", err)
|
||||
} else {
|
||||
mcpRuntime.Sync(services)
|
||||
log.Printf("MCP services synced: %d", len(services))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if msg.Event == "revoked" {
|
||||
log.Printf("device revoked by admin: %s", msg.Error)
|
||||
return errors.New("revoked by admin")
|
||||
}
|
||||
if msg.Event == "ping" {
|
||||
if err := writeJSON(cluster.Message{Event: "pong", Device: name, TS: msg.TS}); err != nil {
|
||||
prof := sysinfo.Collect("APPLICATION")
|
||||
if err := writeJSON(cluster.Message{Event: "pong", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &prof, TS: msg.TS}); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
@@ -104,7 +128,7 @@ func run(hub, name, token string, insecure bool) error {
|
||||
continue
|
||||
}
|
||||
go func(msg cluster.Message) {
|
||||
if err := handle(writeJSON, exec, msg); err != nil {
|
||||
if err := handle(writeJSON, exec, mcpRuntime, msg); err != nil {
|
||||
log.Printf("request %s failed: %v", msg.ID, err)
|
||||
_ = c.Close()
|
||||
}
|
||||
@@ -112,8 +136,30 @@ func run(hub, name, token string, insecure bool) error {
|
||||
}
|
||||
}
|
||||
|
||||
func handle(writeJSON func(cluster.Message) error, exec executor.Local, msg cluster.Message) error {
|
||||
func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, msg cluster.Message) error {
|
||||
switch msg.Action {
|
||||
case "mcp_call":
|
||||
var p struct {
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Args any `json:"args"`
|
||||
}
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
if p.Server == "" || p.Tool == "" {
|
||||
return sendError(writeJSON, msg.ID, errors.New("server and tool required"))
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
result, err := mcpRuntime.Call(ctx, p.Server, p.Tool, p.Args)
|
||||
duration := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
_ = writeJSON(cluster.Message{ID: msg.ID, Status: "error", Error: err.Error(), Payload: map[string]any{"server": p.Server, "tool": p.Tool, "duration_ms": duration}})
|
||||
return nil
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"server": p.Server, "tool": p.Tool, "result": result, "duration_ms": duration}})
|
||||
case "exec":
|
||||
var p cluster.ExecPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
@@ -185,6 +231,7 @@ func decodePayload(v any, out any) error {
|
||||
}
|
||||
return json.Unmarshal(b, out)
|
||||
}
|
||||
|
||||
func sendError(writeJSON func(cluster.Message) error, id string, err error) error {
|
||||
return writeJSON(cluster.Message{ID: id, Status: "error", Error: err.Error()})
|
||||
}
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ func main() {
|
||||
s := &api.Server{
|
||||
Auth: authManager,
|
||||
Exec: executor.Local{MaxOutput: 1024 * 1024},
|
||||
Cluster: cluster.NewManager(clusterSecret),
|
||||
Cluster: cluster.NewManager(clusterSecret, store),
|
||||
Store: store,
|
||||
LocalName: local,
|
||||
}
|
||||
|
||||
+17
-19
@@ -2,12 +2,13 @@
|
||||
set -e
|
||||
|
||||
# VPS-Commander 一键安装与配置脚本 (Hub / Agent)
|
||||
# Repo: https://github.com/kyaring/vps-commander
|
||||
# Repo: https://gitea.king.nyc.mn/openclaw/vps-commander
|
||||
|
||||
REPO="kyaring/vps-commander"
|
||||
GITEA_HOST="gitea.king.nyc.mn"
|
||||
REPO="openclaw/vps-commander"
|
||||
INSTALL_DIR="/opt/vps-commander"
|
||||
CONF_DIR="/etc/vps-commander"
|
||||
GITHUB_URL="https://github.com"
|
||||
GITEA_URL="https://gitea.king.nyc.mn"
|
||||
|
||||
# 颜色输出
|
||||
RED='\033[0;31m'
|
||||
@@ -37,12 +38,12 @@ command -v curl >/dev/null 2>&1 || (apt-get update && apt-get install -y curl ||
|
||||
|
||||
# 获取最新版本 tag
|
||||
info "正在获取 VPS-Commander 最新版本信息..."
|
||||
LATEST_TAG=$(curl -sSL "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
|
||||
LATEST_TAG=$(curl -fsSL -k "${GITEA_URL}/api/v1/repos/${REPO}/releases/latest" 2>/dev/null | grep -o '"tag_name":"[^"]*"' | head -n1 | cut -d'"' -f4)
|
||||
if [ -z "$LATEST_TAG" ]; then
|
||||
warn "无法通过 GitHub API 自动获取 Tag,将尝试使用默认版本 v1.0.0"
|
||||
LATEST_TAG="v1.0.0"
|
||||
warn "无法通过 Gitea API 自动获取 Tag,回退至 v1.1.5"
|
||||
LATEST_TAG="v1.1.5"
|
||||
fi
|
||||
info "检测到最新版本: ${LATEST_TAG}"
|
||||
info "检测到最新版本: ${LATEST_TAG} (${TARGET_ARCH})"
|
||||
|
||||
mkdir -p "$INSTALL_DIR" "$INSTALL_DIR/data" "$CONF_DIR"
|
||||
chmod 750 "$INSTALL_DIR" "$CONF_DIR"
|
||||
@@ -58,10 +59,10 @@ select_mode() {
|
||||
install_agent() {
|
||||
info "开始安装 VPS-Commander Agent (${TARGET_ARCH})..."
|
||||
BIN_NAME="vps-commander-agent-linux-${TARGET_ARCH}"
|
||||
DOWNLOAD_URL="${GITHUB_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
|
||||
DOWNLOAD_URL="${GITEA_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
|
||||
|
||||
info "正在下载 Agent: ${DOWNLOAD_URL}"
|
||||
curl -sSL -o "${INSTALL_DIR}/vps-commander-agent" "${DOWNLOAD_URL}" || error "下载失败,请检查网络或 Release 是否存在"
|
||||
info "正在从 Gitea 下载 Agent: ${DOWNLOAD_URL}"
|
||||
curl -fsSL -k -o "${INSTALL_DIR}/vps-commander-agent" "${DOWNLOAD_URL}" || error "下载失败,请检查 Gitea 网络或 Release 是否存在"
|
||||
chmod +x "${INSTALL_DIR}/vps-commander-agent"
|
||||
|
||||
echo -e "\n--- 配置 Agent 参数 ---"
|
||||
@@ -77,7 +78,6 @@ install_agent() {
|
||||
read -rp "Cluster Secret 不能为空,请重新输入: " CLUSTER_SECRET
|
||||
done
|
||||
|
||||
# 写入凭据文件
|
||||
cat << ENV > "${CONF_DIR}/agent.env"
|
||||
VPS_COMMANDER_HUB_WS_URL=${HUB_WS}
|
||||
VPS_COMMANDER_AGENT_NAME=${AGENT_NAME}
|
||||
@@ -85,7 +85,6 @@ VPS_COMMANDER_CLUSTER_SECRET=${CLUSTER_SECRET}
|
||||
ENV
|
||||
chmod 0600 "${CONF_DIR}/agent.env"
|
||||
|
||||
# 配置 systemd
|
||||
cat << SVC > /etc/systemd/system/vps-commander-agent.service
|
||||
[Unit]
|
||||
Description=VPS-Commander Agent
|
||||
@@ -125,20 +124,19 @@ SVC
|
||||
install_hub() {
|
||||
info "开始安装 VPS-Commander Hub (${TARGET_ARCH})..."
|
||||
BIN_NAME="vps-commander-hub-linux-${TARGET_ARCH}"
|
||||
DOWNLOAD_URL="${GITHUB_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
|
||||
DOWNLOAD_URL="${GITEA_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
|
||||
|
||||
info "正在下载 Hub: ${DOWNLOAD_URL}"
|
||||
curl -sSL -o "${INSTALL_DIR}/vps-commander-hub" "${DOWNLOAD_URL}" || error "下载失败,请检查网络或 Release 是否存在"
|
||||
info "正在从 Gitea 下载 Hub: ${DOWNLOAD_URL}"
|
||||
curl -fsSL -k -o "${INSTALL_DIR}/vps-commander-hub" "${DOWNLOAD_URL}" || error "下载失败,请检查 Gitea 网络或 Release 是否存在"
|
||||
chmod +x "${INSTALL_DIR}/vps-commander-hub"
|
||||
|
||||
echo -e "\n--- 配置 Hub 参数 ---"
|
||||
read -rp "请输入监听端口 (默认 9521): " HUB_PORT
|
||||
HUB_PORT=${HUB_PORT:-9521}
|
||||
|
||||
# 自动生成随机凭据
|
||||
GEN_API_KEY=$(head -c 24 /dev/urandom | xxd -p)
|
||||
GEN_SECRET=$(head -c 24 /dev/urandom | xxd -p)
|
||||
GEN_PASS=$(head -c 16 /dev/urandom | xxd -p)
|
||||
GEN_API_KEY=$(head -c 24 /dev/urandom | xxd -p 2>/dev/null || openssl rand -hex 24)
|
||||
GEN_SECRET=$(head -c 24 /dev/urandom | xxd -p 2>/dev/null || openssl rand -hex 24)
|
||||
GEN_PASS=$(head -c 16 /dev/urandom | xxd -p 2>/dev/null || openssl rand -hex 16)
|
||||
|
||||
read -rp "请输入 API Key (默认随机生成): " API_KEY
|
||||
API_KEY=${API_KEY:-$GEN_API_KEY}
|
||||
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# VPS-Commander Agent 一键安全升级脚本
|
||||
# Repo: https://gitea.king.nyc.mn/openclaw/vps-commander
|
||||
|
||||
GITEA_HOST="gitea.king.nyc.mn"
|
||||
REPO="openclaw/vps-commander"
|
||||
INSTALL_DIR="/opt/vps-commander"
|
||||
GITEA_URL="https://gitea.king.nyc.mn"
|
||||
|
||||
# 颜色输出
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m'
|
||||
|
||||
info() { echo -e "${BLUE}[INFO]${NC} $*"; }
|
||||
success() { echo -e "${GREEN}[SUCCESS]${NC} $*"; }
|
||||
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }
|
||||
|
||||
# 检查 root 权限
|
||||
[[ $EUID -ne 0 ]] && error "必须使用 root 权限运行此脚本"
|
||||
|
||||
# 检查是否安装过 agent
|
||||
if [ ! -f "${INSTALL_DIR}/vps-commander-agent" ]; then
|
||||
error "未检测到已安装的 Agent (${INSTALL_DIR}/vps-commander-agent),请先使用 install.sh 完整安装。"
|
||||
fi
|
||||
|
||||
# 架构检测
|
||||
ARCH=$(uname -m)
|
||||
case "$ARCH" in
|
||||
x86_64|amd64) TARGET_ARCH="amd64" ;;
|
||||
aarch64|arm64) TARGET_ARCH="arm64" ;;
|
||||
*) error "暂不支持的系统架构: $ARCH" ;;
|
||||
esac
|
||||
|
||||
info "正在获取最新 Release 版本信息..."
|
||||
LATEST_TAG=$(curl -fsSL -k "${GITEA_URL}/api/v1/repos/${REPO}/releases/latest" 2>/dev/null | grep -o '"tag_name":"[^"]*"' | head -n1 | cut -d'"' -f4)
|
||||
if [ -z "$LATEST_TAG" ]; then
|
||||
warn "无法通过 Gitea API 自动获取 Tag,回退至 v1.1.5"
|
||||
LATEST_TAG="v1.1.5"
|
||||
fi
|
||||
info "目标升级版本: ${LATEST_TAG} (${TARGET_ARCH})"
|
||||
|
||||
BIN_NAME="vps-commander-agent-linux-${TARGET_ARCH}"
|
||||
DOWNLOAD_URL="${GITEA_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
|
||||
TMP_BIN="${INSTALL_DIR}/vps-commander-agent.tmp"
|
||||
BAK_BIN="${INSTALL_DIR}/vps-commander-agent.bak"
|
||||
|
||||
info "正在从 Gitea 下载新版本二进制文件..."
|
||||
curl -fsSL -k -o "${TMP_BIN}" "${DOWNLOAD_URL}" || error "下载失败,请检查 Gitea 网络或 Release 是否存在"
|
||||
|
||||
# 完整性校验:文件大小不能小于 1MB
|
||||
FILE_SIZE=$(stat -c%s "${TMP_BIN}" 2>/dev/null || stat -f%z "${TMP_BIN}" 2>/dev/null || echo 0)
|
||||
if [ "$FILE_SIZE" -lt 1000000 ]; then
|
||||
rm -f "${TMP_BIN}"
|
||||
error "下载的文件不完整或损坏 (大小: ${FILE_SIZE} 字节),已终止升级"
|
||||
fi
|
||||
|
||||
chmod +x "${TMP_BIN}"
|
||||
|
||||
info "备份旧版本并原子替换..."
|
||||
cp -f "${INSTALL_DIR}/vps-commander-agent" "${BAK_BIN}" 2>/dev/null || true
|
||||
mv -f "${TMP_BIN}" "${INSTALL_DIR}/vps-commander-agent"
|
||||
|
||||
info "重启 vps-commander-agent 服务..."
|
||||
systemctl restart vps-commander-agent
|
||||
sleep 2
|
||||
|
||||
if systemctl is-active --quiet vps-commander-agent; then
|
||||
success "Agent 成功平滑升级至 ${LATEST_TAG} 并已恢复运行!"
|
||||
rm -f "${BAK_BIN}"
|
||||
else
|
||||
warn "服务启动异常,正在自动回滚原版本..."
|
||||
mv -f "${BAK_BIN}" "${INSTALL_DIR}/vps-commander-agent"
|
||||
systemctl restart vps-commander-agent
|
||||
error "升级失败,已安全回滚至上一版本,请查看日志: journalctl -u vps-commander-agent -n 20"
|
||||
fi
|
||||
@@ -1,7 +1,7 @@
|
||||
# VPS-Commander M4 最终验收报告(待人工签收)
|
||||
|
||||
日期:2026-09-28
|
||||
状态:🟡 技术收尾完成,等待 Custom GPT Actions 人工签收
|
||||
状态:🟡 技术收尾完成;管理面板 UI 已人工验收并上线,M4 总体验收仍等待 Custom GPT Actions 人工签收
|
||||
|
||||
## 已完成
|
||||
|
||||
@@ -25,3 +25,5 @@
|
||||
4. 完成后由用户人工确认 M4 通过。
|
||||
|
||||
在此之前,本报告不得视为 Release Ready / M4 Passed。
|
||||
|
||||
- 管理面板 UI 已完成手机端多 Agent 适配与深/浅双态主题;用户人工验收通过后已重新构建 Hub 并重启 systemd,线上 embed 静态资源已立即生效。
|
||||
|
||||
@@ -107,6 +107,14 @@
|
||||
- [x] 临时凭据文件 `/tmp/m4-prod.env` 已删除;`/etc/vps-commander/{hub,agent}.env` 权限均为 `0600`。
|
||||
- [ ] Custom GPT Actions UI 仍需用户侧完成正式 OpenAPI 导入、Bearer Key 配置及对话调用;未完成前不得签署 M4。
|
||||
|
||||
### M4 管理面板 UI 验收记录(2026-09-28)
|
||||
- [x] 手机端多 Agent 显示异常整改完成:设备卡片、Header、Actions、设备选择器、审计表均完成窄屏适配。
|
||||
- [x] 面板颜色体系改为 CSS Variables 双态主题,支持深色/浅色切换。
|
||||
- [x] 主题选择持久化到 localStorage,登录页与主面板统一。
|
||||
- [x] UI 静态资源与 Go embed 资源保持同步,并完成 Node JS 语法、go test ./...、release build 验证。
|
||||
- [x] 用户已于 2026-09-28 人工验收通过;已重新构建 Hub 二进制并重启 systemd 服务,正式线上 UI 已立即生效。
|
||||
- [ ] M4 总体验收仍保留 Custom GPT Actions 正式联调、Key 轮换及最终人工签收门禁。
|
||||
|
||||
### M4 终验签收记录(2026-09-28)
|
||||
- [x] 安全清理:已彻底清除 `openapi.json` 中冗余残留的 `apiKey` 定义,统一收敛为标准 `bearerAuth`。
|
||||
- [x] 二次回归验证通过:全链路 API 鉴权、受控节点列表获取及本地命令执行均现场实测 100% PASS。
|
||||
|
||||
+181
-2
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
"github.com/wjyhk/vps-commander/internal/model"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
"github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
panelweb "github.com/wjyhk/vps-commander/internal/web"
|
||||
)
|
||||
|
||||
@@ -75,6 +76,157 @@ func (s *Server) AuditsJSON(w http.ResponseWriter, r *http.Request) {
|
||||
jsonOut(w, logs)
|
||||
}
|
||||
|
||||
type MCPServiceRequest struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command"`
|
||||
Args []string `json:"args"`
|
||||
Env map[string]string `json:"env"`
|
||||
URL string `json:"url"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Scope string `json:"scope"`
|
||||
TargetNodes []string `json:"target_nodes"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
type MCPCallRequest struct {
|
||||
Device string `json:"device"`
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Arguments any `json:"arguments"`
|
||||
}
|
||||
|
||||
func (s *Server) MCPServicesJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Store == nil {
|
||||
http.Error(w, "storage unavailable", 500)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
v, err := s.Store.ListMCPServices()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
jsonOut(w, v)
|
||||
case http.MethodPost:
|
||||
var q MCPServiceRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&q); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if q.ID == "" || q.Name == "" || q.Transport == "stdio" && q.Command == "" || (q.Transport != "stdio" && q.URL == "") {
|
||||
http.Error(w, "invalid MCP service", 400)
|
||||
return
|
||||
}
|
||||
args, _ := json.Marshal(q.Args)
|
||||
env, _ := json.Marshal(q.Env)
|
||||
headers, _ := json.Marshal(q.Headers)
|
||||
nodes, _ := json.Marshal(q.TargetNodes)
|
||||
if q.Scope == "" {
|
||||
q.Scope = "all"
|
||||
}
|
||||
if q.Scope != "all" && q.Scope != "custom" {
|
||||
http.Error(w, "invalid scope", 400)
|
||||
return
|
||||
}
|
||||
v := storage.MCPService{ID: q.ID, Name: q.Name, Description: q.Description, Transport: q.Transport, Command: q.Command, ArgsJSON: string(args), EnvJSON: string(env), URL: q.URL, HeadersJSON: string(headers), Scope: q.Scope, TargetNodesJSON: string(nodes), Enabled: q.Enabled}
|
||||
if err := s.Store.SaveMCPService(v); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if s.Cluster != nil {
|
||||
s.Cluster.SyncMCPServices()
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), "", "mcp_service_save", q.ID, 0, 0, "")
|
||||
jsonOut(w, v)
|
||||
default:
|
||||
http.Error(w, "method not allowed", 405)
|
||||
}
|
||||
}
|
||||
func (s *Server) DeleteMCPService(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
id := r.URL.Query().Get("id")
|
||||
if id == "" {
|
||||
http.Error(w, "id required", 400)
|
||||
return
|
||||
}
|
||||
if err := s.Store.DeleteMCPService(id); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if s.Cluster != nil {
|
||||
s.Cluster.SyncMCPServices()
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), "", "mcp_service_delete", id, 0, 0, "")
|
||||
jsonOut(w, map[string]any{"ok": true})
|
||||
}
|
||||
func (s *Server) ListAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
device := r.URL.Query().Get("device")
|
||||
if device == "" {
|
||||
http.Error(w, "device required", 400)
|
||||
return
|
||||
}
|
||||
if s.isRemote(device) && (s.Cluster == nil || !s.Cluster.Online(device)) {
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
if s.isRemote(device) {
|
||||
v, err := s.Cluster.ListMCP(device)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 404)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"device": device, "services": v})
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"device": s.LocalName, "services": []any{}})
|
||||
}
|
||||
func (s *Server) CallAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var q MCPCallRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&q); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if q.Device == "" || q.Server == "" || q.Tool == "" {
|
||||
http.Error(w, "device, server and tool required", 400)
|
||||
return
|
||||
}
|
||||
if s.isRemote(q.Device) && (s.Cluster == nil || !s.Cluster.Online(q.Device)) {
|
||||
if s.Store != nil {
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, 0, "device offline")
|
||||
}
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
if !s.isRemote(q.Device) {
|
||||
http.Error(w, "agent MCP requires a remote device", 400)
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
v, err := s.Cluster.CallMCP(r.Context(), q.Device, q.Server, q.Tool, q.Arguments)
|
||||
ms := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, ms, err.Error())
|
||||
http.Error(w, err.Error(), 502)
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 0, ms, "")
|
||||
jsonOut(w, v)
|
||||
}
|
||||
|
||||
func (s *Server) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/healthz", s.health)
|
||||
@@ -82,6 +234,10 @@ func (s *Server) Routes() http.Handler {
|
||||
mux.HandleFunc("/api/v1/exec", s.exec)
|
||||
mux.HandleFunc("/api/v1/file/read", s.fileRead)
|
||||
mux.HandleFunc("/api/v1/file/write", s.fileWrite)
|
||||
mux.HandleFunc("/api/v1/mcp/services", s.MCPServicesJSON)
|
||||
mux.HandleFunc("/api/v1/mcp/service", s.DeleteMCPService)
|
||||
mux.HandleFunc("/api/v1/mcp/list", s.ListAgentMCPJSON)
|
||||
mux.HandleFunc("/api/v1/mcp/call", s.CallAgentMCPJSON)
|
||||
mux.HandleFunc("/agent/ws", s.agentWS)
|
||||
mux.HandleFunc("/openapi.json", s.openapi)
|
||||
return mux
|
||||
@@ -104,7 +260,8 @@ func (s *Server) devices(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
out := []model.Device{{Name: s.LocalName, Status: "online", Local: true, Arch: runtime.GOARCH, OS: runtime.GOOS}}
|
||||
localProf := sysinfo.Collect("CONTROL")
|
||||
out := []model.Device{{Name: s.LocalName, Status: "online", Local: true, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &localProf}}
|
||||
if s.Cluster != nil {
|
||||
for _, d := range s.Cluster.Devices() {
|
||||
b, _ := json.Marshal(d)
|
||||
@@ -116,6 +273,28 @@ func (s *Server) devices(w http.ResponseWriter, r *http.Request) {
|
||||
jsonOut(w, out)
|
||||
}
|
||||
|
||||
func (s *Server) DeleteDevice(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.URL.Query().Get("name")
|
||||
if name == "" {
|
||||
http.Error(w, "device name required", 400)
|
||||
return
|
||||
}
|
||||
if name == s.LocalName || name == "local" {
|
||||
http.Error(w, "cannot delete local control node", 403)
|
||||
return
|
||||
}
|
||||
if s.Cluster != nil {
|
||||
if err := s.Cluster.RevokeDevice(name, "revoked by admin via web console"); err != nil {
|
||||
http.Error(w, "revoke failed: "+err.Error(), 500)
|
||||
return
|
||||
}
|
||||
} else if s.Store != nil {
|
||||
_ = s.Store.RevokeDevice(name, "revoked by admin via web console")
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), name, "revoke_device", "revoked by admin", 0, 0, "")
|
||||
jsonOut(w, map[string]any{"ok": true, "revoked": name})
|
||||
}
|
||||
|
||||
func (s *Server) agentWS(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Cluster == nil {
|
||||
http.Error(w, "cluster unavailable", 503)
|
||||
@@ -155,7 +334,7 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
|
||||
var res executor.Result
|
||||
if s.isRemote(req.Device) {
|
||||
if s.Cluster == nil || !s.Cluster.Online(req.Device) {
|
||||
http.Error(w, "device offline", 404)
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
rr, err := s.Cluster.Exec(ctx, req.Device, cluster.ExecPayload{Command: req.Command, Workdir: req.Workdir, Timeout: req.Timeout})
|
||||
|
||||
@@ -188,3 +188,38 @@ func (b *MCPBackend) WriteFile(ctx context.Context, clientIP, device, path, cont
|
||||
Bytes: n,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (b *MCPBackend) ListAgentMCP(ctx context.Context, device string) (any, error) {
|
||||
if device == "" {
|
||||
return nil, errors.New("device required")
|
||||
}
|
||||
if b.server.isRemote(device) && (b.server.Cluster == nil || !b.server.Cluster.Online(device)) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
if !b.server.isRemote(device) {
|
||||
return map[string]any{"device": b.server.LocalName, "services": []any{}}, nil
|
||||
}
|
||||
return b.server.Cluster.ListMCP(device)
|
||||
}
|
||||
func (b *MCPBackend) CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error) {
|
||||
if device == "" || server == "" || tool == "" {
|
||||
return nil, errors.New("device, server and tool required")
|
||||
}
|
||||
if b.server.isRemote(device) && (b.server.Cluster == nil || !b.server.Cluster.Online(device)) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
if !b.server.isRemote(device) {
|
||||
return nil, errors.New("agent MCP requires a remote device")
|
||||
}
|
||||
start := time.Now()
|
||||
v, err := b.server.Cluster.CallMCP(ctx, device, server, tool, args)
|
||||
ms := time.Since(start).Milliseconds()
|
||||
if b.server.Store != nil {
|
||||
if err != nil {
|
||||
_ = b.server.Store.Audit(clientIP, device, "mcp_call", server+"/"+tool, 1, ms, err.Error())
|
||||
} else {
|
||||
_ = b.server.Store.Audit(clientIP, device, "mcp_call", server+"/"+tool, 0, ms, "")
|
||||
}
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
@@ -157,6 +157,69 @@
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"MCPService": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
},
|
||||
"transport": {
|
||||
"type": "string"
|
||||
},
|
||||
"command": {
|
||||
"type": "string"
|
||||
},
|
||||
"args_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"env_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"headers_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"scope": {
|
||||
"type": "string"
|
||||
},
|
||||
"target_nodes_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"MCPCallRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"device",
|
||||
"server",
|
||||
"tool"
|
||||
],
|
||||
"properties": {
|
||||
"device": {
|
||||
"type": "string"
|
||||
},
|
||||
"server": {
|
||||
"type": "string"
|
||||
},
|
||||
"tool": {
|
||||
"type": "string"
|
||||
},
|
||||
"arguments": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -281,6 +344,135 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/services": {
|
||||
"get": {
|
||||
"operationId": "list_mcp_services",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "MCP services",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MCPService"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"operationId": "save_mcp_service",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MCPService"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Saved MCP service"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/service": {
|
||||
"delete": {
|
||||
"operationId": "delete_mcp_service",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Deleted"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/list": {
|
||||
"get": {
|
||||
"operationId": "list_agent_mcp",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "device",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Mounted MCP services"
|
||||
},
|
||||
"409": {
|
||||
"description": "Device offline"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/call": {
|
||||
"post": {
|
||||
"operationId": "call_agent_mcp",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MCPCallRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "MCP result"
|
||||
},
|
||||
"409": {
|
||||
"description": "Device offline"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+197
-28
@@ -12,20 +12,33 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
"github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
)
|
||||
|
||||
const deviceOfflineAfter = 70 * time.Second
|
||||
|
||||
type Manager struct {
|
||||
Secret string
|
||||
Store *storage.Store
|
||||
mu sync.RWMutex
|
||||
nodes map[string]*Node
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
Name string
|
||||
Conn *websocket.Conn
|
||||
WriteMu sync.Mutex
|
||||
Pending sync.Map
|
||||
LastSeen atomic.Int64
|
||||
Name string
|
||||
Conn *websocket.Conn
|
||||
ConnectionID string
|
||||
WriteMu sync.Mutex
|
||||
Pending sync.Map
|
||||
LastSeen atomic.Int64
|
||||
LastHeartbeat atomic.Int64
|
||||
Connected atomic.Bool
|
||||
LastProfile *sysinfo.Profile
|
||||
Arch string
|
||||
OS string
|
||||
IsLocal bool
|
||||
MCP *MCPRuntime
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
@@ -43,9 +56,36 @@ type FileResult struct {
|
||||
EOF bool `json:"eof"`
|
||||
}
|
||||
|
||||
func NewManager(secret string) *Manager {
|
||||
return &Manager{Secret: secret, nodes: make(map[string]*Node)}
|
||||
func NewManager(secret string, store *storage.Store) *Manager {
|
||||
m := &Manager{Secret: secret, Store: store, nodes: make(map[string]*Node)}
|
||||
if store != nil {
|
||||
if records, err := store.ListDevices(); err == nil {
|
||||
for _, d := range records {
|
||||
if d.IsLocal {
|
||||
continue
|
||||
}
|
||||
n := &Node{Name: d.Name, Arch: d.Arch, OS: d.OS, MCP: NewMCPRuntime()}
|
||||
n.LastSeen.Store(d.LastSeen * int64(time.Second))
|
||||
n.LastHeartbeat.Store(d.LastHeartbeat * int64(time.Second))
|
||||
if d.ProfileJSON != "" {
|
||||
var p sysinfo.Profile
|
||||
if json.Unmarshal([]byte(d.ProfileJSON), &p) == nil {
|
||||
n.LastProfile = &p
|
||||
}
|
||||
}
|
||||
n.Connected.Store(false)
|
||||
m.nodes[d.Name] = n
|
||||
_ = store.UpdateDeviceStatus(d.Name, "offline", d.LastHeartbeat)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *Manager) SetStore(s *storage.Store) {
|
||||
m.Store = s
|
||||
}
|
||||
|
||||
func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
provided := ""
|
||||
@@ -61,20 +101,32 @@ func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "device_name required", 400)
|
||||
return
|
||||
}
|
||||
|
||||
if m.Store != nil {
|
||||
if revoked, _ := m.Store.IsRevoked(name); revoked {
|
||||
http.Error(w, "device has been revoked by admin", 403)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
up := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
|
||||
c, err := up.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n := &Node{Name: name, Conn: c}
|
||||
n := &Node{Name: name, Conn: c, ConnectionID: fmt.Sprintf("%s-%d", name, time.Now().UnixNano()), MCP: NewMCPRuntime()}
|
||||
n.LastSeen.Store(time.Now().UnixNano())
|
||||
n.LastHeartbeat.Store(time.Now().UnixNano())
|
||||
n.Connected.Store(true)
|
||||
m.mu.Lock()
|
||||
if old := m.nodes[name]; old != nil {
|
||||
_ = old.Conn.Close()
|
||||
}
|
||||
old := m.nodes[name]
|
||||
m.nodes[name] = n
|
||||
m.mu.Unlock()
|
||||
if old != nil && old.Conn != nil {
|
||||
_ = old.Conn.Close()
|
||||
}
|
||||
_ = n.write(Message{Event: "registered", Device: name, TS: time.Now().Unix()})
|
||||
m.syncMCP(n)
|
||||
go m.heartbeat(n)
|
||||
go m.readLoop(n)
|
||||
}
|
||||
@@ -90,32 +142,61 @@ func (n *Node) write(msg Message) error {
|
||||
|
||||
func (m *Manager) readLoop(n *Node) {
|
||||
defer func() {
|
||||
m.mu.Lock()
|
||||
if m.nodes[n.Name] == n {
|
||||
delete(m.nodes, n.Name)
|
||||
n.Connected.Store(false)
|
||||
conn := n.Conn
|
||||
m.mu.RLock()
|
||||
current := m.nodes[n.Name] == n
|
||||
m.mu.RUnlock()
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
_ = n.Conn.Close()
|
||||
n.Pending.Range(func(key, v any) bool {
|
||||
if ch, ok := v.(chan Message); ok {
|
||||
select {
|
||||
case ch <- Message{Status: "error", Error: "device disconnected"}:
|
||||
default:
|
||||
}
|
||||
n.Pending.Delete(key)
|
||||
}
|
||||
n.Pending.Delete(key)
|
||||
return true
|
||||
})
|
||||
if current && m.Store != nil {
|
||||
_ = m.Store.UpdateDeviceStatus(n.Name, "offline", n.LastHeartbeat.Load()/int64(time.Second))
|
||||
}
|
||||
}()
|
||||
_ = n.Conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
conn := n.Conn
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
_ = conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
for {
|
||||
var msg Message
|
||||
if err := n.Conn.ReadJSON(&msg); err != nil {
|
||||
if err := conn.ReadJSON(&msg); err != nil {
|
||||
return
|
||||
}
|
||||
n.LastSeen.Store(time.Now().UnixNano())
|
||||
_ = n.Conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
if msg.Event == "pong" || msg.Event == "ping" {
|
||||
now := time.Now().UnixNano()
|
||||
n.LastSeen.Store(now)
|
||||
_ = conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
if msg.Arch != "" {
|
||||
n.Arch = msg.Arch
|
||||
}
|
||||
if msg.OS != "" {
|
||||
n.OS = msg.OS
|
||||
}
|
||||
if msg.Profile != nil {
|
||||
n.LastProfile = msg.Profile
|
||||
n.LastHeartbeat.Store(now)
|
||||
if m.Store != nil {
|
||||
b, _ := json.Marshal(msg.Profile)
|
||||
_ = m.Store.UpsertRemote(n.Name, "online", n.Arch, n.OS, now/int64(time.Second), string(b))
|
||||
}
|
||||
} else {
|
||||
n.LastHeartbeat.Store(now)
|
||||
if m.Store != nil {
|
||||
_ = m.Store.UpdateDeviceStatus(n.Name, "online", now/int64(time.Second))
|
||||
}
|
||||
}
|
||||
if msg.Event == "pong" || msg.Event == "ping" || msg.Event == "hello" || msg.Event == "profile" {
|
||||
continue
|
||||
}
|
||||
if msg.ID != "" {
|
||||
@@ -130,11 +211,33 @@ func (m *Manager) readLoop(n *Node) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) Online(name string) bool {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
n := m.nodes[name]
|
||||
return n != nil && time.Since(time.Unix(0, n.LastSeen.Load())) < 70*time.Second
|
||||
m.mu.RUnlock()
|
||||
if n == nil || !n.Connected.Load() {
|
||||
return false
|
||||
}
|
||||
return time.Since(time.Unix(0, n.LastSeen.Load())) < deviceOfflineAfter
|
||||
}
|
||||
|
||||
func (m *Manager) RevokeDevice(name, reason string) error {
|
||||
m.mu.Lock()
|
||||
n := m.nodes[name]
|
||||
delete(m.nodes, name)
|
||||
m.mu.Unlock()
|
||||
if n != nil {
|
||||
n.Connected.Store(false)
|
||||
if n.Conn != nil {
|
||||
_ = n.write(Message{Event: "revoked", Error: "revoked by admin"})
|
||||
_ = n.Conn.Close()
|
||||
}
|
||||
}
|
||||
if m.Store != nil {
|
||||
return m.Store.RevokeDevice(name, reason)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) Devices() []map[string]any {
|
||||
@@ -142,12 +245,20 @@ func (m *Manager) Devices() []map[string]any {
|
||||
defer m.mu.RUnlock()
|
||||
out := make([]map[string]any, 0, len(m.nodes))
|
||||
for name, n := range m.nodes {
|
||||
status := "online"
|
||||
status := "offline"
|
||||
lastSeen := time.Unix(0, n.LastSeen.Load())
|
||||
if time.Since(lastSeen) >= 70*time.Second {
|
||||
status = "offline"
|
||||
if n.Connected.Load() && time.Since(lastSeen) < deviceOfflineAfter {
|
||||
status = "online"
|
||||
}
|
||||
out = append(out, map[string]any{"name": name, "status": status, "is_local": false, "last_heartbeat": lastSeen.Unix()})
|
||||
item := map[string]any{
|
||||
"name": name, "status": status, "is_local": n.IsLocal,
|
||||
"arch": n.Arch, "os": n.OS,
|
||||
"last_heartbeat": n.LastHeartbeat.Load() / int64(time.Second),
|
||||
}
|
||||
if n.LastProfile != nil {
|
||||
item["profile"] = n.LastProfile
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -180,6 +291,7 @@ func (m *Manager) call(ctx context.Context, name, action string, payload any) (M
|
||||
return Message{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) Exec(ctx context.Context, name string, p ExecPayload) (Result, error) {
|
||||
msg, err := m.call(ctx, name, "exec", p)
|
||||
if err != nil {
|
||||
@@ -216,6 +328,63 @@ func (m *Manager) WriteFile(ctx context.Context, name string, p FileWritePayload
|
||||
return v.Bytes, nil
|
||||
}
|
||||
|
||||
func (m *Manager) syncMCP(n *Node) {
|
||||
if n == nil || n.MCP == nil || m.Store == nil {
|
||||
return
|
||||
}
|
||||
services, err := m.Store.ListMCPServicesForNode(n.Name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = n.write(Message{Event: "mcp_sync", Payload: services, TS: time.Now().Unix()})
|
||||
}
|
||||
|
||||
func (m *Manager) SyncMCPServices() {
|
||||
m.mu.RLock()
|
||||
nodes := make([]*Node, 0, len(m.nodes))
|
||||
for _, n := range m.nodes {
|
||||
nodes = append(nodes, n)
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
for _, n := range nodes {
|
||||
if n.Connected.Load() {
|
||||
m.syncMCP(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) ListMCP(name string) ([]MCPService, error) {
|
||||
m.mu.RLock()
|
||||
n := m.nodes[name]
|
||||
m.mu.RUnlock()
|
||||
if n == nil {
|
||||
return nil, fmt.Errorf("device %s not found", name)
|
||||
}
|
||||
if n.MCP == nil {
|
||||
n.MCP = NewMCPRuntime()
|
||||
}
|
||||
return n.MCP.List(), nil
|
||||
}
|
||||
|
||||
func (m *Manager) CallMCP(ctx context.Context, name, server, tool string, args any) (MCPCallResult, error) {
|
||||
m.mu.RLock()
|
||||
n := m.nodes[name]
|
||||
m.mu.RUnlock()
|
||||
if n == nil || !m.Online(name) {
|
||||
return MCPCallResult{}, fmt.Errorf("device %s is offline", name)
|
||||
}
|
||||
msg, err := m.call(ctx, name, "mcp_call", map[string]any{"server": server, "tool": tool, "args": args})
|
||||
if err != nil {
|
||||
return MCPCallResult{}, err
|
||||
}
|
||||
var out MCPCallResult
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return MCPCallResult{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Manager) heartbeat(n *Node) {
|
||||
t := time.NewTicker(30 * time.Second)
|
||||
defer t.Stop()
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type MCPService struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
}
|
||||
|
||||
type MCPCallResult struct {
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
}
|
||||
|
||||
type mcpRPC struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id,omitempty"`
|
||||
Method string `json:"method"`
|
||||
Params any `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type mcpRPCResponse struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id,omitempty"`
|
||||
Result json.RawMessage `json:"result,omitempty"`
|
||||
Error *struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type MCPRuntime struct {
|
||||
mu sync.RWMutex
|
||||
services map[string]MCPService
|
||||
}
|
||||
|
||||
func NewMCPRuntime() *MCPRuntime { return &MCPRuntime{services: make(map[string]MCPService)} }
|
||||
|
||||
func (r *MCPRuntime) Sync(services []MCPService) {
|
||||
next := make(map[string]MCPService, len(services))
|
||||
for _, s := range services {
|
||||
if s.ID == "" || s.Transport == "" {
|
||||
continue
|
||||
}
|
||||
next[s.ID] = s
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.services = next
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *MCPRuntime) List() []MCPService {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
out := make([]MCPService, 0, len(r.services))
|
||||
for _, s := range r.services {
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *MCPRuntime) Get(id string) (MCPService, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
s, ok := r.services[id]
|
||||
return s, ok
|
||||
}
|
||||
|
||||
func (r *MCPRuntime) Call(ctx context.Context, server, tool string, args any) (any, error) {
|
||||
s, ok := r.Get(server)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("MCP service %q is not mounted", server)
|
||||
}
|
||||
switch strings.ToLower(s.Transport) {
|
||||
case "stdio":
|
||||
return callStdio(ctx, s, tool, args)
|
||||
case "http", "sse":
|
||||
return callHTTP(ctx, s, tool, args)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported MCP transport %q", s.Transport)
|
||||
}
|
||||
}
|
||||
|
||||
func callStdio(ctx context.Context, s MCPService, tool string, args any) (any, error) {
|
||||
if s.Command == "" {
|
||||
return nil, errors.New("MCP stdio command is empty")
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, s.Command, s.Args...)
|
||||
if len(s.Env) > 0 {
|
||||
cmd.Env = append(os.Environ(), envList(s.Env)...)
|
||||
}
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cmd.Stderr = io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }()
|
||||
|
||||
enc := json.NewEncoder(stdin)
|
||||
dec := bufio.NewReaderSize(stdout, 64*1024)
|
||||
id := int64(1)
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: id, Method: "initialize", Params: map[string]any{
|
||||
"protocolVersion": "2024-11-05", "capabilities": map[string]any{},
|
||||
"clientInfo": map[string]string{"name": "vps-commander-agent", "version": "1.0"},
|
||||
}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := readRPC(ctx, dec, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id++
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: id, Method: "tools/call", Params: map[string]any{"name": tool, "arguments": args}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return readRPC(ctx, dec, id)
|
||||
}
|
||||
|
||||
func readRPC(ctx context.Context, r *bufio.Reader, wantID int64) (any, error) {
|
||||
for {
|
||||
lineCh := make(chan []byte, 1)
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
b, err := r.ReadBytes('\n')
|
||||
if err != nil && len(b) == 0 {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
lineCh <- bytes.TrimSpace(b)
|
||||
}()
|
||||
var line []byte
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case err := <-errCh:
|
||||
return nil, err
|
||||
case line = <-lineCh:
|
||||
}
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
var resp mcpRPCResponse
|
||||
if json.Unmarshal(line, &resp) != nil {
|
||||
continue
|
||||
}
|
||||
if resp.ID == nil {
|
||||
continue
|
||||
}
|
||||
if n, ok := resp.ID.(float64); !ok || int64(n) != wantID {
|
||||
continue
|
||||
}
|
||||
if resp.Error != nil {
|
||||
return nil, fmt.Errorf("MCP error %d: %s", resp.Error.Code, resp.Error.Message)
|
||||
}
|
||||
var out any
|
||||
if len(resp.Result) > 0 {
|
||||
if err := json.Unmarshal(resp.Result, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
|
||||
func callHTTP(ctx context.Context, s MCPService, tool string, args any) (any, error) {
|
||||
if s.URL == "" {
|
||||
return nil, errors.New("MCP HTTP URL is empty")
|
||||
}
|
||||
client := &http.Client{Timeout: 0}
|
||||
var session string
|
||||
post := func(req mcpRPC) (any, http.Header, error) {
|
||||
b, _ := json.Marshal(req)
|
||||
h := make(http.Header)
|
||||
h.Set("Content-Type", "application/json")
|
||||
h.Set("Accept", "application/json, text/event-stream")
|
||||
for k, v := range s.Headers {
|
||||
h.Set(k, v)
|
||||
}
|
||||
if session != "" {
|
||||
h.Set("Mcp-Session-Id", session)
|
||||
}
|
||||
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, s.URL, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
hr.Header = h
|
||||
resp, err := client.Do(hr)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, resp.Header, fmt.Errorf("MCP HTTP status %s", resp.Status)
|
||||
}
|
||||
if v := resp.Header.Get("Mcp-Session-Id"); v != "" {
|
||||
session = v
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil, resp.Header, nil
|
||||
}
|
||||
if bytes.Contains(data, []byte("event:")) {
|
||||
data = parseSSEData(data)
|
||||
}
|
||||
var rr mcpRPCResponse
|
||||
if err := json.Unmarshal(bytes.TrimSpace(data), &rr); err != nil {
|
||||
return nil, resp.Header, err
|
||||
}
|
||||
if rr.Error != nil {
|
||||
return nil, resp.Header, fmt.Errorf("MCP error %d: %s", rr.Error.Code, rr.Error.Message)
|
||||
}
|
||||
var out any
|
||||
if len(rr.Result) > 0 {
|
||||
if err := json.Unmarshal(rr.Result, &out); err != nil {
|
||||
return nil, resp.Header, err
|
||||
}
|
||||
}
|
||||
return out, resp.Header, nil
|
||||
}
|
||||
if strings.EqualFold(s.Transport, "sse") {
|
||||
endpoint, err := discoverSSEEndpoint(ctx, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
old := s.URL
|
||||
s.URL = endpoint
|
||||
defer func() { s.URL = old }()
|
||||
}
|
||||
if _, _, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(1), Method: "initialize", Params: map[string]any{"protocolVersion": "2024-11-05", "capabilities": map[string]any{}, "clientInfo": map[string]string{"name": "vps-commander-agent", "version": "1.0"}}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, _, err := post(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return func() (any, error) {
|
||||
v, _, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(2), Method: "tools/call", Params: map[string]any{"name": tool, "arguments": args}})
|
||||
return v, err
|
||||
}()
|
||||
}
|
||||
|
||||
func discoverSSEEndpoint(ctx context.Context, s MCPService) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for k, v := range s.Headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("MCP SSE status %s", resp.Status)
|
||||
}
|
||||
sc := bufio.NewScanner(io.LimitReader(resp.Body, 256*1024))
|
||||
isEndpoint := false
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if strings.HasPrefix(line, "event:") {
|
||||
isEndpoint = strings.TrimSpace(strings.TrimPrefix(line, "event:")) == "endpoint"
|
||||
continue
|
||||
}
|
||||
if isEndpoint && strings.HasPrefix(line, "data:") {
|
||||
u := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
if strings.HasPrefix(u, "/") {
|
||||
base := *resp.Request.URL
|
||||
base.Path = u
|
||||
base.RawQuery = ""
|
||||
return base.String(), nil
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("MCP SSE endpoint event not received")
|
||||
}
|
||||
|
||||
func parseSSEData(b []byte) []byte {
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
return []byte(strings.TrimSpace(strings.TrimPrefix(line, "data:")))
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
func envList(m map[string]string) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k, v := range m {
|
||||
out = append(out, k+"="+v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMCPRuntimeStdioOnDemand(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("python3 unavailable")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
script := dir + "/mcp.py"
|
||||
code := `import json,sys
|
||||
for line in sys.stdin:
|
||||
r=json.loads(line)
|
||||
if r.get("method")=="initialize":
|
||||
print(json.dumps({"jsonrpc":"2.0","id":r["id"],"result":{"protocolVersion":"2024-11-05"}}),flush=True)
|
||||
elif r.get("method")=="tools/call":
|
||||
a=r.get("params",{}).get("arguments",{})
|
||||
print(json.dumps({"jsonrpc":"2.0","id":r["id"],"result":{"content":[{"type":"text","text":"hello "+a.get("name","")}]}}),flush=True)
|
||||
`
|
||||
if err := os.WriteFile(script, []byte(code), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := NewMCPRuntime()
|
||||
r.Sync([]MCPService{{ID: "test", Transport: "stdio", Command: "python3", Args: []string{script}}})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
v, err := r.Call(ctx, "test", "hello", map[string]any{"name": "vpc"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := json.Marshal(v)
|
||||
if string(b) == "" {
|
||||
t.Fatal("empty result")
|
||||
}
|
||||
if !contains(string(b), "hello vpc") {
|
||||
t.Fatalf("unexpected %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPRuntimeHTTP(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var q mcpRPC
|
||||
_ = json.Unmarshal(b, &q)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%s,"result":{"ok":true}}`, jsonID(q.ID))
|
||||
}))
|
||||
defer ts.Close()
|
||||
r := NewMCPRuntime()
|
||||
r.Sync([]MCPService{{ID: "http", Transport: "http", URL: ts.URL}})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
v, err := r.Call(ctx, "http", "ping", map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !contains(fmt.Sprint(v), "true") {
|
||||
t.Fatalf("unexpected %v", v)
|
||||
}
|
||||
}
|
||||
func jsonID(v any) string { b, _ := json.Marshal(v); return string(b) }
|
||||
func contains(s, x string) bool {
|
||||
for i := 0; i+len(x) <= len(s); i++ {
|
||||
if s[i:i+len(x)] == x {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,18 +1,23 @@
|
||||
package cluster
|
||||
|
||||
import "github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Event string `json:"event,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Payload any `json:"payload,omitempty"`
|
||||
ExitCode int `json:"exit_code,omitempty"`
|
||||
Stdout string `json:"stdout,omitempty"`
|
||||
Stderr string `json:"stderr,omitempty"`
|
||||
DurationMS int64 `json:"duration_ms,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
TS int64 `json:"ts,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Event string `json:"event,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Payload any `json:"payload,omitempty"`
|
||||
Profile *sysinfo.Profile `json:"profile,omitempty"`
|
||||
ExitCode int `json:"exit_code,omitempty"`
|
||||
Stdout string `json:"stdout,omitempty"`
|
||||
Stderr string `json:"stderr,omitempty"`
|
||||
DurationMS int64 `json:"duration_ms,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
TS int64 `json:"ts,omitempty"`
|
||||
}
|
||||
|
||||
type ExecPayload struct {
|
||||
|
||||
@@ -76,6 +76,11 @@ type ActionBackend interface {
|
||||
WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error)
|
||||
}
|
||||
|
||||
type AgentMCPBackend interface {
|
||||
ListAgentMCP(ctx context.Context, device string) (any, error)
|
||||
CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error)
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
Backend ActionBackend
|
||||
Auth *auth.Manager
|
||||
@@ -272,6 +277,14 @@ func (s *Server) handleRequest(ctx context.Context, r *http.Request, req JSONRPC
|
||||
Required: []string{"path", "content"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "list_agent_mcp", Description: "列出指定 Agent 当前通过 Hub 动态挂载的 MCP 服务及状态",
|
||||
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标 Agent 节点名称"}}, Required: []string{"device"}},
|
||||
},
|
||||
{
|
||||
Name: "call_agent_mcp", Description: "通过 Hub 调度指定 Agent 上已挂载的 MCP 工具",
|
||||
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标 Agent 节点名称"}, "server": {Type: "string", Description: "MCP 服务 ID"}, "tool": {Type: "string", Description: "MCP 工具名称"}, "arguments": {Type: "object", Description: "MCP 工具参数 JSON 对象"}}, Required: []string{"device", "server", "tool"}},
|
||||
},
|
||||
}
|
||||
return JSONRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
@@ -372,6 +385,43 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
|
||||
}
|
||||
return res, false
|
||||
|
||||
case "list_agent_mcp":
|
||||
var args struct {
|
||||
Device string `json:"device"`
|
||||
}
|
||||
_ = json.Unmarshal(params.Arguments, &args)
|
||||
b, ok := s.Backend.(AgentMCPBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "agent MCP unavailable"}, true
|
||||
}
|
||||
res, err := b.ListAgentMCP(ctx, args.Device)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
|
||||
case "call_agent_mcp":
|
||||
var args struct {
|
||||
Device string `json:"device"`
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
_ = json.Unmarshal(params.Arguments, &args)
|
||||
b, ok := s.Backend.(AgentMCPBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "agent MCP unavailable"}, true
|
||||
}
|
||||
var av any
|
||||
if len(args.Arguments) > 0 {
|
||||
_ = json.Unmarshal(args.Arguments, &av)
|
||||
}
|
||||
res, err := b.CallAgentMCP(ctx, clientIP, args.Device, args.Server, args.Tool, av)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
|
||||
default:
|
||||
return map[string]string{"error": "unknown tool: " + params.Name}, true
|
||||
}
|
||||
|
||||
@@ -75,8 +75,8 @@ func TestMCPInitializeAndListTools(t *testing.T) {
|
||||
t.Fatalf("expected map result")
|
||||
}
|
||||
tools, ok := resMap["tools"].([]any)
|
||||
if !ok || len(tools) != 4 {
|
||||
t.Fatalf("expected 4 tools, got %d", len(tools))
|
||||
if !ok || len(tools) != 6 {
|
||||
t.Fatalf("expected 6 tools, got %d", len(tools))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package model
|
||||
|
||||
import "github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
|
||||
type ExecRequest struct {
|
||||
Device string `json:"device,omitempty"`
|
||||
Command string `json:"command"`
|
||||
@@ -16,11 +18,12 @@ type ExecResponse struct {
|
||||
}
|
||||
|
||||
type Device struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Local bool `json:"is_local"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Local bool `json:"is_local"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
Profile *sysinfo.Profile `json:"profile,omitempty"`
|
||||
}
|
||||
|
||||
type FileReadRequest struct {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeviceLifecyclePersistence(t *testing.T) {
|
||||
s, err := Open(filepath.Join(t.TempDir(), "commander.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.DB.Close()
|
||||
|
||||
if err := s.UpsertRemote("node1", "online", "amd64", "linux", 100, "{\"role\":\"APPLICATION\"}"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, err := s.ListDevices()
|
||||
if err != nil || len(rows) != 1 {
|
||||
t.Fatalf("rows=%d err=%v", len(rows), err)
|
||||
}
|
||||
if rows[0].Status != "online" || rows[0].Arch != "amd64" || rows[0].OS != "linux" {
|
||||
t.Fatalf("unexpected row: %+v", rows[0])
|
||||
}
|
||||
|
||||
if err := s.UpdateDeviceStatus("node1", "offline", 120); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, err = s.ListDevices()
|
||||
if err != nil || len(rows) != 1 {
|
||||
t.Fatalf("rows=%d err=%v", len(rows), err)
|
||||
}
|
||||
if rows[0].Status != "offline" || rows[0].OfflineAt == nil {
|
||||
t.Fatalf("offline state not persisted: %+v", rows[0])
|
||||
}
|
||||
|
||||
if err := s.RevokeDevice("node1", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, err = s.ListDevices()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 0 {
|
||||
t.Fatalf("revoked device still present: %+v", rows)
|
||||
}
|
||||
revoked, err := s.IsRevoked("node1")
|
||||
if err != nil || !revoked {
|
||||
t.Fatalf("revoked=%v err=%v", revoked, err)
|
||||
}
|
||||
}
|
||||
+253
-20
@@ -2,6 +2,8 @@ package storage
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
_ "modernc.org/sqlite"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -18,8 +20,6 @@ func Open(path string) (*Store, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// SQLite has a single-writer model. Keep one application connection so
|
||||
// concurrent callers queue instead of opening competing writer connections.
|
||||
db.SetMaxOpenConns(1)
|
||||
db.SetMaxIdleConns(1)
|
||||
s := &Store{db}
|
||||
@@ -31,28 +31,235 @@ func Open(path string) (*Store, error) {
|
||||
}
|
||||
|
||||
func (s *Store) init() error {
|
||||
if _, err := s.DB.Exec(`PRAGMA journal_mode = WAL`); err != nil {
|
||||
if _, err := s.DB.Exec("PRAGMA journal_mode = WAL"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.DB.Exec(`PRAGMA busy_timeout = 5000`); err != nil {
|
||||
if _, err := s.DB.Exec("PRAGMA busy_timeout = 5000"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS devices (
|
||||
name TEXT PRIMARY KEY, status TEXT NOT NULL, is_local INTEGER NOT NULL,
|
||||
arch TEXT, os TEXT, updated_at INTEGER NOT NULL
|
||||
); CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL,
|
||||
caller_ip TEXT, device TEXT, action TEXT, command TEXT,
|
||||
exit_code INTEGER, duration_ms INTEGER, error_msg TEXT
|
||||
);`)
|
||||
_, err := s.DB.Exec("CREATE TABLE IF NOT EXISTS devices (" +
|
||||
"name TEXT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'offline', is_local INTEGER NOT NULL DEFAULT 0, " +
|
||||
"arch TEXT, os TEXT, last_seen INTEGER NOT NULL DEFAULT 0, last_heartbeat INTEGER NOT NULL DEFAULT 0, " +
|
||||
"offline_at INTEGER, profile_json TEXT, created_at INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0); " +
|
||||
"CREATE TABLE IF NOT EXISTS audit_logs (" +
|
||||
"id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL, caller_ip TEXT, device TEXT, action TEXT, command TEXT, " +
|
||||
"exit_code INTEGER, duration_ms INTEGER, error_msg TEXT); " +
|
||||
"CREATE TABLE IF NOT EXISTS revoked_devices (name TEXT PRIMARY KEY, revoked_at INTEGER NOT NULL, reason TEXT); CREATE TABLE IF NOT EXISTS mcp_services (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, transport TEXT NOT NULL, command TEXT, args_json TEXT, env_json TEXT, url TEXT, headers_json TEXT, scope TEXT NOT NULL DEFAULT 'all', target_nodes_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_mcp_services_enabled ON mcp_services(enabled);")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateDevices()
|
||||
}
|
||||
|
||||
type MCPService struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command,omitempty"`
|
||||
ArgsJSON string `json:"args_json,omitempty"`
|
||||
EnvJSON string `json:"env_json,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
HeadersJSON string `json:"headers_json,omitempty"`
|
||||
Scope string `json:"scope"`
|
||||
TargetNodesJSON string `json:"target_nodes_json,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s *Store) SaveMCPService(v MCPService) error {
|
||||
now := time.Now().Unix()
|
||||
if v.CreatedAt <= 0 {
|
||||
v.CreatedAt = now
|
||||
}
|
||||
v.UpdatedAt = now
|
||||
if v.Scope == "" {
|
||||
v.Scope = "all"
|
||||
}
|
||||
if v.Transport == "" {
|
||||
return errors.New("transport required")
|
||||
}
|
||||
_, err := s.DB.Exec(`INSERT INTO mcp_services(id,name,description,transport,command,args_json,env_json,url,headers_json,scope,target_nodes_json,enabled,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,description=excluded.description,transport=excluded.transport,command=excluded.command,args_json=excluded.args_json,env_json=excluded.env_json,url=excluded.url,headers_json=excluded.headers_json,scope=excluded.scope,target_nodes_json=excluded.target_nodes_json,enabled=excluded.enabled,updated_at=excluded.updated_at`,
|
||||
v.ID, v.Name, v.Description, v.Transport, v.Command, v.ArgsJSON, v.EnvJSON, v.URL, v.HeadersJSON, v.Scope, v.TargetNodesJSON, boolInt(v.Enabled), v.CreatedAt, v.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
func boolInt(v bool) int {
|
||||
if v {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
func (s *Store) DeleteMCPService(id string) error {
|
||||
_, err := s.DB.Exec(`DELETE FROM mcp_services WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) ListMCPServices() ([]MCPService, error) {
|
||||
return s.listMCP(`SELECT id,name,description,transport,COALESCE(command,''),COALESCE(args_json,''),COALESCE(env_json,''),COALESCE(url,''),COALESCE(headers_json,''),scope,COALESCE(target_nodes_json,''),enabled,created_at,updated_at FROM mcp_services ORDER BY id`)
|
||||
}
|
||||
func (s *Store) ListMCPServicesForNode(node string) ([]MCPService, error) {
|
||||
all, err := s.listMCP(`SELECT id,name,description,transport,COALESCE(command,''),COALESCE(args_json,''),COALESCE(env_json,''),COALESCE(url,''),COALESCE(headers_json,''),scope,COALESCE(target_nodes_json,''),enabled,created_at,updated_at FROM mcp_services WHERE enabled=1 ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]MCPService, 0, len(all))
|
||||
for _, v := range all {
|
||||
if v.Scope != "custom" || containsNode(v.TargetNodesJSON, node) {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func containsNode(raw, node string) bool {
|
||||
var a []string
|
||||
if json.Unmarshal([]byte(raw), &a) != nil {
|
||||
return false
|
||||
}
|
||||
for _, v := range a {
|
||||
if v == node {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *Store) listMCP(q string) ([]MCPService, error) {
|
||||
rows, err := s.DB.Query(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []MCPService{}
|
||||
for rows.Next() {
|
||||
var v MCPService
|
||||
var en int
|
||||
if err := rows.Scan(&v.ID, &v.Name, &v.Description, &v.Transport, &v.Command, &v.ArgsJSON, &v.EnvJSON, &v.URL, &v.HeadersJSON, &v.Scope, &v.TargetNodesJSON, &en, &v.CreatedAt, &v.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.Enabled = en != 0
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) migrateDevices() error {
|
||||
cols := map[string]bool{}
|
||||
rows, err := s.DB.Query("PRAGMA table_info(devices)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var cid, notnull, pk int
|
||||
var name, typ string
|
||||
var dflt sql.NullString
|
||||
if err := rows.Scan(&cid, &name, &typ, ¬null, &dflt, &pk); err != nil {
|
||||
return err
|
||||
}
|
||||
cols[name] = true
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
migrations := []struct{ name, sql string }{
|
||||
{"last_seen", "ALTER TABLE devices ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0"},
|
||||
{"last_heartbeat", "ALTER TABLE devices ADD COLUMN last_heartbeat INTEGER NOT NULL DEFAULT 0"},
|
||||
{"offline_at", "ALTER TABLE devices ADD COLUMN offline_at INTEGER"},
|
||||
{"profile_json", "ALTER TABLE devices ADD COLUMN profile_json TEXT"},
|
||||
{"created_at", "ALTER TABLE devices ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0"},
|
||||
}
|
||||
for _, m := range migrations {
|
||||
if !cols[m.name] {
|
||||
if _, err := s.DB.Exec(m.sql); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
_, err = s.DB.Exec("UPDATE devices SET created_at=CASE WHEN created_at=0 THEN updated_at ELSE created_at END, " +
|
||||
"last_seen=CASE WHEN last_seen=0 THEN updated_at ELSE last_seen END, " +
|
||||
"last_heartbeat=CASE WHEN last_heartbeat=0 THEN updated_at ELSE last_heartbeat END " +
|
||||
"WHERE created_at=0 OR last_seen=0 OR last_heartbeat=0")
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpsertLocal(name, arch, osName string) error {
|
||||
_, err := s.DB.Exec(`INSERT INTO devices(name,status,is_local,arch,os,updated_at)
|
||||
VALUES(?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status=excluded.status,
|
||||
arch=excluded.arch, os=excluded.os, updated_at=excluded.updated_at`,
|
||||
name, "online", 1, arch, osName, time.Now().Unix())
|
||||
now := time.Now().Unix()
|
||||
_, err := s.DB.Exec("INSERT INTO devices(name,status,is_local,arch,os,last_seen,last_heartbeat,offline_at,profile_json,created_at,updated_at) "+
|
||||
"VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status='online', is_local=1, arch=excluded.arch, os=excluded.os, offline_at=NULL, updated_at=excluded.updated_at",
|
||||
name, "online", 1, arch, osName, now, now, nil, nil, now, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpsertRemote(name, status, arch, osName string, lastHeartbeat int64, profileJSON string) error {
|
||||
now := time.Now().Unix()
|
||||
if lastHeartbeat <= 0 {
|
||||
lastHeartbeat = now
|
||||
}
|
||||
_, err := s.DB.Exec("INSERT INTO devices(name,status,is_local,arch,os,last_seen,last_heartbeat,offline_at,profile_json,created_at,updated_at) "+
|
||||
"VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status=excluded.status, is_local=0, arch=excluded.arch, os=excluded.os, "+
|
||||
"last_seen=excluded.last_seen, last_heartbeat=excluded.last_heartbeat, offline_at=NULL, profile_json=excluded.profile_json, updated_at=excluded.updated_at",
|
||||
name, status, 0, arch, osName, lastHeartbeat, lastHeartbeat, nil, profileJSON, now, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateRemoteProfile(name string, lastHeartbeat int64, arch, osName, profileJSON string) error {
|
||||
now := time.Now().Unix()
|
||||
if lastHeartbeat <= 0 {
|
||||
lastHeartbeat = now
|
||||
}
|
||||
_, err := s.DB.Exec("UPDATE devices SET status='online', arch=?, os=?, last_seen=?, last_heartbeat=?, offline_at=NULL, profile_json=?, updated_at=? WHERE name=? AND is_local=0",
|
||||
arch, osName, lastHeartbeat, lastHeartbeat, profileJSON, now, name)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateDeviceStatus(name, status string, lastHeartbeat int64) error {
|
||||
now := time.Now().Unix()
|
||||
if lastHeartbeat <= 0 {
|
||||
lastHeartbeat = now
|
||||
}
|
||||
var offlineAt any
|
||||
if status == "offline" {
|
||||
offlineAt = now
|
||||
}
|
||||
_, err := s.DB.Exec("UPDATE devices SET status=?, last_seen=?, last_heartbeat=?, offline_at=?, updated_at=? WHERE name=? AND is_local=0",
|
||||
status, lastHeartbeat, lastHeartbeat, offlineAt, now, name)
|
||||
return err
|
||||
}
|
||||
|
||||
type DeviceRecord struct {
|
||||
Name, Status, Arch, OS, ProfileJSON string
|
||||
IsLocal bool
|
||||
LastSeen, LastHeartbeat int64
|
||||
OfflineAt *int64
|
||||
UpdatedAt int64
|
||||
}
|
||||
|
||||
func (s *Store) ListDevices() ([]DeviceRecord, error) {
|
||||
rows, err := s.DB.Query("SELECT name,status,is_local,COALESCE(arch,''),COALESCE(os,''),last_seen,last_heartbeat,offline_at,COALESCE(profile_json,''),updated_at FROM devices ORDER BY name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []DeviceRecord
|
||||
for rows.Next() {
|
||||
var d DeviceRecord
|
||||
var local int
|
||||
var offline sql.NullInt64
|
||||
if err := rows.Scan(&d.Name, &d.Status, &local, &d.Arch, &d.OS, &d.LastSeen, &d.LastHeartbeat, &offline, &d.ProfileJSON, &d.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.IsLocal = local != 0
|
||||
if offline.Valid {
|
||||
v := offline.Int64
|
||||
d.OfflineAt = &v
|
||||
}
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) DeleteDevice(name string) error {
|
||||
_, err := s.DB.Exec("DELETE FROM devices WHERE name=? AND is_local=0", name)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -69,8 +276,8 @@ type AuditLog struct {
|
||||
}
|
||||
|
||||
func (s *Store) Audit(ip, device, action, command string, code int, ms int64, msg string) error {
|
||||
_, err := s.DB.Exec(`INSERT INTO audit_logs(timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg)
|
||||
VALUES(?,?,?,?,?,?,?,?)`, time.Now().Unix(), ip, device, action, command, code, ms, msg)
|
||||
_, err := s.DB.Exec("INSERT INTO audit_logs(timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg) VALUES(?,?,?,?,?,?,?,?)",
|
||||
time.Now().Unix(), ip, device, action, command, code, ms, msg)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -81,8 +288,7 @@ func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
|
||||
if limit > 500 {
|
||||
limit = 500
|
||||
}
|
||||
rows, err := s.DB.Query(`SELECT id,timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg
|
||||
FROM audit_logs ORDER BY id DESC LIMIT ?`, limit)
|
||||
rows, err := s.DB.Query("SELECT id,timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg FROM audit_logs ORDER BY id DESC LIMIT ?", limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -97,3 +303,30 @@ func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RevokeDevice(name, reason string) error {
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec("INSERT INTO revoked_devices(name,revoked_at,reason) VALUES(?,?,?) ON CONFLICT(name) DO UPDATE SET revoked_at=excluded.revoked_at,reason=excluded.reason",
|
||||
name, time.Now().Unix(), reason); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec("DELETE FROM devices WHERE name=? AND is_local=0", name); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) UnrevokeDevice(name string) error {
|
||||
_, err := s.DB.Exec("DELETE FROM revoked_devices WHERE name = ?", name)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) IsRevoked(name string) (bool, error) {
|
||||
var count int
|
||||
err := s.DB.QueryRow("SELECT COUNT(*) FROM revoked_devices WHERE name = ?", name).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
package sysinfo
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Profile struct {
|
||||
Role string `json:"role,omitempty"`
|
||||
CPUCores int `json:"cpu_cores"`
|
||||
CPUUsagePercent int `json:"cpu_usage_percent"`
|
||||
Load1M float64 `json:"load_1m"`
|
||||
MemPercent int `json:"mem_percent"`
|
||||
MemAvailable string `json:"mem_available"`
|
||||
DiskPercent int `json:"disk_percent"`
|
||||
DiskFree string `json:"disk_free"`
|
||||
IOPSI float64 `json:"io_psi"`
|
||||
Docker bool `json:"docker"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
func Collect(defaultRole string) Profile {
|
||||
role := os.Getenv("VPS_COMMANDER_ROLE")
|
||||
if role == "" {
|
||||
role = defaultRole
|
||||
}
|
||||
if role == "" {
|
||||
role = "APPLICATION"
|
||||
}
|
||||
|
||||
cores := runtime.NumCPU()
|
||||
cpuPercent := getCPUUsage()
|
||||
load1m := getLoad1M()
|
||||
memPct, memAvl := getMemInfo()
|
||||
diskPct, diskFree := getDiskInfo()
|
||||
psi := getIOPSI()
|
||||
docker := hasDocker()
|
||||
|
||||
return Profile{
|
||||
Role: role,
|
||||
CPUCores: cores,
|
||||
CPUUsagePercent: cpuPercent,
|
||||
Load1M: load1m,
|
||||
MemPercent: memPct,
|
||||
MemAvailable: memAvl,
|
||||
DiskPercent: diskPct,
|
||||
DiskFree: diskFree,
|
||||
IOPSI: psi,
|
||||
Docker: docker,
|
||||
UpdatedAt: time.Now().Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func getLoad1M() float64 {
|
||||
if data, err := os.ReadFile("/proc/loadavg"); err == nil {
|
||||
fields := strings.Fields(string(data))
|
||||
if len(fields) > 0 {
|
||||
if val, err := strconv.ParseFloat(fields[0], 64); err == nil {
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0.0
|
||||
}
|
||||
|
||||
func getCPUUsage() int {
|
||||
pct := sampleCPUStat()
|
||||
if pct >= 0 {
|
||||
return pct
|
||||
}
|
||||
if data, err := os.ReadFile("/proc/loadavg"); err == nil {
|
||||
fields := strings.Fields(string(data))
|
||||
if len(fields) > 0 {
|
||||
if l1, err := strconv.ParseFloat(fields[0], 64); err == nil {
|
||||
cores := float64(runtime.NumCPU())
|
||||
if cores < 1 {
|
||||
cores = 1
|
||||
}
|
||||
val := int((l1 / cores) * 100)
|
||||
if val > 100 {
|
||||
val = 100
|
||||
}
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func sampleCPUStat() int {
|
||||
readStat := func() (idle, total uint64, ok bool) {
|
||||
f, err := os.Open("/proc/stat")
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
if scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) >= 5 && fields[0] == "cpu" {
|
||||
var sum uint64
|
||||
for i := 1; i < len(fields); i++ {
|
||||
v, _ := strconv.ParseUint(fields[i], 10, 64)
|
||||
sum += v
|
||||
}
|
||||
idleVal, _ := strconv.ParseUint(fields[4], 10, 64)
|
||||
return idleVal, sum, true
|
||||
}
|
||||
}
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
idle1, total1, ok1 := readStat()
|
||||
if !ok1 {
|
||||
return -1
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
idle2, total2, ok2 := readStat()
|
||||
if !ok2 || total2 <= total1 {
|
||||
return -1
|
||||
}
|
||||
deltaTotal := total2 - total1
|
||||
deltaIdle := idle2 - idle1
|
||||
if deltaTotal == 0 {
|
||||
return 0
|
||||
}
|
||||
busy := float64(deltaTotal-deltaIdle) / float64(deltaTotal) * 100
|
||||
if busy < 0 {
|
||||
busy = 0
|
||||
}
|
||||
if busy > 100 {
|
||||
busy = 100
|
||||
}
|
||||
return int(busy)
|
||||
}
|
||||
|
||||
func getMemInfo() (memPct int, memAvl string) {
|
||||
f, err := os.Open("/proc/meminfo")
|
||||
if err != nil {
|
||||
return 0, "N/A"
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var total, free, avail, buffers, cached uint64
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
parts := strings.SplitN(line, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
key := strings.TrimSpace(parts[0])
|
||||
valFields := strings.Fields(parts[1])
|
||||
if len(valFields) == 0 {
|
||||
continue
|
||||
}
|
||||
v, _ := strconv.ParseUint(valFields[0], 10, 64)
|
||||
switch key {
|
||||
case "MemTotal":
|
||||
total = v
|
||||
case "MemFree":
|
||||
free = v
|
||||
case "MemAvailable":
|
||||
avail = v
|
||||
case "Buffers":
|
||||
buffers = v
|
||||
case "Cached":
|
||||
cached = v
|
||||
}
|
||||
}
|
||||
|
||||
if avail == 0 {
|
||||
avail = free + buffers + cached
|
||||
}
|
||||
|
||||
if total > 0 {
|
||||
used := total - avail
|
||||
memPct = int(float64(used) / float64(total) * 100)
|
||||
if avail >= 1024*1024 {
|
||||
memAvl = fmt.Sprintf("%.1fG", float64(avail)/(1024*1024))
|
||||
} else {
|
||||
memAvl = fmt.Sprintf("%dM", avail/1024)
|
||||
}
|
||||
} else {
|
||||
memAvl = "N/A"
|
||||
}
|
||||
|
||||
return memPct, memAvl
|
||||
}
|
||||
|
||||
func getDiskInfo() (diskPct int, diskFree string) {
|
||||
var stat syscall.Statfs_t
|
||||
if err := syscall.Statfs("/", &stat); err != nil {
|
||||
return 0, "N/A"
|
||||
}
|
||||
total := stat.Blocks * uint64(stat.Bsize)
|
||||
free := stat.Bavail * uint64(stat.Bsize)
|
||||
if total == 0 {
|
||||
return 0, "N/A"
|
||||
}
|
||||
used := total - free
|
||||
diskPct = int(float64(used) / float64(total) * 100)
|
||||
if diskPct > 100 {
|
||||
diskPct = 100
|
||||
}
|
||||
|
||||
if free >= 1024*1024*1024 {
|
||||
diskFree = fmt.Sprintf("%.1fG", float64(free)/(1024*1024*1024))
|
||||
} else {
|
||||
diskFree = fmt.Sprintf("%dM", free/(1024*1024))
|
||||
}
|
||||
|
||||
return diskPct, diskFree
|
||||
}
|
||||
|
||||
func getIOPSI() float64 {
|
||||
data, err := os.ReadFile("/proc/pressure/io")
|
||||
if err == nil {
|
||||
lines := strings.Split(string(data), "\n")
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "some") {
|
||||
fields := strings.Fields(line)
|
||||
for _, f := range fields {
|
||||
if strings.HasPrefix(f, "avg10=") {
|
||||
val, err := strconv.ParseFloat(strings.TrimPrefix(f, "avg10="), 64)
|
||||
if err == nil {
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if data, err := os.ReadFile("/proc/loadavg"); err == nil {
|
||||
fields := strings.Fields(string(data))
|
||||
if len(fields) > 0 {
|
||||
if val, err := strconv.ParseFloat(fields[0], 64); err == nil {
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0.0
|
||||
}
|
||||
|
||||
func hasDocker() bool {
|
||||
if _, err := os.Stat("/var/run/docker.sock"); err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package sysinfo
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCollect(t *testing.T) {
|
||||
p := Collect("CONTROL")
|
||||
if p.Role != "CONTROL" {
|
||||
t.Fatalf("expected CONTROL, got %s", p.Role)
|
||||
}
|
||||
if p.CPUCores <= 0 {
|
||||
t.Fatalf("expected >0 CPU cores, got %d", p.CPUCores)
|
||||
}
|
||||
t.Logf("Profile: %+v", p)
|
||||
}
|
||||
+53
-1
@@ -20,6 +20,7 @@ type Runner interface {
|
||||
AuditsJSON(http.ResponseWriter, *http.Request)
|
||||
PanelExec(http.ResponseWriter, *http.Request)
|
||||
RotateAPIKey(http.ResponseWriter, *http.Request)
|
||||
DeleteDevice(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
type Panel struct {
|
||||
@@ -38,14 +39,62 @@ func (p *Panel) Handler() http.Handler {
|
||||
mux.HandleFunc("/panel/login", p.login)
|
||||
mux.HandleFunc("/panel/logout", p.logout)
|
||||
mux.HandleFunc("/static/", p.static)
|
||||
mux.HandleFunc("/panel/api/devices", p.protected(p.Runner.DevicesJSON))
|
||||
mux.HandleFunc("/panel/api/devices", p.protected(p.handleDevices))
|
||||
mux.HandleFunc("/panel/api/audits", p.protected(p.Runner.AuditsJSON))
|
||||
mux.HandleFunc("/panel/api/exec", p.protected(p.Runner.PanelExec))
|
||||
mux.HandleFunc("/panel/api/key/rotate", p.protected(p.Runner.RotateAPIKey))
|
||||
mux.HandleFunc("/panel/api/mcp/services", p.protected(p.mcpServices))
|
||||
mux.HandleFunc("/panel/api/mcp/service", p.protected(p.deleteMCPService))
|
||||
mux.HandleFunc("/panel/api/mcp/list", p.protected(p.listAgentMCP))
|
||||
mux.HandleFunc("/panel/api/mcp/call", p.protected(p.callAgentMCP))
|
||||
mux.HandleFunc("/", p.index)
|
||||
return mux
|
||||
}
|
||||
|
||||
type mcpPanelRunner interface {
|
||||
MCPServicesJSON(http.ResponseWriter, *http.Request)
|
||||
DeleteMCPService(http.ResponseWriter, *http.Request)
|
||||
ListAgentMCPJSON(http.ResponseWriter, *http.Request)
|
||||
CallAgentMCPJSON(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
func (p *Panel) mcpServices(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.MCPServicesJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) deleteMCPService(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.DeleteMCPService(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) listAgentMCP(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.ListAgentMCPJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) callAgentMCP(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.CallAgentMCPJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
|
||||
func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodDelete {
|
||||
p.Runner.DeleteDevice(w, r)
|
||||
return
|
||||
}
|
||||
p.Runner.DevicesJSON(w, r)
|
||||
}
|
||||
|
||||
func (p *Panel) index(w http.ResponseWriter, r *http.Request) {
|
||||
if !p.valid(r) {
|
||||
http.Redirect(w, r, "/panel/login", http.StatusFound)
|
||||
@@ -141,6 +190,9 @@ func (p *Panel) static(w http.ResponseWriter, r *http.Request) {
|
||||
if len(path) >= 3 && path[len(path)-3:] == ".js" {
|
||||
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||
}
|
||||
if strings.HasSuffix(path, ".png") {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
}
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ func (testRunner) DevicesJSON(w http.ResponseWriter, r *http.Request) {}
|
||||
func (testRunner) AuditsJSON(w http.ResponseWriter, r *http.Request) {}
|
||||
func (testRunner) PanelExec(w http.ResponseWriter, r *http.Request) {}
|
||||
func (testRunner) RotateAPIKey(w http.ResponseWriter, r *http.Request) {}
|
||||
func (testRunner) DeleteDevice(w http.ResponseWriter, r *http.Request) {}
|
||||
|
||||
func TestStaticCSSContentType(t *testing.T) {
|
||||
p := New("test-password", testRunner{})
|
||||
|
||||
@@ -1 +1,45 @@
|
||||
*{box-sizing:border-box}body{margin:0;background:#0b1020;color:#e7ebf3;font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #202a3d;background:#10182b;position:sticky;top:0;z-index:2}header strong{font-size:18px}header span{margin-left:12px;color:#7f8ba3;font-size:12px}main{max-width:1400px;margin:auto;padding:22px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.wide{grid-column:1/-1}.card{background:#111a2d;border:1px solid #24304a;border-radius:14px;padding:18px;box-shadow:0 8px 30px #0003}.cardhead{display:flex;align-items:center;justify-content:space-between}h2{margin:0 0 14px;font-size:16px}button,select,input,textarea{border:1px solid #34415d;border-radius:9px;background:#0d1526;color:#e7ebf3;padding:9px 12px}button{cursor:pointer}button:hover{background:#17233a}textarea{width:100%;height:110px;resize:vertical;font-family:ui-monospace,monospace;margin:8px 0}pre{white-space:pre-wrap;overflow:auto;background:#090e1a;border-radius:9px;padding:12px;color:#b9c5da}.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}.device{padding:14px;border:1px solid #283650;border-radius:10px}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#4ade80;margin-right:7px}.offline .dot{background:#f87171}.muted{color:#7f8ba3}.tablewrap{overflow:auto}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:9px;border-bottom:1px solid #26324a;font-size:12px}th{color:#91a0bb}.login{display:grid;place-items:center;min-height:100vh}.login form{width:min(380px,90vw);background:#111a2d;border:1px solid #24304a;border-radius:16px;padding:28px}.login input,.login button{width:100%;margin-top:10px}.login h1{margin:0}.login p,#error{color:#8c9ab2}.status{font-size:12px;color:#9aabc5}@media(max-width:800px){.grid{grid-template-columns:1fr}.wide{grid-column:auto}main{padding:12px}header{padding:0 14px}}
|
||||
*{box-sizing:border-box}
|
||||
:root{color-scheme:dark;--bg-body:#0b1020;--bg-card:#111a2d;--bg-sub:#0d1526;--border:#24304a;--border-strong:#34415d;--text-main:#e7ebf3;--text-muted:#7f8ba3;--text-status:#9aabc5;--pre-text:#b9c5da;--thead:#91a0bb;--dot-online:#4ade80;--dot-offline:#f87171;--shadow:0 8px 30px rgba(0,0,0,.2)}
|
||||
:root[data-theme="light"]{color-scheme:light;--bg-body:#f4f6fa;--bg-card:#fff;--bg-sub:#eef2f7;--border:#d1d9e4;--border-strong:#b8c3d3;--text-main:#172033;--text-muted:#647089;--text-status:#58657a;--pre-text:#26344b;--thead:#53627a;--dot-online:#16833d;--dot-offline:#c62828;--shadow:0 8px 26px rgba(28,45,72,.08)}
|
||||
html,body{min-height:100%}body{margin:0;background:var(--bg-body);color:var(--text-main);font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{min-height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border);background:var(--bg-card);position:sticky;top:0;z-index:2}
|
||||
.brand-wrap{display:flex;align-items:center;gap:12px;min-width:0}
|
||||
.brand-logo{width:36px;height:36px;border-radius:8px;object-fit:cover;flex:none;box-shadow:0 2px 8px rgba(0,0,0,.15)}
|
||||
header strong{font-size:18px}header span{margin-left:12px;color:var(--text-muted);font-size:12px}.header-actions{display:flex;align-items:center;gap:8px;flex-shrink:0}main{max-width:1400px;margin:auto;padding:22px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.wide{grid-column:1/-1}.card{min-width:0;background:var(--bg-card);border:1px solid var(--border);border-radius:14px;padding:18px;box-shadow:var(--shadow)}.cardhead{display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0}.cardhead>h2{min-width:0}h2{margin:0 0 14px;font-size:16px}button,select,input,textarea{border:1px solid var(--border-strong);border-radius:9px;background:var(--bg-sub);color:var(--text-main);padding:9px 12px;font:inherit;max-width:100%}button{cursor:pointer}button:hover{filter:brightness(1.05)}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--border-strong);outline-offset:2px}textarea{width:100%;height:110px;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;margin:8px 0}pre{white-space:pre-wrap;overflow:auto;background:var(--bg-sub);border:1px solid var(--border);border-radius:9px;padding:12px;color:var(--pre-text)}.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}.device{min-width:0;padding:14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-sub)}.device b{display:block;min-width:0;overflow-wrap:anywhere;word-break:break-all}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--dot-online);vertical-align:middle;flex:none;margin-right:7px}.offline .dot{background:var(--dot-offline)}.muted{color:var(--text-muted)}.status{margin-top:3px;font-size:12px;color:var(--text-status);overflow-wrap:anywhere;word-break:break-word}.actions{display:flex;flex-wrap:wrap;gap:8px}.actions button{flex:1 1 150px}#device{min-width:180px}.tablewrap{width:100%;max-width:100%;overflow-x:auto;overscroll-behavior-x:contain}table{width:100%;min-width:760px;border-collapse:collapse}th,td{text-align:left;padding:9px;border-bottom:1px solid var(--border);font-size:12px;white-space:nowrap}th{color:var(--thead)}.login{display:grid;place-items:center;min-height:100vh;padding:20px}.login form{width:min(380px,90vw);background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:28px;box-shadow:var(--shadow)}.login input,.login button{width:100%;margin-top:10px}.login h1{margin:0}.login p,#error{color:var(--text-muted)}
|
||||
@media(max-width:800px){.grid{grid-template-columns:1fr}.wide{grid-column:auto}main{padding:12px}header{padding:0 14px}.header-actions{gap:6px}.card{padding:15px}.cardhead{flex-wrap:wrap}.cardhead>#device{width:100%;min-width:0}.actions button{flex:1 1 140px}}
|
||||
@media(max-width:680px){header{align-items:flex-start;padding-top:12px;padding-bottom:12px}header span{display:none}.brand-wrap{padding-top:2px}.brand-logo{width:32px;height:32px}.header-actions{flex-direction:column;align-items:stretch;width:112px}.header-actions button{width:100%;padding:8px 9px}.devices{grid-template-columns:1fr}.cardhead{flex-direction:column;align-items:stretch;gap:8px}.cardhead h2{margin-bottom:0}.cardhead button,#device{width:100%;min-width:0}.actions button{flex:1 1 calc(50% - 4px)}}
|
||||
@media(max-width:450px){main{padding:9px}.card{padding:13px;border-radius:12px}.actions{display:grid;grid-template-columns:1fr 1fr}.actions button{width:100%;min-width:0}.login form{padding:22px}.header-actions{width:104px}}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important}}
|
||||
|
||||
/* 主题切换极简矢量图标按钮 */
|
||||
.btn-icon{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;padding:0;border-radius:9px;background:var(--bg-sub);border:1px solid var(--border-strong);color:var(--text-main);cursor:pointer;transition:background .2s,border-color .2s}
|
||||
.btn-icon:hover{filter:brightness(1.1)}
|
||||
.theme-svg{display:none;width:18px;height:18px}
|
||||
:root[data-theme="dark"] .svg-sun{display:block;color:#facc15}
|
||||
:root[data-theme="light"] .svg-moon{display:block;color:#475569}
|
||||
|
||||
/* 设备卡片与画像升级 (方案 1: 经典主副标题分行) */
|
||||
.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px}
|
||||
.device-card{min-width:0;padding:16px;border:1px solid var(--border);border-radius:12px;background:var(--bg-sub);display:flex;flex-direction:column;gap:12px}
|
||||
|
||||
.v1-head{display:flex;flex-direction:column;gap:4px;min-width:0}
|
||||
.v1-row1{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}
|
||||
.v1-title{display:flex;align-items:center;gap:8px;min-width:0;flex:1}
|
||||
.v1-name{font-size:16px;font-weight:700;color:var(--text-main);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block}
|
||||
.v1-row2{font-size:12px;color:var(--text-muted);padding-left:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
|
||||
.btn-revoke{padding:2px 8px;font-size:11px;border-radius:5px;background:transparent;border:1px solid var(--border-strong);color:var(--dot-offline);cursor:pointer;flex-shrink:0}
|
||||
.btn-revoke:hover{background:rgba(239,68,68,.15);border-color:var(--dot-offline)}
|
||||
|
||||
/* 资源画像 2列紧凑栅格 */
|
||||
.profile-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px 12px;padding:10px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:8px;font-size:12px}
|
||||
.p-item{display:flex;justify-content:space-between;align-items:center;gap:6px;min-height:20px}
|
||||
.p-label{color:var(--text-muted);font-weight:500;font-size:11px}
|
||||
.p-val{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-weight:600;font-size:12px;color:var(--text-main);white-space:nowrap}
|
||||
.badge-docker-text{padding:1px 6px;border-radius:4px;font-size:11px;font-weight:700}
|
||||
.badge-docker-text.yes{background:rgba(34,197,94,.15);color:var(--dot-online);border:1px solid rgba(34,197,94,.3)}
|
||||
.badge-docker-text.no{background:rgba(148,163,184,.15);color:var(--text-muted);border:1px solid var(--border)}
|
||||
.device-card.offline{opacity:.62;filter:saturate(.45)}
|
||||
.device-card.offline .btn-revoke{opacity:1}
|
||||
|
||||
.mcp-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:14px}.mcp-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}.mcp-item{border:1px solid var(--line,#30343b);border-radius:10px;padding:14px;background:var(--card,#11151a)}.mcp-item h3{margin:0 0 6px;font-size:15px}.mcp-meta{font-size:12px;opacity:.72;line-height:1.7}.mcp-actions{display:flex;gap:8px;margin-top:10px}.mcp-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.mcp-form .full{grid-column:1/-1}.mcp-form label{display:flex;flex-direction:column;gap:5px;font-size:12px;opacity:.9}.mcp-form input,.mcp-form select,.mcp-form textarea{width:100%;box-sizing:border-box}.mcp-form textarea{min-height:72px;font-family:monospace}.mcp-nodes{display:flex;flex-wrap:wrap;gap:8px}.mcp-nodes label{flex-direction:row;align-items:center}.mcp-status{font-size:12px;margin-top:8px;min-height:18px}
|
||||
@media(max-width:700px){.mcp-form{grid-template-columns:1fr}.mcp-form .full{grid-column:auto}.mcp-toolbar{align-items:flex-start;flex-direction:column}}
|
||||
|
||||
+127
-9
@@ -1,12 +1,130 @@
|
||||
const $=s=>document.querySelector(s);
|
||||
async function api(path,opt={}){let r=await fetch("/panel/api"+path,opt);if(r.status===401){location.href="/panel/login";throw Error("unauthorized")}if(!r.ok)throw Error(await r.text());return r.json()}
|
||||
function esc(v){return String(v??"").replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]))}
|
||||
async function loadDevices(){let ds=await api("/devices");$("#devices").innerHTML=ds.map(d=>`<div class="device ${d.status==="online"?"":"offline"}"><b><i class="dot"></i>${esc(d.name)}</b><div class="status">${esc(d.status)} · ${d.is_local?"local":"remote"} · ${esc(d.arch||"")}/${esc(d.os||"")}</div></div>`).join("");$("#device").innerHTML=ds.map(d=>`<option>${esc(d.name)}</option>`).join("")}
|
||||
async function loadAudits(){let a=await api("/audits?limit=100");$("#audits").innerHTML=a.map(x=>`<tr><td>${new Date(x.timestamp*1000).toLocaleString()}</td><td>${esc(x.device)}</td><td>${esc(x.action)}</td><td><code>${esc(x.command)}</code></td><td>${x.exit_code}</td><td>${x.duration_ms}ms</td><td>${esc(x.caller_ip)}</td></tr>`).join("")}
|
||||
$("#refresh").onclick=loadDevices;$("#auditRefresh").onclick=loadAudits;
|
||||
$("#run").onclick=async()=>{let o=$("#output");o.textContent="执行中…";try{let x=await api("/exec",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device:$("#device").value,command:$("#command").value,timeout:30})});o.textContent=`exit_code: ${x.exit_code}\n\nstdout:\n${x.stdout}\n\nstderr:\n${x.stderr}\nduration: ${x.duration_ms}ms`}catch(e){o.textContent=e.message}};
|
||||
(function(){
|
||||
const b=$("#themeToggle");
|
||||
if(!b)return;
|
||||
b.onclick=()=>{
|
||||
const current=document.documentElement.dataset.theme||"dark";
|
||||
const next=current==="light"?"dark":"light";
|
||||
document.documentElement.dataset.theme=next;
|
||||
localStorage.setItem("vpc_theme",next);
|
||||
};
|
||||
})();
|
||||
|
||||
async function api(path,opt={}){
|
||||
let r=await fetch("/panel/api"+path,opt);
|
||||
if(r.status===401){location.href="/panel/login";throw Error("unauthorized")}
|
||||
if(!r.ok)throw Error(await r.text());
|
||||
return r.json()
|
||||
}
|
||||
|
||||
function esc(v){
|
||||
return String(v??"").replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]))
|
||||
}
|
||||
|
||||
async function removeDevice(name){
|
||||
if(!confirm(`确认注销并踢出节点 [${name}] 吗?\n注销后该节点将被断开并禁止再次连入。`)) return;
|
||||
try{
|
||||
await api("/devices?name="+encodeURIComponent(name), {method: "DELETE"});
|
||||
await loadDevices();
|
||||
}catch(e){
|
||||
alert("注销失败: "+e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDevices(){
|
||||
let all=await api("/devices");
|
||||
let ds=all.filter(d=>!d.is_local);
|
||||
$("#devices").innerHTML=ds.map(d=>{
|
||||
const p = d.profile || {};
|
||||
const role = p.role || "APPLICATION";
|
||||
const isOnline = d.status === "online";
|
||||
const statusText = isOnline ? "在线" : "离线";
|
||||
const lastText = d.last_heartbeat ? new Date(d.last_heartbeat*1000).toLocaleString() : "";
|
||||
const archOs = (d.arch || d.os) ? `${esc(d.arch||"")}/${esc(d.os||"")} · ` : "";
|
||||
const cpuStr = p.cpu_cores ? `${p.cpu_cores}C · ${p.cpu_usage_percent ?? 0}%` : '-';
|
||||
const loadStr = p.load_1m !== undefined ? p.load_1m.toFixed(2) : '-';
|
||||
const memStr = p.mem_available ? `${p.mem_available} (${p.mem_percent}%)` : (p.mem_percent !== undefined ? `${p.mem_percent}%` : '-');
|
||||
const diskStr = p.disk_free ? `${p.disk_free} (${p.disk_percent}%)` : (p.disk_percent !== undefined ? `${p.disk_percent}%` : '-');
|
||||
const psiStr = p.io_psi !== undefined ? p.io_psi.toFixed(2) : '-';
|
||||
const dockerVal = p.docker ? 'YES' : 'NO';
|
||||
const dockerClass = p.docker ? 'yes' : 'no';
|
||||
|
||||
return `
|
||||
<div class="device-card ${isOnline ? "online" : "offline"}">
|
||||
<div class="v1-head">
|
||||
<div class="v1-row1">
|
||||
<div class="v1-title">
|
||||
<span class="dot"></span>
|
||||
<strong class="v1-name" title="${esc(d.name)}">${esc(d.name)}</strong>
|
||||
</div>
|
||||
<button class="btn-revoke" onclick="removeDevice('${esc(d.name)}')">注销</button>
|
||||
</div>
|
||||
<div class="v1-row2">${archOs}${statusText}${isOnline ? "" : (lastText ? " · 最后活跃: "+lastText : "")}</div>
|
||||
</div>
|
||||
<div class="profile-grid">
|
||||
<div class="p-item"><span class="p-label">CPU</span><span class="p-val">${cpuStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">LOAD</span><span class="p-val">${loadStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">MEM</span><span class="p-val">${memStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">DISK</span><span class="p-val">${diskStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">IO PSI</span><span class="p-val">${psiStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">DOCKER</span><span class="p-val badge-docker-text ${dockerClass}">${dockerVal}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
$("#device").innerHTML=ds.map(d=>`<option value="${esc(d.name)}" ${d.status==="offline" ? "disabled" : ""}>${esc(d.name)}${d.status==="offline" ? " [离线]" : ""}</option>`).join("");
|
||||
}
|
||||
|
||||
async function loadAudits(){
|
||||
let a=await api("/audits?limit=100");
|
||||
$("#audits").innerHTML=a.map(x=>'<tr><td>'+new Date(x.timestamp*1000).toLocaleString()+'</td><td>'+esc(x.device)+'</td><td>'+esc(x.action)+'</td><td><code>'+esc(x.command)+'</code></td><td>'+x.exit_code+'</td><td>'+x.duration_ms+'ms</td><td>'+esc(x.caller_ip)+'</td></tr>').join("")
|
||||
}
|
||||
|
||||
$("#refresh").onclick=loadDevices;
|
||||
$("#auditRefresh").onclick=loadAudits;
|
||||
$("#run").onclick=async()=>{
|
||||
let o=$("#output");
|
||||
o.textContent="执行中…";
|
||||
try{
|
||||
let x=await api("/exec",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device:$("#device").value,command:$("#command").value,timeout:30})});
|
||||
o.textContent=`exit_code: ${x.exit_code}\n\nstdout:\n${x.stdout}\n\nstderr:\n${x.stderr}\nduration: ${x.duration_ms}ms`
|
||||
}catch(e){
|
||||
o.textContent=e.message
|
||||
}
|
||||
};
|
||||
$("#copySchema").onclick=()=>navigator.clipboard.writeText(location.origin+"/openapi.json");
|
||||
$("#copyPrompt").onclick=()=>navigator.clipboard.writeText("你是我的私有 VPS 运维助手。执行操作前确认目标设备;优先使用 list_devices 确认节点状态;高风险操作先向用户确认。");
|
||||
$("#rotateKey").onclick=async()=>{if(!confirm("轮换后旧 API Key 会立即失效,确认继续?"))return;try{let x=await api("/key/rotate",{method:"POST"});$("#newKey").textContent="新 API Key(仅本次显示):\n"+x.api_key}catch(e){$("#newKey").textContent=e.message}};
|
||||
$("#logout").onclick=async()=>{await fetch("/panel/logout",{method:"POST"});location.href="/panel/login"};
|
||||
loadDevices().then(loadAudits).catch(console.error);
|
||||
$("#rotateKey").onclick=async()=>{
|
||||
if(!confirm("轮换后旧 API Key 会立即失效,确认继续?"))return;
|
||||
try{
|
||||
let x=await api("/key/rotate",{method:"POST"});
|
||||
$("#newKey").textContent="新 API Key(仅本次显示):\n"+x.api_key
|
||||
}catch(e){
|
||||
$("#newKey").textContent=e.message
|
||||
}
|
||||
};
|
||||
$("#logout").onclick=async()=>{
|
||||
await fetch("/panel/logout",{method:"POST"});
|
||||
location.href="/panel/login"
|
||||
};
|
||||
loadDevices().then(loadAudits).catch(console.error);
|
||||
|
||||
let mcpEditingId="";
|
||||
async function loadMCPServices(){
|
||||
const services=await api("/mcp/services");
|
||||
const devices=(await api("/devices")).filter(d=>!d.is_local);
|
||||
$("#mcpNodes").innerHTML=devices.map(d=>`<label><input type="checkbox" value="${esc(d.name)}">${esc(d.name)}</label>`).join("");
|
||||
$("#mcpList").innerHTML=services.map(s=>`<div class="mcp-item"><h3>${esc(s.name)} <small>${esc(s.id)}</small></h3><div class="mcp-meta">${esc(s.transport)} · ${s.scope==='custom'?'指定节点':'全部节点'} · ${s.enabled?'启用':'停用'}${s.url?' · '+esc(s.url):s.command?' · '+esc(s.command):''}</div><div class="mcp-actions"><button type="button" onclick="editMCP('${esc(s.id)}')">编辑</button><button type="button" onclick="deleteMCP('${esc(s.id)}')">删除</button></div></div>`).join("")||'<div class="mcp-meta">暂无 MCP 服务配置。</div>';
|
||||
}
|
||||
function resetMCPForm(){
|
||||
mcpEditingId=""; $("#mcpEditor").hidden=false; $("#mcpId").disabled=false; ["mcpId","mcpName","mcpCommand","mcpUrl"].forEach(id=>$("#"+id).value=""); $("#mcpTransport").value="stdio"; $("#mcpEnabled").value="1"; $("#mcpArgs").value="[]"; $("#mcpHeaders").value="{}"; $("#mcpEnv").value="{}"; $("#mcpScope").value="all"; $("#mcpStatus").textContent=""; $("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=false);
|
||||
}
|
||||
async function editMCP(id){
|
||||
const services=await api("/mcp/services"); const s=services.find(x=>x.id===id); if(!s)return; resetMCPForm(); mcpEditingId=id; $("#mcpId").value=s.id; $("#mcpId").disabled=true; $("#mcpName").value=s.name||""; $("#mcpTransport").value=s.transport; $("#mcpEnabled").value=s.enabled?"1":"0"; $("#mcpCommand").value=s.command||""; $("#mcpUrl").value=s.url||""; $("#mcpArgs").value=s.args_json||"[]"; $("#mcpHeaders").value=s.headers_json||"{}"; $("#mcpEnv").value=s.env_json||"{}"; $("#mcpScope").value=s.scope||"all"; let nodes=[];try{nodes=JSON.parse(s.target_nodes_json||"[]")}catch(e){};$("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=nodes.includes(x.value));
|
||||
}
|
||||
async function deleteMCP(id){if(!confirm(`确认删除 MCP 服务 [${id}]?`))return;try{await api("/mcp/service?id="+encodeURIComponent(id),{method:"DELETE"});await loadMCPServices()}catch(e){alert("删除失败: "+e.message)}}
|
||||
$("#mcpNew").onclick=resetMCPForm; $("#mcpCancel").onclick=()=>$("#mcpEditor").hidden=true;
|
||||
$("#mcpSave").onclick=async()=>{try{const scope=$("#mcpScope").value;const body={id:$("#mcpId").value.trim(),name:$("#mcpName").value.trim(),transport:$("#mcpTransport").value,command:$("#mcpCommand").value.trim(),url:$("#mcpUrl").value.trim(),scope,enabled:$("#mcpEnabled").value==="1",args:JSON.parse($("#mcpArgs").value||"[]"),headers:JSON.parse($("#mcpHeaders").value||"{}"),env:JSON.parse($("#mcpEnv").value||"{}"),target_nodes:[...$("#mcpNodes").querySelectorAll("input:checked")].map(x=>x.value)};if(!body.id||!body.name)throw Error("服务标识和显示名称不能为空");await api("/mcp/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});$("#mcpStatus").textContent="已保存并向在线节点同步。";await loadMCPServices()}catch(e){$("#mcpStatus").textContent="保存失败: "+e.message}};
|
||||
$("#mcpTransport").onchange=()=>{const stdio=$("#mcpTransport").value==="stdio";$("#mcpCommand").parentElement.style.display=stdio?"":"none";$("#mcpArgs").parentElement.style.display=stdio?"":"none";$("#mcpUrl").parentElement.style.display=stdio?"none":""};
|
||||
loadMCPServices().catch(console.error);
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
@@ -1,13 +1,2 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head>
|
||||
<body>
|
||||
<header><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div><button id="logout">退出</button></header>
|
||||
<main>
|
||||
<section class="grid">
|
||||
<article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh">刷新</button></div><div id="devices" class="devices"></div></article>
|
||||
<article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><button id="copySchema">复制 Schema 地址</button><button id="copyPrompt">复制 System Prompt</button><button id="rotateKey">轮换 API Key</button><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article>
|
||||
<article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run">执行</button></div><pre id="output"></pre></article>
|
||||
<article class="card wide"><div class="cardhead"><h2>审计日志</h2><button id="auditRefresh">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article>
|
||||
</section>
|
||||
</main><script src="/static/app.js"></script></body></html>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="mcp-toolbar"><h2>MCP 挂载</h2><button id="mcpNew" type="button">新增 MCP</button></div><div id="mcpList" class="mcp-grid"></div><div id="mcpEditor" hidden><div class="mcp-form"><label>服务标识<input id="mcpId" placeholder="docker"></label><label>显示名称<input id="mcpName" placeholder="Docker 容器管理"></label><label>传输类型<select id="mcpTransport"><option value="stdio">命令行 / stdio</option><option value="http">HTTP / Streamable HTTP</option><option value="sse">SSE</option></select></label><label>启用<select id="mcpEnabled"><option value="1">启用</option><option value="0">停用</option></select></label><label class="full">Command<input id="mcpCommand" placeholder="docker-mcp"></label><label class="full">Arguments(JSON 数组)<textarea id="mcpArgs">[]</textarea></label><label class="full">URL<input id="mcpUrl" placeholder="http://127.0.0.1:8080/mcp"></label><label class="full">Headers(JSON 对象,可选)<textarea id="mcpHeaders">{}</textarea></label><label class="full">环境变量(JSON 对象,可选)<textarea id="mcpEnv">{}</textarea></label><label>生效范围<select id="mcpScope"><option value="all">全部节点</option><option value="custom">指定节点</option></select></label><div><span>指定节点</span><div id="mcpNodes" class="mcp-nodes"></div></div></div><div class="mcp-actions"><button id="mcpSave" type="button">保存并热更新</button><button id="mcpCancel" type="button">取消</button></div><div id="mcpStatus" class="mcp-status"></div></div></article>
|
||||
<article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>审计日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html>
|
||||
|
||||
@@ -1 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button>登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/";else document.querySelector("#error").textContent="密码错误或未配置面板密码";}</script></body></html>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html>
|
||||
|
||||
+40
-1
@@ -1 +1,40 @@
|
||||
*{box-sizing:border-box}body{margin:0;background:#0b1020;color:#e7ebf3;font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #202a3d;background:#10182b;position:sticky;top:0;z-index:2}header strong{font-size:18px}header span{margin-left:12px;color:#7f8ba3;font-size:12px}main{max-width:1400px;margin:auto;padding:22px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.wide{grid-column:1/-1}.card{background:#111a2d;border:1px solid #24304a;border-radius:14px;padding:18px;box-shadow:0 8px 30px #0003}.cardhead{display:flex;align-items:center;justify-content:space-between}h2{margin:0 0 14px;font-size:16px}button,select,input,textarea{border:1px solid #34415d;border-radius:9px;background:#0d1526;color:#e7ebf3;padding:9px 12px}button{cursor:pointer}button:hover{background:#17233a}textarea{width:100%;height:110px;resize:vertical;font-family:ui-monospace,monospace;margin:8px 0}pre{white-space:pre-wrap;overflow:auto;background:#090e1a;border-radius:9px;padding:12px;color:#b9c5da}.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}.device{padding:14px;border:1px solid #283650;border-radius:10px}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#4ade80;margin-right:7px}.offline .dot{background:#f87171}.muted{color:#7f8ba3}.tablewrap{overflow:auto}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:9px;border-bottom:1px solid #26324a;font-size:12px}th{color:#91a0bb}.login{display:grid;place-items:center;min-height:100vh}.login form{width:min(380px,90vw);background:#111a2d;border:1px solid #24304a;border-radius:16px;padding:28px}.login input,.login button{width:100%;margin-top:10px}.login h1{margin:0}.login p,#error{color:#8c9ab2}.status{font-size:12px;color:#9aabc5}@media(max-width:800px){.grid{grid-template-columns:1fr}.wide{grid-column:auto}main{padding:12px}header{padding:0 14px}}
|
||||
*{box-sizing:border-box}
|
||||
:root{color-scheme:dark;--bg-body:#0b1020;--bg-card:#111a2d;--bg-sub:#0d1526;--border:#24304a;--border-strong:#34415d;--text-main:#e7ebf3;--text-muted:#7f8ba3;--text-status:#9aabc5;--pre-text:#b9c5da;--thead:#91a0bb;--dot-online:#4ade80;--dot-offline:#f87171;--shadow:0 8px 30px rgba(0,0,0,.2)}
|
||||
:root[data-theme="light"]{color-scheme:light;--bg-body:#f4f6fa;--bg-card:#fff;--bg-sub:#eef2f7;--border:#d1d9e4;--border-strong:#b8c3d3;--text-main:#172033;--text-muted:#647089;--text-status:#58657a;--pre-text:#26344b;--thead:#53627a;--dot-online:#16833d;--dot-offline:#c62828;--shadow:0 8px 26px rgba(28,45,72,.08)}
|
||||
html,body{min-height:100%}body{margin:0;background:var(--bg-body);color:var(--text-main);font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{min-height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border);background:var(--bg-card);position:sticky;top:0;z-index:2}
|
||||
.brand-wrap{display:flex;align-items:center;gap:12px;min-width:0}
|
||||
.brand-logo{width:36px;height:36px;border-radius:8px;object-fit:cover;flex:none;box-shadow:0 2px 8px rgba(0,0,0,.15)}
|
||||
header strong{font-size:18px}header span{margin-left:12px;color:var(--text-muted);font-size:12px}.header-actions{display:flex;align-items:center;gap:8px;flex-shrink:0}main{max-width:1400px;margin:auto;padding:22px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.wide{grid-column:1/-1}.card{min-width:0;background:var(--bg-card);border:1px solid var(--border);border-radius:14px;padding:18px;box-shadow:var(--shadow)}.cardhead{display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0}.cardhead>h2{min-width:0}h2{margin:0 0 14px;font-size:16px}button,select,input,textarea{border:1px solid var(--border-strong);border-radius:9px;background:var(--bg-sub);color:var(--text-main);padding:9px 12px;font:inherit;max-width:100%}button{cursor:pointer}button:hover{filter:brightness(1.05)}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--border-strong);outline-offset:2px}textarea{width:100%;height:110px;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;margin:8px 0}pre{white-space:pre-wrap;overflow:auto;background:var(--bg-sub);border:1px solid var(--border);border-radius:9px;padding:12px;color:var(--pre-text)}.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}.device{min-width:0;padding:14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-sub)}.device b{display:block;min-width:0;overflow-wrap:anywhere;word-break:break-all}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--dot-online);vertical-align:middle;flex:none;margin-right:7px}.offline .dot{background:var(--dot-offline)}.muted{color:var(--text-muted)}.status{margin-top:3px;font-size:12px;color:var(--text-status);overflow-wrap:anywhere;word-break:break-word}.actions{display:flex;flex-wrap:wrap;gap:8px}.actions button{flex:1 1 150px}#device{min-width:180px}.tablewrap{width:100%;max-width:100%;overflow-x:auto;overscroll-behavior-x:contain}table{width:100%;min-width:760px;border-collapse:collapse}th,td{text-align:left;padding:9px;border-bottom:1px solid var(--border);font-size:12px;white-space:nowrap}th{color:var(--thead)}.login{display:grid;place-items:center;min-height:100vh;padding:20px}.login form{width:min(380px,90vw);background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:28px;box-shadow:var(--shadow)}.login input,.login button{width:100%;margin-top:10px}.login h1{margin:0}.login p,#error{color:var(--text-muted)}
|
||||
@media(max-width:800px){.grid{grid-template-columns:1fr}.wide{grid-column:auto}main{padding:12px}header{padding:0 14px}.header-actions{gap:6px}.card{padding:15px}.cardhead{flex-wrap:wrap}.cardhead>#device{width:100%;min-width:0}.actions button{flex:1 1 140px}}
|
||||
@media(max-width:680px){header{align-items:flex-start;padding-top:12px;padding-bottom:12px}header span{display:none}.brand-wrap{padding-top:2px}.brand-logo{width:32px;height:32px}.header-actions{flex-direction:column;align-items:stretch;width:112px}.header-actions button{width:100%;padding:8px 9px}.devices{grid-template-columns:1fr}.cardhead{flex-direction:column;align-items:stretch;gap:8px}.cardhead h2{margin-bottom:0}.cardhead button,#device{width:100%;min-width:0}.actions button{flex:1 1 calc(50% - 4px)}}
|
||||
@media(max-width:450px){main{padding:9px}.card{padding:13px;border-radius:12px}.actions{display:grid;grid-template-columns:1fr 1fr}.actions button{width:100%;min-width:0}.login form{padding:22px}.header-actions{width:104px}}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important}}
|
||||
|
||||
/* 主题切换极简矢量图标按钮 */
|
||||
.btn-icon{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;padding:0;border-radius:9px;background:var(--bg-sub);border:1px solid var(--border-strong);color:var(--text-main);cursor:pointer;transition:background .2s,border-color .2s}
|
||||
.btn-icon:hover{filter:brightness(1.1)}
|
||||
.theme-svg{display:none;width:18px;height:18px}
|
||||
:root[data-theme="dark"] .svg-sun{display:block;color:#facc15}
|
||||
:root[data-theme="light"] .svg-moon{display:block;color:#475569}
|
||||
|
||||
/* 设备卡片与画像升级 (方案 1: 经典主副标题分行) */
|
||||
.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px}
|
||||
.device-card{min-width:0;padding:16px;border:1px solid var(--border);border-radius:12px;background:var(--bg-sub);display:flex;flex-direction:column;gap:12px}
|
||||
|
||||
.v1-head{display:flex;flex-direction:column;gap:4px;min-width:0}
|
||||
.v1-row1{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}
|
||||
.v1-title{display:flex;align-items:center;gap:8px;min-width:0;flex:1}
|
||||
.v1-name{font-size:16px;font-weight:700;color:var(--text-main);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block}
|
||||
.v1-row2{font-size:12px;color:var(--text-muted);padding-left:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
|
||||
.btn-revoke{padding:2px 8px;font-size:11px;border-radius:5px;background:transparent;border:1px solid var(--border-strong);color:var(--dot-offline);cursor:pointer;flex-shrink:0}
|
||||
.btn-revoke:hover{background:rgba(239,68,68,.15);border-color:var(--dot-offline)}
|
||||
|
||||
/* 资源画像 2列紧凑栅格 */
|
||||
.profile-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px 12px;padding:10px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:8px;font-size:12px}
|
||||
.p-item{display:flex;justify-content:space-between;align-items:center;gap:6px;min-height:20px}
|
||||
.p-label{color:var(--text-muted);font-weight:500;font-size:11px}
|
||||
.p-val{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-weight:600;font-size:12px;color:var(--text-main);white-space:nowrap}
|
||||
.badge-docker-text{padding:1px 6px;border-radius:4px;font-size:11px;font-weight:700}
|
||||
.badge-docker-text.yes{background:rgba(34,197,94,.15);color:var(--dot-online);border:1px solid rgba(34,197,94,.3)}
|
||||
.badge-docker-text.no{background:rgba(148,163,184,.15);color:var(--text-muted);border:1px solid var(--border)}
|
||||
+107
-9
@@ -1,12 +1,110 @@
|
||||
const $=s=>document.querySelector(s);
|
||||
async function api(path,opt={}){let r=await fetch("/panel/api"+path,opt);if(r.status===401){location.href="/panel/login";throw Error("unauthorized")}if(!r.ok)throw Error(await r.text());return r.json()}
|
||||
function esc(v){return String(v??"").replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]))}
|
||||
async function loadDevices(){let ds=await api("/devices");$("#devices").innerHTML=ds.map(d=>`<div class="device ${d.status==="online"?"":"offline"}"><b><i class="dot"></i>${esc(d.name)}</b><div class="status">${esc(d.status)} · ${d.is_local?"local":"remote"} · ${esc(d.arch||"")}/${esc(d.os||"")}</div></div>`).join("");$("#device").innerHTML=ds.map(d=>`<option>${esc(d.name)}</option>`).join("")}
|
||||
async function loadAudits(){let a=await api("/audits?limit=100");$("#audits").innerHTML=a.map(x=>`<tr><td>${new Date(x.timestamp*1000).toLocaleString()}</td><td>${esc(x.device)}</td><td>${esc(x.action)}</td><td><code>${esc(x.command)}</code></td><td>${x.exit_code}</td><td>${x.duration_ms}ms</td><td>${esc(x.caller_ip)}</td></tr>`).join("")}
|
||||
$("#refresh").onclick=loadDevices;$("#auditRefresh").onclick=loadAudits;
|
||||
$("#run").onclick=async()=>{let o=$("#output");o.textContent="执行中…";try{let x=await api("/exec",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device:$("#device").value,command:$("#command").value,timeout:30})});o.textContent=`exit_code: ${x.exit_code}\n\nstdout:\n${x.stdout}\n\nstderr:\n${x.stderr}\nduration: ${x.duration_ms}ms`}catch(e){o.textContent=e.message}};
|
||||
(function(){
|
||||
const b=$("#themeToggle");
|
||||
if(!b)return;
|
||||
b.onclick=()=>{
|
||||
const current=document.documentElement.dataset.theme||"dark";
|
||||
const next=current==="light"?"dark":"light";
|
||||
document.documentElement.dataset.theme=next;
|
||||
localStorage.setItem("vpc_theme",next);
|
||||
};
|
||||
})();
|
||||
|
||||
async function api(path,opt={}){
|
||||
let r=await fetch("/panel/api"+path,opt);
|
||||
if(r.status===401){location.href="/panel/login";throw Error("unauthorized")}
|
||||
if(!r.ok)throw Error(await r.text());
|
||||
return r.json()
|
||||
}
|
||||
|
||||
function esc(v){
|
||||
return String(v??"").replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]))
|
||||
}
|
||||
|
||||
async function removeDevice(name){
|
||||
if(!confirm(`确认注销并踢出节点 [${name}] 吗?\n注销后该节点将被断开并禁止再次连入。`)) return;
|
||||
try{
|
||||
await api("/devices?name="+encodeURIComponent(name), {method: "DELETE"});
|
||||
await loadDevices();
|
||||
}catch(e){
|
||||
alert("注销失败: "+e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDevices(){
|
||||
let all=await api("/devices");
|
||||
let ds=all.filter(d=>!d.is_local);
|
||||
$("#devices").innerHTML=ds.map(d=>{
|
||||
const p = d.profile || {};
|
||||
const role = p.role || "APPLICATION";
|
||||
const isOnline = d.status === "online";
|
||||
const statusText = isOnline ? "在线" : "离线";
|
||||
const archOs = (d.arch || d.os) ? `${esc(d.arch||"")}/${esc(d.os||"")} · ` : "";
|
||||
const cpuStr = p.cpu_cores ? `${p.cpu_cores}C · ${p.cpu_usage_percent ?? 0}%` : '-';
|
||||
const loadStr = p.load_1m !== undefined ? p.load_1m.toFixed(2) : '-';
|
||||
const memStr = p.mem_available ? `${p.mem_available} (${p.mem_percent}%)` : (p.mem_percent !== undefined ? `${p.mem_percent}%` : '-');
|
||||
const diskStr = p.disk_free ? `${p.disk_free} (${p.disk_percent}%)` : (p.disk_percent !== undefined ? `${p.disk_percent}%` : '-');
|
||||
const psiStr = p.io_psi !== undefined ? p.io_psi.toFixed(2) : '-';
|
||||
const dockerVal = p.docker ? 'YES' : 'NO';
|
||||
const dockerClass = p.docker ? 'yes' : 'no';
|
||||
|
||||
return `
|
||||
<div class="device-card ${isOnline ? "online" : "offline"}">
|
||||
<div class="v1-head">
|
||||
<div class="v1-row1">
|
||||
<div class="v1-title">
|
||||
<span class="dot"></span>
|
||||
<strong class="v1-name" title="${esc(d.name)}">${esc(d.name)}</strong>
|
||||
</div>
|
||||
<button class="btn-revoke" onclick="removeDevice('${esc(d.name)}')">注销</button>
|
||||
</div>
|
||||
<div class="v1-row2">${archOs}${statusText}</div>
|
||||
</div>
|
||||
<div class="profile-grid">
|
||||
<div class="p-item"><span class="p-label">CPU</span><span class="p-val">${cpuStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">LOAD</span><span class="p-val">${loadStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">MEM</span><span class="p-val">${memStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">DISK</span><span class="p-val">${diskStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">IO PSI</span><span class="p-val">${psiStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">DOCKER</span><span class="p-val badge-docker-text ${dockerClass}">${dockerVal}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
$("#device").innerHTML=ds.map(d=>'<option>'+esc(d.name)+'</option>').join("");
|
||||
}
|
||||
|
||||
async function loadAudits(){
|
||||
let a=await api("/audits?limit=100");
|
||||
$("#audits").innerHTML=a.map(x=>'<tr><td>'+new Date(x.timestamp*1000).toLocaleString()+'</td><td>'+esc(x.device)+'</td><td>'+esc(x.action)+'</td><td><code>'+esc(x.command)+'</code></td><td>'+x.exit_code+'</td><td>'+x.duration_ms+'ms</td><td>'+esc(x.caller_ip)+'</td></tr>').join("")
|
||||
}
|
||||
|
||||
$("#refresh").onclick=loadDevices;
|
||||
$("#auditRefresh").onclick=loadAudits;
|
||||
$("#run").onclick=async()=>{
|
||||
let o=$("#output");
|
||||
o.textContent="执行中…";
|
||||
try{
|
||||
let x=await api("/exec",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device:$("#device").value,command:$("#command").value,timeout:30})});
|
||||
o.textContent=`exit_code: ${x.exit_code}\n\nstdout:\n${x.stdout}\n\nstderr:\n${x.stderr}\nduration: ${x.duration_ms}ms`
|
||||
}catch(e){
|
||||
o.textContent=e.message
|
||||
}
|
||||
};
|
||||
$("#copySchema").onclick=()=>navigator.clipboard.writeText(location.origin+"/openapi.json");
|
||||
$("#copyPrompt").onclick=()=>navigator.clipboard.writeText("你是我的私有 VPS 运维助手。执行操作前确认目标设备;优先使用 list_devices 确认节点状态;高风险操作先向用户确认。");
|
||||
$("#rotateKey").onclick=async()=>{if(!confirm("轮换后旧 API Key 会立即失效,确认继续?"))return;try{let x=await api("/key/rotate",{method:"POST"});$("#newKey").textContent="新 API Key(仅本次显示):\n"+x.api_key}catch(e){$("#newKey").textContent=e.message}};
|
||||
$("#logout").onclick=async()=>{await fetch("/panel/logout",{method:"POST"});location.href="/panel/login"};
|
||||
loadDevices().then(loadAudits).catch(console.error);
|
||||
$("#rotateKey").onclick=async()=>{
|
||||
if(!confirm("轮换后旧 API Key 会立即失效,确认继续?"))return;
|
||||
try{
|
||||
let x=await api("/key/rotate",{method:"POST"});
|
||||
$("#newKey").textContent="新 API Key(仅本次显示):\n"+x.api_key
|
||||
}catch(e){
|
||||
$("#newKey").textContent=e.message
|
||||
}
|
||||
};
|
||||
$("#logout").onclick=async()=>{
|
||||
await fetch("/panel/logout",{method:"POST"});
|
||||
location.href="/panel/login"
|
||||
};
|
||||
loadDevices().then(loadAudits).catch(console.error);
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
+1
-13
@@ -1,13 +1 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head>
|
||||
<body>
|
||||
<header><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div><button id="logout">退出</button></header>
|
||||
<main>
|
||||
<section class="grid">
|
||||
<article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh">刷新</button></div><div id="devices" class="devices"></div></article>
|
||||
<article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><button id="copySchema">复制 Schema 地址</button><button id="copyPrompt">复制 System Prompt</button><button id="rotateKey">轮换 API Key</button><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article>
|
||||
<article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run">执行</button></div><pre id="output"></pre></article>
|
||||
<article class="card wide"><div class="cardhead"><h2>审计日志</h2><button id="auditRefresh">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article>
|
||||
</section>
|
||||
</main><script src="/static/app.js"></script></body></html>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>审计日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html>
|
||||
|
||||
@@ -1 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button>登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/";else document.querySelector("#error").textContent="密码错误或未配置面板密码";}</script></body></html>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html>
|
||||
|
||||
Reference in New Issue
Block a user