Move VM actions into detail view and show host region

main
admin 2 months ago
parent c83e17cd46
commit ff29462f2a

@ -42,11 +42,13 @@ PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m uvicorn virsh_panel.app:create_app
1. 通过你的 HTTPS 域名打开面板,使用启动终端输出中的一次性令牌填写 MariaDB 的地址、端口、已有数据库名、专用账号和密码。数据库账号至少需要在该数据库中建表及读写权限;连接失败时不会保存配置。当前数据库连接尚未提供 TLS 参数,数据库请放在面板本机或可信内网,不要将其端口暴露公网。
2. 使用同一个令牌创建面板管理员。创建完成后令牌失效,管理员密码只保存为密码哈希。
3. 在网页填写 B 的 IP/DNS、SSH 端口、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。口令只在当前面板进程的内存中用于解锁,不写入数据库、磁盘或浏览器存储;面板重启后,登录网页并在“解锁宿主机 SSH 私钥”页面重新输入。
3. 在网页填写 B 的 IP/DNS、SSH 端口、虚拟机地区、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。地区是这台宿主机上虚拟机共用的展示标签,可留空;它不影响 SSH 连接或已导入的模板。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。口令只在当前面板进程的内存中用于解锁,不写入数据库、磁盘或浏览器存储;面板重启后,登录网页并在“解锁宿主机 SSH 私钥”页面重新输入。
4. 点击“扫描主机指纹”,再通过 B 的可信控制台运行 `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` 独立核对;确认后在网页测试、保存。保存前会重扫并测试 SSH 与 libvirt API,失败不会覆盖现有连接。
宿主机私钥和配置加密保存在 MariaDB。OpenSSH 连接时需要读取私钥文件,Linux 上面板会将其临时还原到权限为 `0700` 的 `/dev/shm` 内存文件系统目录;面板关闭时清除。`data/runtime-wrappers/` 只包含不带密钥的启动包装器。面板仅支持单个 Uvicorn worker;多 worker 会导致各自 SSH 解锁状态不一致。
虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。
磁盘目录和 ISO 目录填写的是 **B 宿主机**上已存在的绝对路径,例如 `/home/kvm`、`/home/iso`,不是 A 面板服务器的路径;不需要提前手动创建 libvirt 存储池。点击“保存”时,面板会将这些现有目录定义为 libvirt `dir` 存储池并启动,作为内部管理机制;不会创建目录,也不会移动或删除现有文件。新建虚拟机的磁盘文件使用配置的磁盘目录下的 `<虚拟机名>.qcow2`,安装镜像使用配置的 ISO 目录下所选的 `.iso`;虚拟机 XML 通过绝对文件路径引用它们。“测试连接”不会修改宿主机,因此此时若目录尚未注册为池,可能仅显示资源警告。也可继续填写已有的 libvirt 存储池名称。若 B 的目录权限或 SELinux 策略阻止 libvirt 访问,保存会给出错误,需在 B 上修正权限或标签。
“默认虚拟网络或网桥”填写已有 libvirt 虚拟网络名称(如 `default`);若要使用 B 上已有的 Linux 网桥 `br0`,请填写 **`bridge:br0`**。单独填写 `br0` 表示名为 `br0` 的 libvirt 虚拟网络,不表示网桥。面板不会创建网桥;桥接网络的 IP、DHCP 与防火墙由你在 B 上配置。创建 VM 时,面板自动按 vCPU 数设置 virtio 网卡队列,例如 8 vCPU 对应 `driver.queues=8`;按 RHEL 10 建议最多设 16 队列。

