diff --git a/README.md b/README.md index 5afed32b..64d38011 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,9 @@ PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m uvicorn virsh_panel.app:create_app 宿主机私钥和配置加密保存在 MariaDB。OpenSSH 连接时需要读取私钥文件,Linux 上面板会将其临时还原到权限为 `0700` 的 `/dev/shm` 内存文件系统目录;面板关闭时清除。`data/runtime-wrappers/` 只包含不带密钥的启动包装器。面板仅支持单个 Uvicorn worker;多 worker 会导致各自 SSH 解锁状态不一致。 -虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。 +虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。详情页的公网 IP 不显示 `/24` 等掩码后缀,可点击旁边的按钮复制;磁盘信息只显示总容量,不再显示磁盘块数。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。 + +云镜像 VM 的详情页显示 SSH 登录名 `root`。面板保存了初始 root 密码时,默认以星号遮盖,管理员可按需点击“查看”或“复制”;不会在虚拟机列表或普通详情数据中直接返回密码。只有本版本以后由面板新建、或成功重装的密码模式云镜像 VM 才能查看其加密保存的初始密码;公钥模式不保存也不显示密码,ISO 安装和面板外创建的 VM 的客体密码则不由面板管理。旧 VM 曾使用但面板未保存的密码无法从密码哈希或虚拟机系统中还原。客体内修改 root 密码后,详情页保存的**初始**密码不会自动更新,可能已无法用于登录;请妥善保护数据库备份和面板主密钥。 虚拟机详情页显示 CPU、客体内存、磁盘 I/O 和网络收发四张历史走势图,可切换最近 1 小时、24 小时、7 天和 30 天。面板后台定时从 [libvirt 域统计](https://libvirt.org/manpages/virsh.html#domstats)采样并写入 MariaDB,即使无人打开详情页也会继续记录。查询**只返回最近 30 天**的数据;运行中的面板会分批清理更早的数据库记录。面板停机或数据库不可用时物理清理会暂停,恢复后继续追赶,因此中断期间数据库中可能暂时留有超期记录。CPU 是按 vCPU 数归一化、最高显示 100% 的使用率,磁盘和网络显示每秒速率而不是累计量或网络带宽上限;网络收发方向以虚拟机为准。磁盘与网卡只汇总 libvirt 实际提供计数的设备,未提供计数的设备无法纳入统计。内存占用依赖客体内存气球统计,客户机不提供或统计过期时会显示无数据,不会把宿主机 QEMU 进程占用误当客体内存。初次采样、虚拟机停机、面板/宿主机不可达或计数器重置期间可能出现空白;面板停机期间不会补录历史。较长时间范围会聚合采样,短暂的停机或采样缺口可能不明显。 @@ -65,11 +67,11 @@ PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m uvicorn virsh_panel.app:create_app 面板的“创建虚拟机”现在有独立的“公网云镜像”方式。先在宿主机设置中选择已工作的 Linux 网桥,例如 `bridge:br0`;打开创建弹窗的“导入新的云镜像模板”,填写 [AlmaLinux 10 官方 Generic Cloud qcow2 镜像](https://wiki.almalinux.org/cloud/Generic-cloud)在 `https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/` 下的下载地址、发布方 SHA-256 和模板显示名。地址必须是官方 HTTPS 直链,面板不会跟随重定向。面板服务器 A 需要能访问该地址。导入在后台运行,一次只允许一个任务,面板下载、校验 SHA-256 后通过当前 libvirt SSH 连接把模板镜像上传到 B 的磁盘池;无需登录 B 手工复制。模板目录记录加密保存在 MariaDB,绑定当前宿主机身份和磁盘池。不要在导入期间关闭面板进程;若进程异常退出,运行中的导入任务记录不会恢复,可能需要检查项目 `data/` 中的 `.cloud-image-*` 临时文件和 B 磁盘池中 `panel-template-*` 卷,不要未经核对就删除。 -选择模板后,填写 VM 资源、已分配给你的**具体公网 IPv4/CIDR**(如实际公网地址加 `/24` 或 `/28`)、同网段网关、1–4 个公网 DNS 地址,再选择一种 root 登录方式:填写 OpenSSH **公钥**时,只能用对应私钥登录 `root@<公网IP>`,密码输入会隐藏;不填公钥时,必须设置 12–128 字符的初始 root 密码,可用它从 VNC 和 SSH 登录。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板会校验公网地址、网络/广播地址、网关和已由面板分配的重复 IP;它无法检测面板外设备的 IP 占用,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。 +选择模板后,填写 VM 资源、已分配给你的**具体公网 IPv4/CIDR**(如实际公网地址加 `/24` 或 `/28`)、同网段网关、1–4 个公网 DNS 地址,再选择一种 root 登录方式:填写 OpenSSH **公钥**时,只能用对应私钥登录 `root@<公网IP>`,密码输入会隐藏;不填公钥时,可以设置 12–128 字符的初始 root 密码,可用它从 VNC 和 SSH 登录;公钥和密码都不填时,面板会自动生成强初始 root 密码。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板会校验公网地址、网络/广播地址、网关和已由面板分配的重复 IP;它无法检测面板外设备的 IP 占用,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。 -创建时,面板在 B 的磁盘池克隆独立 qcow2 磁盘并扩容,生成一个只读、不可启动的 `CIDATA` cloud-init 配置 ISO,经 libvirt 上传后挂载。客体首次直接从硬盘开机,cloud-init 按固定 MAC 配置静态公网 IP、默认网关和 DNS;**不会进入 VNC 安装程序**。[AlmaLinux 本地云镜像用法](https://wiki.almalinux.org/cloud/Generic-cloud-on-local)、[NoCloud 配置说明](https://docs.cloud-init.io/en/latest/reference/datasources/nocloud.html)。有公钥时,面板将其写入 root 的授权密钥并禁用 SSH 密码登录,root 密码保持锁定(VNC 密码登录也不可用);无公钥时,面板只把加盐的 SHA-512-crypt 密码哈希写入配置 ISO,不在面板数据中保存明文,并开启 root 的 SSH 密码登录。密码模式会暴露公网 root 密码认证,建议优先使用公钥及限制 SSH 来源;宿主机上的配置 ISO 仍含密码哈希,必须防止未授权读取。网络或凭据填错后需离线修复或重建。删除 VM 时若勾选“同时删除虚拟磁盘”,面板也会删除其配置 ISO,但**保留共享模板镜像**。这项登录方式变更只对新创建的 VM 生效,不会修改已有 VM。 +创建时,面板在 B 的磁盘池克隆独立 qcow2 磁盘并扩容,生成一个只读、不可启动的 `CIDATA` cloud-init 配置 ISO,经 libvirt 上传后挂载。客体首次直接从硬盘开机,cloud-init 按固定 MAC 配置静态公网 IP、默认网关和 DNS;**不会进入 VNC 安装程序**。[AlmaLinux 本地云镜像用法](https://wiki.almalinux.org/cloud/Generic-cloud-on-local)、[NoCloud 配置说明](https://docs.cloud-init.io/en/latest/reference/datasources/nocloud.html)。有公钥时,面板将其写入 root 的授权密钥并禁用 SSH 密码登录,root 密码保持锁定(VNC 密码登录也不可用);无公钥时,面板把加盐的 SHA-512-crypt 密码哈希写入配置 ISO,并开启 root 的 SSH 密码登录;生成或手填的初始密码还会在 MariaDB 中加密保存,供详情页按需查看或复制。密码模式会暴露公网 root 密码认证,建议优先使用公钥及限制 SSH 来源;宿主机上的配置 ISO 仍含密码哈希,必须防止未授权读取。网络或凭据填错后需离线修复或重建。删除 VM 时若勾选“同时删除虚拟磁盘”,面板也会删除其配置 ISO,但**保留共享模板镜像**。这项登录方式变更只对新创建的 VM 生效,不会修改已有 VM。 -面板创建的公网云镜像 VM 在列表中有“重装”按钮。点击后选择当前宿主机已导入的云镜像模板,输入 VM 名称确认;可填写新的 root SSH 公钥或 12–128 字符的初始 root 密码,二者均不填时会生成强密码。自动生成的密码会在 MariaDB 中加密保存,并在任务成功后显示;管理员点击“已保存密码,完成”后,面板会从任务记录中清除它,之后无法再次查看。同一浏览器标签页刷新或面板进程重启后仍可按任务编号查询,直到确认保存密码为止;关闭标签页前请及时妥善保存。重装自动读取原配置盘中的公网 IP/CIDR、网关、DNS 和 MAC,不要求再次手填网络。运行中的 VM 会先收到正常关机请求;120 秒内未关机则中止,不会强制断电,也不会切换或删除旧系统盘。面板会将所选模板克隆到新系统盘,生成新的 cloud-init 配置盘并启动 VM;新系统尚未启动时切换失败会恢复原定义,旧盘保留。如果启动调用结果不确定但发现新盘已在运行,则保留新旧两份磁盘并提示人工核查。**libvirt 报告新 VM 已启动后,面板会自动删除旧系统盘与旧配置盘;这并不能证明客体系统、网络或 SSH 已工作,旧数据一旦删除不可恢复。** 若旧盘清理失败,任务仍返回成功但附带警告,需在宿主机核查残留卷。此功能仅支持面板创建且配置未被外部修改的公网云镜像 VM,不支持 ISO 安装 VM、快照或多网卡/多磁盘 VM。 +面板创建的公网云镜像 VM 在详情页有“重装”按钮。点击后选择当前宿主机已导入的云镜像模板,输入 VM 名称确认;可填写新的 root SSH 公钥或 12–128 字符的初始 root 密码,二者均不填时会生成强密码。密码模式下,无论密码是自动生成还是手动输入,成功重装后的初始密码都会在 MariaDB 中加密保存,并可在虚拟机详情页按需查看或复制;公钥模式会清除面板此前保存的密码。自动生成的密码仍会在任务成功后显示,管理员点击“已保存密码,完成”只会从**任务记录**中清除密码,不影响详情页保存的初始密码。同一浏览器标签页刷新或面板进程重启后仍可按任务编号查询,直到确认保存密码为止。重装自动读取原配置盘中的公网 IP/CIDR、网关、DNS 和 MAC,不要求再次手填网络。运行中的 VM 会先收到正常关机请求;120 秒内未关机则中止,不会强制断电,也不会切换或删除旧系统盘。面板会将所选模板克隆到新系统盘,生成新的 cloud-init 配置盘并启动 VM;新系统尚未启动时切换失败会恢复原定义,旧盘保留。如果启动调用结果不确定但发现新盘已在运行,则保留新旧两份磁盘并提示人工核查。**libvirt 报告新 VM 已启动后,面板会自动删除旧系统盘与旧配置盘;这并不能证明客体系统、网络或 SSH 已工作,旧数据一旦删除不可恢复。** 若旧盘清理失败,任务仍返回成功但附带警告,需在宿主机核查残留卷。此功能仅支持面板创建且配置未被外部修改的公网云镜像 VM,不支持 ISO 安装 VM、快照或多网卡/多磁盘 VM。 ## 网页一键更新 diff --git a/static/app.js b/static/app.js index 7d98e3c4..b1969781 100644 --- a/static/app.js +++ b/static/app.js @@ -8,6 +8,12 @@ const state = { username: "", vms: [], selectedVmId: null, + credentialVmId: null, + credentialPassword: "", + credentialVisible: false, + credentialBusy: false, + credentialRequestToken: 0, + credentialHideTimer: null, vmActionInFlight: null, metricsRange: "24h", metricsPollTimer: null, @@ -46,6 +52,41 @@ function text(id, value) { byId(id).textContent = value; } +function clearVmCredential() { + state.credentialRequestToken += 1; + if (state.credentialHideTimer) window.clearTimeout(state.credentialHideTimer); + state.credentialHideTimer = null; + state.credentialVmId = null; + state.credentialPassword = ""; + state.credentialVisible = false; + state.credentialBusy = false; + text("vm-detail-root-password", "未记录"); + byId("vm-detail-password-reveal").hidden = true; + byId("vm-detail-password-copy").hidden = true; +} + +async function copyText(value) { + if (navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(value); + return; + } catch { /* Fall back for browsers without clipboard permission. */ } + } + const field = document.createElement("textarea"); + field.value = value; + field.setAttribute("readonly", ""); + field.style.position = "fixed"; + field.style.opacity = "0"; + document.body.append(field); + field.select(); + let copied = false; + try { copied = document.execCommand("copy"); } finally { + field.value = ""; + field.remove(); + } + if (!copied) throw new Error("浏览器无法复制,请手动选择文本。"); +} + function showError(id, message) { const element = byId(id); element.textContent = message; @@ -130,6 +171,7 @@ function showLogin() { stopPolling(); stopVmMetrics(); closeModal(); + clearVmCredential(); state.updatePollToken += 1; state.updateJobId = null; state.updateLastShownJobId = null; @@ -155,6 +197,7 @@ function showDatabaseView() { stopPolling(); stopVmMetrics(); closeModal(); + clearVmCredential(); byId("boot-screen").hidden = true; byId("setup-view").hidden = true; byId("login-view").hidden = true; @@ -168,6 +211,7 @@ function showSetup() { stopPolling(); stopVmMetrics(); closeModal(); + clearVmCredential(); byId("unlock-passphrase").value = ""; byId("boot-screen").hidden = true; byId("database-view").hidden = true; @@ -190,6 +234,7 @@ function showUnlockView(hostConfig) { stopPolling(); stopVmMetrics(); closeModal(); + clearVmCredential(); state.hostConfig = hostConfig; clearHostPrivateKey(); byId("unlock-passphrase").value = ""; @@ -225,6 +270,7 @@ function showHostView(hostConfig = { configured: false }) { stopPolling(); stopVmMetrics(); closeModal(); + clearVmCredential(); state.hostConfig = hostConfig; clearHostPrivateKey(); byId("unlock-passphrase").value = ""; @@ -311,6 +357,7 @@ async function initialize() { function showVmWorkspace() { stopVmMetrics(); + clearVmCredential(); state.selectedVmId = null; byId("vm-workspace").hidden = false; byId("vm-list-view").hidden = false; @@ -354,6 +401,7 @@ function leaveUpdateWorkspace() { async function showUpdateWorkspace() { stopVmMetrics(); + clearVmCredential(); byId("vm-workspace").hidden = true; byId("update-workspace").hidden = false; byId("vm-navigation-button").classList.remove("active"); @@ -677,10 +725,12 @@ function stateLabel(value) { } function diskLabel(vm) { - if (Array.isArray(vm.disks)) { - if (!vm.disks.length) return "—"; - const size = vm.disks.reduce((sum, disk) => sum + Number(disk.capacity_gib || disk.size_gib || 0), 0); - return size > 0 ? `${vm.disks.length} 块 · ${size} GiB` : `${vm.disks.length} 块磁盘`; + if (Array.isArray(vm.disks) && vm.disks.length) { + const size = vm.disks.reduce((sum, disk) => { + const capacity = Number(disk.capacity_gib ?? disk.size_gib ?? 0); + return sum + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0); + }, 0); + if (size > 0) return `${Math.round(size * 100) / 100} GiB`; } if (Number.isFinite(Number(vm.disk_gib)) && Number(vm.disk_gib) > 0) return `${vm.disk_gib} GiB`; return "—"; @@ -697,7 +747,7 @@ function vmRegion(vm) { } function vmIp(vm) { - return String(vm.public_ip_cidr || "").trim() || "未获取"; + return String(vm.public_ip_cidr || "").trim().split("/")[0] || "未获取"; } function makeCell(row, className = "") { @@ -714,6 +764,33 @@ function makeElement(tag, className, content) { return element; } +function makeCopyIconButton(value, label) { + const button = makeElement("button", "vm-copy-icon"); + button.type = "button"; + button.title = `复制${label}`; + button.setAttribute("aria-label", `复制${label}`); + const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + icon.setAttribute("viewBox", "0 0 24 24"); + icon.setAttribute("aria-hidden", "true"); + const back = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + for (const [name, attribute] of Object.entries({ x: "8", y: "8", width: "12", height: "12", rx: "2" })) { + back.setAttribute(name, attribute); + } + const front = document.createElementNS("http://www.w3.org/2000/svg", "path"); + front.setAttribute("d", "M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"); + icon.append(back, front); + button.append(icon); + button.addEventListener("click", async () => { + try { + await copyText(value); + toast(`${label}已复制。`, "success"); + } catch (error) { + toast(error.message, "error"); + } + }); + return button; +} + function actionButton(label, handler, options = {}) { const button = makeElement("button", `row-button ${options.variant || ""}`, label); button.type = "button"; @@ -792,7 +869,11 @@ function renderVMs(connectionError = false) { 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 ip = vmIp(vm); + const ipRow = makeElement("span", "vm-ip-copy-row"); + ipRow.append(makeElement("span", "vm-metadata vm-ip", ip)); + if (ip !== "未获取") ipRow.append(makeCopyIconButton(ip, "公网 IP")); + ipCell.append(ipRow); const spec = makeElement("div", "vm-spec"); spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`)); spec.append(makeElement("small", "", "计算资源")); @@ -811,6 +892,36 @@ function renderVMs(connectionError = false) { } } +function renderVmCredentialStatus(vm) { + const uuid = String(vm.uuid || ""); + const mode = String(vm.auth_mode || "unknown"); + const passwordAvailable = vm.password_available === true; + if (state.credentialVmId && (state.credentialVmId !== uuid || !passwordAvailable)) clearVmCredential(); + const knownRoot = vm.managed && (vm.os_source === "cloud_template" || mode === "password" || mode === "ssh_key"); + text("vm-detail-ssh-user", knownRoot ? "root" : "未记录"); + const shown = passwordAvailable && state.credentialVmId === uuid && state.credentialVisible && !!state.credentialPassword; + text("vm-detail-root-password", passwordAvailable + ? (shown ? state.credentialPassword : "********") + : mode === "ssh_key" ? "SSH 公钥登录,无密码" : mode === "password" ? "未保存" : "未记录"); + const reveal = byId("vm-detail-password-reveal"); + const copy = byId("vm-detail-password-copy"); + reveal.hidden = !passwordAvailable; + copy.hidden = !passwordAvailable; + reveal.disabled = state.credentialBusy || !uuid; + copy.disabled = state.credentialBusy || !uuid; + reveal.textContent = state.credentialBusy ? "读取中…" : shown ? "隐藏" : "查看"; +} + +async function readVmCredential(uuid) { + const token = ++state.credentialRequestToken; + const result = await api(`/api/v1/vms/${encodeURIComponent(uuid)}/credential`, { method: "POST" }); + if (token !== state.credentialRequestToken || state.selectedVmId !== uuid || byId("vm-detail-view").hidden) return null; + if (result?.login_name !== "root" || typeof result?.password !== "string" || !result.password) { + throw new Error("这台虚拟机没有可查看的面板记录密码。"); + } + return result.password; +} + function openVmDetail(uuid) { const vm = state.vms.find((item) => String(item.uuid || "") === uuid); if (!vm) { @@ -818,6 +929,7 @@ function openVmDetail(uuid) { return; } stopVmMetrics(); + clearVmCredential(); state.selectedVmId = uuid; byId("vm-list-view").hidden = true; byId("vm-detail-view").hidden = false; @@ -854,9 +966,12 @@ function renderVmDetail(vm) { 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)); + const ip = vmIp(vm); + text("vm-detail-ip", ip); + byId("vm-detail-ip-copy").hidden = ip === "未获取"; text("vm-detail-spec", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`); text("vm-detail-disk", diskLabel(vm)); + renderVmCredentialStatus(vm); const hasConsole = Number(vm.console_port) > 0; text("vm-detail-console-status", hasConsole ? (running ? "可连接" : "需先开机") : "未配置"); text("vm-detail-autostart", vm.autostart ? "已开启" : "未开启"); @@ -1272,7 +1387,7 @@ function updateCreateAuthMode() { const password = byId("vm-root-password"); const passwordMode = cloud && !publicKey.value.trim(); byId("vm-root-password-field").hidden = !passwordMode; - password.required = passwordMode; + password.required = false; password.disabled = !passwordMode; if (!passwordMode) password.value = ""; } @@ -1887,6 +2002,72 @@ byId("vm-detail-refresh-button").addEventListener("click", () => { void loadVMs(); void loadVmMetrics(); }); +byId("vm-detail-ip-copy").addEventListener("click", async () => { + const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId); + const ip = vm && vmIp(vm); + if (!ip || ip === "未获取") return; + try { + await copyText(ip); + toast("公网 IP 已复制。", "success"); + } catch (error) { + toast(error.message, "error"); + } +}); +byId("vm-detail-password-reveal").addEventListener("click", async () => { + const uuid = state.selectedVmId; + const vm = state.vms.find((item) => String(item.uuid || "") === uuid); + if (!uuid || !vm?.password_available || state.credentialBusy) return; + if (state.credentialVisible && state.credentialVmId === uuid) { + clearVmCredential(); + renderVmCredentialStatus(vm); + return; + } + state.credentialBusy = true; + renderVmCredentialStatus(vm); + try { + const password = await readVmCredential(uuid); + if (!password) return; + state.credentialVmId = uuid; + state.credentialPassword = password; + state.credentialVisible = true; + state.credentialHideTimer = window.setTimeout(() => { + if (state.selectedVmId !== uuid) return; + clearVmCredential(); + const current = state.vms.find((item) => String(item.uuid || "") === uuid); + if (current) renderVmCredentialStatus(current); + }, 30000); + } catch (error) { + if (state.selectedVmId === uuid) toast(error.message, "error"); + } finally { + if (state.selectedVmId === uuid) { + state.credentialBusy = false; + const current = state.vms.find((item) => String(item.uuid || "") === uuid); + if (current) renderVmCredentialStatus(current); + } + } +}); +byId("vm-detail-password-copy").addEventListener("click", async () => { + const uuid = state.selectedVmId; + const vm = state.vms.find((item) => String(item.uuid || "") === uuid); + if (!uuid || !vm?.password_available || state.credentialBusy) return; + state.credentialBusy = true; + renderVmCredentialStatus(vm); + try { + const password = state.credentialVisible && state.credentialVmId === uuid + ? state.credentialPassword : await readVmCredential(uuid); + if (!password || state.selectedVmId !== uuid) return; + await copyText(password); + if (state.selectedVmId === uuid) toast("初始 root 密码已复制,请妥善保管。", "success"); + } catch (error) { + if (state.selectedVmId === uuid) toast(error.message, "error"); + } finally { + if (state.selectedVmId === uuid) { + state.credentialBusy = false; + const current = state.vms.find((item) => String(item.uuid || "") === uuid); + if (current) renderVmCredentialStatus(current); + } + } +}); byId("vm-metrics-range").addEventListener("change", (event) => { const range = event.currentTarget.value; if (!Object.hasOwn(VM_METRICS_RANGE_SECONDS, range)) return; @@ -1904,8 +2085,12 @@ window.addEventListener("resize", () => { }, 120); }); document.addEventListener("visibilitychange", () => { - if (document.hidden) stopVmMetrics(); - else startVmMetrics(); + if (document.hidden) { + stopVmMetrics(); + clearVmCredential(); + const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId); + if (vm) renderVmCredentialStatus(vm); + } else startVmMetrics(); }); byId("vm-detail-back-button").addEventListener("click", () => { showVmWorkspace(); @@ -2070,11 +2255,12 @@ byId("create-form").addEventListener("submit", async (event) => { return; } } else { - body.root_password = String(data.get("root_password") || ""); - if (body.root_password.length < 12 || body.root_password.length > 128) { - showError("create-error", "未填写 SSH 公钥时,请设置 12 至 128 个字符的初始 root 密码。"); + const requestedPassword = String(data.get("root_password") || ""); + if (requestedPassword && (requestedPassword.length < 12 || requestedPassword.length > 128)) { + showError("create-error", "自行设置的初始 root 密码需为 12 至 128 个字符;留空将自动生成强密码。"); return; } + if (requestedPassword) body.root_password = requestedPassword; } } else { body.iso = String(data.get("iso") || ""); @@ -2087,9 +2273,12 @@ byId("create-form").addEventListener("submit", async (event) => { byId("vm-root-password").value = ""; setButtonBusy(button, true, "正在创建…"); try { + const autoPassword = source === "cloud" && !body.guest_ssh_public_key && !body.root_password; await api("/api/v1/vms", { method: "POST", body }); closeModal(); - toast(`虚拟机 ${body.name} 创建成功。`, "success"); + toast(autoPassword + ? `虚拟机 ${body.name} 创建成功。初始 root 密码可在虚拟机详情页查看。` + : `虚拟机 ${body.name} 创建成功。`, "success"); await loadVMs(true); window.setTimeout(() => void loadVMs(true), 1200); } catch (error) { diff --git a/static/index.html b/static/index.html index 4347bae8..43e4b3db 100644 --- a/static/index.html +++ b/static/index.html @@ -5,8 +5,8 @@ VirtPilot · 虚拟机管理 - - + +
@@ -228,8 +228,9 @@

虚拟机信息

状态和配置每 15 秒自动更新;IP 是面板记录的配置,不代表系统已联网。

地区
未设置
系统
未识别
-
已配置公网 IP
未获取
计算规格
—
+
已配置公网 IP
未获取
计算规格
—
磁盘
—
VNC 控制台
未配置
+
SSH 登录名
未记录
面板记录的初始 root 密码
未记录
开机自启
未开启
管理来源
—

日常操作

在这里管理这台虚拟机的电源和控制台。

@@ -306,11 +307,11 @@
填写具体 IP 和前缀长度,不是网段地址。
多个地址用逗号或空格分隔。
-
填写后导入 root 用户,使用对应私钥登录;此时无需设置 root 密码,也不开放密码登录。留空则必须设置下方的初始密码。
- +
填写后导入 root 用户,使用对应私钥登录;此时无需设置 root 密码,也不开放密码登录。公钥和密码都留空时自动生成强密码。
+
-

创建后会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。

+

创建后会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。

@@ -334,12 +335,12 @@
仅显示当前宿主机已经导入的云镜像模板;模板必须支持 cloud-init。
填写公钥后使用 root 和对应私钥登录,不开放密码登录。
-
公钥和密码只能选择一种;两项都留空时会自动生成强密码,并仅在本次操作完成后显示一次。
+
公钥和密码只能选择一种;两项都留空时会自动生成强密码。成功重装后,面板记录的初始密码可在虚拟机详情页查看。
- - + + diff --git a/static/styles.css b/static/styles.css index f5041032..99a132da 100644 --- a/static/styles.css +++ b/static/styles.css @@ -125,6 +125,7 @@ tbody tr:hover{background:#fcfefe} .empty-state{text-align:center;padding:65px 20px 72px}.empty-icon{margin:0 auto 16px;width:54px;height:54px;display:flex;align-items:center;justify-content:center;border-radius:16px;background:#eaf7f7;color:#17a3aa;font-size:28px}.empty-state h3{font-size:16px;color:#34465a;margin:0 0 8px}.empty-state p{font-size:12px;color:#a0aebe;margin:0} .footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px} .vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-uuid{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef} +.vm-detail-inline,.vm-ip-copy-row{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.vm-detail-inline{min-height:25px}.vm-detail-secret{font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-mini-button,.vm-copy-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;border:1px solid #d9e9ea;border-radius:6px;background:#f5fbfb;color:#1b8790;font-size:11px;font-weight:700;min-height:25px;padding:3px 7px}.vm-detail-mini-button:not(:disabled):hover,.vm-copy-icon:not(:disabled):hover{background:#e6f6f7;border-color:#b6dcdf}.vm-copy-icon{width:25px;padding:3px}.vm-copy-icon svg{display:block;width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} .vm-metrics{margin-top:25px}.vm-metrics-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}.vm-metrics-heading h2{font-size:19px;margin:7px 0 6px}.vm-metrics-heading p{font-size:11px;color:#8191a1;line-height:1.6;margin:0}.vm-metrics-range-control{display:flex;align-items:center;gap:9px;flex:none;color:#64768a;font-size:11px;font-weight:700}.vm-metrics-range-control select{height:37px;padding:0 11px;border:1px solid #dbe6ec;border-radius:8px;color:#344e60;background:#fff;font-size:12px;font-weight:700}.vm-metrics-status{margin:0 0 14px;padding:9px 12px;border-radius:8px;background:#eaf7f7;color:#277b82;font-size:11px;line-height:1.5}.vm-metrics-status.warning{background:#fff6e9;color:#946620}.vm-metrics-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-metric-card{min-width:0;padding:20px 21px 16px;border:1px solid #e7ecf2;border-radius:13px;background:#fff;box-shadow:0 10px 30px rgba(19,42,65,.027)}.vm-metric-card-heading{display:flex;align-items:flex-start;gap:11px;min-height:62px}.vm-metric-card-heading>div{min-width:0}.vm-metric-card-heading h3{margin:1px 0 6px;font-size:13px;color:#32485b}.vm-metric-card-heading p{margin:0;color:#60758a;font-size:12px;line-height:1.45;overflow-wrap:anywhere}.vm-metric-icon{display:flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;border-radius:9px;font-size:18px;font-weight:700}.vm-metric-icon.cpu{background:#e8f8f8;color:#0f9eaa}.vm-metric-icon.memory{background:#edf3fb;color:#4781cf}.vm-metric-icon.disk{background:#eef3fa;color:#477dc9}.vm-metric-icon.network{background:#eaf8f2;color:#17a685}.vm-metric-plot{display:flex;align-items:center;justify-content:center;height:205px;margin:8px 0 6px;overflow:hidden}.vm-metric-plot svg{display:block;width:100%;height:100%;font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif}.vm-metric-gridline{stroke:#e5edf2;stroke-width:1;stroke-dasharray:3 4}.vm-metric-axis-label{fill:#9aabb9;font-size:10px}.vm-metric-empty{margin:0;padding:15px;text-align:center;color:#94a2af;font-size:11px;line-height:1.6}.vm-metric-legend{display:flex;align-items:center;flex-wrap:wrap;gap:15px;padding-left:7px;color:#728297;font-size:10px;font-weight:700}.vm-metric-legend span{display:inline-flex;align-items:center;gap:6px}.vm-metric-swatch{display:inline-block;width:16px;height:0;border-top:3px solid #0f9eaa;border-radius:2px}.vm-metric-swatch.cpu{border-color:#0f9eaa}.vm-metric-swatch.memory{border-color:#4781cf}.vm-metric-swatch.memory-total{border-color:#a4b7d7;border-top-style:dashed}.vm-metric-swatch.disk-read{border-color:#477dc9}.vm-metric-swatch.disk-write{border-color:#e59c46}.vm-metric-swatch.network-rx{border-color:#17a685}.vm-metric-swatch.network-tx{border-color:#926ed0}.vm-metrics-footnote{margin:12px 1px 0;color:#9ba8b6;font-size:10px;line-height:1.6} .modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)} .modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)} diff --git a/tests/test_app.py b/tests/test_app.py index 9a7b2f68..e896e893 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -102,7 +102,7 @@ class FakeVMService: def get_vm(self, vm_id): self.calls.append(("get_vm", vm_id)) - if vm_id != VM_ID: + if vm_id != self.vm["uuid"]: raise VMError("虚拟机不存在", 404) return self.vm @@ -112,7 +112,13 @@ class FakeVMService: def create_cloud_vm(self, spec, template_volume_name): self.calls.append(("create_cloud_vm", spec, template_volume_name)) - return {**self.vm, "name": spec["name"]} + self.vm = { + **self.vm, "uuid": spec["vm_uuid"], "name": spec["name"], + "managed": True, "os_source": "cloud_template", + "public_ip_cidr": spec["public_ip_cidr"], "os_name": spec["os_name"], + "credential_generation": f"panel-seed-{spec['vm_uuid']}.iso", + } + return self.vm def reinstall_cloud_vm(self, vm_id, template_volume_name, *, os_name=None, ssh_public_key="", root_password_hash=None, @@ -124,7 +130,9 @@ class FakeVMService: assert self.reinstall_gate.wait(timeout=5), "test did not release reinstall job" if progress is not None: progress("completed") - return {"vm": self.vm} + generation = f"panel-seed-reinstall-{len(self.calls)}.iso" + self.vm["credential_generation"] = generation + return {"vm": self.vm, "credential_generation": generation} def import_template(self, image_path, volume_name, virtual_size): self.calls.append(("import_template", volume_name, virtual_size)) @@ -315,7 +323,8 @@ def configure_reinstall_case(web): scope, {"id": template_id, "volume_name": volume_name, "name": "AlmaLinux 10"}, ) service.vm.update({ - "name": "cloud-vm", "managed": True, "public_ip_cidr": "8.8.8.18/24", + "name": "cloud-vm", "managed": True, "os_source": "cloud_template", + "public_ip_cidr": "8.8.8.18/24", "credential_generation": "legacy-seed.iso", }) return csrf, template_id, volume_name @@ -673,6 +682,7 @@ def test_cloud_template_import_job_and_create_dispatch(web): expected_spec = {key: value for key, value in cloud_body.items() if key not in {"source", "template_id"}} expected_spec["os_name"] = "AlmaLinux 10" + expected_spec["vm_uuid"] = created.json()["uuid"] assert ("create_cloud_vm", expected_spec, volume_name) in service.calls assert ("create_vm", expected_spec) not in service.calls @@ -700,6 +710,17 @@ def test_cloud_vm_root_login_uses_either_key_or_hashed_initial_password(web): assert key_spec["guest_ssh_public_key"] == CLOUD_CREATE_BODY["guest_ssh_public_key"] assert "root_password" not in key_spec assert not key_spec.get("root_password_hash") + assert key_response.json()["login_name"] == "root" + assert key_response.json()["auth_mode"] == "ssh_key" + assert not key_response.json()["password_available"] + key_uuid = key_response.json()["uuid"] + key_credential = client.post( + f"/api/v1/vms/{key_uuid}/credential", headers=headers, + ) + assert key_credential.headers["Cache-Control"] == "no-store" + assert key_credential.json() == { + "login_name": "root", "auth_mode": "ssh_key", "password": None, + } password_body = { **key_body, "guest_ssh_public_key": "", "root_password": GUEST_PASSWORD, @@ -714,10 +735,25 @@ def test_cloud_vm_root_login_uses_either_key_or_hashed_initial_password(web): assert "root_password" not in password_spec assert GUEST_PASSWORD not in password_response.text assert GUEST_PASSWORD not in repr(service.calls) + password_uuid = password_response.json()["uuid"] + assert password_response.json()["password_available"] + assert GUEST_PASSWORD not in client.get("/api/v1/vms").text + assert GUEST_PASSWORD not in client.get(f"/api/v1/vms/{password_uuid}").text + assert client.post(f"/api/v1/vms/{password_uuid}/credential").status_code == 403 + assert client.post( + f"/api/v1/vms/{password_uuid}/credential", headers=headers, + ).json() == { + "login_name": "root", "auth_mode": "password", "password": GUEST_PASSWORD, + } + original_generation = service.vm["credential_generation"] + service.vm["credential_generation"] = "new-system-seed.iso" + assert not client.get(f"/api/v1/vms/{password_uuid}").json()["password_available"] + assert client.post(f"/api/v1/vms/{password_uuid}/credential", + headers=headers).json()["password"] is None + service.vm["credential_generation"] = original_generation for invalid_body in ( {**key_body, "root_password": GUEST_PASSWORD}, - {**password_body, "root_password": ""}, {**password_body, "root_password": "too-short"}, {**password_body, "root_password": "X" * 129}, ): @@ -728,14 +764,72 @@ def test_cloud_vm_root_login_uses_either_key_or_hashed_initial_password(web): if call[0] == "create_cloud_vm"]) == 2 no_credential = {**key_body, "guest_ssh_public_key": ""} - rejected = client.post("/api/v1/vms", json=no_credential, - headers=headers) - assert rejected.status_code == 422 + generated = client.post("/api/v1/vms", json=no_credential, + headers=headers) + assert generated.status_code == 201 + assert generated.json()["password_available"] + generated_password = client.post( + f"/api/v1/vms/{generated.json()['uuid']}/credential", headers=headers, + ).json()["password"] + assert len(generated_password) >= 24 + assert generated_password not in generated.text + assert generated_password not in client.get("/api/v1/vms").text + assert generated_password not in repr(service.calls) assert len([call for call in service.calls - if call[0] == "create_cloud_vm"]) == 2 + if call[0] == "create_cloud_vm"]) == 3 + assert client.delete( + f"/api/v1/vms/{generated.json()['uuid']}", headers=headers, + ).status_code == 200 + assert not client.get(f"/api/v1/vms/{generated.json()['uuid']}").json()["password_available"] + + +def test_unknown_vm_has_no_recoverable_password(web): + client, _state, token, service, _manager, _ = web + csrf = setup_admin(client, token) + configure_host(client, csrf) + listed = client.get("/api/v1/vms") + assert listed.status_code == 200 + assert listed.json()["items"][0]["login_name"] is None + assert listed.json()["items"][0]["auth_mode"] == "unknown" + assert not listed.json()["items"][0]["password_available"] + assert client.post( + f"/api/v1/vms/{VM_ID}/credential", headers={"X-CSRF-Token": csrf}, + ).json()["password"] is None + service.vm.update({"managed": True, "os_source": "cloud_template"}) + old_cloud = client.get(f"/api/v1/vms/{VM_ID}").json() + assert old_cloud["login_name"] == "root" + assert old_cloud["auth_mode"] == "unknown" + assert not old_cloud["password_available"] + + +def test_reinstall_password_record_is_removed_when_switching_to_ssh_key(web): + client, _state, _token, _service, _manager, _ = web + csrf, template_id, _volume_name = configure_reinstall_case(web) + headers = {"X-CSRF-Token": csrf} + password_job = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={"template_id": template_id, "confirmation_name": "cloud-vm", + "root_password": GUEST_PASSWORD}, headers=headers, + ) + assert password_job.status_code == 202 + assert wait_for_reinstall_job(client, password_job.json()["job_id"], csrf)["status"] == "succeeded" + assert client.post(f"/api/v1/vms/{VM_ID}/credential", + headers=headers).json()["password"] == GUEST_PASSWORD + key_job = client.post( + f"/api/v1/vms/{VM_ID}/reinstall", + json={"template_id": template_id, "confirmation_name": "cloud-vm", + "ssh_public_key": CLOUD_CREATE_BODY["guest_ssh_public_key"]}, headers=headers, + ) + assert key_job.status_code == 202 + assert wait_for_reinstall_job(client, key_job.json()["job_id"], csrf)["status"] == "succeeded" + assert client.post(f"/api/v1/vms/{VM_ID}/credential", + headers=headers).json()["password"] is None + deleted = client.delete(f"/api/v1/vms/{VM_ID}", headers=headers) + assert deleted.status_code == 200 + assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "unknown" -def test_reinstall_auto_password_remains_available_until_ack_and_is_never_persisted(web): +def test_reinstall_auto_password_job_ack_keeps_vm_credential(web): client, state, _token, service, _manager, _ = web csrf, template_id, volume_name = configure_reinstall_case(web) headers = {"X-CSRF-Token": csrf} @@ -777,6 +871,9 @@ def test_reinstall_auto_password_remains_available_until_ack_and_is_never_persis assert after_ack.status_code == 200 assert "generated_password" not in after_ack.json() assert generated_password not in after_ack.text + assert client.get(f"/api/v1/vms/{VM_ID}").json()["password_available"] + revealed = client.post(f"/api/v1/vms/{VM_ID}/credential", headers=headers) + assert revealed.json()["password"] == generated_password for path in state.data_dir.rglob("*"): if path.is_file(): assert generated_password.encode() not in path.read_bytes() @@ -800,6 +897,9 @@ def test_reinstall_key_mode_has_no_generated_password(web): completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf) assert completed["status"] == "succeeded" assert "generated_password" not in completed + assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key" + assert client.post(f"/api/v1/vms/{VM_ID}/credential", + headers={"X-CSRF-Token": csrf}).json()["password"] is None assert ("reinstall_cloud_vm", VM_ID, volume_name, public_key, None, "AlmaLinux 10") in service.calls diff --git a/tests/test_libvirt_service.py b/tests/test_libvirt_service.py index afc0f4a6..fd39e339 100644 --- a/tests/test_libvirt_service.py +++ b/tests/test_libvirt_service.py @@ -220,6 +220,20 @@ class FakeDomain: int(self.root.findtext("memory")) * 1024, int(self.root.findtext("vcpu")), 0) + def blockInfo(self, identifier, flags): + assert flags == 0 + for disk in self.root.findall("./devices/disk[@device='disk']"): + source = disk.find("source") + target = disk.find("target") + path = source.get("file") if source is not None else None + if identifier not in (path, target.get("dev") if target is not None else None): + continue + for pool in self.backend.pools.values(): + for volume in pool.volumes.values(): + if volume.path() == path: + return (volume.capacity, len(volume.contents), volume.capacity) + raise FakeLibvirtError("block capacity unavailable") + def XMLDesc(self, flags): assert flags in (0, 1) if flags == 1: @@ -589,6 +603,7 @@ class VMServiceTests(unittest.TestCase): self.assertEqual(len(vm["disks"]), 1) self.assertEqual(vm["disks"][0]["source"], "/var/lib/libvirt/images/alma-test.qcow2") + self.assertEqual(vm["disks"][0]["capacity_gib"], 20) self.assertTrue(vm["managed"]) self.assertEqual(vm["console_port"], 5907) self.assertEqual(self.service.console_port(vm["uuid"]), 5907) @@ -1207,6 +1222,15 @@ class VMServiceTests(unittest.TestCase): self.assertIn("alma-test.qcow2", self.backend.pools["images"].volumes) self.assertEqual(len(self.backend.domains), 2) + def test_cloud_vm_uses_panel_reserved_uuid_for_credential_binding(self): + service = self.cloud_service() + reserved_uuid = str(uuid.uuid4()) + created = self.create_cloud_vm(service, self.cloud_spec(vm_uuid=reserved_uuid)) + self.assertEqual(created["uuid"], reserved_uuid) + self.assertEqual(created["credential_generation"], + f"panel-seed-{reserved_uuid}.iso") + self.assertEqual(created["disks"][0]["capacity_gib"], 20) + def test_cloud_vm_clones_template_and_uses_nonboot_seed_iso(self): service = self.cloud_service() created = self.create_cloud_vm(service, self.cloud_spec(os_name="AlmaLinux 10")) diff --git a/virsh_panel/app.py b/virsh_panel/app.py index ac6536d5..89339a9e 100644 --- a/virsh_panel/app.py +++ b/virsh_panel/app.py @@ -288,6 +288,74 @@ def create_app( reinstall_lock = threading.RLock() reinstall_jobs: dict[str, dict] = {} pending_reinstalls: set[tuple[str, str]] = set() + # The production store encrypts each credential record with a fresh AES-GCM + # nonce. The in-memory fallback is only for injected, database-free tests. + test_credentials: dict[str, str] = {} + + def credential_key(profile: dict, vm_id: str) -> str: + try: + canonical_id = str(uuid.UUID(vm_id)) + return f"{host_scope(profile)}.{canonical_id}" + except (TypeError, ValueError, AttributeError, KeyError) as exc: + raise VMError("虚拟机或宿主机身份信息无效", 400) from exc + + def save_credential(profile: dict, vm_id: str, auth_mode: str, + generation: str, password: str | None = None) -> None: + key = credential_key(profile, vm_id) + if not isinstance(generation, str) or not generation: + raise ValueError("虚拟机系统配置代号无效") + value = json.dumps({"auth_mode": auth_mode, "password": password, + "generation": generation}, + ensure_ascii=False, separators=(",", ":")) + if data_store is not None: + data_store.set("vm_credential", key, value) + else: + test_credentials[key] = value + + def delete_credential(profile: dict, vm_id: str) -> None: + key = credential_key(profile, vm_id) + if data_store is not None: + data_store.delete("vm_credential", key) + else: + test_credentials.pop(key, None) + + def parse_credential(raw: str | None) -> dict | None: + if raw is None: + return None + try: + value = json.loads(raw) + except (TypeError, ValueError) as exc: + raise DatabaseError("虚拟机登录凭据记录损坏") from exc + if (not isinstance(value, dict) + or value.get("auth_mode") not in ("password", "ssh_key") + or (value["auth_mode"] == "password" + and (not isinstance(value.get("password"), str) + or not value["password"])) + or not isinstance(value.get("generation"), str) + or not value["generation"] + or (value["auth_mode"] == "ssh_key" and value.get("password") is not None)): + raise DatabaseError("虚拟机登录凭据记录损坏") + return value + + def get_credential(profile: dict, vm_id: str) -> dict | None: + key = credential_key(profile, vm_id) + raw = (data_store.get("vm_credential", key) if data_store is not None + else test_credentials.get(key)) + return parse_credential(raw) + + def decorate_vm(vm: dict, credential: dict | None, profile: dict) -> dict: + cloud = bool(vm.get("managed") and vm.get("os_source") == "cloud_template") + current_credential = (credential if cloud and credential + and credential["generation"] == vm.get("credential_generation") + else None) + return { + **{key: value for key, value in vm.items() if key != "credential_generation"}, + "region": profile.get("region", ""), + "login_name": "root" if cloud else None, + "auth_mode": current_credential["auth_mode"] if current_credential else "unknown", + "password_available": bool(current_credential and + current_credential["auth_mode"] == "password"), + } def save_job(kind: str, job_id: str, job: dict) -> None: if data_store is not None: @@ -857,13 +925,31 @@ def create_app( @app.get("/api/v1/vms") def list_vms(_session: Session = Depends(require_session)): profile = current_profile() - region = profile.get("region", "") - return {"items": [{**vm, "region": region} for vm in new_service(profile).list_vms()]} + vms = new_service(profile).list_vms() + records = (data_store.list("vm_credential") if data_store is not None + else test_credentials.copy()) + return {"items": [decorate_vm( + vm, parse_credential(records.get(credential_key(profile, vm["uuid"]))), profile, + ) for vm in vms]} @app.get("/api/v1/vms/{vm_id}") def get_vm(vm_id: str, _session: Session = Depends(require_session)): profile = current_profile() - return {**new_service(profile).get_vm(vm_id), "region": profile.get("region", "")} + vm = new_service(profile).get_vm(vm_id) + return decorate_vm(vm, get_credential(profile, vm["uuid"]), profile) + + @app.post("/api/v1/vms/{vm_id}/credential") + def reveal_vm_credential(vm_id: str, _session: Session = Depends(require_write)): + profile = current_profile() + vm = new_service(profile).get_vm(vm_id) + credential = get_credential(profile, vm["uuid"]) + decorated = decorate_vm(vm, credential, profile) + LOG.info("vm credential viewed: uuid=%s admin=%s", vm["uuid"], _session.username) + return { + "login_name": decorated["login_name"], + "auth_mode": decorated["auth_mode"], + "password": credential["password"] if decorated["password_available"] else None, + } @app.get("/api/v1/vms/{vm_id}/metrics") def get_vm_metrics( @@ -908,11 +994,13 @@ def create_app( public_key = body.guest_ssh_public_key.strip() root_password = (body.root_password.get_secret_value() if body.root_password is not None else "") - if bool(public_key) == bool(root_password): + if public_key and root_password: raise HTTPException( status_code=422, - detail="虚拟机 SSH 公钥和初始 root 密码必须且只能填写一项", + detail="虚拟机 SSH 公钥和初始 root 密码只能填写一项", ) + if not public_key and not root_password: + root_password = secrets.token_urlsafe(24) password_hash = None if root_password: try: @@ -925,17 +1013,44 @@ def create_app( spec["guest_ssh_public_key"] = public_key if password_hash is not None: spec["root_password_hash"] = password_hash - vm = new_service(profile).create_cloud_vm(spec, record["volume_name"]) + requested_uuid = str(uuid.uuid4()) + spec["vm_uuid"] = requested_uuid + save_credential(profile, requested_uuid, + "ssh_key" if public_key else "password", + f"panel-seed-{requested_uuid}.iso", + root_password or None) + try: + vm = new_service(profile).create_cloud_vm(spec, record["volume_name"]) + except Exception as exc: + # An incomplete libvirt rollback may have left the guest + # behind. Keep its credential in that exceptional case so + # the operator can still recover access if it exists. + rollback_incomplete = (isinstance(exc, VMError) + and "回滚不完整" in str(exc)) + if not rollback_incomplete: + try: + delete_credential(profile, requested_uuid) + except DatabaseError: + LOG.exception("Could not remove unused VM credential for %s", requested_uuid) + raise + if vm.get("uuid") != requested_uuid: + # A mismatched UUID would bind a root password to the + # wrong guest; do not silently claim the credential works. + LOG.error("Created VM UUID does not match requested UUID: %s", requested_uuid) + raise VMError("虚拟机已创建,但凭据绑定异常;请检查宿主机后再操作", 502) else: vm = new_service(profile).create_vm(body.model_dump(exclude={"source"})) LOG.info("vm created: uuid=%s admin=%s", vm.get("uuid"), _session.username) - return {**vm, "region": profile.get("region", "")} + credential = get_credential(profile, vm["uuid"]) if isinstance(body, CreateCloudBody) else None + return decorate_vm(vm, credential, profile) def run_reinstall( job_id: str, profile: dict, scope: str, vm_id: str, template_volume_name: str, template_name: str | None, ssh_public_key: str, root_password_hash: str | None, generated_password: str | None, + credential_password: str | None, ) -> None: + vm_reinstalled = False def report_progress(phase: str) -> None: if not isinstance(phase, str): return @@ -957,6 +1072,11 @@ def create_app( root_password_hash=root_password_hash, progress=report_progress, ) + vm_reinstalled = True + save_credential(profile, vm_id, + "ssh_key" if ssh_public_key else "password", + result["credential_generation"], + credential_password) with reinstall_lock: job = reinstall_jobs[job_id] job["status"] = "succeeded" @@ -977,11 +1097,22 @@ def create_app( error = "重装系统失败,请查看面板日志" with reinstall_lock: job = reinstall_jobs[job_id] - job["status"] = "failed" - job["phase"] = "重装失败" - job["error"] = error - save_job("reinstall_job", job_id, job) - LOG.warning("vm reinstall failed: job=%s uuid=%s", job_id, vm_id) + if vm_reinstalled: + job["status"] = "succeeded" + job["phase"] = "重装已完成,但凭据或任务记录保存失败" + job["warning"] = "新系统已启动,但面板无法确认初始密码已保存;请立即保存结果页显示的密码并检查数据库" + if generated_password is not None: + job["generated_password"] = generated_password + else: + job["status"] = "failed" + job["phase"] = "重装失败" + job["error"] = error + try: + save_job("reinstall_job", job_id, job) + except DatabaseError: + LOG.exception("Could not persist reinstall status: job=%s", job_id) + if not vm_reinstalled: + LOG.warning("vm reinstall failed: job=%s uuid=%s", job_id, vm_id) finally: with reinstall_lock: pending_reinstalls.discard((scope, vm_id)) @@ -1041,7 +1172,7 @@ def create_app( reinstall_executor.submit( run_reinstall, job_id, profile, scope, normalized_id, record["volume_name"], record.get("name"), ssh_public_key, root_password_hash, - generated_password, + generated_password, supplied_password or None, ) except RuntimeError as exc: pending_reinstalls.discard(key) @@ -1112,6 +1243,11 @@ def create_app( if (template_scope(profile), normalized_id) in pending_reinstalls: raise VMError("虚拟机正在重装系统,暂时不能删除", 409) result = new_service(profile).delete_vm(vm_id, delete_disks) + try: + delete_credential(profile, result["uuid"]) + except DatabaseError: + LOG.exception("Could not remove credential for deleted VM %s", result["uuid"]) + result = {**result, "warning": "虚拟机已删除,但数据库中的登录凭据未能清理;请检查数据库状态"} LOG.info( "vm deleted: uuid=%s delete_disks=%s admin=%s", result.get("uuid"), delete_disks, _session.username, diff --git a/virsh_panel/libvirt_service.py b/virsh_panel/libvirt_service.py index 79228152..9a4e617c 100644 --- a/virsh_panel/libvirt_service.py +++ b/virsh_panel/libvirt_service.py @@ -253,8 +253,8 @@ class VMService: raise VMError("宿主机返回的虚拟机配置 XML 无效", 502) from exc @staticmethod - def _disk_rows(root: ET.Element) -> list[dict[str, str]]: - rows: list[dict[str, str]] = [] + def _disk_rows(root: ET.Element) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] for disk in root.findall("./devices/disk"): if disk.get("device") != "disk": continue @@ -295,6 +295,19 @@ class VMService: def _vm_dict(self, domain: Any) -> dict[str, Any]: info = domain.info() root = self._vm_xml(domain) + disks = self._disk_rows(root) + for disk in disks: + identifier = disk["target"] or disk["source"] + if not identifier: + continue + try: + capacity, _allocation, _physical = domain.blockInfo(identifier, 0) + except libvirt.libvirtError: + # The domain remains manageable when an external storage + # backend cannot report its capacity (for example, RBD). + continue + if isinstance(capacity, int) and capacity > 0: + disk["capacity_gib"] = round(capacity / GIB, 2) managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") os_source = managed.get("os-source") if managed is not None else None if os_source not in {"cloud_template", "iso"}: @@ -309,10 +322,11 @@ class VMService: "state": STATES.get(info[0], "unknown"), "vcpu": info[3], "memory_mib": info[1] // 1024, - "disks": self._disk_rows(root), + "disks": disks, "autostart": autostart, "managed": managed is not None, "public_ip_cidr": managed.get("public-ip-cidr") if managed is not None else None, + "credential_generation": managed.get("seed-volume") if os_source == "cloud_template" else None, "os_name": managed.get("os-name") if os_source == "cloud_template" else None, "os_source": os_source, "install_iso": managed.get("install-iso") if os_source == "iso" else None, @@ -715,8 +729,8 @@ class VMService: raise VMError("无法生成面板元数据", 500) managed.set("seed-volume", seed_name) managed.set("public-ip-cidr", public_ip_cidr) + managed.set("os-source", "cloud_template") if spec.get("os_name") is not None: - managed.set("os-source", "cloud_template") managed.set("os-name", spec["os_name"]) return ET.tostring(root, encoding="unicode") @@ -724,6 +738,12 @@ class VMService: """Clone a trusted cloud image and supply static public networking.""" validated = self._validate_common_create(spec) validated["os_name"] = self._validated_os_name(spec.get("os_name")) + requested_uuid = spec.get("vm_uuid") + if requested_uuid is not None: + try: + requested_uuid = str(uuidlib.UUID(requested_uuid)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效") from exc if self.bridge_name is None: raise VMError("公网模板创建需要先在宿主机设置 Linux 网桥,例如 bridge:br0", 409) if not TEMPLATE_VOLUME_RE.fullmatch(template_volume_name): @@ -762,7 +782,7 @@ class VMService: raise VMError("虚拟磁盘不能小于云镜像模板的原始容量", 409) if target_capacity > pool.info()[3]: raise VMError("存储池剩余空间不足", 409) - vm_uuid = str(uuidlib.uuid4()) + vm_uuid = requested_uuid or str(uuidlib.uuid4()) disk_name = f"{validated['name']}.qcow2" seed_name = f"panel-seed-{vm_uuid}.iso" if disk_name in pool.listVolumes() or seed_name in pool.listVolumes(): @@ -980,8 +1000,8 @@ class VMService: new_managed.attrib.pop("os-source", None) new_managed.attrib.pop("os-name", None) new_managed.attrib.pop("install-iso", None) + new_managed.set("os-source", "cloud_template") if os_name is not None: - new_managed.set("os-source", "cloud_template") new_managed.set("os-name", os_name) phase("starting") new_domain = conn.defineXML(ET.tostring(new_root, encoding="unicode")) @@ -1064,7 +1084,7 @@ class VMService: vm_state = {"uuid": vm_id, "name": inactive_root.findtext("name") or vm_id, "state": "running"} warnings.append("新系统已启动,但面板未能读取完整虚拟机状态,请检查宿主机") - result: dict[str, Any] = {"vm": vm_state} + result: dict[str, Any] = {"vm": vm_state, "credential_generation": seed_name} if warnings: result["warning"] = ";".join(warnings) phase("completed")