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"; const state = { csrfToken: "", sessionEpoch: 0, username: "", admin: false, approved: false, hostReady: false, vms: [], selectedVmId: null, credentialVmId: null, credentialPassword: "", credentialVisible: false, credentialBusy: false, credentialRequestToken: 0, credentialHideTimer: null, vmActionInFlight: null, metricsRange: "24h", metricsPollTimer: null, metricsRequest: null, metricsPayload: null, metricsResizeTimer: null, resources: null, sshKeys: [], sshKeysLoad: null, sshKeysReturnView: null, 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, lastFocus: null, deleteTarget: null, confirmTarget: null, reinstallTarget: null, reinstallJobId: null, reinstallInProgress: false, reinstallExpectGeneratedPassword: false, reinstallPasswordPendingAck: false, reinstallPollToken: 0, rfb: null, consoleToken: 0, hostConfig: null, scannedHost: null, uploadedPrivateKey: "", updateSettings: null, updateCheck: null, updateJobId: null, updateLastShownJobId: null, updatePollToken: 0, updateReturnView: null, }; 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", "未记录"); const reveal = byId("vm-detail-password-reveal"); reveal.hidden = true; reveal.setAttribute("aria-pressed", "false"); reveal.setAttribute("aria-label", "查看初始 root 密码"); reveal.title = "查看初始 root 密码"; 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; element.hidden = !message; } function resourceWarnings(payload) { if (Array.isArray(payload?.warnings)) return payload.warnings.filter((item) => typeof item === "string" && item.trim()); return typeof payload?.resource_warning === "string" && payload.resource_warning.trim() ? [payload.resource_warning] : []; } function showResourceWarning(message) { const element = byId("resource-warning"); element.textContent = message; element.hidden = !message; } function toast(message, kind = "info") { const item = document.createElement("div"); item.className = `toast ${kind}`; item.textContent = message; byId("toast-region").append(item); window.setTimeout(() => item.remove(), 5000); } function errorMessage(payload, fallback) { if (typeof payload?.error === "string") return payload.error; if (typeof payload?.message === "string") return payload.message; if (typeof payload?.detail === "string") return payload.detail; return fallback; } async function api(path, options = {}) { const method = options.method || "GET"; const headers = { Accept: "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; } let response; try { response = await fetch(path, { method, headers, credentials: "same-origin", cache: "no-store", signal: options.signal, body: options.rawBody !== undefined ? options.rawBody : options.body === undefined ? undefined : JSON.stringify(options.body), }); } catch (error) { if (options.signal?.aborted) throw error; throw new Error("无法连接面板服务,请检查网络或稍后重试。"); } let payload = null; if (response.status !== 204) { try { payload = await response.json(); } catch { /* A failed HTTP response may not be JSON. */ } } if (response.status === 401 && path !== "/api/v1/login" && path !== "/api/v1/session" && !path.startsWith("/api/v1/register") && !path.startsWith("/api/v1/setup/") && !path.startsWith("/api/v1/database/")) { showLogin(); throw new Error("登录已过期,请重新登录。"); } if (response.status === 423 && payload?.error_code === "key_locked" && path !== "/api/v1/host/unlock") { if (state.admin) { showUnlockView({ ...state.hostConfig, configured: true, key_locked: true }); throw new Error("宿主机私钥已锁定,请输入私钥口令解锁。"); } showAccessWait("host"); throw new Error("宿主机暂不可用,请联系管理员解锁私钥。"); } if (!state.admin && response.status === 409 && /宿主机/.test(errorMessage(payload, "")) && (path.startsWith("/api/v1/vms") || path === "/api/v1/resources")) { showAccessWait("host"); throw new Error("宿主机尚未就绪,请等待管理员完成配置。"); } if (!state.admin && response.status === 403 && /审核/.test(errorMessage(payload, ""))) { showAccessWait("approval"); throw new Error("账号正在等待管理员审核。"); } if (!response.ok) { const error = new Error(errorMessage(payload, `请求失败(HTTP ${response.status})`)); error.status = response.status; throw error; } return payload; } function stopPolling() { if (state.pollTimer) window.clearInterval(state.pollTimer); state.pollTimer = null; } function clearAdminContent() { for (const id of ["smtp-host", "smtp-username", "smtp-password", "smtp-from-address", "host-address", "host-region", "host-storage-pool", "host-iso-pool", "host-network", "host-public-pool-cidr", "host-public-gateway", "host-public-vm-prefix", "host-public-dns", "host-public-reserved"]) byId(id).value = ""; refreshPublicPoolPreview(); byId("smtp-port").value = 465; byId("smtp-tls-mode").value = "ssl"; byId("smtp-status").hidden = true; byId("pending-users-list").replaceChildren(); showError("smtp-error", ""); 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() { stopPolling(); stopVmMetrics(); closeModal(); resetCreatePage(); resetReinstallPage(); clearVmCredential(); state.updatePollToken += 1; state.updateJobId = null; state.updateLastShownJobId = null; state.updateCheck = null; state.updateSettings = null; state.updateReturnView = null; state.sessionEpoch += 1; state.csrfToken = ""; state.admin = false; state.approved = false; state.hostReady = false; state.vms = []; state.sshKeys = []; state.sshKeysLoad = null; state.sshKeysReturnView = null; state.resources = null; state.hostConfig = null; 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(); clearVmMetrics("登录后加载监控数据。"); fillSelect("vm-network", [], "network"); fillSelect("vm-iso", [], "iso"); fillTemplateViews([]); fillSshKeyCards([]); byId("ssh-keys-list").replaceChildren(); byId("ssh-key-form").reset(); showError("ssh-key-form-error", ""); showError("ssh-keys-list-error", ""); text("vm-detail-name", "虚拟机"); text("vm-detail-header-ip", "未获取"); text("vm-detail-header-region", "未设置"); text("vm-detail-header-created-at", "未记录"); clearHostPrivateKey(); byId("unlock-passphrase").value = ""; byId("update-access-token").value = ""; byId("smtp-password").value = ""; byId("admin-menu").open = false; byId("login-success").hidden = true; byId("register-code-status").hidden = true; byId("boot-screen").hidden = true; byId("database-view").hidden = true; byId("setup-view").hidden = true; byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; byId("login-view").hidden = false; byId("register-card").hidden = true; byId("login-card").hidden = false; byId("register-password").value = ""; byId("register-password-confirm").value = ""; byId("register-code").value = ""; } function showRegister() { showError("register-error", ""); showError("login-error", ""); byId("login-card").hidden = true; byId("register-card").hidden = false; byId("register-username").focus(); } function showAccessWait(kind) { stopPolling(); stopVmMetrics(); closeModal(); clearVmCredential(); const approval = kind === "approval"; text("wait-current-user", state.username || "用户"); text("wait-eyebrow", approval ? "ACCOUNT APPROVAL" : "HOST SETUP"); text("wait-title", approval ? "等待管理员审核" : "等待管理员配置宿主机"); text("wait-description", approval ? "邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机;现在可以先导入自己的公钥。" : "管理员尚未完成宿主机配置,暂时无法创建或管理虚拟机。现在可以先导入自己的公钥,稍后点击“刷新状态”。"); byId("boot-screen").hidden = true; for (const id of ["database-view", "setup-view", "login-view", "host-view", "unlock-view", "dashboard-view"]) byId(id).hidden = true; byId("access-wait-view").hidden = false; } function showDatabaseView() { stopPolling(); stopVmMetrics(); closeModal(); clearVmCredential(); byId("boot-screen").hidden = true; byId("setup-view").hidden = true; byId("login-view").hidden = true; byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; byId("database-view").hidden = false; } function showSetup() { stopPolling(); stopVmMetrics(); closeModal(); clearVmCredential(); byId("unlock-passphrase").value = ""; byId("boot-screen").hidden = true; byId("database-view").hidden = true; byId("login-view").hidden = true; byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; byId("setup-view").hidden = false; } function clearHostPrivateKey() { state.uploadedPrivateKey = ""; byId("host-private-key").value = ""; byId("host-private-key-file").value = ""; byId("host-private-key-passphrase").value = ""; text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。"); } function showUnlockView(hostConfig) { stopPolling(); stopVmMetrics(); closeModal(); clearVmCredential(); state.hostConfig = hostConfig; clearHostPrivateKey(); byId("unlock-passphrase").value = ""; showError("unlock-error", ""); text("unlock-current-user", state.username || "管理员"); text("unlock-host-label", hostConfig?.host ? `${hostConfig.host}:${hostConfig.port || 22}` : "当前宿主机"); byId("boot-screen").hidden = true; byId("database-view").hidden = true; byId("setup-view").hidden = true; byId("login-view").hidden = true; byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("dashboard-view").hidden = true; byId("unlock-view").hidden = false; } function resetFingerprint() { state.scannedHost = null; byId("host-fingerprint-result").hidden = true; byId("host-confirm-row").hidden = true; byId("host-fingerprint-confirm").checked = false; text("host-test-status", "主机地址或端口已变更,请重新扫描并核对指纹。"); byId("host-test-status").classList.remove("success", "warning"); } function markHostTestStale() { if (byId("host-test-status").classList.contains("success") || byId("host-test-status").classList.contains("warning")) { text("host-test-status", "配置已变更;保存时会重新测试连接。"); byId("host-test-status").classList.remove("success", "warning"); } } function showHostView(hostConfig = { configured: false }) { if (!state.admin) return; byId("admin-menu").open = false; stopPolling(); stopVmMetrics(); closeModal(); clearVmCredential(); state.hostConfig = hostConfig; clearHostPrivateKey(); byId("unlock-passphrase").value = ""; state.scannedHost = null; byId("host-fingerprint-result").hidden = true; byId("host-confirm-row").hidden = true; byId("host-fingerprint-confirm").checked = false; showError("host-error", ""); text("host-current-user", state.username || "管理员"); const configured = Boolean(hostConfig.configured); text("host-step-label", configured ? "HOST SETTINGS" : "管理员操作"); text("host-page-title", configured ? "宿主机设置" : "连接 libvirt 宿主机"); text("host-save-button", configured ? "保存修改" : "保存并进入面板"); byId("host-back-button").hidden = !configured; byId("host-address").value = configured ? (hostConfig.host || "") : ""; byId("host-port").value = configured ? (hostConfig.port || 22) : 22; byId("host-region").value = configured ? (hostConfig.region || "") : ""; byId("host-storage-pool").value = configured ? (hostConfig.storage_pool || "default") : "default"; byId("host-iso-pool").value = configured ? (hostConfig.iso_pool || "iso") : "iso"; byId("host-rescue-iso-pool").value = configured ? (hostConfig.rescue_iso_pool || "") : ""; byId("host-network").value = configured ? (hostConfig.default_network || "default") : "default"; byId("host-public-pool-cidr").value = configured ? (hostConfig.public_pool_cidr || "") : ""; refreshPublicPoolPreview(); byId("host-public-gateway").value = configured ? (hostConfig.public_gateway || "") : ""; byId("host-public-vm-prefix").value = configured && Number.isInteger(hostConfig.public_vm_prefix) ? String(hostConfig.public_vm_prefix) : ""; byId("host-public-dns").value = configured && Array.isArray(hostConfig.public_dns_servers) ? hostConfig.public_dns_servers.join(", ") : ""; byId("host-public-reserved").value = configured && Array.isArray(hostConfig.public_reserved_ips) ? hostConfig.public_reserved_ips.join("\n") : ""; text("host-key-required-mark", configured ? "" : "*"); text("host-key-hint", configured ? "留空则继续使用已保存的私钥;填写或选择文件会替换它。已保存私钥不会回显。" : "仅通过 HTTPS 传输并保存在面板服务器。请确保这把密钥已在宿主机 root 账号上获得授权。"); const passphraseSaved = Boolean(hostConfig.private_key_passphrase_saved); byId("host-private-key-passphrase").placeholder = passphraseSaved ? "留空继续使用已保存的口令" : "输入用于解锁私钥的口令"; text("host-passphrase-hint", passphraseSaved ? "口令已加密保存且不会回显;私钥不变时留空可沿用,更换私钥时请填写新口令。" : configured ? "当前没有保存私钥口令。如私钥需要口令,请在此输入并重新保存,供面板重启后自动连接和后台持续采样。" : "保存时会加密写入面板数据库,供重启后自动连接和后台持续采样;面板不会回显口令或写入浏览器存储。"); text("host-test-status", configured ? `当前已保存 ${hostConfig.host}:${hostConfig.port},修改前请重新扫描并核对主机指纹。` : "尚未测试连接"); byId("host-test-status").classList.remove("success", "warning"); byId("boot-screen").hidden = true; byId("database-view").hidden = true; byId("setup-view").hidden = true; byId("login-view").hidden = true; byId("access-wait-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; byId("host-view").hidden = false; } async function showDashboard(session) { if (!state.admin && !state.approved) { showAccessWait("approval"); return; } if (!state.admin && !state.hostReady) { showAccessWait("host"); return; } state.updateReturnView = null; state.csrfToken = session.csrf_token || ""; state.username = session.username || "用户"; text("current-username", state.username); byId("login-view").hidden = true; byId("access-wait-view").hidden = true; byId("database-view").hidden = true; byId("setup-view").hidden = true; byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("boot-screen").hidden = true; byId("dashboard-view").hidden = false; showVmWorkspace(); await Promise.allSettled([loadVMs(), loadResources()]); if (byId("dashboard-view").hidden) return; resumeReinstallJob(); stopPolling(); state.pollTimer = window.setInterval(() => { if (!document.hidden) void loadVMs(true); }, 15000); } function applySession(session) { state.sessionEpoch += 1; state.templates = []; state.rescueTemplates = []; state.sshKeys = []; state.sshKeysLoad = null; fillSshKeyCards([]); byId("ssh-keys-list").replaceChildren(); byId("ssh-key-form").reset(); showError("ssh-key-form-error", ""); showError("ssh-keys-list-error", ""); state.csrfToken = session.csrf_token || ""; state.username = session.username || "用户"; state.admin = session.admin === true; state.approved = session.approved === true; state.hostReady = session.host_ready === true; fillTemplateViews([]); if (!state.admin) clearAdminContent(); 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; byId("admin-menu").open = false; text("current-username", state.username); } async function continueAfterLogin(session) { applySession(session); if (!state.admin) { state.hostConfig = null; if (!state.approved) { showAccessWait("approval"); return; } if (!state.hostReady) { showAccessWait("host"); return; } await showDashboard(session); return; } const hostConfig = await api("/api/v1/host"); state.hostConfig = hostConfig || { configured: false }; if (hostConfig?.configured && hostConfig?.key_locked) showUnlockView(hostConfig); else if (hostConfig?.configured) await showDashboard(session); else showHostView(hostConfig || { configured: false }); } async function initialize() { try { const database = await api("/api/v1/database/status"); if (database?.setup_required) { showDatabaseView(); return; } const setup = await api("/api/v1/setup/status"); if (setup?.setup_required) { showSetup(); return; } const session = await api("/api/v1/session"); if (session?.authenticated) await continueAfterLogin(session); else showLogin(); } catch (error) { showLogin(); showError("login-error", error.message); } } function resetCreatePage() { byId("create-form").reset(); byId("vm-template").value = ""; renderTemplateCatalog("vm-template"); clearSshKeyPicker("vm-guest-ssh-key-cards"); byId("vm-root-password").value = ""; updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); showError("create-error", ""); } function resetReinstallPage() { state.reinstallPollToken += 1; state.reinstallTarget = null; state.reinstallJobId = null; state.reinstallInProgress = false; state.reinstallExpectGeneratedPassword = false; state.reinstallPasswordPendingAck = false; byId("reinstall-form").reset(); byId("reinstall-template").value = ""; renderTemplateCatalog("reinstall-template"); clearSshKeyPicker("reinstall-ssh-key-cards"); byId("reinstall-root-password").value = ""; updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); byId("reinstall-generated-password").textContent = ""; showError("reinstall-error", ""); } function canLeaveReinstallPage() { if (byId("dashboard-view").hidden || byId("vm-workspace").hidden || byId("reinstall-view").hidden) return true; if (state.reinstallPasswordPendingAck) { toast("请先保存 root 密码,再点击“已保存密码,完成”确认清除。", "error"); return false; } if (state.reinstallInProgress) { toast("重装正在进行,请保持此页面打开,以免错过一次性显示的 root 密码。", "error"); return false; } return true; } 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; } function showVmSubpage(view) { stopVmMetrics(); clearVmCredential(); byId("vm-list-view").hidden = true; byId("vm-detail-view").hidden = true; byId("create-view").hidden = view !== "create"; byId("reinstall-view").hidden = view !== "reinstall"; byId("rescue-view").hidden = view !== "rescue"; text("breadcrumb-current", view === "create" ? "创建虚拟机" : view === "reinstall" ? "重装系统" : "紧急救援"); window.scrollTo({ top: 0, behavior: "auto" }); byId(view === "create" ? "create-title" : view === "reinstall" ? "reinstall-title" : "rescue-title").focus(); } function showVmWorkspace({ preserveDraft = false } = {}) { if (!state.admin && (!state.approved || !state.hostReady)) { showAccessWait(state.approved ? "host" : "approval"); return false; } if (!canLeaveReinstallPage()) return false; byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); if (!preserveDraft) discardVmSubpageDrafts(); state.selectedVmId = null; byId("vm-workspace").hidden = false; byId("vm-list-view").hidden = 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 = ""; byId("vm-navigation-button").classList.add("active"); byId("vm-navigation-button").setAttribute("aria-current", "page"); byId("ssh-keys-button").classList.remove("active"); 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"); byId("smtp-settings-button").removeAttribute("aria-current"); text("breadcrumb-current", "虚拟机"); window.scrollTo({ top: 0, behavior: "auto" }); return true; } async function showSshKeysWorkspace(returnView = null) { if (!state.csrfToken) return; if (!canLeaveReinstallPage()) return; if (returnView === "create" || returnView === "reinstall") { const passwordId = returnView === "create" ? "vm-root-password" : "reinstall-root-password"; const hintId = returnView === "create" ? "vm-root-password-hint" : "reinstall-root-password-hint"; if (byId(passwordId).value) { byId(passwordId).value = ""; updateRootPasswordHint(passwordId, hintId); toast("已清空未提交的 root 密码;返回后请重新填写。", "info"); } } else discardVmSubpageDrafts(); state.sshKeysReturnView = returnView; byId("access-wait-view").hidden = true; byId("dashboard-view").hidden = false; byId("admin-menu").open = false; state.updateReturnView = null; stopVmMetrics(); clearVmCredential(); 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", "rescue-templates-button", "update-settings-button", "smtp-settings-button"]) { byId(id).classList.remove("active"); byId(id).removeAttribute("aria-current"); } byId("ssh-keys-button").classList.add("active"); byId("ssh-keys-button").setAttribute("aria-current", "page"); text("breadcrumb-current", "公钥管理"); showError("ssh-key-form-error", ""); showError("ssh-keys-list-error", ""); if (!state.sshKeys.length) byId("ssh-keys-list").replaceChildren(makeElement("p", "muted", "正在加载…")); try { await loadSshKeys(); } catch (error) { showError("ssh-keys-list-error", `无法读取公钥:${error.message}`); } } function returnFromSshKeysWorkspace() { const returnView = state.sshKeysReturnView; if (!returnView) { showVmWorkspace(); return; } state.sshKeysReturnView = null; if (!showVmWorkspace({ preserveDraft: true })) return; showVmSubpage(returnView); if (returnView === "create") updateCreateSource(); else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); } async function showTemplateWorkspace() { if (!state.admin || !state.csrfToken) return; if (!canLeaveReinstallPage()) return; discardVmSubpageDrafts(); byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); state.selectedVmId = null; byId("vm-workspace").hidden = true; byId("ssh-keys-workspace").hidden = true; byId("update-workspace").hidden = true; byId("smtp-workspace").hidden = true; byId("smtp-password").value = ""; byId("template-workspace").hidden = false; 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"); } byId("template-settings-button").classList.add("active"); byId("template-settings-button").setAttribute("aria-current", "page"); text("breadcrumb-current", "云镜像模板"); showError("template-import-error", ""); showError("template-list-error", ""); showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板;点击“导入模板”继续查询任务状态。" : ""); byId("template-admin-list").replaceChildren(makeElement("p", "muted", "正在加载…")); window.scrollTo({ top: 0, behavior: "auto" }); try { await loadTemplates(); } catch (error) { showError("template-list-error", `无法读取云镜像模板:${error.message}`); byId("template-admin-list").replaceChildren(); } } 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", "救援模版"); const rescueIsoPool = String(state.hostConfig?.rescue_iso_pool || "").trim(); text("rescue-directory-note", rescueIsoPool ? `救援 ISO 专用目录或存储池:${rescueIsoPool}。上传的镜像不会列入创建虚拟机的安装 ISO 选项。` : "尚未配置救援 ISO 专用目录。请先在“宿主机设置”填写已存在的救援目录并保存,然后再上传镜像。"); byId("rescue-directory-note").hidden = false; 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 || ""; } function clearSshKeyPicker(containerId) { byId(containerId).querySelectorAll(".ssh-key-option").forEach((option) => option.setAttribute("aria-pressed", "false")); } function renderSshKeyPicker(containerId, items) { const container = byId(containerId); const previous = selectedSshKeyId(containerId); const available = items.filter((item) => Number.isSafeInteger(Number(item?.id)) && Number(item.id) > 0); const selected = available.some((item) => String(item.id) === previous) ? previous : ""; const cards = available.map((item) => { const button = makeElement("button", "ssh-key-option"); button.type = "button"; button.dataset.keyId = String(item.id); button.setAttribute("aria-pressed", String(button.dataset.keyId === selected)); button.append(makeElement("strong", "", String(item.name || `公钥 ${item.id}`))); button.addEventListener("click", () => { const wasSelected = button.getAttribute("aria-pressed") === "true"; container.querySelectorAll(".ssh-key-option").forEach((option) => option.setAttribute("aria-pressed", "false")); button.setAttribute("aria-pressed", String(!wasSelected)); if (containerId === "vm-guest-ssh-key-cards") updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); }); return button; }); if (!available.length) { cards.push(makeElement("p", "ssh-key-picker-empty", "还没有保存 SSH 公钥。可点击下方“管理我的公钥”先添加。")); } container.replaceChildren(...cards); if (containerId === "vm-guest-ssh-key-cards") updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); } function fillSshKeyCards(items) { renderSshKeyPicker("vm-guest-ssh-key-cards", items); renderSshKeyPicker("reinstall-ssh-key-cards", items); } function sshKeyCreatedAt(value) { if (value === null || value === undefined || value === "") return "未记录"; const parsed = typeof value === "number" ? new Date(value * 1000) : new Date(value); return Number.isFinite(parsed.getTime()) ? parsed.toLocaleString() : "未记录"; } function renderSshKeys() { const list = byId("ssh-keys-list"); list.replaceChildren(); if (!state.sshKeys.length) { list.append(makeElement("p", "muted", "还没有保存公钥。导入后,创建云镜像虚拟机时即可直接选择。")); return; } for (const key of state.sshKeys) { const row = makeElement("div", "ssh-key-row"); const details = makeElement("div", "ssh-key-details"); details.append(makeElement("strong", "", key.name || `公钥 ${key.id}`)); details.append(makeElement("code", "", key.fingerprint || "指纹未记录")); details.append(makeElement("small", "", `添加时间:${sshKeyCreatedAt(key.created_at)}`)); const actions = makeElement("div", "ssh-key-actions"); const copy = makeElement("button", "button button-outline small", "复制公钥"); copy.type = "button"; copy.disabled = !key.public_key; copy.addEventListener("click", async () => { try { await copyText(key.public_key); toast("公钥已复制。", "success"); } catch (error) { toast(error.message, "error"); } }); const remove = makeElement("button", "button button-outline small ssh-key-delete", "删除"); remove.type = "button"; remove.addEventListener("click", async () => { if (!window.confirm(`确定删除公钥“${key.name}”?已经创建的虚拟机不会受影响。`)) return; showError("ssh-keys-list-error", ""); setButtonBusy(remove, true, "删除中…"); try { await api(`/api/v1/ssh-keys/${encodeURIComponent(String(key.id))}`, { method: "DELETE" }); await loadSshKeys(); toast("公钥已删除。", "success"); } catch (error) { showError("ssh-keys-list-error", error.message); } finally { if (remove.isConnected) setButtonBusy(remove, false); } }); actions.append(copy, remove); row.append(details, actions); list.append(row); } } async function loadSshKeys() { if (state.sshKeysLoad) return state.sshKeysLoad; const epoch = state.sessionEpoch; const request = api("/api/v1/ssh-keys"); state.sshKeysLoad = request; try { const result = await request; if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; state.sshKeys = (Array.isArray(result?.items) ? result.items : []).filter((item) => { const id = Number(item?.id); return Number.isSafeInteger(id) && id > 0; }); fillSshKeyCards(state.sshKeys); renderSshKeys(); } finally { if (state.sshKeysLoad === request) state.sshKeysLoad = null; } } function openUpdateFromGate(returnView) { if (!state.admin) return; if (returnView === "host") { const hasKeyInput = Boolean(byId("host-private-key").value || state.uploadedPrivateKey || byId("host-private-key-passphrase").value); if (hasKeyInput && !window.confirm("切换到网站更新会清空尚未保存的 SSH 私钥与口令输入。确定继续吗?")) return; clearHostPrivateKey(); } else if (returnView === "unlock") { byId("unlock-passphrase").value = ""; } state.updateReturnView = returnView; text("current-username", state.username || "管理员"); byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = false; void showUpdateWorkspace(); } function leaveUpdateWorkspace() { byId("update-access-token").value = ""; const returnView = state.updateReturnView; if (returnView === "host" || returnView === "unlock") { state.updateReturnView = null; byId("dashboard-view").hidden = true; byId("host-view").hidden = returnView !== "host"; byId("unlock-view").hidden = returnView !== "unlock"; return; } showVmWorkspace(); } async function showUpdateWorkspace() { if (!state.admin) return; if (!canLeaveReinstallPage()) return; discardVmSubpageDrafts(); byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); 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; byId("vm-navigation-button").classList.remove("active"); byId("vm-navigation-button").removeAttribute("aria-current"); byId("ssh-keys-button").classList.remove("active"); 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"); byId("smtp-settings-button").removeAttribute("aria-current"); text("breadcrumb-current", "网站更新"); showError("update-settings-error", ""); if (!state.updateLastShownJobId && !state.updateJobId) showError("update-action-error", ""); try { await loadUpdateSettings(); } catch (error) { showError("update-settings-error", `无法读取更新设置:${error.message}`); } } async function loadSmtpSettings() { const epoch = state.sessionEpoch; const settings = await api("/api/v1/smtp/settings"); if (epoch !== state.sessionEpoch || !state.admin) return; byId("smtp-host").value = settings?.host || ""; byId("smtp-port").value = settings?.port || 465; byId("smtp-tls-mode").value = settings?.tls_mode || "ssl"; byId("smtp-username").value = settings?.username || ""; byId("smtp-from-address").value = settings?.from_address || ""; byId("smtp-password").value = ""; byId("smtp-password").placeholder = settings?.password_configured ? "留空沿用已保存的密码" : "填写 SMTP 密码或应用专用密码"; text("smtp-password-hint", settings?.password_configured ? "密码已加密保存;留空沿用现有密码。已保存密码不会回显,也不会写入浏览器存储。" : "保存后不会回显,也不会写入浏览器存储。"); text("smtp-status", settings?.configured ? "邮件服务已配置,可发送注册验证码。" : "尚未配置邮件服务;注册验证码暂不可发送。"); byId("smtp-status").hidden = false; } async function loadPendingUsers() { const epoch = state.sessionEpoch; const result = await api("/api/v1/users/pending"); if (epoch !== state.sessionEpoch || !state.admin) return; const list = byId("pending-users-list"); list.replaceChildren(); const users = Array.isArray(result?.items) ? result.items : []; if (!users.length) { list.append(makeElement("p", "muted", "暂无待审核用户。")); return; } for (const user of users) { const id = Number(user?.id); if (!Number.isSafeInteger(id) || id <= 0) continue; const row = makeElement("div", "pending-user-row"); const details = makeElement("div", "pending-user-details"); details.append(makeElement("strong", "", user.username || `用户 ${id}`)); details.append(makeElement("span", "", user.email || "")); const createdAt = Number(user.created_at); const createdDate = Number.isSafeInteger(createdAt) && createdAt > 0 ? new Date(createdAt * 1000) : null; const created = createdDate && Number.isFinite(createdDate.getTime()) ? vmCreatedAt({ created_at: createdDate.toISOString() }) : "未记录"; details.append(makeElement("small", "", `注册时间:${created}`)); const button = makeElement("button", "button button-outline small", "审核通过"); button.type = "button"; button.addEventListener("click", async () => { if (!window.confirm(`确认通过用户 ${String(user.username || id)} 的审核?通过后该用户可创建并管理自己的虚拟机。`)) return; setButtonBusy(button, true, "正在审核…"); showError("pending-users-error", ""); try { const approved = await api(`/api/v1/users/${encodeURIComponent(String(id))}/approve`, { method: "POST" }); if (approved?.approved !== true) throw new Error("无法确认审核结果,请刷新待审核列表。"); toast("用户审核通过。", "success"); await loadPendingUsers(); } catch (error) { showError("pending-users-error", error.message); } finally { setButtonBusy(button, false); } }); row.append(details, button); list.append(row); } } async function showSmtpWorkspace() { if (!state.admin) return; if (!canLeaveReinstallPage()) return; discardVmSubpageDrafts(); byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); 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"); byId("vm-navigation-button").removeAttribute("aria-current"); byId("ssh-keys-button").classList.remove("active"); 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"); byId("smtp-settings-button").setAttribute("aria-current", "page"); text("breadcrumb-current", "邮件与用户审核"); showError("smtp-error", ""); showError("pending-users-error", ""); const [settingsResult, usersResult] = await Promise.allSettled([loadSmtpSettings(), loadPendingUsers()]); if (settingsResult.status === "rejected") showError("smtp-error", `无法读取邮件设置:${settingsResult.reason.message}`); if (usersResult.status === "rejected") showError("pending-users-error", `无法读取待审核用户:${usersResult.reason.message}`); } async function loadUpdateSettings() { const settings = await api("/api/v1/update/settings"); state.updateCheck = null; state.updateSettings = { configured: Boolean(settings?.configured), token_configured: Boolean(settings?.token_configured) }; byId("update-repository-url").value = UPDATE_REPOSITORY_URL; byId("update-branch").value = UPDATE_BRANCH; byId("update-access-token").value = ""; text("update-token-hint", settings?.token_configured ? "访问令牌已保存;留空则继续使用现有令牌。令牌不会在页面回显。" : "填写具有仓库读取权限的令牌。保存后不会回显,也不会写入浏览器存储。"); if (settings?.current_version) text("update-current-version", settings.current_version); byId("update-check-button").disabled = !settings?.configured || Boolean(settings?.active_job_id); byId("update-apply-button").disabled = true; if (settings?.checkout_error) text("update-status", settings.checkout_error); else if (!settings?.token_configured) text("update-status", "请先保存私有仓库访问令牌,再检查更新。"); const activeJobId = settings?.active_job_id; if (activeJobId && activeJobId !== state.updateJobId) { state.updateJobId = activeJobId; void pollUpdateJob(activeJobId, ++state.updatePollToken); return; } if (activeJobId) return; const lastJobId = settings?.last_job_id; if (lastJobId && lastJobId !== state.updateLastShownJobId) { try { const job = await api(`/api/v1/update/jobs/${encodeURIComponent(lastJobId)}`); const status = String(job?.status || ""); if (status === "succeeded" || status === "completed") { state.updateLastShownJobId = lastJobId; state.updateJobId = null; state.updatePollToken += 1; if (job?.new_commit) text("update-current-version", job.new_commit); showError("update-action-error", ""); text("update-status", "上次面板更新已完成。请确认虚拟机与宿主机连接正常。"); } else if (status === "failed") { state.updateLastShownJobId = lastJobId; state.updateJobId = null; state.updatePollToken += 1; text("update-status", "上次面板更新未完成。"); showError("update-action-error", String(job?.error || job?.message || "请检查独立更新服务日志。")); } else if (status === "queued" || status === "running") { state.updateJobId = lastJobId; void pollUpdateJob(lastJobId, ++state.updatePollToken); } } catch (error) { showError("update-action-error", `无法读取上次更新结果:${error.message}`); } } } async function pollUpdateJob(jobId, token) { let errors = 0; for (let attempt = 0; attempt < 420; attempt += 1) { if (token !== state.updatePollToken) return; try { const job = await api(`/api/v1/update/jobs/${encodeURIComponent(jobId)}`); if (token !== state.updatePollToken) return; errors = 0; const status = String(job?.status || "running"); const phase = String(job?.phase || job?.message || "正在更新面板文件…"); text("update-status", `更新任务:${phase}`); if (status === "succeeded" || status === "completed") { text("update-status", "面板更新已完成。请刷新页面,并确认虚拟机与宿主机连接正常。"); state.updateJobId = null; state.updateLastShownJobId = jobId; byId("update-check-button").disabled = false; toast("面板更新已完成。", "success"); return; } if (status === "failed") { const message = String(job?.error || job?.message || "更新失败,请检查面板日志。"); text("update-status", "更新未完成。"); showError("update-action-error", message); state.updateJobId = null; state.updateLastShownJobId = jobId; byId("update-check-button").disabled = false; return; } } catch (error) { if (token !== state.updatePollToken) return; errors += 1; text("update-status", `面板暂时无法响应(第 ${errors} 次),可能正在重启;将继续查询同一更新任务。`); } await new Promise((resolve) => window.setTimeout(resolve, 5000)); } if (token === state.updatePollToken) { text("update-status", "暂时无法确认更新结果。请检查服务状态和日志,不要重复点击更新。"); } } function setButtonBusy(button, busy, busyLabel = "处理中…") { if (busy) { button.dataset.originalLabel = button.textContent; button.textContent = busyLabel; button.disabled = true; } else { button.textContent = button.dataset.originalLabel || button.textContent; button.disabled = false; } } function saveReinstallJob(jobId) { try { sessionStorage.setItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`, JSON.stringify({ job_id: jobId, username: state.username, expect_generated_password: state.reinstallExpectGeneratedPassword, })); } catch { /* Private browsing may disable session storage; the open page still tracks this job. */ } } function clearSavedReinstallJob() { try { sessionStorage.removeItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`); } catch { /* Storage is optional. */ } } function readSavedReinstallJob() { try { const record = JSON.parse(sessionStorage.getItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`) || "null"); if (!record || record.username !== state.username || !/^[0-9a-f-]{36}$/.test(record.job_id)) return null; return record; } catch { return null; } } function setConnection(connected) { text("host-connection-label", connected ? "连接正常" : "连接失败"); byId("host-connection-dot").classList.toggle("offline", !connected); } function hostCoordinates() { return { host: byId("host-address").value.trim(), port: Number(byId("host-port").value), }; } function requireSecureCredentialTransport() { if (location.protocol === "https:") return; throw new Error("不能通过明文 HTTP 提交密码或 root 私钥。请通过你配置的 HTTPS 反向代理访问面板。"); } function hostPayload() { if (!byId("host-form").reportValidity()) return null; const { host, port } = hostCoordinates(); const scan = state.scannedHost; if (!scan || scan.host !== host || Number(scan.port) !== port || !byId("host-fingerprint-confirm").checked) { throw new Error("请先扫描主机指纹,并在宿主机控制台独立核对后勾选确认。"); } const privateKey = byId("host-private-key").value.trim() || state.uploadedPrivateKey.trim(); if (!privateKey && !state.hostConfig?.private_key_configured) { throw new Error("首次连接需要提供宿主机 root 账号已有的 SSH 私钥。"); } const isoPool = byId("host-iso-pool").value.trim(); const rescueIsoPool = byId("host-rescue-iso-pool").value.trim(); if (rescueIsoPool && rescueIsoPool === isoPool) { throw new Error("救援 ISO 目录必须与安装 ISO 目录不同,避免救援镜像出现在创建虚拟机的安装镜像列表中。"); } const publicPoolCidr = byId("host-public-pool-cidr").value.trim(); const publicGateway = byId("host-public-gateway").value.trim(); const publicVmPrefixText = byId("host-public-vm-prefix").value.trim(); const publicVmPrefix = publicVmPrefixText ? Number(publicVmPrefixText) : null; const publicDnsServers = byId("host-public-dns").value.split(/[\s,;]+/).filter(Boolean); const publicReservedIps = [...new Set(byId("host-public-reserved").value.split(/[\s,;]+/).filter(Boolean))]; if (!publicPoolCidr && (publicGateway || publicVmPrefix !== null || publicDnsServers.length || publicReservedIps.length)) { throw new Error("填写公网网关、虚拟机网卡前缀、DNS 或保留地址时,必须先填写服务商分配的公网网段;如需关闭地址池,请将这些项全部清空。"); } if (publicPoolCidr) { const pool = parsePublicPool(publicPoolCidr); if (!pool) { throw new Error("公网地址池请填写服务商实际分配的 IPv4 网段(/24 至 /30),例如 123.123.123.112/28;/28 可填段内网关/前缀并自动换算,/24 必须填写网段起始地址。"); } if (publicVmPrefix !== null && (!Number.isInteger(publicVmPrefix) || publicVmPrefix < 24 || publicVmPrefix > pool.prefix)) { throw new Error(`虚拟机网卡前缀须介于 /24 和地址池前缀 /${pool.prefix} 之间;留空则使用 /${pool.prefix}。`); } if (!validPoolMember(publicGateway, publicPoolCidr)) { throw new Error("公网地址池网关必须是该网段内有效的 IPv4 地址,且不能是网段或广播地址。"); } if (publicDnsServers.length < 1 || publicDnsServers.length > 4 || !publicDnsServers.every((address) => ipv4Parts(address))) { throw new Error("公网地址池需配置 1 至 4 个有效的 DNS IPv4 地址。"); } if (!publicReservedIps.every((address) => validPoolMember(address, publicPoolCidr))) { throw new Error("额外保留的 IP 必须是该网段内的有效主机地址,不能填写网段或广播地址。"); } } return { host, port, region: byId("host-region").value.trim(), private_key: privateKey, private_key_passphrase: byId("host-private-key-passphrase").value, host_key: scan.known_hosts_line, confirmed_fingerprint: scan.fingerprint, storage_pool: byId("host-storage-pool").value.trim(), iso_pool: isoPool, rescue_iso_pool: rescueIsoPool, default_network: byId("host-network").value.trim(), public_pool_cidr: publicPoolCidr, public_gateway: publicGateway, public_vm_prefix: publicVmPrefix, public_dns_servers: publicDnsServers, public_reserved_ips: publicReservedIps, }; } async function scanHost() { showError("host-error", ""); const { host, port } = hostCoordinates(); if (!host || !Number.isInteger(port) || port < 1 || port > 65535) { showError("host-error", "请先填写有效的宿主机地址和 SSH 端口。"); return; } resetFingerprint(); const button = byId("host-scan-button"); setButtonBusy(button, true, "扫描中…"); try { const result = await api("/api/v1/host/scan", { method: "POST", body: { host, port } }); const current = hostCoordinates(); if (current.host !== host || current.port !== port) return; if (!result?.fingerprint || !result?.known_hosts_line) throw new Error("扫描结果缺少主机公钥,请重试。"); state.scannedHost = { ...result, host, port }; text("host-key-type", result.key_type || "未知类型"); text("host-fingerprint", result.fingerprint); byId("host-fingerprint-result").hidden = false; byId("host-confirm-row").hidden = false; text("host-test-status", "扫描完成。请在宿主机控制台独立核对指纹,再勾选确认。"); } catch (error) { showError("host-error", `扫描失败:${error.message}`); } finally { setButtonBusy(button, false); } } async function submitHost(save) { showError("host-error", ""); const button = byId(save ? "host-save-button" : "host-test-button"); try { requireSecureCredentialTransport(); const body = hostPayload(); if (!body) return; setButtonBusy(button, true, save ? "保存并连接中…" : "测试连接中…"); const result = await api(save ? "/api/v1/host" : "/api/v1/host/test", { method: save ? "PUT" : "POST", body, }); const warnings = resourceWarnings(result); if (save) { if (!result?.configured) throw new Error("宿主机配置未确认保存,请检查后重试。"); state.hostConfig = result; clearHostPrivateKey(); await showDashboard({ username: state.username, csrf_token: state.csrfToken }); if (warnings.length) { const message = `宿主机已连接,但资源尚未就绪:${warnings.join(";")}`; showResourceWarning(message); toast(message); } else { toast("宿主机已连接,设置已保存。", "success"); } } else { if (warnings.length) { text("host-test-status", `root SSH 和 libvirt 连接成功,但资源尚未就绪:${warnings.join(";")}。仍可保存宿主机配置。`); byId("host-test-status").classList.add("warning"); byId("host-test-status").classList.remove("success"); } else { text("host-test-status", body.default_network.startsWith("bridge:") ? "连接成功:root SSH、libvirt 和存储池可访问。现有网桥将在创建虚拟机时由宿主机验证;现在可以保存设置。" : "连接成功:root SSH、libvirt、存储池和虚拟网络均可访问。现在可以保存设置。"); byId("host-test-status").classList.add("success"); byId("host-test-status").classList.remove("warning"); } } } catch (error) { byId("host-private-key-passphrase").value = ""; text("host-test-status", "连接未完成,请检查错误信息。"); byId("host-test-status").classList.remove("success", "warning"); showError("host-error", error.message); } finally { setButtonBusy(button, false); } } async function submitUnlock() { showError("unlock-error", ""); const button = byId("unlock-submit"); try { requireSecureCredentialTransport(); const passphrase = byId("unlock-passphrase").value; if (!passphrase) throw new Error("请输入 SSH 私钥口令。"); setButtonBusy(button, true, "解锁中…"); const result = await api("/api/v1/host/unlock", { method: "POST", body: { passphrase }, }); if (!result?.configured || result?.key_locked) throw new Error("私钥未解锁,请确认口令后重试。"); const hostConfig = await api("/api/v1/host"); if (!hostConfig?.configured || hostConfig?.key_locked) throw new Error("无法确认私钥已解锁,请重试。"); state.hostConfig = hostConfig; await showDashboard({ username: state.username, csrf_token: state.csrfToken }); toast("宿主机私钥已解锁。", "success"); } catch (error) { showError("unlock-error", error.message); } finally { byId("unlock-passphrase").value = ""; setButtonBusy(button, false); } } async function loadVMs(silent = false) { if (state.loadingVMs || byId("dashboard-view").hidden) return; state.loadingVMs = true; const epoch = state.sessionEpoch; const refreshButton = byId("refresh-button"); const detailRefreshButton = byId("vm-detail-refresh-button"); refreshButton.disabled = true; detailRefreshButton.disabled = true; try { const result = await api("/api/v1/vms"); if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; state.vms = Array.isArray(result?.items) ? result.items : []; setConnection(true); renderVMs(); syncVmDetailAfterRefresh(); } catch (error) { if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; setConnection(false); if (!silent && !byId("dashboard-view").hidden) toast(error.message, "error"); if (!state.vms.length) renderVMs(true); } finally { refreshButton.disabled = false; detailRefreshButton.disabled = false; state.loadingVMs = false; } } function stateCategory(value) { const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); if (normalized === "running" || normalized === "blocked") return "running"; if (["shutoff", "stopped", "crashed"].includes(normalized)) return "stopped"; return "other"; } function stateLabel(value) { const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); const labels = { running: "运行中", blocked: "运行中", shutoff: "已关机", stopped: "已关机", shutdown: "关机中", crashed: "已崩溃", paused: "已暂停", pmsuspended: "已挂起", nostate: "未知", unknown: "未知", }; return labels[normalized] || String(value || "未知"); } function diskLabel(vm) { 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 "—"; } function vmSystemInfo(vm) { if (vm.os_source === "iso") return { label: "安装镜像", value: String(vm.install_iso || "未识别") }; if (vm.os_source === "cloud_template") return { label: "系统镜像", value: String(vm.os_name || "未识别") }; return { label: "系统", value: String(vm.os_name || "未识别") }; } function vmRegion(vm) { return String(vm.region || "").trim() || "未设置"; } function vmIp(vm) { return String(vm.public_ip_cidr || "").trim().split("/")[0] || "未获取"; } function vmCreatedAt(vm) { const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; if (!value) return "未记录"; const date = new Date(value); if (!Number.isFinite(date.getTime())) return "未记录"; const pad = (number) => String(number).padStart(2, "0"); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`; } function vmCreatedAgo(vm, now = Date.now()) { const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; if (!value) return "未记录"; const created = Date.parse(value); if (!Number.isFinite(created)) return "未记录"; const elapsed = Math.max(0, now - created); const minute = 60 * 1000; const hour = 60 * minute; const day = 24 * hour; const month = 30 * day; if (elapsed < minute) return "创建于刚刚"; if (elapsed < hour) return `创建于 ${Math.floor(elapsed / minute)} 分钟前`; if (elapsed < day) return `创建于 ${Math.floor(elapsed / hour)} 小时前`; if (elapsed < month) return `创建于 ${Math.floor(elapsed / day)} 天前`; return `创建于 ${Math.floor(elapsed / month)} 个月前`; } function makeCell(row, className = "") { const cell = document.createElement("td"); if (className) cell.className = className; row.append(cell); return cell; } function makeElement(tag, className, content) { const element = document.createElement(tag); if (className) element.className = className; if (content !== undefined) element.textContent = String(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"; button.disabled = Boolean(options.disabled); if (options.key) button.dataset.vmAction = options.key; if (options.title) button.title = options.title; button.addEventListener("click", handler); return button; } function renderVMs(connectionError = false) { const all = state.vms; const runningCount = all.filter((vm) => stateCategory(vm.state) === "running").length; const stoppedCount = all.filter((vm) => stateCategory(vm.state) === "stopped").length; text("stat-total", String(all.length)); text("stat-running", String(runningCount)); text("stat-stopped", String(stoppedCount)); const query = byId("search-input").value.trim().toLocaleLowerCase(); const filter = byId("state-filter").value; const filtered = all.filter((vm) => { const matchesText = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.region, vm.os_name, vm.install_iso] .some((value) => String(value || "").toLocaleLowerCase().includes(query)); return matchesText && (filter === "all" || stateCategory(vm.state) === filter); }); text("inventory-count", `${filtered.length} 台虚拟机${filtered.length !== all.length ? ` · 共 ${all.length} 台` : ""}`); const tbody = byId("vm-table-body"); const focusedVmId = document.activeElement?.classList.contains("vm-name-link") ? document.activeElement.dataset.vmUuid : null; tbody.replaceChildren(); const empty = byId("empty-state"); empty.hidden = filtered.length !== 0; if (!filtered.length) { if (connectionError) { text("empty-title", "无法加载虚拟机"); text("empty-description", "请检查面板与宿主机的连接,然后点击刷新。"); } else if (all.length) { text("empty-title", "没有匹配的虚拟机"); text("empty-description", "尝试更换搜索词或状态筛选。"); } else { text("empty-title", "还没有虚拟机"); text("empty-description", "点击右上角“创建虚拟机”开始。"); } return; } for (const vm of filtered) { const uuid = String(vm.uuid || ""); const category = stateCategory(vm.state); const row = document.createElement("tr"); const identity = makeElement("div", "vm-identity"); identity.append(makeElement("div", "vm-icon", "▣")); const identityText = makeElement("div"); const nameButton = makeElement("button", "vm-name-link", vm.name || "未命名虚拟机"); nameButton.type = "button"; nameButton.disabled = !uuid; nameButton.dataset.vmUuid = uuid; nameButton.setAttribute("aria-label", `管理虚拟机 ${vm.name || uuid}`); nameButton.addEventListener("click", () => openVmDetail(uuid)); identityText.append(nameButton); const uuidRow = makeElement("span", "vm-uuid-row"); const uuidText = makeElement("span", "vm-id", uuid || "UUID 未知"); if (uuid) uuidText.title = uuid; uuidRow.append(uuidText); if (uuid) uuidRow.append(makeCopyIconButton(uuid, "UUID")); identityText.append(uuidRow); identity.append(identityText); const identityCell = makeCell(row); identityCell.dataset.label = "虚拟机"; identityCell.append(identity); const stateCell = makeCell(row); stateCell.dataset.label = "状态"; stateCell.append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state))); const regionCell = makeCell(row); regionCell.dataset.label = "地区"; regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm))); const system = vmSystemInfo(vm); const systemCell = makeCell(row); systemCell.dataset.label = system.label; systemCell.append(makeElement("span", "vm-metadata", system.value)); const ipCell = makeCell(row); ipCell.dataset.label = "已配置公网 IP"; 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", "", "计算资源")); const specCell = makeCell(row); specCell.dataset.label = "规格"; specCell.append(spec); const diskCell = makeCell(row); diskCell.dataset.label = "磁盘"; diskCell.append(makeElement("span", "vm-spec", diskLabel(vm))); tbody.append(row); } if (focusedVmId) { const replacement = Array.from(tbody.querySelectorAll(".vm-name-link")) .find((button) => button.dataset.vmUuid === focusedVmId); replacement?.focus({ preventScroll: true }); } } function 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" || mode === "ssh_key_password"); 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; const revealAction = state.credentialBusy ? "正在读取初始 root 密码…" : shown ? "隐藏初始 root 密码" : "查看初始 root 密码"; reveal.setAttribute("aria-label", revealAction); reveal.setAttribute("aria-pressed", String(shown)); reveal.title = revealAction; } 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) { toast("虚拟机已不在当前列表中,请刷新后重试。", "error"); return; } stopVmMetrics(); clearVmCredential(); state.selectedVmId = uuid; byId("vm-list-view").hidden = true; 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(); window.scrollTo({ top: 0, behavior: "auto" }); byId("vm-detail-name").focus(); } function syncVmDetailAfterRefresh() { if (!state.selectedVmId || byId("vm-workspace").hidden || byId("vm-detail-view").hidden) return; const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId); if (!vm) { showVmWorkspace(); toast("这台虚拟机已从宿主机移除,已返回列表。", "info"); byId("vm-list-title").focus(); return; } renderVmDetail(vm); } function renderVmDetail(vm) { const category = stateCategory(vm.state); const running = category === "running"; const stopped = category === "stopped"; const 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); text("vm-detail-name", vm.name || "未命名虚拟机"); text("vm-detail-state", stateLabel(vm.state)); byId("vm-detail-state").className = `state-pill ${category}`; const region = vmRegion(vm); text("vm-detail-header-region", region); text("vm-detail-header-created-at", vmCreatedAgo(vm)); text("vm-detail-region", region); text("vm-detail-os-label", system.label); text("vm-detail-os", system.value); const ip = vmIp(vm); text("vm-detail-header-ip", ip); 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("breadcrumb-current", vm.name || "虚拟机详情"); const primary = byId("vm-detail-primary-actions"); const danger = byId("vm-detail-danger-actions"); const focusedAction = document.activeElement?.dataset.vmAction || null; primary.replaceChildren(); danger.replaceChildren(); primary.append(actionButton("打开 VNC 控制台", () => void openConsole(vm), { disabled: busy || !running || !uuid || !hasConsole, variant: "primary", key: "console", title: !running ? "虚拟机运行时可用" : hasConsole ? "打开 VNC 控制台" : "该虚拟机未配置 VNC 控制台", })); if (running) { primary.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget), { disabled: busy || 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 || (rescueMode && !rescueStaged) || !stopped || !uuid, key: "start", title: rescueStaged ? "从已预挂载的救援 ISO 开机" : rescueMode ? "请先退出救援模式" : "启动虚拟机" })); } if (vm.managed && vm.public_ip_cidr) { danger.append(actionButton("重装系统", () => openReinstall(vm), { 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 || rescueGuard || !stopped || !uuid, variant: "danger", key: "delete", title: rescueGuard ? "请先退出救援模式" : stopped ? "删除虚拟机" : "请先关机再删除", })); if (focusedAction) { const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) .find((button) => button.dataset.vmAction === focusedAction && !button.disabled); replacement?.focus({ preventScroll: true }); } } const VM_METRICS_RANGE_SECONDS = { "1h": 3600, "24h": 86400, "7d": 604800, "30d": 2592000 }; const VM_METRIC_CHARTS = [ { id: "cpu", title: "CPU 使用率", unit: "percent", series: [{ key: "cpu_percent", color: "#0f9eaa" }] }, { id: "memory", title: "内存用量", unit: "memory", series: [{ key: "memory_used_mib", color: "#4781cf" }, { key: "memory_total_mib", color: "#a4b7d7", dash: "6 5" }] }, { id: "disk", title: "磁盘 I/O", unit: "rate", series: [{ key: "disk_read_bps", color: "#477dc9" }, { key: "disk_write_bps", color: "#e59c46" }] }, { id: "network", title: "网络速率", unit: "rate", series: [{ key: "network_rx_bps", color: "#17a685" }, { key: "network_tx_bps", color: "#926ed0" }] }, ]; function metricViewVisible() { return Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden && !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden; } function stopVmMetrics() { if (state.metricsPollTimer) window.clearInterval(state.metricsPollTimer); state.metricsPollTimer = null; if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer); state.metricsResizeTimer = null; state.metricsRequest?.controller.abort(); state.metricsRequest = null; } function startVmMetrics() { if (!metricViewVisible()) return; void loadVmMetrics(); if (!state.metricsPollTimer) { state.metricsPollTimer = window.setInterval(() => { if (metricViewVisible()) void loadVmMetrics(); }, 60000); } } function setVmMetricsStatus(message, warning = false) { const status = byId("vm-metrics-status"); status.textContent = message; status.classList.toggle("warning", warning); } function clearVmMetrics(message) { state.metricsPayload = null; setVmMetricsStatus(message); for (const chart of VM_METRIC_CHARTS) { text(`vm-metric-${chart.id}-summary`, "—"); byId(`vm-metric-${chart.id}-plot`).replaceChildren(makeElement("p", "vm-metric-empty", message)); } } async function loadVmMetrics() { if (!metricViewVisible()) return; const vmId = state.selectedVmId; const range = state.metricsRange; const previous = state.metricsRequest; if (previous?.vmId === vmId && previous.range === range) return; previous?.controller.abort(); const request = { vmId, range, controller: new AbortController() }; state.metricsRequest = request; setVmMetricsStatus("正在更新监控数据…"); try { const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/metrics?range=${encodeURIComponent(range)}`, { signal: request.controller.signal, }); if (request !== state.metricsRequest || !metricViewVisible()) return; if (!Array.isArray(payload?.points) || (payload.vm_id && payload.vm_id !== vmId)) { throw new Error("监控数据格式无效。"); } renderVmMetrics(payload); } catch (error) { if (request !== state.metricsRequest || request.controller.signal.aborted || !metricViewVisible()) return; setVmMetricsStatus(`监控数据暂时无法加载:${error.message}。已显示的数据可能不是最新。`, true); } finally { if (request === state.metricsRequest) state.metricsRequest = null; } } function metricNumber(value) { return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; } function formatMetricRate(value) { if (value === null) return "无统计"; const units = ["B/s", "KB/s", "MB/s", "GB/s", "TB/s"]; let amount = value; let index = 0; while (amount >= 1000 && index < units.length - 1) { amount /= 1000; index += 1; } return `${amount.toFixed(index === 0 ? (amount < 1 && amount > 0 ? 2 : 0) : amount < 10 ? 2 : 1)} ${units[index]}`; } function formatMetricMemory(value) { if (value === null) return "无统计"; return value >= 1024 ? `${(value / 1024).toFixed(value < 10240 ? 2 : 1)} GiB` : `${Math.round(value)} MiB`; } function formatMetricValue(value, unit) { if (value === null) return "无统计"; if (unit === "percent") return `${value.toFixed(1)}%`; if (unit === "memory") return formatMetricMemory(value); return formatMetricRate(value); } function formatMetricTime(timestamp) { return new Date(timestamp * 1000).toLocaleString("zh-CN", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", }); } function metricSummary(chart, points) { const latest = [...points].reverse().find((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); if (!latest) return "暂无统计"; const value = (key) => metricNumber(latest[key]); if (chart.id === "cpu") return formatMetricValue(value("cpu_percent"), "percent"); if (chart.id === "memory") return `已使用(估算)${formatMetricMemory(value("memory_used_mib"))} · 总量 ${formatMetricMemory(value("memory_total_mib"))}`; if (chart.id === "disk") return `读取 ${formatMetricRate(value("disk_read_bps"))} · 写入 ${formatMetricRate(value("disk_write_bps"))}`; return `接收 ${formatMetricRate(value("network_rx_bps"))} · 发送 ${formatMetricRate(value("network_tx_bps"))}`; } function metricChartEmptyText(chart) { if (chart.id === "memory") return "暂无内存统计;虚拟机可能未提供气球驱动数据。"; if (chart.id === "disk" || chart.id === "network") return "暂无速率数据;首次采样或停机时无法计算速率。"; return "当前时间范围内暂无 CPU 采样数据。"; } function metricNiceMax(value) { if (value <= 0) return 1; const base = 10 ** Math.floor(Math.log10(value)); for (const step of [1, 1.5, 2, 2.5, 5, 10]) { if (value <= step * base) return step * base; } return 10 * base; } function metricSvgElement(tag, attributes = {}) { const element = document.createElementNS("http://www.w3.org/2000/svg", tag); for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value)); return element; } function drawMetricChart(chart, points, start, end, intervalSeconds) { const plot = byId(`vm-metric-${chart.id}-plot`); const summary = metricSummary(chart, points); text(`vm-metric-${chart.id}-summary`, summary); const hasData = points.some((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); if (!hasData) { plot.replaceChildren(makeElement("p", "vm-metric-empty", metricChartEmptyText(chart))); return; } const values = points.flatMap((point) => chart.series.map((series) => metricNumber(point[series.key]))).filter((value) => value !== null); const maximum = chart.unit === "percent" ? Math.max(100, metricNiceMax(Math.max(...values))) : metricNiceMax(Math.max(...values)); // A fixed 640px viewBox shrinks axis text to ~4px inside a phone card. const width = Math.max(240, Math.floor(plot.clientWidth || 640)); const height = Math.max(180, Math.floor(plot.clientHeight || 216)); const left = 64; const right = 18; const top = 14; const bottom = 37; const plotWidth = width - left - right; const plotHeight = height - top - bottom; const x = (timestamp) => left + Math.max(0, Math.min(1, (timestamp - start) / (end - start))) * plotWidth; const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight; const svg = metricSvgElement("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": `${chart.title},${byId("vm-metrics-range").selectedOptions[0]?.textContent || "当前范围"};最近记录:${summary}` }); for (const fraction of [1, 0.5, 0]) { const lineY = top + (1 - fraction) * plotHeight; svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" })); const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" }); label.textContent = formatMetricValue(fraction * maximum, chart.unit); svg.append(label); } for (const [fraction, anchor] of [[0, "start"], [0.5, "middle"], [1, "end"]]) { const label = metricSvgElement("text", { x: left + fraction * plotWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" }); label.textContent = formatMetricTime(start + fraction * (end - start)); svg.append(label); } const maxGap = intervalSeconds * 2.5; for (const series of chart.series) { const segments = []; let segment = []; for (const point of points) { const value = metricNumber(point[series.key]); if (value === null) { if (segment.length) segments.push(segment); segment = []; continue; } if (segment.length && point.timestamp - segment[segment.length - 1].timestamp > maxGap) { segments.push(segment); segment = []; } segment.push({ timestamp: point.timestamp, value }); } if (segment.length) segments.push(segment); for (const group of segments) { if (group.length > 1) { const path = metricSvgElement("path", { d: group.map((point, index) => `${index ? "L" : "M"}${x(point.timestamp).toFixed(2)} ${y(point.value).toFixed(2)}`).join(" "), fill: "none", stroke: series.color, "stroke-width": 2.6, "stroke-linecap": "round", "stroke-linejoin": "round", ...(series.dash ? { "stroke-dasharray": series.dash } : {}), }); svg.append(path); } const last = group[group.length - 1]; svg.append(metricSvgElement("circle", { cx: x(last.timestamp), cy: y(last.value), r: group.length === 1 ? 3.8 : 2.8, fill: series.color })); } } plot.replaceChildren(svg); } function renderVmMetrics(payload) { state.metricsPayload = payload; const intervalSeconds = Math.max(1, Number(payload.interval_seconds) || 60); const rangeSeconds = VM_METRICS_RANGE_SECONDS[state.metricsRange]; const now = Math.floor(Date.now() / 1000); const points = payload.points .filter((point) => Number.isFinite(Number(point?.timestamp)) && Number(point.timestamp) >= now - rangeSeconds - intervalSeconds && Number(point.timestamp) <= now + intervalSeconds) .map((point) => ({ ...point, timestamp: Number(point.timestamp) })) .sort((a, b) => a.timestamp - b.timestamp); const end = Math.max(now, points.length ? points[points.length - 1].timestamp : now); const start = end - rangeSeconds; const visiblePoints = points.filter((point) => point.timestamp >= start && point.timestamp <= end); for (const chart of VM_METRIC_CHARTS) drawMetricChart(chart, visiblePoints, start, end, intervalSeconds); if (!visiblePoints.length) { setVmMetricsStatus("当前时间范围内没有采样记录。虚拟机运行后,通常需等待下一次后台采样。", true); return; } const latest = visiblePoints[visiblePoints.length - 1].timestamp; // Bucket width grows for long ranges; freshness still follows the 60s // collector cadence, not the downsampling bucket width. const stale = end - latest > 60 * 2.5; setVmMetricsStatus(`${visiblePoints.length} 个采样点 · ${stale ? "最近历史记录" : "最近采样"} ${formatMetricTime(latest)} · 每分钟自动刷新${stale ? "(当前无新数据)" : ""}`, stale); } function resourceValue(item, kind) { if (typeof item === "string") return item; if (item && typeof item === "object") return String(kind === "iso" ? (item.path || item.name || "") : (item.name || item.id || "")); return ""; } function resourceLabel(item, kind) { if (typeof item === "string") return kind === "iso" ? item.split("/").pop() : item; if (item && typeof item === "object") return String(item.label || item.name || item.path || item.id || ""); return ""; } function fillSelect(id, items, kind) { const select = byId(id); const previous = select.value; select.replaceChildren(); const placeholder = document.createElement("option"); placeholder.value = ""; placeholder.textContent = items.length ? (kind === "iso" ? "选择安装镜像" : "选择虚拟网络或网桥") : (kind === "iso" ? "没有可用 ISO 镜像" : "没有可用虚拟网络或网桥"); select.append(placeholder); for (const item of items) { const value = resourceValue(item, kind); if (!value) continue; const option = document.createElement("option"); option.value = value; option.textContent = resourceLabel(item, kind); select.append(option); } if (previous && Array.from(select.options).some((option) => option.value === previous)) select.value = previous; select.disabled = select.options.length <= 1; } async function loadResources() { const epoch = state.sessionEpoch; try { const result = await api("/api/v1/resources"); if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; state.resources = result || {}; fillSelect("vm-network", Array.isArray(result?.networks) ? result.networks : [], "network"); fillSelect("vm-iso", Array.isArray(result?.isos) ? result.isos : [], "iso"); updateCreateSource(); showResourceWarning(""); } catch (error) { if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; state.resources = null; fillSelect("vm-network", [], "network"); fillSelect("vm-iso", [], "iso"); updateCreateSource(); showResourceWarning(state.admin ? `宿主机资源尚未就绪:${error.message}。请检查存储池和网络或网桥设置。` : `宿主机资源尚未就绪:${error.message}。请联系管理员检查宿主机。`); throw error; } } const TEMPLATE_FAMILY_NAMES = { almalinux: "AlmaLinux", debian: "Debian", centos: "CentOS Stream", centosstream: "CentOS Stream", ubuntu: "Ubuntu", }; const TEMPLATE_ICON_PATHS = { AlmaLinux: "/static/almalinux-icon.svg", Debian: "/static/debian-icon.svg", "CentOS Stream": "/static/centos-icon.svg", Ubuntu: "/static/ubuntu-icon.svg", }; function templateSystem(item) { const id = String(item?.id || ""); const familyKey = String(item?.os_family || "").trim().toLowerCase().replace(/[\s_-]+/g, ""); const namedFamily = Object.prototype.hasOwnProperty.call(TEMPLATE_FAMILY_NAMES, familyKey) ? TEMPLATE_FAMILY_NAMES[familyKey] : ""; const idMatch = /^(alma|debian|ubuntu|centosstream)([0-9]{1,4})-/.exec(id); const idFamily = ({ alma: "AlmaLinux", debian: "Debian", ubuntu: "Ubuntu", centosstream: "CentOS Stream" })[idMatch?.[1]] || ""; const rawIdVersion = idMatch?.[2] || ""; const idVersion = idMatch?.[1] === "ubuntu" && rawIdVersion.length === 4 ? `${rawIdVersion.slice(0, 2)}.${rawIdVersion.slice(2)}` : rawIdVersion; const family = namedFamily || idFamily || "其他系统"; const providedVersion = String(item?.os_version || ""); const version = /^[0-9]+(?:\.[0-9]+)?$/.test(providedVersion) ? providedVersion : idVersion; return { family, version }; } function templateIcon(family, className) { const logoPath = TEMPLATE_ICON_PATHS[family]; const icon = makeElement("span", `${className}${logoPath ? " system" : ""}`); icon.setAttribute("aria-hidden", "true"); if (logoPath) { const logo = makeElement("img", "template-system-logo"); logo.src = logoPath; logo.alt = ""; icon.append(logo); } else { icon.textContent = "◈"; } return icon; } function renderTemplateCatalog(inputId) { const input = byId(inputId); const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog"); const opened = new Set(Array.from(container.querySelectorAll("details[open]"), (detail) => detail.dataset.family)); const groups = new Map(); for (const item of state.templates) { if (!item?.id) continue; const { family, version } = templateSystem(item); if (!groups.has(family)) groups.set(family, []); groups.get(family).push({ item, version }); } if (!groups.size) { input.value = ""; container.replaceChildren(makeElement("p", "template-catalog-empty", state.admin ? "暂无云镜像,请先到“云镜像模板”页面导入。" : "暂无可用云镜像,请联系管理员导入模板。")); return; } if (!state.templates.some((item) => String(item.id) === input.value)) input.value = ""; const cards = []; for (const [family, entries] of groups) { entries.sort((a, b) => Number(b.version || 0) - Number(a.version || 0) || String(a.item.name || "").localeCompare(String(b.item.name || ""), "zh-CN")); const card = makeElement("details", "template-family-card"); card.dataset.family = family; card.open = opened.has(family) || entries.some(({ item }) => String(item.id) === input.value); const summary = makeElement("summary", "template-family-summary"); const icon = templateIcon(family, "template-family-icon"); summary.append(icon, makeElement("strong", "", family), makeElement("span", "template-family-arrow", "⌄")); const versions = makeElement("div", "template-versions"); versions.setAttribute("role", "group"); versions.setAttribute("aria-label", `${family} 可用版本`); for (const { item } of entries) { const id = String(item.id); const name = String(item.name || id); const option = makeElement("button", "template-version-option"); option.type = "button"; option.dataset.templateId = id; option.setAttribute("aria-pressed", String(input.value === id)); option.setAttribute("aria-label", `选择模板 ${name}`); option.append(makeElement("strong", "", name)); option.addEventListener("click", () => { input.value = id; container.querySelectorAll(".template-version-option").forEach((button) => { button.setAttribute("aria-pressed", String(button.dataset.templateId === id)); }); if (inputId === "vm-template") showError("create-error", ""); else showError("reinstall-error", ""); }); versions.append(option); } card.append(summary, versions); cards.push(card); } container.replaceChildren(...cards); } function renderTemplateAdminList() { const list = byId("template-admin-list"); list.replaceChildren(); if (!state.admin) return; if (!state.templates.length) { list.append(makeElement("p", "muted", "当前宿主机还没有导入云镜像模板。")); return; } for (const item of state.templates) { const id = String(item?.id || ""); if (!id) continue; const { family, version } = templateSystem(item); const row = makeElement("form", "template-admin-row"); const heading = makeElement("div", "template-admin-row-heading"); const icon = templateIcon(family, "template-admin-icon"); heading.append(icon, makeElement("strong", "", `${family}${version ? ` ${version}` : ""}`)); const label = makeElement("label", "", "模板名称"); const name = makeElement("input", ""); name.type = "text"; name.required = true; name.maxLength = 64; name.value = String(item.name || ""); name.setAttribute("autocomplete", "off"); name.id = `template-admin-name-${id}`; label.htmlFor = name.id; const button = makeElement("button", "button button-outline small", "保存名称"); button.type = "submit"; const error = makeElement("p", "form-error"); error.hidden = true; error.setAttribute("role", "alert"); row.addEventListener("submit", async (event) => { event.preventDefault(); const requested = name.value.trim(); error.hidden = true; if (!requested || requested.length > 64) { error.textContent = "模板名称应为 1 至 64 个字符。"; error.hidden = false; return; } if (requested === item.name) return; setButtonBusy(button, true, "正在保存…"); try { await api(`/api/v1/vm-templates/${encodeURIComponent(id)}`, { method: "PATCH", body: { name: requested } }); await loadTemplates(); toast("模板名称已更新。", "success"); } catch (caught) { error.textContent = caught.message; error.hidden = false; } finally { if (button.isConnected) setButtonBusy(button, false); } }); row.append(heading, label, name, button, error); list.append(row); } } function fillTemplateViews(items, preferredId = "") { state.templates = items.filter((item) => item && typeof item.id === "string"); if (preferredId && state.templates.some((item) => item.id === preferredId)) byId("vm-template").value = preferredId; renderTemplateCatalog("vm-template"); renderTemplateCatalog("reinstall-template"); renderTemplateAdminList(); updateCreateSource(); } async function loadTemplates(preferredId = "") { if (state.templateLoad) await state.templateLoad; const epoch = state.sessionEpoch; const request = api("/api/v1/vm-templates"); state.templateLoad = request; try { const result = await request; if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; fillTemplateViews(Array.isArray(result?.templates) ? result.templates : [], preferredId); } finally { if (state.templateLoad === request) state.templateLoad = null; } } function showTemplateImportStatus(message) { const element = byId("template-import-status"); element.textContent = message; element.hidden = !message; } async function waitForTemplateImport(jobId) { for (let attempt = 0; attempt < 360; attempt += 1) { await new Promise((resolve) => window.setTimeout(resolve, 5000)); const job = await api(`/api/v1/vm-templates/import-jobs/${encodeURIComponent(jobId)}`); if (job?.status === "completed") return job; if (job?.status === "failed") { state.templateImportJobId = null; throw new Error(job.error || "模板导入失败,请核对下载地址和 SHA-256 校验值。"); } if (job?.status !== "running") throw new Error("模板导入状态未知,请稍后重新查看。"); if (attempt % 6 === 5) { const seconds = (attempt + 1) * 5; showTemplateImportStatus(`宿主机正在后台导入镜像,已等待约 ${seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分钟`}。离开页面不会取消任务。`); } } throw new Error("模板仍在后台导入。稍后返回“云镜像模板”页面查看导入状态。"); } function selectedCreateSource() { return document.querySelector('input[name="source"]:checked')?.value || "iso"; } function configuredPublicPool() { if (state.resources && Object.prototype.hasOwnProperty.call(state.resources, "public_pool_cidr")) { return String(state.resources.public_pool_cidr || "").trim(); } return String(state.hostConfig?.public_pool_cidr || "").trim(); } function updateCreateAuthMode() { const cloud = selectedCreateSource() === "cloud"; const password = byId("vm-root-password"); password.disabled = !cloud; updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); } function manualRootPasswordIssue(value) { if (!value) return ""; const missing = []; const characters = Array.from(value); if (characters.length < 12) missing.push("至少 12 个字符"); if (characters.length > 128) missing.push("不超过 128 个字符"); if (!characters.every((character) => { const code = character.codePointAt(0); return code >= 0x21 && code <= 0x7e; })) missing.push("仅使用不含空格的英文可打印字符"); if (!/[A-Z]/.test(value)) missing.push("大写字母"); if (!/[a-z]/.test(value)) missing.push("小写字母"); if (!/[0-9]/.test(value)) missing.push("数字"); if (!/[^A-Za-z0-9]/.test(value)) missing.push("符号"); return missing.length ? `自行设置的初始 root 密码还需:${missing.join("、")}。` : ""; } function updateRootPasswordHint(inputId, hintId) { const value = byId(inputId).value; const hint = byId(hintId); const issue = manualRootPasswordIssue(value); const creatingVm = inputId === "vm-root-password"; const keySelected = !creatingVm && Boolean(selectedSshKeyId("reinstall-ssh-key-cards")); hint.classList.toggle("root-password-hint-error", !!issue); hint.classList.toggle("root-password-hint-success", !!value && !issue); hint.textContent = issue || (value ? "密码符合要求,可与 SSH 公钥同时使用。" : `${creatingVm ? "留空时生成 32 位完全随机密码,即使选择了 SSH 公钥" : keySelected ? "留空时仅允许 SSH 公钥登录,不生成密码" : "不选公钥且留空时生成 32 位完全随机密码"};自行设置需为 12 至 128 位不含空格的英文可打印字符,包含大写字母、小写字母、数字和符号。`); } function updateCreateSource() { const cloud = selectedCreateSource() === "cloud"; const publicPool = configuredPublicPool(); const guestPrefix = state.resources?.public_vm_prefix ?? state.hostConfig?.public_vm_prefix ?? parsePublicPool(publicPool)?.prefix; const automaticPublicIp = cloud && Boolean(publicPool); byId("vm-iso-field").hidden = cloud; byId("vm-template-field").hidden = !cloud; byId("vm-cloud-fields").hidden = !cloud; byId("create-iso-tip").hidden = cloud; byId("create-cloud-tip").hidden = !cloud; byId("vm-auto-public-pool").hidden = !automaticPublicIp; text("vm-auto-public-pool-description", publicPool ? `创建时仅从 ${publicPool} 中选择未使用的公网 IP${guestPrefix ? `,虚拟机网卡使用 /${guestPrefix}` : ""},并自动配置宿主机保存的网关和 DNS。` : "创建时将从宿主机地址池中选择未使用的 IP,并自动写入网关和 DNS。"); byId("vm-manual-public-network").hidden = automaticPublicIp; const iso = byId("vm-iso"); iso.required = !cloud; iso.disabled = cloud || iso.options.length <= 1; const template = byId("vm-template"); template.disabled = !cloud; byId("vm-guest-ssh-key-cards").hidden = !cloud; ["vm-public-ip-cidr", "vm-gateway", "vm-dns"].forEach((id) => { const input = byId(id); input.required = cloud && !automaticPublicIp; input.disabled = !cloud || automaticPublicIp; }); updateCreateAuthMode(); const network = byId("vm-network"); for (const option of network.options) { option.disabled = cloud && !!option.value && !option.value.startsWith("bridge:"); } if (cloud && network.value && !network.value.startsWith("bridge:")) network.value = ""; if (cloud && !network.value) { const bridge = Array.from(network.options).find((option) => option.value.startsWith("bridge:")); if (bridge) network.value = bridge.value; } } function openModal(id) { if (state.activeModal) closeModal(); state.lastFocus = document.activeElement; state.activeModal = byId(id); state.activeModal.hidden = false; document.body.style.overflow = "hidden"; const focusTarget = state.activeModal.querySelector("input:not(:disabled),button:not(:disabled)"); window.requestAnimationFrame(() => focusTarget?.focus()); } function closeModal() { if (!state.activeModal) return; const returnFocus = state.lastFocus; if (state.activeModal.id === "console-modal") disconnectConsole(); state.activeModal.hidden = true; state.activeModal = null; state.deleteTarget = null; state.confirmTarget = null; document.body.style.overflow = ""; if (returnFocus?.isConnected && returnFocus.getClientRects().length && !returnFocus.disabled) { returnFocus.focus(); } else if (!byId("vm-workspace").hidden && !byId("vm-detail-view").hidden) { const action = returnFocus?.dataset?.vmAction; const replacement = action ? Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) .find((button) => button.dataset.vmAction === action && !button.disabled) : null; (replacement || byId("vm-detail-name")).focus(); } } function openCreate() { if (!state.admin && (!state.approved || !state.hostReady)) return; if (!showVmWorkspace()) return; resetCreatePage(); fillSshKeyCards(state.sshKeys); clearSshKeyPicker("vm-guest-ssh-key-cards"); showError("create-error", ""); updateCreateSource(); showVmSubpage("create"); if (!state.resources) { void loadResources().catch((error) => showError("create-error", `无法加载宿主机资源:${error.message}`)); } void loadSshKeys().catch((error) => showError("create-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`)); } function openDelete(vm) { state.deleteTarget = vm; text("delete-vm-name", vm.name || vm.uuid || "此虚拟机"); byId("delete-disks").checked = false; showError("delete-error", ""); openModal("delete-modal"); 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(); toast("此标签页已有重装任务,已恢复任务状态;请不要重复提交。", "info"); return; } resetReinstallPage(); fillSshKeyCards(state.sshKeys); clearSshKeyPicker("reinstall-ssh-key-cards"); updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); byId("reinstall-fields").hidden = false; byId("reinstall-progress").hidden = true; byId("reinstall-result").hidden = true; byId("reinstall-password-box").hidden = true; byId("reinstall-generated-password").textContent = ""; byId("reinstall-result-warning").hidden = true; byId("reinstall-cancel").hidden = false; byId("reinstall-submit").hidden = false; byId("reinstall-forget").hidden = true; byId("reinstall-retry").hidden = true; byId("reinstall-done").hidden = true; text("reinstall-done", "完成"); byId("reinstall-back").disabled = false; showError("reinstall-error", ""); text("reinstall-subtitle", `${vm.name || vm.uuid} · 保留公网网络参数,重新创建系统盘。`); text("reinstall-public-ip", String(vm.public_ip_cidr || "未知")); text("reinstall-confirm-hint", `请准确输入“${vm.name || ""}”;这也是防止选错虚拟机的最后一道确认。`); byId("reinstall-confirm-name").placeholder = vm.name || "请输入完整的虚拟机名称"; state.reinstallTarget = vm; showVmSubpage("reinstall"); void loadTemplates().catch((error) => showError("reinstall-error", `无法加载重装模板:${error.message}`)); void loadSshKeys().catch((error) => showError("reinstall-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`)); } function leaveReinstallPage() { if (!canLeaveReinstallPage()) return; const uuid = String(state.reinstallTarget?.uuid || ""); if (!showVmWorkspace()) return; if (uuid && state.vms.some((vm) => String(vm.uuid || "") === uuid)) openVmDetail(uuid); else byId("vm-list-title").focus(); } function resumeReinstallJob() { const saved = readSavedReinstallJob(); if (!saved) return; if (state.reinstallJobId === saved.job_id && (state.reinstallInProgress || state.reinstallPasswordPendingAck)) { showVmSubpage("reinstall"); return; } byId("reinstall-form").reset(); byId("reinstall-fields").hidden = true; byId("reinstall-result").hidden = true; byId("reinstall-progress").hidden = false; byId("reinstall-cancel").hidden = true; byId("reinstall-submit").hidden = true; byId("reinstall-forget").hidden = true; byId("reinstall-retry").hidden = true; byId("reinstall-done").hidden = true; byId("reinstall-generated-password").textContent = ""; byId("reinstall-password-box").hidden = true; showError("reinstall-error", ""); text("reinstall-subtitle", "正在恢复此标签页中尚未确认的重装任务。"); text("reinstall-phase", "正在查询已有重装任务…"); state.reinstallTarget = null; state.reinstallJobId = saved.job_id; state.reinstallExpectGeneratedPassword = Boolean(saved.expect_generated_password); state.reinstallPasswordPendingAck = false; state.reinstallInProgress = true; byId("reinstall-back").disabled = true; showVmSubpage("reinstall"); const token = ++state.reinstallPollToken; void pollReinstallJob(saved.job_id, token); } function reinstallPhaseLabel(phase) { const labels = { queued: "等待执行…", validating: "检查虚拟机、模板和原系统盘…", shutting_down: "正在请求虚拟机正常关机…", waiting_for_shutdown: "等待虚拟机完成正常关机…", preparing: "正在准备新的系统盘和 cloud-init 配置…", cloning: "正在复制云镜像模板到新系统盘…", defining: "正在切换虚拟机系统盘…", starting: "正在启动新系统…", cleaning_up: "libvirt/QEMU 已报告启动,正在删除旧系统盘…", }; return labels[phase] || (typeof phase === "string" && phase.trim() ? phase : "正在执行重装任务…"); } function showReinstallResult(success, message, job = {}, terminal = true) { state.reinstallInProgress = false; const password = success && typeof job.generated_password === "string" ? job.generated_password : ""; state.reinstallPasswordPendingAck = Boolean(password); if (terminal && !state.reinstallPasswordPendingAck) { state.reinstallJobId = null; clearSavedReinstallJob(); } byId("reinstall-fields").hidden = true; byId("reinstall-progress").hidden = true; byId("reinstall-result").hidden = false; byId("reinstall-cancel").hidden = true; byId("reinstall-submit").hidden = true; byId("reinstall-forget").hidden = true; byId("reinstall-retry").hidden = terminal; byId("reinstall-done").hidden = false; text("reinstall-done", state.reinstallPasswordPendingAck ? "已保存密码,完成" : "完成"); byId("reinstall-back").disabled = state.reinstallPasswordPendingAck; text("reinstall-result-title", success ? "重装任务已完成" : "重装任务未完成"); text("reinstall-result-message", message); byId("reinstall-result").classList.toggle("failed", !success); byId("reinstall-result").classList.remove("unknown"); byId("reinstall-generated-password").textContent = password; byId("reinstall-password-box").hidden = !password; const warnings = []; if (typeof job.warning === "string" && job.warning) warnings.push(job.warning); if (success && state.reinstallExpectGeneratedPassword && !password) { warnings.push("未收到自动生成的 root 密码,请通过虚拟机控制台恢复 root 登录,并检查面板日志。"); } const warning = warnings.join(" "); text("reinstall-result-warning", warning); byId("reinstall-result-warning").hidden = !warning; showError("reinstall-error", ""); } function showReinstallUnknown(message) { showReinstallResult(false, message, {}, false); text("reinstall-result-title", "重装任务状态未明"); byId("reinstall-result").classList.remove("failed"); byId("reinstall-result").classList.add("unknown"); byId("reinstall-done").hidden = true; byId("reinstall-forget").hidden = false; } async function pollReinstallJob(jobId, token) { let consecutiveErrors = 0; for (let attempt = 0; attempt < 600; attempt += 1) { if (state.reinstallPollToken !== token) return; let job; try { job = await api(`/api/v1/reinstall-jobs/${encodeURIComponent(jobId)}`, { csrf: true }); consecutiveErrors = 0; } catch (error) { if (state.reinstallPollToken !== token) return; if (error.status === 404) { showReinstallUnknown("面板找不到此重装任务。面板进程可能已重启,内存中的任务和未确认密码可能已丢失。请检查虚拟机、旧盘和新盘状态,切勿直接再次重装;如有必要可在控制台恢复 root 登录。"); return; } consecutiveErrors += 1; text("reinstall-phase", `暂时无法读取任务进度(第 ${consecutiveErrors} 次):${error.message}。面板仍会继续查询。`); } if (state.reinstallPollToken !== token) return; if (job) { if (job.status === "succeeded" || job.status === "completed") { showReinstallResult(true, "libvirt/QEMU 已报告虚拟机从新系统盘启动,但尚不能证明客户机系统、网络或 SSH 正常。请通过控制台及 SSH 验证。公网网络参数沿用原配置。", job); void loadVMs(true); return; } if (job.status === "failed") { showReinstallResult(false, String(job.error || "重装失败,请检查宿主机状态后再决定是否重试。"), job); void loadVMs(true); return; } text("reinstall-phase", reinstallPhaseLabel(job.phase || job.status)); } await new Promise((resolve) => window.setTimeout(resolve, 3000)); } if (state.reinstallPollToken === token) { showReinstallUnknown("连续查询约 30 分钟仍未取得最终状态。任务可能仍在面板进程中运行;请点击“重新查询任务”,不要重新提交重装。若面板进程已重启,请先检查虚拟机、旧盘和新盘状态。"); } } function openConfirm(vm, action) { const label = action === "poweroff" ? "强制断电" : "强制重置"; text("confirm-title", 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"); state.confirmTarget = { vm, action }; } async function runAction(vm, action, button) { const label = { start: "开机", shutdown: "关机", reboot: "重启", poweroff: "强制断电", reset: "强制重置" }[action] || action; const focusAction = button?.dataset.vmAction || null; if (state.vmActionInFlight === vm.uuid) return false; state.vmActionInFlight = vm.uuid; if (button) setButtonBusy(button, true); if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh(); try { await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/actions`, { method: "POST", body: { action } }); toast(vm.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; } catch (error) { toast(`${label}失败:${error.message}`, "error"); return false; } finally { state.vmActionInFlight = null; if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh(); if (button?.isConnected) setButtonBusy(button, false); if (focusAction && !state.activeModal && state.selectedVmId === vm.uuid && !byId("vm-detail-view").hidden) { const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]")) .find((item) => item.dataset.vmAction === focusAction && !item.disabled); (replacement || byId("vm-detail-name")).focus(); } } } function disconnectConsole() { state.consoleToken += 1; const rfb = state.rfb; state.rfb = null; if (rfb) { try { rfb.disconnect(); } catch { /* Already disconnected. */ } } const stage = byId("console-stage"); const placeholder = byId("console-placeholder"); stage.replaceChildren(placeholder); placeholder.hidden = false; byId("console-password-form").hidden = true; byId("console-cad").disabled = true; } async function openConsole(vm) { openModal("console-modal"); text("console-title", `${vm.name || vm.uuid} · 控制台`); text("console-status", "正在连接…"); const stage = byId("console-stage"); const placeholder = byId("console-placeholder"); placeholder.hidden = false; const token = ++state.consoleToken; try { const { default: RFB } = await import("/vendor/novnc/core/rfb.js"); if (token !== state.consoleToken) return; const url = new URL(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/console`, location.href); url.protocol = location.protocol === "https:" ? "wss:" : "ws:"; const rfb = new RFB(stage, url.toString(), { shared: true }); state.rfb = rfb; placeholder.hidden = true; rfb.scaleViewport = true; rfb.resizeSession = false; rfb.addEventListener("connect", () => { if (state.rfb !== rfb) return; text("console-status", "已连接"); byId("console-cad").disabled = false; }); rfb.addEventListener("disconnect", (event) => { if (state.rfb !== rfb) return; text("console-status", event.detail?.clean ? "连接已关闭" : "连接已中断,请关闭后重试"); byId("console-cad").disabled = true; }); rfb.addEventListener("credentialsrequired", () => { if (state.rfb !== rfb) return; byId("console-password-form").hidden = false; byId("console-password").focus(); text("console-status", "请输入 VNC 密码"); }); } catch (error) { if (token !== state.consoleToken) return; text("console-status", `连接失败:${error.message}`); placeholder.hidden = false; placeholder.lastElementChild.textContent = "控制台连接失败,请关闭后重试。"; } } byId("database-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("database-error", ""); const button = byId("database-submit"); const token = byId("database-token").value.trim(); const body = { host: byId("database-host").value.trim(), port: Number(byId("database-port").value), database: byId("database-name").value.trim(), username: byId("database-username").value.trim(), password: byId("database-password").value, setup_token: token, }; setButtonBusy(button, true, "正在连接…"); try { requireSecureCredentialTransport(); const result = await api("/api/v1/database/setup", { method: "POST", csrf: false, body }); if (result?.configured !== true) throw new Error("无法确认数据库配置已保存,请刷新页面后检查状态。"); byId("setup-token").value = token; byId("database-password").value = ""; byId("database-token").value = ""; showSetup(); } catch (error) { showError("database-error", error.message); } finally { delete body.password; delete body.setup_token; byId("database-password").value = ""; byId("database-token").value = ""; setButtonBusy(button, false); } }); byId("setup-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("setup-error", ""); const password = byId("setup-password").value; if (password !== byId("setup-password-confirm").value) { showError("setup-error", "两次输入的初始用户密码不一致。"); return; } const button = byId("setup-submit"); setButtonBusy(button, true, "正在创建…"); try { requireSecureCredentialTransport(); const session = await api("/api/v1/setup/admin", { method: "POST", csrf: false, body: { token: byId("setup-token").value.trim(), username: byId("setup-username").value.trim(), password, }, }); if (!session?.authenticated || !session?.csrf_token) throw new Error("初始用户已创建,但未能登录。请刷新页面后使用邮箱登录。"); byId("setup-token").value = ""; byId("setup-password").value = ""; byId("setup-password-confirm").value = ""; await continueAfterLogin(session); } catch (error) { showError("setup-error", error.message); } finally { setButtonBusy(button, false); } }); byId("login-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("login-error", ""); byId("login-success").hidden = true; const button = byId("login-submit"); setButtonBusy(button, true, "正在登录…"); try { requireSecureCredentialTransport(); const session = await api("/api/v1/login", { method: "POST", csrf: false, body: { email: byId("login-email").value.trim(), password: byId("login-password").value }, }); if (!session?.authenticated) throw new Error("登录失败,请检查邮箱和密码。"); byId("login-password").value = ""; await continueAfterLogin(session); } catch (error) { showError("login-error", error.message); } finally { setButtonBusy(button, false); } }); byId("show-register-button").addEventListener("click", showRegister); byId("show-login-button").addEventListener("click", () => { showLogin(); byId("login-email").focus(); }); byId("register-code-send").addEventListener("click", async () => { showError("register-error", ""); const emailInput = byId("register-email"); if (!emailInput.checkValidity()) { showError("register-error", "请先填写有效的邮箱地址。"); emailInput.focus(); return; } const button = byId("register-code-send"); setButtonBusy(button, true, "正在发送…"); try { requireSecureCredentialTransport(); const result = await api("/api/v1/register/code", { method: "POST", csrf: false, body: { email: emailInput.value.trim() } }); if (result?.sent !== true) throw new Error("面板未确认验证码已发送,请稍后重试。"); text("register-code-status", "如邮箱可注册且邮件服务可用,验证码将发送至该邮箱。请检查收件箱和垃圾邮件。"); byId("register-code-status").hidden = false; } catch (error) { showError("register-error", error.message); } finally { setButtonBusy(button, false); } }); byId("register-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("register-error", ""); const password = byId("register-password").value; if (password !== byId("register-password-confirm").value) { showError("register-error", "两次输入的密码不一致。"); return; } const button = byId("register-submit"); setButtonBusy(button, true, "正在注册…"); try { requireSecureCredentialTransport(); const username = byId("register-username").value.trim(); const email = byId("register-email").value.trim(); const result = await api("/api/v1/register", { method: "POST", csrf: false, body: { username, email, password, code: byId("register-code").value.trim(), } }); if (result?.registered !== true) throw new Error("面板未确认注册结果,请勿重复提交,稍后尝试登录。"); byId("register-form").reset(); showLogin(); byId("login-email").value = email; text("login-success", "邮箱已验证,注册成功。账号需等待管理员审核通过后才能创建虚拟机;你可以先登录查看审核状态。"); byId("login-success").hidden = false; } catch (error) { showError("register-error", error.message); } finally { byId("register-password").value = ""; byId("register-password-confirm").value = ""; setButtonBusy(button, false); } }); byId("wait-refresh-button").addEventListener("click", async () => { const button = byId("wait-refresh-button"); setButtonBusy(button, true, "正在检查…"); try { const session = await api("/api/v1/session"); if (!session?.authenticated) { showLogin(); return; } await continueAfterLogin(session); } catch (error) { toast(`状态检查失败:${error.message}`, "error"); } finally { setButtonBusy(button, false); } }); byId("wait-ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspace()); byId("smtp-settings-form").addEventListener("submit", async (event) => { event.preventDefault(); if (!state.admin) return; showError("smtp-error", ""); const button = byId("smtp-save-button"); const body = { host: byId("smtp-host").value.trim(), port: Number(byId("smtp-port").value), tls_mode: byId("smtp-tls-mode").value, username: byId("smtp-username").value.trim(), password: byId("smtp-password").value, from_address: byId("smtp-from-address").value.trim(), }; setButtonBusy(button, true, "正在保存…"); try { requireSecureCredentialTransport(); await api("/api/v1/smtp/settings", { method: "PUT", body }); await loadSmtpSettings(); toast("邮件设置已保存。", "success"); } catch (error) { showError("smtp-error", error.message); } finally { delete body.password; byId("smtp-password").value = ""; setButtonBusy(button, false); } }); async function logout(button) { if (!canLeaveReinstallPage()) return; setButtonBusy(button, true, "退出中…"); try { await api("/api/v1/logout", { method: "POST" }); showLogin(); } catch (error) { toast(`退出失败:${error.message}`, "error"); } finally { setButtonBusy(button, false); } } byId("logout-button").addEventListener("click", () => void logout(byId("logout-button"))); byId("wait-logout-button").addEventListener("click", () => void logout(byId("wait-logout-button"))); byId("host-logout-button").addEventListener("click", () => void logout(byId("host-logout-button"))); byId("unlock-logout-button").addEventListener("click", () => void logout(byId("unlock-logout-button"))); function openHostSettings() { if (!canLeaveReinstallPage()) return; discardVmSubpageDrafts(); showHostView(state.hostConfig || { configured: true }); } byId("host-settings-button").addEventListener("click", openHostSettings); byId("host-settings-mobile-button").addEventListener("click", openHostSettings); byId("host-update-button").addEventListener("click", () => openUpdateFromGate("host")); byId("unlock-update-button").addEventListener("click", () => openUpdateFromGate("unlock")); byId("vm-navigation-button").addEventListener("click", leaveUpdateWorkspace); byId("vm-navigation-mobile-button").addEventListener("click", leaveUpdateWorkspace); byId("ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspace()); 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()); byId("smtp-settings-mobile-button").addEventListener("click", () => void showSmtpWorkspace()); 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", () => { clearHostPrivateKey(); if (state.hostConfig?.key_locked) showUnlockView(state.hostConfig); else void showDashboard({ username: state.username, csrf_token: state.csrfToken }); }); byId("host-address").addEventListener("input", resetFingerprint); byId("host-port").addEventListener("input", resetFingerprint); for (const id of ["host-region", "host-storage-pool", "host-iso-pool", "host-rescue-iso-pool", "host-network", "host-public-pool-cidr", "host-public-gateway", "host-public-vm-prefix", "host-public-dns", "host-public-reserved"]) { byId(id).addEventListener("input", markHostTestStale); } byId("host-public-pool-cidr").addEventListener("input", refreshPublicPoolPreview); byId("host-private-key").addEventListener("input", () => { if (state.uploadedPrivateKey) { state.uploadedPrivateKey = ""; byId("host-private-key-file").value = ""; text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。"); } markHostTestStale(); }); byId("host-private-key-passphrase").addEventListener("input", markHostTestStale); byId("host-scan-button").addEventListener("click", () => void scanHost()); byId("host-test-button").addEventListener("click", () => void submitHost(false)); byId("host-form").addEventListener("submit", (event) => { event.preventDefault(); void submitHost(true); }); byId("unlock-form").addEventListener("submit", (event) => { event.preventDefault(); void submitUnlock(); }); byId("host-private-key-file").addEventListener("change", async (event) => { state.uploadedPrivateKey = ""; const input = event.currentTarget; const file = input.files?.[0]; if (!file) { text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。"); return; } if (file.size > 64 * 1024) { input.value = ""; showError("host-error", "私钥文件超过 64 KiB,请检查是否选错文件。"); return; } try { const content = await file.text(); if (input.files?.[0] !== file) return; state.uploadedPrivateKey = content; byId("host-private-key").value = ""; text("host-key-file-label", `已选择 ${file.name};文件内容不会在页面回显。`); showError("host-error", ""); markHostTestStale(); } catch { input.value = ""; showError("host-error", "无法读取所选私钥文件,请重试或粘贴私钥内容。"); } }); byId("update-settings-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("update-settings-error", ""); const body = { repository_url: UPDATE_REPOSITORY_URL, branch: UPDATE_BRANCH }; const accessToken = byId("update-access-token").value; if (accessToken) body.access_token = accessToken; if (!accessToken && !state.updateSettings?.token_configured) { showError("update-settings-error", "请填写具有仓库读取权限的 Gitea 访问令牌。"); return; } const button = byId("update-settings-submit"); setButtonBusy(button, true, "正在保存…"); try { requireSecureCredentialTransport(); const settings = await api("/api/v1/update/settings", { method: "PUT", body }); state.updateSettings = { configured: Boolean(settings?.configured), token_configured: Boolean(settings?.token_configured) }; state.updateCheck = null; byId("update-check-button").disabled = !settings?.configured; byId("update-apply-button").disabled = true; byId("update-access-token").value = ""; text("update-token-hint", "访问令牌已保存;留空则继续使用现有令牌。令牌不会在页面回显。"); text("update-latest-version", "—"); text("update-status", settings?.checkout_error || "访问令牌已保存。请点击“检查更新”。"); toast("更新来源已保存。", "success"); } catch (error) { showError("update-settings-error", error.message); } finally { delete body.access_token; byId("update-access-token").value = ""; setButtonBusy(button, false); } }); byId("update-check-button").addEventListener("click", async () => { showError("update-action-error", ""); const button = byId("update-check-button"); setButtonBusy(button, true, "正在检查…"); byId("update-apply-button").disabled = true; try { const result = await api("/api/v1/update/check", { method: "POST" }); state.updateCheck = result; text("update-current-version", result?.current_version || "—"); text("update-latest-version", result?.latest_version || "—"); const available = result?.update_available === true; byId("update-apply-button").disabled = !available || Boolean(state.updateJobId); text("update-status", available ? "发现新版本。请先备份数据库和面板数据,再点击“一键更新”。" : "当前已是最新版本。"); } catch (error) { state.updateCheck = null; showError("update-action-error", `检查更新失败:${error.message}`); text("update-status", "未能确认仓库版本,请检查更新来源与令牌。"); } finally { setButtonBusy(button, false); } }); byId("update-apply-button").addEventListener("click", async () => { if (!state.updateCheck?.update_available || state.updateJobId) return; const expectedCurrent = String(state.updateCheck.current_version || ""); const expectedRemote = String(state.updateCheck.latest_version || ""); if (!expectedCurrent || !expectedRemote) { showError("update-action-error", "缺少已检查的提交编号,请重新检查更新。"); return; } if (!window.confirm(`即将把面板更新到已检查的提交 ${expectedRemote.slice(0, 12)}。如果仓库版本已变化,更新会停止并要求重新检查。过程可能重启服务。确认已备份数据库和面板数据,并且可以使用服务器控制台恢复后,再继续。确定执行吗?`)) return; showError("update-action-error", ""); const button = byId("update-apply-button"); setButtonBusy(button, true, "正在提交…"); byId("update-check-button").disabled = true; try { const started = await api("/api/v1/update/apply", { method: "POST", body: { expected_current_commit: expectedCurrent, expected_remote_commit: expectedRemote, } }); const jobId = String(started?.job_id || ""); if (!jobId) throw new Error("未收到更新任务编号;请检查服务端状态,勿重复提交。"); state.updateJobId = jobId; text("update-status", "更新任务已提交,正在查询进度。服务可能短暂断开。"); void pollUpdateJob(jobId, ++state.updatePollToken); } catch (error) { showError("update-action-error", `提交更新失败:${error.message}`); byId("update-check-button").disabled = false; } finally { setButtonBusy(button, false); byId("update-apply-button").disabled = true; } }); byId("refresh-button").addEventListener("click", () => void loadVMs()); 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; state.metricsRange = range; stopVmMetrics(); clearVmMetrics("正在加载所选时间范围的监控数据…"); startVmMetrics(); }); window.addEventListener("resize", () => { if (!metricViewVisible() || !state.metricsPayload) return; if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer); state.metricsResizeTimer = window.setTimeout(() => { state.metricsResizeTimer = null; if (metricViewVisible() && state.metricsPayload) renderVmMetrics(state.metricsPayload); }, 120); }); document.addEventListener("visibilitychange", () => { 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(); byId("search-input").focus(); }); byId("search-input").addEventListener("input", () => renderVMs()); byId("state-filter").addEventListener("change", () => renderVMs()); byId("create-button").addEventListener("click", openCreate); byId("create-back").addEventListener("click", () => { if (showVmWorkspace()) byId("vm-list-title").focus(); }); 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; showError("ssh-key-form-error", ""); try { if (file.size > 16384) throw new Error("公钥文件不能超过 16 KiB;请选择 .pub 公钥文件,不要选择私钥。"); const publicKey = (await file.text()).trim(); if (!validSshPublicKey(publicKey)) throw new Error("文件内容不是受支持的单行 OpenSSH 公钥;请确认选择的是 .pub 文件而非私钥。"); byId("ssh-key-public-key").value = publicKey; if (!byId("ssh-key-name").value.trim()) byId("ssh-key-name").value = file.name.replace(/\.pub$/i, "").slice(0, 80); } catch (error) { showError("ssh-key-form-error", error.message); } finally { event.currentTarget.value = ""; } }); byId("ssh-key-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("ssh-key-form-error", ""); const name = byId("ssh-key-name").value.trim(); const publicKey = byId("ssh-key-public-key").value.trim(); if (!name || name.length > 80) { showError("ssh-key-form-error", "请填写 1 至 80 个字符的公钥名称。"); return; } if (!validSshPublicKey(publicKey)) { showError("ssh-key-form-error", "请填写单行 OpenSSH 公钥,例如 ssh-ed25519 AAAA…;不要填写私钥。"); return; } const button = byId("ssh-key-save-button"); setButtonBusy(button, true, "正在保存…"); try { await api("/api/v1/ssh-keys", { method: "POST", body: { name, public_key: publicKey } }); byId("ssh-key-form").reset(); if (state.sshKeysLoad) await state.sshKeysLoad.catch(() => {}); await loadSshKeys(); toast("公钥已保存,创建云镜像虚拟机时可以直接选择。", "success"); } catch (error) { showError("ssh-key-form-error", error.message); } finally { setButtonBusy(button, false); } }); for (const id of ["vm-open-ssh-keys", "reinstall-open-ssh-keys"]) { byId(id).addEventListener("click", () => { void showSshKeysWorkspace(id === "vm-open-ssh-keys" ? "create" : "reinstall"); }); } for (const [inputId, hintId] of [["vm-root-password", "vm-root-password-hint"], ["reinstall-root-password", "reinstall-root-password-hint"]]) { byId(inputId).addEventListener("input", () => updateRootPasswordHint(inputId, hintId)); } document.querySelectorAll('input[name="source"]').forEach((radio) => radio.addEventListener("change", () => { showError("create-error", ""); updateCreateSource(); if (selectedCreateSource() === "cloud") { void loadTemplates().catch((error) => showError("create-error", `无法加载云镜像模板:${error.message}`)); void loadSshKeys().catch((error) => showError("create-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`)); } })); byId("template-import-form").addEventListener("submit", async (event) => { event.preventDefault(); if (!state.admin) return; showError("template-import-error", ""); const existingJobId = state.templateImportJobId; const name = byId("template-name").value.trim(); const rawUrl = byId("template-url").value.trim(); const sha256 = byId("template-sha256").value.trim().toLowerCase(); let url; try { url = new URL(rawUrl); } catch { /* Validate below without displaying the supplied URL. */ } if (!existingJobId && (!name || name.length > 64)) { showError("template-import-error", "请填写不超过 64 个字符的模板名称。"); return; } const officialHosts = new Set([ "repo.almalinux.org", "cloud.debian.org", "cloud-images.ubuntu.com", "cloud.centos.org", ]); if (!existingJobId && (!url || url.protocol !== "https:" || !officialHosts.has(url.hostname) || (url.port && url.port !== "443") || url.username || url.password || url.search || url.hash)) { showError("template-import-error", "请填写受支持发行版官方镜像站的 HTTPS 文件地址。"); return; } if (!existingJobId && sha256 && !/^[a-f0-9]{64}$/.test(sha256)) { showError("template-import-error", "SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。"); return; } const button = byId("template-import-button"); setButtonBusy(button, true, "正在检查后台导入…"); try { let jobId = existingJobId; if (!jobId) { const body = { name, url: url.href }; if (sha256) body.sha256 = sha256; const started = await api("/api/v1/vm-templates/import", { method: "POST", body }); jobId = String(started?.job_id || ""); if (!jobId) throw new Error("面板未返回模板导入任务编号,请刷新模板列表确认结果。"); state.templateImportJobId = jobId; } showTemplateImportStatus("宿主机正在后台下载并检查云镜像。离开页面不会取消任务,请稍候。"); const completed = await waitForTemplateImport(jobId); state.templateImportJobId = null; showTemplateImportStatus(""); await loadTemplates(); byId("template-import-form").reset(); toast("云镜像模板已导入,用户现在可以在创建页面选择。", "success"); } catch (error) { showTemplateImportStatus(state.templateImportJobId ? "暂时无法确认导入进度,任务可能仍在后台运行;稍后点击按钮继续查看。" : ""); showError("template-import-error", error.message); } finally { setButtonBusy(button, false); } }); 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("."); const parts = segments.map(Number); return parts.every((part, index) => part >= 0 && part <= 255 && String(part) === segments[index]) ? parts : null; } function ipv4Number(parts) { return parts.reduce((accumulator, part) => ((accumulator << 8) | part) >>> 0, 0); } function ipv4Text(number) { return [number >>> 24, (number >>> 16) & 255, (number >>> 8) & 255, number & 255].join("."); } function validPublicIpCidr(value) { const match = /^([^/]+)\/(\d{1,2})$/.exec(value); if (!match) return false; const parts = ipv4Parts(match[1]); const prefix = Number(match[2]); if (!parts || prefix < 1 || prefix > 30) return false; const [first, second] = parts; if (first === 0 || first === 10 || first === 127 || first >= 224 || (first === 100 && second >= 64 && second <= 127) || (first === 169 && second === 254) || (first === 172 && second >= 16 && second <= 31) || (first === 192 && second === 168)) return false; if (prefix <= 30) { const address = ipv4Number(parts); const hostMask = 2 ** (32 - prefix) - 1; const host = address & hostMask; if (host === 0 || host === hostMask) return false; } return true; } function parsePublicPool(value) { const match = /^([^/]+)\/(\d{1,2})$/.exec(value); const parts = match && ipv4Parts(match[1]); const prefix = match && Number(match[2]); if (!parts || prefix < 24 || prefix > 30) return null; if ((parts[0] === 192 && parts[1] === 0 && parts[2] === 2) || (parts[0] === 198 && parts[1] === 51 && parts[2] === 100) || (parts[0] === 203 && parts[1] === 0 && parts[2] === 113)) return null; const mask = (0xffffffff << (32 - prefix)) >>> 0; const inputAddress = ipv4Number(parts); const network = (inputAddress & mask) >>> 0; if (prefix === 24 && inputAddress !== network) return null; const broadcast = (network | (~mask >>> 0)) >>> 0; if (!validPublicIpCidr(`${ipv4Text(network + 1)}/${prefix}`) || !validPublicIpCidr(`${ipv4Text(broadcast - 1)}/${prefix}`)) return null; return { network, broadcast, prefix, cidr: `${ipv4Text(network)}/${prefix}` }; } function refreshPublicPoolPreview() { const value = byId("host-public-pool-cidr").value.trim(); const pool = parsePublicPool(value); const preview = byId("host-public-pool-preview"); preview.hidden = !pool; if (pool) { preview.textContent = `实际网段:${pool.cidr};主机地址范围:${ipv4Text(pool.network + 1)}–${ipv4Text(pool.broadcast - 1)}。网关、保留和已用地址不会分配。`; } else { preview.textContent = ""; } } function validPoolMember(value, publicPoolCidr) { const parts = ipv4Parts(value); const pool = parsePublicPool(publicPoolCidr); if (!parts || !pool) return false; const address = ipv4Number(parts); return address > pool.network && address < pool.broadcast; } function validGatewayForCidr(gateway, publicIpCidr) { const gatewayParts = ipv4Parts(gateway); const [ip, prefixText] = publicIpCidr.split("/"); const ipParts = ipv4Parts(ip); const prefix = Number(prefixText); if (!gatewayParts || !ipParts || !Number.isInteger(prefix) || prefix < 1 || prefix > 30 || gateway === ip) return false; const mask = (0xffffffff << (32 - prefix)) >>> 0; const gatewayNumber = ipv4Number(gatewayParts); if ((gatewayNumber & mask) !== (ipv4Number(ipParts) & mask)) return false; if (prefix <= 30) { const hostMask = (~mask) >>> 0; const host = gatewayNumber & hostMask; if (host === 0 || host === hostMask) return false; } return true; } function validSshPublicKey(value) { return !/[\r\n]/.test(value) && /^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)) [A-Za-z0-9+/]{32,}={0,2}(?: [^\r\n]*)?$/.test(value); } byId("create-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("create-error", ""); const button = byId("create-submit"); const data = new FormData(event.currentTarget); const source = selectedCreateSource(); const body = { name: String(data.get("name") || "").trim(), vcpu: Number(data.get("vcpu")), memory_mib: Number(data.get("memory_mib")), disk_gib: Number(data.get("disk_gib")), network: String(data.get("network") || ""), }; if (source === "cloud") { body.source = "cloud"; body.template_id = String(data.get("template_id") || ""); const automaticPublicIp = Boolean(configuredPublicPool()); if (!automaticPublicIp) { body.public_ip_cidr = String(data.get("public_ip_cidr") || "").trim(); body.gateway = String(data.get("gateway") || "").trim(); body.dns_servers = String(data.get("dns_servers") || "").split(/[\s,;]+/).filter(Boolean); } const selectedKeyId = selectedSshKeyId("vm-guest-ssh-key-cards"); if (selectedKeyId) { const keyId = Number(selectedKeyId); if (!Number.isSafeInteger(keyId) || keyId <= 0 || !state.sshKeys.some((key) => Number(key.id) === keyId)) { showError("create-error", "所选公钥已不可用,请刷新公钥列表或重新选择。"); return; } body.guest_ssh_key_id = keyId; } if (!body.network.startsWith("bridge:")) { showError("create-error", "公网云镜像需要 Linux 网桥。请先在宿主机设置中配置 bridge:br0 等网桥。"); return; } if (!body.template_id) { showError("create-error", state.admin ? "请先选择已导入的云镜像版本;如无可用镜像,请到“云镜像模板”页面导入。" : "请先选择云镜像版本;如无可用镜像,请联系管理员导入。"); return; } if (!automaticPublicIp && !validPublicIpCidr(body.public_ip_cidr)) { showError("create-error", "请填写有效的公网 IPv4/CIDR,例如已分配给你的地址和 /24 或 /28 前缀;不能填写网段或广播地址。"); return; } if (!automaticPublicIp && !validGatewayForCidr(body.gateway, body.public_ip_cidr)) { showError("create-error", "请填写与虚拟机 IP 同网段的有效网关 IPv4,且不能与虚拟机 IP 相同。非同网段网关暂不支持。"); return; } if (!automaticPublicIp && (!body.dns_servers.length || body.dns_servers.length > 4 || !body.dns_servers.every((address) => ipv4Parts(address)))) { showError("create-error", "请填写 1 至 4 个有效的 DNS IPv4 地址,用逗号或空格分隔。"); return; } const requestedPassword = String(data.get("root_password") || ""); const passwordIssue = manualRootPasswordIssue(requestedPassword); if (passwordIssue) { showError("create-error", passwordIssue); byId("vm-root-password").focus(); return; } if (requestedPassword) body.root_password = requestedPassword; } else { body.iso = String(data.get("iso") || ""); if (!body.network || !body.iso) { showError("create-error", "请先选择可用的虚拟网络或网桥,以及 ISO 镜像。"); return; } } data.delete("root_password"); byId("vm-root-password").value = ""; updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); setButtonBusy(button, true, "正在创建…"); try { const autoPassword = source === "cloud" && !body.root_password; const createdVm = await api("/api/v1/vms", { method: "POST", body }); showVmWorkspace(); const createdIp = String(createdVm?.public_ip_cidr || "").split("/")[0]; toast(autoPassword ? `虚拟机 ${body.name} 创建成功${createdIp ? `,公网 IP:${createdIp}` : ""}。初始 root 密码可在虚拟机详情页查看。` : `虚拟机 ${body.name} 创建成功${createdIp ? `,公网 IP:${createdIp}` : ""}。`, "success"); await loadVMs(true); window.setTimeout(() => void loadVMs(true), 1200); } catch (error) { showError("create-error", error.message); } finally { delete body.root_password; byId("vm-root-password").value = ""; updateRootPasswordHint("vm-root-password", "vm-root-password-hint"); setButtonBusy(button, false); } }); byId("reinstall-form").addEventListener("submit", async (event) => { event.preventDefault(); const vm = state.reinstallTarget; if (!vm || state.reinstallInProgress) return; showError("reinstall-error", ""); const templateId = byId("reinstall-template").value; const selectedKeyId = selectedSshKeyId("reinstall-ssh-key-cards"); const rootPassword = byId("reinstall-root-password").value; const confirmationName = byId("reinstall-confirm-name").value; if (!templateId) { showError("reinstall-error", state.admin ? "请先选择已导入的云镜像版本;如无可用镜像,请到“云镜像模板”页面导入。" : "请先选择云镜像版本;如无可用镜像,请联系管理员导入。"); return; } if (selectedKeyId && !state.sshKeys.some((key) => String(key.id) === selectedKeyId)) { showError("reinstall-error", "所选公钥已不可用,请刷新公钥列表并重试。"); return; } const passwordIssue = manualRootPasswordIssue(rootPassword); if (passwordIssue) { showError("reinstall-error", passwordIssue); byId("reinstall-root-password").focus(); return; } if (confirmationName !== vm.name) { showError("reinstall-error", "确认名称与虚拟机名称不一致,未执行重装。"); return; } const button = byId("reinstall-submit"); const body = { template_id: templateId, confirmation_name: confirmationName, }; if (selectedKeyId) body.ssh_key_id = Number(selectedKeyId); if (rootPassword) body.root_password = rootPassword; state.reinstallInProgress = true; state.reinstallExpectGeneratedPassword = !selectedKeyId && !rootPassword; byId("reinstall-back").disabled = true; byId("reinstall-cancel").disabled = true; setButtonBusy(button, true, "正在提交…"); try { const started = await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/reinstall`, { method: "POST", body }); const jobId = String(started?.job_id || ""); if (!jobId) throw new Error("面板未返回重装任务编号,请先检查虚拟机状态,勿重复提交。"); state.reinstallJobId = jobId; saveReinstallJob(jobId); byId("reinstall-fields").hidden = true; byId("reinstall-progress").hidden = false; byId("reinstall-cancel").hidden = true; byId("reinstall-submit").hidden = true; text("reinstall-phase", "重装任务已提交,正在检查宿主机状态…"); const token = ++state.reinstallPollToken; void pollReinstallJob(jobId, token); } catch (error) { state.reinstallInProgress = false; byId("reinstall-back").disabled = false; byId("reinstall-cancel").disabled = false; showError("reinstall-error", error.message); } finally { delete body.root_password; byId("reinstall-root-password").value = ""; updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint"); setButtonBusy(button, false); } }); byId("reinstall-copy-password").addEventListener("click", async () => { const password = byId("reinstall-generated-password").textContent; if (!password) return; try { await navigator.clipboard.writeText(password); toast("root 密码已复制,请安全保存。", "success"); } catch { toast("浏览器无法复制,请手动选中并保存密码。", "error"); } }); byId("reinstall-done").addEventListener("click", async () => { if (!state.reinstallPasswordPendingAck) { leaveReinstallPage(); return; } const jobId = state.reinstallJobId; if (!jobId) { showError("reinstall-error", "无法确认此密码已保存,请立即手动复制,并检查面板任务状态。"); return; } const button = byId("reinstall-done"); setButtonBusy(button, true, "正在确认…"); try { const result = await api(`/api/v1/reinstall-jobs/${encodeURIComponent(jobId)}/ack-password`, { method: "POST" }); if (result?.acknowledged !== true) throw new Error("面板未确认密码已经清除,请稍后重试。"); state.reinstallPasswordPendingAck = false; clearSavedReinstallJob(); leaveReinstallPage(); } catch (error) { showError("reinstall-error", `确认密码失败:${error.message}。密码仍在此页面中,请先安全保存后重试。`); } finally { setButtonBusy(button, false); } }); byId("reinstall-retry").addEventListener("click", () => { const jobId = state.reinstallJobId; if (!jobId) return; state.reinstallInProgress = true; byId("reinstall-back").disabled = true; byId("reinstall-result").hidden = true; byId("reinstall-progress").hidden = false; byId("reinstall-retry").hidden = true; byId("reinstall-done").hidden = true; text("reinstall-phase", "正在重新查询已有重装任务…"); const token = ++state.reinstallPollToken; void pollReinstallJob(jobId, token); }); byId("reinstall-forget").addEventListener("click", () => { if (!window.confirm("请先在宿主机核对虚拟机、新旧系统盘和登录方式。放弃恢复后,本标签页将不再查询此任务,尚未领取的自动 root 密码也可能无法找回。确定放弃吗?")) return; clearSavedReinstallJob(); leaveReinstallPage(); }); byId("delete-form").addEventListener("submit", async (event) => { event.preventDefault(); const vm = state.deleteTarget; if (!vm) return; showError("delete-error", ""); const button = byId("delete-submit"); setButtonBusy(button, true, "正在删除…"); const deleteDisks = byId("delete-disks").checked; try { await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}?delete_disks=${deleteDisks}`, { method: "DELETE" }); closeModal(); toast(`${vm.name || vm.uuid} 已删除${deleteDisks ? ",磁盘已一并删除" : ""}。`, "success"); if (state.selectedVmId === vm.uuid) { showVmWorkspace(); byId("vm-list-title").focus(); } await loadVMs(true); } catch (error) { showError("delete-error", error.message); } finally { setButtonBusy(button, false); } }); byId("confirm-submit").addEventListener("click", async () => { const target = state.confirmTarget; if (!target) return; const button = byId("confirm-submit"); setButtonBusy(button, true); try { const succeeded = await runAction(target.vm, target.action); if (succeeded) closeModal(); else showError("confirm-error", "操作未完成,请检查宿主机状态后重试。"); } finally { setButtonBusy(button, false); } }); byId("console-cad").addEventListener("click", () => state.rfb?.sendCtrlAltDel()); byId("console-fullscreen").addEventListener("click", async () => { const stage = byId("console-stage"); try { if (document.fullscreenElement) await document.exitFullscreen(); else await stage.requestFullscreen(); } catch (error) { toast(`无法进入全屏:${error.message}`, "error"); } }); byId("console-password-form").addEventListener("submit", (event) => { event.preventDefault(); if (!state.rfb) return; state.rfb.sendCredentials({ password: byId("console-password").value }); byId("console-password").value = ""; byId("console-password-form").hidden = true; text("console-status", "正在验证 VNC 密码…"); }); function requestCloseModal() { closeModal(); } document.querySelectorAll("[data-close-modal]").forEach((button) => button.addEventListener("click", requestCloseModal)); document.querySelectorAll(".modal-backdrop").forEach((backdrop) => backdrop.addEventListener("click", (event) => { if (event.target === backdrop) requestCloseModal(); })); document.addEventListener("keydown", (event) => { if (!state.activeModal) return; if (event.key === "Escape") { requestCloseModal(); return; } if (event.key !== "Tab") return; const focusables = Array.from(state.activeModal.querySelectorAll("button:not(:disabled):not([hidden]),input:not(:disabled):not([hidden]),select:not(:disabled):not([hidden])")) .filter((element) => element.getClientRects().length); if (!focusables.length) return; const first = focusables[0]; const last = focusables[focusables.length - 1]; if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } }); void initialize();