|
|
|
|
@ -35,6 +35,7 @@ LOG = logging.getLogger(__name__)
|
|
|
|
|
GIB = 1024**3
|
|
|
|
|
PANEL_NS = "urn:virsh-panel:1"
|
|
|
|
|
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z")
|
|
|
|
|
INTERNAL_RESOURCE_PREFIX_LENGTHS = (16, 20, 24, 28, 32)
|
|
|
|
|
BRIDGE_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z")
|
|
|
|
|
TEMPLATE_VOLUME_RE = re.compile(
|
|
|
|
|
r"panel-template-(?:alma(?:8|9|10)|debian(?:11|12|13)|"
|
|
|
|
|
@ -387,6 +388,44 @@ class VMService:
|
|
|
|
|
except ET.ParseError as exc:
|
|
|
|
|
raise VMError("宿主机返回的虚拟机配置 XML 无效", 502) from exc
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _display_name(domain: Any, managed: ET.Element | None) -> str:
|
|
|
|
|
"""Return the customer label without exposing host resource names.
|
|
|
|
|
|
|
|
|
|
Older panel domains did not persist a separate label, so their
|
|
|
|
|
libvirt name remains the compatibility fallback.
|
|
|
|
|
"""
|
|
|
|
|
display_name = managed.get("display-name") if managed is not None else None
|
|
|
|
|
if isinstance(display_name, str) and NAME_RE.fullmatch(display_name):
|
|
|
|
|
return display_name
|
|
|
|
|
return domain.name()
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _internal_resource_names(vm_uuid: str) -> tuple[str, ...]:
|
|
|
|
|
compact = uuidlib.UUID(vm_uuid).hex
|
|
|
|
|
return tuple(
|
|
|
|
|
f"vc-{compact[:length]}" for length in INTERNAL_RESOURCE_PREFIX_LENGTHS
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def _select_internal_resource_name(
|
|
|
|
|
cls,
|
|
|
|
|
vm_uuid: str,
|
|
|
|
|
domains: list[Any],
|
|
|
|
|
volume_names: set[str],
|
|
|
|
|
) -> str:
|
|
|
|
|
"""Choose a short UUID-derived domain/disk stem without overwriting.
|
|
|
|
|
|
|
|
|
|
Sixteen hexadecimal digits are ample for routine host maintenance.
|
|
|
|
|
If an existing domain or volume has that prefix, progressively reveal
|
|
|
|
|
more of the UUID instead of falling back to a user-controlled name.
|
|
|
|
|
"""
|
|
|
|
|
domain_names = {domain.name() for domain in domains}
|
|
|
|
|
for candidate in cls._internal_resource_names(vm_uuid):
|
|
|
|
|
if candidate not in domain_names and f"{candidate}.qcow2" not in volume_names:
|
|
|
|
|
return candidate
|
|
|
|
|
raise VMError("虚拟机内部资源标识已被占用,请重试", 409)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _disk_rows(root: ET.Element) -> list[dict[str, Any]]:
|
|
|
|
|
rows: list[dict[str, Any]] = []
|
|
|
|
|
@ -467,7 +506,7 @@ class VMService:
|
|
|
|
|
autostart = False
|
|
|
|
|
return {
|
|
|
|
|
"uuid": domain.UUIDString(),
|
|
|
|
|
"name": domain.name(),
|
|
|
|
|
"name": self._display_name(domain, managed),
|
|
|
|
|
"state": STATES.get(info[0], "unknown"),
|
|
|
|
|
"vcpu": info[3],
|
|
|
|
|
"memory_mib": info[1] // 1024,
|
|
|
|
|
@ -558,7 +597,7 @@ class VMService:
|
|
|
|
|
autostart = False
|
|
|
|
|
return {
|
|
|
|
|
"uuid": domain.UUIDString(),
|
|
|
|
|
"name": domain.name(),
|
|
|
|
|
"name": self._display_name(domain, managed),
|
|
|
|
|
"vcpu": info[3],
|
|
|
|
|
"memory_mib": info[1] // 1024,
|
|
|
|
|
# Storage paths and volume names are host-internal details. The
|
|
|
|
|
@ -624,7 +663,14 @@ class VMService:
|
|
|
|
|
continue
|
|
|
|
|
return rows
|
|
|
|
|
|
|
|
|
|
def provisioning_absent(self, vm_uuid: str, name: str) -> bool:
|
|
|
|
|
def provisioning_absent(
|
|
|
|
|
self,
|
|
|
|
|
vm_uuid: str,
|
|
|
|
|
name: str,
|
|
|
|
|
*,
|
|
|
|
|
uuid_resources: bool = False,
|
|
|
|
|
legacy_name_collision: bool = False,
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""Only certify refund safety after a fresh host/volume inventory.
|
|
|
|
|
|
|
|
|
|
Any connection failure, external disk collision or partial rollback is
|
|
|
|
|
@ -634,12 +680,28 @@ class VMService:
|
|
|
|
|
if not isinstance(name, str) or not NAME_RE.fullmatch(name):
|
|
|
|
|
return False
|
|
|
|
|
with self._connect() as conn:
|
|
|
|
|
if any(domain.UUIDString() == vm_uuid for domain in conn.listAllDomains(0)):
|
|
|
|
|
domains = conn.listAllDomains(0)
|
|
|
|
|
if any(domain.UUIDString() == vm_uuid for domain in domains):
|
|
|
|
|
return False
|
|
|
|
|
pool = self._active_pool(conn, self.storage_pool)
|
|
|
|
|
self._refresh_directory_pool(pool)
|
|
|
|
|
volumes = set(pool.listVolumes())
|
|
|
|
|
return not {f"{name}.qcow2", f"panel-seed-{vm_uuid}.iso"}.intersection(volumes)
|
|
|
|
|
seed_name = f"panel-seed-{vm_uuid}.iso"
|
|
|
|
|
if seed_name in volumes:
|
|
|
|
|
return False
|
|
|
|
|
if (legacy_name_collision and not uuid_resources
|
|
|
|
|
and any(domain.name() == name for domain in domains)):
|
|
|
|
|
# Legacy creates rejected a duplicate libvirt name before
|
|
|
|
|
# allocating either disk. Therefore a same-name domain with
|
|
|
|
|
# another UUID (and its same-name disk) predates this failed
|
|
|
|
|
# operation and must not keep a deterministic 409 uncertain
|
|
|
|
|
# forever. The operation UUID and seed were checked above.
|
|
|
|
|
return True
|
|
|
|
|
disk_names = (
|
|
|
|
|
{f"{candidate}.qcow2" for candidate in self._internal_resource_names(vm_uuid)}
|
|
|
|
|
if uuid_resources else {f"{name}.qcow2"}
|
|
|
|
|
)
|
|
|
|
|
return not disk_names.intersection(volumes)
|
|
|
|
|
|
|
|
|
|
def get_vm(self, uuid: str) -> dict[str, Any]:
|
|
|
|
|
with self._connect() as conn:
|
|
|
|
|
@ -808,7 +870,7 @@ class VMService:
|
|
|
|
|
iso_source: tuple[str, dict[str, str]], *,
|
|
|
|
|
install_phase: bool) -> str:
|
|
|
|
|
root = ET.Element("domain", type="kvm")
|
|
|
|
|
ET.SubElement(root, "name").text = spec["name"]
|
|
|
|
|
ET.SubElement(root, "name").text = spec.get("resource_name", spec["name"])
|
|
|
|
|
ET.SubElement(root, "uuid").text = vm_uuid
|
|
|
|
|
ET.SubElement(root, "memory", unit="MiB").text = str(spec["memory_mib"])
|
|
|
|
|
ET.SubElement(root, "vcpu", placement="static").text = str(spec["vcpu"])
|
|
|
|
|
@ -832,6 +894,7 @@ class VMService:
|
|
|
|
|
metadata = ET.SubElement(root, "metadata")
|
|
|
|
|
managed = ET.SubElement(metadata, f"{{{PANEL_NS}}}managed", version="2",
|
|
|
|
|
**{"disk-volume": disk_name})
|
|
|
|
|
managed.set("display-name", spec["name"])
|
|
|
|
|
if spec.get("created_at"):
|
|
|
|
|
managed.set("created-at", spec["created_at"])
|
|
|
|
|
if "iso" in spec:
|
|
|
|
|
@ -884,13 +947,14 @@ class VMService:
|
|
|
|
|
ET.SubElement(memballoon, "stats", period="10")
|
|
|
|
|
return ET.tostring(root, encoding="unicode")
|
|
|
|
|
|
|
|
|
|
def _rollback_new_vm(self, conn: Any, vm_uuid: str, name: str,
|
|
|
|
|
def _rollback_new_vm(self, conn: Any, vm_uuid: str, resource_name: str,
|
|
|
|
|
pool: Any, volume: Any, disk_name: str) -> bool:
|
|
|
|
|
"""Delete the new disk only after verifying its VM no longer exists."""
|
|
|
|
|
try:
|
|
|
|
|
domains = [domain for domain in conn.listAllDomains(0)
|
|
|
|
|
if domain.UUIDString() == vm_uuid]
|
|
|
|
|
if len(domains) > 1 or any(domain.name() != name for domain in domains):
|
|
|
|
|
if (len(domains) > 1
|
|
|
|
|
or any(domain.name() != resource_name for domain in domains)):
|
|
|
|
|
LOG.error("Cannot safely identify new domain %s during rollback", vm_uuid)
|
|
|
|
|
return False
|
|
|
|
|
for domain in domains:
|
|
|
|
|
@ -1989,7 +2053,12 @@ class VMService:
|
|
|
|
|
|
|
|
|
|
with _CREATE_LOCK, self._connect() as conn:
|
|
|
|
|
domains = conn.listAllDomains(0)
|
|
|
|
|
if any(domain.name() == validated["name"] for domain in domains):
|
|
|
|
|
uuid_resource_naming = requested_uuid is not None
|
|
|
|
|
vm_uuid = requested_uuid or str(uuidlib.uuid4())
|
|
|
|
|
if any(domain.UUIDString() == vm_uuid for domain in domains):
|
|
|
|
|
raise VMError("虚拟机 UUID 已存在", 409)
|
|
|
|
|
if (not uuid_resource_naming
|
|
|
|
|
and any(domain.name() == validated["name"] for domain in domains)):
|
|
|
|
|
raise VMError("虚拟机名称已存在", 409)
|
|
|
|
|
for domain in domains:
|
|
|
|
|
managed = self._vm_xml(domain).find(f"./metadata/{{{PANEL_NS}}}managed")
|
|
|
|
|
@ -2013,10 +2082,15 @@ class VMService:
|
|
|
|
|
raise VMError("虚拟磁盘不能小于云镜像模板的原始容量", 409)
|
|
|
|
|
if target_capacity > pool.info()[3]:
|
|
|
|
|
raise VMError("存储池剩余空间不足", 409)
|
|
|
|
|
vm_uuid = requested_uuid or str(uuidlib.uuid4())
|
|
|
|
|
disk_name = f"{validated['name']}.qcow2"
|
|
|
|
|
volume_names = set(pool.listVolumes())
|
|
|
|
|
resource_name = (
|
|
|
|
|
self._select_internal_resource_name(vm_uuid, domains, volume_names)
|
|
|
|
|
if uuid_resource_naming else validated["name"]
|
|
|
|
|
)
|
|
|
|
|
validated["resource_name"] = resource_name
|
|
|
|
|
disk_name = f"{resource_name}.qcow2"
|
|
|
|
|
seed_name = f"panel-seed-{vm_uuid}.iso"
|
|
|
|
|
if disk_name in pool.listVolumes() or seed_name in pool.listVolumes():
|
|
|
|
|
if disk_name in volume_names or seed_name in volume_names:
|
|
|
|
|
raise VMError("同名虚拟磁盘或配置盘已存在,不会覆盖", 409)
|
|
|
|
|
mac = self._mac_for_new_vm(conn)
|
|
|
|
|
try:
|
|
|
|
|
@ -2052,13 +2126,14 @@ class VMService:
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
clean = True
|
|
|
|
|
for volume, volume_name in reversed(created):
|
|
|
|
|
if not self._rollback_new_vm(conn, vm_uuid, validated["name"],
|
|
|
|
|
if not self._rollback_new_vm(conn, vm_uuid, resource_name,
|
|
|
|
|
pool, volume, volume_name):
|
|
|
|
|
clean = False
|
|
|
|
|
break
|
|
|
|
|
if not clean:
|
|
|
|
|
raise VMError(
|
|
|
|
|
f"云虚拟机创建失败且回滚不完整;已保留相关文件,请检查 {validated['name']}",
|
|
|
|
|
"云虚拟机创建失败且回滚不完整;已保留相关文件,请检查内部资源 "
|
|
|
|
|
f"{resource_name}(显示名 {validated['name']})",
|
|
|
|
|
502,
|
|
|
|
|
) from exc
|
|
|
|
|
if isinstance(exc, VMError):
|
|
|
|
|
@ -2178,6 +2253,7 @@ class VMService:
|
|
|
|
|
or inactive_source is None
|
|
|
|
|
or inactive_source.get("bridge") != self.bridge_name):
|
|
|
|
|
raise VMError("关机后虚拟机配置已变化,重装已停止", 409)
|
|
|
|
|
display_name = self._display_name(domain, inactive_managed)
|
|
|
|
|
if self._owned_volume(conn, domain).name() != old_disk.name() or \
|
|
|
|
|
self._owned_seed_volume(conn, domain).name() != old_seed.name():
|
|
|
|
|
raise VMError("关机后存储卷已变化,重装已停止", 409)
|
|
|
|
|
@ -2188,7 +2264,7 @@ class VMService:
|
|
|
|
|
if disk_name in pool.listVolumes() or seed_name in pool.listVolumes():
|
|
|
|
|
raise VMError("新系统盘或配置盘名称冲突,已停止重装", 409)
|
|
|
|
|
try:
|
|
|
|
|
seed_data = build_seed_iso(seed_uuid, domain.name(), mac, network)
|
|
|
|
|
seed_data = build_seed_iso(seed_uuid, display_name, mac, network)
|
|
|
|
|
except ImportError as exc:
|
|
|
|
|
raise VMError("面板缺少 pycdlib,需安装 requirements.txt 中的依赖", 503) from exc
|
|
|
|
|
created: list[Any] = []
|
|
|
|
|
@ -2257,7 +2333,7 @@ class VMService:
|
|
|
|
|
phase("completed")
|
|
|
|
|
return {
|
|
|
|
|
"vm": {"uuid": vm_id,
|
|
|
|
|
"name": inactive_root.findtext("name") or vm_id,
|
|
|
|
|
"name": display_name,
|
|
|
|
|
"state": "running"},
|
|
|
|
|
"warning": "新系统可能已启动,但启动返回错误;旧系统盘已保留,"
|
|
|
|
|
"请检查虚拟机状态和存储卷后手工清理",
|
|
|
|
|
@ -2312,7 +2388,7 @@ class VMService:
|
|
|
|
|
vm_state = self._vm_dict(new_domain)
|
|
|
|
|
except Exception:
|
|
|
|
|
LOG.exception("VM %s started after reinstall, but its details could not be read", vm_id)
|
|
|
|
|
vm_state = {"uuid": vm_id, "name": inactive_root.findtext("name") or vm_id,
|
|
|
|
|
vm_state = {"uuid": vm_id, "name": display_name,
|
|
|
|
|
"state": "running"}
|
|
|
|
|
warnings.append("新系统已启动,但面板未能读取完整虚拟机状态,请检查宿主机")
|
|
|
|
|
result: dict[str, Any] = {"vm": vm_state, "credential_generation": seed_name}
|
|
|
|
|
@ -2334,7 +2410,13 @@ class VMService:
|
|
|
|
|
def _create_iso_vm(self, conn: Any, validated: dict[str, Any],
|
|
|
|
|
requested_uuid: str | None, iso_pool: Any,
|
|
|
|
|
iso_volume: Any) -> dict[str, Any]:
|
|
|
|
|
if any(domain.name() == validated["name"] for domain in conn.listAllDomains(0)):
|
|
|
|
|
domains = conn.listAllDomains(0)
|
|
|
|
|
uuid_resource_naming = requested_uuid is not None
|
|
|
|
|
vm_uuid = requested_uuid or str(uuidlib.uuid4())
|
|
|
|
|
if any(domain.UUIDString() == vm_uuid for domain in domains):
|
|
|
|
|
raise VMError("虚拟机 UUID 已存在", 409)
|
|
|
|
|
if (not uuid_resource_naming
|
|
|
|
|
and any(domain.name() == validated["name"] for domain in domains)):
|
|
|
|
|
raise VMError("虚拟机名称已存在", 409)
|
|
|
|
|
if conn.getInfo()[0] != "x86_64":
|
|
|
|
|
raise VMError("当前创建模板只支持 x86_64 宿主机", 422)
|
|
|
|
|
@ -2347,9 +2429,14 @@ class VMService:
|
|
|
|
|
if not network.isActive():
|
|
|
|
|
raise VMError("配置的虚拟网络未启动", 409)
|
|
|
|
|
|
|
|
|
|
vm_uuid = requested_uuid or str(uuidlib.uuid4())
|
|
|
|
|
disk_name = f"{validated['name']}.qcow2"
|
|
|
|
|
if disk_name in disk_pool.listVolumes():
|
|
|
|
|
volume_names = set(disk_pool.listVolumes())
|
|
|
|
|
resource_name = (
|
|
|
|
|
self._select_internal_resource_name(vm_uuid, domains, volume_names)
|
|
|
|
|
if uuid_resource_naming else validated["name"]
|
|
|
|
|
)
|
|
|
|
|
validated["resource_name"] = resource_name
|
|
|
|
|
disk_name = f"{resource_name}.qcow2"
|
|
|
|
|
if disk_name in volume_names:
|
|
|
|
|
raise VMError(f"磁盘文件 {disk_name} 已存在,不会覆盖现有数据", 409)
|
|
|
|
|
iso_source = self._volume_source(iso_pool, iso_volume)
|
|
|
|
|
volume = disk_pool.createXML(self._volume_xml(disk_name, validated["disk_gib"]), 0)
|
|
|
|
|
@ -2384,11 +2471,11 @@ class VMService:
|
|
|
|
|
self._enable_vm_autostart(domain)
|
|
|
|
|
return self._vm_dict(domain)
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
if not self._rollback_new_vm(conn, vm_uuid, validated["name"],
|
|
|
|
|
if not self._rollback_new_vm(conn, vm_uuid, resource_name,
|
|
|
|
|
disk_pool, volume, disk_name):
|
|
|
|
|
raise VMError(
|
|
|
|
|
"创建失败且自动回滚不完整;为避免误删运行中磁盘,请检查宿主机中的"
|
|
|
|
|
f"虚拟机 {validated['name']} 和磁盘 {disk_name}", 502,
|
|
|
|
|
f"内部资源 {resource_name}(显示名 {validated['name']})和磁盘 {disk_name}", 502,
|
|
|
|
|
) from exc
|
|
|
|
|
raise
|
|
|
|
|
|
|
|
|
|
|