From ff29462f2adaf68c9de3e6de009342afe89c2611 Mon Sep 17 00:00:00 2001 From: admin Date: Sat, 26 Sep 2026 01:31:38 +0800 Subject: [PATCH] Move VM actions into detail view and show host region --- README.md | 4 +- static/app.js | 222 +++++++++++++++++++++++++++------ static/index.html | 27 +++- static/styles.css | 7 +- tests/test_app.py | 37 ++++-- tests/test_database.py | 13 +- tests/test_libvirt_service.py | 26 +++- tests/test_remote_host.py | 18 ++- virsh_panel/app.py | 25 ++-- virsh_panel/database.py | 4 +- virsh_panel/libvirt_service.py | 36 +++++- virsh_panel/remote_host.py | 16 +++ 12 files changed, 368 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 3817afcd..eaf8163f 100644 --- a/README.md +++ b/README.md @@ -42,11 +42,13 @@ PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m uvicorn virsh_panel.app:create_app 1. 通过你的 HTTPS 域名打开面板,使用启动终端输出中的一次性令牌填写 MariaDB 的地址、端口、已有数据库名、专用账号和密码。数据库账号至少需要在该数据库中建表及读写权限;连接失败时不会保存配置。当前数据库连接尚未提供 TLS 参数,数据库请放在面板本机或可信内网,不要将其端口暴露公网。 2. 使用同一个令牌创建面板管理员。创建完成后令牌失效,管理员密码只保存为密码哈希。 -3. 在网页填写 B 的 IP/DNS、SSH 端口、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。口令只在当前面板进程的内存中用于解锁,不写入数据库、磁盘或浏览器存储;面板重启后,登录网页并在“解锁宿主机 SSH 私钥”页面重新输入。 +3. 在网页填写 B 的 IP/DNS、SSH 端口、虚拟机地区、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。地区是这台宿主机上虚拟机共用的展示标签,可留空;它不影响 SSH 连接或已导入的模板。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。口令只在当前面板进程的内存中用于解锁,不写入数据库、磁盘或浏览器存储;面板重启后,登录网页并在“解锁宿主机 SSH 私钥”页面重新输入。 4. 点击“扫描主机指纹”,再通过 B 的可信控制台运行 `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` 独立核对;确认后在网页测试、保存。保存前会重扫并测试 SSH 与 libvirt API,失败不会覆盖现有连接。 宿主机私钥和配置加密保存在 MariaDB。OpenSSH 连接时需要读取私钥文件,Linux 上面板会将其临时还原到权限为 `0700` 的 `/dev/shm` 内存文件系统目录;面板关闭时清除。`data/runtime-wrappers/` 只包含不带密钥的启动包装器。面板仅支持单个 Uvicorn worker;多 worker 会导致各自 SSH 解锁状态不一致。 +虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。 + 磁盘目录和 ISO 目录填写的是 **B 宿主机**上已存在的绝对路径,例如 `/home/kvm`、`/home/iso`,不是 A 面板服务器的路径;不需要提前手动创建 libvirt 存储池。点击“保存”时,面板会将这些现有目录定义为 libvirt `dir` 存储池并启动,作为内部管理机制;不会创建目录,也不会移动或删除现有文件。新建虚拟机的磁盘文件使用配置的磁盘目录下的 `<虚拟机名>.qcow2`,安装镜像使用配置的 ISO 目录下所选的 `.iso`;虚拟机 XML 通过绝对文件路径引用它们。“测试连接”不会修改宿主机,因此此时若目录尚未注册为池,可能仅显示资源警告。也可继续填写已有的 libvirt 存储池名称。若 B 的目录权限或 SELinux 策略阻止 libvirt 访问,保存会给出错误,需在 B 上修正权限或标签。 “默认虚拟网络或网桥”填写已有 libvirt 虚拟网络名称(如 `default`);若要使用 B 上已有的 Linux 网桥 `br0`,请填写 **`bridge:br0`**。单独填写 `br0` 表示名为 `br0` 的 libvirt 虚拟网络,不表示网桥。面板不会创建网桥;桥接网络的 IP、DHCP 与防火墙由你在 B 上配置。创建 VM 时,面板自动按 vCPU 数设置 virtio 网卡队列,例如 8 vCPU 对应 `driver.queues=8`;按 RHEL 10 建议最多设 16 队列。 diff --git a/static/app.js b/static/app.js index e871f053..ab5f1cff 100644 --- a/static/app.js +++ b/static/app.js @@ -7,6 +7,8 @@ const state = { csrfToken: "", username: "", vms: [], + selectedVmId: null, + vmActionInFlight: null, resources: null, templateLoad: null, templateImportJobId: null, @@ -128,6 +130,7 @@ function showLogin() { state.updateReturnView = null; state.csrfToken = ""; state.vms = []; + state.selectedVmId = null; clearHostPrivateKey(); byId("unlock-passphrase").value = ""; byId("update-access-token").value = ""; @@ -226,6 +229,7 @@ function showHostView(hostConfig = { configured: false }) { byId("host-back-button").hidden = !configured; byId("host-address").value = configured ? (hostConfig.host || "") : ""; byId("host-port").value = configured ? (hostConfig.port || 22) : 22; + byId("host-region").value = configured ? (hostConfig.region || "") : ""; byId("host-storage-pool").value = configured ? (hostConfig.storage_pool || "default") : "default"; byId("host-iso-pool").value = configured ? (hostConfig.iso_pool || "iso") : "iso"; byId("host-network").value = configured ? (hostConfig.default_network || "default") : "default"; @@ -294,7 +298,10 @@ async function initialize() { } function showVmWorkspace() { + state.selectedVmId = null; byId("vm-workspace").hidden = false; + byId("vm-list-view").hidden = false; + byId("vm-detail-view").hidden = true; byId("update-workspace").hidden = true; byId("vm-navigation-button").classList.add("active"); byId("vm-navigation-button").setAttribute("aria-current", "page"); @@ -503,6 +510,7 @@ function hostPayload() { return { host, port, + region: byId("host-region").value.trim(), private_key: privateKey, private_key_passphrase: byId("host-private-key-passphrase").value, host_key: scan.known_hosts_line, @@ -617,18 +625,22 @@ async function loadVMs(silent = false) { if (state.loadingVMs || byId("dashboard-view").hidden) return; state.loadingVMs = true; const refreshButton = byId("refresh-button"); + const detailRefreshButton = byId("vm-detail-refresh-button"); refreshButton.disabled = true; + detailRefreshButton.disabled = true; try { const result = await api("/api/v1/vms"); state.vms = Array.isArray(result?.items) ? result.items : []; setConnection(true); renderVMs(); + syncVmDetailAfterRefresh(); } catch (error) { setConnection(false); if (!silent && !byId("dashboard-view").hidden) toast(error.message, "error"); if (!state.vms.length) renderVMs(true); } finally { refreshButton.disabled = false; + detailRefreshButton.disabled = false; state.loadingVMs = false; } } @@ -660,6 +672,20 @@ function diskLabel(vm) { return "—"; } +function vmSystemInfo(vm) { + if (vm.os_source === "iso") return { label: "安装镜像", value: String(vm.install_iso || "未识别") }; + if (vm.os_source === "cloud_template") return { label: "系统镜像", value: String(vm.os_name || "未识别") }; + return { label: "系统", value: String(vm.os_name || "未识别") }; +} + +function vmRegion(vm) { + return String(vm.region || "").trim() || "未设置"; +} + +function vmIp(vm) { + return String(vm.public_ip_cidr || "").trim() || "未获取"; +} + function makeCell(row, className = "") { const cell = document.createElement("td"); if (className) cell.className = className; @@ -678,6 +704,7 @@ function actionButton(label, handler, options = {}) { const button = makeElement("button", `row-button ${options.variant || ""}`, label); button.type = "button"; button.disabled = Boolean(options.disabled); + if (options.key) button.dataset.vmAction = options.key; if (options.title) button.title = options.title; button.addEventListener("click", handler); return button; @@ -694,11 +721,14 @@ function renderVMs(connectionError = false) { const query = byId("search-input").value.trim().toLocaleLowerCase(); const filter = byId("state-filter").value; const filtered = all.filter((vm) => { - const matchesText = !query || String(vm.name || "").toLocaleLowerCase().includes(query) || String(vm.uuid || "").toLocaleLowerCase().includes(query) || String(vm.public_ip_cidr || "").toLocaleLowerCase().includes(query); + const matchesText = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.region, vm.os_name, vm.install_iso] + .some((value) => String(value || "").toLocaleLowerCase().includes(query)); return matchesText && (filter === "all" || stateCategory(vm.state) === filter); }); text("inventory-count", `${filtered.length} 台虚拟机${filtered.length !== all.length ? ` · 共 ${all.length} 台` : ""}`); const tbody = byId("vm-table-body"); + const focusedVmId = document.activeElement?.classList.contains("vm-name-link") + ? document.activeElement.dataset.vmUuid : null; tbody.replaceChildren(); const empty = byId("empty-state"); empty.hidden = filtered.length !== 0; @@ -719,51 +749,141 @@ function renderVMs(connectionError = false) { for (const vm of filtered) { const uuid = String(vm.uuid || ""); const category = stateCategory(vm.state); - const running = category === "running"; - const stopped = category === "stopped"; const row = document.createElement("tr"); const identity = makeElement("div", "vm-identity"); identity.append(makeElement("div", "vm-icon", "▣")); const identityText = makeElement("div"); - identityText.append(makeElement("span", "vm-name", vm.name || "未命名虚拟机")); + const nameButton = makeElement("button", "vm-name-link", vm.name || "未命名虚拟机"); + nameButton.type = "button"; + nameButton.disabled = !uuid; + nameButton.dataset.vmUuid = uuid; + nameButton.setAttribute("aria-label", `管理虚拟机 ${vm.name || uuid}`); + nameButton.addEventListener("click", () => openVmDetail(uuid)); + identityText.append(nameButton); identityText.append(makeElement("span", "vm-id", uuid || "UUID 未知")); - if (vm.public_ip_cidr) identityText.append(makeElement("span", "vm-public-ip", `公网 ${vm.public_ip_cidr}`)); identity.append(identityText); - makeCell(row).append(identity); - - makeCell(row).append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state))); + const identityCell = makeCell(row); + identityCell.dataset.label = "虚拟机"; + identityCell.append(identity); + + const stateCell = makeCell(row); + stateCell.dataset.label = "状态"; + stateCell.append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state))); + const regionCell = makeCell(row); + regionCell.dataset.label = "地区"; + regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm))); + const system = vmSystemInfo(vm); + const systemCell = makeCell(row); + systemCell.dataset.label = system.label; + systemCell.append(makeElement("span", "vm-metadata", system.value)); + const ipCell = makeCell(row); + ipCell.dataset.label = "已配置公网 IP"; + ipCell.append(makeElement("span", "vm-metadata vm-ip", vmIp(vm))); const spec = makeElement("div", "vm-spec"); spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`)); spec.append(makeElement("small", "", "计算资源")); - makeCell(row).append(spec); - makeCell(row).append(makeElement("span", "vm-spec", diskLabel(vm))); - - const actions = makeElement("div", "row-actions"); - const hasConsole = Number(vm.console_port) > 0; - actions.append(actionButton("控制台", () => void openConsole(vm), { - disabled: !running || !uuid || !hasConsole, - variant: "primary", - title: !running ? "虚拟机运行时可用" : hasConsole ? "打开 VNC 控制台" : "该虚拟机未配置 VNC 控制台", - })); - if (running) { - actions.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget))); - actions.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget))); - actions.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { variant: "danger" })); - actions.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { variant: "danger" })); - } else { - actions.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: !stopped || !uuid })); - } - if (vm.managed && vm.public_ip_cidr) { - actions.append(actionButton("重装", () => openReinstall(vm), { - disabled: !uuid, - variant: "danger", - title: "从云镜像模板重装,成功后自动删除旧系统盘", - })); - } - actions.append(actionButton("删除", () => openDelete(vm), { disabled: !stopped || !uuid, variant: "danger", title: stopped ? "删除虚拟机" : "请先关机再删除" })); - makeCell(row).append(actions); + const specCell = makeCell(row); + specCell.dataset.label = "规格"; + specCell.append(spec); + const diskCell = makeCell(row); + diskCell.dataset.label = "磁盘"; + diskCell.append(makeElement("span", "vm-spec", diskLabel(vm))); tbody.append(row); } + if (focusedVmId) { + const replacement = Array.from(tbody.querySelectorAll(".vm-name-link")) + .find((button) => button.dataset.vmUuid === focusedVmId); + replacement?.focus({ preventScroll: true }); + } +} + +function openVmDetail(uuid) { + const vm = state.vms.find((item) => String(item.uuid || "") === uuid); + if (!vm) { + toast("虚拟机已不在当前列表中,请刷新后重试。", "error"); + return; + } + state.selectedVmId = uuid; + byId("vm-list-view").hidden = true; + byId("vm-detail-view").hidden = false; + renderVmDetail(vm); + window.scrollTo({ top: 0, behavior: "auto" }); + byId("vm-detail-name").focus(); +} + +function syncVmDetailAfterRefresh() { + if (!state.selectedVmId || byId("vm-workspace").hidden || byId("vm-detail-view").hidden) return; + const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId); + if (!vm) { + showVmWorkspace(); + toast("这台虚拟机已从宿主机移除,已返回列表。", "info"); + byId("vm-list-title").focus(); + return; + } + renderVmDetail(vm); +} + +function renderVmDetail(vm) { + const category = stateCategory(vm.state); + const running = category === "running"; + const stopped = category === "stopped"; + const uuid = String(vm.uuid || ""); + const busy = state.vmActionInFlight === uuid; + const system = vmSystemInfo(vm); + text("vm-detail-name", vm.name || "未命名虚拟机"); + text("vm-detail-uuid", uuid || "UUID 未知"); + text("vm-detail-state", stateLabel(vm.state)); + byId("vm-detail-state").className = `state-pill ${category}`; + text("vm-detail-region", vmRegion(vm)); + text("vm-detail-os-label", system.label); + text("vm-detail-os", system.value); + text("vm-detail-ip", vmIp(vm)); + text("vm-detail-spec", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`); + text("vm-detail-disk", diskLabel(vm)); + const hasConsole = Number(vm.console_port) > 0; + text("vm-detail-console-status", hasConsole ? (running ? "可连接" : "需先开机") : "未配置"); + text("vm-detail-autostart", vm.autostart ? "已开启" : "未开启"); + text("vm-detail-managed", vm.managed ? "面板创建" : "外部导入"); + text("breadcrumb-current", vm.name || "虚拟机详情"); + + const primary = byId("vm-detail-primary-actions"); + const danger = byId("vm-detail-danger-actions"); + const focusedAction = document.activeElement?.dataset.vmAction || null; + primary.replaceChildren(); + danger.replaceChildren(); + primary.append(actionButton("打开 VNC 控制台", () => void openConsole(vm), { + disabled: busy || !running || !uuid || !hasConsole, + variant: "primary", + key: "console", + title: !running ? "虚拟机运行时可用" : hasConsole ? "打开 VNC 控制台" : "该虚拟机未配置 VNC 控制台", + })); + if (running) { + primary.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget), { disabled: busy, key: "shutdown" })); + primary.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget), { disabled: busy, key: "reboot" })); + danger.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { disabled: busy, variant: "danger", key: "poweroff" })); + danger.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { disabled: busy, variant: "danger", key: "reset" })); + } else { + primary.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: busy || !stopped || !uuid, key: "start" })); + } + if (vm.managed && vm.public_ip_cidr) { + danger.append(actionButton("重装系统", () => openReinstall(vm), { + disabled: busy || !uuid, + variant: "danger", + key: "reinstall", + title: "从云镜像模板重装,成功后自动删除旧系统盘", + })); + } + danger.append(actionButton("删除虚拟机", () => openDelete(vm), { + disabled: busy || !stopped || !uuid, + variant: "danger", + key: "delete", + title: stopped ? "删除虚拟机" : "请先关机再删除", + })); + if (focusedAction) { + const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) + .find((button) => button.dataset.vmAction === focusedAction && !button.disabled); + replacement?.focus({ preventScroll: true }); + } } function resourceValue(item, kind) { @@ -955,6 +1075,7 @@ function openModal(id) { function closeModal() { if (!state.activeModal) return; + const returnFocus = state.lastFocus; if (state.activeModal.id === "console-modal") disconnectConsole(); if (state.activeModal.id === "create-modal") { byId("vm-guest-ssh-public-key").value = ""; @@ -976,7 +1097,14 @@ function closeModal() { state.deleteTarget = null; state.confirmTarget = null; document.body.style.overflow = ""; - state.lastFocus?.focus?.(); + if (returnFocus?.isConnected && returnFocus.getClientRects().length && !returnFocus.disabled) { + returnFocus.focus(); + } else if (!byId("vm-workspace").hidden && !byId("vm-detail-view").hidden) { + const action = returnFocus?.dataset?.vmAction; + const replacement = action ? Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) + .find((button) => button.dataset.vmAction === action && !button.disabled) : null; + (replacement || byId("vm-detail-name")).focus(); + } } function openCreate() { @@ -1169,7 +1297,11 @@ function openConfirm(vm, action) { async function runAction(vm, action, button) { const label = { start: "开机", shutdown: "关机", reboot: "重启", poweroff: "强制断电", reset: "强制重置" }[action] || action; + const focusAction = button?.dataset.vmAction || null; + if (state.vmActionInFlight === vm.uuid) return false; + state.vmActionInFlight = vm.uuid; if (button) setButtonBusy(button, true); + if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh(); try { await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/actions`, { method: "POST", body: { action } }); toast(`已向 ${vm.name || vm.uuid} 发送${label}指令。`, "success"); @@ -1180,7 +1312,14 @@ async function runAction(vm, action, button) { toast(`${label}失败:${error.message}`, "error"); return false; } finally { + state.vmActionInFlight = null; + if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh(); if (button?.isConnected) setButtonBusy(button, false); + if (focusAction && !state.activeModal && state.selectedVmId === vm.uuid && !byId("vm-detail-view").hidden) { + const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) + .find((item) => item.dataset.vmAction === focusAction && !item.disabled); + (replacement || byId("vm-detail-name")).focus(); + } } } @@ -1358,7 +1497,7 @@ byId("host-back-button").addEventListener("click", () => { }); byId("host-address").addEventListener("input", resetFingerprint); byId("host-port").addEventListener("input", resetFingerprint); -for (const id of ["host-storage-pool", "host-iso-pool", "host-network"]) { +for (const id of ["host-region", "host-storage-pool", "host-iso-pool", "host-network"]) { byId(id).addEventListener("input", markHostTestStale); } byId("host-private-key").addEventListener("input", () => { @@ -1495,6 +1634,11 @@ byId("update-apply-button").addEventListener("click", async () => { }); byId("refresh-button").addEventListener("click", () => void loadVMs()); +byId("vm-detail-refresh-button").addEventListener("click", () => void loadVMs()); +byId("vm-detail-back-button").addEventListener("click", () => { + showVmWorkspace(); + byId("search-input").focus(); +}); byId("search-input").addEventListener("input", () => renderVMs()); byId("state-filter").addEventListener("change", () => renderVMs()); byId("create-button").addEventListener("click", openCreate); @@ -1817,6 +1961,10 @@ byId("delete-form").addEventListener("submit", async (event) => { await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}?delete_disks=${deleteDisks}`, { method: "DELETE" }); closeModal(); toast(`${vm.name || vm.uuid} 已删除${deleteDisks ? ",磁盘已一并删除" : ""}。`, "success"); + if (state.selectedVmId === vm.uuid) { + showVmWorkspace(); + byId("vm-list-title").focus(); + } await loadVMs(true); } catch (error) { showError("delete-error", error.message); diff --git a/static/index.html b/static/index.html index e68d75ab..36a2cc5f 100644 --- a/static/index.html +++ b/static/index.html @@ -5,8 +5,8 @@ VirtPilot · 虚拟机管理 - - + +
@@ -129,6 +129,7 @@
+
用于展示这台宿主机上的虚拟机所在地区;留空时显示“未设置”。
可直接填写宿主机上的绝对路径,如 /home/kvm;也兼容现有 libvirt 存储池名称。
可直接填写宿主机上的绝对路径,如 /home/iso;不是面板服务器的路径。
@@ -204,7 +205,8 @@
-
VIRTUAL MACHINES

虚拟机管理

查看状态、管理电源,并通过浏览器接入控制台。

+
+
VIRTUAL MACHINES

虚拟机管理

查看虚拟机信息;点击名称进入管理页面执行操作。

@@ -214,12 +216,27 @@
-

虚拟机列表

正在加载…

-
虚拟机状态规格磁盘操作
+

虚拟机列表

正在加载…

+
虚拟机状态地区系统 / 安装镜像已配置公网 IP规格磁盘
+ +