Compare commits

...

191 Commits
main ... dev

Author SHA1 Message Date
admin 887072ac61 fix: confirm generic VM power action state 1 month ago
admin be5efa7033 fix: guard inactive snapshot reconciliation stats 1 month ago
admin a578502798 fix: clean libvirt metadata on VM deletion 1 month ago
admin 5b8240939b fix: accept random reinstall seed cleanup identities 1 month ago
admin 287670d584 fix: recover reinstall review codes after restart 1 month ago
admin 177ebb7cb6 fix: mark reinstall cleanup failures uncertain 1 month ago
admin d3bba00f14 fix: remove account instance count cap 1 month ago
admin 13aacd7636 docs: avoid stale remote hash in validation 1 month ago
admin ce9d77f999 docs: align final remote revision 1 month ago
admin 78cadb051f docs: record final deployment smoke revision 1 month ago
admin 36636221f7 docs: add deployment page smoke check 1 month ago
admin e7230fffe2 fix: stop querying removed host address column 1 month ago
admin fc01273112 Document private engine compatibility endpoints 1 month ago
admin 521d40ae72 Remove host inventory from panel scheduling 1 month ago
admin 2bac113155 fix: preserve inventory failure terminal logs 1 month ago
admin 6dbd1fe593 fix: reveal system log detail drawer 1 month ago
admin 67e59a263a fix: make admin system logs bounded and inspectable 1 month ago
admin 212f770154 fix: include direct policy worker journal 1 month ago
admin b5ed1e130d fix: surface journal permission failures 1 month ago
admin b1429f61b4 feat: add admin system journal log page 1 month ago
admin e290872e5a feat: allow admins to stop retrying destructive jobs 1 month ago
admin 4ec4fefc30 fix: preserve detailed inventory failure diagnostics 1 month ago
admin b333246e9f fix: skip inactive snapshot job stats on delete 1 month ago
admin 04e12d1906 fix: reconcile inventory and VM deletion races 1 month ago
admin 9f0d16600d feat: add per-instance platform test policies 1 month ago
admin 40f9c549da feat: enforce default platform network policy 1 month ago
admin 7d60707246 fix: preserve unrestricted firewall egress 1 month ago
admin 38fd302195 fix: left align firewall action column 1 month ago
admin 2112379323 fix: align firewall rule controls 1 month ago
admin 41528cfc76 fix: refine mobile firewall rule layout 1 month ago
admin d51b169ffc fix: preserve firewall filter uuid on update 1 month ago
admin ecd65d6b65 feat: add per-instance cloud firewall 1 month ago
admin afbd8c2941 feat: add local live snapshots 1 month ago
admin 3e2b36723a fix: refine inline instance name editor 2 months ago
admin 3f9d3d2d63 feat: add inline instance display-name editing 2 months ago
admin b8105fab23 fix: gate update consumers on engine readiness 2 months ago
admin 9bb5d30b0a fix: streamline instance checkout flow 2 months ago
admin 7b70b8f285 fix: decouple inventory reads from host mutations 2 months ago
admin 12e20d150f feat: add host inventory diagnostics and admin history 2 months ago
admin fad3b4e4fd fix: extend host inventory timeout 2 months ago
admin 77566fc15c fix: converge live VM shutdown status 2 months ago
admin b7c4cc270c fix: preserve public pool identity on VM create 2 months ago
admin 59dd1e4d33 docs: define multi-CIDR pool operations 2 months ago
admin 9c84724eb1 feat: manage host public IP pools 2 months ago
admin b9a2829bed fix: guard host network line reassignment 2 months ago
admin ff75762a75 fix: preserve pending public pool intent 2 months ago
admin f3ca55b5e4 feat: allocate from multiple public pools 2 months ago
admin f3822ac66d feat: sync multi-pool host inventory 2 months ago
admin 7f804125b5 feat: add revisioned multi-CIDR engine pools 2 months ago
admin ff0cdcb620 feat: add multi-public-pool data model 2 months ago
admin 6d6e497db0 fix: correct host memory capacity units 2 months ago
admin f2c624b2db fix: clarify resource region fields 2 months ago
admin 069c7f1b56 fix: repair host configuration retries 2 months ago
admin 514861f562 fix: validate host public network settings 2 months ago
admin 5e8f623e2a feat: close offer availability against pool capacity 2 months ago
admin 328b18b8e3 refactor: update host placement guidance 2 months ago
admin 3fcebe4d40 security: keep ambiguous deletes non-replayable 2 months ago
admin 0347169753 refactor: remove the retired user storefront 2 months ago
admin 4f889fb1cc security: hide host placement from tenant responses 2 months ago
admin f0ad01fb47 feat: deploy instances from regional offers 2 months ago
admin 8b9d8d7e82 feat: schedule paid orders across host pools 2 months ago
admin 05f42e51bf feat: separate base plans from sales offers 2 months ago
admin 74cd779901 feat: configure host placement policies 2 months ago
admin d6b6d390d5 feat: add resource scheduling administration 2 months ago
admin 68108b3f38 feat: sync host capacity and public IP inventory 2 months ago
admin a07e11c681 feat: add multi-host resource data model 2 months ago
admin 5c8d95bd9a feat: provision instances with reserved public IPs 2 months ago
admin 3c305a552d feat: expose host capacity snapshots from engine 2 months ago
admin fe43fdbf9c refactor: remove retired frontend residues 2 months ago
admin 5e71f81c5a feat: animate user and admin drawers 2 months ago
admin 40d32f5bfc refactor: reuse password result card 2 months ago
admin 4559cc57b2 refactor: redesign user instance settings 2 months ago
admin ecc15d56f1 feat: add user instance settings 2 months ago
admin a94c5667a8 feat: merge instance traffic into usage records 2 months ago
admin 8829ad009d fix: apply updated root passwords through cloud-init chpasswd 2 months ago
admin 95787ca9c3 feat: add admin instance settings controls 2 months ago
admin a442dd0292 fix: render cached VM state on detail pages 2 months ago
admin cf2a4e3ec4 feat: cache VM runtime status for instant list rendering 2 months ago
admin b2c19d18bb fix: handle admin user referral collections safely 2 months ago
admin 8658d6b4e6 refactor: remove duplicate admin permission client logic 2 months ago
admin 8944cf3588 security: sanitize cloud operation diagnostics 2 months ago
admin c133b788f4 fix: make ticket replies transactional 2 months ago
admin b5a6b792e1 refactor: centralize cloud operation labels 2 months ago
admin 982aa16449 feat: select available host public IPs 2 months ago
admin 6b143a02e1 fix: reapply guest network after public IP change 2 months ago
admin 6c223a3ead fix: render admin network permissions server-side 2 months ago
admin 3a7e272b04 fix: bump venix asset cache version 2 months ago
admin 92b2e9666e feat: add admin public IP network change 2 months ago
admin 407d368892 feat: bind clean traffic to panel cloud VMs 2 months ago
admin 59ff1e1d43 refactor: paginate instance operation logs 2 months ago
admin b2368a86da feat: add instance operation logs 2 months ago
admin 5c98954067 fix: balance recharge prefix spacing 2 months ago
admin 433e34c5f5 fix: refine recharge amount prefix 2 months ago
admin 6b292373c6 fix: remove mobile drawer focus flashes 2 months ago
admin a912b1c39e perf: preload user account drawers 2 months ago
admin d96dfa3166 fix: remove remaining user link underlines 2 months ago
admin efbadcfbf2 fix: remove underlines from user buttons 2 months ago
admin 2a50650059 fix: keep reinstall name copy inline on mobile 2 months ago
admin 1e52eb28d2 feat: show reinstall password receipt 2 months ago
admin e8004b6b52 feat: improve reinstall name confirmation 2 months ago
admin a942124549 feat: route instance creation to invoice payment 2 months ago
admin fb855241d0 fix: restore admin ticket view rendering 2 months ago
admin 8419152f1c fix: restore promotion hint side spacing 2 months ago
admin 56b28045c0 fix: align ticket summary and referral hint 2 months ago
admin 45eed216ba revert: restore legacy ticket layouts 2 months ago
admin 611c1949ce fix: keep ticket uploads outside online update status 2 months ago
admin d3ce270654 feat: redesign ticket desk and harden admin view 2 months ago
admin d791fc5f1d feat: rebuild ticket workflow with image uploads 2 months ago
admin cac637c615 feat: add compact account feedback toasts 2 months ago
admin c98b43988f fix: correct mobile currency displays and overflow 2 months ago
admin 9d40f5095f feat: redesign compact account drawer pages 2 months ago
admin b58473a52f fix: apply referral migration during cloud init 2 months ago
admin dd3dcedb8b feat: move account tools into user menu and add referral security flows 2 months ago
admin c5a7ca6d35 fix: refresh announcements whenever drawer opens 2 months ago
admin 7353f9f7eb fix: retain announcement read time during silent refresh 2 months ago
admin 1df35d092d fix: refresh announcement drawer silently 2 months ago
admin 6902215b2f feat: add plain-text announcements and user drawer 2 months ago
admin 5f5f89c68b feat: add admin runtime and abnormal task diagnostics 2 months ago
admin 8759373324 style: align cloud product editor with Venix layout 2 months ago
admin eca57ab75f feat: improve admin billing views and detail drawer 2 months ago
admin 5905699742 feat: improve admin virtual machine inventory and details 2 months ago
admin 5919dff9a9 fix: lock mobile admin sidebar viewport and restore scrolling 2 months ago
admin 8338b3ce21 fix: prevent stale admin page flash 2 months ago
admin b7efaa282c fix: fill mobile admin navigation viewport 2 months ago
admin f781e5065d fix: compact admin overview and billing layout 2 months ago
admin 8b2cb35b58 fix: stabilize mobile admin navigation 2 months ago
admin 3aeeff22a7 fix: prevent mobile admin navigation flash 2 months ago
admin 73afe9db50 fix: restore legacy admin page styling 2 months ago
admin 18e22dacee feat: add admin operations overview 2 months ago
admin eb21b2ad92 feat: unify admin billing and retire bought ledger 2 months ago
admin 34259bd277 feat: merge Telegram settings into ticket system 2 months ago
admin 1e2f8aba60 feat: refresh admin UI and manage Telegram settings 2 months ago
admin 4c3e98cad7 perf: server-render SSH key page 2 months ago
admin 2df07d9143 fix: configure Debian 12 networking through cloud-init 2 months ago
admin f51ee5268e fix: restore Debian 12 guest networking 2 months ago
admin 9695f4c68c fix: activate Debian 12 networking before wait-online 2 months ago
admin 0c98d4e336 fix: persist Debian 12 guest networking 2 months ago
admin 26ca956431 fix: avoid Debian first-boot network rename race 2 months ago
admin 99b4e96405 fix: bring Debian 12 network up on first boot 2 months ago
admin a6cccf5951 fix: preserve cloud image upload responses 2 months ago
admin b2654590c1 feat: add browser cloud image uploads 2 months ago
admin d92f3570d4 fix: remove duplicate traffic formatter 2 months ago
admin ebf1860d45 feat: delete cloud templates and optimize invoice details 2 months ago
admin f8bf9cf171 feat: separate instance display and resource names 2 months ago
admin a4b2ee923e fix: refine deployment selectors 2 months ago
admin 44f681efa8 refactor: remove retired user pages 2 months ago
admin 8e201ace0f fix: harden generated root passwords 2 months ago
admin 8f1fa892de fix: simplify mobile plan selection 2 months ago
admin 3ba575213e feat: compact mobile instance plans 2 months ago
admin 542e8fa10e fix: keep mobile image menu inside card 2 months ago
admin 2d22f41ed6 fix: prevent mobile image menu overlap 2 months ago
admin 059dcf0f6f fix: remove mobile image card tap flash 2 months ago
admin 85839e097e fix: anchor mobile image version menu 2 months ago
admin 961c90b361 refine system image selection cards 2 months ago
admin a8336ee468 fix: refine mobile image version picker 2 months ago
admin 149bb28a1d fix: stabilize deployment selectors 2 months ago
admin b82abf5547 perf: render deployment workflows on first response 2 months ago
admin dad9fa6ad2 feat: add themed lifecycle email notifications 2 months ago
admin 64205cf8f2 fix: remove legacy cloud image import restriction 2 months ago
admin 40248c1064 feat: support official multi-os cloud images 2 months ago
admin 308977473f feat: share cloud images across regions 2 months ago
admin 59f262b9aa fix: prevent template loading flicker 2 months ago
admin 352ac4bdb8 fix: restore instance metadata after SSR 2 months ago
admin ea84d9519e perf: server-render instance pages 2 months ago
admin 1e1f68d503 perf: render billing first page server-side 2 months ago
admin 0dae9397b0 perf: streamline cloud deployment and billing 2 months ago
admin d510eeca36 refactor: add invoice detail payment flow 2 months ago
admin 73b4c12d19 refactor: streamline instance plan selection 2 months ago
admin 83bf4b0f29 feat: add global user ISO deployment workflow 2 months ago
admin d7262885ea fix: compact saved SSH key cards 2 months ago
admin 32ac875475 refactor: split cloud pages into real routes 2 months ago
admin 2ef392ffa9 feat: provision instances through unified invoices 2 months ago
admin 4bb98a3de8 Enforce invoice grace cleanup and refine traffic panel 2 months ago
admin de871e0d74 Preserve web-readable modes after updates 2 months ago
admin 9809b2cee2 Prevent online update service outage 2 months ago
admin 9689e386f0 Add renewal billing and traffic views 2 months ago
admin c27fab1cff Add secure admin online updates 2 months ago
admin 772fa83ae4 Add prepaid lifecycle and traffic enforcement 2 months ago
admin 74b89051a7 Refine provisioning order layout 2 months ago
admin 5044441aba Fix empty VM discovery ownership payload 2 months ago
admin c6e36159d5 Fix provisioning reconciliation and VM discovery 2 months ago
admin 0c7c8a7022 Assign discovered host VMs to administrator 2 months ago
admin 52294f7c3f Fix plan host binding and optional image checksum 2 months ago
admin aac5024245 Align instance deployment pages 2 months ago
admin 848318b65a Unify user pages on VM panel shell 2 months ago
admin d99dca3ff3 Bust cached user interface assets 2 months ago
admin 1f4051a030 Polish user navigation and responsive UI 2 months ago
admin bb9b244364 Initialize log metrics schema on fresh installs 2 months ago
admin 4bfda1cc9a Integrate Venix sales portal with private libvirt engine 2 months ago
admin f535424087 Remove orphaned traffic trigger from pruned log schema 2 months ago
admin a4947c0c24 Initialize venix Virt Cloud project with pruned PHP sales foundation 2 months ago

45
.gitignore vendored

@ -1,7 +1,40 @@
.venv/
data/
__pycache__/
.pytest_cache/
*.py[cod]
*.egg-info/
# Local environment, credentials and machine metadata
.DS_Store
.env
.env.*
!.env.example
!.env.sample
.user.ini
master.key
id_rsa
id_ed25519
*.key
*.pem
*.p12
# Installed dependencies and runtime data
/web/vendor/
/web/node_modules/
/web/config/.config.php
/web/storage/backups/
/web/storage/logs/
/web/storage/cloud-runtime/
/web/storage/ticket-attachments/
/web/storage/framework/smarty/compile/*
/web/storage/framework/smarty/cache/*
/web/storage/framework/views/*
!/web/storage/framework/views/.gitignore
*.log
*.sqlite
*.sqlite3
# Local archives; source SQL under web/sql remains versioned
*.zip
*.tar
*.tar.gz
*.tgz
*.sql.gz
runtime/
web/config/config.php
engine/.venv/
engine/**/__pycache__/

@ -0,0 +1,37 @@
# Virt Cloud development rules
- This repository is the independent Virt Cloud project. Work only inside this
checkout unless the user explicitly authorizes changes to another project.
- When a task depends on historical decisions, test results, or project
context, and the knowledge vault is available, first read
`/Users/admin/Documents/www/codex-knowledge/AGENTS.md`, then
`Memory/INDEX.md` and `Memory/CURRENT.md`; follow only the linked notes
relevant to the task. If the vault is unavailable, say so explicitly and do
not guess the old project state.
- The Git remote is `https://g.luoli.live/root/virt.git`.
- All subsequent changes, commits and pushes for this project must use the
`venix` branch. Do not commit or push them to `main` or force-push.
- Before editing or committing, check the current branch and working tree.
Preserve unrelated user changes. If this checkout is not on `venix`, stop
before changing files and resolve the branch safely.
- Never commit real configuration, credentials, private keys, database dumps,
installed dependencies, runtime logs or caches. Keep source configuration
examples and source schema files versioned.
- The PHP application lives in `web/`; its eventual HTTP document root is
`web/public/`, not the repository root.
- Only the venix theme is retained. Ordinary users must not receive host
administration or retired node-management routes.
- PHP owns accounts, wallet purchases, orders, public-key ownership and public
HTTP authorization. The Python engine owns libvirt, host credentials and VM
operations. Keep the engine private and authenticate every internal request.
- Purchases provision one VM from the plan snapshot. Each purchase or renewal
creates an independent prepaid service period with its own traffic quota.
An exhausted quota disconnects VM networking until the next paid period;
final expiry disconnects networking without powering off the VM. An unpaid
renewal invoice enters a three-day grace period and then permanently removes
the VM definition and its panel-managed disks. Never replay an ambiguous
destructive operation or refund it without confirmed cleanup; reconcile its
operation identifier.
- Users share the original VM-panel styling; administrator pages retain venix.
- See `docs/PRUNING_REPORT.md` for retained/removed feature boundaries and
`docs/INTEGRATION_PLAN.md` for the planned Python engine integration.

