PANEL UPDATE网站更新
从当前项目的私有 Gitea 仓库检查并安装新版本。
diff --git a/static/styles.css b/static/styles.css
index bd19505b..92967844 100644
--- a/static/styles.css
+++ b/static/styles.css
@@ -111,18 +111,20 @@ input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,
.search-box input,.panel-tools select{height:37px;border:1px solid #e0e6ec;border-radius:8px;background:#fff;color:#516075;font-size:12px}
.search-box input{width:220px;padding:0 12px 0 34px}.search-box input::placeholder{color:#a4afbb}.panel-tools select{padding:0 29px 0 11px}
.table-scroll{overflow-x:auto;min-height:100px}
-table{border-collapse:collapse;width:100%;min-width:850px}
+table{border-collapse:collapse;width:100%;min-width:850px}.vm-table{min-width:1060px}.vm-table th,.vm-table td{padding-left:15px;padding-right:15px}
thead{background:#fbfcfe}th{height:47px;text-align:left;font-size:10px;letter-spacing:.05em;color:#9ba8b7;text-transform:uppercase;font-weight:800;padding:0 24px}
th.actions-heading{text-align:right;padding-right:28px}
td{height:83px;border-top:1px solid #edf1f5;padding:15px 24px;font-size:12px;color:#607087}
tbody tr:hover{background:#fcfefe}
.vm-identity{display:flex;align-items:center;gap:12px;min-width:160px}.vm-icon{width:38px;height:38px;border-radius:10px;background:#e9f8f8;color:#239eaa;display:flex;align-items:center;justify-content:center;font-size:19px;flex:none}.vm-name{display:block;color:#25384e;font-size:13px;font-weight:800;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-id{display:block;color:#a6b1bf;font-size:10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;margin-top:6px;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.vm-public-ip{display:block;color:#16868f;font-size:10px;font-weight:700;margin-top:5px;white-space:nowrap}
+.vm-name-link{display:block;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;padding:2px 0;color:#25384e;font-size:13px;font-weight:800;text-align:left;text-decoration:underline;text-decoration-color:transparent;text-underline-offset:3px;cursor:pointer}.vm-name-link:not(:disabled):hover,.vm-name-link:not(:disabled):focus-visible{color:#118e98;text-decoration-color:currentColor}.vm-metadata{display:block;max-width:205px;color:#53647a;line-height:1.5;overflow-wrap:anywhere}.vm-ip{color:#16868f;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;white-space:nowrap}
.state-pill{display:inline-flex;align-items:center;gap:7px;padding:6px 9px;border-radius:6px;font-size:11px;font-weight:800;background:#f1f3f6;color:#758499;white-space:nowrap}.state-pill:before{content:"";width:6px;height:6px;background:currentColor;border-radius:50%}.state-pill.running{background:#e7f8ef;color:#20a46f}.state-pill.stopped{background:#f2f4f7;color:#8290a3}.state-pill.other{background:#fff4e5;color:#b98129}
.vm-spec{color:#53647a;white-space:nowrap}.vm-spec strong{color:#283a50;font-weight:700}.vm-spec small{display:block;color:#a2aeb9;font-size:10px;margin-top:5px}
.row-actions{display:flex;align-items:center;justify-content:flex-end;gap:5px;white-space:nowrap}.row-button{border:1px solid transparent;background:transparent;color:#577083;border-radius:7px;padding:7px 8px;min-height:31px;font-size:11px;font-weight:700}.row-button:not(:disabled):hover{background:#e8f7f7;color:#117f88}.row-button.primary{background:#e7f7f7;color:#118e98}.row-button.danger{color:#bf6470}.row-button.danger:not(:disabled):hover{background:#fff0f1;color:#ba3a49}
.empty-state{text-align:center;padding:65px 20px 72px}.empty-icon{margin:0 auto 16px;width:54px;height:54px;display:flex;align-items:center;justify-content:center;border-radius:16px;background:#eaf7f7;color:#17a3aa;font-size:28px}.empty-state h3{font-size:16px;color:#34465a;margin:0 0 8px}.empty-state p{font-size:12px;color:#a0aebe;margin:0}
.footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px}
+.vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-uuid{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef}
.modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)}
.modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)}
.create-modal{width:min(100%,720px)}
@@ -146,8 +148,11 @@ tbody tr:hover{background:#fcfefe}
@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.host-settings-mobile{display:inline-flex}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}}
@media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}}
@media(max-width:960px){.update-grid{grid-template-columns:1fr}}
+@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}}
@media(max-width:740px){.login-layout{display:block;min-height:100vh}.login-art{display:none}.login-form-side{min-height:100vh;padding:32px 25px}.login-mobile-brand{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:800;margin-bottom:70px}.login-card h2{font-size:29px}.page-heading{align-items:flex-start;flex-direction:column;gap:20px}.heading-actions{width:100%}.heading-actions .button{flex:1}.overview-grid{gap:9px}.stat-card{min-height:121px;padding:16px}.stat-card>strong{font-size:25px}.stat-top{font-size:10px}.stat-icon{width:27px;height:27px;font-size:12px}.stat-card>small{font-size:9px}.panel-heading{align-items:flex-start;flex-direction:column;padding:19px}.panel-tools{width:100%}.search-box{flex:1}.search-box input{width:100%}.footer-note{text-align:left}.console-toolbar{align-items:flex-start}.console-tools{flex-wrap:wrap;justify-content:flex-end}.console-tools .button{font-size:10px}}
+@media(max-width:740px){.vm-table{min-width:0}.vm-table thead{display:none}.vm-table tbody{display:grid;gap:12px;padding:12px}.vm-table tr{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid #e4ebf0;border-radius:10px;overflow:hidden}.vm-table td{display:block;min-width:0;height:auto;border:0;padding:12px 14px}.vm-table td:first-child{grid-column:1/-1;border-bottom:1px solid #edf1f5}.vm-table td:not(:first-child):before{content:attr(data-label);display:block;color:#9ba8b7;font-size:10px;font-weight:800;margin-bottom:7px}.vm-table .vm-metadata{max-width:none}.vm-table .vm-ip{white-space:normal}.vm-detail-facts{padding:4px 17px 12px}.vm-detail-actions{padding:16px 19px 19px}}
@media(max-width:740px){.setup-layout{display:block}.setup-intro{min-height:0;padding:28px 25px}.setup-brand{margin:0 0 38px}.setup-intro h1{font-size:31px;margin:11px 0}.setup-intro p{font-size:12px;margin-bottom:24px}.setup-steps{margin-top:0}.setup-form-side{padding:36px 25px 55px}.setup-card h2{font-size:27px}.host-side-stack{grid-template-columns:1fr}.host-heading{align-items:flex-start;flex-direction:column}.host-topbar{height:65px}.host-content{padding-top:27px}.host-card{padding:20px}}
@media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}}
@media(max-width:510px){.topbar-right{flex-wrap:wrap;justify-content:flex-end;gap:2px}.host-settings-mobile{font-size:10px!important;padding:5px!important;min-height:28px!important}.topbar-user .avatar{display:none}.update-versions{grid-template-columns:1fr}}
@media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}}
+@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}}
diff --git a/tests/test_app.py b/tests/test_app.py
index 82cc651c..99749267 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import re
import stat
import sys
import threading
@@ -113,10 +114,10 @@ class FakeVMService:
return {**self.vm, "name": spec["name"]}
def reinstall_cloud_vm(self, vm_id, template_volume_name, *,
- ssh_public_key="", root_password_hash=None,
+ os_name=None, ssh_public_key="", root_password_hash=None,
progress=None):
self.calls.append(("reinstall_cloud_vm", vm_id, template_volume_name,
- ssh_public_key, root_password_hash))
+ ssh_public_key, root_password_hash, os_name))
self.reinstall_started.set()
if self.reinstall_gate is not None:
assert self.reinstall_gate.wait(timeout=5), "test did not release reinstall job"
@@ -183,6 +184,7 @@ class FakeRemoteManager:
"storage_pool": staged.profile.storage_pool,
"iso_pool": staged.profile.iso_pool,
"default_network": staged.profile.default_network,
+ "region": staged.profile.region,
"libvirt_uri": "qemu+ssh://root@vp-managed/system?no_tty=1&command=/fake/ssh-wrapper",
"ssh_target": "vp-managed", "ssh_config_file": "/fake/config",
"ssh_known_hosts_file": "/fake/known_hosts",
@@ -309,7 +311,7 @@ def configure_reinstall_case(web):
template_id = template_id_for(scope, "d" * 64)
volume_name = template_volume_name(template_id)
TemplateStore(state.data_dir).add(
- scope, {"id": template_id, "volume_name": volume_name},
+ scope, {"id": template_id, "volume_name": volume_name, "name": "AlmaLinux 10"},
)
service.vm.update({
"name": "cloud-vm", "managed": True, "public_ip_cidr": "8.8.8.18/24",
@@ -404,6 +406,21 @@ def test_host_scan_test_save_and_secret_is_never_returned(web):
("list_vms",), ("resources",)]
+def test_host_region_is_returned_with_host_and_vms(web):
+ client, _, token, _service, _manager, _ = web
+ csrf = setup_admin(client, token)
+ body = {**HOST_BODY, "region": "中国香港"}
+ headers = {"X-CSRF-Token": csrf}
+ assert client.put("/api/v1/host", json=body, headers=headers).json()["region"] == "中国香港"
+ assert client.get("/api/v1/host").json()["region"] == "中国香港"
+ assert client.get("/api/v1/vms").json()["items"][0]["region"] == "中国香港"
+ assert client.get(f"/api/v1/vms/{VM_ID}").json()["region"] == "中国香港"
+ assert client.post("/api/v1/vms", json=CREATE_BODY,
+ headers=headers).json()["region"] == "中国香港"
+ assert client.put("/api/v1/host", json={**body, "region": "a\nline"},
+ headers=headers).status_code == 422
+
+
def test_private_key_passphrase_reaches_host_profile_but_is_never_echoed(web):
client, _, token, _, manager, _ = web
csrf = setup_admin(client, token)
@@ -654,6 +671,7 @@ def test_cloud_template_import_job_and_create_dispatch(web):
assert created.json()["name"] == "cloud-vm"
expected_spec = {key: value for key, value in cloud_body.items()
if key not in {"source", "template_id"}}
+ expected_spec["os_name"] = "AlmaLinux 10"
assert ("create_cloud_vm", expected_spec, volume_name) in service.calls
assert ("create_vm", expected_spec) not in service.calls
@@ -741,6 +759,7 @@ def test_reinstall_auto_password_remains_available_until_ack_and_is_never_persis
assert len(service_calls) == 1
assert service_calls[0][1:4] == (VM_ID, volume_name, "")
assert service_calls[0][4].startswith("$6$")
+ assert service_calls[0][5] == "AlmaLinux 10"
assert generated_password not in repr(service.calls)
second = client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers)
@@ -780,7 +799,8 @@ def test_reinstall_key_mode_has_no_generated_password(web):
completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf)
assert completed["status"] == "succeeded"
assert "generated_password" not in completed
- assert ("reinstall_cloud_vm", VM_ID, volume_name, public_key, None) in service.calls
+ assert ("reinstall_cloud_vm", VM_ID, volume_name, public_key, None,
+ "AlmaLinux 10") in service.calls
def test_reinstall_requires_exact_name_and_blocks_duplicate_or_lifecycle_actions(web):
@@ -845,10 +865,11 @@ def test_static_assets_and_security_headers(web):
assert page.status_code == 200 and "text/html" in page.headers["content-type"]
assert page.headers["cache-control"] == "no-store"
assert "frame-ancestors 'none'" in page.headers["content-security-policy"]
- assert "/static/app.js?v=database-update-1" in page.text
- assert "/static/styles.css?v=database-update-1" in page.text
- script = client.get("/static/app.js?v=database-update-1")
- style = client.get("/static/styles.css?v=database-update-1")
+ script_url = re.search(r'src="(/static/app\.js\?v=[^"]+)"', page.text)
+ style_url = re.search(r'href="(/static/styles\.css\?v=[^"]+)"', page.text)
+ assert script_url is not None and style_url is not None
+ script = client.get(script_url.group(1))
+ style = client.get(style_url.group(1))
assert script.status_code == 200 and script.headers["cache-control"] == "no-store"
assert style.status_code == 200 and style.headers["cache-control"] == "no-store"
assert "function updateCreateSource()" in script.text
diff --git a/tests/test_database.py b/tests/test_database.py
index d5120535..c5718893 100644
--- a/tests/test_database.py
+++ b/tests/test_database.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import base64
+import json
import os
import stat
import struct
@@ -157,7 +158,7 @@ def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_pa
profile = HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], storage_pool="/home/kvm",
- iso_pool="/home/iso", default_network="bridge:br0",
+ iso_pool="/home/iso", default_network="bridge:br0", region="东京",
)
staged = first.stage(profile, scan["fingerprint"])
assert first.test(staged)["libvirt"] == "available"
@@ -174,11 +175,21 @@ def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_pa
)
assert second.current()["storage_pool"] == "/home/kvm"
assert second.current()["default_network"] == "bridge:br0"
+ assert second.current()["region"] == "东京"
assert (second._current_generation() / "id_private").read_text() == PRIVATE_KEY
assert not list(data_dir.rglob("id_private"))
second.close()
assert not list(runtime_parent.rglob("id_private"))
+ legacy = json.loads(store.records[("host", "current")])
+ legacy["metadata"].pop("region")
+ store.records[("host", "current")] = json.dumps(legacy)
+ third = DatabaseRemoteHostManager(
+ store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh,
+ )
+ assert third.current()["region"] == ""
+ third.close()
+
def test_encrypted_host_key_is_locked_again_after_process_restart(tmp_path: Path):
store = MemoryStore()
diff --git a/tests/test_libvirt_service.py b/tests/test_libvirt_service.py
index 2d0ba44b..e6b6216b 100644
--- a/tests/test_libvirt_service.py
+++ b/tests/test_libvirt_service.py
@@ -601,6 +601,18 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(len(self.backend.define_xmls), 1)
self.assertEqual(self.backend.opened, self.backend.closed)
+ def test_unmanaged_vm_does_not_claim_an_os_or_ip(self):
+ vm = self.service.create_vm(self.spec())
+ domain = self.backend.domains[0]
+ for root in (domain.live_root, domain.inactive_root):
+ root.remove(root.find("metadata"))
+ listed = self.service.get_vm(vm["uuid"])
+ self.assertFalse(listed["managed"])
+ self.assertIsNone(listed["os_name"])
+ self.assertEqual(listed["os_source"], "unknown")
+ self.assertIsNone(listed["install_iso"])
+ self.assertIsNone(listed["public_ip_cidr"])
+
def test_installer_reboot_stops_guest_and_next_start_uses_unmounted_iso(self):
vm = self.service.create_vm(self.spec())
domain = self.backend.domains[0]
@@ -707,7 +719,11 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(balloon.get("freePageReporting"), "on")
self.assertGreater(int(balloon.find("stats").get("period")), 0)
self.assertEqual(root.find("./metadata/{urn:virsh-panel:1}managed").attrib,
- {"version": "2", "disk-volume": "web.qcow2"})
+ {"version": "2", "disk-volume": "web.qcow2",
+ "os-source": "iso", "install-iso": iso_name})
+ self.assertIsNone(vm["os_name"])
+ self.assertEqual(vm["os_source"], "iso")
+ self.assertEqual(vm["install_iso"], iso_name)
service.action(vm["uuid"], "shutdown")
self.assertEqual(service.delete_vm(vm["uuid"], True)["deleted_disks"],
@@ -1169,7 +1185,7 @@ class VMServiceTests(unittest.TestCase):
def test_cloud_vm_clones_template_and_uses_nonboot_seed_iso(self):
service = self.cloud_service()
- created = self.create_cloud_vm(service, self.cloud_spec())
+ created = self.create_cloud_vm(service, self.cloud_spec(os_name="AlmaLinux 10"))
self.assertEqual(created["state"], "running")
self.assertEqual(created["name"], "cloud-vm")
@@ -1205,6 +1221,10 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(managed.get("seed-volume"), seed_name)
self.assertEqual(managed.get("public-ip-cidr"), "8.8.8.18/24")
self.assertEqual(created["public_ip_cidr"], "8.8.8.18/24")
+ self.assertEqual(managed.get("os-source"), "cloud_template")
+ self.assertEqual(managed.get("os-name"), "AlmaLinux 10")
+ self.assertEqual(created["os_name"], "AlmaLinux 10")
+ self.assertEqual(created["os_source"], "cloud_template")
self.assertEqual(self.backend.opened, self.backend.closed)
def test_cloud_vm_delete_disks_removes_clone_and_seed_but_keeps_template(self):
@@ -1328,12 +1348,14 @@ class VMServiceTests(unittest.TestCase):
old_disk.delete = delete_after_new_start
result = service.reinstall_cloud_vm(
created["uuid"], TEMPLATE_NAME,
+ os_name="AlmaLinux 10.2",
ssh_public_key=spec["guest_ssh_public_key"],
)
self.assertEqual(result["vm"]["uuid"], created["uuid"])
self.assertEqual(result["vm"]["state"], "running")
self.assertEqual(result["vm"]["public_ip_cidr"], spec["public_ip_cidr"])
+ self.assertEqual(result["vm"]["os_name"], "AlmaLinux 10.2")
self.assertFalse(result.get("warning"))
self.assertEqual(self.backend.shutdown_calls, 1)
self.assertNotIn("cloud-vm.qcow2", pool.volumes)
diff --git a/tests/test_remote_host.py b/tests/test_remote_host.py
index 59b4f4fe..2156b29f 100644
--- a/tests/test_remote_host.py
+++ b/tests/test_remote_host.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import base64
import hashlib
import itertools
+import json
import shutil
import stat
import struct
@@ -70,7 +71,7 @@ def make_manager(tmp_path: Path, runner: Runner) -> RemoteHostManager:
def make_profile(
scanned: dict, *, key: str = PRIVATE_KEY, host: str = "host.example",
passphrase: str = "", storage_pool: str = "images", iso_pool: str = "iso",
- default_network: str = "default",
+ default_network: str = "default", region: str = "",
) -> HostProfile:
return HostProfile(
host=host,
@@ -81,9 +82,24 @@ def make_profile(
storage_pool=storage_pool,
iso_pool=iso_pool,
default_network=default_network,
+ region=region,
)
+def test_region_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path):
+ runner = Runner()
+ manager = make_manager(tmp_path, runner)
+ scanned = manager.scan("host.example", 2222)
+ staged = manager.stage(make_profile(scanned, region="中国香港"), scanned["fingerprint"])
+ manager.test(staged)
+ assert manager.commit(staged)["region"] == "中国香港"
+ profile_path = staged.path / "profile.json"
+ legacy = json.loads(profile_path.read_text(encoding="utf-8"))
+ legacy.pop("region")
+ profile_path.write_text(json.dumps(legacy), encoding="utf-8")
+ assert manager.current()["region"] == ""
+
+
class FakeAgent:
sequence = itertools.count()
diff --git a/virsh_panel/app.py b/virsh_panel/app.py
index 55da0278..ceaf3d02 100644
--- a/virsh_panel/app.py
+++ b/virsh_panel/app.py
@@ -104,6 +104,8 @@ class HostBody(HostScanBody):
storage_pool: str = Field(default="default", min_length=1, max_length=4096)
iso_pool: str = Field(default="iso", min_length=1, max_length=4096)
default_network: str = Field(default="default", min_length=1, max_length=128)
+ region: str = Field(default="", max_length=64,
+ pattern=r"^[^\x00-\x1f\x7f]*$")
def profile(self) -> HostProfile:
return HostProfile(
@@ -115,6 +117,7 @@ class HostBody(HostScanBody):
storage_pool=self.storage_pool,
iso_pool=self.iso_pool,
default_network=self.default_network,
+ region=self.region,
)
@@ -178,7 +181,8 @@ def _public_host(profile: dict | None) -> dict:
"iso_pool", "default_network", "private_key_configured",
"private_key_encrypted", "key_locked",
)
- return {"configured": True, **{key: profile[key] for key in keys if key in profile}}
+ return {"configured": True, **{key: profile[key] for key in keys if key in profile},
+ "region": profile.get("region", "")}
def _peer(request: Request) -> str:
@@ -839,11 +843,14 @@ def create_app(
@app.get("/api/v1/vms")
def list_vms(_session: Session = Depends(require_session)):
- return {"items": current_service().list_vms()}
+ profile = current_profile()
+ region = profile.get("region", "")
+ return {"items": [{**vm, "region": region} for vm in new_service(profile).list_vms()]}
@app.get("/api/v1/vms/{vm_id}")
def get_vm(vm_id: str, _session: Session = Depends(require_session)):
- return current_service().get_vm(vm_id)
+ profile = current_profile()
+ return {**new_service(profile).get_vm(vm_id), "region": profile.get("region", "")}
@app.post("/api/v1/vms", status_code=201)
def create_vm(body: CreateISOBody | CreateCloudBody,
@@ -852,6 +859,7 @@ def create_app(
# the VM. Otherwise an update can restart the web process mid-create.
with reinstall_lock:
forbid_long_job_during_update()
+ profile = current_profile()
if isinstance(body, CreateCloudBody):
public_key = body.guest_ssh_public_key.strip()
root_password = (body.root_password.get_secret_value()
@@ -867,21 +875,21 @@ def create_app(
password_hash = hash_root_password(root_password)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
- profile = current_profile()
record = templates.get(template_scope(profile), body.template_id)
spec = body.model_dump(exclude={"source", "template_id", "root_password"})
+ spec["os_name"] = record.get("name")
spec["guest_ssh_public_key"] = public_key
if password_hash is not None:
spec["root_password_hash"] = password_hash
vm = new_service(profile).create_cloud_vm(spec, record["volume_name"])
else:
- vm = current_service().create_vm(body.model_dump(exclude={"source"}))
+ vm = new_service(profile).create_vm(body.model_dump(exclude={"source"}))
LOG.info("vm created: uuid=%s admin=%s", vm.get("uuid"), _session.username)
- return vm
+ return {**vm, "region": profile.get("region", "")}
def run_reinstall(
job_id: str, profile: dict, scope: str, vm_id: str,
- template_volume_name: str, ssh_public_key: str,
+ template_volume_name: str, template_name: str | None, ssh_public_key: str,
root_password_hash: str | None, generated_password: str | None,
) -> None:
def report_progress(phase: str) -> None:
@@ -900,6 +908,7 @@ def create_app(
save_job("reinstall_job", job_id, reinstall_jobs[job_id])
result = new_service(profile).reinstall_cloud_vm(
vm_id, template_volume_name,
+ os_name=template_name,
ssh_public_key=ssh_public_key,
root_password_hash=root_password_hash,
progress=report_progress,
@@ -987,7 +996,7 @@ def create_app(
try:
reinstall_executor.submit(
run_reinstall, job_id, profile, scope, normalized_id,
- record["volume_name"], ssh_public_key, root_password_hash,
+ record["volume_name"], record.get("name"), ssh_public_key, root_password_hash,
generated_password,
)
except RuntimeError as exc:
diff --git a/virsh_panel/database.py b/virsh_panel/database.py
index 006b2dd4..670a9da7 100644
--- a/virsh_panel/database.py
+++ b/virsh_panel/database.py
@@ -45,6 +45,7 @@ from .remote_host import (
_validate_pool_selector,
_validate_port,
_validate_private_key,
+ _validate_region,
_write_private,
)
from .ssh_agent import SSHAgentSession, _ASKPASS_SOURCE
@@ -592,6 +593,7 @@ class DatabaseRemoteHostManager(RemoteHostManager):
storage_pool = _validate_pool_selector(metadata["storage_pool"], "磁盘池")
iso_pool = _validate_pool_selector(metadata["iso_pool"], "ISO 池")
default_network = _validate_network_selector(metadata["default_network"])
+ region = _validate_region(metadata.get("region", ""))
private_key = _validate_private_key(record["private_key"])
known_hosts = record["known_hosts"].strip()
key_type, encoded = _key_parts(known_hosts)
@@ -651,7 +653,7 @@ class DatabaseRemoteHostManager(RemoteHostManager):
_write_private(generation / "profile.json", json.dumps(
{**metadata, "host": host, "port": port,
"storage_pool": storage_pool, "iso_pool": iso_pool,
- "default_network": default_network},
+ "default_network": default_network, "region": region},
ensure_ascii=False,
).encode("utf-8"))
wrapper = self._write_wrapper(generation)
diff --git a/virsh_panel/libvirt_service.py b/virsh_panel/libvirt_service.py
index d4fd3663..d76c54b0 100644
--- a/virsh_panel/libvirt_service.py
+++ b/virsh_panel/libvirt_service.py
@@ -295,6 +295,9 @@ class VMService:
info = domain.info()
root = self._vm_xml(domain)
managed = root.find(f"./metadata/{{{PANEL_NS}}}managed")
+ os_source = managed.get("os-source") if managed is not None else None
+ if os_source not in {"cloud_template", "iso"}:
+ os_source = "unknown"
try:
autostart = bool(domain.autostart())
except libvirt.libvirtError:
@@ -309,6 +312,9 @@ class VMService:
"autostart": autostart,
"managed": managed is not None,
"public_ip_cidr": managed.get("public-ip-cidr") if managed is not None else None,
+ "os_name": managed.get("os-name") if os_source == "cloud_template" else None,
+ "os_source": os_source,
+ "install_iso": managed.get("install-iso") if os_source == "iso" else None,
"console_port": self._vnc_port(root),
}
@@ -375,6 +381,15 @@ class VMService:
validated["iso"] = iso
return validated
+ @staticmethod
+ def _validated_os_name(value: Any) -> str | None:
+ if value is None:
+ return None
+ if (not isinstance(value, str) or not 1 <= len(value) <= 64
+ or value != value.strip() or any(ord(char) < 32 for char in value)):
+ raise VMError("云镜像模板名称无效")
+ return value
+
@staticmethod
def _volume_xml(name: str, disk_gib: int) -> str:
return VMService._volume_xml_bytes(name, disk_gib * GIB, "qcow2")
@@ -427,8 +442,12 @@ class VMService:
# The next panel Start uses the persistent, ISO-free definition.
ET.SubElement(root, "on_reboot").text = "destroy"
metadata = ET.SubElement(root, "metadata")
- ET.SubElement(metadata, f"{{{PANEL_NS}}}managed", version="2",
- **{"disk-volume": disk_name})
+ managed = ET.SubElement(metadata, f"{{{PANEL_NS}}}managed", version="2",
+ **{"disk-volume": disk_name})
+ if "iso" in spec:
+ # The installation media does not prove which OS was installed.
+ managed.set("os-source", "iso")
+ managed.set("install-iso", spec["iso"])
devices = ET.SubElement(root, "devices")
disk = ET.SubElement(devices, "disk", type=disk_source[0], device="disk")
@@ -657,11 +676,15 @@ class VMService:
raise VMError("无法生成面板元数据", 500)
managed.set("seed-volume", seed_name)
managed.set("public-ip-cidr", public_ip_cidr)
+ if spec.get("os_name") is not None:
+ managed.set("os-source", "cloud_template")
+ managed.set("os-name", spec["os_name"])
return ET.tostring(root, encoding="unicode")
def create_cloud_vm(self, spec: dict[str, Any], template_volume_name: str) -> dict[str, Any]:
"""Clone a trusted cloud image and supply static public networking."""
validated = self._validate_common_create(spec)
+ validated["os_name"] = self._validated_os_name(spec.get("os_name"))
if self.bridge_name is None:
raise VMError("公网模板创建需要先在宿主机设置 Linux 网桥,例如 bridge:br0", 409)
if not TEMPLATE_VOLUME_RE.fullmatch(template_volume_name):
@@ -757,6 +780,7 @@ class VMService:
vm_id: str,
template_volume_name: str,
*,
+ os_name: str | None = None,
ssh_public_key: str = "",
root_password_hash: str | None = None,
progress: Callable[[str], None] | None = None,
@@ -770,6 +794,7 @@ class VMService:
"""
if not TEMPLATE_VOLUME_RE.fullmatch(template_volume_name):
raise VMError("只能使用面板导入的云镜像模板")
+ os_name = self._validated_os_name(os_name)
if self.bridge_name is None:
raise VMError("公网模板重装需要原 Linux 网桥配置", 409)
@@ -911,6 +936,13 @@ class VMService:
raise VMError("虚拟机面板元数据已变化,无法切换", 409)
new_managed.set("disk-volume", disk_name)
new_managed.set("seed-volume", seed_name)
+ # A different reinstall template invalidates the old label.
+ new_managed.attrib.pop("os-source", None)
+ new_managed.attrib.pop("os-name", None)
+ new_managed.attrib.pop("install-iso", None)
+ if os_name is not None:
+ new_managed.set("os-source", "cloud_template")
+ new_managed.set("os-name", os_name)
phase("starting")
new_domain = conn.defineXML(ET.tostring(new_root, encoding="unicode"))
if new_domain is None:
diff --git a/virsh_panel/remote_host.py b/virsh_panel/remote_host.py
index c4943f62..b6846049 100644
--- a/virsh_panel/remote_host.py
+++ b/virsh_panel/remote_host.py
@@ -64,6 +64,7 @@ class HostProfile:
storage_pool: str = "default"
iso_pool: str = "iso"
default_network: str = "default"
+ region: str = ""
@dataclass
@@ -139,6 +140,14 @@ def _validate_network_selector(value: str) -> str:
return _validate_name(value, "网络")
+def _validate_region(value: str) -> str:
+ # This is an operator-supplied display label, not a provider region ID.
+ if (not isinstance(value, str) or len(value) > 64 or value != value.strip()
+ or any(ord(char) < 32 or ord(char) == 127 for char in value)):
+ raise RemoteHostError("宿主机地区最多 64 字符,且不能包含控制字符或首尾空格")
+ return value
+
+
def _key_parts(line: str) -> tuple[str, str]:
if not isinstance(line, str) or len(line) > 4096 or any(c in line for c in "\r\n\x00"):
raise RemoteHostError("主机公钥格式无效")
@@ -315,6 +324,7 @@ class RemoteHostManager:
storage_pool = _validate_pool_selector(profile.storage_pool, "磁盘池")
iso_pool = _validate_pool_selector(profile.iso_pool, "ISO 池")
default_network = _validate_network_selector(profile.default_network)
+ region = _validate_region(profile.region)
if not isinstance(confirmed_fingerprint, str) or not _FINGERPRINT.fullmatch(confirmed_fingerprint):
raise RemoteHostError("请确认扫描得到的 SHA256 主机指纹")
try:
@@ -422,6 +432,7 @@ class RemoteHostManager:
"storage_pool": storage_pool,
"iso_pool": iso_pool,
"default_network": default_network,
+ "region": region,
}
_write_private(
generation / "profile.json",
@@ -652,8 +663,13 @@ class RemoteHostManager:
)
if any(field not in metadata for field in fields):
raise RemoteHostError("已保存的宿主机配置损坏", status=500)
+ try:
+ region = _validate_region(metadata.get("region", ""))
+ except RemoteHostError as exc:
+ raise RemoteHostError("已保存的宿主机配置损坏", status=500) from exc
return {
**{field: metadata[field] for field in fields},
+ "region": region,
"private_key_encrypted": bool(metadata.get("private_key_encrypted", False)),
"key_locked": bool(metadata.get("private_key_encrypted", False)) and not (
generation in self._agents and self._agents[generation].alive