|
|
const byId = (id) => document.getElementById(id);
|
|
|
const REINSTALL_JOB_STORAGE_PREFIX = "virsh-panel:reinstall-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,
|
|
|
templateLoad: null,
|
|
|
templateImportJobId: null,
|
|
|
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.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.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", "用户");
|
|
|
}
|
|
|
|
|
|
function showLogin() {
|
|
|
stopPolling();
|
|
|
stopVmMetrics();
|
|
|
closeModal();
|
|
|
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.resources = null;
|
|
|
state.hostConfig = null;
|
|
|
state.templateLoad = null;
|
|
|
state.templateImportJobId = null;
|
|
|
state.selectedVmId = null;
|
|
|
clearAdminContent();
|
|
|
renderVMs();
|
|
|
clearVmMetrics("登录后加载监控数据。");
|
|
|
fillSelect("vm-network", [], "network");
|
|
|
fillSelect("vm-iso", [], "iso");
|
|
|
fillTemplateSelect([]);
|
|
|
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-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.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;
|
|
|
if (!state.admin) clearAdminContent();
|
|
|
for (const id of ["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;
|
|
|
byId("template-import").hidden = !state.admin;
|
|
|
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 showVmWorkspace() {
|
|
|
if (!state.admin && (!state.approved || !state.hostReady)) {
|
|
|
showAccessWait(state.approved ? "host" : "approval");
|
|
|
return;
|
|
|
}
|
|
|
byId("admin-menu").open = false;
|
|
|
stopVmMetrics();
|
|
|
clearVmCredential();
|
|
|
state.selectedVmId = null;
|
|
|
byId("vm-workspace").hidden = false;
|
|
|
byId("vm-list-view").hidden = false;
|
|
|
byId("vm-detail-view").hidden = true;
|
|
|
byId("ssh-keys-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("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", "虚拟机");
|
|
|
}
|
|
|
|
|
|
async function showSshKeysWorkspace() {
|
|
|
if (!state.csrfToken) return;
|
|
|
byId("access-wait-view").hidden = true;
|
|
|
byId("dashboard-view").hidden = false;
|
|
|
byId("admin-menu").open = false;
|
|
|
state.updateReturnView = null;
|
|
|
stopVmMetrics();
|
|
|
clearVmCredential();
|
|
|
state.selectedVmId = null;
|
|
|
byId("vm-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", "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 selectedSshKeyId(containerId) {
|
|
|
return byId(containerId).querySelector('input[type="radio"]:checked')?.value || "";
|
|
|
}
|
|
|
|
|
|
function renderSshKeyPicker(containerId, fieldName, items, onChange) {
|
|
|
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 card = (value, title, detail = "") => {
|
|
|
const label = makeElement("label", "ssh-key-option");
|
|
|
const input = document.createElement("input");
|
|
|
input.type = "radio";
|
|
|
input.name = fieldName;
|
|
|
input.value = value;
|
|
|
input.defaultChecked = value === "";
|
|
|
input.checked = value === selected;
|
|
|
input.addEventListener("change", onChange);
|
|
|
const body = makeElement("div", "ssh-key-option-body");
|
|
|
body.append(makeElement("strong", "", title));
|
|
|
if (detail) body.append(makeElement("small", "", detail));
|
|
|
label.append(input, body);
|
|
|
return label;
|
|
|
};
|
|
|
const cards = [card("", "使用 root 密码", "不选公钥,可填写密码或自动生成")];
|
|
|
for (const item of available) {
|
|
|
cards.push(card(String(item.id), String(item.name || `公钥 ${item.id}`)));
|
|
|
}
|
|
|
if (!available.length) {
|
|
|
cards.push(makeElement("p", "ssh-key-picker-empty", "还没有保存 SSH 公钥。可点击下方“管理我的公钥”先添加。"));
|
|
|
}
|
|
|
container.replaceChildren(...cards);
|
|
|
onChange();
|
|
|
}
|
|
|
|
|
|
function fillSshKeyCards(items) {
|
|
|
renderSshKeyPicker("vm-guest-ssh-key-cards", "guest_ssh_key_id", items, updateCreateAuthMode);
|
|
|
renderSshKeyPicker("reinstall-ssh-key-cards", "ssh_key_id", items, updateReinstallAuthMode);
|
|
|
}
|
|
|
|
|
|
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;
|
|
|
byId("admin-menu").open = false;
|
|
|
stopVmMetrics();
|
|
|
clearVmCredential();
|
|
|
byId("vm-workspace").hidden = true;
|
|
|
byId("ssh-keys-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("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;
|
|
|
byId("admin-menu").open = false;
|
|
|
stopVmMetrics();
|
|
|
clearVmCredential();
|
|
|
byId("vm-workspace").hidden = true;
|
|
|
byId("ssh-keys-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("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 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: byId("host-iso-pool").value.trim(),
|
|
|
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");
|
|
|
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;
|
|
|
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 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, key: "shutdown" }));
|
|
|
primary.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget), { disabled: busy, key: "reboot" }));
|
|
|
danger.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { disabled: busy, variant: "danger", key: "poweroff" }));
|
|
|
danger.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { disabled: busy, variant: "danger", key: "reset" }));
|
|
|
} else {
|
|
|
primary.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: busy || !stopped || !uuid, key: "start" }));
|
|
|
}
|
|
|
if (vm.managed && vm.public_ip_cidr) {
|
|
|
danger.append(actionButton("重装系统", () => openReinstall(vm), {
|
|
|
disabled: busy || !uuid,
|
|
|
variant: "danger",
|
|
|
key: "reinstall",
|
|
|
title: "从云镜像模板重装,成功后自动删除旧系统盘",
|
|
|
}));
|
|
|
}
|
|
|
danger.append(actionButton("删除虚拟机", () => openDelete(vm), {
|
|
|
disabled: busy || !stopped || !uuid,
|
|
|
variant: "danger",
|
|
|
key: "delete",
|
|
|
title: stopped ? "删除虚拟机" : "请先关机再删除",
|
|
|
}));
|
|
|
if (focusedAction) {
|
|
|
const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]"))
|
|
|
.find((button) => button.dataset.vmAction === focusedAction && !button.disabled);
|
|
|
replacement?.focus({ preventScroll: true });
|
|
|
}
|
|
|
}
|
|
|
|
|
|
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;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function fillTemplateSelect(items, preferredId = "") {
|
|
|
const select = byId("vm-template");
|
|
|
const previous = preferredId || select.value;
|
|
|
select.replaceChildren();
|
|
|
const placeholder = document.createElement("option");
|
|
|
placeholder.value = "";
|
|
|
placeholder.textContent = items.length ? "选择云镜像模板" : "暂无模板,请先导入";
|
|
|
select.append(placeholder);
|
|
|
for (const item of items) {
|
|
|
const id = String(item?.id || "");
|
|
|
if (!id) continue;
|
|
|
const option = document.createElement("option");
|
|
|
option.value = id;
|
|
|
option.textContent = String(item.name || id);
|
|
|
select.append(option);
|
|
|
}
|
|
|
if (previous && Array.from(select.options).some((option) => option.value === previous)) select.value = previous;
|
|
|
select.disabled = selectedCreateSource() !== "cloud" || select.options.length <= 1;
|
|
|
if (!items.length && state.admin) byId("template-import").open = true;
|
|
|
|
|
|
const reinstallSelect = byId("reinstall-template");
|
|
|
const reinstallPrevious = reinstallSelect.value;
|
|
|
reinstallSelect.replaceChildren();
|
|
|
const reinstallPlaceholder = document.createElement("option");
|
|
|
reinstallPlaceholder.value = "";
|
|
|
reinstallPlaceholder.textContent = items.length ? "选择重装模板" : "暂无模板,请先在创建虚拟机窗口导入";
|
|
|
reinstallSelect.append(reinstallPlaceholder);
|
|
|
for (const item of items) {
|
|
|
const id = String(item?.id || "");
|
|
|
if (!id) continue;
|
|
|
const option = document.createElement("option");
|
|
|
option.value = id;
|
|
|
option.textContent = String(item.name || id);
|
|
|
reinstallSelect.append(option);
|
|
|
}
|
|
|
if (reinstallPrevious && Array.from(reinstallSelect.options).some((option) => option.value === reinstallPrevious)) {
|
|
|
reinstallSelect.value = reinstallPrevious;
|
|
|
}
|
|
|
reinstallSelect.disabled = reinstallSelect.options.length <= 1;
|
|
|
}
|
|
|
|
|
|
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;
|
|
|
fillTemplateSelect(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 savedKeySelected = cloud && Boolean(selectedSshKeyId("vm-guest-ssh-key-cards"));
|
|
|
const password = byId("vm-root-password");
|
|
|
const passwordMode = cloud && !savedKeySelected;
|
|
|
byId("vm-root-password-field").hidden = !passwordMode;
|
|
|
password.required = false;
|
|
|
password.disabled = !passwordMode;
|
|
|
if (!passwordMode) password.value = "";
|
|
|
}
|
|
|
|
|
|
function updateReinstallAuthMode() {
|
|
|
const savedKeySelected = Boolean(selectedSshKeyId("reinstall-ssh-key-cards"));
|
|
|
const password = byId("reinstall-root-password");
|
|
|
byId("reinstall-root-password-field").hidden = savedKeySelected;
|
|
|
password.disabled = savedKeySelected;
|
|
|
if (savedKeySelected) password.value = "";
|
|
|
}
|
|
|
|
|
|
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.required = cloud;
|
|
|
template.disabled = !cloud || template.options.length <= 1;
|
|
|
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();
|
|
|
if (state.activeModal.id === "create-modal") {
|
|
|
byId("create-form").reset();
|
|
|
byId("vm-root-password").value = "";
|
|
|
}
|
|
|
if (state.activeModal.id === "reinstall-modal") {
|
|
|
state.reinstallPollToken += 1;
|
|
|
state.reinstallTarget = null;
|
|
|
state.reinstallJobId = null;
|
|
|
state.reinstallInProgress = false;
|
|
|
state.reinstallExpectGeneratedPassword = false;
|
|
|
state.reinstallPasswordPendingAck = false;
|
|
|
byId("reinstall-form").reset();
|
|
|
byId("reinstall-root-password").value = "";
|
|
|
byId("reinstall-generated-password").textContent = "";
|
|
|
}
|
|
|
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;
|
|
|
byId("create-form").reset();
|
|
|
fillSshKeyCards(state.sshKeys);
|
|
|
byId("vm-root-password").value = "";
|
|
|
byId("template-import").open = !!state.templateImportJobId;
|
|
|
showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板。查询会自动更新;若中断,可点击“导入模板”继续查看。" : "");
|
|
|
showError("template-import-error", "");
|
|
|
showError("create-error", "");
|
|
|
updateCreateSource();
|
|
|
openModal("create-modal");
|
|
|
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 openReinstall(vm) {
|
|
|
if (readSavedReinstallJob()) {
|
|
|
resumeReinstallJob();
|
|
|
toast("此标签页已有重装任务,已恢复任务状态;请不要重复提交。", "info");
|
|
|
return;
|
|
|
}
|
|
|
byId("reinstall-form").reset();
|
|
|
fillSshKeyCards(state.sshKeys);
|
|
|
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-close-top").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 || "请输入完整的虚拟机名称";
|
|
|
openModal("reinstall-modal");
|
|
|
state.reinstallTarget = vm;
|
|
|
void loadTemplates().catch((error) => showError("reinstall-error", `无法加载重装模板:${error.message}`));
|
|
|
void loadSshKeys().catch((error) => showError("reinstall-error", `无法读取已保存公钥:${error.message}。请稍后重试,或选择密码登录。`));
|
|
|
}
|
|
|
|
|
|
function resumeReinstallJob() {
|
|
|
const saved = readSavedReinstallJob();
|
|
|
if (!saved || state.activeModal) 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", "正在查询已有重装任务…");
|
|
|
openModal("reinstall-modal");
|
|
|
state.reinstallTarget = null;
|
|
|
state.reinstallJobId = saved.job_id;
|
|
|
state.reinstallExpectGeneratedPassword = Boolean(saved.expect_generated_password);
|
|
|
state.reinstallPasswordPendingAck = false;
|
|
|
state.reinstallInProgress = true;
|
|
|
byId("reinstall-close-top").disabled = true;
|
|
|
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-close-top").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", `确定对 ${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.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) {
|
|
|
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")));
|
|
|
byId("host-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true }));
|
|
|
byId("host-settings-mobile-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true }));
|
|
|
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("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", showVmWorkspace);
|
|
|
byId("update-back-button").addEventListener("click", leaveUpdateWorkspace);
|
|
|
byId("unlock-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true }));
|
|
|
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-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("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", () => {
|
|
|
closeModal();
|
|
|
void showSshKeysWorkspace();
|
|
|
});
|
|
|
}
|
|
|
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-button").addEventListener("click", async () => {
|
|
|
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;
|
|
|
}
|
|
|
if (!existingJobId && (!url || url.origin !== "https://repo.almalinux.org" || url.username || url.password || url.search || url.hash || !url.pathname.toLowerCase().endsWith(".qcow2"))) {
|
|
|
showError("template-import-error", "目前仅支持 repo.almalinux.org 上的 AlmaLinux 10 x86_64 GenericCloud qcow2 HTTPS 地址。");
|
|
|
return;
|
|
|
}
|
|
|
if (!existingJobId && !/^[a-f0-9]{64}$/.test(sha256)) {
|
|
|
showError("template-import-error", "请填写镜像发布方提供的 64 位 SHA-256 校验值。");
|
|
|
return;
|
|
|
}
|
|
|
const button = byId("template-import-button");
|
|
|
setButtonBusy(button, true, "正在检查后台导入…");
|
|
|
try {
|
|
|
let jobId = existingJobId;
|
|
|
if (!jobId) {
|
|
|
const started = await api("/api/v1/vm-templates/import", { method: "POST", body: { name, url: url.href, sha256 } });
|
|
|
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(String(completed?.template?.id || ""));
|
|
|
byId("template-import").open = false;
|
|
|
byId("template-name").value = "";
|
|
|
byId("template-url").value = "";
|
|
|
byId("template-sha256").value = "";
|
|
|
toast("云镜像模板已导入,请在系统模板中确认选择。", "success");
|
|
|
} catch (error) {
|
|
|
showTemplateImportStatus(state.templateImportJobId ? "暂时无法确认导入进度,任务可能仍在后台运行;稍后点击按钮继续查看。" : "");
|
|
|
showError("template-import-error", error.message);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
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 = String(data.get("guest_ssh_key_id") || "");
|
|
|
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", "请先选择或导入云镜像模板。");
|
|
|
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;
|
|
|
}
|
|
|
if (!body.guest_ssh_key_id) {
|
|
|
const requestedPassword = String(data.get("root_password") || "");
|
|
|
if (requestedPassword && (requestedPassword.length < 12 || requestedPassword.length > 128)) {
|
|
|
showError("create-error", "自行设置的初始 root 密码需为 12 至 128 个字符;留空将自动生成强密码。");
|
|
|
return;
|
|
|
}
|
|
|
if (requestedPassword) body.root_password = requestedPassword;
|
|
|
}
|
|
|
} else {
|
|
|
body.iso = String(data.get("iso") || "");
|
|
|
if (!body.network || !body.iso) {
|
|
|
showError("create-error", "请先选择可用的虚拟网络或网桥,以及 ISO 镜像。");
|
|
|
return;
|
|
|
}
|
|
|
}
|
|
|
data.delete("root_password");
|
|
|
byId("vm-root-password").value = "";
|
|
|
setButtonBusy(button, true, "正在创建…");
|
|
|
try {
|
|
|
const autoPassword = source === "cloud" && !body.guest_ssh_key_id && !body.root_password;
|
|
|
const createdVm = await api("/api/v1/vms", { method: "POST", body });
|
|
|
closeModal();
|
|
|
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 = "";
|
|
|
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", "请先选择已导入的云镜像模板。若列表为空,请在“创建虚拟机”窗口先导入模板。");
|
|
|
return;
|
|
|
}
|
|
|
if (selectedKeyId && (rootPassword || !state.sshKeys.some((key) => String(key.id) === selectedKeyId))) {
|
|
|
showError("reinstall-error", "所选公钥已不可用或与密码设置冲突,请刷新公钥列表并重试。");
|
|
|
return;
|
|
|
}
|
|
|
if (rootPassword && (rootPassword.length < 12 || rootPassword.length > 128)) {
|
|
|
showError("reinstall-error", "初始 root 密码需要 12 至 128 个字符。");
|
|
|
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);
|
|
|
else if (rootPassword) body.root_password = rootPassword;
|
|
|
state.reinstallInProgress = true;
|
|
|
state.reinstallExpectGeneratedPassword = !selectedKeyId && !rootPassword;
|
|
|
byId("reinstall-close-top").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-close-top").disabled = false;
|
|
|
byId("reinstall-cancel").disabled = false;
|
|
|
showError("reinstall-error", error.message);
|
|
|
} finally {
|
|
|
delete body.root_password;
|
|
|
byId("reinstall-root-password").value = "";
|
|
|
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) {
|
|
|
closeModal();
|
|
|
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();
|
|
|
closeModal();
|
|
|
} 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-close-top").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();
|
|
|
closeModal();
|
|
|
});
|
|
|
|
|
|
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() {
|
|
|
if (state.activeModal?.id === "reinstall-modal" && state.reinstallPasswordPendingAck) {
|
|
|
toast("请先保存 root 密码,再点击“已保存密码,完成”确认清除。", "error");
|
|
|
return;
|
|
|
}
|
|
|
if (state.activeModal?.id === "reinstall-modal" && state.reinstallInProgress) {
|
|
|
toast("重装正在进行,请保持此窗口打开,以免错过一次性显示的 root 密码。", "error");
|
|
|
return;
|
|
|
}
|
|
|
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();
|