@ -1,12 +0,0 @@
# 操作系统图标来源
这些图标随面板保存在 `static/`,页面运行时不向图标来源站点发起请求。它们仅用于标识实际系统模板,不表示发行版项目或商标持有人认可本面板。
| 本地文件 | 官方来源 | 使用说明 |
| --- | --- | --- |
| `static/almalinux-icon.svg` | [AlmaLinux 官方圆形图标](https://almalinux.org/branding/AlmaLinux%20Icon%20Circle.svg) | 保留官方图形及颜色;参阅 [AlmaLinux 品牌规范](https://almalinux.org/branding/brand-book)。 |
| `static/debian-icon.svg` | [Debian Open Use Logo(无文字版)](https://www.debian.org/logos/openlogo-nd.svg) | Copyright © 1999 Software in the Public Interest, Inc.;官方提供 LGPL-3.0-or-later 或 [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/) 双重许可。此本地 SVG 移除了原文件的外部 DTD 与 Illustrator 元数据,图形路径和颜色保持不变。参阅 [Debian 图标说明](https://www.debian.org/logos/)。 |
| `static/centos-icon.svg` | [CentOS 官网图形标识](https://www.centos.org/assets/img/centos-symbol.svg) | 保留官方图形及颜色;参阅 [CentOS 商标指南](https://www.centos.org/legal/trademarks/)。 |
| `static/ubuntu-icon.svg` | [Canonical 官方 Circle of Friends SVG](https://assets.ubuntu.com/v1/ce518a18-CoF-2022_solid+O.svg) | 保留官方图形及颜色;参阅 [Canonical 知识产权政策](https://canonical.com/legal/intellectual-property-policy)。 |
目前后端仍只允许导入 AlmaLinux 9/10 镜像。预存另外三个图标不等于已开放对应系统的镜像导入、创建或销售。未来正式提供商业套餐前,应核对相应镜像的再分发条件和商标使用要求,尤其是 CentOS 的商业使用限制。

@ -1,129 +1,50 @@
# VirtPilot:远端 virsh/libvirt 面板
项目提供面板程序、Python 依赖清单和可选的 [systemd service 文件](deploy/virsh-panel.service),没有安装器或反向代理配置。面板运行在管理服务器 A,默认只监听 `127.0.0.1:8000`;AlmaLinux 10 的 virsh 宿主机 B 通过已有的 root SSH 密钥连接。B 不需要安装面板、创建新账号或导入新公钥。面板使用 [libvirt 官方 SSH 连接方式](https://www.libvirt.org/uri.html)管理 `qemu:///system`,VNC 经 SSH 连接 B 的本机端口。
这一版的持久化面板数据使用 **MariaDB**。首次打开网页会先配置数据库连接、创建初始账户;初始账户可不填写邮箱,由你随后在 MariaDB 手动补齐。之后所有用户**只能使用邮箱和密码登录**,用户名仅用于显示、注册和数据库管理,不能作为登录凭据。初始账户的 `admin` 字段初始为 `0`,需由你手工在数据库升为管理员,之后才能在网页配置宿主机和 SMTP。数据库及有建表权限的专用账号需要你事先准备;面板不会安装 MariaDB 或自动创建数据库。旧版 `data/state.json`、`data/templates.json` 和本地宿主机配置**不会自动迁移**。虚拟机定义和虚拟磁盘仍由远端 libvirt/宿主机持有,数据库保存用户、邮箱验证码、虚拟机归属、登录会话、SMTP 设置、模板目录、宿主机连接资料、更新设置、更新任务及虚拟机性能历史等面板数据。
如果是在旧测试目录上替换代码,旧 `data/generations/` 中的明文 SSH 私钥不会被新版使用,也**不会自动删除**。为避免遗留敏感文件,建议先备份并核对后,在首次运行新版前使用全新的 `data/` 目录;不要未经核对直接删除仍需使用的资料。
## 目录与依赖
面板目录固定为 `/home/virsh-panel`。代码、静态资源、`.venv/` 和启动后自动创建的 `data/` 都在这个目录下;**不会把持久面板业务数据放到 `/var`**。本地 `data/` 的持久敏感文件仅有连接 MariaDB 所必需的加密引导配置、0600 主密钥和初始化阶段的令牌;还会有锁文件及不含密钥的 SSH 运行包装器。主密钥与数据库备份须分别安全保管;只有数据库而丢失主密钥,已加密的宿主机资料及更新令牌将无法恢复。不要把 `/home/virsh-panel` 当作 Web 静态目录对外提供。
管理服务器 A 需要 Python 3、`pip`、Python 的 libvirt 绑定和 OpenSSH 客户端(包含 `ssh`、`ssh-keyscan`、`ssh-keygen`、`ssh-agent`、`ssh-add`),另需 MariaDB 数据库。如果 A 也是 AlmaLinux 10,对应 RPM 是 `python3`、`python3-pip`、`python3-libvirt`、`openssh-clients`;Python 依赖在 `requirements.txt` 中,包括 FastAPI、Uvicorn、Pydantic、pycdlib、Passlib、PyMySQL 和 cryptography。`static/vendor/` 已包含浏览器 VNC 前端,无需 npm。请自行安装这些依赖;面板没有安装器。
宿主机 B 需已有正常工作的 SSH 服务、`/usr/bin/virsh`、libvirt/QEMU 服务,以及 root 账号已授权的公钥。libvirt 的 SSH 传输优先使用宿主机上的原生代理,不可用时可能回退到 `nc`;若网页测试提示 libvirt 连接失败,可检查 B 是否有 `virt-ssh-helper` 或兼容 `nc -U` 的工具。[libvirt 传输参数说明](https://www.libvirt.org/uri.html)。
## 启动
把整个项目放到 `/home/virsh-panel`,保持代码和虚拟环境仅 root 可修改。创建 `.venv` 时务必使用 `--system-site-packages`,让虚拟环境可以读取系统安装的 `python3-libvirt`;不要把 FastAPI 等依赖装到系统 Python。以下命令在 A 上执行,软件安装本身由你完成:
```bash
cd /home/virsh-panel
python3 -m venv --system-site-packages .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python -c 'import libvirt; print("libvirt Python 绑定可用")'
PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m uvicorn virsh_panel.app:create_app --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1
# Virt Cloud
PHP 8.5 网站与私有 Python/libvirt 引擎集成的虚拟机销售面板。使用 `venix` 分支;`main` 的原 virsh-panel 不受影响。
## 本版功能
- PHP 统一注册、邮箱登录、账户、充值、支付、SMTP、工单;注册后无需创建审核。注册验证、密码重置、自动续费账单和实例开通成功通知均使用统一的用户面板邮件主题。
- 用户购买套餐开通 VM,余额扣款、库存扣减、确认创建失败退款;可手动续费,续费从已购期限末尾顺延。
- 套餐绑定宿主机,提供 CPU、内存、磁盘、网络带宽、账期天数和每期流量额度,用户不能随意修改套餐资源。
- 下载 RX 与上传 TX 按字节累加计费;当期额度用尽只断开 VM 网卡,不关机,下一已付费账期开始自动归零当期用量并恢复网络;无后续账期的最终到期才停机。
- 管理员管理多宿主机、全局云镜像目录和独立救援 ISO;云镜像既可从受信任的官方 HTTPS 地址下载,也可由管理员在浏览器上传不超过 4 GiB 的独立 QCOW2。支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10 和 Ubuntu 20.04/22.04/24.04/25.04/25.10/26.04。用户切换地区时云镜像选择保持不变,首次部署由引擎按需同步到目标宿主机并缓存复用。
- 用户仅操作自己的 VM:控制台、开关机、软/硬重启、重装、救援、删除、初始 root 密码查看/复制。
- CPU、内存、磁盘 I/O、网络带宽图表;后台持续采集,写入日志库,最长保留 30 天。
- 全部用户页及登录页使用原虚拟机面板风格;管理员后台保留 venix 样式。
- 宿主机凭据及任务密码等敏感数据加密保存;内部请求签名,控制台使用短时一次性凭据。
- 超级管理员在线检查并更新固定 Gitea 私有仓库的 `venix` 分支;访问令牌由私有引擎加密保存且永不回显,更新由独立 root one-shot 服务执行。在线通道只快进代码并重启既有服务;不运行 Composer/pip、不准备依赖暂存区、不改写 systemd unit。目标版本修改 `engine/requirements.txt`、`web/composer.json`、`web/composer.lock` 或 `deploy/**` 时必须改用 SSH 升级;代码或数据库状态无法确认的失败会保留维护锁,其中数据库迁移中断不能仅靠回退源码解除,必须通过 SSH 人工完成并验证恢复。
## 目录与部署
```text
virt-cloud/
web/ PHP 网站、页面、SQL、测试
engine/ 私有 FastAPI/libvirt 引擎及测试
deploy/ 引擎、业务 worker、策略 worker 与按需更新 worker 的 systemd 配置
runtime/ 私有配置、密钥、引擎数据(安装生成,不入 Git)
docs/ 架构、部署、原清理记录
```
上述命令保持在前台运行。出现 `Uvicorn running on http://127.0.0.1:8000` 表示已监听;可另开终端运行 `curl http://127.0.0.1:8000/api/v1/health` 检查。首次启动时,在启动终端输出中查找 `VIRSH_PANEL_SETUP_TOKEN=`,用它在网页先配置数据库,再创建初始账户;账户创建后令牌失效。停止面板用 `Ctrl+C`,再次启动只需执行最后一行启动命令。**不需要编辑面板配置文件,也不需要运行初始化命令。**
手工更新版本时请同时替换 `static/index.html`、`static/app.js`、`static/styles.css` 和后端代码,不要只上传页面 HTML;保留原有 `data/` 和数据库。浏览器若出现“已选公网云镜像却仍要求 ISO”,先确认这三个静态文件均为同一版本,再重新打开页面。网页一键更新另有 Git 仓库和更新服务的要求,见下文。
网站文档根目录必须是 `web/public`。引擎仅监听 `127.0.0.1:8000`;不能把整个网站反代到引擎,只有 `/engine-console` 的 WebSocket 转发给引擎。
从仍允许用户名登录的版本升级时,**先检查初始账户的邮箱再替换代码并重启**。旧版可能创建了 `email=NULL` 的初始账户;新版首次创建的账户也可以不填邮箱。这种账户创建后会建立当前浏览器会话,但一旦退出、会话过期或清除 Cookie,在数据库补齐邮箱前就无法再次登录。请先备份数据库,在 MariaDB 中查询并确认准确的账户 ID 与用户名,再将示例邮箱换成你自己的、尚未被其他用户占用的真实邮箱:
云镜像的远程下载入口只接受官方镜像站的 HTTPS 文件地址,不接受下载介绍页;引擎只跟随由官方入口返回且通过公网地址安全校验的跳转链。AlmaLinux、Debian 和 CentOS Stream 使用 `.qcow2`;Ubuntu 官方云镜像文件名为 `.img`,但下载内容必须是 qcow2。支持的文件地址形式例如:
```sql
SELECT id, username, email FROM users;
UPDATE users SET email = LOWER('你的邮箱@example.com'), email_verified = 1
WHERE id = 1 AND username = '你的初始用户名' AND email IS NULL;
SELECT id, username, email FROM users WHERE id = 1;
```text
https://repo.almalinux.org/almalinux/8/cloud/x86_64/images/AlmaLinux-8-GenericCloud-latest.x86_64.qcow2
https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2
https://cloud.centos.org/centos/9-stream/x86_64/images/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2
https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-amd64.img
```
请确认 `UPDATE` 实际影响一行,且查询结果是预期邮箱;否则不要继续升级、退出当前会话或重启,应核对 ID、用户名及已有邮箱。初始账户的邮箱由持有初始化令牌的你设置,不通过公开注册验证码流程。已设置邮箱的现有账户无需再改,升级后直接用其邮箱登录;邮箱不区分大小写。
若初始化令牌意外公开、且尚未创建初始账户,请先停止面板,只删除 `/home/virsh-panel/data/setup-token`,再启动面板生成新令牌。不要删除整个 `data/`;新令牌不要再次公开。
按当前需求从 A 的 root 终端运行面板;程序自动将 `data/` 目录及本地加密主密钥限制为 `0700`、`0600`。数据库中的敏感资料采用应用层认证加密,但运行中的 root 面板仍能解密 B 的 root SSH 私钥;只在可信网络和 HTTPS 反代后使用,妥善限制谁能访问 A。A 若启用 SELinux enforcing,还需在真实系统上验证 `/home/virsh-panel` 的访问标签。仓库保留可选 service 文件,但以上启动方式不依赖它。
## 你自行配置的反向代理
反代与面板在 A 上时,上游指向 `http://127.0.0.1:8000`。对外必须使用你信任的 HTTPS 证书;保留原始 `Host`,由反代覆盖 `X-Forwarded-Proto: https` 和真实客户端的 `X-Forwarded-For`,并透传 `/api/v1/vms/{uuid}/console` 的 WebSocket。面板需要位于站点根路径 `/`。面板只信任来自 `127.0.0.1` 的代理头;直连明文 8000 仅允许 `/api/v1/health` 健康检查,不能登录或上传私钥。不要向公网暴露 8000。[Uvicorn 官方代理说明](https://www.uvicorn.org/deployment/)。
## 首次网页操作
1. 通过你的 HTTPS 域名打开面板,使用启动终端输出中的一次性令牌填写 MariaDB 的地址、端口、已有数据库名、专用账号和密码。数据库账号至少需要在该数据库中建表及读写权限;连接失败时不会保存配置。当前数据库连接尚未提供 TLS 参数,数据库请放在面板本机或可信内网,不要将其端口暴露公网。
2. 使用同一个令牌填写用户名和密码,创建初始账户;此处不要求填写邮箱。密码只保存为密码哈希。此时 `users.admin=0`,账户已建立当前浏览器会话,但还不能管理宿主机。按照你的要求,面板**不会自动赋予管理员权限**。用有权访问该数据库的账号在 MariaDB 中核对用户名及 ID 后,手工执行下面 SQL;将示例 ID、用户名和邮箱换成实际值。**必须在退出当前会话前补齐邮箱**,否则无法再次登录:
```sql
SELECT id, username, email, admin, approved FROM users;
UPDATE users SET email = LOWER('你的邮箱@example.com'), email_verified = 1
WHERE id = 1 AND username = '你的初始用户名' AND email IS NULL;
UPDATE users SET admin = 1 WHERE id = 1 AND username = '你的初始用户名';
SELECT id, username, email, admin, approved FROM users WHERE id = 1;
```
核对查询结果中的邮箱和管理员标志后,再刷新面板;权限会从数据库即时读取,不必重启。此后用邮箱登录,不能用用户名登录。不要把 `admin=1` 给公开注册用户。
3. 管理员在网页配置 SMTP 地址、端口、SSL/STARTTLS、发件邮箱及需要时的 SMTP 账号密码;设置加密保存在 MariaDB,页面不回显密码。完成后,访客可用邮箱验证码注册(10 分钟有效,重复发送与输错次数受限);邮箱验证成功即可登录,但须由管理员在“用户审核”批准后才能创建虚拟机。普通用户不能添加宿主机、导入云镜像模板、配置 SMTP 或更新面板,也看不到其他人的虚拟机和初始密码。面板外创建或管理员创建的未归属虚拟机仅管理员可见;当前没有从网页将旧 VM 分配给用户的功能。
4. 在网页填写 B 的 IP/DNS、SSH 端口、虚拟机地区、现有的 **root 客户端 SSH 私钥**、磁盘目录、安装 ISO 目录、独立救援 ISO 目录和网络名称。救援目录可暂留空,但配置前不能上传救援模版;它不能与安装 ISO 目录相同。还可配置由服务商分配且已路由到该宿主机的**公网 IPv4 `/24` 地址池**、同网段网关、DNS,以及不能分配给虚拟机的保留地址。地区是这台宿主机上虚拟机共用的展示标签,可留空;它不影响 SSH 连接或已导入的模板。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。保存宿主机设置时,面板会将口令与私钥加密写入 MariaDB,以便面板重启后自动连接和无人登录时继续采样;设置 API 不回显口令,面板代码也不将其写入浏览器存储。**旧版本中只在内存解锁过的口令无法自动恢复**:升级后进入“宿主机设置”,不必重新粘贴原私钥,填写原口令并重新保存一次。只在“解锁宿主机 SSH 私钥”页面输入不会持久保存。
5. 点击“扫描主机指纹”,再通过 B 的可信控制台运行 `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` 独立核对;确认后在网页测试、保存。保存前会重扫并测试 SSH 与 libvirt API,失败不会覆盖现有连接。
宿主机私钥、已填写的私钥口令和配置加密保存在 MariaDB。数据库备份与 `data/master.key` 同时泄露时,这些凭据可以被解密,因此须分别严密保护;运行中的 root 面板进程同样能使用它们。OpenSSH 连接时需要读取私钥文件,Linux 上面板会将其临时还原到权限为 `0700` 的 `/dev/shm` 内存文件系统目录;面板关闭时清除。`data/runtime-wrappers/` 只包含不带密钥的启动包装器。若 SSH agent 异常退出,后台采样会限频尝试使用已保存口令恢复连接;若保存的口令错误,仍需管理员检查并重新保存。面板仅支持单个 Uvicorn worker。
虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。“创建虚拟机”从列表进入独立页面,“重装系统”从虚拟机详情进入独立页面,表单和任务进度不再使用弹窗。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。详情页的公网 IP 不显示 `/24` 等掩码后缀,可点击旁边的按钮复制;磁盘信息只显示总容量,不再显示磁盘块数。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。
云镜像 VM 的详情页显示 SSH 登录名 `root`。面板保存了初始 root 密码时,默认以星号遮盖;管理员或该 VM 的所属用户可按需点击图标查看、复制,不会在虚拟机列表或普通详情数据中直接返回密码。新建云镜像 VM 无论是否选择 SSH 公钥,都会设置并加密保存可查看的初始密码;重装时若只选公钥而不填写密码,则保持仅公钥登录,不保存新密码。ISO 安装和面板外创建的 VM 的客体密码不由面板管理。旧 VM 曾使用但面板未保存的密码无法从密码哈希或虚拟机系统中还原。客体内修改 root 密码后,详情页保存的**初始**密码不会自动更新,可能已无法用于登录;请妥善保护数据库备份和面板主密钥。
自制或修复后的镜像使用管理员页面“从本机上传 QCOW2”。上传时必须选择与镜像内容一致的系统及版本;引擎会计算 SHA-256,并拒绝 raw/ISO、加密镜像、外部 data file、backing file、无法通过 QCOW2 结构检查的文件及超过 4 GiB 的文件。浏览器上传还需要按部署说明配置 PHP、Web 服务器和反代的请求体上限与超时。
虚拟机详情页显示 CPU、客体内存、磁盘 I/O 和网络收发四张历史走势图,可切换最近 1 小时、24 小时、7 天和 30 天。面板后台定时从 [libvirt 域统计](https://libvirt.org/manpages/virsh.html#domstats)采样并写入 MariaDB,即使无人登录也会继续记录,前提是宿主机连接可用且加密私钥能自动解锁。旧配置若只在内存中解锁、没有重新保存口令,重启后后台采样会暂停,直到管理员解锁;按上述步骤保存口令后可避免这种中断。查询**只返回最近 30 天**的数据;运行中的面板会分批清理更早的数据库记录。面板停机或数据库不可用时物理清理会暂停,恢复后继续追赶,因此中断期间数据库中可能暂时留有超期记录。CPU 是按 vCPU 数归一化、最高显示 100% 的使用率,磁盘和网络显示每秒速率而不是累计量或网络带宽上限;网络收发方向以虚拟机为准。磁盘与网卡只汇总 libvirt 实际提供计数的设备,未提供计数的设备无法纳入统计。内存占用依赖客体内存气球统计,客户机不提供或统计过期时会显示无数据,不会把宿主机 QEMU 进程占用误当客体内存。初次采样、虚拟机停机、面板/宿主机不可达或计数器重置期间可能出现空白;面板停机期间不会补录历史。较长时间范围会聚合采样,短暂的停机或采样缺口可能不明显。
全新安装见 [部署说明](docs/DEPLOYMENT.md),职责边界见 [集成架构](docs/INTEGRATION_PLAN.md)。配置使用 `web/config/config.php`,兼容旧文件名 `.config.php`;两者存在时前者优先。本版不导入原 Python 面板数据。
磁盘目录、安装 ISO 目录和救援 ISO 目录填写的是 **B 宿主机**上已存在的绝对路径,例如 `/home/kvm`、`/home/iso` 和 `/home/rescue-iso`,不是 A 面板服务器的路径;不需要提前手动创建 libvirt 存储池。救援目录须实际独立,不要通过软链接或绑定挂载指向安装 ISO 目录。点击“保存”时,面板会将这些现有目录定义为 libvirt `dir` 存储池并启动,作为内部管理机制;不会创建目录,也不会移动或删除现有文件。新建虚拟机的磁盘文件使用配置的磁盘目录下的 `<虚拟机名>.qcow2`,安装镜像使用配置的安装 ISO 目录下所选的 `.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 队列。
面板设置 API 不回显 root 私钥或口令。B 无需对公网开放 VNC 或明文 libvirt TCP 端口;面板创建的虚拟机 VNC 仅监听 B 的 `127.0.0.1`。创建新虚拟机需 B 已有可用的目录或存储池、虚拟网络或 Linux 网桥、以及包含 ISO 的目录或池;资源暂时缺失不妨碍保存宿主机连接,但创建虚拟机会提示问题。
若某台现有 VM 是用 `--graphics vnc,listen=0.0.0.0` 创建的,它会出现在列表,但面板出于安全考虑不会连接其公开监听的 VNC。需在 B 上把该 VM 的 VNC 监听改为 `127.0.0.1` 后再使用面板控制台。面板新建 VM 的 XML 使用 `host-passthrough` CPU、Q35 机型与 UEFI(启用 ACPI/APIC)、磁盘 `cache=none` 和 `discard=unmap`、按 vCPU 数设置 virtio 网卡队列,并加入 QEMU Guest Agent 通道和 virtio 内存气球空闲页回报。首次安装时临时挂载 ISO 并从光驱启动;保存的配置已弹出 ISO,后续仅从硬盘启动。B 需要有可用的 UEFI/OVMF 固件,客户机内还需安装并运行 `qemu-guest-agent` 才能使用 Guest Agent 功能。VNC 仍仅监听 B 的 `127.0.0.1`,现有 VM 配置不会被面板自动改写。
安装程序首次请求重启时,安装阶段的 VM 会先停机;请在面板点击“开机”,它会使用已弹出 ISO 的持久配置从硬盘继续启动。首次重启若发生在多阶段安装的中途,也按此方式继续。这个行为只适用于更新后**新创建**的 VM;此前已创建的 VM 不会自动改写,可在宿主机手动弹出 ISO 并把硬盘设为首选启动设备。此后新建的 ISO 和云镜像 VM 都会自动开启 libvirt 的**随宿主机开机自启**;现有 VM 的设置不会批量改动。开机自启只在宿主机启动时生效,不会让安装程序首次重启后的停机自动恢复。如果 ISO 安装尚未完成时宿主机重启,VM 可能从尚未安装完成的硬盘启动,建议初次安装期间避免重启宿主机。若网页 VNC 显示“连接已中断”,这与虚拟机的 UEFI/磁盘 XML 是不同链路:先在浏览器开发者工具的 Network → WS 检查控制台请求是否得到 `101`。若 Uvicorn 日志显示对 `/console` 的普通 `GET` 返回 `404`,先检查面板虚拟环境是否安装了 WebSocket 协议依赖(旧版依赖清单可能遗漏),重新运行 `.venv/bin/python -m pip install -r requirements.txt`;若已安装,则检查反代是否用 HTTP/1.1 透传 `Upgrade` 和 `Connection` 头。确认 WebSocket 已连接后,再从 A 测试已保存 SSH 配置能否用 `ssh -W 127.0.0.1:<实际 VNC 端口>` 连到 B;不要为排障把 VNC 改成公网监听。
## 公网云镜像模板创建(无需手动安装)
面板随项目预存 AlmaLinux、Debian、CentOS 和 Ubuntu 的官方图标,页面运行时不会从外网加载图标;来源与使用说明见 [ICON-SOURCES.md](ICON-SOURCES.md)。图标仅用于识别真实的系统模板,不表示发行版项目认可本面板。当前后端仍只允许导入 AlmaLinux 9/10 镜像,预存其他图标并未开放相应系统的导入或销售。
面板的“创建虚拟机”有独立的“公网云镜像”方式。先在宿主机设置中选择已工作的 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 内配置 `/24`,而实际只获配上述 `/28`,这里填 `24`,新建 VM 将获得例如 `123.123.123.114/24`,但面板仍只会从 `123.123.123.112/28` 挑选地址。可填写的客体前缀范围为 `/24` 到地址池前缀,以确保整个地址池中的 IP 与网关处于同一客体子网。修改此项不会自动改写已创建 VM;云镜像重装会保留该 VM 首次创建时的网络前缀。若使用 `/28` 不通,其具体原因仍需结合宿主机路由、网桥及服务商网络确认;仅改变面板掩码无法替代上游放行或路由配置。
配置地址池后,创建时会自动选择一个尚未使用的地址,并沿用宿主机设置的网关和 DNS;用户不能在创建请求中另填 IP、网关或 DNS 来绕过地址池。面板会跳过网络地址、广播地址、网关、保留地址、宿主机自身的字面 IPv4,以及 libvirt 可见虚拟机元数据中的已用 IP,并防止面板并发创建分到相同地址。地址池用尽时创建会报错,不会复用仍占用的地址;面板删除 VM 后会释放其地址占用记录。旧宿主机若未配置地址池,仍可按原方式手填已分配给你的**具体公网 IPv4/CIDR**(如 `/24` 或 `/28`)、同网段网关和 1–4 个 DNS 地址。在创建页面中可选一个已保存的 SSH 公钥,同时设置初始 root 密码,登录时可用对应私钥或密码;不选择公钥也可以只用密码。手动密码须为 12–128 个字符,包含大写字母、小写字母和符号;密码留空时面板自动生成并加密保存初始密码,**即使已经选择公钥**。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板无法探测面板及 libvirt 元数据之外的设备是否占用地址,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。
若 DNS 本身位于该地址池中,它的地址也会自动跳过。面板创建成功后会保留 IP 占用记录,只有通过面板删除 VM 才自动释放;如果直接在宿主机或其他工具中删除 VM,旧占用记录会保守保留,避免误将该 IP 分给新 VM,需核查真实占用情况后再处理。
每个已登录用户都可导入并命名自己的**单行 OpenSSH 公钥**:已审核账号从侧栏“公钥管理”进入,等待审核的账号可用“管理我的公钥”入口。可以粘贴 `.pub` 文件内容,或在浏览器选择本地 `.pub` 文件填入表单;面板只接受公钥,不要选择或粘贴私钥。公钥管理列表只显示当前账户导入的公钥;管理员账户也不能把另一个用户的公钥当作自己的预设公钥使用。创建与重装公网云镜像 VM 时,SSH 公钥以卡片形式选择,卡片只显示公钥名称,不显示公钥内容或指纹;再次点击已选卡片可取消选择,不再有手动粘贴公钥输入框。初始 root 密码输入框始终显示,可与公钥同时使用;创建时密码留空总会自动生成,重装时只有公钥和密码都留空才自动生成。未通过管理员审核的用户可以管理自己的公钥,但仍不能创建虚拟机。删除公钥只删除面板中的预设记录,**不会撤销已经写入现有虚拟机的 SSH 授权密钥**;要撤销现有 VM 的访问权限,需在客体系统中删除对应的 `authorized_keys` 条目或重装并更换登录密钥。
创建时,面板在 B 的磁盘池克隆独立 qcow2 磁盘并扩容,生成一个只读、不可启动的 `CIDATA` cloud-init 配置 ISO,经 libvirt 上传后挂载。客体首次直接从硬盘开机,cloud-init 按固定 MAC 配置静态公网 IP、默认网关和 DNS;**不会进入 VNC 安装程序**。[AlmaLinux 本地云镜像用法](https://wiki.almalinux.org/cloud/Generic-cloud-on-local)、[NoCloud 配置说明](https://docs.cloud-init.io/en/latest/reference/datasources/nocloud.html)。选中公钥时,面板将其写入 root 的授权密钥;无论是否选公钥,创建时都会将初始 root 密码的加盐 SHA-512-crypt 哈希写入配置 ISO,并开启 root 的 SSH 密码登录,因此公钥和密码可以共存。自动生成或手填的初始密码还会在 MariaDB 中加密保存,供详情页按需查看或复制。启用密码登录会暴露公网 root 密码认证,建议在宿主机或上游防火墙限制 SSH 来源;宿主机上的配置 ISO 含密码哈希,必须防止未授权读取。网络或凭据填错后需离线修复或重建。删除 VM 时若勾选“同时删除虚拟磁盘”,面板也会删除其配置 ISO,但**保留共享模板镜像**。这项登录方式变更只对新创建的 VM 生效,不会修改已有 VM。
面板创建的公网云镜像 VM 在详情页有“重装”按钮。点击后选择当前宿主机已导入的云镜像模板,输入 VM 名称确认;可在卡片中选择自己保存的 SSH 公钥,并同时设置初始 root 密码。手动密码须为 12–128 个字符并包含大写字母、小写字母及符号;只选公钥而不填写密码时保持仅公钥登录,两者都留空时自动生成强密码。设置或生成的初始密码会在成功重装后加密保存至 MariaDB,并可在虚拟机详情页按需查看或复制。自动生成的密码仍会在任务成功后显示,管理员点击“已保存密码,完成”只会从**任务记录**中清除密码,不影响详情页保存的初始密码。同一浏览器标签页刷新或面板进程重启后仍可按任务编号查询,直到确认保存密码为止。重装自动读取原配置盘中的公网 IP/CIDR、网关、DNS 和 MAC,不要求再次手填网络。运行中的 VM 会先收到正常关机请求;120 秒内未关机则中止,不会强制断电,也不会切换或删除旧系统盘。面板会将所选模板克隆到新系统盘,生成新的 cloud-init 配置盘并启动 VM;新系统尚未启动时切换失败会恢复原定义,旧盘保留。如果启动调用结果不确定但发现新盘已在运行,则保留新旧两份磁盘并提示人工核查。**libvirt 报告新 VM 已启动后,面板会自动删除旧系统盘与旧配置盘;这并不能证明客体系统、网络或 SSH 已工作,旧数据一旦删除不可恢复。** 若旧盘清理失败,任务仍返回成功但附带警告,需在宿主机核查残留卷。此功能仅支持面板创建且配置未被外部修改的公网云镜像 VM,不支持 ISO 安装 VM、快照或多网卡/多磁盘 VM。
## 紧急救援 ISO
管理员先在“宿主机设置”填写已存在且不同于安装 ISO 目录的救援 ISO 目录,再从侧栏“救援模版”选择本地可启动的 ISO 并命名上传;面板将文件暂存于私有 `data/` 目录、验证 ISO 9660/El Torito 启动记录,再经现有 libvirt SSH 连接导入当前宿主机的**救援 ISO 池**。普通 ISO 安装列表只读取安装 ISO 池,不会显示救援池中的镜像;后端也拒绝把面板命名的救援卷当作安装 ISO。此验证不保证 ISO 包含适用于目标 VM 的 UEFI/BIOS 启动项,也不保证救援系统能正常运行;切换后须用 VNC 核实。当前只支持 1 MiB–8 GiB 的 ISO,不支持 qcow2/raw 救援系统盘。ISO 文件保存在宿主机,模版元数据和恢复所需的虚拟机原始 XML 加密保存在 MariaDB;面板完成上传后会清理临时文件。若上传在面板进程被强制终止时中断,检查 `data/.rescue-upload-*` 临时文件和宿主机救援目录中的 `panel-rescue-*.iso` 卷,再决定是否清理。反向代理也必须允许相应请求体大小与上传时间,面板服务器暂存盘须有足够空间。升级前上传到旧安装 ISO 目录的救援镜像不会自动迁移到新目录;配置救援目录后请重新上传需要的模版,核对无人使用后再清理旧文件。
已审核的虚拟机所有者或管理员可在虚拟机详情页点“紧急救援”,选择已上传的 ISO 并输入虚拟机名称确认。面板**先预挂载救援 ISO,保存为下次完整开机的启动配置**,再请求运行中的 VM 正常关机(最多等待 120 秒)并从救援 ISO 冷启动;停机 VM 会直接从该 ISO 开机。若正常关机请求失败或超时,预挂载仍保留,救援页会明确显示“已预挂载”,并提供需再次确认的“强制重启进入救援”按钮:它会强制断电再冷启动,可能丢失未保存的数据。面板**不会自动强制断电**。也可在详情页手动“强制断电”后“开机”;普通“强制重置”只重置原 QEMU 进程,不能可靠读取新保存的启动配置。救援 ISO 仅在卸载或取消救援后才会从启动配置移除。取消尚未启动的救援时,若原系统仍在运行则不会打断它;退出已启动的救援时,面板会正常关机、恢复原始启动配置并从系统盘开机。面板添加独立救援光驱,保留原系统盘、cloud-init 配置盘及原始启动 XML。救援期间不允许重装、删除或执行一般电源操作;VNC 控制台仍可使用。救援 ISO 内的用户名、密码与网络行为由 ISO 自身决定,面板不会把原 VM 的 root 密码或 SSH 公钥注入救援系统。任务成功仅表示 libvirt 报告虚拟机已启动,不保证救援系统或原系统已正常登录;应通过 VNC 核对。建议在救援前备份重要数据;面板不会修改原系统盘,但救援系统中的人工操作仍可修改或删除它。
## 网页一键更新
网页的“网站更新”页固定从 `https://g.luoli.live/root/virt.git` 的 `main` 分支读取更新。访问令牌请使用有此私有仓库**读取权限**的 Gitea `root` 账号令牌;网页保存后不会回显,令牌加密保存在 MariaDB,也不会写入 Git URL。面板会拒绝压缩包部署、分支不符、origin 不符、未提交/未跟踪改动以及不能快进的版本;Git 的 [`--ff-only`](https://git-scm.com/docs/git-merge#Documentation/git-merge.txt---ff-only) 会在提交历史分叉时拒绝覆盖本地代码。
一键更新必须将项目部署为 `/home/virsh-panel` 的完整 Git 检出目录(含 `.git`),并用 systemd 运行主面板。目录及 `.git` 必须归运行账号 root 所有,且不可允许组或其他用户写入;当前仅支持 `main` 分支、origin 精确为 `https://g.luoli.live/root/virt.git` 的干净检出。`git`、`pip` 和 `systemctl` 须可用。第一次启用时,手工将仓库中的两个 unit 文件安装到 systemd,再重载并启动主服务;更新服务本身无需 `enable`,由网页按需触发:
```bash
install -m 0644 /home/virsh-panel/deploy/virsh-panel.service /etc/systemd/system/virsh-panel.service
install -m 0644 /home/virsh-panel/deploy/virsh-panel-update.service /etc/systemd/system/virsh-panel-update.service
systemctl daemon-reload
systemctl enable --now virsh-panel.service
```
已进行隔离 PHP 8.5 语法、模板、协议、SQLite 订单状态机和 Python 引擎测试。没有使用真实 MariaDB、SSH/KVM、付款或邮件通道完成生产联调。首次部署请先在测试宿主机验收,再开放销售。
独立的 `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 仓库写入权限和访问令牌。
超时后状态不明的任务保持 `uncertain`,不会直接退款或再次毁盘/创建。管理员需核对宿主机与任务状态,不能靠重复购买处理。这不是自动故障迁移、资源超售防护或高可用平台。
功能范围:邮箱验证注册、管理员审核及按虚拟机归属隔离用户,虚拟机列表和详情页四项性能走势图、从 ISO 创建、由管理员导入并重命名 AlmaLinux 9/10 云镜像模板、使用已导入模板配置公网静态 IP 创建、云镜像重装、管理员上传救援 ISO 和虚拟机紧急救援、开机、关机、重启、强制断电/重置、删除和浏览器 VNC。当前仍是单宿主机版本;不提供普通安装 ISO 上传、目录自动创建、虚拟网络创建、内网 IP 模板或异网段网关。真实 AlmaLinux 10 宿主机、SMTP 服务及 MariaDB 仍需现场联调。
原清理边界见 [清理报告](docs/PRUNING_REPORT.md)。原 `/html` 与 `/virsh-panel` 项目未在本轮修改。

@ -1,8 +0,0 @@
# Third-party code
`static/vendor/novnc/` contains the `core/` and `vendor/` directories from
[noVNC v1.7.0](https://github.com/novnc/noVNC/releases/tag/v1.7.0), plus its
`LICENSE.txt`. The upstream source archive was downloaded from the noVNC GitHub
release tag without modifications. The bundled `vendor/pako/` dependency retains
its own license file.

@ -0,0 +1,106 @@
{
"schema_version": 1,
"policy_version": 1,
"scope": "public_ipv4_interface",
"applies_to": "new_public_cloud_image_instances_only",
"migrate_existing": false,
"rules": [
{
"id": "qotd",
"label": "QOTD",
"category": "permanent",
"protocols": ["tcp", "udp"],
"port_from": 17,
"port_to": 17,
"directions": ["ingress", "egress"],
"reason": "降低反射放大与滥用风险。"
},
{
"id": "chargen",
"label": "Chargen",
"category": "permanent",
"protocols": ["tcp", "udp"],
"port_from": 19,
"port_to": 19,
"directions": ["ingress", "egress"],
"reason": "降低反射放大与滥用风险。"
},
{
"id": "ssdp",
"label": "SSDP",
"category": "permanent",
"protocols": ["tcp", "udp"],
"port_from": 1900,
"port_to": 1900,
"directions": ["ingress", "egress"],
"reason": "降低公网发现服务与反射放大滥用风险。"
},
{
"id": "memcached",
"label": "Memcached UDP",
"category": "permanent",
"protocols": ["udp"],
"port_from": 11211,
"port_to": 11211,
"directions": ["ingress", "egress"],
"reason": "降低 Memcached UDP 反射放大风险。"
},
{
"id": "brand-rex-53413",
"label": "Netis / Netcore 后门端口",
"category": "permanent",
"protocols": ["udp"],
"port_from": 53413,
"port_to": 53413,
"directions": ["ingress", "egress"],
"reason": "阻断已知路由器后门相关公网流量。"
},
{
"id": "smtp-25",
"label": "SMTP 直投",
"category": "default",
"protocols": ["tcp"],
"port_from": 25,
"port_to": 25,
"directions": ["egress"],
"reason": "降低垃圾邮件滥用风险;例外申请流程尚未实现。"
},
{
"id": "netbios",
"label": "NetBIOS",
"category": "default",
"protocols": ["tcp", "udp"],
"port_from": 137,
"port_to": 139,
"directions": ["ingress", "egress"],
"reason": "默认阻断 NetBIOS 服务暴露与公网访问。"
},
{
"id": "smb",
"label": "SMB",
"category": "default",
"protocols": ["tcp", "udp"],
"port_from": 445,
"port_to": 445,
"directions": ["ingress", "egress"],
"reason": "默认阻断 SMB 文件共享服务的公网暴露与访问。"
},
{
"id": "kms-1688",
"label": "KMS 服务端",
"category": "default",
"protocols": ["tcp"],
"port_from": 1688,
"port_to": 1688,
"directions": ["ingress"],
"reason": "默认阻断 KMS 服务端口直接暴露到公网。"
}
],
"explicitly_unrestricted": [
{
"protocol": "tcp",
"port": 587,
"reason": "SMTP 提交端口当前不受平台默认策略限制。"
}
]
}

@ -1,22 +0,0 @@
[Unit]
Description=Virsh Panel one-shot update from the pinned private Gitea repository
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=root
Group=root
WorkingDirectory=/home/virsh-panel
Environment=PANEL_DATA_DIR=/home/virsh-panel/data
Environment=PYTHONDONTWRITEBYTECODE=1
ExecStart=/home/virsh-panel/.venv/bin/python -m virsh_panel.update_worker
ExecStopPost=/home/virsh-panel/.venv/bin/python -m virsh_panel.update_worker --finalize-incomplete
TimeoutStartSec=30min
UMask=0077
LimitCORE=0
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=/home/virsh-panel

@ -1,26 +0,0 @@
[Unit]
Description=Virsh Panel (local HTTP upstream and remote libvirt)
After=network-online.target
Wants=network-online.target
[Service]
Type=exec
User=root
Group=root
WorkingDirectory=/home/virsh-panel
Environment=PANEL_DATA_DIR=/home/virsh-panel/data
Environment=PYTHONDONTWRITEBYTECODE=1
ExecStartPre=+/usr/bin/install -d -o root -g root -m 0700 /home/virsh-panel/data
ExecStart=/home/virsh-panel/.venv/bin/python -m uvicorn virsh_panel.app:create_app --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
CapabilityBoundingSet=CAP_SETPCAP
PrivateTmp=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=-/home/virsh-panel/data
[Install]
WantedBy=multi-user.target

@ -0,0 +1,25 @@
[Unit]
Description=Virt Cloud private libvirt engine
After=network-online.target
Wants=network-online.target
[Service]
Type=exec
User=root
Group=root
WorkingDirectory=/home/virt-cloud/engine
Environment=CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json
Environment=PYTHONDONTWRITEBYTECODE=1
ExecStart=/home/virt-cloud/engine/.venv/bin/python -m uvicorn virsh_panel.internal:create_engine --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1 --no-access-log
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=/home/virt-cloud/runtime
LimitCORE=0
[Install]
WantedBy=multi-user.target

@ -0,0 +1,24 @@
[Unit]
Description=Virt Cloud service-period and traffic lifecycle worker
After=network-online.target virt-cloud-engine.service
Wants=network-online.target
[Service]
Type=simple
User=apache
Group=apache
WorkingDirectory=/home/virt-cloud/web
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudLifecycle
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=false
ProtectSystem=strict
ReadWritePaths=-/home/virt-cloud/runtime/php
ReadWritePaths=-/home/virt-cloud/web/storage
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

@ -0,0 +1,24 @@
[Unit]
Description=Virt Cloud enforcement policy worker %i
After=network-online.target virt-cloud-engine.service
Wants=network-online.target
[Service]
Type=simple
User=apache
Group=apache
WorkingDirectory=/home/virt-cloud/web
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudWorker --policy-only
Restart=on-failure
RestartSec=3
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=false
ProtectSystem=strict
ReadWritePaths=-/home/virt-cloud/runtime/php
ReadWritePaths=-/home/virt-cloud/web/storage
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

@ -0,0 +1,23 @@
[Unit]
Description=Virt Cloud privileged online update worker
After=network-online.target mariadb.service
Wants=network-online.target
[Service]
Type=oneshot
User=root
Group=root
WorkingDirectory=/home/virt-cloud/engine
Environment=CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json
Environment=PYTHONDONTWRITEBYTECODE=1
ExecStart=/home/virt-cloud/engine/.venv/bin/python -m virsh_panel.update_worker
ExecStopPost=/home/virt-cloud/engine/.venv/bin/python -m virsh_panel.update_worker --finalize-incomplete
TimeoutStartSec=45min
TimeoutStopSec=10min
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=/home/virt-cloud
LimitCORE=0

@ -0,0 +1,25 @@
[Unit]
Description=Virt Cloud purchased VM provisioning worker
After=network-online.target virt-cloud-engine.service
Wants=network-online.target
[Service]
Type=simple
# AlmaLinux PHP-FPM normally runs as apache; use the same user as your PHP pool.
User=apache
Group=apache
WorkingDirectory=/home/virt-cloud/web
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudWorker
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=false
ProtectSystem=strict
ReadWritePaths=-/home/virt-cloud/runtime/php
ReadWritePaths=-/home/virt-cloud/web/storage
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

@ -0,0 +1,53 @@
# 系统运行与异常任务
管理员入口:`/admin/operations`。沿用 Venix 管理主题,任务列表由业务数据库直接渲染;运行检查随后异步加载,不等待引擎才显示任务。
宿主机容量和公网 IP 以资源池、调度策略及面板 reservation/IP 账本为准。本页不触发宿主机盘点,也不依赖盘点诊断表;实例创建和换 IP 请求会把具体 reservation、地址池、IP 与 `operation_id` 交给私有引擎做最终校验。响应不确定时按操作标识核对,不能重复执行原请求。
## 查看范围
- 覆盖创建、电源操作、重装、救援、删除及到期、流量策略任务。
- 默认“需要关注”:失败、待核对、已可调度超过 5 分钟且无有效租约的排队任务、执行租约已过期的运行中任务。未来的重试等待和无租约的正常核对轮次不会仅因等待而标为租约过期。
- 可按任务状态、类型、宿主机、任务编号、操作标识、实例名称或 UUID 筛选;每页 20/50/100 条。摘要统计跟随当前筛选。
- 详情区分操作人和实例所属用户,展示调度时间、尝试次数、脱敏错误和关联入口。实例已经删除或关联丢失时仍保留任务记录,不猜测所属用户。
列表、详情和健康检查保持数据库快照读取;超级管理员可以对快照创建/恢复/删除、实例删除及到期清理任务使用“中止任务”按钮。中止只在数据库事务中将未结束任务标记为 `cancelled`、清除执行租约并阻止后续 worker 领取,不删除任务、不退款,也不向引擎发送补偿请求。已经派发到引擎的操作不会被假定已回滚,快照/删除关联状态会保守保留为待核对,`expiry_delete` 会进入 `purge_failed` 等待人工核查。租约过期不等于操作失败,不应据此手动重放破坏性操作。
```text
GET /api/v1/admin/operations
GET /api/v1/admin/operations/jobs/{id}
GET /api/v1/admin/operations/health
POST /api/v1/admin/operations/jobs/{id}/cancel
```
需要管理员会话,响应禁止缓存,POST 还需要管理端 CSRF 令牌。读取任务不创建引擎会话、不读取任务加密载荷或租约令牌、不返回原始结果 JSON。健康检查独立发送签名的引擎健康请求。重复中止同一任务是幂等的;已完成任务、非允许类型或不存在任务返回受控错误。
## 运行状态的含义
- 业务/日志数据库:只读 `SELECT 1` 成功,不代表全部表结构或业务数据正确。MySQL 使用独立、非持久连接,连接及读取超时各为 2 秒;仅在支持 mysqlnd 的 PDO 驱动下探测,临时读取超时配置在检查后恢复,不修改应用共享连接。驱动或运行环境不支持短超时设置时显示未知,不回退到无界连接;SQLite 保持原有只读查询。日志库未启用则明确显示未启用。DNS 解析不受这些连接/读取超时完整约束,因此不能将它们理解为整个健康接口的硬总时限。
- 私有引擎:签名接口和引擎存储检查通过,不代表每台宿主机或虚拟机正常。引擎请求有 4 秒超时。
- Redis:配置后检查 PING;独立客户端使用 1 秒连接/读写超时,不影响应用共享客户端,也不验证缓存内容。
- 普通 worker、策略 worker、生命周期调度:读取本机最近运行记录;不是 `systemctl` 状态,也不是对进程仍然存活的保证。页面可见时每 30 秒检查一次,不刷新整个任务列表;检查失败时明确标记保留的是旧状态。
“近期上报进程数”不是任务数量,也不能证明期望的全部策略 worker 已启动。新安装、旧进程尚未升级、权限不符合或只运行过 `--once` 时显示未知;不要把未知当作正常。
## 升级与心跳目录
无需数据库迁移或额外采集软件。新 worker 在 `web/storage/cloud-runtime/` 原子写入私有心跳:目录 `0700`,文件 `0600`。网页 PHP 与 worker/lifecycle 应按部署文档使用同一系统用户;所有者不符或目录不可读时显示未知,不建议放宽权限解决。目录位于 Web 文档根之外并已加入 `.gitignore`。
已运行的 PHP 常驻进程不会自动载入新代码。使用在线更新流程会重启相关服务;手动更新则按现有维护流程,在任务安全的维护窗口重启普通 worker、生命周期调度和实际部署的全部策略 worker。标准服务名为:
```text
virt-cloud-worker.service
virt-cloud-lifecycle.service
virt-cloud-policy-worker@1.service
virt-cloud-policy-worker@2.service
```
不要仅为获得心跳而中断正在重装/删除的任务。通过既有服务日志确认任务情况;缺少心跳不会改变现有任务处理逻辑。
观测写入失败不会中止任务。记录只包含固定阶段、固定错误分类和时间,不记录密码、邮箱、载荷或原始异常。每个进程独立记录,读取有数量与大小上限,启动时有限清理超过 7 天的私有旧记录。
新鲜度判断:空闲/错误记录 90 秒;策略 worker 忙碌阶段 180 秒;普通 worker 与生命周期的忙碌阶段 1200 秒。长操作宽限仅用于避免把正常等待立即报为失联,不改变任务超时或租约。超时表示“需检查”,不直接判定进程死亡。内部部分任务或账单/邮件处理失败也记录需关注,成功轮次才清除未恢复错误。
这是面板所在机器的辅助诊断入口:不同机器上的 worker 不共享此目录;面板或主数据库完全不可用时仍需要外部监控和 SSH 日志,不能依赖该页面告警。

@ -0,0 +1,29 @@
# 管理面板系统日志
`/admin/system-logs` 为管理员提供 Virt Cloud 运行日志和错误日志的只读查询页面。页面通过 `/api/v1/admin/system-logs` 调用宿主机的 `journalctl`,并支持服务、级别、关键词、时间范围和结果条数筛选。首屏只渲染页面框架,日志由有超时的 API 请求异步读取,避免一次 journal 读取阻塞整个页面;列表请求可手动停止,详情请求也有独立截止时间。
日志读取范围固定为以下服务单元:
- `virt-cloud-engine.service`
- `virt-cloud-worker.service`
- `virt-cloud-lifecycle.service`
- `virt-cloud-policy-worker.service`
- `virt-cloud-policy-worker@1.service`
- `virt-cloud-policy-worker@2.service`
- `virt-cloud-update.service`
- `libvirtd.service`
- `virtqemud.service`
- `virtnwfilterd.service`
- `virtstoraged.service`
- `virtlogd.service`
- `virtlockd.service`
接口使用参数数组启动 `/usr/bin/journalctl`(系统没有该路径时使用 `/bin/journalctl`),不会经过 shell,也不接受任意 unit、命令或文件路径。单次最多读取 200 条,使用 `--cursor` 加 `--reverse` 加载更早记录;journalctl 会从游标向更早记录移动,返回结果通常不包含边界,服务端也会防御性移除意外返回的边界记录。这样可以避开部分旧 systemd 版本在 `--after-cursor` 与 unit 筛选组合下漏掉首条记录的问题。带时间下界的游标页会在 PHP 中继续应用下界,因为 systemd 不允许 `--since` 与游标同时出现。消息预览、详情字段、输出、stderr 和子进程运行时间都有上限。每条列表记录保留 journal cursor、服务和 UTC 微秒时间戳,点击后通过 `GET /api/v1/admin/system-logs/detail?cursor=...&unit=...&timestamp=...` 在该时间戳窗口内重新读取,再校验返回 cursor,避免不同 systemd 版本的 cursor seek 差异影响详情;日志轮转或游标不存在时返回 404。命令行、可执行文件和 core-dump 字段不会返回,名称明显表示密码、令牌、密钥、凭据或授权信息的结构化字段会隐藏值,消息中的常见凭据形式也会遮罩。日志内容可能包含运行时上下文,因此接口仅对管理员开放,并设置 `private, no-store`。
PHP-FPM 或 Web 服务账号需要具备读取 systemd journal 的权限。部署后如果页面提示无权读取日志,应将该账号加入目标系统的 `systemd-journal` 组并重启 PHP-FPM;不要为了此页面授予 root 权限。
接口读取的是运行 PHP 面板的本机 journal。若引擎部署在独立宿主机,页面不会假装已经读取远程宿主机日志;远程宿主机的 libvirt 错误仍需在该宿主机执行 `journalctl`,或后续增加经过引擎认证的只读日志代理。
列表每一行是可聚焦的详情触发器:鼠标点击行内任意内容、按 Enter 或空格都会打开右侧详情抽屉。详情抽屉使用共享的 `VenixDrawerMotion` 控制器;如果共享脚本未加载,页面会回退到原生 dialog 并显式添加可见状态类。详情请求和抽屉显示相互独立,网络读取失败时仍会显示可定位的错误状态。
页面的时间输入使用面板 PHP 时区,传给 journalctl 时转换为 Unix 时间戳。错误级别对应 journald 的 priority `0..3`,警告为 `4`,其余级别分别对应 `5`、`6`、`7`。

@ -0,0 +1,252 @@
# 全新安装与启动
没有安装器,不迁移旧 virsh-panel 数据。示例默认 AlmaLinux 面板服务器、项目 `/home/virt-cloud`、PHP-FPM 用户 `apache`;调整实际 PHP 路径、FPM 用户及 service 路径。宿主机是另外的 SSH/libvirt 服务器。
## 1. 自行安装依赖
- PHP 8.5 CLI/FPM:PDO MySQL、sodium、mbstring、curl、XML/DOM、OpenSSL、session 等扩展,Composer 2。
- MariaDB:业务库、日志库,初始化账号需要建表和执行幂等升级 DDL 的权限;PHP/PDO 中驱动名仍为 `mysql`。当前升级脚本使用 MariaDB 的 `ADD COLUMN IF NOT EXISTS`,不承诺兼容 Oracle MySQL。
- Redis 或兼容的 Valkey:沿用 venix 会话、验证码与限流。
- Python 3.12 或更新的项目支持版本、venv/pip、libvirt 客户端及开发头文件、C 编译工具、pkg-config、OpenSSH 客户端、`/usr/bin/qemu-img`(用于镜像完整性检查)。
- Nginx/Apache、HTTPS、PHP-FPM,网站配置由你自行管理。
`libvirt-python` 是面板依赖,不代表面板服务器需要运行 KVM 宿主服务;远端宿主另需现有 KVM/QEMU、libvirt、网桥、UEFI 固件和存储目录。
AlmaLinux 编译 Python libvirt 绑定常用系统依赖:`dnf install gcc pkgconf-pkg-config python3-devel libvirt-devel openssh-clients qemu-img`。Python 可执行文件与开发头文件应使用相同版本。
## 2. 拉取与安装程序依赖
```bash
git clone --branch venix --single-branch https://g.luoli.live/root/virt.git /home/virt-cloud
cd /home/virt-cloud/web
composer install --no-dev --prefer-dist --optimize-autoloader
cd /home/virt-cloud
python3 -m venv engine/.venv
engine/.venv/bin/python -m pip install -r engine/requirements.txt
engine/.venv/bin/python -c 'import libvirt; print(libvirt.getVersion())'
```
已拉取则从安装依赖开始,不要覆盖目录 clone。Python 依赖编译失败先核对系统 `libvirt-devel`、Python 开发头文件与 Python 版本。
## 3. 配置与全新数据库
```bash
cd /home/virt-cloud/web
cp config/.config.php.example config/config.php
```
编辑 `config/config.php`:
- `db_host/db_port/db_database/db_username/db_password`:业务库。
- `enable_log` 设置为字符串 `'true'`;`log_db_host/log_db_port/log_db_database/log_db_user/log_db_password`:日志库。空日志库地址沿用本机默认,远程数据库请填写明确地址。
- `db_prefix` 留空,网站域名、HTTPS Cookie、Redis/Valkey、账户安全、SMTP 按 venix 设置。
- `cloud_*` 默认路径适配 `/home/virt-cloud`,私有密钥自动生成;宿主机凭据稍后在页面设置。
- `cloud_max_renewal_periods_ahead` 限制单台实例可排队的未来续费账期,默认 24;不要设成无限值。
- 账户固定实例数量上限已删除。旧 `config.php` 若仍保留账户实例数量上限配置项,该项已不再读取,可在维护窗口手动删除;宿主机资源调度中的 `max_instances` 仍是有效的单宿主机容量策略。
- `cloud_introspection_url` 必须指向 PHP 网站,不是引擎 8000。默认 `http://127.0.0.1/api/internal/cloud/session-introspection`;多虚拟主机可设置 `cloud_introspection_host` 为网站域名,或改为正确的本机 HTTPS URL。
在**两个全新空数据库**分别导入,替换命令中的地址、端口、账号、库名;`-p` 提示密码,不把密码写入历史:
```bash
mariadb -h DB_HOST -P DB_PORT -u DB_USER -p BUSINESS_DB < /home/virt-cloud/web/sql/ss.sql
mariadb -h LOG_DB_HOST -P LOG_DB_PORT -u LOG_DB_USER -p LOG_DB < /home/virt-cloud/web/sql/user_log.sql
cd /home/virt-cloud/web
php xcat cloudInit
php xcat createAdmin
```
`cloudInit` 新建云业务/指标表、应用推广码兼容迁移(`web/sql/referral_affiliate_code.sql`)、生成独立签名和加密密钥及 `runtime/engine.json`,不连接宿主机。按 CLI 提示创建管理员,邮箱应真实可用;核对 `super_admin` UID 包含有宿主机管理权限的管理员。
公告纯文本升级也由 `cloudInit` 显式执行:为当前空的 `announcement` 旧表添加标题、类型、正文和发布状态,移除旧 `date` / `content` / `markdown` 字段,不包含历史富文本转换。若检测到旧表仍有记录,会在修改公告表结构前停止并提示,不自动删除旧记录。迁移可重复运行,不会覆盖新结构中的公告或重新发布已撤下的公告;HTTP 请求不执行数据库结构变更。手动升级须在维护窗口备份数据库、停止 PHP-FPM 等旧版本公告写入入口,拉取代码并执行 `php xcat cloudInit` 成功后再恢复服务,避免空表检查期间出现并发写入;在线更新器会自动停服务并执行该步骤。用户改从顶栏公告按钮查看已发布内容,原 `/user/announcement` 页面和旧管理端删除/AJAX 接口已移除;后台“撤下”不删除记录。
数据库或内省 URL 修改后重新导出并重启引擎(保留现有密钥):
```bash
cd /home/virt-cloud/web
php xcat cloudExportConfig
```
**不要删除** `runtime/php/payload.key`、`engine.hmac` 或 `runtime/engine/master.key`。备份数据库时同步安全备份密钥,否则加密记录无法使用。
## 4. 权限
`cloudInit` 成功后以 root 执行,FPM 用户不是 apache 时替换。PHP 不需要读取引擎私钥数据:
```bash
chown root:apache /home/virt-cloud/runtime
chmod 0750 /home/virt-cloud/runtime
chown -R apache:apache /home/virt-cloud/runtime/php
chmod 0700 /home/virt-cloud/runtime/php
chmod 0600 /home/virt-cloud/runtime/php/engine.hmac /home/virt-cloud/runtime/php/payload.key
chown root:root /home/virt-cloud/runtime/engine.json
chmod 0600 /home/virt-cloud/runtime/engine.json
chown root:apache /home/virt-cloud/web/config/config.php
chmod 0640 /home/virt-cloud/web/config/config.php
mkdir -p /home/virt-cloud/web/storage/framework/smarty/compile /home/virt-cloud/web/storage/framework/smarty/cache
chown -R apache:apache /home/virt-cloud/web/storage
```
代码/依赖只需可读,不要整项目 `chmod 777`。在 `/home` 发布需配置父目录遍历权限、SELinux 网站文件标签和所需网络访问策略,不要关闭 SELinux。引擎 root 运行,自行创建私有 `runtime/engine`。
## 5. 启动
前台调试引擎:
```bash
cd /home/virt-cloud/engine
PYTHONDONTWRITEBYTECODE=1 CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json .venv/bin/python -m uvicorn virsh_panel.internal:create_engine --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1
```
另一个终端以前台方式运行任务 worker(与 FPM 相同用户):
```bash
cd /home/virt-cloud/web
sudo -u apache php xcat cloudWorker
```
策略专用 worker 调试(正式部署至少运行两个实例,避免慢镜像任务阻塞到期/流量策略):
```bash
cd /home/virt-cloud/web
sudo -u apache php xcat cloudWorker --policy-only
```
账单提醒、账期、到期和流量限额前台调试:
```bash
cd /home/virt-cloud/web
sudo -u apache php xcat cloudLifecycle
```
常驻 service:
```bash
cp /home/virt-cloud/deploy/virt-cloud-engine.service /etc/systemd/system/virt-cloud-engine.service
cp /home/virt-cloud/deploy/virt-cloud-worker.service /etc/systemd/system/virt-cloud-worker.service
cp /home/virt-cloud/deploy/virt-cloud-lifecycle.service /etc/systemd/system/virt-cloud-lifecycle.service
cp /home/virt-cloud/deploy/virt-cloud-policy-worker@.service /etc/systemd/system/virt-cloud-policy-worker@.service
cp /home/virt-cloud/deploy/virt-cloud-update.service /etc/systemd/system/virt-cloud-update.service
systemctl daemon-reload
systemctl enable --now virt-cloud-engine.service virt-cloud-worker.service virt-cloud-lifecycle.service \
virt-cloud-policy-worker@1.service virt-cloud-policy-worker@2.service
systemctl status virt-cloud-engine.service virt-cloud-worker.service virt-cloud-lifecycle.service \
virt-cloud-policy-worker@1.service virt-cloud-policy-worker@2.service --no-pager
journalctl -u virt-cloud-engine -u virt-cloud-worker -u virt-cloud-lifecycle \
-u 'virt-cloud-policy-worker@*' -n 100 --no-pager
```
worker 使用 `/usr/bin/php`,须为 PHP 8.5,否则修改 unit。引擎使用一个 Uvicorn worker。普通 worker 负责购买、重装、续费账单及实例开通成功邮件投递和最终一次性删除,并可在策略 worker 缺失时兜底;两个策略 worker 专门处理到期断网、网络恢复和删除前关机等可安全收敛的目标状态,不能省略。`virt-cloud-lifecycle` 负责到期前 7 天生成续费账单以及账期、流量、到期宽限和删除策略;SMTP 发送与其隔离,不会阻塞这些策略。购买排队或通知邮件不执行时先检查 `virt-cloud-worker`;账单不生成、流量用尽不断网、账期不切换、到期不断网或宽限期结束后不删除时,同时检查 `virt-cloud-lifecycle`、`virt-cloud-worker` 与 `virt-cloud-policy-worker@1/@2`。PHP 网站由你现有的 Web/FPM 服务提供。`virt-cloud-update.service` 是按需启动的一次性服务,不要 `enable` 或手动常驻运行。
管理员可在“系统运行与异常任务”查看数据库、引擎、Redis 与任务处理心跳,并筛选全局异常任务。该页面仅做诊断,不自动重试或退款;升级后的常驻 worker 需重启才能产生新心跳,详见 [运行诊断说明](ADMIN_OPERATIONS.md)。
## 6. 网站与控制台
文档根目录 `/home/virt-cloud/web/public`,未命中文件的请求交给 Slim 的 `index.php`。**不再使用原面板 `ProxyPass / http://127.0.0.1:8000/`**,普通页面/API 现在由 PHP 提供。
仅把 `/engine-console` WebSocket 转发到引擎,保留 Host、Origin、WebSocket 子协议与 Upgrade;发送可信 `X-Forwarded-Proto`。Nginx 示例,map 放在 http 级,location 放在现有 HTTPS server 内:
```nginx
map $http_upgrade $cloud_connection_upgrade {
default upgrade;
'' close;
}
location = /engine-console {
proxy_pass http://127.0.0.1:8000/engine-console;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $cloud_connection_upgrade;
proxy_set_header Host $host;
proxy_set_header Origin $http_origin;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
}
```
不要公开 `/internal/v1/*` 或开放 8000 防火墙。PHP `/api/internal/cloud/session-introspection` 建议在 Web 层限定本机访问,仍有内部签名认证。管理员浏览器上传最大 4 GiB 云镜像或最大 8 GiB 救援 ISO 时,需要同步配置 PHP、FPM、Web 服务器及反代的请求体上限和至少 900 秒的读写/执行超时;入口只对管理员开放。代码会流式写入 0600 私有临时文件,不会把完整镜像载入 PHP 内存,但临时目录和 `runtime/engine/` 所在磁盘必须同时预留足够空间。
## 7. 页面配置与验收
1. 管理员添加宿主机:填写现有 SSH/root/私钥口令、从可信控制台核验指纹,并设置地区、`default_network`、存储/ISO/救援目录后测试连接。宿主机基础表单不再写入旧版单 CIDR、网关或 DNS 字段。
2. 在“资源调度”中把宿主机加入一个资源池,并设置容量、安全余量和调度状态。当前每台宿主机只有一个权威资源池成员关系,因此也只有该资源池对应的一条权威线路;一台宿主机挂多条线路、多个 bridge/VLAN 或多个路由表属于后续阶段。
3. 打开宿主机“公网地址池”,为同一个 `default_network` 添加一个或多个互不重叠的实际公网 IPv4 CIDR,分别填写网关、DNS、客户机前缀、保留地址和状态。面板先在事务中保存期望配置,再向引擎提交同一版本;引擎确认后标记为 `applied`,并由面板把 CIDR 物化为具体 IP 账本。网络超时或响应不确定时保留同一 `request_key` 和版本重试,不能创建第二个池。调度器只使用面板策略、reservation 和 IP 账本计算的剩余资源。完整顺序和失败/回滚边界见 [单宿主机多公网 IPv4 地址池](MULTI_PUBLIC_IPV4_POOLS.md)。
4. 导入云镜像与救援模板;无已有模板不能开通云镜像 VM。云镜像是面板全局目录,验证后的源文件持久保存在 `runtime/engine/cloud-templates/`;首次在某宿主机创建或重装时才同步一份缓存,之后复用,所以切换地区不会更换或刷新镜像列表。支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10、Ubuntu 20.04/22.04/24.04/25.04/25.10/26.04 x86_64 云镜像。官方镜像可填写官方镜像站的 HTTPS 文件地址,引擎只跟随由官方入口返回且通过公网地址安全校验的跳转链;例如 AlmaLinux 8 可使用 `https://repo.almalinux.org/almalinux/8/cloud/x86_64/images/AlmaLinux-8-GenericCloud-latest.x86_64.qcow2`,Debian 12 可使用 `https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2`,CentOS Stream 9 可使用 `https://cloud.centos.org/centos/9-stream/x86_64/images/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2`,Ubuntu 24.04 可使用 `https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-amd64.img`。自制或修复镜像使用管理员页面的本地 QCOW2 上传入口,并明确选择与内容一致的系统和版本;文件必须是 1 MiB 至 4 GiB 的独立、未加密 QCOW2,不能包含 backing file 或外部 data file,ISO 和 raw 镜像均不接受。面板磁盘需为上传临时文件、全局源镜像及 256 MiB 安全余量预留空间,各宿主机的镜像存储池也需容纳本地缓存。远程导入的 SHA-256 可留空;本地上传始终由面板计算、签名并保存实际摘要。
5. 套餐设置规格、每期价格、账期天数、每期流量额度和库存,并绑定可销售的资源池。用户提交部署后先生成 30 分钟有效的开通账单,支付成功才创建实例;实例到期前 7 天再生成续费账单。两种账单均可用余额支付,也可由启用的易支付、Paytaro 或 USDT 渠道生成支付订单。在线支付回调会自动结清对应账单;失效账单的晚到款只保留在账户余额中,不会创建实例或恢复已进入删除流程的实例。
6. 测试用户注册验证码、密码重置、充值、生成开通账单和账单支付,确认未支付时没有引擎任务,支付后只创建一个实例,并收到一次开通成功邮件;再验证到期前 7 天只生成一张续费账单并发送提醒、到期仅断网、宽限期内续费恢复网络,以及到期满 3 天后永久删除实例和系统盘;同时验收任务、VM 控制台、SSH、重装、救援、手动删除与图表。
7. 日志库 `engine_vm_metric_samples` 应在所有用户退出后继续新增,`engine_vm_traffic_totals` 应持续累加 RX/TX 字节;稳定 MAC 用于跨 QEMU/tap 重启衔接计数,首批数据需等待采样间隔。
8. 用测试小额度验收:下载与上传合计达额度后 VM 仍运行但所有网卡断开;下一已付费周期开始后当期用量归零且网卡自动恢复。无下一周期时,实例到期后 VM 保持原电源状态但网络立即停用;3 天宽限期内续费会恢复网络,超过宽限期则永久删除实例和面板管理的系统盘。
先不要启用旧 `web/crontab`,付款扫描/备份任务按保留业务单独核对。真实 MariaDB/KVM/SMTP/支付未在开发环境联调,先验收测试环境。公网地址池或破坏性任务进入 `uncertain` 时先按记录的请求标识、版本和 `operation_id` 对账,不要换新标识重复提交、直接改库退款或重复毁盘任务。
## 8. 从旧版更新
首次升级到带在线更新功能的版本仍需通过 SSH 在维护窗口完成。开始前备份业务库、日志库和 `runtime/engine/master.key`。下例先停掉所有会写业务数据的服务,再更换源码和依赖;任何一步失败都不要执行最后的启动命令,应先修复或恢复备份。若 PHP-FPM unit 不是 `php-fpm.service`,将下列两处名称替换为实际 unit:
本版本的 `cloudInit` 会删除已退役的 `cloud_host_inventory_attempts`、`cloud_host_capacity_snapshots` 及宿主机旧健康字段;这是不可逆的结构迁移,必须在执行前保留可恢复的数据库备份。迁移后先完成旧实例资源/IP 账本审计、显式保留管理 IPv4,并确认未知/不确定宿主机没有重新开放销售,再启动 worker 和生命周期服务。
更新完成后先做部署页 smoke,再开放销售:确认 `SHOW COLUMNS FROM cloud_hosts` 不包含已删除的 `host` 列;用同一已登录管理员/用户会话请求 `/user/cloud/deploy` 和 `/api/v1/catalog`,两者都应返回 200,销售目录应显示资源池账本计算出的可售状态。同步查看 `php-fpm` 错误日志,不能出现 `eligible_host.host` 或 `no such column`。共享静态资源键当前为 `2026100701`,页面 `data-asset-version`、`/cloud/app.js`、`/cloud/deploy.js` 和 `/cloud/runtime.js` 的查询参数应一致。旧的 SQL 500 不是通过清 Smarty 缓存解决的;缓存清理只能作为确认代码和 FPM/opcache 已加载后的辅助动作。
```bash
set -euo pipefail
systemctl stop php-fpm.service virt-cloud-engine.service virt-cloud-worker.service \
virt-cloud-lifecycle.service virt-cloud-policy-worker@1.service \
virt-cloud-policy-worker@2.service
cd /home/virt-cloud
git pull --ff-only origin venix
cd /home/virt-cloud/web
composer install --no-dev --prefer-dist --optimize-autoloader
php xcat cloudInit
cd /home/virt-cloud
engine/.venv/bin/python -m pip install -r engine/requirements.txt
cp /home/virt-cloud/deploy/virt-cloud-engine.service /etc/systemd/system/virt-cloud-engine.service
cp /home/virt-cloud/deploy/virt-cloud-worker.service /etc/systemd/system/virt-cloud-worker.service
cp /home/virt-cloud/deploy/virt-cloud-lifecycle.service /etc/systemd/system/virt-cloud-lifecycle.service
cp /home/virt-cloud/deploy/virt-cloud-policy-worker@.service /etc/systemd/system/virt-cloud-policy-worker@.service
cp /home/virt-cloud/deploy/virt-cloud-update.service /etc/systemd/system/virt-cloud-update.service
systemctl daemon-reload
systemctl enable virt-cloud-lifecycle.service \
virt-cloud-policy-worker@1.service virt-cloud-policy-worker@2.service
systemctl start virt-cloud-engine.service virt-cloud-worker.service virt-cloud-lifecycle.service \
virt-cloud-policy-worker@1.service virt-cloud-policy-worker@2.service php-fpm.service
```
以后超级管理员可在“在线更新”页面填写具有该私有仓库只读权限的 Gitea 访问令牌。仓库地址固定为 `https://g.luoli.live/root/virt.git`,分支固定为 `venix`,网页不能修改。令牌写入主库 `engine_records` 时使用引擎 `master.key` 和随机 nonce 进行 AES-GCM 认证加密;读取设置只返回是否已配置,令牌不会回显到页面、Git URL、命令参数或日志。备份数据库时必须同时备份 `runtime/engine/master.key`。若 PHP-FPM unit 不是默认的 `php-fpm.service`,在 `web/config/config.php` 设置 `cloud_update_php_fpm_unit` 后重新执行 `php xcat cloudInit`。
点击更新前,项目根目录必须是干净的 Git 检出、处于 `venix`、origin 与固定地址完全一致,目录及 `.git` 不能允许组或其他用户写入。工单图片属于运行时数据,保存在 `web/storage/ticket-attachments/`,新版本已通过 Git 忽略规则排除;更新器不会删除或覆盖这些附件。若旧版本已经上传过附件,首次升级前先在项目根目录核对工作树只包含该目录,再执行一次性本地排除(不要执行 `git clean`):
```bash
git status --short --untracked-files=all
printf '\n# Runtime ticket images\n/web/storage/ticket-attachments/\n' >> .git/info/exclude
git status --short --untracked-files=all
```
确认第二次状态为空后再打开在线更新。更新器只接受快进提交并保存人工回滚引用;通过兼容性检查后,才暂停引擎、worker、策略服务和 PHP-FPM,快进切换代码,执行幂等 `php xcat cloudInit`,最后重启并检查现有服务。更新期间虚拟化写操作会暂停,页面轮询只查询原任务,不会重复提交更新。
在线更新是纯代码更新:不运行 Composer 或 pip,不创建依赖暂存目录,不复制、改写或重载 systemd unit。若目标提交修改 `engine/requirements.txt`、`web/composer.json`、`web/composer.lock` 或 `deploy/**`,面板会在停服和切换代码前拒绝整个版本。这类版本必须通过 SSH 执行上述手工流程,由部署者审核并安装锁定的 PHP 依赖、Python 依赖和定制的服务单元。
更新失败时不要反复点击;先查看任务显示的旧提交、回滚引用和以下日志。若代码已经切换但数据库升级、服务重启或健康检查失败,页面会明确显示失败而不会伪报成功。任务状态为 `blocked` 表示代码与数据库兼容性尚未确认:维护锁会继续生效,页面不会重新开放令牌、检查或执行按钮。必须通过 SSH 核对 Git、数据库初始化状态和服务日志。如果任务在进入数据库迁移前中断,恢复为记录的干净 `old_commit` 可作为安全释放条件;但一旦进入 `schema_migrating`,MariaDB DDL 可能已部分提交,仅回退源码不会解除维护锁。部署者必须手工完成并验证迁移、代码和服务兼容性,不得盲目启动服务:
```bash
journalctl -u virt-cloud-update.service -u virt-cloud-engine.service \
-u virt-cloud-worker.service -u virt-cloud-lifecycle.service \
-u 'virt-cloud-policy-worker@*' -n 300 --no-pager
```
若确认应继续使用任务记录的 `new_commit`,先保证项目处于该提交且工作树完全干净,再使用受控的前向恢复命令;不要绕过状态机直接启动业务服务。该命令会再次停止相关服务、重跑幂等 `cloudInit`,持久记录数据库安全检查点,并在全部服务和私有引擎健康检查通过后解除维护锁:
```bash
cd /home/virt-cloud/engine
CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json \
.venv/bin/python -m virsh_panel.update_worker --recover-blocked
```
命令会自行拒绝不等于任务 `new_commit` 的 HEAD、脏工作树或非 `blocked`/可恢复任务。若再次失败,服务与维护锁会按最后一个可证明安全的检查点保持;继续依据日志处理,不要手工删除数据库中的更新记录。
已存在的宿主机需在管理页重新保存一次。当前版本不再把保存宿主机当作存量虚拟机盘点入口:保存和连接测试只验证 SSH、存储池和网络配置;宿主机容量、可售 IP 和调度状态完全来自面板的资源池策略、reservation 和具体 IP 账本。旧版本实例如果没有 reservation,会在首次应用公网地址池时从 `cloud_instances.spec_json` 导入可验证的 CPU、内存、磁盘和公网 IP;字段缺失、格式损坏或重复地址会被标记为未知/不确定并阻止该宿主机继续售卖,不能用宿主机扫描绕过。宿主机管理 IPv4 必须提前加入地址池 `reserved_ips`,因为引擎不会把管理地址作为客户 IP;桥接网络仍由管理员预先配置。
订单状态为“待核对”时不要重复下单或手动退款。worker 会使用原操作编号向引擎核对,确认成功后关联实例,确认未创建后才退款。管理页会显示格式化时间、尝试次数和安全的错误摘要;更详细日志使用:
```bash
journalctl -u virt-cloud-worker.service -u virt-cloud-engine.service \
-u virt-cloud-lifecycle.service -u 'virt-cloud-policy-worker@*' -n 200 --no-pager
```

@ -0,0 +1,77 @@
# Virt Cloud 集成架构
更新:2026-10-07。描述当前实现边界;真实部署仍需测试环境联调。
## 请求链路
```text
浏览器
├─ HTTPS 页面/API → PHP:账户、授权、CSRF、套餐、钱包、订单
│ └─ HMAC 内部 API → Python → SSH/libvirt → 宿主机
└─ WSS /engine-console ──────────────────→ Python → SSH 隧道 → VM VNC
PHP cloudWorker → 持久任务 → Python operation_id → 实例关联/核对/退款
Python 后台采集 → 日志库指标/持久流量基线 → 图表与字节计量
PHP cloudLifecycle → 续费账单/独立账期/流量限额 → 到期断网、恢复或宽限期后永久删除
PHP cloudWorker → 隔离投递账单提醒和实例开通成功邮件 → SMTP 异常不阻塞开通事务及到期策略
```
PHP 是唯一账户入口,所有用户页面使用原虚拟化面板 CSS;后台保留 venix。没有第二套 Python 注册、SMTP、数据库设置或审核流程。
## 数据职责
| 数据 | 权威写入方 | 存储 |
| --- | --- | --- |
| 用户、钱包、套餐、原财务/工单 | PHP | 原业务库表 |
| 宿主机索引、资源池成员关系、网络接入、公网池/IP 账本、订单、实例、账单、支付映射、账期、续费、公钥、会话、任务 | PHP | `cloud_hosts/cloud_host_resource_pool_memberships/cloud_host_network_attachments/cloud_public_ip_pools/cloud_public_ips/cloud_orders/cloud_instances/cloud_invoices/cloud_invoice_payments/cloud_service_periods/cloud_renewals/cloud_ssh_keys/cloud_sessions/cloud_jobs` |
| 宿主机凭据、VM 元数据、镜像、操作进度 | Python | 主库 `engine_records`,敏感记录加密 |
| 引擎签名防重放 | Python | 主库 `engine_request_nonces` |
| 四项性能指标样本 | Python | 日志库 `engine_vm_metric_samples`,保留 30 天 |
| VM RX/TX 持久累计与网卡基线 | Python | 日志库 `engine_vm_traffic_totals`,不随 30 天图表样本清理 |
多个宿主机使用稳定 `host_id`,不共用一个可切换的全局“当前宿主机”。模板、磁盘/ISO/救援目录和默认网络均按宿主机设置;单台宿主机可在同一个 `default_network` 下保存多个互不重叠的公网 IPv4 CIDR。每个池有稳定 `pool_key`、独立网关/DNS/客户机前缀/保留地址/运行状态,以及 PHP 期望和已应用 revision。地址池与网卡前缀分开:供应商地址池可以为 /28,虚拟机网卡可以为 /24,不能因此把售卖范围扩大为 /24。面板由容量策略、reservation 和具体 IP 账本计算剩余资源;引擎只应用网络配置并在创建/换 IP 时做当前操作的最终校验。具体上线顺序见 [单宿主机多公网 IPv4 地址池](MULTI_PUBLIC_IPV4_POOLS.md)。
当前网络模型有意保持一条权威路径:每台宿主机只有一个 `default_network`,并通过唯一有效的资源池成员关系归属一条线路;多个公网 CIDR 共享该网络接入。线路管理和数据表为未来扩展保留,但“同一宿主机同时销售多条线路”尚未开放。该阶段必须增加多个资源池成员/网络接入选择、bridge/VLAN/路由表验证、逐线路容量以及实例跨接入迁移策略,不能仅给现有公网池补一个线路下拉框。
PHP 不直接解密 Python 记录或执行任意 virsh 命令。主库与日志库可同实例或分别配置地址/端口。敏感业务数据加密;部署数据库连接配置仍是权限受限配置文件,不代表配置文件本身加密。
在线更新同样遵守这条边界:PHP 仅做超级管理员授权、CSRF 和固定路径代理;Gitea 令牌由私有引擎写入加密 `engine_records`,Git 快进、幂等升级及现有服务重启只由按需启动的 root `virt-cloud-update.service` 执行。仓库和 `venix` 分支均不可由浏览器修改,更新仅允许干净工作树上的 fast-forward。在线流程不运行 Composer/pip、不建立依赖暂存区、不改写 systemd unit;目标提交一旦修改 `engine/requirements.txt`、`web/composer.json`、`web/composer.lock` 或 `deploy/**`,必须在停服与切换前拒绝并改走 SSH 升级。工作器以持久检查点区分“代码已切换但数据库未确认”、“数据库正在迁移”与“数据库已就绪”;不安全的中断进入 `blocked` 并保留维护锁,不会在兼容性未知时自动启动服务。特别是进入 `schema_migrating` 后,MariaDB DDL 可能已部分提交,仅回退源码不足以解除维护锁。
## 购买状态机
1. 用户选择启用套餐、已有系统来源、公钥/强 root 密码,提交幂等键。
2. PHP 事务校验销售库存、宿主机面板容量与公网 IP 账本,保存不可由浏览器改写的规格快照和加密创建载荷,预留有限库存并生成开通账单;此时不扣钱、不创建引擎任务。账户不设固定实例数量上限。
3. 余额或在线支付结清账单后,同一事务才扣减钱包并创建唯一队列任务。未支付开通账单 30 分钟后失效,释放库存并清除其加密凭据载荷;晚到的在线付款只保留为账户余额。
4. 独立 `cloudWorker` 获取租约,携带唯一 `operation_id` 请求引擎。只有已支付且经过签名的开通上下文可以创建 VM。
5. 成功关联实例和凭据;确认创建失败且无残留时只退款、恢复库存一次。超时、引擎中断或残留无法确认时保持待核对,只查询原操作,不重复创建或盲目退款。
金额通过精确小数与整数最小单位换算处理,不用浮点完成扣款比较。套餐带宽转换成 libvirt 网卡双向 KiB/s 限制。到期前 7 天幂等生成一张续费账单和可重试邮件任务;账单可由余额结清,也可绑定现有在线支付订单。网关回调先入账余额并在同一事务结清账单,净余额为零;账单已结清或失效时晚到款保留为余额,不能重复续期或丢失。每次结清账单都生成一个独立预付费周期,提前支付只排在已购周期末尾,不会提前刷新当期流量。每期额度为下载 RX + 上传 TX;用尽只持久断开网卡,VM 不关机;下一已付费周期开始时以新的累计基线归零当期用量并自动恢复网卡。
未支付账单不会延长到期时间。实例到期时只停用网络,不改变用户原来的开关机状态;在随后 3 天宽限期内结清账单会建立新账期并自动恢复网络,也不会擅自开启用户已经关机的 VM。到期满 3 天仍未支付,账单失效,系统先安全收敛虚拟机电源状态,再永久删除实例定义和面板管理的系统盘;此后支付渠道的晚到款只进入账户余额,不能恢复已经删除的实例或磁盘。数据库继续保留订单、账单和支付审计记录,“永久删除”指宿主机上的实例及其受管磁盘数据。
单台实例默认最多排队 24 个未来账期,可通过 `cloud_max_renewal_periods_ahead` 调整(服务端限制为 1–120)。这个上限在实例行锁内校验,避免免费套餐或自动化重复请求无限写入续费与账期记录。
本轮不含免确认自动扣费、套餐升级、账单自动退款或按日比例退款。已生效服务账单不得通过支付渠道自动退款;需要人工审核并进行补偿记账。流量依赖约 60 秒的宿主机采样,因此限额可能有一个采样间隔的少量超额;日志库不可读时采取 fail-open,不会因未知流量误停租户。
## 安全与控制台
- 用户 ID、角色、VM 归属由 PHP 确定,不能相信浏览器身份字段;引擎再次检查归属。
- 管理员与 `super_admin` 白名单权限分开;跨用户只读不自动获得跨用户写权限。
- 云 API 写操作校验 CSRF;未登录/无权限返回 JSON,不重定向 HTML。
- HMAC 覆盖方法、完整路径/查询、请求体摘要、时间戳、nonce、身份。防重放存储是共享的持久数据库/Redis。
- PHP 签名密钥与任务加密密钥独立生成;任务使用 sodium secretbox 随机 nonce,引擎有独立 master.key。备份时保存密钥,不能删除后期待解密数据。
- root 公钥和密码可以同时设置,未填密码时生成强密码;root 密码策略独立于网站 bcrypt 的 72 字节限制。
VNC 凭据 60 秒有效、单次、绑定用户/VM/会话,通过 WebSocket 子协议传递而非 URL。连接期间持续校验 PHP 会话,退出或停权会阻止继续访问。线上使用 HTTPS/WSS。
## 原虚拟化功能与限制
保留云镜像/ISO 创建、UEFI/ACPI、host-passthrough、virtio 队列随 vCPU、开机自启、首次安装重启停止并弹出 ISO、磁盘删除、重装网络保留、救援挂载/卸载、SSH 隧道 VNC。救援正常关机失败不会自动断电,用户可确认硬重启,主动退出救援前 ISO 保持挂载。
重装、救援、手动删除和到期自动清理使用持久操作编号,进程中断不盲目重复破坏性步骤。自动清理只有在实例定义和受管磁盘的删除结果得到确认后,才把业务库实例标记为已删除;宿主机或磁盘异常会保留失败状态供管理员处理,不会伪装成成功。救援 ISO 为管理员授权原始流上传及摘要校验;线上需配置 FPM/反代超时与大小限制。
已实现按资源池的面板容量策略、CPU/内存/磁盘 reservation 和具体 IP 账本调度,多公网池配置使用稳定请求标识与 revision 幂等写入;不再周期盘点宿主机容量或 IP。用户列表、状态同步和生命周期观察只向引擎发送面板已知的 UUID,宿主机保存/测试也不枚举全部域。尚未实现同一宿主机多线路选择、IP/MAC 防伪的完整租户策略、套餐磁盘 IOPS、备份、热迁移或 HA。线程中断进入待核对,并非完整步骤恢复;后续应增加基于 `operation_id` 的运维对账与独立执行器。
上线前必须验收真实 MariaDB 并发、两库权限、宿主机固件/网桥/SELinux、cloud-init 与 SSH、浏览器 WSS、会话撤销、失败清理/退款。SMTP 沿用 venix,TLS 证书校验已恢复,自签邮件证书需修复信任链。
全新安装见 [DEPLOYMENT.md](DEPLOYMENT.md),历史清理见 [PRUNING_REPORT.md](PRUNING_REPORT.md)。

@ -0,0 +1,48 @@
# 单宿主机多公网 IPv4 地址池
## 当前范围
一台独占宿主机可以配置最多 32 个互不重叠的实际公网 IPv4 CIDR。每个 CIDR 独立保存网关、1~4 个 DNS、客户机前缀、保留地址和运行状态;CIDR 与客户机前缀范围为 `/24`~`/30`,客户机前缀不能比地址池前缀更长。
当前阶段是一条手工准备好的 bridge、一个资源池成员关系和多个公网池。多线路、VLAN、路由表及实例迁移需要另行设计。
## 权威数据与状态
| 对象 | 作用 |
| --- | --- |
| `cloud_host_network_attachments` | 面板保存宿主机、线路和 `default_network` 的接入身份 |
| `cloud_public_ip_pools` | 面板保存池配置、期望/已应用版本和应用状态 |
| `cloud_public_ips` | 面板唯一的具体 IP 账本,保存可用、预留、分配和不确定状态 |
| 私有引擎公网池目录 | 只保存面板下发的运行配置,并在创建/换 IP 时做最终参数校验 |
面板是调度、容量、reservation 和 IP 可售状态的唯一事实源。引擎不再向面板提供宿主机容量或 IP 盘点结果;宿主机连接仅用于配置网络、执行 VM 操作和对当前操作做最终校验。IP 分配使用面板账本与引擎原子 claim,不在每次创建时枚举宿主机全部虚拟机。
从旧版本升级时,先备份业务库并停止销售,再运行 `php xcat cloudInit`。旧实例若没有 reservation,首次物化地址池会从 `cloud_instances.spec_json` 迁入仍有效的公网地址和资源规格;无法解析、重复或缺少资源字段的记录会进入未知/不确定状态并 fail-closed。管理宿主机的 IPv4 必须显式加入 `reserved_ips`,引擎不会通过扫描自动发现并保留它。面板账本之外手工创建的客户地址不会被系统发现,独占宿主机和预配置 bridge 是当前版本前提。
地址池状态:
- `active`:允许从面板 IP 账本分配新地址。
- `draining`:停止新分配,保留现有实例和任务。
- `disabled`:停止新分配,不自动释放已有占用。
应用状态:`pending` 表示已经写入面板、等待引擎确认,`applied` 表示响应与版本匹配且面板已物化 IP 账本,`failed` 表示引擎明确拒绝,`uncertain` 表示网络或业务库无法确认结果,`never` 表示尚未提交。调度器不依赖宿主机扫描或新鲜度标记。
## 配置与幂等顺序
1. 更新代码和依赖后,在停写维护窗口运行 `php xcat cloudInit`,再重启引擎、worker 与 lifecycle。
2. 添加宿主机并验证 SSH 指纹,设置地区、目录和唯一 `default_network`;桥接网络由管理员预先在宿主机准备好。
3. 在“资源调度”中加入资源池,填写 CPU、内存、磁盘、安全余量和最大实例数。面板用这些策略减去 reservation/IP 账本计算剩余资源。
4. 在“公网地址池”逐个添加实际 CIDR。创建使用稳定 `request_key`,它确定性映射到池标识;更新使用页面读取的 `expected_revision`,旧表单不能覆盖新版本。
5. 面板在事务中保存配置并生成版本,然后向私有引擎提交同版本。签名响应匹配后标记 `applied`,自动物化 CIDR 中未保留的具体 IP;响应超时则标记 `uncertain`。
6. 超时后必须使用原 `request_key` 和原版本重试。引擎对同池同版本返回幂等结果,面板只把同一条记录恢复为 `applied`,不会创建第二个池或第二批 IP。
7. 用测试实例验证创建、重装、换 IP、任务失败恢复、相同 client token 重试和两个 CIDR 的实际公网连通性。
旧 `legacy-default` 只读展示,不自动迁移;检测到旧池时先停止销售、备份并按新版结构重建。
## 失败、恢复与回滚边界
- 引擎明确拒绝时池进入 `failed`;修正输入并基于最新版本重新提交。
- 网络超时、5xx、响应不一致或业务库无法确认时进入 `uncertain`。按原 `request_key`、版本和日志中的 `operation_id` 对账,禁止换新标识盲目重复创建。
- 池中存在实例、预留、换 IP 或不确定任务时,不允许修改 CIDR、网关、DNS、客户机前缀、保留地址或网络接入;只能修改名称与运行状态。
- 停止新销售时改为 `draining` 或 `disabled`,待面板账本中的占用清空后再做前向清理;不要直接删库或复用地址。
- 代码回退不等于数据回退:数据库版本、面板账本和引擎运行配置可能已经前进。回滚前备份业务库及引擎密钥/记录;优先用前向修复恢复同一版本的幂等状态。

@ -0,0 +1,58 @@
# PHP 旧业务清理报告
日期:2026-09-27。所有改动仅在 `/Users/admin/Documents/www/virt-cloud/web`。
原 `/Users/admin/Documents/www/html` 和 `/Users/admin/Documents/www/virsh-panel` 未修改。清理阶段没有操作 Git;新项目后续统一使用目标仓库的 `venix` 分支管理。
> 历史说明:本文记录 2026-09-27 的旧业务裁剪阶段。之后 Virt Cloud 已完成宿主机配置集成;当前行为以 [INTEGRATION_PLAN.md](INTEGRATION_PLAN.md)、[DEPLOYMENT.md](DEPLOYMENT.md) 和现行路由为准。文中关于管理员宿主机页面“不接受凭据、不连接宿主机”的描述只代表当时的过渡状态,不是当前版本契约。
## 本轮完成
- 仅保留 venix 的模板和静态资源,删除 Material、Codex 两套主题。
- 用户页面节点列表、菜单、旧节点 API 全部移除;在本报告对应的过渡阶段,管理员 `/admin/hosts` 曾是宿主机配置准备页,字段和按钮禁用,不接受凭据、不保存配置、不连接宿主机;该状态已由后续 Virt Cloud 宿主机配置集成取代。
- 用户确认的 AI、社区聊天、边缘配置、DNS 策略、节点网络监控/访问 API、代理流量/TCP/连接告警、闲置/异常用户、Apple 账号功能、订阅记录、Redis 在线设备、在线 IP、审计规则/记录、付费注册、签到、用户文档和旧客户端分发功能已移除。包括路由、后台代码、模型、专属 SQL、页面和相关资源,不只是隐藏菜单。
- `Bob.php`、`apple-account-detector-go` 和检测器配套资源已移除。
- 取消代理流量/账户/等级重置、试用和自动清理任务;不再按账户/等级到期自动禁用或清除用户。验证码、会话、支付订单和优惠券的安全/支付有效期仍保留。
- 邮箱账户注册/登录、验证码、TOTP、可信设备、会话撤销、密码找回/修改、人工账户管理、公告、工单、问卷、邀请和充值/财务基础功能保留。手动邀请码轮换不是退役的代理重置任务。
- 账户表删去代理字段及账户/等级到期列,不提供旧测试数据迁移或代理占位字段。新密码使用 `password_hash`/`password_verify`,bcrypt cost 12、随机盐;新密码需 12–72 字节并包含大小写、数字、符号。旧 MD5/SHA 账户哈希不兼容。
- 本轮当时保留的用户旧商城及公开优惠码试算接口已在后续清理中移除;管理员基础套餐、销售方案与优惠券管理继续保留。旧代理套餐开通、流量/等级变更、重置/续费逻辑已经删除;保留优惠券管理不代表优惠券已接入新的云账单或订单流程。
- Telegram 只提供管理员私聊绑定和管理员工单通知。没有普通用户绑定、群组功能、TG 登录、签到、AI、订阅或机器人回复用户工单的能力;用户工单在网页处理。
## 配置、SQL 与备份
- 原实际 `.config.php` 未复制,因此修改的是 `web/config/.config.php.example`。
- 邮件、数据库和超级管理员配置区块保留;邮件模板已在后续云账单与实例通知工作中改造,不属于本次旧业务裁剪的原始结果。数据库区块内原有 Redis 在线库键也按“数据库配置不动”的要求保留,但没有在线设备实现再使用它们。
- 删除注册旧配置区块、旧业务重置/自动清理、多用户混淆、签到、文档、订阅/TG URL 等配置;保留登录 IP 绑定和剩余流量提醒配置。
- 剩余流量提醒阈值规则保留为 `TrafficNotificationThreshold`;尚未接入 VM 流量配额,因此不会读取已删除的代理用量字段或假装已经发出 VM 提醒。
- `ss.sql` 为全新 PHP 账户/销售基础结构,`user_log.sql` 仅保留邮件、设置和站点统计/安全五张表。它们不包含 Python 虚拟化引擎表;不要对生产数据库直接执行。
- 自动备份仅导出已配置的数据库 SQL,使用 AES-256 ZIP,私有目录 0700、文件 0600。无口令或 AES 支持时拒绝执行,不把网站、配置文件或应用密钥装入归档。数据库账号口令经私有临时客户端配置传递,不放入进程参数。
- 加密备份保存在 `storage/backups`,不自动删除历史。恢复加密支付设置还需另行保管原应用密钥/环境密钥;仅 SQL 不能替代密钥保管。
- cron 为注释示例,不会在副本中启动自动任务。
管理员 Telegram:配置入口已合并到 `/admin/ticket#telegram-notifications` 的“工单系统”,独立管理页面已删除。在这里配置开关、bot token 和独立 HTTPS 通信域名;token 与服务端生成的 webhook secret 使用 purpose-separated 密钥加密存储。升级时会尝试一次性导入旧 `config.php` 值,写入迁移标记后运行期只读数据库;示例配置已删除这些旧项。后台状态展示使用 60 秒 Redis 快照,其中 token 和 secret 始终保持密文,Redis 故障自动回退数据库,配置写入后立即失效快照;Webhook 校验、通知、注册和绑定等运行期凭据始终绕过缓存读取权威数据库。保存后注册 webhook、生成五分钟一次性绑定码,再向机器人私聊发送 `/start 绑定码`。绑定码只存哈希、事务锁消费;Webhook 使用官方 [secret token 请求头](https://core.telegram.org/bots/api#setwebhook) 校验,不在 URL 中传 secret。当前通知仅绑定一个管理员接收方,后台可重新绑定或解绑。
## 验证及限制
- 使用隔离 PHP 8.5.10 检查全部 177 个 PHP 源文件语法,32 个测试中 30 个通过、2 个因运行时缺少 sodium 扩展未能完成。涵盖路由目标、账户强密码、配置/SQL 边界、手动删除隔离、验证码、会话、邮件假客户端、配额阈值、CLI 安全等。
- Smarty 编译全部 66 个 venix 模板,无应用引导、无真实数据库访问;独立 Telegram 管理页路由移除后,共 142 条路由注册目标可解析。
- 44 个内联脚本以两种模板分支共检查 88 次,10 个顶层 venix JS 文件语法通过;51 个完整页面展开后的 HTML 标签检查通过。
- USDT 模拟扫描与 SQLite 内存库重复入账测试通过。易支付/Paytaro 完整测试受隔离运行时缺少 sodium 扩展限制,不能记为完整通过;保留真实加密实现,未做降级。生产运行仍需对应 PHP sodium 扩展。
- 依赖按现有 Composer lock 安装到临时测试目录,未升级项目锁定版本、未给网站安装运行依赖。
- 原第三方 Datatables 库仍有 PHP 8.5 弃用提示;原 venix 第三方 CSS 有少量已有的装饰图片缺失,不属于此次删除导致。尚未进行浏览器完整业务联调。
- 没有连接真实 MariaDB/Redis、SMTP、Telegram、支付渠道或虚拟化宿主机,没有初始化或清理任何真实数据库。
这仍是待集成的开发版本。网页首次初始化、统一普通用户 CSRF、SMTP TLS 校验、Python 私有引擎认证、VM 所有权、开通/计费状态机、VNC 和大文件上传等仍需后续实施;不要把此轮清理当成销售面板已经上线。
## 可恢复副本
清理前完整快照:
`/private/tmp/virt-cloud-prune.QCPXnM/web-before-prune.tar.gz`
精确移出的目录/文件:
- `/private/tmp/virt-cloud-prune.QCPXnM/removed-ui/views/material`、`views/codex`
- `/private/tmp/virt-cloud-prune.QCPXnM/removed-ui/theme/material`、`theme/codex`
- `/private/tmp/virt-cloud-prune.QCPXnM/removed-ui/downloads/SSEncrypt.module`
- `/private/tmp/virt-cloud-prune.QCPXnM/removed-backend` 中的 Bob、Go 检测器及删除文件清单
以上临时路径可能被系统清理。需要长期保留时,请把完整快照另存到自己的备份位置;不要直接覆盖已清理的工作目录,恢复应先解压到新的目录核对。

@ -0,0 +1,86 @@
# 本版验证记录
## 2026-10-07:在线更新后部署页 SQL 回归修复
- 在线更新到 `521d40a` 后,`/user/cloud/deploy` 在读取销售目录时会因 `cloud_hosts` 不存在 `host` 列而返回 500;同一错误也影响管理员资源汇总。根因已在 `e7230ff` 修复,应用查询现在只使用面板资源策略、reservation 和已物化的公网 IP ledger。
- 管理 IPv4、网关和 DNS 必须在地址池 `reserved_ips` 中显式保留;代码不再从宿主机模型读取 SSH/管理地址,也不通过宿主机盘点补全地址。
- saleCatalog SQLite/WASM 首屏 smoke 通过;部署 SSR、资源调度、IP ledger、宿主机网络池/调度、模板编译、虚拟化资产和 Node JS 语法检查通过。完整财务流程继续执行到既有 reconciliation 场景后失败,不能把该失败归因于本次缺失列修复。
- 代码修复提交为 `e7230ff`,随后补充部署 smoke 与验证记录文档;提交链已推送到远端 `venix`。真实 PHP-FPM、MariaDB、浏览器和宿主机仍需部署验收;上线后应同时检查 `/user/cloud/deploy`、`/api/v1/catalog` 和 PHP-FPM 错误日志。
## 2026-10-07:移除账户实例数量上限
- 删除账户实例数量配置、购买事务中的账户级 409 检查,以及金融测试中依赖该限制的场景;账户实例数量现在只受销售库存、宿主机面板容量、reservation 和具体公网 IP 账本约束。
- 全仓精确搜索未发现该配置键或账户上限错误文案的 CSS、JS、SQL 残留;`cloud_host_capacity_policies.max_instances` 保留为单宿主机调度容量,分页大小和快照/防火墙等其他实例上限也未误删。
- 账户上限相关的财务流程已越过,完整金融测试仍在既有 reconciliation fixture 处失败;具体契约、模板、JS 语法和 `git diff --check` 通过。真实 PHP-FPM、MariaDB 和并发购买仍需部署环境验收。
## 2026-10-07:面板资源账本取代宿主机盘点
- 调度、创建放置和网络选项现在只读取面板配置的容量策略、活动资源池、reservation 账本和 `cloud_public_ips`;不再要求容量快照、盘点新鲜度、宿主机 `host/network-options` 或 VM discovery 结果。
- 创建和换 IP 的引擎路径只读取面板传入的具体地址池参数与持久 claim,并用原子 claim 防并发重复;不会为每个请求枚举宿主机全部虚拟机。
- 宿主机保存/连接测试只验证 SSH、存储池和网络资源,不调用 `list_vms()`;用户 VM 列表和指定 UUID 的状态读取仍保留为用户操作及结果核对路径,不参与容量或 IP 调度。
- 用户列表、实时状态和生命周期状态同步只向引擎发送面板已知的 UUID(每批最多 100 个);旧的无参数全量状态接口仅为未接入面板的私有兼容 UI 保留。
- 引擎本机兼容 UI 仍保留全量 `/api/v1/vms`、无参数 `/api/v1/vm-states` 和资源目录接口;它们不进入 PHP 调度链,部署只允许 `127.0.0.1:8000`,不能作为公网管理入口。`inventory-panel` 是旧 UI 的通用卡片类,不代表已保留宿主机容量盘点功能。
- 旧 `cloud_instances.spec_json` 的可验证资源与公网地址会在地址池物化时迁移到面板账本;缺失、损坏或重复数据会阻止该宿主机调度。管理宿主机 IPv4 需在 `reserved_ips` 中显式保留。
- 私有引擎仍负责最终宿主机操作和具体 IP claim。网络超时或响应不确定时保留 `operation_id` 与 reservation,先核对再决定补偿;同一 client token 重试不得重复创建。
- 最终隔离回归:`engine.tests.test_libvirt_service` **183 passed、10 skipped**;`test_app.py` 与 `test_engine_boundary.py` **205 passed、4 failed**。4 个失败均为既有的云模板平台策略断言和 Python 3.9 上传超时/事件循环兼容问题,不涉及面板调度、IP 账本或盘点删除路径。
- PHP/WASM 契约测试通过:`CloudInstanceReadPerformanceTest`、`CloudInstancePageSsrContractTest`、`AdminHostNetworkPoolsContractTest`、`AdminResourceSchedulingContractTest`、`CloudNetworkIpLedgerContractTest`、`AdminHostSchedulingContractTest`、`CloudMultiHostSchemaDefinitionTest`、`VirtualizationAssetsTest`。
- `python -m compileall` 与 `git diff --check` 已通过。当前 macOS 工作区没有 PHP CLI、Composer 依赖、真实 MariaDB、systemd journal 或 libvirt 宿主机;PHP 契约测试使用隔离 WASM 运行时,真实引擎/数据库验收仍需在部署环境复跑。
## 2026-10-06:系统日志异步读取与详情
- 系统日志首屏改为只渲染页面框架,列表 API 增加浏览器截止时间、显式停止读取、旧响应隔离和 `journalctl` 子进程的有界回收;分页游标使用 `--cursor` + `--reverse`,按 systemd 的实际 seek 语义从边界向更早记录读取,并防御性移除意外返回的边界记录。
- 新增管理员只读详情接口,按列表携带的 UTC 微秒时间戳和服务窗口重新读取单条记录,再校验 journal cursor;返回受限的完整诊断字段和完整消息。日志轮转、字段上限和敏感字段省略均有明确状态。
- 使用工作区捆绑 Node 运行并通过 `AdminSystemLogsBehaviorTest.mjs`、`AdminOperationsCancelBehaviorTest.mjs`、日志页 JavaScript 语法检查和 `git diff --check`。
- 当前 macOS 工作区没有 PHP CLI、Composer 依赖或 systemd journal,因此 PHP 契约测试、真实 PHP-FPM 子进程超时回收和远程宿主机日志读取仍需在部署环境复跑。
## 2026-10-06:修复系统日志详情抽屉不可见
- 现场复现确认:日志行的鼠标点击和键盘事件已经执行,详情请求也可发出;页面没有视觉反馈是因为日志页直接调用 `showModal()`,绕过了共享抽屉的 `is-drawer-visible` 动画类,抽屉因此保持在屏幕右侧的初始变换位置。
- 日志页现在统一使用 `VenixDrawerMotion` 打开和关闭详情,缺少共享脚本时仍有可见的降级路径,同时锁定页面滚动、恢复触发行焦点,并拦截原生 `cancel` 事件以完成动画关闭。
- 详情对话框位于日志 `<main>` 外,详情消息和字段样式已改为直接以 `#system-logs-detail` 作用域,避免样式选择器永远不匹配。
- `AdminSystemLogsBehaviorTest.mjs` 现通过嵌套消息元素模拟真实冒泡点击,并验证鼠标、Enter、空格、共享 motion、可见类和滚动锁;资产版本更新为 `2026100602` 以避免部署端继续使用旧脚本。
## 2026-10-04:盘点只读并发与删除驱动清理(历史记录,盘点方案已退役)
- `host/capacity`、`host/network-options` 与诊断查询已从引擎全局写锁、在线更新修复及 ISO/云镜像惰性清理中拆出;删除后的宿主缓存回收只由持久 tombstone 监督器重试。诊断专项回归:**33 passed**,覆盖慢盘、取消/晚完成、满接纳窗口终态、淘汰失败上界、异常引用释放及 daemon writer 退出边界。
- Python 3.12 全量隔离回归:**762 passed、10 skipped、68 subtests passed、1 failed**。唯一失败仍为 `test_app.py::test_native_public_pool_blocks_silent_default_network_change` 的既有 409“公网地址池目录存储不可用”;该失败在本轮修改前已有独立复现记录。
- 本轮没有修改 PHP 或前端源码;当前工作区没有 PHP/Node 可执行文件,因此未重复运行上一节的 PHP/WASM 与页面行为测试。
- 未连接真实 MariaDB、systemd 或 SSH/libvirt 宿主机。该轮并发盘点验证属于历史实现;当前上线验收应改为并发创建、IP reservation、相同 client token 重试及 `operation_id` 对账,并验证显式删除模板后的离线宿主重试与代际保护。
## 2026-10-04:宿主机盘点诊断(历史记录,相关页面和服务已删除)
本轮只增加过渡期诊断历史、管理员页面和跨 PHP/引擎阶段证据;每请求 8 秒预算、容量/IP 提交代际和调度判定不变。该页面和服务不再属于当前部署路径,以下结果仅用于解释迁移前的基线。
- Python 3.12 全量隔离回归:**747 passed、10 skipped、68 subtests passed、1 failed**。新增诊断用例覆盖签名/权限、锁等待、存储失败降级、嵌套阶段、取消请求与 worker 晚完成、重启和保留上限。
- 唯一 Python 失败为 `test_app.py::test_native_public_pool_blocks_silent_default_network_change`:测试创建公网池返回 409“公网地址池目录存储不可用”,预期 200。在修改前的 `fad3b4e` 独立源码快照中复现同一失败;未在本轮扩大范围修改。
- 隔离 PHP 8.5.10/WASM、精确 `composer.lock` 依赖与 SQLite 测试曾覆盖盘点客户端、诊断、同步服务和关系边界;这些盘点专项名称和结果仅保留作迁移前记录,对应页面、同步服务和诊断服务当前已删除,不再列入本版执行集。
- 扩展 PHP 检查另发现两项既有失败,均在 `fad3b4e` 快照复现:`CloudProtocolTest.php:85` 的源码断言插值 `$actor`;`CloudAdminOperationsServiceTest.php:245` 的查询字段断言与原服务选择 `payload_cipher` 不一致。本轮未修改这两个测试或其既有服务。
- 过渡期盘点页面行为测试、相关 PHP 语法、两份 JS 语法及 `git diff --check` 曾通过。该页面和测试已删除;当前前端验收应覆盖宿主机调度抽屉、面板容量计算、IP 账本筛选和操作核对。
- 未连接真实 MariaDB 或远程宿主机,没有验证生产 PHP-FPM/systemd、cURL 传输、SSH/libvirt 延迟或诊断持久化的实际 I/O 开销;不能据此声称用户当前 `unavailable` 的根因已确定。真实环境启用后,应依据新增记录验证失败层和最后确认阶段。
## 2026-09-27:集成基线
2026-09-27,集成代码的隔离验证,不代表生产验收。
- 当前 macOS 工作区 Python 3.12 回归:515 passed、10 skipped、55 subtests passed。覆盖原虚拟化逻辑及私有 API、签名/重放、多宿主机归属、持久幂等、一次性 VNC、退出后断权、带宽 XML、救援上传摘要,以及到期断网/恢复、同实例变更串行、多网卡 live+config 断网/恢复、退出救援保持计费断网、流量累计检查点和破坏性操作结果核对。生产仍按部署文档使用 Python 3.12 或更新的受支持版本复测。
- 隔离 PHP 8.5.10 验证源码语法、Smarty 模板、路由目标、精确金额/HMAC、SQLite 购买开通/退款/超时核对、宿主机面板容量/IP 账本、租户隔离、Cookie/Redis 会话撤销及内省、统一用户资源和 noVNC 模块;账户固定实例数量上限已删除。本次账期与生命周期用例应覆盖提前续费、精确扣款幂等、RX+TX 额度、断网不关机、下期恢复、到期仅断网、3 天宽限期内续费恢复,以及宽限期结束后的实例与受管磁盘删除;当前 macOS 工作区没有 PHP 可执行文件时,需在下方 PHP 8.5 环境命令中复跑。
- Chrome 使用模拟 API 检查套餐购买、VM 详情/指标/凭据、公钥、重装/救援、后台宿主机/镜像操作与 CSRF;用户账户及登录等页面进行桌面/手机布局检查。不连接真实数据库或宿主机。
- PHP 隔离环境不提供 sodium:`CloudSecretsTest` 明确跳过,原 Paytaro/易支付密钥加密测试因同一缺失无法运行;财务/会话测试的加密存储仅用明确标注的测试替身,不作为实际加密验证。生产必须安装 sodium,没有弱加密回退。
- Python 的跳过项需要真实 libvirt/网络环境。没有验证真实 MariaDB 并发、AlmaLinux systemd、宿主机 VM 操作、SMTP、支付和大文件上传。
## 在具备依赖的环境复测
不要使用生产数据库/宿主机运行额外真实集成测试;以下默认单元/隔离测试:
```bash
cd /home/virt-cloud/web
for test_file in tests/*Test.php; do php "$test_file" || exit $?; done
cd /home/virt-cloud/engine
.venv/bin/python -m pip install -r requirements-dev.txt
PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest -q -p no:cacheprovider
```
PHP 测试需 Composer 开发可用依赖和测试所用 PDO SQLite。测试中的模拟凭据、地址与密钥不是部署配置。
上线前按 [部署说明](DEPLOYMENT.md) 完成测试用户的实际购买、首次 SSH 登录、重装、救援、VNC 撤销、故障清理退款与无人登录时持续采样。另须使用短测试账期实际验证:到期只断网、宽限期续费恢复网络、宽限期结束后 VM 定义/系统盘/cloud-init 盘均被删除,以及删除失败或响应丢失时不会错误标记成功。共享公网网桥的 IP/MAC 防欺骗及宿主容量调度尚未提供,不能只凭单元测试开放不受信任客户的资源销售。

5
engine/.gitignore vendored

@ -0,0 +1,5 @@
.venv/
data/
__pycache__/
*.py[cod]
.pytest_cache/

@ -5,3 +5,4 @@ pycdlib>=1.14,<2
passlib>=1.7.4,<2
PyMySQL>=1.1,<2
cryptography>=44,<49
libvirt-python>=10,<13; sys_platform == "linux"

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

@ -2195,15 +2195,15 @@ async function loadResources() {
const TEMPLATE_FAMILY_NAMES = {
almalinux: "AlmaLinux",
debian: "Debian",
centos: "CentOS",
centosstream: "CentOS",
centos: "CentOS Stream",
centosstream: "CentOS Stream",
ubuntu: "Ubuntu",
};
const TEMPLATE_ICON_PATHS = {
AlmaLinux: "/static/almalinux-icon.svg",
Debian: "/static/debian-icon.svg",
CentOS: "/static/centos-icon.svg",
"CentOS Stream": "/static/centos-icon.svg",
Ubuntu: "/static/ubuntu-icon.svg",
};
@ -2212,11 +2212,14 @@ function templateSystem(item) {
const familyKey = String(item?.os_family || "").trim().toLowerCase().replace(/[\s_-]+/g, "");
const namedFamily = Object.prototype.hasOwnProperty.call(TEMPLATE_FAMILY_NAMES, familyKey)
? TEMPLATE_FAMILY_NAMES[familyKey] : "";
const family = namedFamily
|| (/^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;
const idMatch = /^(alma|debian|ubuntu|centosstream)([0-9]{1,4})-/.exec(id);
const idFamily = ({ alma: "AlmaLinux", debian: "Debian", ubuntu: "Ubuntu", centosstream: "CentOS Stream" })[idMatch?.[1]] || "";
const rawIdVersion = idMatch?.[2] || "";
const idVersion = idMatch?.[1] === "ubuntu" && rawIdVersion.length === 4
? `${rawIdVersion.slice(0, 2)}.${rawIdVersion.slice(2)}` : rawIdVersion;
const family = namedFamily || idFamily || "其他系统";
const providedVersion = String(item?.os_version || "");
const version = /^[0-9]+(?:\.[0-9]+)?$/.test(providedVersion) ? providedVersion : idVersion;
return { family, version };
}
@ -2420,10 +2423,14 @@ function manualRootPasswordIssue(value) {
const characters = Array.from(value);
if (characters.length < 12) missing.push("至少 12 个字符");
if (characters.length > 128) missing.push("不超过 128 个字符");
if (!characters.every((character) => {
const code = character.codePointAt(0);
return code >= 0x21 && code <= 0x7e;
})) missing.push("仅使用不含空格的英文可打印字符");
if (!/[A-Z]/.test(value)) missing.push("大写字母");
if (!/[a-z]/.test(value)) missing.push("小写字母");
if (!/[^\p{L}\p{N}\s]/u.test(value)) missing.push("符号");
if (characters.some((character) => character !== " " && /[\p{C}\p{Z}]/u.test(character))) missing.push("仅使用可打印字符");
if (!/[0-9]/.test(value)) missing.push("数字");
if (!/[^A-Za-z0-9]/.test(value)) missing.push("符号");
return missing.length ? `自行设置的初始 root 密码还需:${missing.join("、")}。` : "";
}
@ -2437,7 +2444,7 @@ function updateRootPasswordHint(inputId, hintId) {
hint.classList.toggle("root-password-hint-success", !!value && !issue);
hint.textContent = issue || (value
? "密码符合要求,可与 SSH 公钥同时使用。"
: `${creatingVm ? "留空时自动生成强密码,即使选择了 SSH 公钥" : keySelected ? "留空时仅允许 SSH 公钥登录,不生成密码" : "不选公钥且留空时自动生成强密码"};自行设置需至少 12 个字符,包含大写字母、小写字母和符号。`);
: `${creatingVm ? "留空时生成 32 位完全随机密码,即使选择了 SSH 公钥" : keySelected ? "留空时仅允许 SSH 公钥登录,不生成密码" : "不选公钥且留空时生成 32 位完全随机密码"};自行设置需为 12 至 128 位不含空格的英文可打印字符,包含大写字母、小写字母、数字和符号。`);
}
function updateCreateSource() {
@ -3520,13 +3527,19 @@ byId("template-import-form").addEventListener("submit", async (event) => {
showError("template-import-error", "请填写不超过 64 个字符的模板名称。");
return;
}
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 地址。");
const officialHosts = new Set([
"repo.almalinux.org",
"cloud.debian.org",
"cloud-images.ubuntu.com",
"cloud.centos.org",
]);
if (!existingJobId && (!url || url.protocol !== "https:" || !officialHosts.has(url.hostname)
|| (url.port && url.port !== "443") || url.username || url.password || url.search || url.hash)) {
showError("template-import-error", "请填写受支持发行版官方镜像站的 HTTPS 文件地址。");
return;
}
if (!existingJobId && !/^[a-f0-9]{64}$/.test(sha256)) {
showError("template-import-error", "请填写镜像发布方提供的 64 位 SHA-256 校验值。");
if (!existingJobId && sha256 && !/^[a-f0-9]{64}$/.test(sha256)) {
showError("template-import-error", "SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。");
return;
}
const button = byId("template-import-button");
@ -3534,12 +3547,14 @@ byId("template-import-form").addEventListener("submit", async (event) => {
try {
let jobId = existingJobId;
if (!jobId) {
const started = await api("/api/v1/vm-templates/import", { method: "POST", body: { name, url: url.href, sha256 } });
const body = { name, url: url.href };
if (sha256) body.sha256 = sha256;
const started = await api("/api/v1/vm-templates/import", { method: "POST", body });
jobId = String(started?.job_id || "");
if (!jobId) throw new Error("面板未返回模板导入任务编号,请刷新模板列表确认结果。");
state.templateImportJobId = jobId;
}
showTemplateImportStatus("宿主机正在后台下载并校验云镜像。离开页面不会取消任务,请稍候。");
showTemplateImportStatus("宿主机正在后台下载并检查云镜像。离开页面不会取消任务,请稍候。");
const completed = await waitForTemplateImport(jobId);
state.templateImportJobId = null;
showTemplateImportStatus("");

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

@ -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=rescue-iso-pool-1" />
<script type="module" src="/static/app.js?v=rescue-iso-pool-1"></script>
<link rel="stylesheet" href="/static/styles.css?v=root-password-policy-1" />
<script type="module" src="/static/app.js?v=root-password-policy-1"></script>
</head>
<body>
<div id="boot-screen" class="boot-screen" role="status" aria-live="polite">
@ -320,7 +320,7 @@
</div>
<div class="form-grid vm-cloud-auth-fields">
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="创建虚拟机时选择 SSH 公钥"></div><small>只显示你在“公钥管理”中添加的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><button id="vm-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></div>
<div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="vm-root-password-hint" placeholder="可自行设置,留空时自动生成强密码" disabled /><small id="vm-root-password-hint" aria-live="polite">留空时自动生成强密码,即使选择了 SSH 公钥;自行设置需至少 12 个字符,包含大写字母、小写字母和符号。</small></div>
<div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="128" autocomplete="new-password" spellcheck="false" aria-describedby="vm-root-password-hint" placeholder="可自行设置,留空时自动生成强密码" disabled /><small id="vm-root-password-hint" aria-live="polite">留空时生成 32 位完全随机密码,即使选择了 SSH 公钥;自行设置需为 12–128 位不含空格的英文可打印字符,包含大写字母、小写字母、数字和符号。</small></div>
</div>
</div>
</div><div id="create-iso-tip" class="form-tip"><span aria-hidden="true">ⓘ</span><p>创建后会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。</p></div><div id="create-cloud-tip" class="form-tip" hidden><span aria-hidden="true">ⓘ</span><p>云镜像首次启动由 cloud-init 写入静态 IP、DNS 和 root 登录凭据,无需 VNC 安装。可同时使用已保存的 SSH 公钥和 root 密码;密码留空时,即使选择了公钥也会自动生成强密码。初始密码可在虚拟机详情页查看。</p></div><p id="create-error" class="form-error" role="alert" hidden></p></div>
@ -338,7 +338,7 @@
<div class="form-grid">
<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" id="reinstall-root-password-field"><label for="reinstall-root-password">初始 root 密码(可选)</label><input id="reinstall-root-password" name="root_password" type="password" maxlength="128" autocomplete="new-password" spellcheck="false" aria-describedby="reinstall-root-password-hint" placeholder="可自行设置,留空时按公钥选择决定" /><small id="reinstall-root-password-hint" aria-live="polite">不选公钥且留空时生成 32 位完全随机密码;自行设置需为 12–128 位不含空格的英文可打印字符,包含大写字母、小写字母、数字和符号。</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>
</div>
</div>
@ -391,11 +391,11 @@
<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>
<div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="template-import-title">导入云镜像</h2><p>从受支持发行版的官方镜像站下载;可选择使用发布方 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>
<label for="template-url">云镜像下载地址</label><input id="template-url" type="url" inputmode="url" maxlength="2048" required autocomplete="off" placeholder="粘贴官方云镜像完整 HTTPS 文件地址" /><small class="template-field-help">支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10 和 Ubuntu 20.04/22.04/24.04/25.04/25.10/26.04 官方 x86_64 云镜像;Ubuntu 官方 qcow2 内容的 .img 文件也可导入。</small>
<label for="template-sha256">镜像 SHA-256 校验值(可选)</label><input id="template-sha256" type="text" maxlength="64" spellcheck="false" autocomplete="off" placeholder="可留空;填写时必须为 64 位十六进制" /><small class="template-field-help">留空时面板仍会计算并保存实际 SHA-256;填写后会在导入前核对。</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>

@ -139,7 +139,7 @@ tbody tr:hover{background:#fcfefe}
.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)}
.modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:26px 29px 18px;border-bottom:1px solid #edf1f5}.modal-header h2{font-size:21px;letter-spacing:-.35px;margin:7px 0 5px}.modal-header p{font-size:12px;color:#95a1af;margin:0}.icon-button{border:0;border-radius:8px;background:transparent;color:#8a98a8;width:31px;height:31px;font-size:23px;line-height:1;display:flex;align-items:center;justify-content:center}.icon-button:hover{background:#f1f5f8;color:#30445a}
.modal-body{padding:23px 29px 25px}.modal-footer{display:flex;justify-content:flex-end;gap:9px;padding:18px 29px;border-top:1px solid #edf1f5}
.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}
.workspace-form-page{width:min(100%,900px);margin:0 auto 48px}#create-view.workspace-form-page,#reinstall-view.workspace-form-page{width:100%;margin-left:0;margin-right:0}.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-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-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[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}

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

File diff suppressed because it is too large Load Diff

@ -0,0 +1,496 @@
"""Cloud-init public networking and NoCloud seed behavior."""
from __future__ import annotations
import importlib.util
import json
import uuid
import pytest
from virsh_panel.cloud_init import (
ROOT_PASSWORD_ALPHABET, ROOT_PASSWORD_DIGITS, ROOT_PASSWORD_LENGTH,
ROOT_PASSWORD_LOWERCASE, ROOT_PASSWORD_SYMBOLS, ROOT_PASSWORD_UPPERCASE,
_build_seed_iso, _enable_network_updates, build_seed_iso,
generate_root_password,
hash_root_password,
read_seed_network, replace_seed_network, replace_seed_settings,
validate_cloud_network, validate_guest_hostname,
)
PUBLIC_KEY = (
"ssh-ed25519 "
"AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 "
"panel-test"
)
GUEST_PASSWORD = "A-strong-guest-password-2026"
def _user_data(seed: bytes) -> dict:
"""Read the single-line JSON cloud-config embedded in the generated ISO."""
prefix = b"#cloud-config\n"
start = seed.index(prefix) + len(prefix)
return json.loads(seed[start:seed.index(b"\n", start)])
def _meta_data(seed: bytes) -> dict:
"""Read the single-line JSON meta-data embedded in the generated ISO."""
prefix = b'{"instance-id":'
start = seed.index(prefix)
return json.loads(seed[start:seed.index(b"\n", start)])
def _network_data(seed: bytes) -> dict:
"""Read the single-line JSON network-config embedded in the ISO."""
prefix = b'{"version": 2, "ethernets":'
start = seed.index(prefix)
return json.loads(seed[start:seed.index(b"\n", start)])
@pytest.mark.parametrize(
("address", "gateway"),
[
("8.8.8.18/24", "8.8.8.1"),
("8.8.8.18/28", "8.8.8.17"),
("123.123.123.114/24", "123.123.123.113"),
],
)
def test_public_network_accepts_24_and_28(address, gateway):
validated = validate_cloud_network(
address, gateway, ["1.1.1.1", "8.8.8.8"], PUBLIC_KEY,
)
assert validated == {
"public_ip_cidr": address,
"gateway": gateway,
"dns_servers": ["1.1.1.1", "8.8.8.8"],
"guest_ssh_public_key": PUBLIC_KEY,
}
def test_cloud_login_accepts_key_and_root_password_together():
network = ("8.8.8.18/24", "8.8.8.1", ["1.1.1.1"])
password_hash = hash_root_password(GUEST_PASSWORD)
assert password_hash.startswith("$6$")
assert GUEST_PASSWORD not in password_hash
assert hash_root_password(GUEST_PASSWORD) != password_hash
validated = validate_cloud_network(
*network, "", root_password_hash=password_hash,
)
assert validated["root_password_hash"] == password_hash
assert not validated["guest_ssh_public_key"]
together = validate_cloud_network(
*network, PUBLIC_KEY, root_password_hash=password_hash,
)
assert together["guest_ssh_public_key"] == PUBLIC_KEY
assert together["root_password_hash"] == password_hash
with pytest.raises(ValueError):
validate_cloud_network(*network, "", root_password_hash=None)
with pytest.raises(ValueError):
validate_cloud_network(*network, "", root_password_hash=GUEST_PASSWORD)
@pytest.mark.parametrize("invalid", [
"Short1!", "alllowercase12!", "ALLUPPERCASE12!", "NoSymbolPassword12",
"NoDigitsLong!Aa", "A-lowercase password12!", "A-lowercase\npassword12!",
"A-lowercase-password-1" + "x" * 110, "ValidAscii1!含中文",
])
def test_manual_root_password_requires_ascii_and_all_character_classes(invalid):
with pytest.raises(ValueError, match="初始 root 密码"):
hash_root_password(invalid)
@pytest.mark.parametrize("value", [
"node-1", "node.example.com", "A-Node.Example",
])
def test_guest_hostname_is_canonical_and_bounded(value):
assert validate_guest_hostname(value) == value.lower()
@pytest.mark.parametrize("value", [
"", ".node", "node.", "node..example", "-node", "node-",
"node_name", "node with spaces", "节点", "a" * 64,
])
def test_guest_hostname_rejects_unsafe_values(value):
with pytest.raises(ValueError):
validate_guest_hostname(value)
def test_generated_root_password_always_meets_policy():
assert ROOT_PASSWORD_ALPHABET == (
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
"0123456789!@#$%*-_=+?"
)
samples = set()
for _ in range(50):
password = generate_root_password()
samples.add(password)
assert len(password) == ROOT_PASSWORD_LENGTH
assert set(password) <= set(ROOT_PASSWORD_ALPHABET)
assert any(char in ROOT_PASSWORD_UPPERCASE for char in password)
assert any(char in ROOT_PASSWORD_LOWERCASE for char in password)
assert any(char in ROOT_PASSWORD_DIGITS for char in password)
assert any(char in ROOT_PASSWORD_SYMBOLS for char in password)
assert len(samples) == 50
assert len({password[:4] for password in samples}) > 1
assert hash_root_password(password).startswith("$6$")
def test_generated_root_password_rejects_whole_noncompliant_candidate(monkeypatch):
# First candidate is 32 uppercase A characters and must be discarded.
# The second one is a known compliant candidate with no post-processing.
indexes = iter([0] * 32 + [0, 26, 52, 62] * 8)
bounds = []
def deterministic_randbelow(bound):
bounds.append(bound)
return next(indexes)
monkeypatch.setattr("virsh_panel.cloud_init.secrets.randbelow",
deterministic_randbelow)
assert generate_root_password() == "Aa0!" * 8
assert bounds == [len(ROOT_PASSWORD_ALPHABET)] * 64
@pytest.mark.parametrize(
("address", "gateway"),
[
("192.168.1.18/24", "192.168.1.1"),
("10.0.0.18/24", "10.0.0.1"),
("172.16.0.18/24", "172.16.0.1"),
("127.0.0.18/24", "127.0.0.1"),
("169.254.0.18/24", "169.254.0.1"),
("224.0.0.18/24", "224.0.0.1"),
("2001:4860:4860::8888/64", "2001:4860:4860::1"),
("8.8.8.0/24", "8.8.8.1"),
("8.8.8.255/24", "8.8.8.1"),
("8.8.8.18/28", "8.8.8.1"),
("8.8.8.18", "8.8.8.1"),
],
)
def test_public_network_rejects_nonpublic_or_unroutable_pairs(address, gateway):
with pytest.raises(ValueError):
validate_cloud_network(address, gateway, ["1.1.1.1"], PUBLIC_KEY)
@pytest.mark.parametrize(
("dns", "key"),
[
(["not-an-ip"], PUBLIC_KEY),
(["192.168.1.1"], PUBLIC_KEY),
([], PUBLIC_KEY),
(["1.1.1.1"], "not-an-ssh-key"),
(["1.1.1.1"], PUBLIC_KEY + "\nruncmd: [evil]"),
],
)
def test_public_network_rejects_bad_dns_and_ssh_key(dns, key):
with pytest.raises(ValueError):
validate_cloud_network("8.8.8.18/24", "8.8.8.1", dns, key)
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_seed_iso_has_nocloud_files_and_mac_specific_static_network():
vm_uuid = str(uuid.uuid4())
mac = "52:54:00:12:34:56"
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
)
seed = build_seed_iso(vm_uuid, "cloud-vm", mac, validated)
assert isinstance(seed, bytes)
assert seed[32769:32774] == b"CD001" # ISO-9660 primary volume descriptor
assert b"CIDATA" in seed
for marker in (
b"user-data", b"meta-data", b"network-config", b"8.8.8.18/28",
b"8.8.8.17", b"1.1.1.1", mac.encode(), PUBLIC_KEY.encode(),
):
assert marker in seed
assert b'"routes": [{"to": "0.0.0.0/0", "via": "8.8.8.17"}]' in seed
assert b'"to": "default"' not in seed
assert b'"renderer": "networkd"' not in seed
assert b'"set-name"' not in seed
assert b"IPv6AcceptRA=no" not in seed
assert b"systemd-machine-id-setup" not in seed
user_data = _user_data(seed)
metadata = _meta_data(seed)
assert user_data["disable_root"] is False
assert user_data["ssh_pwauth"] is False
assert user_data["updates"] == {"network": {"when": ["boot"]}}
assert metadata["virt-cloud-network-policy"] == "boot-v1"
assert user_data["users"][0]["name"] == "root"
assert user_data["users"][0]["ssh_authorized_keys"] == [PUBLIC_KEY]
assert "hashed_passwd" not in user_data["users"][0]
assert "passwd" not in user_data["users"][0]
sshd_dropin = user_data["write_files"][0]
assert sshd_dropin["path"] == "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf"
assert "PermitRootLogin prohibit-password" in sshd_dropin["content"]
assert "PasswordAuthentication no" in sshd_dropin["content"]
assert "runcmd" not in user_data
assert "bootcmd" not in user_data
assert "dsmode" not in metadata
assert all(
item["path"] != "/etc/systemd/network/05-virt-cloud-public.network"
for item in user_data["write_files"]
)
assert b"almalinux" not in seed
assert read_seed_network(seed) == {
"public_ip_cidr": "8.8.8.18/28",
"gateway": "8.8.8.17",
"dns_servers": ["1.1.1.1"],
"mac": mac,
}
def test_enable_network_updates_upgrades_legacy_panel_user_data():
legacy = b'#cloud-config\n{"users": [{"name": "root"}]}\n'
upgraded = _enable_network_updates(legacy)
assert upgraded.startswith(b"#cloud-config\n")
payload = json.loads(upgraded.split(b"\n", 1)[1])
assert payload["users"] == [{"name": "root"}]
assert payload["updates"] == {"network": {"when": ["boot"]}}
assert _enable_network_updates(upgraded) == upgraded
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_debian12_network_fix_uses_standard_nocloud_network_config():
mac = "52:54:00:12:34:56"
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1", "8.8.8.8"], PUBLIC_KEY,
)
seed = build_seed_iso(
str(uuid.uuid4()), "debian-12-vm", mac, validated,
debian12_network_fix=True,
)
user_data = _user_data(seed)
metadata = _meta_data(seed)
network_data = _network_data(seed)
assert network_data == {
"version": 2,
"ethernets": {
"public0": {
"match": {"macaddress": mac},
"dhcp4": False,
"dhcp6": False,
"addresses": ["8.8.8.18/28"],
"routes": [{"to": "0.0.0.0/0", "via": "8.8.8.17"}],
"nameservers": {"addresses": ["1.1.1.1", "8.8.8.8"]},
"accept-ra": False,
},
},
"renderer": "networkd",
}
assert metadata["dsmode"] == "local"
bootcmd = user_data["bootcmd"]
assert bootcmd[0][:2] == ["/bin/sh", "-ec"]
queue_networkd = bootcmd[0][2]
assert queue_networkd.splitlines() == [
"systemd-machine-id-setup",
"netplan generate",
"systemctl unmask systemd-networkd.service",
"systemctl enable systemd-networkd.service",
"systemctl start --no-block systemd-networkd.service",
]
assert "ip address" not in queue_networkd
assert "ip route" not in queue_networkd
assert "restart" not in json.dumps(bootcmd)
assert "--now" not in json.dumps(bootcmd)
assert "runcmd" not in user_data
assert b'"set-name"' not in seed
assert b"enp1s0" not in seed
assert all(
not item["path"].startswith("/etc/systemd/network/")
for item in user_data["write_files"]
)
assert read_seed_network(seed) == {
"public_ip_cidr": "8.8.8.18/28",
"gateway": "8.8.8.17",
"dns_servers": ["1.1.1.1", "8.8.8.8"],
"mac": mac,
}
@pytest.mark.parametrize("invalid", [None, 0, 1, "networkd"])
def test_seed_rejects_invalid_debian12_network_fix_option(invalid):
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
)
with pytest.raises(ValueError, match="Debian 12 网络修复选项"):
build_seed_iso(
str(uuid.uuid4()), "cloud-vm", "52:54:00:12:34:56", validated,
debian12_network_fix=invalid,
)
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_read_seed_network_rejects_invalid_iso_without_exposing_credentials():
with pytest.raises(ValueError):
read_seed_network(b"not an ISO")
with pytest.raises(ValueError):
read_seed_network(b"x" * (1024 * 1024 + 1))
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_password_seed_sets_root_hash_and_enables_ssh_password_login():
password_hash = hash_root_password(GUEST_PASSWORD)
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], "",
root_password_hash=password_hash,
)
seed = build_seed_iso(
str(uuid.uuid4()), "password-vm", "52:54:00:12:34:56", validated,
)
user_data = _user_data(seed)
assert user_data["disable_root"] is False
assert user_data["ssh_pwauth"] is True
assert user_data["users"][0]["name"] == "root"
assert user_data["users"][0]["lock_passwd"] is False
assert user_data["users"][0]["hashed_passwd"] == password_hash
assert "ssh_authorized_keys" not in user_data["users"][0]
assert user_data["chpasswd"] == {
"expire": False,
"users": [{"name": "root", "password": password_hash, "type": "hash"}],
}
sshd_dropin = user_data["write_files"][0]
assert sshd_dropin["path"] == "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf"
assert "PermitRootLogin yes" in sshd_dropin["content"]
assert "PasswordAuthentication yes" in sshd_dropin["content"]
assert GUEST_PASSWORD.encode() not in seed
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_seed_allows_root_password_and_ssh_key_together():
password_hash = hash_root_password(GUEST_PASSWORD)
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
root_password_hash=password_hash,
)
seed = build_seed_iso(
str(uuid.uuid4()), "both-vm", "52:54:00:12:34:56", validated,
)
user_data = _user_data(seed)
root = user_data["users"][0]
assert root["name"] == "root"
assert root["lock_passwd"] is False
assert root["ssh_authorized_keys"] == [PUBLIC_KEY]
assert root["hashed_passwd"] == password_hash
assert user_data["ssh_pwauth"] is True
assert user_data["chpasswd"]["users"][0]["password"] == password_hash
assert "PermitRootLogin yes" in user_data["write_files"][0]["content"]
assert "PasswordAuthentication yes" in user_data["write_files"][0]["content"]
assert GUEST_PASSWORD.encode() not in seed
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_replace_seed_network_preserves_user_data_and_metadata():
password_hash = hash_root_password(GUEST_PASSWORD)
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
root_password_hash=password_hash,
)
seed = build_seed_iso(
str(uuid.uuid4()), "network-change-vm", "52:54:00:12:34:56", validated,
)
import pycdlib
from io import BytesIO
def file_bytes(image: bytes, path: str) -> bytes:
iso = pycdlib.PyCdlib()
iso.open_fp(BytesIO(image))
output = BytesIO()
iso.get_file_from_iso_fp(output, rr_path=path)
iso.close()
return output.getvalue()
user_data = file_bytes(seed, "/user-data")
metadata = file_bytes(seed, "/meta-data")
original_metadata = json.loads(metadata)
changed = replace_seed_network(
seed, "8.8.8.19/28", "8.8.8.17", ["8.8.8.8"],
)
assert file_bytes(changed, "/user-data") == user_data
changed_metadata = json.loads(file_bytes(changed, "/meta-data"))
assert changed_metadata["instance-id"] == original_metadata["instance-id"]
assert changed_metadata["local-hostname"] == original_metadata["local-hostname"]
assert changed_metadata["virt-cloud-network-policy"] == "boot-v1"
assert read_seed_network(changed) == {
"public_ip_cidr": "8.8.8.19/28",
"gateway": "8.8.8.17",
"dns_servers": ["8.8.8.8"],
"mac": "52:54:00:12:34:56",
}
# A seed created before the network-refresh policy has no marker and must
# rotate its NoCloud generation once so cloud-init reloads the new files.
legacy_user_data = b'#cloud-config\n{"users": [{"name": "root"}]}\n'
legacy_metadata = json.dumps({
"instance-id": original_metadata["instance-id"],
"local-hostname": original_metadata["local-hostname"],
}).encode("ascii") + b"\n"
legacy_network = file_bytes(seed, "/network-config")
legacy_seed = _build_seed_iso((
("/USERDATA.;1", "user-data", "/user-data", legacy_user_data),
("/METADATA.;1", "meta-data", "/meta-data", legacy_metadata),
("/NETWORK.;1", "network-config", "/network-config", legacy_network),
))
migrated = replace_seed_network(
legacy_seed, "8.8.8.19/28", "8.8.8.17", ["8.8.8.8"],
)
migrated_metadata = json.loads(file_bytes(migrated, "/meta-data"))
assert migrated_metadata["instance-id"] != original_metadata["instance-id"]
assert migrated_metadata["instance-id"].startswith("virt-cloud-network-")
migrated_user_data = file_bytes(migrated, "/user-data")
assert json.loads(migrated_user_data.split(b"\n", 1)[1])["updates"] == {
"network": {"when": ["boot"]}
}
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_replace_seed_network_rejects_non_panel_seed():
with pytest.raises(ValueError, match="无法读取原 cloud-init 配置盘"):
replace_seed_network(
b"not-an-iso", "8.8.8.19/28", "8.8.8.17", ["8.8.8.8"],
)
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_replace_seed_settings_rotates_generation_without_exposing_password():
password_hash = hash_root_password(GUEST_PASSWORD)
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
root_password_hash=password_hash,
)
seed = build_seed_iso(
str(uuid.uuid4()), "settings-vm", "52:54:00:12:34:56", validated,
)
changed = replace_seed_settings(
seed, hostname="Node.Example", root_password_hash=hash_root_password(
"Another-strong-password-2026!"
), ssh_public_key=PUBLIC_KEY,
)
user_data = _user_data(changed)
root = user_data["users"][0]
assert root["ssh_authorized_keys"] == [PUBLIC_KEY]
assert root["lock_passwd"] is False
assert root["hashed_passwd"].startswith("$6$")
assert GUEST_PASSWORD.encode() not in changed
assert b"Another-strong-password-2026!" not in changed
assert user_data["ssh_pwauth"] is True
assert user_data["chpasswd"]["users"][0]["type"] == "hash"
assert _meta_data(changed)["local-hostname"] == "node.example"
assert _meta_data(changed)["instance-id"].startswith("virt-cloud-settings-")
assert read_seed_network(changed) == read_seed_network(seed)

@ -0,0 +1,750 @@
"""Global cloud-template catalog, source file and import job tests."""
from __future__ import annotations
import hashlib
import json
import os
import stat
import threading
import time
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from virsh_panel.cloud_template_runtime import (
CACHE_TOMBSTONE_KIND,
CATALOG_KIND,
IMPORT_JOB_KIND,
CloudTemplateRuntime,
GlobalCloudTemplateFiles,
GlobalCloudTemplateStore,
PERSISTENT_FREE_RESERVE_BYTES,
cloud_template_id_for,
)
from virsh_panel.cloud_templates import GIB, TemplateError, template_volume_name
ALMA_10_URL = (
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/"
"AlmaLinux-10-GenericCloud-latest.x86_64.qcow2"
)
ALMA_8_URL = (
"https://repo.almalinux.org/almalinux/8/cloud/x86_64/images/"
"AlmaLinux-8-GenericCloud-latest.x86_64.qcow2"
)
DEBIAN_12_URL = (
"https://cloud.debian.org/images/cloud/bookworm/latest/"
"debian-12-generic-amd64.qcow2"
)
UBUNTU_24_URL = (
"https://cloud-images.ubuntu.com/releases/24.04/release/"
"ubuntu-24.04-server-cloudimg-amd64.img"
)
CENTOS_STREAM_10_URL = (
"https://cloud.centos.org/centos/10-stream/x86_64/images/"
"CentOS-Stream-GenericCloud-10-latest.x86_64.qcow2"
)
class MemoryStore:
def __init__(self) -> None:
self.values: dict[tuple[str, str], str] = {}
self.lock = threading.RLock()
def list(self, kind: str) -> dict[str, str]:
with self.lock:
return {
key: value for (record_kind, key), value in self.values.items()
if record_kind == kind
}
def get(self, kind: str, key: str) -> str | None:
with self.lock:
return self.values.get((kind, key))
def set(self, kind: str, key: str, value: str) -> None:
with self.lock:
self.values[(kind, key)] = value
def insert(self, kind: str, key: str, value: str) -> bool:
with self.lock:
identity = (kind, key)
if identity in self.values:
return False
self.values[identity] = value
return True
def delete(self, kind: str, key: str) -> None:
with self.lock:
self.values.pop((kind, key), None)
class CommitThenRaiseCatalogStore(MemoryStore):
"""Simulate a committed INSERT whose acknowledgement is lost."""
def insert(self, kind: str, key: str, value: str) -> bool:
inserted = super().insert(kind, key, value)
if kind == CATALOG_KIND and inserted:
raise RuntimeError("catalog insert acknowledgement lost")
return inserted
class AmbiguousCatalogCommitStore(CommitThenRaiseCatalogStore):
"""Also fail the first catalog read after the ambiguous INSERT."""
def __init__(self) -> None:
super().__init__()
self.fail_next_catalog_read = False
def list(self, kind: str) -> dict[str, str]:
if kind == CATALOG_KIND and self.fail_next_catalog_read:
self.fail_next_catalog_read = False
raise RuntimeError("catalog read unavailable")
return super().list(kind)
def insert(self, kind: str, key: str, value: str) -> bool:
try:
return super().insert(kind, key, value)
except RuntimeError:
self.fail_next_catalog_read = True
raise
class LoseFirstCompletedJobWriteStore(MemoryStore):
"""Drop one terminal job update while retaining its running record."""
def __init__(self) -> None:
super().__init__()
self.lost_completed_write = False
def set(self, kind: str, key: str, value: str) -> None:
if kind == IMPORT_JOB_KIND:
job = json.loads(value)
if (job.get("status") == "completed"
and not self.lost_completed_write):
self.lost_completed_write = True
raise RuntimeError("completed job write acknowledgement lost")
super().set(kind, key, value)
def wait_for_job(runtime: CloudTemplateRuntime, job_id: str) -> dict:
for _ in range(200):
job = runtime.get_job(job_id)
if job["status"] in {"completed", "failed"}:
return job
time.sleep(0.01)
raise AssertionError("cloud template import did not finish")
def fake_download_bytes(payload: bytes):
digest = hashlib.sha256(payload).hexdigest()
def download(_url: str, expected_sha256: str, directory: Path, **_kwargs):
assert expected_sha256 in {"", digest}
source = Path(directory) / ".cloud-image-test.qcow2"
source.write_bytes(payload)
os.chmod(source, 0o600)
return source, 2 * GIB, digest
return digest, download
def record_for(payload: bytes, *, name: str = "AlmaLinux 10") -> dict:
digest = hashlib.sha256(payload).hexdigest()
template_id = cloud_template_id_for(digest, "10")
return {
"id": template_id,
"name": name,
"os_family": "AlmaLinux",
"os_version": "10",
"sha256": digest,
"volume_name": template_volume_name(template_id),
"virtual_size": 2 * GIB,
"image_bytes": len(payload),
"created_at": 1,
}
def test_stable_global_id_and_catalog_use_an_independent_record_kind():
digest = "a" * 64
first = cloud_template_id_for(digest, "10")
second = cloud_template_id_for(digest.upper(), "10")
assert first == second
assert first.startswith("alma10-")
assert template_volume_name(first).endswith(".qcow2")
store = MemoryStore()
catalog = GlobalCloudTemplateStore(store)
record = record_for(b"catalog-image")
catalog.add(record)
assert catalog.get(record["id"]) == record
assert list(store.list(CATALOG_KIND)) == [record["id"]]
assert store.list("template") == {}
@pytest.mark.parametrize(
"message",
[
"官方云镜像地址无法解析",
"官方云镜像地址解析结果无效",
"官方云镜像地址解析到非公网地址",
"无法连接官方云镜像下载地址",
"官方云镜像重定向目标不安全",
"官方云镜像重定向次数过多",
"官方云镜像下载服务器返回异常状态",
"官方云镜像下载响应格式无效",
"云镜像下载内容不完整",
],
)
def test_public_job_preserves_fixed_safe_download_errors(message):
job = {
"job_id": "safe-error",
"status": "failed",
"phase": "导入失败",
"created_at": 1,
"error": message,
}
assert CloudTemplateRuntime.public_job(job)["error"] == message
def test_import_publishes_private_source_and_restores_global_catalog(tmp_path):
store = MemoryStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"verified-global-cloud-image"
digest, downloader = fake_download_bytes(payload)
try:
with patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=downloader,
):
queued = runtime.queue_import(
ALMA_10_URL, "AlmaLinux 10", digest
)
job = wait_for_job(runtime, queued["job_id"])
assert job["status"] == "completed", job
template_id = job["template"]["id"]
assert template_id == cloud_template_id_for(digest, "10")
assert "volume_name" not in job["template"]
listed = runtime.list()
assert listed == [job["template"]]
assert "active_import_job" not in runtime.status()
root = tmp_path / "cloud-templates"
source = root / template_volume_name(template_id)
assert source.read_bytes() == payload
assert stat.S_IMODE(root.stat().st_mode) == 0o700
assert stat.S_IMODE(source.stat().st_mode) == 0o600
assert store.get(IMPORT_JOB_KIND, queued["job_id"]) is not None
# A new runtime reads the same host-independent catalog and verifies
# the persisted source from disk instead of trusting process memory.
restored = CloudTemplateRuntime(store, tmp_path)
try:
restored.restore_jobs()
assert restored.list() == listed
with restored.source(template_id) as (record, path):
assert record["sha256"] == digest
assert path == source
assert restored.in_use[template_id] == 1
assert template_id not in restored.in_use
finally:
restored.close()
finally:
runtime.close()
@pytest.mark.parametrize(
("url", "family", "version", "prefix"),
[
(ALMA_8_URL, "AlmaLinux", "8", "alma8-"),
(DEBIAN_12_URL, "Debian", "12", "debian12-"),
(UBUNTU_24_URL, "Ubuntu", "24.04", "ubuntu2404-"),
(CENTOS_STREAM_10_URL, "CentOS Stream", "10", "centosstream10-"),
],
)
def test_import_derives_family_version_and_safe_source_name(
tmp_path, url, family, version, prefix):
runtime = CloudTemplateRuntime(MemoryStore(), tmp_path)
payload = f"{family}-{version}-cloud-image".encode()
digest, downloader = fake_download_bytes(payload)
try:
with patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=downloader,
):
queued = runtime.queue_import(url, f"{family} {version}", digest)
job = wait_for_job(runtime, queued["job_id"])
assert job["status"] == "completed", job
template = job["template"]
assert template["id"].startswith(prefix)
assert template["os_family"] == family
assert template["os_version"] == version
internal = runtime.get(template["id"])
assert internal["volume_name"] == template_volume_name(template["id"])
assert (
tmp_path / "cloud-templates" / internal["volume_name"]
).read_bytes() == payload
finally:
runtime.close()
def test_available_bytes_preserves_panel_disk_reserve(tmp_path):
files = GlobalCloudTemplateFiles(tmp_path)
with patch(
"virsh_panel.cloud_template_runtime.shutil.disk_usage",
return_value=SimpleNamespace(
free=PERSISTENT_FREE_RESERVE_BYTES + 3 * 1024 * 1024
),
):
assert files.available_bytes() == 3 * 1024 * 1024
with patch(
"virsh_panel.cloud_template_runtime.shutil.disk_usage",
return_value=SimpleNamespace(free=PERSISTENT_FREE_RESERVE_BYTES - 1),
):
assert files.available_bytes() == 0
def test_import_rejects_before_queue_when_only_reserved_space_remains(tmp_path):
runtime = CloudTemplateRuntime(MemoryStore(), tmp_path)
try:
with patch.object(
runtime.files, "available_bytes", return_value=1024 * 1024 - 1
):
with pytest.raises(TemplateError, match="空间不足") as insufficient:
runtime.queue_import(ALMA_10_URL, "No Disk Space", "")
assert insufficient.value.status == 507
assert runtime.jobs == {}
assert runtime.pending == set()
finally:
runtime.close()
def test_import_passes_only_space_above_reserve_to_downloader(tmp_path):
runtime = CloudTemplateRuntime(MemoryStore(), tmp_path)
payload = b"bounded-global-cloud-image"
digest = hashlib.sha256(payload).hexdigest()
limits: list[int] = []
def bounded_download(_url: str, _expected: str, directory: Path, *,
max_bytes: int):
limits.append(max_bytes)
source = Path(directory) / ".cloud-image-bounded.qcow2"
source.write_bytes(payload)
os.chmod(source, 0o600)
return source, 2 * GIB, digest
try:
with patch.object(
runtime.files, "available_bytes",
side_effect=[3 * 1024 * 1024, 2 * 1024 * 1024],
), patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=bounded_download,
):
queued = runtime.queue_import(ALMA_10_URL, "Bounded", "")
job = wait_for_job(runtime, queued["job_id"])
assert job["status"] == "completed", job
assert limits == [2 * 1024 * 1024]
finally:
runtime.close()
def test_duplicate_digest_and_casefold_name_are_rejected_globally():
store = MemoryStore()
catalog = GlobalCloudTemplateStore(store)
first = record_for(b"first-image", name="AlmaLinux Gold")
catalog.add(first)
with pytest.raises(TemplateError, match="已经导入") as duplicate_digest:
catalog.add(first)
assert duplicate_digest.value.status == 409
second = record_for(b"second-image", name="almalinux gold")
with pytest.raises(TemplateError, match="同名") as duplicate_name:
catalog.add(second)
assert duplicate_name.value.status == 409
def test_rename_changes_only_display_name_and_keeps_source_identity(tmp_path):
store = MemoryStore()
catalog = GlobalCloudTemplateStore(store)
record = record_for(b"rename-image")
catalog.add(record)
updated = catalog.rename(record["id"], "AlmaLinux 10 Production")
assert updated["name"] == "AlmaLinux 10 Production"
for key in (
"id", "sha256", "volume_name", "virtual_size", "image_bytes",
"os_family", "os_version", "created_at",
):
assert updated[key] == record[key]
files = GlobalCloudTemplateFiles(tmp_path)
temporary = files.directory() / ".cloud-image-rename.qcow2"
temporary.write_bytes(b"rename-image")
os.chmod(temporary, 0o600)
source = files.publish(
temporary, record["id"], expected_size=len(b"rename-image")
)
assert source.name == record["volume_name"]
def test_delete_removes_global_catalog_source_and_verification_cache(tmp_path):
store = MemoryStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"delete-global-cloud-image"
record = record_for(payload)
runtime.catalog.add(record)
temporary = runtime.files.directory() / ".cloud-image-delete.qcow2"
temporary.write_bytes(payload)
os.chmod(temporary, 0o600)
source = runtime.files.publish(
temporary, record["id"], expected_size=len(payload)
)
runtime.verified_sources[record["id"]] = (1, 2, 3, 4, record["sha256"])
try:
runtime.delete(record["id"])
assert not source.exists()
assert store.get(CATALOG_KIND, record["id"]) is None
assert record["id"] not in runtime.verified_sources
with pytest.raises(TemplateError) as missing:
runtime.get(record["id"])
assert missing.value.status == 404
finally:
runtime.close()
def test_delete_rejects_import_or_active_source_lease(tmp_path):
runtime = CloudTemplateRuntime(MemoryStore(), tmp_path)
payload = b"leased-global-cloud-image"
record = record_for(payload)
runtime.catalog.add(record)
temporary = runtime.files.directory() / ".cloud-image-leased.qcow2"
temporary.write_bytes(payload)
os.chmod(temporary, 0o600)
source = runtime.files.publish(
temporary, record["id"], expected_size=len(payload)
)
try:
runtime.pending.add("active-import")
with pytest.raises(TemplateError, match="正在导入") as importing:
runtime.delete(record["id"])
assert importing.value.status == 409
runtime.pending.clear()
with runtime.source(record["id"]):
with pytest.raises(TemplateError, match="正在同步") as leased:
runtime.delete(record["id"])
assert leased.value.status == 409
assert source.exists()
assert runtime.get(record["id"])["id"] == record["id"]
finally:
runtime.close()
def test_reimport_waits_for_old_host_cache_gc_then_reuses_stable_id(tmp_path):
store = MemoryStore()
runtime = CloudTemplateRuntime(store, tmp_path)
record = record_for(b"reimport-identical-image")
tombstone = {
"deletion_id": "a" * 32,
"template_id": record["id"],
"template_created_at": record["created_at"],
"source_volume_name": record["volume_name"],
"pending_hosts": ["offline-host"],
"source_deleted": True,
"created_at": 1,
}
store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone))
try:
with pytest.raises(TemplateError, match="缓存仍在清理") as pending:
runtime._prepare_reimport(record["id"])
assert pending.value.status == 409
assert store.get(CACHE_TOMBSTONE_KIND, record["id"]) is not None
tombstone["pending_hosts"] = []
store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone))
previous_created_at = runtime._prepare_reimport(record["id"])
assert store.get(CACHE_TOMBSTONE_KIND, record["id"]) is None
assert previous_created_at == record["created_at"]
first_generation = runtime._next_generation(
record["id"], previous_created_at)
second_generation = runtime._next_generation(record["id"])
assert second_generation > first_generation > previous_created_at
finally:
runtime.close()
def test_restore_cancels_provisional_delete_when_source_and_catalog_survive(
tmp_path):
store = MemoryStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"delete-never-committed"
record = record_for(payload)
runtime.catalog.add(record)
temporary = runtime.files.directory() / ".cloud-image-delete-intact.qcow2"
temporary.write_bytes(payload)
os.chmod(temporary, 0o600)
source = runtime.files.publish(
temporary, record["id"], expected_size=len(payload)
)
tombstone = {
"deletion_id": "c" * 32,
"template_id": record["id"],
"template_created_at": record["created_at"],
"source_volume_name": record["volume_name"],
"pending_hosts": ["host-one"],
"source_deleted": False,
"created_at": 1,
}
store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone))
try:
runtime.restore_jobs()
assert runtime.get(record["id"])["id"] == record["id"]
assert source.is_file()
assert store.get(CACHE_TOMBSTONE_KIND, record["id"]) is None
finally:
runtime.close()
def test_restore_finishes_delete_after_source_unlink_crash_window(tmp_path):
store = MemoryStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"delete-unlink-committed"
record = record_for(payload)
runtime.catalog.add(record)
tombstone = {
"deletion_id": "d" * 32,
"template_id": record["id"],
"template_created_at": record["created_at"],
"source_volume_name": record["volume_name"],
"pending_hosts": ["host-one"],
"source_deleted": False,
"created_at": 1,
}
store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone))
try:
# Listing is observational. Only delete recovery/maintenance may
# advance the durable tombstone and remove local source/catalog data.
assert [row["id"] for row in runtime.list()] == [record["id"]]
before = json.loads(store.get(CACHE_TOMBSTONE_KIND, record["id"]))
assert before["source_deleted"] is False
assert runtime.get(record["id"])["id"] == record["id"]
runtime.restore_jobs()
with pytest.raises(TemplateError) as missing:
runtime.get(record["id"])
assert missing.value.status == 404
restored = json.loads(store.get(
CACHE_TOMBSTONE_KIND, record["id"]
))
assert restored["source_deleted"] is True
assert restored["pending_hosts"] == ["host-one"]
finally:
runtime.close()
def test_source_rejects_permission_damage_and_content_tampering(tmp_path):
store = MemoryStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"source-integrity"
record = record_for(payload)
runtime.catalog.add(record)
temporary = runtime.files.directory() / ".cloud-image-integrity.qcow2"
temporary.write_bytes(payload)
os.chmod(temporary, 0o600)
source = runtime.files.publish(
temporary, record["id"], expected_size=len(payload)
)
try:
os.chmod(source, 0o640)
with pytest.raises(TemplateError, match="已损坏"):
with runtime.source(record["id"]):
pass
os.chmod(source, 0o600)
source.write_bytes(b"x" * len(payload))
with pytest.raises(TemplateError, match="SHA-256"):
with runtime.source(record["id"]):
pass
finally:
runtime.close()
def test_concurrent_import_is_serialized_and_second_request_is_rejected(tmp_path):
runtime = CloudTemplateRuntime(MemoryStore(), tmp_path)
started = threading.Event()
release = threading.Event()
payload = b"blocking-image"
digest = hashlib.sha256(payload).hexdigest()
def blocking_download(_url: str, _expected: str, directory: Path,
**_kwargs):
started.set()
assert release.wait(timeout=5)
source = Path(directory) / ".cloud-image-blocking.qcow2"
source.write_bytes(payload)
os.chmod(source, 0o600)
return source, 2 * GIB, digest
try:
with patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=blocking_download,
):
first = runtime.queue_import(ALMA_10_URL, "First", "")
assert started.wait(timeout=2)
assert runtime.has_active_jobs() is True
with pytest.raises(TemplateError, match="正在导入") as busy:
runtime.queue_import(ALMA_10_URL, "Second", "")
assert busy.value.status == 409
release.set()
assert wait_for_job(runtime, first["job_id"])["status"] == "completed"
assert runtime.has_active_jobs() is False
finally:
release.set()
runtime.close()
def test_restore_marks_interrupted_job_failed_and_removes_partial_files(tmp_path):
store = MemoryStore()
job_id = "interrupted-cloud-template"
store.set(IMPORT_JOB_KIND, job_id, json.dumps({
"job_id": job_id,
"status": "running",
"phase": "正在下载并校验云镜像",
"created_at": 1,
}))
files = GlobalCloudTemplateFiles(tmp_path)
partial = files.directory() / ".cloud-image-abandoned.qcow2"
partial.write_bytes(b"partial")
os.chmod(partial, 0o600)
runtime = CloudTemplateRuntime(store, tmp_path)
try:
runtime.restore_jobs()
job = runtime.get_job(job_id)
assert job["status"] == "failed"
assert "重启" in job["phase"]
assert "重启" in job["error"]
assert not partial.exists()
assert runtime.has_active_jobs() is False
finally:
runtime.close()
def test_import_failure_redacts_internal_paths_and_releases_pending(tmp_path):
runtime = CloudTemplateRuntime(MemoryStore(), tmp_path)
try:
with patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=TemplateError(
"私有目录 /home/virt-cloud/data/cloud-templates 损坏", 500
),
):
queued = runtime.queue_import(ALMA_10_URL, "Broken", "")
failed = wait_for_job(runtime, queued["job_id"])
assert failed["status"] == "failed"
assert failed["error"] == "云镜像下载或保存失败,请联系管理员查看日志"
assert "/home/" not in json.dumps(failed, ensure_ascii=False)
assert runtime.pending == set()
finally:
runtime.close()
def test_catalog_insert_commit_with_lost_ack_is_completed_not_rolled_back(
tmp_path):
store = CommitThenRaiseCatalogStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"catalog-commit-ack-lost"
digest, downloader = fake_download_bytes(payload)
try:
with patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=downloader,
):
queued = runtime.queue_import(ALMA_10_URL, "Committed", digest)
job = wait_for_job(runtime, queued["job_id"])
assert job["status"] == "completed"
template_id = cloud_template_id_for(digest, "10")
assert runtime.get(template_id)["sha256"] == digest
source = tmp_path / "cloud-templates" / template_volume_name(template_id)
assert source.read_bytes() == payload
finally:
runtime.close()
def test_ambiguous_catalog_commit_preserves_source_for_startup_recovery(
tmp_path):
store = AmbiguousCatalogCommitStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"ambiguous-catalog-commit"
digest, downloader = fake_download_bytes(payload)
try:
with patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=downloader,
):
queued = runtime.queue_import(ALMA_10_URL, "Ambiguous", digest)
failed = wait_for_job(runtime, queued["job_id"])
assert failed["status"] == "failed"
template_id = cloud_template_id_for(digest, "10")
source = tmp_path / "cloud-templates" / template_volume_name(template_id)
assert source.read_bytes() == payload
finally:
runtime.close()
restored = CloudTemplateRuntime(store, tmp_path)
try:
restored.restore_jobs()
recovered = restored.get_job(queued["job_id"])
assert recovered["status"] == "completed"
assert recovered["template"]["id"] == template_id
assert source.read_bytes() == payload
finally:
restored.close()
def test_lost_completed_job_write_is_success_in_memory_and_repaired_on_restart(
tmp_path):
store = LoseFirstCompletedJobWriteStore()
runtime = CloudTemplateRuntime(store, tmp_path)
payload = b"lost-completed-job-write"
digest, downloader = fake_download_bytes(payload)
try:
with patch(
"virsh_panel.cloud_template_runtime.download_verified_image",
side_effect=downloader,
):
queued = runtime.queue_import(ALMA_10_URL, "Recoverable", digest)
completed = wait_for_job(runtime, queued["job_id"])
assert completed["status"] == "completed"
persisted = json.loads(store.get(IMPORT_JOB_KIND, queued["job_id"]))
assert persisted["status"] == "running"
assert persisted["candidate_template_id"] == cloud_template_id_for(
digest, "10"
)
finally:
runtime.close()
restored = CloudTemplateRuntime(store, tmp_path)
try:
restored.restore_jobs()
repaired = restored.get_job(queued["job_id"])
assert repaired["status"] == "completed"
persisted = json.loads(store.get(IMPORT_JOB_KIND, queued["job_id"]))
assert persisted["status"] == "completed"
finally:
restored.close()

@ -0,0 +1,502 @@
"""Official-image import restrictions and private template catalog tests."""
from __future__ import annotations
import hashlib
import io
import socket
import stat
import struct
from types import SimpleNamespace
from unittest.mock import patch
from urllib.parse import urlsplit
import pytest
from virsh_panel.cloud_templates import (
TemplateError,
TemplateStore,
_RejectRedirects,
_open_image_response,
_redirect_target,
_resolve_global_addresses,
download_verified_image,
image_metadata_for,
image_version_for,
template_id_for,
template_scope,
template_volume_name,
validate_image_url,
verify_qcow2_image,
)
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"
)
OFFICIAL_8 = (
"https://repo.almalinux.org/almalinux/8/cloud/x86_64/images/"
"AlmaLinux-8-GenericCloud-latest.x86_64.qcow2"
)
DEBIAN_12 = (
"https://cloud.debian.org/images/cloud/bookworm/latest/"
"debian-12-generic-amd64.qcow2"
)
DEBIAN_13_BUILD = (
"https://cloud.debian.org/images/cloud/trixie/20260801-2204/"
"debian-13-generic-amd64-20260801-2204.qcow2"
)
DEBIAN_12_GENERICCLOUD = (
"https://cloud.debian.org/images/cloud/bookworm/latest/"
"debian-12-genericcloud-amd64.qcow2"
)
UBUNTU_24 = (
"https://cloud-images.ubuntu.com/releases/noble/release/"
"ubuntu-24.04-server-cloudimg-amd64.img"
)
UBUNTU_26_CURRENT = (
"https://cloud-images.ubuntu.com/resolute/current/"
"resolute-server-cloudimg-amd64.img"
)
CENTOS_STREAM_9 = (
"https://cloud.centos.org/centos/9-stream/x86_64/images/"
"CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2"
)
CENTOS_STREAM_10 = (
"https://cloud.centos.org/centos/10-stream/x86_64/images/"
"CentOS-Stream-GenericCloud-x86_64-10-20260810.0.x86_64.qcow2"
)
class FakeHeaders:
def __init__(self, values=None):
self.values = values or {}
def get_all(self, name, default=None):
return self.values.get(name, default)
class FakeImageResponse(io.BytesIO):
def __init__(self, body=b"", *, status=200, headers=None):
super().__init__(body)
self.status = status
self.header_values = headers or {}
self.headers = FakeHeaders(self.header_values)
def getheader(self, name, default=None):
values = self.header_values.get(name)
if not values:
return default
return values[0]
def fake_image_response(body: bytes):
return (
SimpleNamespace(close=lambda: None),
FakeImageResponse(
body,
headers={"Content-Length": [str(len(body))]},
),
)
def test_official_almalinux_8_9_and_10_are_distinct_supported_versions():
assert validate_image_url(OFFICIAL_8) == OFFICIAL_8
assert validate_image_url(OFFICIAL_9) == OFFICIAL_9
assert image_metadata_for(OFFICIAL_8) == ("AlmaLinux", "8")
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, "8").startswith("alma8-")
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, "7")
@pytest.mark.parametrize(
("url", "family", "version", "prefix"),
[
(DEBIAN_12, "Debian", "12", "debian12-"),
(DEBIAN_12_GENERICCLOUD, "Debian", "12", "debian12-"),
(DEBIAN_13_BUILD, "Debian", "13", "debian13-"),
(UBUNTU_24, "Ubuntu", "24.04", "ubuntu2404-"),
(UBUNTU_26_CURRENT, "Ubuntu", "26.04", "ubuntu2604-"),
(CENTOS_STREAM_9, "CentOS Stream", "9", "centosstream9-"),
(CENTOS_STREAM_10, "CentOS Stream", "10", "centosstream10-"),
],
)
def test_supported_official_cloud_images_have_distinct_safe_identifiers(
url, family, version, prefix):
assert validate_image_url(url) == url
assert image_metadata_for(url) == (family, version)
template_id = template_id_for("a" * 64, "b" * 64, version, family)
assert template_id.startswith(prefix)
assert template_volume_name(template_id) == (
f"panel-template-{template_id}.qcow2"
)
def test_template_identifier_rejects_invalid_digest_precisely():
with pytest.raises(TemplateError, match="SHA-256 格式"):
template_id_for("a" * 64, "not-a-digest", "12", "Debian")
with pytest.raises(TemplateError, match="系统版本无效"):
template_id_for("a" * 64, "b" * 64, ["12"], "Debian")
def qcow2_fixture(virtual_size=2 * 1024**3) -> bytes:
header = bytearray(104)
header[:4] = b"QFI\xfb"
header[4:8] = struct.pack(">I", 3)
header[20:24] = struct.pack(">I", 16)
header[24:32] = struct.pack(">Q", virtual_size)
header[100:104] = struct.pack(">I", 104)
return bytes(header) + b"fake qcow2 content for controlled import test"
@pytest.mark.parametrize(
"url",
[
"http://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://repo.almalinux.org.evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://user:pass@repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/../../etc/passwd",
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2?token=secret",
"https://cloud.debian.org/images/cloud/bookworm/latest/debian-13-generic-amd64.qcow2",
"https://cloud.debian.org/images/cloud/bookworm/20260801-2204/debian-12-generic-amd64-20260802-2205.qcow2",
"https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-generic-arm64.qcow2",
"https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-22.04-server-cloudimg-amd64.img",
"https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-arm64.img",
"https://cloud.centos.org/centos/9-stream/x86_64/images/CentOS-Stream-GenericCloud-10-latest.x86_64.qcow2",
"https://cloud.centos.org/centos/9-stream/aarch64/images/CentOS-Stream-GenericCloud-9-latest.aarch64.qcow2",
],
)
def test_import_url_rejects_nonofficial_and_ambiguous_targets(url):
with pytest.raises(TemplateError):
validate_image_url(url)
def test_verified_image_is_private_and_has_expected_virtual_size(tmp_path):
body = qcow2_fixture()
digest = hashlib.sha256(body).hexdigest()
with patch("virsh_panel.cloud_templates._open_image_response",
return_value=fake_image_response(body)), patch(
"virsh_panel.cloud_templates._verify_qcow2_with_qemu"
) as checked:
downloaded, virtual_size, actual_sha256 = download_verified_image(
OFFICIAL, digest, tmp_path
)
try:
assert downloaded.read_bytes() == body
assert virtual_size == 2 * 1024**3
assert actual_sha256 == digest
assert stat.S_IMODE(downloaded.stat().st_mode) == 0o600
checked.assert_called_once_with(downloaded, 2 * 1024**3)
finally:
downloaded.unlink()
def test_image_without_expected_hash_records_computed_digest(tmp_path):
body = qcow2_fixture()
digest = hashlib.sha256(body).hexdigest()
with patch("virsh_panel.cloud_templates._open_image_response",
return_value=fake_image_response(body)), patch(
"virsh_panel.cloud_templates._verify_qcow2_with_qemu"
):
downloaded, virtual_size, actual_sha256 = download_verified_image(
OFFICIAL, "", tmp_path
)
try:
assert virtual_size == 2 * 1024**3
assert actual_sha256 == digest
finally:
downloaded.unlink()
def test_failed_hash_never_leaves_unverified_template_file(tmp_path):
body = qcow2_fixture()
with patch("virsh_panel.cloud_templates._open_image_response",
return_value=fake_image_response(body)):
with pytest.raises(TemplateError, match="SHA-256"):
download_verified_image(OFFICIAL, "0" * 64, tmp_path)
assert list(tmp_path.iterdir()) == []
def test_download_limit_preserves_persistent_disk_reserve(tmp_path):
body = qcow2_fixture()
digest = hashlib.sha256(body).hexdigest()
with patch("virsh_panel.cloud_templates._open_image_response",
return_value=fake_image_response(body)):
with pytest.raises(TemplateError, match="持久目录空间不足") as error:
download_verified_image(
OFFICIAL, digest, tmp_path, max_bytes=len(body) - 1
)
assert error.value.status == 507
assert list(tmp_path.iterdir()) == []
def test_redirect_to_nonofficial_target_is_rejected_before_following():
handler = _RejectRedirects()
with pytest.raises(TemplateError, match="重定向"):
handler.redirect_request(None, None, 302, "Found", {},
"http://127.0.0.1/private")
def test_debian_official_redirect_downloads_same_object_from_public_mirror(
tmp_path):
mirror = DEBIAN_12.replace(
"cloud.debian.org", "chuangtzu.ftp.acc.umu.se"
)
body = qcow2_fixture()
first = FakeImageResponse(
status=302, headers={"Location": [mirror]}
)
final = FakeImageResponse(
body,
status=200,
headers={"Content-Length": [str(len(body))]},
)
connections = [SimpleNamespace(close=lambda: None) for _ in range(2)]
with patch(
"virsh_panel.cloud_templates._resolve_global_addresses",
return_value=["2001:4860:4860::8888"],
), patch(
"virsh_panel.cloud_templates._open_pinned_response",
side_effect=[(connections[0], first), (connections[1], final)],
) as opened, patch(
"virsh_panel.cloud_templates._verify_qcow2_with_qemu"
):
downloaded, virtual_size, digest = download_verified_image(
DEBIAN_12, hashlib.sha256(body).hexdigest(), tmp_path
)
assert downloaded.read_bytes() == body
assert virtual_size == 2 * 1024**3
assert digest == hashlib.sha256(body).hexdigest()
assert opened.call_args_list[0].args[0].hostname == "cloud.debian.org"
assert opened.call_args_list[1].args[0].hostname == "chuangtzu.ftp.acc.umu.se"
assert opened.call_args_list[1].args[0].path == urlsplit(DEBIAN_12).path
downloaded.unlink()
def test_ubuntu_redirect_stays_on_official_host_and_same_release():
target = UBUNTU_24.replace(
"/releases/noble/release/", "/releases/24.04/release/"
)
first = FakeImageResponse(
status=302, headers={"Location": [UBUNTU_24]}
)
final = FakeImageResponse(b"image", status=200)
connections = [SimpleNamespace(close=lambda: None) for _ in range(2)]
with patch(
"virsh_panel.cloud_templates._resolve_global_addresses",
return_value=["8.8.8.8"],
), patch(
"virsh_panel.cloud_templates._open_pinned_response",
side_effect=[(connections[0], first), (connections[1], final)],
):
connection, response = _open_image_response(target)
assert connection is connections[1]
assert response is final
@pytest.mark.parametrize(
"target",
[
"http://127.0.0.1/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2",
"https://mirror.example/images/cloud/bookworm/latest/debian-13-generic-amd64.qcow2",
"https://user:password@mirror.example/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2",
],
)
def test_debian_redirect_rejects_unsafe_or_different_object(target):
with pytest.raises(TemplateError, match="重定向目标不安全"):
_redirect_target(
DEBIAN_12, DEBIAN_12, target, ("Debian", "12")
)
def test_ubuntu_redirect_rejects_other_host_or_release():
for target in (
UBUNTU_24.replace("cloud-images.ubuntu.com", "mirror.example"),
UBUNTU_24.replace("24.04", "22.04"),
):
with pytest.raises(TemplateError, match="重定向目标不安全"):
_redirect_target(
UBUNTU_24, UBUNTU_24, target, ("Ubuntu", "24.04")
)
def test_image_download_dns_rejects_any_nonpublic_answer():
rows = [
(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "",
("8.8.8.8", 443)),
(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "",
("127.0.0.1", 443)),
]
with patch("virsh_panel.cloud_templates.socket.getaddrinfo", return_value=rows):
with pytest.raises(TemplateError, match="非公网"):
_resolve_global_addresses("mirror.example")
def test_image_redirect_count_is_bounded():
def redirect_response(*_args):
connection = SimpleNamespace(close=lambda: None)
response = FakeImageResponse(
status=302, headers={"Location": [UBUNTU_24]}
)
return connection, response
with patch(
"virsh_panel.cloud_templates._resolve_global_addresses",
return_value=["8.8.8.8"],
), patch(
"virsh_panel.cloud_templates._open_pinned_response",
side_effect=redirect_response,
):
with pytest.raises(TemplateError, match="次数过多"):
_open_image_response(UBUNTU_24)
@pytest.mark.parametrize(
("response", "message"),
[
(FakeImageResponse(status=404), "异常状态"),
(FakeImageResponse(
qcow2_fixture(), headers={"Content-Encoding": ["gzip"]}
), "响应格式无效"),
(FakeImageResponse(
qcow2_fixture(),
headers={"Content-Length": [str(len(qcow2_fixture()) + 1)]},
), "内容不完整"),
],
)
def test_image_download_rejects_unsafe_or_incomplete_http_response(
tmp_path, response, message):
connection = SimpleNamespace(close=lambda: None)
with patch(
"virsh_panel.cloud_templates._open_image_response",
return_value=(connection, response),
):
with pytest.raises(TemplateError, match=message):
download_verified_image(OFFICIAL, "", tmp_path)
assert list(tmp_path.iterdir()) == []
def test_external_data_file_feature_is_rejected(tmp_path):
body = bytearray(qcow2_fixture())
body[72:80] = struct.pack(">Q", 4)
digest = hashlib.sha256(body).hexdigest()
with patch("virsh_panel.cloud_templates._open_image_response",
return_value=fake_image_response(body)):
with pytest.raises(TemplateError, match="外部依赖"):
download_verified_image(OFFICIAL, digest, tmp_path)
assert list(tmp_path.iterdir()) == []
def test_qcow2_full_integrity_check_rejects_corrupt_image(tmp_path):
image = tmp_path / "corrupt.qcow2"
image.write_bytes(qcow2_fixture())
info = [{"format": "qcow2", "virtual-size": 2 * 1024**3}]
with patch(
"virsh_panel.cloud_templates._qemu_img_json",
side_effect=[info, TemplateError("云镜像完整性检查失败", 422)],
) as inspect:
with pytest.raises(TemplateError, match="完整性检查"):
verify_qcow2_image(image)
assert inspect.call_count == 2
@pytest.mark.parametrize(
"info",
[
[{"format": "raw", "virtual-size": 2 * 1024**3}],
[{"format": "qcow2", "virtual-size": 2 * 1024**3,
"backing-filename": "/private/base.qcow2"}],
[{"format": "qcow2", "virtual-size": 2 * 1024**3,
"format-specific": {"data": {"data-file": "/private/data"}}}],
[{"format": "qcow2", "virtual-size": 2 * 1024**3},
{"format": "qcow2", "virtual-size": 2 * 1024**3}],
],
)
def test_qcow2_full_integrity_check_rejects_dependencies_and_wrong_format(
tmp_path, info):
image = tmp_path / "unsafe.qcow2"
image.write_bytes(qcow2_fixture())
with patch("virsh_panel.cloud_templates._qemu_img_json",
return_value=info) as inspect:
with pytest.raises(TemplateError, match="外部依赖"):
verify_qcow2_image(image)
inspect.assert_called_once()
def test_template_catalog_is_private_and_scoped_to_host_and_disk_pool(tmp_path):
data_dir = tmp_path / "data"
data_dir.mkdir(mode=0o700)
store = TemplateStore(data_dir)
profile = {
"host": "hypervisor.example", "port": 2222,
"fingerprint": "SHA256:fixture", "storage_pool": "/home/kvm",
}
scope = template_scope(profile)
other_scope = template_scope({**profile, "storage_pool": "/other/pool"})
record = {
"id": "alma10-example", "name": "AlmaLinux 10", "sha256": "a" * 64,
"volume_name": "alma10-cloud.qcow2", "virtual_size": 2 * 1024**3,
}
assert store.add(scope, record) == record
assert store.list(scope) == [record]
assert store.list(other_scope) == []
assert TemplateStore(data_dir).get(scope, record["id"]) == record
assert stat.S_IMODE(store.file.stat().st_mode) == 0o600
with pytest.raises(TemplateError):
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

@ -80,6 +80,10 @@ class MemoryUsers:
def owns_vm(self, host_scope, vm_id, user_id):
return self.store.get("test_vm_owner", f"{host_scope}:{vm_id}") == str(user_id)
def owner_of_vm(self, host_scope, vm_id):
value = self.store.get("test_vm_owner", f"{host_scope}:{vm_id}")
return None if value is None else int(value)
def assign_vm(self, host_scope, vm_id, user_id):
self.store.set("test_vm_owner", f"{host_scope}:{vm_id}", str(user_id))

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save