Move cloud image management to admin catalog

main
admin 2 months ago
parent 180d5f5fae
commit 8bf90639b8

@ -87,9 +87,9 @@ SELECT id, username, email FROM users WHERE id = 1;
## 公网云镜像模板创建(无需手动安装)
面板的“创建虚拟机”现在有独立的“公网云镜像”方式。先在宿主机设置中选择已工作的 Linux 网桥,例如 `bridge:br0`;进入创建虚拟机页面,展开“导入新的云镜像模板”,填写 [AlmaLinux 10 官方 Generic Cloud qcow2 镜像](https://wiki.almalinux.org/cloud/Generic-cloud)在 `https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/` 下的下载地址、发布方 SHA-256 和模板显示名。地址必须是官方 HTTPS 直链,面板不会跟随重定向。面板服务器 A 需要能访问该地址。导入在后台运行,一次只允许一个任务,面板下载、校验 SHA-256 后通过当前 libvirt SSH 连接把模板镜像上传到 B 的磁盘池;无需登录 B 手工复制。模板目录记录加密保存在 MariaDB,绑定当前宿主机身份和磁盘池。不要在导入期间关闭面板进程;若进程异常退出,运行中的导入任务记录不会恢复,可能需要检查项目 `data/` 中的 `.cloud-image-*` 临时文件和 B 磁盘池中 `panel-template-*` 卷,不要未经核对就删除。
面板的“创建虚拟机”有独立的“公网云镜像”方式。先在宿主机设置中选择已工作的 Linux 网桥,例如 `bridge:br0`。只有管理员可进入侧栏的“云镜像模板”页面,填写 [AlmaLinux 官方 Generic Cloud qcow2 镜像](https://wiki.almalinux.org/cloud/Generic-cloud)在 `https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/` 或 `https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/` 下的下载地址、发布方 SHA-256 和模板显示名;已保存的显示名也可在该页修改。地址必须是官方 HTTPS 直链,面板不会跟随重定向。面板服务器 A 需要能访问该地址。导入在后台运行,一次只允许一个任务,面板下载、校验 SHA-256 后通过当前 libvirt SSH 连接把模板镜像上传到 B 的磁盘池;无需登录 B 手工复制。模板目录记录加密保存在 MariaDB,绑定当前宿主机身份和磁盘池。改名不会改动镜像文件、模板 ID 或已经创建的虚拟机的系统名称记录,只影响后续创建和重装时的显示。普通用户只能在创建或重装页面从已导入的镜像卡片中选择具体版本,不能导入或改名。不要在导入期间关闭面板进程;若进程异常退出,运行中的导入任务记录不会恢复,可能需要检查项目 `data/` 中的 `.cloud-image-*` 临时文件和 B 磁盘池中 `panel-template-*` 卷,不要未经核对就删除。
选择模板后填写 VM 资源和 root 登录方式。宿主机公网地址池支持实际获配的 `/24` 至 `/30` 前缀。例如服务商分配 `123.123.123.112/28`、宿主机网关为 `123.123.123.113` 时,在宿主机设置填写该 `/28` 网段(填写 `123.123.123.113/28` 也会规范化为 `123.123.123.112/28`),网关填 `123.123.123.113`,DNS 按服务商要求填写。自动分配只考虑此 `/28` 的有效主机地址;扣除网关后是 `123.123.123.114` 至 `123.123.123.126`,还会跳过保留、已用及池内 DNS 地址。**不要填写 `123.123.123.114/24` 或 `123.123.123.0/24`,除非服务商确实分配了整个 `/24`。**设置页会预览输入前缀换算出的实际网段和主机地址范围。
选择镜像卡片并展开版本后,填写 VM 资源和 root 登录方式。宿主机公网地址池支持实际获配的 `/24` 至 `/30` 前缀。例如服务商分配 `123.123.123.112/28`、宿主机网关为 `123.123.123.113` 时,在宿主机设置填写该 `/28` 网段(填写 `123.123.123.113/28` 也会规范化为 `123.123.123.112/28`),网关填 `123.123.123.113`,DNS 按服务商要求填写。自动分配只考虑此 `/28` 的有效主机地址;扣除网关后是 `123.123.123.114` 至 `123.123.123.126`,还会跳过保留、已用及池内 DNS 地址。**不要填写 `123.123.123.114/24` 或 `123.123.123.0/24`,除非服务商确实分配了整个 `/24`。**设置页会预览输入前缀换算出的实际网段和主机地址范围。
“虚拟机网卡前缀”与可分配地址池是独立设置:留空时客体使用地址池前缀;如果现场确认服务商要求 VM 内配置 `/24`,而实际只获配上述 `/28`,这里填 `24`,新建 VM 将获得例如 `123.123.123.114/24`,但面板仍只会从 `123.123.123.112/28` 挑选地址。可填写的客体前缀范围为 `/24` 到地址池前缀,以确保整个地址池中的 IP 与网关处于同一客体子网。修改此项不会自动改写已创建 VM;云镜像重装会保留该 VM 首次创建时的网络前缀。若使用 `/28` 不通,其具体原因仍需结合宿主机路由、网桥及服务商网络确认;仅改变面板掩码无法替代上游放行或路由配置。
@ -118,4 +118,4 @@ systemctl enable --now virsh-panel.service
独立的 `virsh-panel-update.service` 会先拉取私有仓库并安装目标版本 Python 依赖,再以快进方式切换代码、重启主面板并检查本机 HTTP 与数据库健康状态。更新任务绑定点击“检查更新”时看到的两个提交编号;若本地或远端版本变化,任务会拒绝切换并要求重新检查。更新任务状态加密存于 MariaDB,页面中断后可继续查询;独立服务异常退出或超时会尝试将未完成任务标为失败。更新前请备份 **MariaDB 数据和 `data/master.key`、`data/database-config.json`**;更新失败时不要重复点按钮,应先看 `journalctl -u virsh-panel-update.service -n 100`。依赖在代码切换前安装到当前 `.venv`,因此若依赖安装成功而代码切换失败,可能需要人工检查依赖版本。更新服务会保留更新前的 Git 回滚引用,但不会自动执行覆盖性的回滚。网页更新不负责安装系统 RPM、替换 `/etc/systemd/system` 中已安装的 unit 或修改反向代理配置;这些变化如后续版本需要,仍需人工处理。由于在线更新会运行私有仓库中的代码与依赖,必须保护 Gitea 仓库写入权限和访问令牌。
功能范围:邮箱验证注册、管理员审核及按虚拟机归属隔离用户,虚拟机列表和详情页四项性能走势图、从 ISO 创建、导入 AlmaLinux 10 云镜像模板并配置公网静态 IP 创建、云镜像重装、开机、关机、重启、强制断电/重置、删除和浏览器 VNC。当前仍是单宿主机版本;不提供 ISO 上传、目录自动创建、虚拟网络创建、内网 IP 模板或异网段网关。真实 AlmaLinux 10 宿主机、SMTP 服务及 MariaDB 仍需现场联调。
功能范围:邮箱验证注册、管理员审核及按虚拟机归属隔离用户,虚拟机列表和详情页四项性能走势图、从 ISO 创建、由管理员导入并重命名 AlmaLinux 9/10 云镜像模板、使用已导入模板配置公网静态 IP 创建、云镜像重装、开机、关机、重启、强制断电/重置、删除和浏览器 VNC。当前仍是单宿主机版本;不提供 ISO 上传、目录自动创建、虚拟网络创建、内网 IP 模板或异网段网关。真实 AlmaLinux 10 宿主机、SMTP 服务及 MariaDB 仍需现场联调。

@ -29,6 +29,7 @@ const state = {
sshKeysLoad: null,
sshKeysReturnView: null,
templateLoad: null,
templates: [],
templateImportJobId: null,
loadingVMs: false,
pollTimer: null,
@ -228,6 +229,7 @@ function showLogin() {
state.resources = null;
state.hostConfig = null;
state.templateLoad = null;
state.templates = [];
state.templateImportJobId = null;
state.selectedVmId = null;
clearAdminContent();
@ -235,7 +237,7 @@ function showLogin() {
clearVmMetrics("登录后加载监控数据。");
fillSelect("vm-network", [], "network");
fillSelect("vm-iso", [], "iso");
fillTemplateSelect([]);
fillTemplateViews([]);
fillSshKeyCards([]);
byId("ssh-keys-list").replaceChildren();
byId("ssh-key-form").reset();
@ -454,6 +456,7 @@ async function showDashboard(session) {
function applySession(session) {
state.sessionEpoch += 1;
state.templates = [];
state.sshKeys = [];
state.sshKeysLoad = null;
fillSshKeyCards([]);
@ -466,13 +469,13 @@ function applySession(session) {
state.admin = session.admin === true;
state.approved = session.approved === true;
state.hostReady = session.host_ready === true;
fillTemplateViews([]);
if (!state.admin) clearAdminContent();
for (const id of ["host-settings-button", "host-settings-mobile-button", "update-settings-button", "update-settings-mobile-button", "smtp-settings-button", "smtp-settings-mobile-button", "host-update-button", "unlock-update-button", "unlock-settings-button"]) {
for (const id of ["template-settings-button", "template-settings-mobile-button", "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);
}
@ -509,6 +512,8 @@ async function initialize() {
function resetCreatePage() {
byId("create-form").reset();
byId("vm-template").value = "";
renderTemplateCatalog("vm-template");
clearSshKeyPicker("vm-guest-ssh-key-cards");
byId("vm-root-password").value = "";
updateRootPasswordHint("vm-root-password", "vm-root-password-hint");
@ -523,6 +528,8 @@ function resetReinstallPage() {
state.reinstallExpectGeneratedPassword = false;
state.reinstallPasswordPendingAck = false;
byId("reinstall-form").reset();
byId("reinstall-template").value = "";
renderTemplateCatalog("reinstall-template");
clearSshKeyPicker("reinstall-ssh-key-cards");
byId("reinstall-root-password").value = "";
updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint");
@ -578,6 +585,7 @@ function showVmWorkspace({ preserveDraft = false } = {}) {
byId("create-view").hidden = true;
byId("reinstall-view").hidden = true;
byId("ssh-keys-workspace").hidden = true;
byId("template-workspace").hidden = true;
byId("update-workspace").hidden = true;
byId("smtp-workspace").hidden = true;
byId("smtp-password").value = "";
@ -585,6 +593,8 @@ function showVmWorkspace({ preserveDraft = false } = {}) {
byId("vm-navigation-button").setAttribute("aria-current", "page");
byId("ssh-keys-button").classList.remove("active");
byId("ssh-keys-button").removeAttribute("aria-current");
byId("template-settings-button").classList.remove("active");
byId("template-settings-button").removeAttribute("aria-current");
byId("update-settings-button").classList.remove("active");
byId("update-settings-button").removeAttribute("aria-current");
byId("smtp-settings-button").classList.remove("active");
@ -615,11 +625,12 @@ async function showSshKeysWorkspace(returnView = null) {
clearVmCredential();
if (returnView !== "reinstall") state.selectedVmId = null;
byId("vm-workspace").hidden = true;
byId("template-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"]) {
for (const id of ["vm-navigation-button", "template-settings-button", "update-settings-button", "smtp-settings-button"]) {
byId(id).classList.remove("active");
byId(id).removeAttribute("aria-current");
}
@ -649,6 +660,40 @@ function returnFromSshKeysWorkspace() {
else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint");
}
async function showTemplateWorkspace() {
if (!state.admin || !state.csrfToken) return;
if (!canLeaveReinstallPage()) return;
discardVmSubpageDrafts();
byId("admin-menu").open = false;
stopVmMetrics();
clearVmCredential();
state.selectedVmId = null;
byId("vm-workspace").hidden = true;
byId("ssh-keys-workspace").hidden = true;
byId("update-workspace").hidden = true;
byId("smtp-workspace").hidden = true;
byId("smtp-password").value = "";
byId("template-workspace").hidden = false;
for (const id of ["vm-navigation-button", "ssh-keys-button", "update-settings-button", "smtp-settings-button"]) {
byId(id).classList.remove("active");
byId(id).removeAttribute("aria-current");
}
byId("template-settings-button").classList.add("active");
byId("template-settings-button").setAttribute("aria-current", "page");
text("breadcrumb-current", "云镜像模板");
showError("template-import-error", "");
showError("template-list-error", "");
showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板;点击“导入模板”继续查询任务状态。" : "");
byId("template-admin-list").replaceChildren(makeElement("p", "muted", "正在加载…"));
window.scrollTo({ top: 0, behavior: "auto" });
try {
await loadTemplates();
} catch (error) {
showError("template-list-error", `无法读取云镜像模板:${error.message}`);
byId("template-admin-list").replaceChildren();
}
}
function selectedSshKeyId(containerId) {
return byId(containerId).querySelector('.ssh-key-option[aria-pressed="true"]')?.dataset.keyId || "";
}
@ -801,6 +846,7 @@ async function showUpdateWorkspace() {
clearVmCredential();
byId("vm-workspace").hidden = true;
byId("ssh-keys-workspace").hidden = true;
byId("template-workspace").hidden = true;
byId("smtp-workspace").hidden = true;
byId("smtp-password").value = "";
byId("update-workspace").hidden = false;
@ -808,6 +854,8 @@ async function showUpdateWorkspace() {
byId("vm-navigation-button").removeAttribute("aria-current");
byId("ssh-keys-button").classList.remove("active");
byId("ssh-keys-button").removeAttribute("aria-current");
byId("template-settings-button").classList.remove("active");
byId("template-settings-button").removeAttribute("aria-current");
byId("update-settings-button").classList.add("active");
byId("update-settings-button").setAttribute("aria-current", "page");
byId("smtp-settings-button").classList.remove("active");
@ -894,12 +942,15 @@ async function showSmtpWorkspace() {
clearVmCredential();
byId("vm-workspace").hidden = true;
byId("ssh-keys-workspace").hidden = true;
byId("template-workspace").hidden = true;
byId("update-workspace").hidden = true;
byId("smtp-workspace").hidden = false;
byId("vm-navigation-button").classList.remove("active");
byId("vm-navigation-button").removeAttribute("aria-current");
byId("ssh-keys-button").classList.remove("active");
byId("ssh-keys-button").removeAttribute("aria-current");
byId("template-settings-button").classList.remove("active");
byId("template-settings-button").removeAttribute("aria-current");
byId("update-settings-button").classList.remove("active");
byId("update-settings-button").removeAttribute("aria-current");
byId("smtp-settings-button").classList.add("active");
@ -1871,45 +1922,139 @@ async function loadResources() {
}
}
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);
function templateSystem(item) {
const id = String(item?.id || "");
const family = String(item?.os_family || "").toLowerCase() === "almalinux" || /^alma(?:9|10)-/.test(id)
? "AlmaLinux" : "其他系统";
const oldVersion = /^alma(9|10)-/.exec(id)?.[1] || "";
const version = /^[0-9]+$/.test(String(item?.os_version || ""))
? String(item.os_version) : oldVersion;
return { family, version };
}
function renderTemplateCatalog(inputId) {
const input = byId(inputId);
const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog");
const opened = new Set(Array.from(container.querySelectorAll("details[open]"), (detail) => detail.dataset.family));
const groups = new Map();
for (const item of state.templates) {
if (!item?.id) continue;
const { family, version } = templateSystem(item);
if (!groups.has(family)) groups.set(family, []);
groups.get(family).push({ item, version });
}
if (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) {
if (!groups.size) {
input.value = "";
container.replaceChildren(makeElement("p", "template-catalog-empty", state.admin
? "暂无云镜像,请先到“云镜像模板”页面导入。"
: "暂无可用云镜像,请联系管理员导入模板。"));
return;
}
if (!state.templates.some((item) => String(item.id) === input.value)) input.value = "";
const cards = [];
for (const [family, entries] of groups) {
entries.sort((a, b) => Number(b.version || 0) - Number(a.version || 0)
|| String(a.item.name || "").localeCompare(String(b.item.name || ""), "zh-CN"));
const card = makeElement("details", "template-family-card");
card.dataset.family = family;
card.open = opened.has(family) || entries.some(({ item }) => String(item.id) === input.value);
const summary = makeElement("summary", "template-family-summary");
const icon = makeElement("span", family === "AlmaLinux" ? "template-family-icon alma" : "template-family-icon", family === "AlmaLinux" ? "A" : "◈");
icon.setAttribute("aria-hidden", "true");
summary.append(icon, makeElement("strong", "", family), makeElement("span", "template-family-arrow", "⌄"));
const versions = makeElement("div", "template-versions");
versions.setAttribute("role", "group");
versions.setAttribute("aria-label", `${family} 可用版本`);
for (const { item, version } of entries) {
const id = String(item.id);
const versionLabel = version ? `${family} ${version}` : "版本未标注";
const option = makeElement("button", "template-version-option");
option.type = "button";
option.dataset.templateId = id;
option.setAttribute("aria-pressed", String(input.value === id));
option.setAttribute("aria-label", `选择 ${versionLabel},${String(item.name || id)}`);
option.append(makeElement("strong", "", versionLabel), makeElement("small", "", String(item.name || id)));
option.addEventListener("click", () => {
input.value = id;
container.querySelectorAll(".template-version-option").forEach((button) => {
button.setAttribute("aria-pressed", String(button.dataset.templateId === id));
});
if (inputId === "vm-template") showError("create-error", "");
else showError("reinstall-error", "");
});
versions.append(option);
}
card.append(summary, versions);
cards.push(card);
}
container.replaceChildren(...cards);
}
function renderTemplateAdminList() {
const list = byId("template-admin-list");
list.replaceChildren();
if (!state.admin) return;
if (!state.templates.length) {
list.append(makeElement("p", "muted", "当前宿主机还没有导入云镜像模板。"));
return;
}
for (const item of state.templates) {
const id = String(item?.id || "");
if (!id) continue;
const 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;
const { family, version } = templateSystem(item);
const row = makeElement("form", "template-admin-row");
const heading = makeElement("div", "template-admin-row-heading");
const icon = makeElement("span", "template-admin-icon", family === "AlmaLinux" ? "A" : "◈");
icon.setAttribute("aria-hidden", "true");
heading.append(icon, makeElement("strong", "", `${family}${version ? ` ${version}` : ""}`));
const label = makeElement("label", "", "模板名称");
const name = makeElement("input", "");
name.type = "text";
name.required = true;
name.maxLength = 64;
name.value = String(item.name || "");
name.setAttribute("autocomplete", "off");
name.id = `template-admin-name-${id}`;
label.htmlFor = name.id;
const button = makeElement("button", "button button-outline small", "保存名称");
button.type = "submit";
const error = makeElement("p", "form-error");
error.hidden = true;
error.setAttribute("role", "alert");
row.addEventListener("submit", async (event) => {
event.preventDefault();
const requested = name.value.trim();
error.hidden = true;
if (!requested || requested.length > 64) {
error.textContent = "模板名称应为 1 至 64 个字符。";
error.hidden = false;
return;
}
if (requested === item.name) return;
setButtonBusy(button, true, "正在保存…");
try {
await api(`/api/v1/vm-templates/${encodeURIComponent(id)}`, { method: "PATCH", body: { name: requested } });
await loadTemplates();
toast("模板名称已更新。", "success");
} catch (caught) {
error.textContent = caught.message;
error.hidden = false;
} finally {
if (button.isConnected) setButtonBusy(button, false);
}
});
row.append(heading, label, name, button, error);
list.append(row);
}
reinstallSelect.disabled = reinstallSelect.options.length <= 1;
}
function fillTemplateViews(items, preferredId = "") {
state.templates = items.filter((item) => item && typeof item.id === "string");
if (preferredId && state.templates.some((item) => item.id === preferredId)) byId("vm-template").value = preferredId;
renderTemplateCatalog("vm-template");
renderTemplateCatalog("reinstall-template");
renderTemplateAdminList();
updateCreateSource();
}
async function loadTemplates(preferredId = "") {
@ -1920,7 +2065,7 @@ async function loadTemplates(preferredId = "") {
try {
const result = await request;
if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return;
fillTemplateSelect(Array.isArray(result?.templates) ? result.templates : [], preferredId);
fillTemplateViews(Array.isArray(result?.templates) ? result.templates : [], preferredId);
} finally {
if (state.templateLoad === request) state.templateLoad = null;
}
@ -1947,7 +2092,7 @@ async function waitForTemplateImport(jobId) {
showTemplateImportStatus(`宿主机正在后台导入镜像,已等待约 ${seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分钟`}。离开页面不会取消任务。`);
}
}
throw new Error("模板仍在后台导入。稍后返回创建虚拟机页面查看导入状态。");
throw new Error("模板仍在后台导入。稍后返回“云镜像模板”页面查看导入状态。");
}
function selectedCreateSource() {
@ -2015,8 +2160,7 @@ function updateCreateSource() {
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;
template.disabled = !cloud;
byId("vm-guest-ssh-key-cards").hidden = !cloud;
["vm-public-ip-cidr", "vm-gateway", "vm-dns"].forEach((id) => {
const input = byId(id);
@ -2071,9 +2215,6 @@ function openCreate() {
resetCreatePage();
fillSshKeyCards(state.sshKeys);
clearSshKeyPicker("vm-guest-ssh-key-cards");
byId("template-import").open = !!state.templateImportJobId;
showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板。查询会自动更新;若中断,可点击“导入模板”继续查看。" : "");
showError("template-import-error", "");
showError("create-error", "");
updateCreateSource();
showVmSubpage("create");
@ -2582,12 +2723,15 @@ byId("vm-navigation-button").addEventListener("click", leaveUpdateWorkspace);
byId("vm-navigation-mobile-button").addEventListener("click", leaveUpdateWorkspace);
byId("ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspace());
byId("ssh-keys-mobile-button").addEventListener("click", () => void showSshKeysWorkspace());
byId("template-settings-button").addEventListener("click", () => void showTemplateWorkspace());
byId("template-settings-mobile-button").addEventListener("click", () => void showTemplateWorkspace());
byId("update-settings-button").addEventListener("click", () => void showUpdateWorkspace());
byId("update-settings-mobile-button").addEventListener("click", () => void showUpdateWorkspace());
byId("smtp-settings-button").addEventListener("click", () => void showSmtpWorkspace());
byId("smtp-settings-mobile-button").addEventListener("click", () => void showSmtpWorkspace());
byId("smtp-back-button").addEventListener("click", showVmWorkspace);
byId("ssh-keys-back-button").addEventListener("click", returnFromSshKeysWorkspace);
byId("template-back-button").addEventListener("click", showVmWorkspace);
byId("update-back-button").addEventListener("click", leaveUpdateWorkspace);
byId("unlock-settings-button").addEventListener("click", openHostSettings);
byId("host-back-button").addEventListener("click", () => {
@ -2901,7 +3045,8 @@ document.querySelectorAll('input[name="source"]').forEach((radio) => radio.addEv
}
}));
byId("template-import-button").addEventListener("click", async () => {
byId("template-import-form").addEventListener("submit", async (event) => {
event.preventDefault();
if (!state.admin) return;
showError("template-import-error", "");
const existingJobId = state.templateImportJobId;
@ -2914,8 +3059,9 @@ byId("template-import-button").addEventListener("click", async () => {
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 地址。");
if (!existingJobId && (!url || url.origin !== "https://repo.almalinux.org" || url.username || url.password || url.search || url.hash
|| !/^\/almalinux\/(9|10)\/cloud\/x86_64\/images\/AlmaLinux-\1-GenericCloud-[A-Za-z0-9._-]+\.x86_64\.qcow2$/.test(url.pathname))) {
showError("template-import-error", "目前仅支持 repo.almalinux.org 上的 AlmaLinux 9 / 10 x86_64 GenericCloud qcow2 HTTPS 地址。");
return;
}
if (!existingJobId && !/^[a-f0-9]{64}$/.test(sha256)) {
@ -2936,12 +3082,9 @@ byId("template-import-button").addEventListener("click", async () => {
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");
await loadTemplates();
byId("template-import-form").reset();
toast("云镜像模板已导入,用户现在可以在创建页面选择。", "success");
} catch (error) {
showTemplateImportStatus(state.templateImportJobId ? "暂时无法确认导入进度,任务可能仍在后台运行;稍后点击按钮继续查看。" : "");
showError("template-import-error", error.message);
@ -3081,7 +3224,7 @@ byId("create-form").addEventListener("submit", async (event) => {
return;
}
if (!body.template_id) {
showError("create-error", "请先选择或导入云镜像模板。");
showError("create-error", state.admin ? "请先选择已导入的云镜像版本;如无可用镜像,请到“云镜像模板”页面导入。" : "请先选择云镜像版本;如无可用镜像,请联系管理员导入。");
return;
}
if (!automaticPublicIp && !validPublicIpCidr(body.public_ip_cidr)) {
@ -3145,7 +3288,7 @@ byId("reinstall-form").addEventListener("submit", async (event) => {
const rootPassword = byId("reinstall-root-password").value;
const confirmationName = byId("reinstall-confirm-name").value;
if (!templateId) {
showError("reinstall-error", "请先选择已导入的云镜像模板。若列表为空,请在“创建虚拟机”页面先导入模板。");
showError("reinstall-error", state.admin ? "请先选择已导入的云镜像版本;如无可用镜像,请到“云镜像模板”页面导入。" : "请先选择云镜像版本;如无可用镜像,请联系管理员导入。");
return;
}
if (selectedKeyId && !state.sshKeys.some((key) => String(key.id) === selectedKeyId)) {

@ -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=workspace-pages-1" />
<script type="module" src="/static/app.js?v=workspace-pages-1"></script>
<link rel="stylesheet" href="/static/styles.css?v=template-catalog-1" />
<script type="module" src="/static/app.js?v=template-catalog-1"></script>
</head>
<body>
<div id="boot-screen" class="boot-screen" role="status" aria-live="polite">
@ -230,6 +230,7 @@
<div class="sidebar-section-label">工作区</div>
<button id="vm-navigation-button" class="sidebar-link sidebar-button active" type="button" aria-current="page"><span class="nav-icon" aria-hidden="true">▦</span> 虚拟机 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="ssh-keys-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">⌑</span> 公钥管理 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="template-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">◈</span> 云镜像模板 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="host-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">⌁</span> 宿主机设置 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="update-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">↻</span> 网站更新 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="smtp-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">✉</span> 邮件与用户 <span class="nav-arrow" aria-hidden="true">›</span></button>
@ -242,7 +243,7 @@
<div class="main-area">
<header class="topbar">
<div class="breadcrumb">工作区 <span>/</span> <strong id="breadcrumb-current">虚拟机</strong></div>
<div class="topbar-right"><details id="admin-menu" class="admin-menu"><summary>菜单 <span aria-hidden="true">▾</span></summary><div class="admin-menu-options"><button id="vm-navigation-mobile-button" class="button button-ghost small" type="button">虚拟机</button><button id="ssh-keys-mobile-button" class="button button-ghost small" type="button">公钥管理</button><button id="host-settings-mobile-button" class="button button-ghost small" type="button">宿主机设置</button><button id="update-settings-mobile-button" class="button button-ghost small" type="button">网站更新</button><button id="smtp-settings-mobile-button" class="button button-ghost small" type="button">邮件与用户</button></div></details><span class="topbar-user"><span class="avatar" aria-hidden="true">A</span><span id="current-username">用户</span></span><button id="logout-button" class="button button-ghost small" type="button">退出登录</button></div>
<div class="topbar-right"><details id="admin-menu" class="admin-menu"><summary>菜单 <span aria-hidden="true">▾</span></summary><div class="admin-menu-options"><button id="vm-navigation-mobile-button" class="button button-ghost small" type="button">虚拟机</button><button id="ssh-keys-mobile-button" class="button button-ghost small" type="button">公钥管理</button><button id="template-settings-mobile-button" class="button button-ghost small" type="button">云镜像模板</button><button id="host-settings-mobile-button" class="button button-ghost small" type="button">宿主机设置</button><button id="update-settings-mobile-button" class="button button-ghost small" type="button">网站更新</button><button id="smtp-settings-mobile-button" class="button button-ghost small" type="button">邮件与用户</button></div></details><span class="topbar-user"><span class="avatar" aria-hidden="true">A</span><span id="current-username">用户</span></span><button id="logout-button" class="button button-ghost small" type="button">退出登录</button></div>
</header>
<main class="content">
@ -306,14 +307,7 @@
<div class="field"><label for="vm-disk">系统盘 <span>*</span></label><div class="input-suffix"><input id="vm-disk" name="disk_gib" type="number" min="1" max="4096" value="20" required /><span>GiB</span></div></div>
<div class="field"><label for="vm-network">虚拟网络或网桥 <span>*</span></label><select id="vm-network" name="network" required><option value="">正在加载网络…</option></select></div>
<div class="field full" id="vm-iso-field"><label for="vm-iso">安装 ISO <span>*</span></label><select id="vm-iso" name="iso" required><option value="">正在加载镜像…</option></select><small>镜像来自宿主机允许使用的 ISO 目录。</small></div>
<div class="field full" id="vm-template-field" hidden><label for="vm-template">系统模板 <span>*</span></label><select id="vm-template" name="template_id" disabled><option value="">选择云镜像模板</option></select><small>模板需支持 cloud-init;不会再次进入 ISO 安装界面。</small>
<details id="template-import" class="template-import"><summary>导入新的云镜像模板</summary><div class="template-import-fields">
<div class="field"><label for="template-name">模板名称</label><input id="template-name" type="text" maxlength="64" autocomplete="off" placeholder="例如 AlmaLinux 10 Cloud" /></div>
<div class="field"><label for="template-url">云镜像下载地址</label><input id="template-url" type="text" inputmode="url" maxlength="2048" autocomplete="off" placeholder="粘贴 AlmaLinux 10 官方 GenericCloud qcow2 完整 HTTPS 地址" /><small>目前仅支持 repo.almalinux.org 的 AlmaLinux 10 x86_64 GenericCloud qcow2 镜像。</small></div>
<div class="field"><label for="template-sha256">镜像 SHA-256 校验值</label><input id="template-sha256" type="text" maxlength="64" spellcheck="false" autocomplete="off" placeholder="64 位十六进制校验值" /><small>从镜像发布方核对;面板下载后会校验文件。</small></div>
<p id="template-import-status" class="template-import-status" role="status" hidden></p><p id="template-import-error" class="form-error" role="alert" hidden></p><button id="template-import-button" class="button button-outline small" type="button">导入模板</button>
</div></details>
</div>
<div class="field full" id="vm-template-field" hidden><span id="vm-template-label" class="template-field-label">系统镜像 <span>*</span></span><input id="vm-template" name="template_id" type="hidden" value="" disabled /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="vm-template-label" aria-describedby="vm-template-hint" aria-required="true"></div><small id="vm-template-hint">点击系统图标下方的箭头展开版本,再选择已导入的镜像;模板需支持 cloud-init。</small></div>
<div class="cloud-fields full" id="vm-cloud-fields" hidden>
<div class="cloud-fields-heading"><strong>公网网络配置</strong><small>仅支持已配置的 Linux 网桥,例如 bridge:br0;上游网络还需允许虚拟机的 MAC 地址。</small></div>
<div id="vm-auto-public-pool" class="vm-auto-public-pool" role="status" hidden><strong>自动分配公网 IP</strong><span id="vm-auto-public-pool-description">创建时将从宿主机地址池中选择未使用的 IP,并自动写入网关和 DNS。</span></div>
@ -340,7 +334,7 @@
<p class="reinstall-warning"><strong>重装将永久清除原系统盘中的全部数据。</strong>面板会先请求虚拟机正常关机;若关机超时,重装会停止,不会强制断电。libvirt/QEMU 报告虚拟机已从新盘启动后,原系统盘将自动删除。这个“启动”不保证客户机系统、网络或 SSH 已经可用,请确认模板和网络配置。</p>
<p class="reinstall-network">沿用首次创建的公网网络信息:<strong id="reinstall-public-ip"></strong>。网桥、MAC、网关和 DNS 也会保持原配置。</p>
<div class="form-grid">
<div class="field full"><label for="reinstall-template">重装模板 <span>*</span></label><select id="reinstall-template" name="template_id" required><option value="">正在加载模板…</option></select><small>仅显示当前宿主机已经导入的云镜像模板;模板必须支持 cloud-init。</small></div>
<div class="field full"><span id="reinstall-template-label" class="template-field-label">重装镜像 <span>*</span></span><input id="reinstall-template" name="template_id" type="hidden" value="" /><div id="reinstall-template-catalog" class="template-catalog" role="group" aria-labelledby="reinstall-template-label" aria-describedby="reinstall-template-hint" aria-required="true"></div><small id="reinstall-template-hint">点击系统图标下方的箭头展开版本,选择当前宿主机已导入的云镜像。</small></div>
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="reinstall-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="重装系统时选择 SSH 公钥"></div><small>直接选择“公钥管理”中保存的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><button id="reinstall-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></div>
<div class="field full" id="reinstall-root-password-field"><label for="reinstall-root-password">初始 root 密码(可选)</label><input id="reinstall-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="reinstall-root-password-hint" placeholder="可自行设置,留空时按公钥选择决定" /><small id="reinstall-root-password-hint" aria-live="polite">不选公钥且留空时自动生成强密码;自行设置需至少 12 个字符,包含大写字母、小写字母和符号。</small></div>
<div class="field full"><label for="reinstall-confirm-name">输入虚拟机名称以确认删除旧系统盘 <span>*</span></label><input id="reinstall-confirm-name" name="confirmation_name" type="text" required autocomplete="off" spellcheck="false" placeholder="请输入完整的虚拟机名称" /><small id="reinstall-confirm-hint"></small></div>
@ -374,6 +368,25 @@
</section>
</div>
</div>
<div id="template-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">CLOUD IMAGE CATALOG</span><h1>云镜像模板</h1><p>仅管理员可以导入官方云镜像和修改模板名称;用户创建虚拟机时选择已导入的版本。</p></div><button id="template-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="template-admin-grid">
<section class="host-card" aria-labelledby="template-import-title">
<div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="template-import-title">导入云镜像</h2><p>从 AlmaLinux 官方仓库下载,校验 SHA-256 后导入当前宿主机。</p></div></div>
<form id="template-import-form" class="form-stack" novalidate>
<label for="template-name">模板名称</label><input id="template-name" type="text" maxlength="64" required autocomplete="off" placeholder="例如 AlmaLinux 10 Cloud" />
<label for="template-url">云镜像下载地址</label><input id="template-url" type="url" inputmode="url" maxlength="2048" required autocomplete="off" placeholder="粘贴官方 GenericCloud qcow2 完整 HTTPS 地址" /><small class="template-field-help">支持 repo.almalinux.org 的 AlmaLinux 9 / 10 x86_64 GenericCloud qcow2 镜像。</small>
<label for="template-sha256">镜像 SHA-256 校验值</label><input id="template-sha256" type="text" maxlength="64" minlength="64" required spellcheck="false" autocomplete="off" placeholder="64 位十六进制校验值" /><small class="template-field-help">从镜像发布方核对;面板下载后会校验文件。</small>
<p id="template-import-status" class="template-import-status" role="status" hidden></p><p id="template-import-error" class="form-error" role="alert" hidden></p><button id="template-import-button" class="button button-primary" type="submit">导入模板</button>
</form>
</section>
<section class="host-card" aria-labelledby="template-list-title">
<div class="host-card-heading"><span class="host-card-number">◈</span><div><h2 id="template-list-title">已导入模板</h2><p>修改名称不会改变镜像文件或已创建虚拟机的系统。</p></div></div>
<p id="template-list-error" class="form-error" role="alert" hidden></p>
<div id="template-admin-list" class="template-admin-list" aria-live="polite"><p class="muted">正在加载…</p></div>
</section>
</div>
</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">

@ -142,7 +142,7 @@ tbody tr:hover{background:#fcfefe}
.workspace-form-page{width:min(100%,900px);margin:0 auto 48px}.workspace-form-back{padding-left:0;margin-bottom:15px;min-height:34px}.workspace-form-heading{margin-bottom:22px}.workspace-form-heading h1{margin-top:8px}.workspace-form-card{overflow:hidden}.workspace-form-body{padding:28px clamp(22px,3vw,36px) 32px}.workspace-form-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:10px;padding:18px clamp(22px,3vw,36px);border-top:1px solid #edf1f5;background:#fbfdfe}.workspace-form-actions .button{min-width:120px}.workspace-form-body>.form-error{margin:18px 0 0}
.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 17px}.field.full{grid-column:1/-1}.field label{display:block}.field label span{color:#dc5965}.field small{display:block;color:#a1adbb;font-size:10px;margin-top:7px;line-height:1.5}.field select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2393a1ae' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:35px}
.create-source-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;border:0;padding:0;margin:0 0 23px;min-width:0}.create-source-picker legend{color:#34445a;font-size:13px;font-weight:700;padding:0;margin-bottom:10px}.create-source-picker label{position:relative;display:block;cursor:pointer}.create-source-picker input{position:absolute;opacity:0;width:1px;height:1px}.create-source-picker label span{display:block;border:1px solid #dce4eb;border-radius:9px;padding:12px 14px;min-height:65px;background:#fff}.create-source-picker input:checked+span{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.create-source-picker input:focus-visible+span{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.create-source-picker strong{display:block;color:#334a5f;font-size:12px}.create-source-picker small{display:block;color:#8999a8;font-size:10px;margin-top:5px}
.template-import{border:1px solid #e0e9ee;border-radius:9px;margin-top:12px;background:#fbfdfd}.template-import summary{cursor:pointer;padding:11px 13px;color:#148c98;font-size:11px;font-weight:700}.template-import-fields{display:grid;gap:13px;padding:2px 13px 14px}.template-import-fields .field input{height:42px}.template-import-fields .form-error{margin:0}.template-import-fields .button{justify-self:start}.template-import-status{margin:0;color:#317c85;font-size:11px;line-height:1.6}
.template-field-label{display:block;color:#34445a;font-size:13px;font-weight:700;margin-bottom:10px}.template-field-label span{color:#dc5965}.template-catalog{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:14px}.template-catalog-empty{grid-column:1/-1;margin:0;padding:17px;border:1px dashed #cbdbe3;border-radius:10px;background:#f8fbfc;color:#698094;font-size:12px}.template-family-card{min-width:0;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden}.template-family-card[open]{border-color:#46b6ba;box-shadow:0 0 0 2px rgba(20,166,175,.07)}.template-family-summary{display:flex;align-items:center;flex-direction:column;gap:9px;min-height:153px;padding:20px 13px 13px;cursor:pointer;text-align:center;list-style:none}.template-family-summary::-webkit-details-marker{display:none}.template-family-summary:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:-3px}.template-family-summary strong{color:#30465a;font-size:13px}.template-family-icon{display:flex;align-items:center;justify-content:center;width:65px;height:65px;border-radius:17px;background:linear-gradient(145deg,#2a6385,#173d58);color:#fff;font-size:31px;font-weight:800;box-shadow:0 6px 16px rgba(24,68,90,.15)}.template-family-icon.alma{background:conic-gradient(from 35deg,#32bac4 0 28%,#5277cb 28% 51%,#e7ad54 51% 72%,#3ea67b 72% 100%);border:5px solid #f5faf9;color:#fff;text-shadow:0 1px 4px rgba(8,45,65,.35)}.template-family-arrow{color:#258f9b;font-size:20px;line-height:1;transition:transform .2s}.template-family-card[open] .template-family-arrow{transform:rotate(180deg)}.template-versions{display:grid;gap:7px;padding:12px;border-top:1px solid #e7edf2;background:#fbfdfd}.template-version-option{width:100%;display:grid;gap:3px;padding:11px 12px;border:1px solid #dee8ed;border-radius:8px;background:#fff;text-align:left;color:#344e60}.template-version-option strong{font-size:12px}.template-version-option small{margin:0;color:#899cac;font-size:10px;overflow-wrap:anywhere}.template-version-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)}.template-version-option:hover{border-color:#48b6bd}.template-admin-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);align-items:start;gap:19px}.template-admin-grid .host-card{min-width:0}.template-admin-grid .form-stack .button{align-self:flex-start}.template-field-help{display:block;margin:-16px 0 19px;color:#8b9bab;font-size:11px;line-height:1.55}.template-import-status{margin:0 0 14px;padding:10px 12px;border-radius:8px;background:#edf8f8;color:#317c85;font-size:11px;line-height:1.6}.template-admin-list{display:grid;gap:10px}.template-admin-list>.muted{margin:0}.template-admin-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:9px 11px;align-items:end;padding:14px;border:1px solid #e0e9ee;border-radius:10px;background:#fbfdfd}.template-admin-row-heading{grid-column:1/-1;display:flex;align-items:center;gap:9px;margin-bottom:3px;color:#34495c;font-size:12px}.template-admin-icon{display:flex;align-items:center;justify-content:center;width:27px;height:27px;border-radius:7px;background:#e3f6f3;color:#138d8f;font-weight:800}.template-admin-row label{grid-column:1/-1;margin:0;color:#75899b;font-size:11px;font-weight:700}.template-admin-row input{width:100%;min-width:0;height:37px;padding:0 10px;border:1px solid #dce4eb;border-radius:7px;background:#fff;color:#20364a;font-size:12px}.template-admin-row .button{min-height:37px}.template-admin-row .form-error{grid-column:1/-1;margin:0}
.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px}
.vm-auto-public-pool{display:grid;gap:5px;margin:0 0 18px;padding:13px 15px;border:1px solid #cce9e0;border-radius:9px;background:#f0fbf8}.vm-auto-public-pool strong{font-size:12px;color:#217d6e}.vm-auto-public-pool span{font-size:11px;line-height:1.6;color:#5b837a}.vm-cloud-auth-fields{margin-top:18px}
.input-suffix{position:relative}.input-suffix input{padding-right:48px}.input-suffix span{position:absolute;right:13px;top:13px;color:#97a4b2;font-size:12px}
@ -158,6 +158,7 @@ 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}.admin-menu{display:block}.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){.template-admin-grid{grid-template-columns:1fr}}
@media(max-width:960px){.ssh-keys-grid{grid-template-columns:1fr}}
@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}}
@media(max-width:740px){.vm-metrics-grid{grid-template-columns:1fr}.vm-metrics-heading{align-items:flex-start;flex-direction:column}.vm-metric-plot{height:190px}}
@ -167,6 +168,7 @@ tbody tr:hover{background:#fcfefe}
@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:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.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){.template-catalog{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.template-family-summary{min-height:137px;padding:16px 9px 11px}.template-family-icon{width:55px;height:55px;font-size:27px}.template-versions{padding:8px}.template-version-option{padding:9px 8px}.template-admin-row{grid-template-columns:1fr}.template-admin-row .button{justify-self:start}}
@media(max-width:510px){.workspace-form-body{padding:22px 19px 25px}.workspace-form-actions{padding:15px 19px}.workspace-form-actions .button{flex:1 1 100%}.workspace-form-back{margin-bottom:10px}}
@media(max-width:510px){.host-public-pool>.form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}}

@ -62,6 +62,10 @@ OFFICIAL_CLOUD_URL = (
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/"
"AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2"
)
OFFICIAL_ALMA9_URL = (
"https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/"
"AlmaLinux-9-GenericCloud-latest.x86_64.qcow2"
)
HOST_BODY = {
"host": "vmhost.example.test", "port": 2222,
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----",
@ -770,6 +774,40 @@ def test_cloud_template_import_job_and_create_dispatch(web):
assert ("create_vm", expected_spec) not in service.calls
def test_almalinux_9_template_import_exposes_stable_version_and_prevents_duplicate_name(web):
client, state, token, service, manager, _ = web
csrf = setup_admin(client, token)
configure_host(client, csrf)
headers = {"X-CSRF-Token": csrf}
image = state.data_dir / "alma9-verified.qcow2"
image.write_bytes(b"QFI\xfbverified test image")
digest = "b" * 64
with patch("virsh_panel.app.download_verified_image",
return_value=(image, 2 * 1024**3)):
queued = client.post("/api/v1/vm-templates/import", json={
"name": "AlmaLinux 9", "url": OFFICIAL_ALMA9_URL, "sha256": digest,
}, headers=headers)
assert queued.status_code == 202
job = wait_for_import_job(client, queued.json()["job_id"])
assert job["status"] == "completed"
template_id = template_id_for(template_scope(manager.current()), digest, "9")
volume_name = template_volume_name(template_id)
template = job["template"]
assert template["id"] == template_id
assert template["volume_name"] == volume_name
assert template["os_family"] == "AlmaLinux"
assert template["os_version"] == "9"
assert ("import_template", volume_name, 2 * 1024**3) in service.calls
assert client.get("/api/v1/vm-templates").json()["templates"] == [template]
duplicate = client.post("/api/v1/vm-templates/import", json={
"name": "ALMALINUX 9", "url": OFFICIAL_ALMA9_URL, "sha256": "c" * 64,
}, headers=headers)
assert duplicate.status_code == 409
assert len([call for call in service.calls if call[0] == "import_template"]) == 1
def test_cloud_vm_root_login_supports_key_and_hashed_initial_password(web):
client, state, token, service, manager, _ = web
csrf = setup_admin(client, token)

@ -16,7 +16,10 @@ from virsh_panel.cloud_templates import (
TemplateStore,
_RejectRedirects,
download_verified_image,
image_version_for,
template_id_for,
template_scope,
template_volume_name,
validate_image_url,
)
@ -25,6 +28,29 @@ OFFICIAL = (
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/"
"AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2"
)
OFFICIAL_9 = (
"https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/"
"AlmaLinux-9-GenericCloud-latest.x86_64.qcow2"
)
def test_official_almalinux_9_and_10_are_distinct_supported_versions():
assert validate_image_url(OFFICIAL_9) == OFFICIAL_9
assert image_version_for(OFFICIAL_9) == "9"
assert image_version_for(OFFICIAL) == "10"
scope = "a" * 64
digest = "b" * 64
assert template_id_for(scope, digest, "9").startswith("alma9-")
assert template_id_for(scope, digest, "10").startswith("alma10-")
assert template_volume_name(template_id_for(scope, digest, "9")).startswith(
"panel-template-alma9-"
)
with pytest.raises(TemplateError):
validate_image_url(OFFICIAL_9.replace("/almalinux/9/", "/almalinux/10/"))
with pytest.raises(TemplateError):
validate_image_url(OFFICIAL_9.replace("AlmaLinux-9-", "AlmaLinux-8-"))
with pytest.raises(TemplateError):
template_id_for(scope, digest, "8")
def qcow2_fixture(virtual_size=2 * 1024**3) -> bytes:
@ -120,3 +146,36 @@ def test_template_catalog_is_private_and_scoped_to_host_and_disk_pool(tmp_path):
store.get(other_scope, record["id"])
with pytest.raises(TemplateError):
store.add(scope, record)
def test_template_rename_preserves_image_record_and_host_scope(tmp_path):
data_dir = tmp_path / "data"
data_dir.mkdir(mode=0o700)
store = TemplateStore(data_dir)
scope = "a" * 64
other_scope = "b" * 64
template_id = template_id_for(scope, "c" * 64, "9")
record = {
"id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux",
"os_version": "9", "sha256": "c" * 64,
"volume_name": template_volume_name(template_id), "virtual_size": 2 * 1024**3,
}
store.add(scope, record)
store.add(scope, {**record, "id": "other", "name": "Another name"})
store.add(other_scope, {**record, "name": "Other host"})
with pytest.raises(TemplateError) as inaccessible:
store.rename(other_scope, "other", "Missing")
assert inaccessible.value.status == 404
with pytest.raises(TemplateError) as duplicate:
store.rename(scope, template_id, "another NAME")
assert duplicate.value.status == 409
for invalid in ("", "x" * 65, "bad\x7fentry"):
with pytest.raises(TemplateError):
store.rename(scope, template_id, invalid)
updated = store.rename(scope, template_id, " 新名称 ")
assert updated == {**record, "name": "新名称"}
assert TemplateStore(data_dir).get(scope, template_id) == updated
assert store.get(other_scope, template_id)["name"] == "Other host"
assert stat.S_IMODE(store.file.stat().st_mode) == 0o600

@ -153,6 +153,36 @@ def test_templates_are_isolated_by_host_scope_and_atomic_insert():
assert duplicate.value.status == 409
def test_database_template_rename_persists_only_name_and_rejects_duplicate():
store = MemoryStore()
templates = DatabaseTemplateStore(store)
scope = "a" * 64
other_scope = "b" * 64
record = {
"id": "alma9-12345678-abcdef0123456789", "name": "AlmaLinux 9",
"os_family": "AlmaLinux", "os_version": "9", "sha256": "f" * 64,
"volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2",
}
templates.add(scope, record)
templates.add(scope, {**record, "id": "second", "name": "Second"})
templates.add(other_scope, {**record, "name": "Other host"})
with pytest.raises(TemplateError) as duplicate_import:
templates.add(scope, {**record, "id": "third", "name": "ALMALINUX 9"})
assert duplicate_import.value.status == 409
with pytest.raises(TemplateError) as wrong_host:
templates.rename(other_scope, "second", "Missing")
assert wrong_host.value.status == 404
with pytest.raises(TemplateError) as duplicate_rename:
templates.rename(scope, record["id"], "second")
assert duplicate_rename.value.status == 409
updated = templates.rename(scope, record["id"], " 自定义名称 ")
assert updated == {**record, "name": "自定义名称"}
assert DatabaseTemplateStore(store).get(scope, record["id"]) == updated
assert templates.get(other_scope, record["id"])["name"] == "Other host"
def _host_key() -> str:
blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + b"a" * 32
return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii")

@ -1253,6 +1253,21 @@ class VMServiceTests(unittest.TestCase):
f"panel-seed-{reserved_uuid}.iso")
self.assertEqual(created["disks"][0]["capacity_gib"], 20)
def test_cloud_vm_accepts_almalinux_9_panel_template_volume(self):
service = self.cloud_service()
alma9_volume = "panel-template-alma9-12345678-0123456789abcdef.qcow2"
self.backend.pools["images"].volumes[alma9_volume] = FakeVolume(
self.backend.pools["images"], alma9_volume, capacity=2 * 1024**3,
)
with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED",
create=True):
created = service.create_cloud_vm(
self.cloud_spec(os_name="AlmaLinux 9"), alma9_volume,
)
self.assertEqual(created["os_name"], "AlmaLinux 9")
self.assertEqual(self.backend.pools["images"].volumes["cloud-vm.qcow2"].cloned_from,
alma9_volume)
def test_cloud_vm_clones_template_and_uses_nonboot_seed_iso(self):
service = self.cloud_service()
created = self.create_cloud_vm(service, self.cloud_spec(os_name="AlmaLinux 10"))

@ -24,6 +24,7 @@ except ModuleNotFoundError:
from tests.test_database_http import MemoryStore # noqa: E402
from virsh_panel import app as app_module # noqa: E402
from virsh_panel.auth import hash_password # noqa: E402
from virsh_panel.config import Settings # noqa: E402
from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore # noqa: E402
from virsh_panel.libvirt_service import VMError # noqa: E402
@ -195,6 +196,84 @@ def _register(client: TestClient, address: str, username: str):
assert response.json() == {"registered": True, "approved": False}
def test_template_rename_is_admin_only_and_ordinary_users_can_list(monkeypatch, tmp_path):
store = MemoryStore()
service = _Service()
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), _Manager(),
DatabaseTemplateStore(store), store,
))
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
settings = Settings(
data_dir=tmp_path / "data",
static_dir=Path(__file__).resolve().parents[1] / "static",
)
app = app_module.create_app(settings, service_factory=lambda _profile: service)
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
scope = template_scope(_Manager.profile)
template_id = "alma9-12345678-abcdef0123456789"
record = {
"id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux",
"os_version": "9", "sha256": "f" * 64,
"volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2",
}
endpoint = f"/api/v1/vm-templates/{template_id}"
with TestClient(app, base_url=ORIGIN) as admin:
assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 401
configured = admin.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "database-password", "setup_token": token,
})
assert configured.status_code == 200
created = admin.post("/api/v1/setup/admin", json={
"token": token, "username": "initial", "password": PASSWORD,
})
assert created.status_code == 200
admin_headers = {"X-CSRF-Token": created.json()["csrf_token"]}
templates = DatabaseTemplateStore(store)
templates.add(scope, record)
templates.add(scope, {**record, "id": "another", "name": "Other template"})
templates.add("b" * 64, {**record, "name": "Different host"})
assert admin.patch(endpoint, json={"name": "Rename"},
headers=admin_headers).status_code == 403
store.users.promote("initial")
store.set("test_user", "tenant", json.dumps({
"id": 2, "username": "tenant", "email": "tenant@example.test",
"password_hash": hash_password(PASSWORD), "admin": False,
"approved": True, "email_verified": True, "created_at": 100,
}))
with TestClient(app, base_url=ORIGIN) as tenant:
tenant_headers = _login(tenant, "tenant@example.test")
listed = tenant.get("/api/v1/vm-templates")
assert listed.status_code == 200
assert [row["id"] for row in listed.json()["templates"]] == [
template_id, "another",
]
assert tenant.patch(endpoint, json={"name": "Hijack"},
headers=tenant_headers).status_code == 403
assert tenant.post("/api/v1/vm-templates/import", json={
"name": "Extra", "url": "https://invalid.example/image.qcow2",
"sha256": "a" * 64,
}, headers=tenant_headers).status_code == 403
assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 403
assert admin.patch(endpoint, json={"name": "Other TEMPLATE"},
headers=admin_headers).status_code == 409
assert admin.patch(endpoint, json={"name": " "},
headers=admin_headers).status_code == 400
missing = admin.patch("/api/v1/vm-templates/missing", json={"name": "Missing"},
headers=admin_headers)
assert missing.status_code == 404
renamed = admin.patch(endpoint, json={"name": " AlmaLinux 9 Gold "},
headers=admin_headers)
assert renamed.status_code == 200
assert renamed.json()["template"] == {**record, "name": "AlmaLinux 9 Gold"}
assert DatabaseTemplateStore(store).get(scope, template_id) == renamed.json()["template"]
assert templates.get("b" * 64, template_id)["name"] == "Different host"
def test_registration_smtp_approval_and_per_user_vm_isolation(monkeypatch, tmp_path):
store = MemoryStore()
service = _Service()

@ -0,0 +1,134 @@
"""Guard the administrator-only image catalog and card-based VM image picker."""
from __future__ import annotations
from dataclasses import dataclass
from html.parser import HTMLParser
from pathlib import Path
import pytest
STATIC = Path(__file__).resolve().parents[1] / "static"
VOID_TAGS = {
"area", "base", "br", "col", "embed", "hr", "img", "input",
"link", "meta", "param", "source", "track", "wbr",
}
@dataclass(frozen=True)
class Element:
tag: str
attrs: dict[str, str | None]
ancestor_ids: tuple[str, ...]
class CatalogPageParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.elements: list[Element] = []
self.stack: list[Element] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
element = Element(
tag,
dict(attrs),
tuple(item.attrs["id"] for item in self.stack if item.attrs.get("id")),
)
self.elements.append(element)
if tag not in VOID_TAGS:
self.stack.append(element)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
if tag not in VOID_TAGS:
self.stack.pop()
def handle_endtag(self, tag: str) -> None:
for index in range(len(self.stack) - 1, -1, -1):
if self.stack[index].tag == tag:
del self.stack[index:]
return
@pytest.fixture(scope="module")
def page() -> tuple[list[Element], dict[str, Element]]:
parser = CatalogPageParser()
parser.feed((STATIC / "index.html").read_text(encoding="utf-8"))
assert not parser.stack, "Unclosed HTML element in the dashboard page"
by_id = {element.attrs["id"]: element for element in parser.elements if element.attrs.get("id")}
assert len(by_id) == sum(bool(element.attrs.get("id")) for element in parser.elements)
return parser.elements, by_id
def test_image_import_is_on_a_dedicated_admin_page(page) -> None:
_, by_id = page
workspace = by_id["template-workspace"]
assert "hidden" in workspace.attrs
assert "dashboard-view" in workspace.ancestor_ids
form = by_id["template-import-form"]
assert form.tag == "form"
assert "template-workspace" in form.ancestor_ids
for element_id in ("template-name", "template-url", "template-sha256", "template-import-button"):
assert "template-import-form" in by_id[element_id].ancestor_ids
assert "create-view" not in by_id[element_id].ancestor_ids
assert "reinstall-view" not in by_id[element_id].ancestor_ids
assert "template-workspace" in by_id["template-admin-list"].ancestor_ids
assert "template-import" not in by_id, "The old inline import details must be removed"
@pytest.mark.parametrize(
("form_id", "field_id", "catalog_id"),
[
("create-form", "vm-template", "vm-template-catalog"),
("reinstall-form", "reinstall-template", "reinstall-template-catalog"),
],
)
def test_vm_image_selection_uses_cards_not_selects(
page, form_id: str, field_id: str, catalog_id: str
) -> None:
elements, by_id = page
field = by_id[field_id]
catalog = by_id[catalog_id]
assert field.tag == "input"
assert field.attrs.get("type") == "hidden"
assert field.attrs.get("name") == "template_id"
assert form_id in field.ancestor_ids
assert catalog.tag == "div"
assert "template-catalog" in (catalog.attrs.get("class") or "").split()
assert form_id in catalog.ancestor_ids
assert not any(
element.tag == "select"
and element.attrs.get("name") == "template_id"
and form_id in element.ancestor_ids
for element in elements
)
def test_catalog_renders_expandable_family_and_version_cards() -> None:
script = (STATIC / "app.js").read_text(encoding="utf-8")
assert 'makeElement("details", "template-family-card")' in script
assert 'makeElement("button", "template-version-option")' in script
assert 'option.dataset.templateId = id;' in script
assert 'option.setAttribute("aria-pressed"' in script
assert 'input.value = id;' in script
def test_admin_only_catalog_navigation_and_rename_control() -> None:
script = (STATIC / "app.js").read_text(encoding="utf-8")
session_code = script.split("function applySession(session) {", 1)[1].split(
"async function continueAfterLogin", 1
)[0]
for element_id in ("template-settings-button", "template-settings-mobile-button"):
assert f'"{element_id}"' in session_code
assert 'byId(id).hidden = !state.admin;' in session_code
rename_code = script.split("function renderTemplateAdminList() {", 1)[1].split(
"function fillTemplateViews", 1
)[0]
assert 'makeElement("form", "template-admin-row")' in rename_code
assert 'name.type = "text";' in rename_code
assert 'method: "PATCH"' in rename_code
assert 'encodeURIComponent(id)' in rename_code

@ -24,8 +24,8 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr
from .auth import DatabaseSessionStore, LoginLimiter, Session, SessionStore, verify_password
from .cloud_init import _validate_guest_auth, generate_root_password, hash_root_password
from .cloud_templates import (
TemplateError, TemplateStore, download_verified_image, template_id_for,
template_scope, template_volume_name, validate_image_url, validate_template_name,
TemplateError, TemplateStore, download_verified_image, image_version_for, template_id_for,
template_scope, template_volume_name, validate_template_name,
)
from .config import Settings
from .console import ConsoleRelayError, relay_console
@ -208,6 +208,12 @@ class ImportTemplateBody(BaseModel):
name: str = Field(min_length=1, max_length=64)
class RenameTemplateBody(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=64)
class ReinstallBody(BaseModel):
model_config = ConfigDict(extra="forbid")
@ -1296,6 +1302,8 @@ def create_app(
record = {
"id": template_id,
"name": body.name,
"os_family": "AlmaLinux",
"os_version": image_version_for(body.url),
"sha256": body.sha256.lower(),
"volume_name": volume_name,
"virtual_size": virtual_size,
@ -1326,17 +1334,21 @@ def create_app(
@app.post("/api/v1/vm-templates/import", status_code=202)
def import_template(body: ImportTemplateBody, _session: Session = Depends(require_admin_write)):
profile = current_profile()
validate_image_url(body.url)
version = image_version_for(body.url)
name = validate_template_name(body.name)
body = body.model_copy(update={"name": name})
if not all(char in "0123456789abcdefABCDEF" for char in body.sha256):
raise TemplateError("SHA-256 校验值必须是十六进制")
scope = template_scope(profile)
template_id = template_id_for(scope, body.sha256.lower())
template_id = template_id_for(scope, body.sha256.lower(), version)
with import_lock:
forbid_long_job_during_update()
if any(row["id"] == template_id for row in templates.list(scope)):
existing_templates = templates.list(scope)
if any(row["id"] == template_id for row in existing_templates):
raise TemplateError("此云镜像已经导入", 409)
if any(row["name"].casefold() == name.casefold()
for row in existing_templates):
raise TemplateError("当前宿主机已有同名云镜像模板", 409)
if (scope, template_id) in pending_templates:
raise TemplateError("该云镜像正在导入", 409)
if pending_templates:
@ -1356,6 +1368,15 @@ def create_app(
LOG.info("cloud template import queued: job=%s admin=%s", job_id, _session.username)
return {"job_id": job_id, "status": "running"}
@app.patch("/api/v1/vm-templates/{template_id}")
def rename_template(template_id: str, body: RenameTemplateBody,
_session: Session = Depends(require_admin_write)):
scope = template_scope(current_profile())
with import_lock:
if pending_templates:
raise TemplateError("云镜像正在导入,请稍后修改模板名称", 409)
return {"template": templates.rename(scope, template_id, body.name)}
@app.get("/api/v1/vm-templates/import-jobs/{job_id}")
def import_job(job_id: str, _session: Session = Depends(require_admin)):
scope = template_scope(current_profile())

@ -24,8 +24,8 @@ MAX_VIRTUAL_BYTES = 4096 * 1024**3
MAX_DOWNLOAD_SECONDS = 3600
GIB = 1024**3
IMAGE_PATH = re.compile(
r"/almalinux/10/cloud/x86_64/images/"
r"AlmaLinux-10-GenericCloud-[A-Za-z0-9._-]+\.x86_64\.qcow2\Z"
r"/almalinux/(?P<version>9|10)/cloud/x86_64/images/"
r"AlmaLinux-(?P=version)-GenericCloud-[A-Za-z0-9._-]+\.x86_64\.qcow2\Z"
)
SHA256_RE = re.compile(r"[0-9a-fA-F]{64}\Z")
@ -67,24 +67,34 @@ def validate_image_url(url: str) -> str:
if (parsed.scheme != "https" or parsed.hostname != "repo.almalinux.org"
or port not in (None, 443) or parsed.username or parsed.password
or parsed.query or parsed.fragment or not IMAGE_PATH.fullmatch(parsed.path)):
raise TemplateError("仅支持 AlmaLinux 官方仓库的 10 x86_64 GenericCloud qcow2 镜像")
raise TemplateError("仅支持 AlmaLinux 官方仓库的 9/10 x86_64 GenericCloud qcow2 镜像")
return url
def image_version_for(url: str) -> str:
"""Derive the OS major version from an already restricted official URL."""
validate_image_url(url)
match = IMAGE_PATH.fullmatch(urlsplit(url).path)
assert match is not None
return match.group("version")
def validate_template_name(name: str) -> str:
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 64:
raise TemplateError("模板名称应为 1 至 64 个字符")
if any(ord(char) < 32 for char in name):
if any(ord(char) < 32 or ord(char) == 127 for char in name):
raise TemplateError("模板名称不能包含控制字符")
return name.strip()
def template_id_for(scope: str, digest: str) -> str:
return f"alma10-{scope[:8]}-{digest[:16]}"
def template_id_for(scope: str, digest: str, version: str = "10") -> str:
if version not in ("9", "10"):
raise TemplateError("云镜像系统版本无效")
return f"alma{version}-{scope[:8]}-{digest[:16]}"
def template_volume_name(template_id: str) -> str:
if not re.fullmatch(r"alma10-[0-9a-f]{8}-[0-9a-f]{16}", template_id):
if not re.fullmatch(r"alma(?:9|10)-[0-9a-f]{8}-[0-9a-f]{16}", template_id):
raise TemplateError("模板标识无效")
return f"panel-template-{template_id}.qcow2"
@ -234,6 +244,27 @@ class TemplateStore:
if any(item.get("scope") == scope and item.get("id") == record["id"]
for item in data["templates"]):
raise TemplateError("此云镜像已导入", 409)
if any(item.get("scope") == scope
and item.get("name", "").casefold() == record["name"].casefold()
for item in data["templates"]):
raise TemplateError("当前宿主机已有同名云镜像模板", 409)
data["templates"].append({**record, "scope": scope})
self._write(data)
return record
def rename(self, scope: str, template_id: str, name: str) -> dict:
name = validate_template_name(name)
with self._locked():
data = self._read()
target = next((record for record in data["templates"]
if record.get("scope") == scope and record.get("id") == template_id),
None)
if target is None:
raise TemplateError("模板不存在或不属于当前宿主机", 404)
if any(record.get("scope") == scope and record.get("id") != template_id
and record.get("name", "").casefold() == name.casefold()
for record in data["templates"]):
raise TemplateError("当前宿主机已有同名云镜像模板", 409)
target["name"] = name
self._write(data)
return {key: value for key, value in target.items() if key != "scope"}

@ -33,7 +33,7 @@ try:
except ImportError: # Allows package tooling to import without optional DB extras.
pymysql = None
from .cloud_templates import TemplateError
from .cloud_templates import TemplateError, validate_template_name
from .panel_state import PanelState, SetupError, _USERNAME
from .remote_host import (
LIBVIRT_URI,
@ -543,11 +543,27 @@ class DatabaseTemplateStore:
if not isinstance(record, dict) or not isinstance(record.get("id"), str):
raise TemplateError("模板记录无效")
key = f"{scope}:{record['id']}"
if any(row.get("id") != record["id"]
and row.get("name", "").casefold() == record["name"].casefold()
for row in self.list(scope)):
raise TemplateError("当前宿主机已有同名云镜像模板", 409)
if not self.store.insert("template", key, json.dumps(
record, ensure_ascii=False, separators=(",", ":"))):
raise TemplateError("此云镜像已导入", 409)
return record
def rename(self, scope: str, template_id: str, name: str) -> dict:
name = validate_template_name(name)
record = self.get(scope, template_id)
if any(row.get("id") != template_id
and row.get("name", "").casefold() == name.casefold()
for row in self.list(scope)):
raise TemplateError("当前宿主机已有同名云镜像模板", 409)
updated = {**record, "name": name}
self.store.set("template", f"{scope}:{template_id}", json.dumps(
updated, ensure_ascii=False, separators=(",", ":")))
return updated
class DatabaseStagedHost(StagedHost):
def __init__(self, staged: StagedHost, wrapper_path: Path,

@ -32,7 +32,7 @@ GIB = 1024**3
PANEL_NS = "urn:virsh-panel:1"
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z")
BRIDGE_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z")
TEMPLATE_VOLUME_RE = re.compile(r"panel-template-alma10-[0-9a-f]{8}-[0-9a-f]{16}\.qcow2\Z")
TEMPLATE_VOLUME_RE = re.compile(r"panel-template-alma(?:9|10)-[0-9a-f]{8}-[0-9a-f]{16}\.qcow2\Z")
_CREATE_LOCK = threading.RLock()
REINSTALL_SHUTDOWN_TIMEOUT = 120
REINSTALL_SHUTDOWN_POLL_INTERVAL = 1

Loading…
Cancel
Save