@ -7,6 +7,8 @@ const state = {
csrfToken: "",
username: "",
vms: [],
selectedVmId: null,
vmActionInFlight: null,
resources: null,
templateLoad: null,
templateImportJobId: null,
@ -128,6 +130,7 @@ function showLogin() {
state.updateReturnView = null;
state.csrfToken = "";
state.vms = [];
state.selectedVmId = null;
clearHostPrivateKey();
byId("unlock-passphrase").value = "";
byId("update-access-token").value = "";
@ -226,6 +229,7 @@ function showHostView(hostConfig = { configured: false }) {
byId("host-back-button").hidden = !configured;
byId("host-address").value = configured ? (hostConfig.host || "") : "";
byId("host-port").value = configured ? (hostConfig.port || 22) : 22;
byId("host-region").value = configured ? (hostConfig.region || "") : "";
byId("host-storage-pool").value = configured ? (hostConfig.storage_pool || "default") : "default";
byId("host-iso-pool").value = configured ? (hostConfig.iso_pool || "iso") : "iso";
byId("host-network").value = configured ? (hostConfig.default_network || "default") : "default";
@ -294,7 +298,10 @@ async function initialize() {
}
function showVmWorkspace() {
state.selectedVmId = null;
byId("vm-workspace").hidden = false;
byId("vm-list-view").hidden = false;
byId("vm-detail-view").hidden = true;
byId("update-workspace").hidden = true;
byId("vm-navigation-button").classList.add("active");
byId("vm-navigation-button").setAttribute("aria-current", "page");
@ -503,6 +510,7 @@ function hostPayload() {
return {
host,
port,
region: byId("host-region").value.trim(),
private_key: privateKey,
private_key_passphrase: byId("host-private-key-passphrase").value,
host_key: scan.known_hosts_line,
@ -617,18 +625,22 @@ async function loadVMs(silent = false) {
if (state.loadingVMs || byId("dashboard-view").hidden) return;
state.loadingVMs = true;
const refreshButton = byId("refresh-button");
const detailRefreshButton = byId("vm-detail-refresh-button");
refreshButton.disabled = true;
detailRefreshButton.disabled = true;
try {
const result = await api("/api/v1/vms");
state.vms = Array.isArray(result?.items) ? result.items : [];
setConnection(true);
renderVMs();
syncVmDetailAfterRefresh();
} catch (error) {
setConnection(false);
if (!silent && !byId("dashboard-view").hidden) toast(error.message, "error");
if (!state.vms.length) renderVMs(true);
} finally {
refreshButton.disabled = false;
detailRefreshButton.disabled = false;
state.loadingVMs = false;
}
}
@ -660,6 +672,20 @@ function diskLabel(vm) {
return "—";
}
function vmSystemInfo(vm) {
if (vm.os_source === "iso") return { label: "安装镜像", value: String(vm.install_iso || "未识别") };
if (vm.os_source === "cloud_template") return { label: "系统镜像", value: String(vm.os_name || "未识别") };
return { label: "系统", value: String(vm.os_name || "未识别") };
}
function vmRegion(vm) {
return String(vm.region || "").trim() || "未设置";
}
function vmIp(vm) {
return String(vm.public_ip_cidr || "").trim() || "未获取";
}
function makeCell(row, className = "") {
const cell = document.createElement("td");
if (className) cell.className = className;
@ -678,6 +704,7 @@ function actionButton(label, handler, options = {}) {
const button = makeElement("button", `row-button ${options.variant || ""}`, label);
button.type = "button";
button.disabled = Boolean(options.disabled);
if (options.key) button.dataset.vmAction = options.key;
if (options.title) button.title = options.title;
button.addEventListener("click", handler);
return button;
@ -694,11 +721,14 @@ function renderVMs(connectionError = false) {
const query = byId("search-input").value.trim().toLocaleLowerCase();
const filter = byId("state-filter").value;
const filtered = all.filter((vm) => {
const matchesText = !query || String(vm.name || "").toLocaleLowerCase().includes(query) || String(vm.uuid || "").toLocaleLowerCase().includes(query) || String(vm.public_ip_cidr || "").toLocaleLowerCase().includes(query);
const matchesText = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.region, vm.os_name, vm.install_iso]
.some((value) => String(value || "").toLocaleLowerCase().includes(query));
return matchesText && (filter === "all" || stateCategory(vm.state) === filter);
});
text("inventory-count", `${filtered.length} 台虚拟机${filtered.length !== all.length ? ` · 共 ${all.length} 台` : ""}`);
const tbody = byId("vm-table-body");
const focusedVmId = document.activeElement?.classList.contains("vm-name-link")
? document.activeElement.dataset.vmUuid : null;
tbody.replaceChildren();
const empty = byId("empty-state");
empty.hidden = filtered.length !== 0;
@ -719,51 +749,141 @@ function renderVMs(connectionError = false) {
for (const vm of filtered) {
const uuid = String(vm.uuid || "");
const category = stateCategory(vm.state);
const running = category === "running";
const stopped = category === "stopped";
const row = document.createElement("tr");
const identity = makeElement("div", "vm-identity");
identity.append(makeElement("div", "vm-icon", "▣"));
const identityText = makeElement("div");
identityText.append(makeElement("span", "vm-name", vm.name || "未命名虚拟机"));
const nameButton = makeElement("button", "vm-name-link", vm.name || "未命名虚拟机");
nameButton.type = "button";
nameButton.disabled = !uuid;
nameButton.dataset.vmUuid = uuid;
nameButton.setAttribute("aria-label", `管理虚拟机 ${vm.name || uuid}`);
nameButton.addEventListener("click", () => openVmDetail(uuid));
identityText.append(nameButton);
identityText.append(makeElement("span", "vm-id", uuid || "UUID 未知"));
if (vm.public_ip_cidr) identityText.append(makeElement("span", "vm-public-ip", `公网 ${vm.public_ip_cidr}`));
identity.append(identityText);
makeCell(row).append(identity);
makeCell(row).append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state)));
const identityCell = makeCell(row);
identityCell.dataset.label = "虚拟机";
identityCell.append(identity);
const stateCell = makeCell(row);
stateCell.dataset.label = "状态";
stateCell.append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state)));
const regionCell = makeCell(row);
regionCell.dataset.label = "地区";
regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm)));
const system = vmSystemInfo(vm);
const systemCell = makeCell(row);
systemCell.dataset.label = system.label;
systemCell.append(makeElement("span", "vm-metadata", system.value));
const ipCell = makeCell(row);
ipCell.dataset.label = "已配置公网 IP";
ipCell.append(makeElement("span", "vm-metadata vm-ip", vmIp(vm)));
const spec = makeElement("div", "vm-spec");
spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`));
spec.append(makeElement("small", "", "计算资源"));
makeCell(row).append(spec);
makeCell(row).append(makeElement("span", "vm-spec", diskLabel(vm)));
const actions = makeElement("div", "row-actions");
const hasConsole = Number(vm.console_port) > 0;
actions.append(actionButton("控制台", () => void openConsole(vm), {
disabled: !running || !uuid || !hasConsole,
variant: "primary",
title: !running ? "虚拟机运行时可用" : hasConsole ? "打开 VNC 控制台" : "该虚拟机未配置 VNC 控制台",
}));
if (running) {
actions.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget)));
actions.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget)));
actions.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { variant: "danger" }));
actions.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { variant: "danger" }));
} else {
actions.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: !stopped || !uuid }));
}
if (vm.managed && vm.public_ip_cidr) {
actions.append(actionButton("重装", () => openReinstall(vm), {
disabled: !uuid,
variant: "danger",
title: "从云镜像模板重装,成功后自动删除旧系统盘",
}));
}
actions.append(actionButton("删除", () => openDelete(vm), { disabled: !stopped || !uuid, variant: "danger", title: stopped ? "删除虚拟机" : "请先关机再删除" }));
makeCell(row).append(actions);
const specCell = makeCell(row);
specCell.dataset.label = "规格";
specCell.append(spec);
const diskCell = makeCell(row);
diskCell.dataset.label = "磁盘";
diskCell.append(makeElement("span", "vm-spec", diskLabel(vm)));
tbody.append(row);
}
if (focusedVmId) {
const replacement = Array.from(tbody.querySelectorAll(".vm-name-link"))
.find((button) => button.dataset.vmUuid === focusedVmId);
replacement?.focus({ preventScroll: true });
}
}
function openVmDetail(uuid) {
const vm = state.vms.find((item) => String(item.uuid || "") === uuid);
if (!vm) {
toast("虚拟机已不在当前列表中,请刷新后重试。", "error");
return;
}
state.selectedVmId = uuid;
byId("vm-list-view").hidden = true;
byId("vm-detail-view").hidden = false;
renderVmDetail(vm);
window.scrollTo({ top: 0, behavior: "auto" });
byId("vm-detail-name").focus();
}
function syncVmDetailAfterRefresh() {
if (!state.selectedVmId || byId("vm-workspace").hidden || byId("vm-detail-view").hidden) return;
const vm = state.vms.find((item) => String(item.uuid || "") === state.selectedVmId);
if (!vm) {
showVmWorkspace();
toast("这台虚拟机已从宿主机移除,已返回列表。", "info");
byId("vm-list-title").focus();
return;
}
renderVmDetail(vm);
}
function renderVmDetail(vm) {
const category = stateCategory(vm.state);
const running = category === "running";
const stopped = category === "stopped";
const uuid = String(vm.uuid || "");
const busy = state.vmActionInFlight === uuid;
const system = vmSystemInfo(vm);
text("vm-detail-name", vm.name || "未命名虚拟机");
text("vm-detail-uuid", uuid || "UUID 未知");
text("vm-detail-state", stateLabel(vm.state));
byId("vm-detail-state").className = `state-pill ${category}`;
text("vm-detail-region", vmRegion(vm));
text("vm-detail-os-label", system.label);
text("vm-detail-os", system.value);
text("vm-detail-ip", vmIp(vm));
text("vm-detail-spec", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`);
text("vm-detail-disk", diskLabel(vm));
const hasConsole = Number(vm.console_port) > 0;
text("vm-detail-console-status", hasConsole ? (running ? "可连接" : "需先开机") : "未配置");
text("vm-detail-autostart", vm.autostart ? "已开启" : "未开启");
text("vm-detail-managed", vm.managed ? "面板创建" : "外部导入");
text("breadcrumb-current", vm.name || "虚拟机详情");
const primary = byId("vm-detail-primary-actions");
const danger = byId("vm-detail-danger-actions");
const focusedAction = document.activeElement?.dataset.vmAction || null;
primary.replaceChildren();
danger.replaceChildren();
primary.append(actionButton("打开 VNC 控制台", () => void openConsole(vm), {
disabled: busy || !running || !uuid || !hasConsole,
variant: "primary",
key: "console",
title: !running ? "虚拟机运行时可用" : hasConsole ? "打开 VNC 控制台" : "该虚拟机未配置 VNC 控制台",
}));
if (running) {
primary.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget), { disabled: busy, key: "shutdown" }));
primary.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget), { disabled: busy, key: "reboot" }));
danger.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { disabled: busy, variant: "danger", key: "poweroff" }));
danger.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { disabled: busy, variant: "danger", key: "reset" }));
} else {
primary.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: busy || !stopped || !uuid, key: "start" }));
}
if (vm.managed && vm.public_ip_cidr) {
danger.append(actionButton("重装系统", () => openReinstall(vm), {
disabled: busy || !uuid,
variant: "danger",
key: "reinstall",
title: "从云镜像模板重装,成功后自动删除旧系统盘",
}));
}
danger.append(actionButton("删除虚拟机", () => openDelete(vm), {
disabled: busy || !stopped || !uuid,
variant: "danger",
key: "delete",
title: stopped ? "删除虚拟机" : "请先关机再删除",
}));
if (focusedAction) {
const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]"))
.find((button) => button.dataset.vmAction === focusedAction && !button.disabled);
replacement?.focus({ preventScroll: true });
}
}
function resourceValue(item, kind) {
@ -955,6 +1075,7 @@ function openModal(id) {
function closeModal() {
if (!state.activeModal) return;
const returnFocus = state.lastFocus;
if (state.activeModal.id === "console-modal") disconnectConsole();
if (state.activeModal.id === "create-modal") {
byId("vm-guest-ssh-public-key").value = "";
@ -976,7 +1097,14 @@ function closeModal() {
state.deleteTarget = null;
state.confirmTarget = null;
document.body.style.overflow = "";
state.lastFocus?.focus?.();
if (returnFocus?.isConnected && returnFocus.getClientRects().length && !returnFocus.disabled) {
returnFocus.focus();
} else if (!byId("vm-workspace").hidden && !byId("vm-detail-view").hidden) {
const action = returnFocus?.dataset?.vmAction;
const replacement = action ? Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]"))
.find((button) => button.dataset.vmAction === action && !button.disabled) : null;
(replacement || byId("vm-detail-name")).focus();
}
}
function openCreate() {
@ -1169,7 +1297,11 @@ function openConfirm(vm, action) {
async function runAction(vm, action, button) {
const label = { start: "开机", shutdown: "关机", reboot: "重启", poweroff: "强制断电", reset: "强制重置" }[action] || action;
const focusAction = button?.dataset.vmAction || null;
if (state.vmActionInFlight === vm.uuid) return false;
state.vmActionInFlight = vm.uuid;
if (button) setButtonBusy(button, true);
if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh();
try {
await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/actions`, { method: "POST", body: { action } });
toast(`已向 ${vm.name || vm.uuid} 发送${label}指令。`, "success");
@ -1180,7 +1312,14 @@ async function runAction(vm, action, button) {
toast(`${label}失败:${error.message}`, "error");
return false;
} finally {
state.vmActionInFlight = null;
if (state.selectedVmId === vm.uuid) syncVmDetailAfterRefresh();
if (button?.isConnected) setButtonBusy(button, false);
if (focusAction && !state.activeModal && state.selectedVmId === vm.uuid && !byId("vm-detail-view").hidden) {
const replacement = Array.from(byId("vm-detail-view").querySelectorAll("[data-vm-action]"))
.find((item) => item.dataset.vmAction === focusAction && !item.disabled);
(replacement || byId("vm-detail-name")).focus();
}
}
}
@ -1358,7 +1497,7 @@ byId("host-back-button").addEventListener("click", () => {
});
byId("host-address").addEventListener("input", resetFingerprint);
byId("host-port").addEventListener("input", resetFingerprint);
for (const id of ["host-storage-pool", "host-iso-pool", "host-network"]) {
for (const id of ["host-region", "host-storage-pool", "host-iso-pool", "host-network"]) {
byId(id).addEventListener("input", markHostTestStale);
}
byId("host-private-key").addEventListener("input", () => {
@ -1495,6 +1634,11 @@ byId("update-apply-button").addEventListener("click", async () => {
});
byId("refresh-button").addEventListener("click", () => void loadVMs());
byId("vm-detail-refresh-button").addEventListener("click", () => void loadVMs());
byId("vm-detail-back-button").addEventListener("click", () => {
showVmWorkspace();
byId("search-input").focus();
});
byId("search-input").addEventListener("input", () => renderVMs());
byId("state-filter").addEventListener("change", () => renderVMs());
byId("create-button").addEventListener("click", openCreate);
@ -1817,6 +1961,10 @@ byId("delete-form").addEventListener("submit", async (event) => {
await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}?delete_disks=${deleteDisks}`, { method: "DELETE" });
closeModal();
toast(`${vm.name || vm.uuid} 已删除${deleteDisks ? ",磁盘已一并删除" : ""}。`, "success");
if (state.selectedVmId === vm.uuid) {
showVmWorkspace();
byId("vm-list-title").focus();
}
await loadVMs(true);
} catch (error) {
showError("delete-error", error.message);

@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#101d2c" />
<title>VirtPilot · 虚拟机管理</title>
<link rel="stylesheet" href="/static/styles.css?v=database-update-1" />
<script type="module" src="/static/app.js?v=database-update-1"></script>
<link rel="stylesheet" href="/static/styles.css?v=vm-detail-1" />
<script type="module" src="/static/app.js?v=vm-detail-1"></script>
</head>
<body>
<div id="boot-screen" class="boot-screen" role="status" aria-live="polite">
@ -129,6 +129,7 @@
<div class="form-grid">
<div class="field"><label for="host-address">宿主机地址 <span>*</span></label><input id="host-address" name="host" type="text" required maxlength="253" autocomplete="off" placeholder="例如 192.0.2.10" /></div>
<div class="field"><label for="host-port">SSH 端口 <span>*</span></label><input id="host-port" name="port" type="number" min="1" max="65535" value="22" required /></div>
<div class="field"><label for="host-region">虚拟机地区</label><input id="host-region" name="region" type="text" maxlength="64" autocomplete="off" placeholder="例如 中国香港 / 东京 / 洛杉矶" /><small>用于展示这台宿主机上的虚拟机所在地区;留空时显示“未设置”。</small></div>
<div class="field"><label for="host-username">SSH 用户</label><input id="host-username" type="text" value="root" disabled /></div>
<div class="field"><label for="host-storage-pool">虚拟机磁盘目录或存储池名</label><input id="host-storage-pool" name="storage_pool" type="text" maxlength="4096" value="default" required autocomplete="off" placeholder="例如 /home/kvm 或 default" /><small>可直接填写宿主机上的绝对路径,如 /home/kvm;也兼容现有 libvirt 存储池名称。</small></div>
<div class="field"><label for="host-iso-pool">ISO 目录或存储池名</label><input id="host-iso-pool" name="iso_pool" type="text" maxlength="4096" value="iso" required autocomplete="off" placeholder="例如 /home/iso 或 iso" /><small>可直接填写宿主机上的绝对路径,如 /home/iso;不是面板服务器的路径。</small></div>
@ -204,7 +205,8 @@
<main class="content">
<div id="vm-workspace">
<div class="page-heading"><div><span class="eyebrow">VIRTUAL MACHINES</span><h1>虚拟机管理</h1><p>查看状态、管理电源,并通过浏览器接入控制台。</p></div><div class="heading-actions"><button id="refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button><button id="create-button" class="button button-primary" type="button"><span aria-hidden="true">+</span> 创建虚拟机</button></div></div>
<div id="vm-list-view">
<div class="page-heading"><div><span class="eyebrow">VIRTUAL MACHINES</span><h1 id="vm-list-title" tabindex="-1">虚拟机管理</h1><p>查看虚拟机信息;点击名称进入管理页面执行操作。</p></div><div class="heading-actions"><button id="refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button><button id="create-button" class="button button-primary" type="button"><span aria-hidden="true">+</span> 创建虚拟机</button></div></div>
<div id="resource-warning" class="resource-warning" role="alert" hidden></div>
<div class="overview-grid" aria-label="虚拟机概览">
@ -214,12 +216,27 @@
</div>
<section class="inventory-panel" aria-labelledby="inventory-title">
<div class="panel-heading"><div><h2 id="inventory-title">虚拟机列表</h2><p id="inventory-count">正在加载…</p></div><div class="panel-tools"><label class="search-box"><span aria-hidden="true">⌕</span><span class="sr-only">搜索虚拟机</span><input id="search-input" type="search" placeholder="搜索名称或 UUID" /></label><select id="state-filter" aria-label="按状态筛选"><option value="all">全部状态</option><option value="running">运行中</option><option value="stopped">已关机</option><option value="other">其他状态</option></select></div></div>
<div class="table-scroll"><table><thead><tr><th>虚拟机</th><th>状态</th><th>规格</th><th>磁盘</th><th class="actions-heading">操作</th></tr></thead><tbody id="vm-table-body"></tbody></table></div>
<div class="panel-heading"><div><h2 id="inventory-title">虚拟机列表</h2><p id="inventory-count">正在加载…</p></div><div class="panel-tools"><label class="search-box"><span aria-hidden="true">⌕</span><span class="sr-only">搜索虚拟机</span><input id="search-input" type="search" placeholder="搜索名称、地区、系统或 IP" /></label><select id="state-filter" aria-label="按状态筛选"><option value="all">全部状态</option><option value="running">运行中</option><option value="stopped">已关机</option><option value="other">其他状态</option></select></div></div>
<div class="table-scroll"><table class="vm-table"><thead><tr><th>虚拟机</th><th>状态</th><th>地区</th><th>系统 / 安装镜像</th><th>已配置公网 IP</th><th>规格</th><th>磁盘</th></tr></thead><tbody id="vm-table-body"></tbody></table></div>
<div id="empty-state" class="empty-state" hidden><div class="empty-icon" aria-hidden="true">▦</div><h3 id="empty-title">还没有虚拟机</h3><p id="empty-description">点击右上角“创建虚拟机”开始。</p></div>
</section>
<div class="footer-note">状态每 15 秒自动更新 · 操作会发送至远端 libvirt 宿主机</div>
</div>
<section id="vm-detail-view" class="vm-detail-view" aria-labelledby="vm-detail-name" hidden>
<button id="vm-detail-back-button" class="button button-ghost vm-detail-back" type="button">← 返回虚拟机列表</button>
<div class="page-heading vm-detail-heading"><div><span class="eyebrow">VIRTUAL MACHINE DETAILS</span><h1 id="vm-detail-name" tabindex="-1">虚拟机</h1><p id="vm-detail-uuid" class="vm-detail-uuid"></p></div><div class="heading-actions"><span id="vm-detail-state" class="state-pill other">未知</span><button id="vm-detail-refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button></div></div>
<div class="vm-detail-grid">
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-info-title"><div class="panel-heading"><div><h2 id="vm-detail-info-title">虚拟机信息</h2><p>状态和配置每 15 秒自动更新;IP 是面板记录的配置,不代表系统已联网。</p></div></div><dl class="vm-detail-facts">
<div><dt>地区</dt><dd id="vm-detail-region">未设置</dd></div><div><dt id="vm-detail-os-label">系统</dt><dd id="vm-detail-os">未识别</dd></div>
<div><dt>已配置公网 IP</dt><dd id="vm-detail-ip">未获取</dd></div><div><dt>计算规格</dt><dd id="vm-detail-spec">—</dd></div>
<div><dt>磁盘</dt><dd id="vm-detail-disk">—</dd></div><div><dt>VNC 控制台</dt><dd id="vm-detail-console-status">未配置</dd></div>
<div><dt>开机自启</dt><dd id="vm-detail-autostart">未开启</dd></div><div><dt>管理来源</dt><dd id="vm-detail-managed">—</dd></div>
</dl></section>
<div class="vm-detail-operations"><section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions"></div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>强制操作可能丢失未保存的数据;重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions"></div></section></div>
</div>
</section>
</div>
<div id="update-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">PANEL UPDATE</span><h1>网站更新</h1><p>从当前项目的私有 Gitea 仓库检查并安装新版本。</p></div><button id="update-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="update-grid">

@ -111,18 +111,20 @@ input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,
.search-box input,.panel-tools select{height:37px;border:1px solid #e0e6ec;border-radius:8px;background:#fff;color:#516075;font-size:12px}
.search-box input{width:220px;padding:0 12px 0 34px}.search-box input::placeholder{color:#a4afbb}.panel-tools select{padding:0 29px 0 11px}
.table-scroll{overflow-x:auto;min-height:100px}
table{border-collapse:collapse;width:100%;min-width:850px}
table{border-collapse:collapse;width:100%;min-width:850px}.vm-table{min-width:1060px}.vm-table th,.vm-table td{padding-left:15px;padding-right:15px}
thead{background:#fbfcfe}th{height:47px;text-align:left;font-size:10px;letter-spacing:.05em;color:#9ba8b7;text-transform:uppercase;font-weight:800;padding:0 24px}
th.actions-heading{text-align:right;padding-right:28px}
td{height:83px;border-top:1px solid #edf1f5;padding:15px 24px;font-size:12px;color:#607087}
tbody tr:hover{background:#fcfefe}
.vm-identity{display:flex;align-items:center;gap:12px;min-width:160px}.vm-icon{width:38px;height:38px;border-radius:10px;background:#e9f8f8;color:#239eaa;display:flex;align-items:center;justify-content:center;font-size:19px;flex:none}.vm-name{display:block;color:#25384e;font-size:13px;font-weight:800;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-id{display:block;color:#a6b1bf;font-size:10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;margin-top:6px;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.vm-public-ip{display:block;color:#16868f;font-size:10px;font-weight:700;margin-top:5px;white-space:nowrap}
.vm-name-link{display:block;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;padding:2px 0;color:#25384e;font-size:13px;font-weight:800;text-align:left;text-decoration:underline;text-decoration-color:transparent;text-underline-offset:3px;cursor:pointer}.vm-name-link:not(:disabled):hover,.vm-name-link:not(:disabled):focus-visible{color:#118e98;text-decoration-color:currentColor}.vm-metadata{display:block;max-width:205px;color:#53647a;line-height:1.5;overflow-wrap:anywhere}.vm-ip{color:#16868f;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;white-space:nowrap}
.state-pill{display:inline-flex;align-items:center;gap:7px;padding:6px 9px;border-radius:6px;font-size:11px;font-weight:800;background:#f1f3f6;color:#758499;white-space:nowrap}.state-pill:before{content:"";width:6px;height:6px;background:currentColor;border-radius:50%}.state-pill.running{background:#e7f8ef;color:#20a46f}.state-pill.stopped{background:#f2f4f7;color:#8290a3}.state-pill.other{background:#fff4e5;color:#b98129}
.vm-spec{color:#53647a;white-space:nowrap}.vm-spec strong{color:#283a50;font-weight:700}.vm-spec small{display:block;color:#a2aeb9;font-size:10px;margin-top:5px}
.row-actions{display:flex;align-items:center;justify-content:flex-end;gap:5px;white-space:nowrap}.row-button{border:1px solid transparent;background:transparent;color:#577083;border-radius:7px;padding:7px 8px;min-height:31px;font-size:11px;font-weight:700}.row-button:not(:disabled):hover{background:#e8f7f7;color:#117f88}.row-button.primary{background:#e7f7f7;color:#118e98}.row-button.danger{color:#bf6470}.row-button.danger:not(:disabled):hover{background:#fff0f1;color:#ba3a49}
.empty-state{text-align:center;padding:65px 20px 72px}.empty-icon{margin:0 auto 16px;width:54px;height:54px;display:flex;align-items:center;justify-content:center;border-radius:16px;background:#eaf7f7;color:#17a3aa;font-size:28px}.empty-state h3{font-size:16px;color:#34465a;margin:0 0 8px}.empty-state p{font-size:12px;color:#a0aebe;margin:0}
.footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px}
.vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-uuid{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef}
.modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)}
.modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)}
.create-modal{width:min(100%,720px)}
@ -146,8 +148,11 @@ tbody tr:hover{background:#fcfefe}
@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.host-settings-mobile{display:inline-flex}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}}
@media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}}
@media(max-width:960px){.update-grid{grid-template-columns:1fr}}
@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}}
@media(max-width:740px){.login-layout{display:block;min-height:100vh}.login-art{display:none}.login-form-side{min-height:100vh;padding:32px 25px}.login-mobile-brand{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:800;margin-bottom:70px}.login-card h2{font-size:29px}.page-heading{align-items:flex-start;flex-direction:column;gap:20px}.heading-actions{width:100%}.heading-actions .button{flex:1}.overview-grid{gap:9px}.stat-card{min-height:121px;padding:16px}.stat-card>strong{font-size:25px}.stat-top{font-size:10px}.stat-icon{width:27px;height:27px;font-size:12px}.stat-card>small{font-size:9px}.panel-heading{align-items:flex-start;flex-direction:column;padding:19px}.panel-tools{width:100%}.search-box{flex:1}.search-box input{width:100%}.footer-note{text-align:left}.console-toolbar{align-items:flex-start}.console-tools{flex-wrap:wrap;justify-content:flex-end}.console-tools .button{font-size:10px}}
@media(max-width:740px){.vm-table{min-width:0}.vm-table thead{display:none}.vm-table tbody{display:grid;gap:12px;padding:12px}.vm-table tr{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid #e4ebf0;border-radius:10px;overflow:hidden}.vm-table td{display:block;min-width:0;height:auto;border:0;padding:12px 14px}.vm-table td:first-child{grid-column:1/-1;border-bottom:1px solid #edf1f5}.vm-table td:not(:first-child):before{content:attr(data-label);display:block;color:#9ba8b7;font-size:10px;font-weight:800;margin-bottom:7px}.vm-table .vm-metadata{max-width:none}.vm-table .vm-ip{white-space:normal}.vm-detail-facts{padding:4px 17px 12px}.vm-detail-actions{padding:16px 19px 19px}}
@media(max-width:740px){.setup-layout{display:block}.setup-intro{min-height:0;padding:28px 25px}.setup-brand{margin:0 0 38px}.setup-intro h1{font-size:31px;margin:11px 0}.setup-intro p{font-size:12px;margin-bottom:24px}.setup-steps{margin-top:0}.setup-form-side{padding:36px 25px 55px}.setup-card h2{font-size:27px}.host-side-stack{grid-template-columns:1fr}.host-heading{align-items:flex-start;flex-direction:column}.host-topbar{height:65px}.host-content{padding-top:27px}.host-card{padding:20px}}
@media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}}
@media(max-width:510px){.topbar-right{flex-wrap:wrap;justify-content:flex-end;gap:2px}.host-settings-mobile{font-size:10px!important;padding:5px!important;min-height:28px!important}.topbar-user .avatar{display:none}.update-versions{grid-template-columns:1fr}}
@media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}}

@ -2,6 +2,7 @@
from __future__ import annotations
import re
import stat
import sys
import threading
@ -113,10 +114,10 @@ class FakeVMService:
return {**self.vm, "name": spec["name"]}
def reinstall_cloud_vm(self, vm_id, template_volume_name, *,
ssh_public_key="", root_password_hash=None,
os_name=None, ssh_public_key="", root_password_hash=None,
progress=None):
self.calls.append(("reinstall_cloud_vm", vm_id, template_volume_name,
ssh_public_key, root_password_hash))
ssh_public_key, root_password_hash, os_name))
self.reinstall_started.set()
if self.reinstall_gate is not None:
assert self.reinstall_gate.wait(timeout=5), "test did not release reinstall job"
@ -183,6 +184,7 @@ class FakeRemoteManager:
"storage_pool": staged.profile.storage_pool,
"iso_pool": staged.profile.iso_pool,
"default_network": staged.profile.default_network,
"region": staged.profile.region,
"libvirt_uri": "qemu+ssh://root@vp-managed/system?no_tty=1&command=/fake/ssh-wrapper",
"ssh_target": "vp-managed", "ssh_config_file": "/fake/config",
"ssh_known_hosts_file": "/fake/known_hosts",
@ -309,7 +311,7 @@ def configure_reinstall_case(web):
template_id = template_id_for(scope, "d" * 64)
volume_name = template_volume_name(template_id)
TemplateStore(state.data_dir).add(
scope, {"id": template_id, "volume_name": volume_name},
scope, {"id": template_id, "volume_name": volume_name, "name": "AlmaLinux 10"},
)
service.vm.update({
"name": "cloud-vm", "managed": True, "public_ip_cidr": "8.8.8.18/24",
@ -404,6 +406,21 @@ def test_host_scan_test_save_and_secret_is_never_returned(web):
("list_vms",), ("resources",)]
def test_host_region_is_returned_with_host_and_vms(web):
client, _, token, _service, _manager, _ = web
csrf = setup_admin(client, token)
body = {**HOST_BODY, "region": "中国香港"}
headers = {"X-CSRF-Token": csrf}
assert client.put("/api/v1/host", json=body, headers=headers).json()["region"] == "中国香港"
assert client.get("/api/v1/host").json()["region"] == "中国香港"
assert client.get("/api/v1/vms").json()["items"][0]["region"] == "中国香港"
assert client.get(f"/api/v1/vms/{VM_ID}").json()["region"] == "中国香港"
assert client.post("/api/v1/vms", json=CREATE_BODY,
headers=headers).json()["region"] == "中国香港"
assert client.put("/api/v1/host", json={**body, "region": "a\nline"},
headers=headers).status_code == 422
def test_private_key_passphrase_reaches_host_profile_but_is_never_echoed(web):
client, _, token, _, manager, _ = web
csrf = setup_admin(client, token)
@ -654,6 +671,7 @@ def test_cloud_template_import_job_and_create_dispatch(web):
assert created.json()["name"] == "cloud-vm"
expected_spec = {key: value for key, value in cloud_body.items()
if key not in {"source", "template_id"}}
expected_spec["os_name"] = "AlmaLinux 10"
assert ("create_cloud_vm", expected_spec, volume_name) in service.calls
assert ("create_vm", expected_spec) not in service.calls
@ -741,6 +759,7 @@ def test_reinstall_auto_password_remains_available_until_ack_and_is_never_persis
assert len(service_calls) == 1
assert service_calls[0][1:4] == (VM_ID, volume_name, "")
assert service_calls[0][4].startswith("$6$")
assert service_calls[0][5] == "AlmaLinux 10"
assert generated_password not in repr(service.calls)
second = client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers)
@ -780,7 +799,8 @@ def test_reinstall_key_mode_has_no_generated_password(web):
completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf)
assert completed["status"] == "succeeded"
assert "generated_password" not in completed
assert ("reinstall_cloud_vm", VM_ID, volume_name, public_key, None) in service.calls
assert ("reinstall_cloud_vm", VM_ID, volume_name, public_key, None,
"AlmaLinux 10") in service.calls
def test_reinstall_requires_exact_name_and_blocks_duplicate_or_lifecycle_actions(web):
@ -845,10 +865,11 @@ def test_static_assets_and_security_headers(web):
assert page.status_code == 200 and "text/html" in page.headers["content-type"]
assert page.headers["cache-control"] == "no-store"
assert "frame-ancestors 'none'" in page.headers["content-security-policy"]
assert "/static/app.js?v=database-update-1" in page.text
assert "/static/styles.css?v=database-update-1" in page.text
script = client.get("/static/app.js?v=database-update-1")
style = client.get("/static/styles.css?v=database-update-1")
script_url = re.search(r'src="(/static/app\.js\?v=[^"]+)"', page.text)
style_url = re.search(r'href="(/static/styles\.css\?v=[^"]+)"', page.text)
assert script_url is not None and style_url is not None
script = client.get(script_url.group(1))
style = client.get(style_url.group(1))
assert script.status_code == 200 and script.headers["cache-control"] == "no-store"
assert style.status_code == 200 and style.headers["cache-control"] == "no-store"
assert "function updateCreateSource()" in script.text

@ -3,6 +3,7 @@
from __future__ import annotations
import base64
import json
import os
import stat
import struct
@ -157,7 +158,7 @@ def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_pa
profile = HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], storage_pool="/home/kvm",
iso_pool="/home/iso", default_network="bridge:br0",
iso_pool="/home/iso", default_network="bridge:br0", region="东京",
)
staged = first.stage(profile, scan["fingerprint"])
assert first.test(staged)["libvirt"] == "available"
@ -174,11 +175,21 @@ def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_pa
)
assert second.current()["storage_pool"] == "/home/kvm"
assert second.current()["default_network"] == "bridge:br0"
assert second.current()["region"] == "东京"
assert (second._current_generation() / "id_private").read_text() == PRIVATE_KEY
assert not list(data_dir.rglob("id_private"))
second.close()
assert not list(runtime_parent.rglob("id_private"))
legacy = json.loads(store.records[("host", "current")])
legacy["metadata"].pop("region")
store.records[("host", "current")] = json.dumps(legacy)
third = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh,
)
assert third.current()["region"] == ""
third.close()
def test_encrypted_host_key_is_locked_again_after_process_restart(tmp_path: Path):
store = MemoryStore()

