From 4a28c6d043e6271528ddc562b44cd7955d699db8 Mon Sep 17 00:00:00 2001 From: admin Date: Sat, 26 Sep 2026 16:13:55 +0800 Subject: [PATCH] Add staged rescue ISO boot and confirmed force restart --- README.md | 8 +- static/app.js | 606 ++++++++++++++++++++++++++- static/index.html | 39 +- static/styles.css | 15 + tests/test_app.py | 301 +++++++++++++- tests/test_frontend_page_layout.py | 80 ++++ tests/test_libvirt_service.py | 421 ++++++++++++++++++- tests/test_rescue_templates.py | 63 +++ virsh_panel/app.py | 631 ++++++++++++++++++++++++++++- virsh_panel/libvirt_service.py | 546 +++++++++++++++++++++++++ virsh_panel/rescue_templates.py | 142 +++++++ 11 files changed, 2814 insertions(+), 38 deletions(-) create mode 100644 tests/test_rescue_templates.py create mode 100644 virsh_panel/rescue_templates.py diff --git a/README.md b/README.md index 983e8df8..6fd59908 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,12 @@ SELECT id, username, email FROM users WHERE id = 1; 面板创建的公网云镜像 VM 在详情页有“重装”按钮。点击后选择当前宿主机已导入的云镜像模板,输入 VM 名称确认;可在卡片中选择自己保存的 SSH 公钥,并同时设置初始 root 密码。手动密码须为 12–128 个字符并包含大写字母、小写字母及符号;只选公钥而不填写密码时保持仅公钥登录,两者都留空时自动生成强密码。设置或生成的初始密码会在成功重装后加密保存至 MariaDB,并可在虚拟机详情页按需查看或复制。自动生成的密码仍会在任务成功后显示,管理员点击“已保存密码,完成”只会从**任务记录**中清除密码,不影响详情页保存的初始密码。同一浏览器标签页刷新或面板进程重启后仍可按任务编号查询,直到确认保存密码为止。重装自动读取原配置盘中的公网 IP/CIDR、网关、DNS 和 MAC,不要求再次手填网络。运行中的 VM 会先收到正常关机请求;120 秒内未关机则中止,不会强制断电,也不会切换或删除旧系统盘。面板会将所选模板克隆到新系统盘,生成新的 cloud-init 配置盘并启动 VM;新系统尚未启动时切换失败会恢复原定义,旧盘保留。如果启动调用结果不确定但发现新盘已在运行,则保留新旧两份磁盘并提示人工核查。**libvirt 报告新 VM 已启动后,面板会自动删除旧系统盘与旧配置盘;这并不能证明客体系统、网络或 SSH 已工作,旧数据一旦删除不可恢复。** 若旧盘清理失败,任务仍返回成功但附带警告,需在宿主机核查残留卷。此功能仅支持面板创建且配置未被外部修改的公网云镜像 VM,不支持 ISO 安装 VM、快照或多网卡/多磁盘 VM。 +## 紧急救援 ISO + +管理员从侧栏“救援模版”选择本地可启动的 ISO 并命名上传;面板将文件暂存于私有 `data/` 目录、验证 ISO 9660/El Torito 启动记录,再经现有 libvirt SSH 连接导入当前宿主机的 ISO 池。此验证不保证 ISO 包含适用于目标 VM 的 UEFI/BIOS 启动项,也不保证救援系统能正常运行;切换后须用 VNC 核实。当前只支持 1 MiB–8 GiB 的 ISO,不支持 qcow2/raw 救援系统盘。ISO 文件保存在宿主机,模版元数据和恢复所需的虚拟机原始 XML 加密保存在 MariaDB;面板完成上传后会清理临时文件。若上传在面板进程被强制终止时中断,检查 `data/.rescue-upload-*` 临时文件和宿主机 `panel-rescue-*.iso` 卷,再决定是否清理。反向代理也必须允许相应请求体大小与上传时间,面板服务器暂存盘须有足够空间。 + +已审核的虚拟机所有者或管理员可在虚拟机详情页点“紧急救援”,选择已上传的 ISO 并输入虚拟机名称确认。面板**先预挂载救援 ISO,保存为下次完整开机的启动配置**,再请求运行中的 VM 正常关机(最多等待 120 秒)并从救援 ISO 冷启动;停机 VM 会直接从该 ISO 开机。若正常关机请求失败或超时,预挂载仍保留,救援页会明确显示“已预挂载”,并提供需再次确认的“强制重启进入救援”按钮:它会强制断电再冷启动,可能丢失未保存的数据。面板**不会自动强制断电**。也可在详情页手动“强制断电”后“开机”;普通“强制重置”只重置原 QEMU 进程,不能可靠读取新保存的启动配置。救援 ISO 仅在卸载或取消救援后才会从启动配置移除。取消尚未启动的救援时,若原系统仍在运行则不会打断它;退出已启动的救援时,面板会正常关机、恢复原始启动配置并从系统盘开机。面板添加独立救援光驱,保留原系统盘、cloud-init 配置盘及原始启动 XML。救援期间不允许重装、删除或执行一般电源操作;VNC 控制台仍可使用。救援 ISO 内的用户名、密码与网络行为由 ISO 自身决定,面板不会把原 VM 的 root 密码或 SSH 公钥注入救援系统。任务成功仅表示 libvirt 报告虚拟机已启动,不保证救援系统或原系统已正常登录;应通过 VNC 核对。建议在救援前备份重要数据;面板不会修改原系统盘,但救援系统中的人工操作仍可修改或删除它。 + ## 网页一键更新 网页的“网站更新”页固定从 `https://g.luoli.live/root/virt.git` 的 `main` 分支读取更新。访问令牌请使用有此私有仓库**读取权限**的 Gitea `root` 账号令牌;网页保存后不会回显,令牌加密保存在 MariaDB,也不会写入 Git URL。面板会拒绝压缩包部署、分支不符、origin 不符、未提交/未跟踪改动以及不能快进的版本;Git 的 [`--ff-only`](https://git-scm.com/docs/git-merge#Documentation/git-merge.txt---ff-only) 会在提交历史分叉时拒绝覆盖本地代码。 @@ -120,4 +126,4 @@ systemctl enable --now virsh-panel.service 独立的 `virsh-panel-update.service` 会先拉取私有仓库并安装目标版本 Python 依赖,再以快进方式切换代码、重启主面板并检查本机 HTTP 与数据库健康状态。更新任务绑定点击“检查更新”时看到的两个提交编号;若本地或远端版本变化,任务会拒绝切换并要求重新检查。更新任务状态加密存于 MariaDB,页面中断后可继续查询;独立服务异常退出或超时会尝试将未完成任务标为失败。更新前请备份 **MariaDB 数据和 `data/master.key`、`data/database-config.json`**;更新失败时不要重复点按钮,应先看 `journalctl -u virsh-panel-update.service -n 100`。依赖在代码切换前安装到当前 `.venv`,因此若依赖安装成功而代码切换失败,可能需要人工检查依赖版本。更新服务会保留更新前的 Git 回滚引用,但不会自动执行覆盖性的回滚。网页更新不负责安装系统 RPM、替换 `/etc/systemd/system` 中已安装的 unit 或修改反向代理配置;这些变化如后续版本需要,仍需人工处理。由于在线更新会运行私有仓库中的代码与依赖,必须保护 Gitea 仓库写入权限和访问令牌。 -功能范围:邮箱验证注册、管理员审核及按虚拟机归属隔离用户,虚拟机列表和详情页四项性能走势图、从 ISO 创建、由管理员导入并重命名 AlmaLinux 9/10 云镜像模板、使用已导入模板配置公网静态 IP 创建、云镜像重装、开机、关机、重启、强制断电/重置、删除和浏览器 VNC。当前仍是单宿主机版本;不提供 ISO 上传、目录自动创建、虚拟网络创建、内网 IP 模板或异网段网关。真实 AlmaLinux 10 宿主机、SMTP 服务及 MariaDB 仍需现场联调。 +功能范围:邮箱验证注册、管理员审核及按虚拟机归属隔离用户,虚拟机列表和详情页四项性能走势图、从 ISO 创建、由管理员导入并重命名 AlmaLinux 9/10 云镜像模板、使用已导入模板配置公网静态 IP 创建、云镜像重装、管理员上传救援 ISO 和虚拟机紧急救援、开机、关机、重启、强制断电/重置、删除和浏览器 VNC。当前仍是单宿主机版本;不提供普通安装 ISO 上传、目录自动创建、虚拟网络创建、内网 IP 模板或异网段网关。真实 AlmaLinux 10 宿主机、SMTP 服务及 MariaDB 仍需现场联调。 diff --git a/static/app.js b/static/app.js index a6214167..5a9ff9d0 100644 --- a/static/app.js +++ b/static/app.js @@ -1,5 +1,8 @@ const byId = (id) => document.getElementById(id); const REINSTALL_JOB_STORAGE_PREFIX = "virsh-panel:reinstall-job:"; +const RESCUE_UPLOAD_MAX_BYTES = 8 * 1024 * 1024 * 1024; +const RESCUE_IMPORT_STORAGE_PREFIX = "virsh-panel:rescue-import:"; +const RESCUE_JOB_STORAGE_PREFIX = "virsh-panel:rescue-job:"; const UPDATE_REPOSITORY_URL = "https://g.luoli.live/root/virt.git"; const UPDATE_BRANCH = "main"; @@ -31,6 +34,18 @@ const state = { templateLoad: null, templates: [], templateImportJobId: null, + rescueTemplates: [], + rescueTarget: null, + rescueActive: false, + rescueStaged: false, + rescuePowerState: "unknown", + rescueCanExit: false, + rescueJobId: null, + rescuePollToken: 0, + rescueInProgress: false, + rescueUploading: false, + rescueImportJobId: null, + rescueUploadPollToken: 0, loadingVMs: false, pollTimer: null, activeModal: null, @@ -134,7 +149,8 @@ function errorMessage(payload, fallback) { async function api(path, options = {}) { const method = options.method || "GET"; const headers = { Accept: "application/json" }; - if (options.body !== undefined) headers["Content-Type"] = "application/json"; + if (options.rawBody !== undefined) headers["Content-Type"] = options.contentType || "application/octet-stream"; + else if (options.body !== undefined) headers["Content-Type"] = "application/json"; if (((method !== "GET" && method !== "HEAD" && options.csrf !== false) || options.csrf === true) && state.csrfToken) { headers["X-CSRF-Token"] = state.csrfToken; } @@ -147,7 +163,8 @@ async function api(path, options = {}) { credentials: "same-origin", cache: "no-store", signal: options.signal, - body: options.body === undefined ? undefined : JSON.stringify(options.body), + body: options.rawBody !== undefined ? options.rawBody + : options.body === undefined ? undefined : JSON.stringify(options.body), }); } catch (error) { if (options.signal?.aborted) throw error; @@ -202,6 +219,10 @@ function clearAdminContent() { showError("pending-users-error", ""); text("host-fingerprint", ""); text("current-username", "用户"); + byId("rescue-template-upload-form").reset(); + byId("rescue-template-list").replaceChildren(); + showError("rescue-template-upload-error", ""); + showError("rescue-template-list-error", ""); } function showLogin() { @@ -231,6 +252,18 @@ function showLogin() { state.templateLoad = null; state.templates = []; state.templateImportJobId = null; + state.rescueTemplates = []; + state.rescueTarget = null; + state.rescueActive = false; + state.rescueStaged = false; + state.rescuePowerState = "unknown"; + state.rescueCanExit = false; + state.rescueJobId = null; + state.rescuePollToken += 1; + state.rescueInProgress = false; + state.rescueUploading = false; + state.rescueImportJobId = null; + state.rescueUploadPollToken += 1; state.selectedVmId = null; clearAdminContent(); renderVMs(); @@ -457,6 +490,7 @@ async function showDashboard(session) { function applySession(session) { state.sessionEpoch += 1; state.templates = []; + state.rescueTemplates = []; state.sshKeys = []; state.sshKeysLoad = null; fillSshKeyCards([]); @@ -471,7 +505,7 @@ function applySession(session) { state.hostReady = session.host_ready === true; fillTemplateViews([]); if (!state.admin) clearAdminContent(); - for (const id of ["template-settings-button", "template-settings-mobile-button", "host-settings-button", "host-settings-mobile-button", "update-settings-button", "update-settings-mobile-button", "smtp-settings-button", "smtp-settings-mobile-button", "host-update-button", "unlock-update-button", "unlock-settings-button"]) { + for (const id of ["template-settings-button", "template-settings-mobile-button", "rescue-templates-button", "rescue-templates-mobile-button", "host-settings-button", "host-settings-mobile-button", "update-settings-button", "update-settings-mobile-button", "smtp-settings-button", "smtp-settings-mobile-button", "host-update-button", "unlock-update-button", "unlock-settings-button"]) { byId(id).hidden = !state.admin; } byId("admin-menu").hidden = false; @@ -553,6 +587,18 @@ function canLeaveReinstallPage() { function discardVmSubpageDrafts() { if (!byId("create-view").hidden) resetCreatePage(); if (!byId("reinstall-view").hidden) resetReinstallPage(); + if (!byId("rescue-view").hidden) { + byId("rescue-form").reset(); + byId("rescue-template-id").value = ""; + state.rescueTarget = null; + state.rescueActive = false; + state.rescueStaged = false; + state.rescuePowerState = "unknown"; + state.rescueCanExit = false; + state.rescueInProgress = false; + showError("rescue-error", ""); + state.rescuePollToken += 1; + } state.sshKeysReturnView = null; } @@ -563,9 +609,10 @@ function showVmSubpage(view) { byId("vm-detail-view").hidden = true; byId("create-view").hidden = view !== "create"; byId("reinstall-view").hidden = view !== "reinstall"; - text("breadcrumb-current", view === "create" ? "创建虚拟机" : "重装系统"); + byId("rescue-view").hidden = view !== "rescue"; + text("breadcrumb-current", view === "create" ? "创建虚拟机" : view === "reinstall" ? "重装系统" : "紧急救援"); window.scrollTo({ top: 0, behavior: "auto" }); - byId(view === "create" ? "create-title" : "reinstall-title").focus(); + byId(view === "create" ? "create-title" : view === "reinstall" ? "reinstall-title" : "rescue-title").focus(); } function showVmWorkspace({ preserveDraft = false } = {}) { @@ -584,8 +631,10 @@ function showVmWorkspace({ preserveDraft = false } = {}) { byId("vm-detail-view").hidden = true; byId("create-view").hidden = true; byId("reinstall-view").hidden = true; + byId("rescue-view").hidden = true; byId("ssh-keys-workspace").hidden = true; byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; byId("update-workspace").hidden = true; byId("smtp-workspace").hidden = true; byId("smtp-password").value = ""; @@ -595,6 +644,8 @@ function showVmWorkspace({ preserveDraft = false } = {}) { byId("ssh-keys-button").removeAttribute("aria-current"); byId("template-settings-button").classList.remove("active"); byId("template-settings-button").removeAttribute("aria-current"); + byId("rescue-templates-button").classList.remove("active"); + byId("rescue-templates-button").removeAttribute("aria-current"); byId("update-settings-button").classList.remove("active"); byId("update-settings-button").removeAttribute("aria-current"); byId("smtp-settings-button").classList.remove("active"); @@ -626,11 +677,12 @@ async function showSshKeysWorkspace(returnView = null) { if (returnView !== "reinstall") state.selectedVmId = null; byId("vm-workspace").hidden = true; byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; byId("update-workspace").hidden = true; byId("smtp-workspace").hidden = true; byId("smtp-password").value = ""; byId("ssh-keys-workspace").hidden = false; - for (const id of ["vm-navigation-button", "template-settings-button", "update-settings-button", "smtp-settings-button"]) { + for (const id of ["vm-navigation-button", "template-settings-button", "rescue-templates-button", "update-settings-button", "smtp-settings-button"]) { byId(id).classList.remove("active"); byId(id).removeAttribute("aria-current"); } @@ -674,7 +726,8 @@ async function showTemplateWorkspace() { byId("smtp-workspace").hidden = true; byId("smtp-password").value = ""; byId("template-workspace").hidden = false; - for (const id of ["vm-navigation-button", "ssh-keys-button", "update-settings-button", "smtp-settings-button"]) { + byId("rescue-templates-workspace").hidden = true; + for (const id of ["vm-navigation-button", "ssh-keys-button", "rescue-templates-button", "update-settings-button", "smtp-settings-button"]) { byId(id).classList.remove("active"); byId(id).removeAttribute("aria-current"); } @@ -694,6 +747,193 @@ async function showTemplateWorkspace() { } } +function rescueImportStorageKey() { + return `${RESCUE_IMPORT_STORAGE_PREFIX}${state.username}`; +} + +function rescueJobStorageKey(uuid) { + return `${RESCUE_JOB_STORAGE_PREFIX}${state.username}:${uuid}`; +} + +function storedRescueJob(uuid) { + try { return sessionStorage.getItem(rescueJobStorageKey(uuid)) || ""; } catch { return ""; } +} + +function saveRescueJob(uuid, jobId) { + try { sessionStorage.setItem(rescueJobStorageKey(uuid), jobId); } catch { /* Status remains visible in this tab. */ } +} + +function formatRescueSize(bytes) { + const count = Number(bytes); + if (!Number.isFinite(count) || count < 0) return "大小未知"; + return count >= 1024 ** 3 ? `${(count / 1024 ** 3).toFixed(2)} GiB` : `${(count / 1024 ** 2).toFixed(1)} MiB`; +} + +function renderRescueTemplateCards() { + const cards = byId("rescue-template-cards"); + const selectedId = byId("rescue-template-id").value; + cards.replaceChildren(); + if (!state.rescueTemplates.length) { + cards.append(makeElement("p", "template-catalog-empty", state.admin + ? "还没有救援 ISO。请先在“救援模版”页面上传。" + : "还没有可用的救援 ISO,请联系管理员上传。")); + return; + } + for (const item of state.rescueTemplates) { + const id = String(item.id || ""); + if (!id) continue; + const card = makeElement("button", "rescue-template-card"); + card.type = "button"; + card.dataset.templateId = id; + card.setAttribute("aria-pressed", String(id === selectedId)); + card.append(makeElement("span", "rescue-template-symbol", "✚"), + makeElement("strong", "", item.name || id), + makeElement("small", "", `ISO · ${formatRescueSize(item.size_bytes)}`)); + card.addEventListener("click", () => { + byId("rescue-template-id").value = id; + cards.querySelectorAll(".rescue-template-card").forEach((option) => { + option.setAttribute("aria-pressed", String(option.dataset.templateId === id)); + }); + showError("rescue-error", ""); + }); + cards.append(card); + } +} + +function renderRescueTemplateList() { + const list = byId("rescue-template-list"); + list.replaceChildren(); + if (!state.admin) return; + if (!state.rescueTemplates.length) { + list.append(makeElement("p", "muted", "尚未上传救援 ISO。")); + return; + } + for (const item of state.rescueTemplates) { + const id = String(item.id || ""); + if (!id) continue; + const row = makeElement("div", "rescue-template-row"); + const label = makeElement("div", "rescue-template-row-label"); + label.append(makeElement("strong", "", item.name || id), + makeElement("small", "", `ISO · ${formatRescueSize(item.size_bytes)}`)); + const remove = makeElement("button", "button button-outline small", "删除"); + remove.type = "button"; + remove.setAttribute("aria-label", `删除救援模版 ${item.name || id}`); + remove.addEventListener("click", async () => { + if (!window.confirm(`确定删除救援模版“${item.name || id}”?正在使用的镜像不能删除。`)) return; + setButtonBusy(remove, true, "正在删除…"); + showError("rescue-template-list-error", ""); + try { + await api(`/api/v1/rescue-templates/${encodeURIComponent(id)}`, { method: "DELETE" }); + await loadRescueTemplates(); + toast("救援模版已删除。", "success"); + } catch (error) { + showError("rescue-template-list-error", error.message); + } finally { + if (remove.isConnected) setButtonBusy(remove, false); + } + }); + row.append(label, remove); + list.append(row); + } +} + +async function loadRescueTemplates() { + const epoch = state.sessionEpoch; + const result = await api("/api/v1/rescue-templates"); + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; + state.rescueTemplates = (Array.isArray(result?.templates) ? result.templates : []) + .filter((item) => item && (typeof item.id === "string" || Number.isSafeInteger(item.id))); + if (!state.rescueTemplates.some((item) => String(item.id) === byId("rescue-template-id").value)) { + byId("rescue-template-id").value = ""; + } + renderRescueTemplateCards(); + renderRescueTemplateList(); +} + +function showRescueImportStatus(message) { + const status = byId("rescue-template-upload-status"); + status.textContent = message; + status.hidden = !message; +} + +async function pollRescueImport(jobId, token) { + const button = byId("rescue-template-upload-button"); + for (let attempt = 0; attempt < 720 && token === state.rescueUploadPollToken; attempt += 1) { + try { + const job = await api(`/api/v1/rescue-templates/import-jobs/${encodeURIComponent(jobId)}`); + if (token !== state.rescueUploadPollToken) return; + if (job?.status === "completed") { + state.rescueImportJobId = null; + state.rescueUploading = false; + try { sessionStorage.removeItem(rescueImportStorageKey()); } catch { /* Ignore private browsing limits. */ } + showRescueImportStatus("救援 ISO 已上传并导入宿主机。"); + byId("rescue-template-upload-form").reset(); + setButtonBusy(button, false); + button.textContent = "上传并导入"; + await loadRescueTemplates(); + toast("救援模版导入成功。", "success"); + return; + } + if (job?.status === "failed") { + state.rescueImportJobId = null; + try { sessionStorage.removeItem(rescueImportStorageKey()); } catch { /* Ignore private browsing limits. */ } + throw new Error(job.error || "救援 ISO 导入失败,请检查宿主机空间与文件格式。"); + } + if (job?.status !== "queued" && job?.status !== "running") throw new Error("救援模版任务状态未知,请稍后重试查询。"); + showRescueImportStatus(job.phase || (job.status === "queued" ? "等待宿主机导入救援 ISO…" : "宿主机正在导入救援 ISO…")); + } catch (error) { + if (token !== state.rescueUploadPollToken) return; + state.rescueUploading = false; + showError("rescue-template-upload-error", error.message); + setButtonBusy(button, false); + button.textContent = state.rescueImportJobId ? "继续查询导入状态" : "上传并导入"; + return; + } + await new Promise((resolve) => window.setTimeout(resolve, 5000)); + } + if (token === state.rescueUploadPollToken) { + state.rescueUploading = false; + showRescueImportStatus("导入仍未确认完成。请刷新页面后返回“救援模版”查看任务状态,不要重复上传。"); + setButtonBusy(button, false); + button.textContent = "继续查询导入状态"; + } +} + +async function showRescueTemplatesWorkspace() { + if (!state.admin || !state.csrfToken || !canLeaveReinstallPage()) return; + discardVmSubpageDrafts(); + byId("admin-menu").open = false; + stopVmMetrics(); + clearVmCredential(); + state.selectedVmId = null; + for (const id of ["vm-workspace", "ssh-keys-workspace", "template-workspace", "update-workspace", "smtp-workspace"]) byId(id).hidden = true; + byId("rescue-templates-workspace").hidden = false; + for (const id of ["vm-navigation-button", "ssh-keys-button", "template-settings-button", "update-settings-button", "smtp-settings-button"]) { + byId(id).classList.remove("active"); + byId(id).removeAttribute("aria-current"); + } + byId("rescue-templates-button").classList.add("active"); + byId("rescue-templates-button").setAttribute("aria-current", "page"); + text("breadcrumb-current", "救援模版"); + showError("rescue-template-upload-error", ""); + showError("rescue-template-list-error", ""); + byId("rescue-template-list").replaceChildren(makeElement("p", "muted", "正在加载…")); + window.scrollTo({ top: 0, behavior: "auto" }); + try { await loadRescueTemplates(); } catch (error) { showError("rescue-template-list-error", error.message); } + if (!state.rescueUploading) { + let jobId = state.rescueImportJobId; + if (!jobId) { + try { jobId = sessionStorage.getItem(rescueImportStorageKey()) || ""; } catch { jobId = ""; } + } + if (jobId) { + state.rescueImportJobId = jobId; + state.rescueUploading = true; + setButtonBusy(byId("rescue-template-upload-button"), true, "正在导入…"); + void pollRescueImport(jobId, ++state.rescueUploadPollToken); + } + } +} + function selectedSshKeyId(containerId) { return byId(containerId).querySelector('.ssh-key-option[aria-pressed="true"]')?.dataset.keyId || ""; } @@ -847,6 +1087,7 @@ async function showUpdateWorkspace() { byId("vm-workspace").hidden = true; byId("ssh-keys-workspace").hidden = true; byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; byId("smtp-workspace").hidden = true; byId("smtp-password").value = ""; byId("update-workspace").hidden = false; @@ -856,6 +1097,8 @@ async function showUpdateWorkspace() { byId("ssh-keys-button").removeAttribute("aria-current"); byId("template-settings-button").classList.remove("active"); byId("template-settings-button").removeAttribute("aria-current"); + byId("rescue-templates-button").classList.remove("active"); + byId("rescue-templates-button").removeAttribute("aria-current"); byId("update-settings-button").classList.add("active"); byId("update-settings-button").setAttribute("aria-current", "page"); byId("smtp-settings-button").classList.remove("active"); @@ -943,6 +1186,7 @@ async function showSmtpWorkspace() { byId("vm-workspace").hidden = true; byId("ssh-keys-workspace").hidden = true; byId("template-workspace").hidden = true; + byId("rescue-templates-workspace").hidden = true; byId("update-workspace").hidden = true; byId("smtp-workspace").hidden = false; byId("vm-navigation-button").classList.remove("active"); @@ -951,6 +1195,8 @@ async function showSmtpWorkspace() { byId("ssh-keys-button").removeAttribute("aria-current"); byId("template-settings-button").classList.remove("active"); byId("template-settings-button").removeAttribute("aria-current"); + byId("rescue-templates-button").classList.remove("active"); + byId("rescue-templates-button").removeAttribute("aria-current"); byId("update-settings-button").classList.remove("active"); byId("update-settings-button").removeAttribute("aria-current"); byId("smtp-settings-button").classList.add("active"); @@ -1550,6 +1796,7 @@ function openVmDetail(uuid) { byId("vm-detail-view").hidden = false; byId("create-view").hidden = true; byId("reinstall-view").hidden = true; + byId("rescue-view").hidden = true; renderVmDetail(vm); clearVmMetrics("正在加载监控数据…"); startVmMetrics(); @@ -1573,6 +1820,10 @@ function renderVmDetail(vm) { const category = stateCategory(vm.state); const running = category === "running"; const stopped = category === "stopped"; + const shuttingDown = String(vm.state || "").toLowerCase().replace(/[_\s-]+/g, "") === "shutdown"; + const rescueMode = vm.rescue_mode === true; + const rescueStaged = vm.rescue_staged === true; + const rescueGuard = rescueMode || rescueStaged; const uuid = String(vm.uuid || ""); const busy = state.vmActionInFlight === uuid; const system = vmSystemInfo(vm); @@ -1607,26 +1858,33 @@ function renderVmDetail(vm) { 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" })); + primary.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget), { disabled: busy || rescueGuard, key: "shutdown", title: rescueGuard ? "请在紧急救援页面处理启动介质" : "正常关机" })); + primary.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget), { disabled: busy || rescueGuard, key: "reboot", title: rescueGuard ? "请在紧急救援页面处理启动介质" : "重启虚拟机" })); + danger.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { disabled: busy || (rescueMode && !rescueStaged), variant: "danger", key: "poweroff", title: rescueStaged ? "救援 ISO 已预挂载;强制断电后再点开机" : rescueMode ? "请先退出救援模式" : "强制断电" })); + danger.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { disabled: busy || rescueGuard, variant: "danger", key: "reset", title: rescueStaged ? "强制重置不保证读取新保存的救援启动配置" : rescueMode ? "请先退出救援模式" : "强制重置" })); + } else if (shuttingDown) { + danger.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { disabled: busy || (rescueMode && !rescueStaged), variant: "danger", key: "poweroff", title: rescueStaged ? "救援 ISO 已预挂载;强制断电后再点开机" : rescueMode ? "请先退出救援模式" : "关机中仍可手动强制断电" })); } else { - primary.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: busy || !stopped || !uuid, key: "start" })); + primary.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: busy || (rescueMode && !rescueStaged) || !stopped || !uuid, key: "start", title: rescueStaged ? "从已预挂载的救援 ISO 开机" : rescueMode ? "请先退出救援模式" : "启动虚拟机" })); } if (vm.managed && vm.public_ip_cidr) { danger.append(actionButton("重装系统", () => openReinstall(vm), { - disabled: busy || !uuid, + disabled: busy || rescueGuard || !uuid, variant: "danger", key: "reinstall", title: "从云镜像模板重装,成功后自动删除旧系统盘", })); } + danger.append(actionButton("紧急救援", () => void openRescue(vm), { + disabled: busy || !uuid, + key: "rescue", + title: rescueStaged ? "救援 ISO 已预挂载;查看状态或取消救援" : "预挂载救援 ISO;运行中虚拟机会先正常关机,再从救援环境启动", + })); danger.append(actionButton("删除虚拟机", () => openDelete(vm), { - disabled: busy || !stopped || !uuid, + disabled: busy || rescueGuard || !stopped || !uuid, variant: "danger", key: "delete", - title: stopped ? "删除虚拟机" : "请先关机再删除", + title: rescueGuard ? "请先退出救援模式" : stopped ? "删除虚拟机" : "请先关机再删除", })); if (focusedAction) { const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) @@ -2264,6 +2522,156 @@ function openDelete(vm) { state.deleteTarget = vm; } +function renderRescueState(result) { + state.rescueActive = result?.active === true; + state.rescueStaged = result?.staged === true; + state.rescuePowerState = String(result?.power_state || "unknown"); + state.rescueCanExit = result?.can_exit === true; + const templateName = String(result?.template_name || ""); + const rescueIsStopped = stateCategory(state.rescuePowerState) === "stopped"; + text("rescue-status", state.rescueActive + ? `已按救援配置开机${templateName ? ` · ${templateName}` : ""}。请通过 VNC 确认实际进入救援系统;退出救援后将从原系统盘启动。` + : state.rescueStaged + ? `救援 ISO 已预挂载${templateName ? ` · ${templateName}` : ""}。${rescueIsStopped ? "虚拟机已关机,可点击“从救援 ISO 开机”。" : "正常关机未完成时,可确认风险后点击“强制重启进入救援”;也可在详情页手动“强制断电”再“开机”。"}普通“强制重置”不保证读取新启动配置。` + : "当前未处于救援模式。加载救援 ISO 不会删除原系统盘。" ); + const pending = state.rescueInProgress; + byId("rescue-submit").hidden = state.rescueActive || state.rescueStaged; + byId("rescue-force-start").hidden = !state.rescueStaged; + text("rescue-force-start", rescueIsStopped ? "从救援 ISO 开机" : "强制重启进入救援"); + byId("rescue-exit").hidden = !state.rescueActive && !state.rescueStaged; + text("rescue-exit", state.rescueStaged ? "取消救援并卸载 ISO" : "退出救援并重启原系统"); + byId("rescue-submit").disabled = pending; + byId("rescue-force-start").disabled = pending || !state.rescueCanExit; + byId("rescue-exit").disabled = pending || !state.rescueCanExit; + byId("rescue-template-cards").hidden = state.rescueActive || state.rescueStaged; + byId("rescue-template-label").hidden = state.rescueActive || state.rescueStaged; + byId("rescue-template-cards").querySelectorAll("button").forEach((button) => { button.disabled = pending; }); +} + +async function loadVmRescueState(uuid) { + const result = await api(`/api/v1/vms/${encodeURIComponent(uuid)}/rescue`); + if (state.rescueTarget?.uuid !== uuid || byId("rescue-view").hidden) return result; + renderRescueState(result); + if ((state.rescueActive || state.rescueStaged) && !state.rescueCanExit) { + showError("rescue-error", "救援配置缺少可用的原系统恢复记录;请联系管理员检查,面板不会盲目卸载。" ); + } + return result; +} + +async function pollVmRescueJob(jobId, uuid, token) { + for (let attempt = 0; attempt < 720 && token === state.rescuePollToken; attempt += 1) { + try { + const job = await api(`/api/v1/rescue-jobs/${encodeURIComponent(jobId)}`); + if (token !== state.rescuePollToken || state.rescueTarget?.uuid !== uuid) return; + if (job?.status === "completed") { + state.rescueInProgress = false; + state.rescueJobId = null; + try { sessionStorage.removeItem(rescueJobStorageKey(uuid)); } catch { /* Ignore private browsing limits. */ } + const warnings = []; + try { + await loadVmRescueState(uuid); + } catch (error) { + warnings.push(`救援任务已完成,但状态刷新失败:${error.message}。请刷新页面核对虚拟机。`); + } + if ((state.rescueActive || state.rescueStaged) && !state.rescueCanExit) warnings.push("缺少原系统恢复记录,请联系管理员检查,勿手动切换启动配置。" ); + if (job.pending_manual_restart === true) warnings.unshift("正常关机失败或超时,救援 ISO 已预挂载但尚未进入救援系统。可在本页确认风险后点“强制重启进入救援”(强制断电再冷启动,可能丢失未保存数据);也可返回详情页手动“强制断电”后点“开机”。不要使用普通“强制重置”。"); + if (typeof job.warning === "string" && job.warning.trim()) warnings.push(job.warning.trim()); + showError("rescue-error", warnings.join(";")); + void loadVMs(true); + toast(job.pending_manual_restart === true + ? "救援 ISO 已预挂载,但正常关机未完成;可在本页确认后强制重启进入救援。" + : warnings.length ? "救援任务已完成,但有警告;请查看页面提示与 VNC 控制台。" : "救援操作已完成,请检查虚拟机状态和控制台。", warnings.length ? "info" : "success"); + return; + } + if (job?.status === "failed") { + state.rescueInProgress = false; + const failureMessage = job.error || "救援任务失败。请检查虚拟机当前电源状态和宿主机日志;面板未强制断电。"; + const shutdownFailed = /正常关机超时|无法请求虚拟机正常关机/.test(failureMessage); + let current = null; + try { current = await loadVmRescueState(uuid); } catch { /* Keep the job ID until state can be verified. */ } + const hasRecoveryInstructions = /详情页手动“强制断电”|救援系统的 VNC 控制台手动关机/.test(failureMessage); + const recoveryAdvice = current?.staged === true && job.operation === "enter" + ? "救援 ISO 已预挂载,但正常关机未完成。可在本页确认风险后点击“强制重启进入救援”;也可返回详情页手动“强制断电”(可能丢失未保存数据),确认“已关机”后点“开机”。不要使用普通“强制重置”:它不保证读取新启动配置。面板不会自动强制断电。" + : hasRecoveryInstructions ? "" : shutdownFailed && job.operation === "enter" + ? "尚未确认救援 ISO 已预挂载,请先核查救援状态;不要直接强制重启。预挂载成功后,才能通过“强制断电”再“开机”进入救援。" + : shutdownFailed && job.operation === "exit" + ? "退出救援时正常关机未完成。详情页强制操作在救援模式下不可用;可通过救援系统的 VNC 控制台手动关机,待显示“已关机”后重试退出救援。面板不会自动强制断电。" + : "请核查虚拟机当前状态和救援失败原因;面板不会自动强制断电或重启。"; + const recoveryWarning = (current?.active || current?.staged) && !current?.can_exit + ? "缺少原系统恢复记录,请联系管理员检查。" : ""; + showError("rescue-error", [failureMessage, recoveryAdvice, recoveryWarning].filter(Boolean).join(";")); + if (current && (current.can_exit === true || (!current.active && !current.status))) { + state.rescueJobId = null; + try { sessionStorage.removeItem(rescueJobStorageKey(uuid)); } catch { /* Ignore private browsing limits. */ } + } + return; + } + if (job?.status !== "queued" && job?.status !== "running") throw new Error("救援任务状态未知,请稍后重新打开此页面查询。"); + state.rescueInProgress = true; + text("rescue-status", job.phase || (job.status === "queued" ? "救援任务排队中…" : "正在预挂载救援 ISO 并等待正常关机…")); + byId("rescue-submit").disabled = true; + byId("rescue-force-start").disabled = true; + byId("rescue-exit").disabled = true; + byId("rescue-template-cards").querySelectorAll("button").forEach((button) => { button.disabled = true; }); + } catch (error) { + if (token !== state.rescuePollToken) return; + state.rescueInProgress = false; + showError("rescue-error", `暂时无法查询救援任务:${error.message}。请勿重复提交,稍后重新打开页面查看状态。`); + return; + } + await new Promise((resolve) => window.setTimeout(resolve, 5000)); + } + if (token === state.rescuePollToken) { + showError("rescue-error", "尚未确认救援任务完成。请稍后重新打开页面查询,不要重复提交。"); + } +} + +async function openRescue(vm) { + const uuid = String(vm.uuid || ""); + if (!uuid) return; + state.rescuePollToken += 1; + state.rescueTarget = vm; + state.rescueActive = false; + state.rescueStaged = false; + state.rescuePowerState = "unknown"; + state.rescueCanExit = false; + state.rescueInProgress = false; + state.rescueJobId = null; + byId("rescue-form").reset(); + byId("rescue-template-id").value = ""; + text("rescue-subtitle", `${vm.name || uuid} · 选择救援 ISO 并确认切换启动。`); + text("rescue-confirm-hint", `请准确输入“${vm.name || ""}”。面板会先预挂载救援 ISO,再请求运行中的虚拟机正常关机并从救援 ISO 开机;停机虚拟机将直接从救援 ISO 开机。`); + byId("rescue-confirm-name").placeholder = vm.name || "请输入完整的虚拟机名称"; + text("rescue-status", "正在检查虚拟机状态…"); + byId("rescue-submit").disabled = true; + byId("rescue-force-start").disabled = true; + byId("rescue-exit").disabled = true; + showError("rescue-error", ""); + showVmSubpage("rescue"); + const [templates, current] = await Promise.allSettled([loadRescueTemplates(), loadVmRescueState(uuid)]); + if (state.rescueTarget?.uuid !== uuid || byId("rescue-view").hidden) return; + if (templates.status === "rejected") showError("rescue-error", `无法读取救援模版:${templates.reason.message}`); + if (current.status === "rejected") { + showError("rescue-error", `无法读取虚拟机救援状态:${current.reason.message}`); + text("rescue-status", "状态未知;为避免误操作,暂时不能提交救援。"); + return; + } + const rescueState = current.value; + const pendingJobId = storedRescueJob(uuid) || (["queued", "running"].includes(rescueState?.status) + ? String(rescueState.job_id || "") : ""); + if (pendingJobId) { + state.rescueJobId = pendingJobId; + state.rescueInProgress = true; + void pollVmRescueJob(pendingJobId, uuid, ++state.rescuePollToken); + } +} + +function leaveRescuePage() { + const uuid = String(state.rescueTarget?.uuid || ""); + if (!showVmWorkspace()) return; + if (uuid && state.vms.some((item) => String(item.uuid || "") === uuid)) openVmDetail(uuid); +} + function openReinstall(vm) { if (readSavedReinstallJob()) { resumeReinstallJob(); @@ -2438,7 +2846,9 @@ async function pollReinstallJob(jobId, token) { function openConfirm(vm, action) { const label = action === "poweroff" ? "强制断电" : "强制重置"; text("confirm-title", label); - text("confirm-message", `确定对 ${vm.name || vm.uuid} 执行“${label}”吗?这可能导致虚拟机内未保存的数据丢失。`); + text("confirm-message", action === "poweroff" && vm.rescue_staged === true + ? `救援 ISO 已预挂载。确定强制断电 ${vm.name || vm.uuid} 吗?这可能丢失未保存的数据。确认虚拟机已关机后,请回详情页点“开机”进入救援系统;不要使用“强制重置”。` + : `确定对 ${vm.name || vm.uuid} 执行“${label}”吗?这可能导致虚拟机内未保存的数据丢失。`); text("confirm-submit", label); showError("confirm-error", ""); openModal("confirm-modal"); @@ -2454,7 +2864,11 @@ async function runAction(vm, action, button) { 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"); + toast(vm.rescue_staged === true && action === "poweroff" + ? "已发送强制断电指令。确认状态为已关机后,请点“开机”进入救援系统。" + : vm.rescue_staged === true && action === "start" + ? "已发送开机指令,请通过 VNC 控制台确认已进入救援系统。" + : `已向 ${vm.name || vm.uuid} 发送${label}指令。`, "success"); await loadVMs(true); window.setTimeout(() => void loadVMs(true), 1200); return true; @@ -2756,6 +3170,8 @@ byId("ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspac byId("ssh-keys-mobile-button").addEventListener("click", () => void showSshKeysWorkspace()); byId("template-settings-button").addEventListener("click", () => void showTemplateWorkspace()); byId("template-settings-mobile-button").addEventListener("click", () => void showTemplateWorkspace()); +byId("rescue-templates-button").addEventListener("click", () => void showRescueTemplatesWorkspace()); +byId("rescue-templates-mobile-button").addEventListener("click", () => void showRescueTemplatesWorkspace()); byId("update-settings-button").addEventListener("click", () => void showUpdateWorkspace()); byId("update-settings-mobile-button").addEventListener("click", () => void showUpdateWorkspace()); byId("smtp-settings-button").addEventListener("click", () => void showSmtpWorkspace()); @@ -2763,6 +3179,7 @@ byId("smtp-settings-mobile-button").addEventListener("click", () => void showSmt byId("smtp-back-button").addEventListener("click", showVmWorkspace); byId("ssh-keys-back-button").addEventListener("click", returnFromSshKeysWorkspace); byId("template-back-button").addEventListener("click", showVmWorkspace); +byId("rescue-templates-back").addEventListener("click", showVmWorkspace); byId("update-back-button").addEventListener("click", leaveUpdateWorkspace); byId("unlock-settings-button").addEventListener("click", openHostSettings); byId("host-back-button").addEventListener("click", () => { @@ -3016,6 +3433,7 @@ byId("create-back").addEventListener("click", () => { }); byId("reinstall-back").addEventListener("click", leaveReinstallPage); byId("reinstall-cancel").addEventListener("click", leaveReinstallPage); +byId("rescue-back").addEventListener("click", leaveRescuePage); byId("ssh-key-file").addEventListener("change", async (event) => { const file = event.currentTarget.files?.[0]; if (!file) return; @@ -3124,6 +3542,160 @@ byId("template-import-form").addEventListener("submit", async (event) => { } }); +byId("rescue-template-upload-form").addEventListener("submit", async (event) => { + event.preventDefault(); + if (!state.admin || state.rescueUploading) return; + if (state.rescueImportJobId) { + state.rescueUploading = true; + setButtonBusy(byId("rescue-template-upload-button"), true, "正在查询导入…"); + void pollRescueImport(state.rescueImportJobId, ++state.rescueUploadPollToken); + return; + } + showError("rescue-template-upload-error", ""); + const name = byId("rescue-template-name").value.trim(); + const file = byId("rescue-template-file").files?.[0]; + if (!name || name.length > 64) { + showError("rescue-template-upload-error", "救援模版名称应为 1 至 64 个字符。"); + return; + } + if (!file || !/\.iso$/i.test(file.name) || file.size <= 0 || file.size > RESCUE_UPLOAD_MAX_BYTES) { + showError("rescue-template-upload-error", "请选择非空的 .iso 文件,且大小不能超过 8 GiB。"); + return; + } + const button = byId("rescue-template-upload-button"); + const epoch = state.sessionEpoch; + state.rescueUploading = true; + setButtonBusy(button, true, "正在上传 ISO…"); + showRescueImportStatus(`正在传输 ${formatRescueSize(file.size)} 的 ISO;请保持页面和网络连接。上传完成后宿主机会继续导入。`); + try { + const result = await api(`/api/v1/rescue-templates?name=${encodeURIComponent(name)}`, { + method: "POST", rawBody: file, contentType: "application/octet-stream", + }); + if (epoch !== state.sessionEpoch) return; + const jobId = String(result?.job_id || ""); + if (!jobId) throw new Error("上传结果没有任务编号。请先刷新模版列表确认结果,勿重复上传。"); + state.rescueImportJobId = jobId; + try { sessionStorage.setItem(rescueImportStorageKey(), jobId); } catch { /* Status remains visible in this tab. */ } + text("rescue-template-upload-button", "正在导入…"); + void pollRescueImport(jobId, ++state.rescueUploadPollToken); + } catch (error) { + state.rescueUploading = false; + showRescueImportStatus(""); + showError("rescue-template-upload-error", error.message); + setButtonBusy(button, false); + } +}); + +async function startRescueVmAction(exitMode) { + const vm = state.rescueTarget; + if (!vm || state.rescueInProgress) return; + const uuid = String(vm.uuid || ""); + const confirmationName = byId("rescue-confirm-name").value; + const templateId = byId("rescue-template-id").value; + showError("rescue-error", ""); + if (exitMode && ((!state.rescueActive && !state.rescueStaged) || !state.rescueCanExit)) { + showError("rescue-error", "当前无法安全退出救援模式,请刷新状态或联系管理员。"); + return; + } + if (!exitMode && (state.rescueActive || state.rescueStaged)) { + showError("rescue-error", "救援 ISO 已加载或预挂载,请先退出或取消救援。"); + return; + } + if (confirmationName !== vm.name) { + showError("rescue-error", "确认名称与虚拟机名称不一致,未执行救援操作。"); + byId("rescue-confirm-name").focus(); + return; + } + if (!exitMode && !state.rescueTemplates.some((item) => String(item.id) === templateId)) { + showError("rescue-error", "请选择当前可用的救援模版。"); + return; + } + const warning = exitMode + ? state.rescueStaged + ? `确认取消 ${vm.name} 的救援预挂载并卸载 ISO?面板会恢复原系统的启动配置。若原系统仍在运行,不会为取消预挂载而关机;若已关机,将从原系统盘启动。` + : `确认退出 ${vm.name} 的救援模式?运行中的虚拟机会正常关机,然后从原系统盘重启;服务将短暂中断。若正常关机超时,操作会停止且不会强制断电。救援模式下详情页强制操作不可用;可通过救援系统的 VNC 控制台手动关机,待显示“已关机”后重试退出救援。` + : `确认让 ${vm.name} 加载救援 ISO?面板会先预挂载 ISO 为下次完整开机的启动介质,再请求正常关机并开机。若正常关机失败或超时,但救援页显示“已预挂载”,可在本页确认风险后点“强制重启进入救援”;也可返回详情页手动“强制断电”再“开机”。“强制重置”不保证读取新保存的启动配置。面板不会自动强制断电。`; + if (!window.confirm(warning)) return; + const button = byId(exitMode ? "rescue-exit" : "rescue-submit"); + state.rescueInProgress = true; + setButtonBusy(button, true, "正在提交任务…"); + byId(exitMode ? "rescue-submit" : "rescue-exit").disabled = true; + byId("rescue-force-start").disabled = true; + const path = exitMode ? `/api/v1/vms/${encodeURIComponent(uuid)}/rescue/exit` + : `/api/v1/vms/${encodeURIComponent(uuid)}/rescue`; + const body = exitMode ? { confirmation_name: confirmationName } + : { template_id: templateId, confirmation_name: confirmationName }; + try { + const result = await api(path, { method: "POST", body }); + const jobId = String(result?.job_id || ""); + if (!jobId) throw new Error("面板未返回救援任务编号。请检查虚拟机状态,勿重复提交。"); + state.rescueJobId = jobId; + saveRescueJob(uuid, jobId); + text("rescue-status", "任务已提交,正在预挂载救援 ISO 并请求正常关机…"); + void pollVmRescueJob(jobId, uuid, ++state.rescuePollToken); + } catch (error) { + state.rescueInProgress = false; + showError("rescue-error", error.message); + void loadVmRescueState(uuid).catch(() => {}); + } finally { + setButtonBusy(button, false); + button.disabled = state.rescueInProgress; + } +} + +async function forceStartStagedRescue() { + const vm = state.rescueTarget; + if (!vm || state.rescueInProgress) return; + const uuid = String(vm.uuid || ""); + showError("rescue-error", ""); + if (!state.rescueStaged || !state.rescueCanExit) { + showError("rescue-error", "救援 ISO 尚未确认预挂载,不能强制启动;请先刷新救援状态。"); + return; + } + const confirmationName = byId("rescue-confirm-name").value; + if (confirmationName !== vm.name) { + showError("rescue-error", "确认名称与虚拟机名称不一致,未执行救援操作。"); + byId("rescue-confirm-name").focus(); + return; + } + const stopped = stateCategory(state.rescuePowerState) === "stopped"; + const warning = stopped + ? `确认让 ${vm.name} 从已预挂载的救援 ISO 开机?原系统盘不会删除,救援完成后需要退出救援才能恢复原系统启动。` + : `确认强制重启 ${vm.name} 进入救援?救援 ISO 已预挂载。面板将强制断电,再完整开机读取救援启动配置;强制断电可能导致未保存的数据丢失。此操作不是普通“强制重置”。`; + if (!window.confirm(warning)) return; + const button = byId("rescue-force-start"); + state.rescueInProgress = true; + setButtonBusy(button, true, stopped ? "正在启动救援…" : "正在强制重启…"); + byId("rescue-submit").disabled = true; + byId("rescue-exit").disabled = true; + try { + const result = await api(`/api/v1/vms/${encodeURIComponent(uuid)}/rescue/force-start`, { + method: "POST", + body: { confirmation_name: confirmationName, ack_data_loss: true }, + }); + const jobId = String(result?.job_id || ""); + if (!jobId) throw new Error("面板未返回救援任务编号。请检查虚拟机状态,勿重复提交。"); + state.rescueJobId = jobId; + saveRescueJob(uuid, jobId); + text("rescue-status", stopped ? "正在从预挂载的救援 ISO 开机…" : "正在强制断电并从救援 ISO 冷启动…"); + void pollVmRescueJob(jobId, uuid, ++state.rescuePollToken); + } catch (error) { + state.rescueInProgress = false; + showError("rescue-error", error.message); + void loadVmRescueState(uuid).catch(() => {}); + } finally { + setButtonBusy(button, false); + button.disabled = state.rescueInProgress; + } +} + +byId("rescue-form").addEventListener("submit", (event) => { + event.preventDefault(); + void startRescueVmAction(false); +}); +byId("rescue-force-start").addEventListener("click", () => void forceStartStagedRescue()); +byId("rescue-exit").addEventListener("click", () => void startRescueVmAction(true)); + function ipv4Parts(value) { if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(value)) return null; const segments = value.split("."); diff --git a/static/index.html b/static/index.html index bbe602b8..34a759ce 100644 --- a/static/index.html +++ b/static/index.html @@ -5,8 +5,8 @@ VirtPilot · 虚拟机管理 - - + +
@@ -231,6 +231,7 @@ + @@ -243,7 +244,7 @@
-
菜单
用户
+
菜单
用户
@@ -280,7 +281,7 @@

日常操作

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

-

维护与危险操作

强制操作可能丢失未保存的数据;重装或删除会清除数据。

+

维护与危险操作

救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。

PERFORMANCE HISTORY

性能监控

每分钟采样并自动刷新,历史数据最长保留 30 天;长时间范围会聚合,较长的采样缺口留空。

@@ -347,6 +348,23 @@
+ +