@ -601,6 +601,18 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(len(self.backend.define_xmls), 1)
self.assertEqual(self.backend.opened, self.backend.closed)
def test_unmanaged_vm_does_not_claim_an_os_or_ip(self):
vm = self.service.create_vm(self.spec())
domain = self.backend.domains[0]
for root in (domain.live_root, domain.inactive_root):
root.remove(root.find("metadata"))
listed = self.service.get_vm(vm["uuid"])
self.assertFalse(listed["managed"])
self.assertIsNone(listed["os_name"])
self.assertEqual(listed["os_source"], "unknown")
self.assertIsNone(listed["install_iso"])
self.assertIsNone(listed["public_ip_cidr"])
def test_installer_reboot_stops_guest_and_next_start_uses_unmounted_iso(self):
vm = self.service.create_vm(self.spec())
domain = self.backend.domains[0]
@ -707,7 +719,11 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(balloon.get("freePageReporting"), "on")
self.assertGreater(int(balloon.find("stats").get("period")), 0)
self.assertEqual(root.find("./metadata/{urn:virsh-panel:1}managed").attrib,
{"version": "2", "disk-volume": "web.qcow2"})
{"version": "2", "disk-volume": "web.qcow2",
"os-source": "iso", "install-iso": iso_name})
self.assertIsNone(vm["os_name"])
self.assertEqual(vm["os_source"], "iso")
self.assertEqual(vm["install_iso"], iso_name)
service.action(vm["uuid"], "shutdown")
self.assertEqual(service.delete_vm(vm["uuid"], True)["deleted_disks"],
@ -1169,7 +1185,7 @@ class VMServiceTests(unittest.TestCase):
def test_cloud_vm_clones_template_and_uses_nonboot_seed_iso(self):
service = self.cloud_service()
created = self.create_cloud_vm(service, self.cloud_spec())
created = self.create_cloud_vm(service, self.cloud_spec(os_name="AlmaLinux 10"))
self.assertEqual(created["state"], "running")
self.assertEqual(created["name"], "cloud-vm")
@ -1205,6 +1221,10 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(managed.get("seed-volume"), seed_name)
self.assertEqual(managed.get("public-ip-cidr"), "8.8.8.18/24")
self.assertEqual(created["public_ip_cidr"], "8.8.8.18/24")
self.assertEqual(managed.get("os-source"), "cloud_template")
self.assertEqual(managed.get("os-name"), "AlmaLinux 10")
self.assertEqual(created["os_name"], "AlmaLinux 10")
self.assertEqual(created["os_source"], "cloud_template")
self.assertEqual(self.backend.opened, self.backend.closed)
def test_cloud_vm_delete_disks_removes_clone_and_seed_but_keeps_template(self):
@ -1328,12 +1348,14 @@ class VMServiceTests(unittest.TestCase):
old_disk.delete = delete_after_new_start
result = service.reinstall_cloud_vm(
created["uuid"], TEMPLATE_NAME,
os_name="AlmaLinux 10.2",
ssh_public_key=spec["guest_ssh_public_key"],
)
self.assertEqual(result["vm"]["uuid"], created["uuid"])
self.assertEqual(result["vm"]["state"], "running")
self.assertEqual(result["vm"]["public_ip_cidr"], spec["public_ip_cidr"])
self.assertEqual(result["vm"]["os_name"], "AlmaLinux 10.2")
self.assertFalse(result.get("warning"))
self.assertEqual(self.backend.shutdown_calls, 1)
self.assertNotIn("cloud-vm.qcow2", pool.volumes)

@ -5,6 +5,7 @@ from __future__ import annotations
import base64
import hashlib
import itertools
import json
import shutil
import stat
import struct
@ -70,7 +71,7 @@ def make_manager(tmp_path: Path, runner: Runner) -> RemoteHostManager:
def make_profile(
scanned: dict, *, key: str = PRIVATE_KEY, host: str = "host.example",
passphrase: str = "", storage_pool: str = "images", iso_pool: str = "iso",
default_network: str = "default",
default_network: str = "default", region: str = "",
) -> HostProfile:
return HostProfile(
host=host,
@ -81,9 +82,24 @@ def make_profile(
storage_pool=storage_pool,
iso_pool=iso_pool,
default_network=default_network,
region=region,
)
def test_region_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(make_profile(scanned, region="中国香港"), scanned["fingerprint"])
manager.test(staged)
assert manager.commit(staged)["region"] == "中国香港"
profile_path = staged.path / "profile.json"
legacy = json.loads(profile_path.read_text(encoding="utf-8"))
legacy.pop("region")
profile_path.write_text(json.dumps(legacy), encoding="utf-8")
assert manager.current()["region"] == ""
class FakeAgent:
sequence = itertools.count()

@ -104,6 +104,8 @@ class HostBody(HostScanBody):
storage_pool: str = Field(default="default", min_length=1, max_length=4096)
iso_pool: str = Field(default="iso", min_length=1, max_length=4096)
default_network: str = Field(default="default", min_length=1, max_length=128)
region: str = Field(default="", max_length=64,
pattern=r"^[^\x00-\x1f\x7f]*$")
def profile(self) -> HostProfile:
return HostProfile(
@ -115,6 +117,7 @@ class HostBody(HostScanBody):
storage_pool=self.storage_pool,
iso_pool=self.iso_pool,
default_network=self.default_network,
region=self.region,
)
@ -178,7 +181,8 @@ def _public_host(profile: dict | None) -> dict:
"iso_pool", "default_network", "private_key_configured",
"private_key_encrypted", "key_locked",
)
return {"configured": True, **{key: profile[key] for key in keys if key in profile}}
return {"configured": True, **{key: profile[key] for key in keys if key in profile},
"region": profile.get("region", "")}
def _peer(request: Request) -> str:
@ -839,11 +843,14 @@ def create_app(
@app.get("/api/v1/vms")
def list_vms(_session: Session = Depends(require_session)):
return {"items": current_service().list_vms()}
profile = current_profile()
region = profile.get("region", "")
return {"items": [{**vm, "region": region} for vm in new_service(profile).list_vms()]}
@app.get("/api/v1/vms/{vm_id}")
def get_vm(vm_id: str, _session: Session = Depends(require_session)):
return current_service().get_vm(vm_id)
profile = current_profile()
return {**new_service(profile).get_vm(vm_id), "region": profile.get("region", "")}
@app.post("/api/v1/vms", status_code=201)
def create_vm(body: CreateISOBody | CreateCloudBody,
@ -852,6 +859,7 @@ def create_app(
# the VM. Otherwise an update can restart the web process mid-create.
with reinstall_lock:
forbid_long_job_during_update()
profile = current_profile()
if isinstance(body, CreateCloudBody):
public_key = body.guest_ssh_public_key.strip()
root_password = (body.root_password.get_secret_value()
@ -867,21 +875,21 @@ def create_app(
password_hash = hash_root_password(root_password)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
profile = current_profile()
record = templates.get(template_scope(profile), body.template_id)
spec = body.model_dump(exclude={"source", "template_id", "root_password"})
spec["os_name"] = record.get("name")
spec["guest_ssh_public_key"] = public_key
if password_hash is not None:
spec["root_password_hash"] = password_hash
vm = new_service(profile).create_cloud_vm(spec, record["volume_name"])
else:
vm = current_service().create_vm(body.model_dump(exclude={"source"}))
vm = new_service(profile).create_vm(body.model_dump(exclude={"source"}))
LOG.info("vm created: uuid=%s admin=%s", vm.get("uuid"), _session.username)
return vm
return {**vm, "region": profile.get("region", "")}
def run_reinstall(
job_id: str, profile: dict, scope: str, vm_id: str,
template_volume_name: str, ssh_public_key: str,
template_volume_name: str, template_name: str | None, ssh_public_key: str,
root_password_hash: str | None, generated_password: str | None,
) -> None:
def report_progress(phase: str) -> None:
@ -900,6 +908,7 @@ def create_app(
save_job("reinstall_job", job_id, reinstall_jobs[job_id])
result = new_service(profile).reinstall_cloud_vm(
vm_id, template_volume_name,
os_name=template_name,
ssh_public_key=ssh_public_key,
root_password_hash=root_password_hash,
progress=report_progress,
@ -987,7 +996,7 @@ def create_app(
try:
reinstall_executor.submit(
run_reinstall, job_id, profile, scope, normalized_id,
record["volume_name"], ssh_public_key, root_password_hash,
record["volume_name"], record.get("name"), ssh_public_key, root_password_hash,
generated_password,
)
except RuntimeError as exc:

@ -45,6 +45,7 @@ from .remote_host import (
_validate_pool_selector,
_validate_port,
_validate_private_key,
_validate_region,
_write_private,
)
from .ssh_agent import SSHAgentSession, _ASKPASS_SOURCE
@ -592,6 +593,7 @@ class DatabaseRemoteHostManager(RemoteHostManager):
storage_pool = _validate_pool_selector(metadata["storage_pool"], "磁盘池")
iso_pool = _validate_pool_selector(metadata["iso_pool"], "ISO 池")
default_network = _validate_network_selector(metadata["default_network"])
region = _validate_region(metadata.get("region", ""))
private_key = _validate_private_key(record["private_key"])
known_hosts = record["known_hosts"].strip()
key_type, encoded = _key_parts(known_hosts)
@ -651,7 +653,7 @@ class DatabaseRemoteHostManager(RemoteHostManager):
_write_private(generation / "profile.json", json.dumps(
{**metadata, "host": host, "port": port,
"storage_pool": storage_pool, "iso_pool": iso_pool,
"default_network": default_network},
"default_network": default_network, "region": region},
ensure_ascii=False,
).encode("utf-8"))
wrapper = self._write_wrapper(generation)

@ -295,6 +295,9 @@ class VMService:
info = domain.info()
root = self._vm_xml(domain)
managed = root.find(f"./metadata/{{{PANEL_NS}}}managed")
os_source = managed.get("os-source") if managed is not None else None
if os_source not in {"cloud_template", "iso"}:
os_source = "unknown"
try:
autostart = bool(domain.autostart())
except libvirt.libvirtError:
@ -309,6 +312,9 @@ class VMService:
"autostart": autostart,
"managed": managed is not None,
"public_ip_cidr": managed.get("public-ip-cidr") if managed is not None else None,
"os_name": managed.get("os-name") if os_source == "cloud_template" else None,
"os_source": os_source,
"install_iso": managed.get("install-iso") if os_source == "iso" else None,
"console_port": self._vnc_port(root),
}
@ -375,6 +381,15 @@ class VMService:
validated["iso"] = iso
return validated
@staticmethod
def _validated_os_name(value: Any) -> str | None:
if value is None:
return None
if (not isinstance(value, str) or not 1 <= len(value) <= 64
or value != value.strip() or any(ord(char) < 32 for char in value)):
raise VMError("云镜像模板名称无效")
return value
@staticmethod
def _volume_xml(name: str, disk_gib: int) -> str:
return VMService._volume_xml_bytes(name, disk_gib * GIB, "qcow2")
@ -427,8 +442,12 @@ class VMService:
# The next panel Start uses the persistent, ISO-free definition.
ET.SubElement(root, "on_reboot").text = "destroy"
metadata = ET.SubElement(root, "metadata")
ET.SubElement(metadata, f"{{{PANEL_NS}}}managed", version="2",
**{"disk-volume": disk_name})
managed = ET.SubElement(metadata, f"{{{PANEL_NS}}}managed", version="2",
**{"disk-volume": disk_name})
if "iso" in spec:
# The installation media does not prove which OS was installed.
managed.set("os-source", "iso")
managed.set("install-iso", spec["iso"])
devices = ET.SubElement(root, "devices")
disk = ET.SubElement(devices, "disk", type=disk_source[0], device="disk")
@ -657,11 +676,15 @@ class VMService:
raise VMError("无法生成面板元数据", 500)
managed.set("seed-volume", seed_name)
managed.set("public-ip-cidr", public_ip_cidr)
if spec.get("os_name") is not None:
managed.set("os-source", "cloud_template")
managed.set("os-name", spec["os_name"])
return ET.tostring(root, encoding="unicode")
def create_cloud_vm(self, spec: dict[str, Any], template_volume_name: str) -> dict[str, Any]:
"""Clone a trusted cloud image and supply static public networking."""
validated = self._validate_common_create(spec)
validated["os_name"] = self._validated_os_name(spec.get("os_name"))
if self.bridge_name is None:
raise VMError("公网模板创建需要先在宿主机设置 Linux 网桥,例如 bridge:br0", 409)
if not TEMPLATE_VOLUME_RE.fullmatch(template_volume_name):
@ -757,6 +780,7 @@ class VMService:
vm_id: str,
template_volume_name: str,
*,
os_name: str | None = None,
ssh_public_key: str = "",
root_password_hash: str | None = None,
progress: Callable[[str], None] | None = None,
@ -770,6 +794,7 @@ class VMService:
"""
if not TEMPLATE_VOLUME_RE.fullmatch(template_volume_name):
raise VMError("只能使用面板导入的云镜像模板")
os_name = self._validated_os_name(os_name)
if self.bridge_name is None:
raise VMError("公网模板重装需要原 Linux 网桥配置", 409)
@ -911,6 +936,13 @@ class VMService:
raise VMError("虚拟机面板元数据已变化,无法切换", 409)
new_managed.set("disk-volume", disk_name)
new_managed.set("seed-volume", seed_name)
# A different reinstall template invalidates the old label.
new_managed.attrib.pop("os-source", None)
new_managed.attrib.pop("os-name", None)
new_managed.attrib.pop("install-iso", None)
if os_name is not None:
new_managed.set("os-source", "cloud_template")
new_managed.set("os-name", os_name)
phase("starting")
new_domain = conn.defineXML(ET.tostring(new_root, encoding="unicode"))
if new_domain is None:

@ -64,6 +64,7 @@ class HostProfile:
storage_pool: str = "default"
iso_pool: str = "iso"
default_network: str = "default"
region: str = ""
@dataclass
@ -139,6 +140,14 @@ def _validate_network_selector(value: str) -> str:
return _validate_name(value, "网络")
def _validate_region(value: str) -> str:
# This is an operator-supplied display label, not a provider region ID.
if (not isinstance(value, str) or len(value) > 64 or value != value.strip()
or any(ord(char) < 32 or ord(char) == 127 for char in value)):
raise RemoteHostError("宿主机地区最多 64 字符,且不能包含控制字符或首尾空格")
return value
def _key_parts(line: str) -> tuple[str, str]:
if not isinstance(line, str) or len(line) > 4096 or any(c in line for c in "\r\n\x00"):
raise RemoteHostError("主机公钥格式无效")
@ -315,6 +324,7 @@ class RemoteHostManager:
storage_pool = _validate_pool_selector(profile.storage_pool, "磁盘池")
iso_pool = _validate_pool_selector(profile.iso_pool, "ISO 池")
default_network = _validate_network_selector(profile.default_network)
region = _validate_region(profile.region)
if not isinstance(confirmed_fingerprint, str) or not _FINGERPRINT.fullmatch(confirmed_fingerprint):
raise RemoteHostError("请确认扫描得到的 SHA256 主机指纹")
try:
@ -422,6 +432,7 @@ class RemoteHostManager:
"storage_pool": storage_pool,
"iso_pool": iso_pool,
"default_network": default_network,
"region": region,
}
_write_private(
generation / "profile.json",
@ -652,8 +663,13 @@ class RemoteHostManager:
)
if any(field not in metadata for field in fields):
raise RemoteHostError("已保存的宿主机配置损坏", status=500)
try:
region = _validate_region(metadata.get("region", ""))
except RemoteHostError as exc:
raise RemoteHostError("已保存的宿主机配置损坏", status=500) from exc
return {
**{field: metadata[field] for field in fields},
"region": region,
"private_key_encrypted": bool(metadata.get("private_key_encrypted", False)),
"key_locked": bool(metadata.get("private_key_encrypted", False)) and not (
generation in self._agents and self._agents[generation].alive

Loading…
Cancel
Save