You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/virsh_panel/rescue_templates.py

146 lines
6.3 KiB
Python

"""Host-scoped catalog for administrator-uploaded rescue ISO images.
The ISO bytes live in the remote libvirt rescue ISO pool. In production only the
catalog metadata is stored here, encrypted by the MariaDB record store.
"""
from __future__ import annotations
import hashlib
import json
import re
import threading
from pathlib import Path
from typing import Any, Mapping
from .cloud_templates import TemplateError, validate_template_name
RESCUE_ID_RE = re.compile(r"[0-9a-f]{32}\Z")
RESCUE_VOLUME_RE = re.compile(r"panel-rescue-[0-9a-f]{32}\.iso\Z")
MAX_RESCUE_ISO_BYTES = 8 * 1024**3
def rescue_scope(profile: Mapping[str, Any]) -> str:
"""Bind records to a verified SSH host and its selected rescue pool."""
try:
identity = [profile[key] for key in (
"host", "port", "fingerprint", "rescue_iso_pool")]
except (KeyError, TypeError) as exc:
raise TemplateError("宿主机资料不完整,无法选择救援模版", 409) from exc
if (not isinstance(identity[0], str) or isinstance(identity[1], bool)
or not isinstance(identity[1], int)
or not isinstance(identity[2], str) or not isinstance(identity[3], str)):
raise TemplateError("宿主机资料不完整,无法选择救援模版", 409)
if not identity[3]:
raise TemplateError("请先在宿主机设置中配置独立的救援 ISO 目录", 409)
raw = json.dumps(identity, ensure_ascii=False, separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def rescue_volume_name(template_id: str) -> str:
if not isinstance(template_id, str) or not RESCUE_ID_RE.fullmatch(template_id):
raise TemplateError("救援模版标识无效")
return f"panel-rescue-{template_id}.iso"
def verify_bootable_iso(path: Path) -> None:
"""Reject ordinary data ISOs, including cloud-init seed images.
El Torito boot records are required for x86 BIOS/UEFI optical boot. This
checks the disc descriptor, not that its bundled operating system works.
"""
size = path.stat().st_size
if not 1024 * 1024 <= size <= MAX_RESCUE_ISO_BYTES:
raise TemplateError("救援 ISO 大小必须在 1 MiB 至 8 GiB 之间", 413)
bootable = False
with path.open("rb") as image:
for sector in range(16, 80):
image.seek(sector * 2048)
descriptor = image.read(2048)
if len(descriptor) != 2048 or descriptor[1:6] != b"CD001":
raise TemplateError("上传文件不是有效的 ISO 9660 镜像", 422)
if (descriptor[0] == 0
and descriptor[7:30].rstrip(b" ") == b"EL TORITO SPECIFICATION"
and int.from_bytes(descriptor[71:75], "little") > 0):
bootable = True
if descriptor[0] == 255:
break
if not bootable:
raise TemplateError("ISO 未包含可识别的 El Torito 启动记录,无法用作救援模版", 422)
class RescueTemplateStore:
"""Small catalog with the same API in production and isolated HTTP tests."""
def __init__(self, store: Any | None) -> None:
self.store = store
self._memory: dict[str, str] = {}
self._lock = threading.RLock()
def _list(self, scope: str) -> list[dict[str, Any]]:
source = (self.store.list("rescue_template") if self.store is not None
else self._memory.copy())
records = []
for key, payload in source.items():
if not key.startswith(f"{scope}:"):
continue
try:
record = json.loads(payload)
except (TypeError, ValueError) as exc:
raise TemplateError("救援模版数据库记录损坏", 500) from exc
if (not isinstance(record, dict)
or not RESCUE_ID_RE.fullmatch(str(record.get("id", "")))
or record.get("volume_name") != rescue_volume_name(record["id"])
or not isinstance(record.get("name"), str)
or not isinstance(record.get("size_bytes"), int)):
raise TemplateError("救援模版数据库记录损坏", 500)
records.append(record)
return sorted(records, key=lambda item: item["name"].casefold())
def list(self, scope: str) -> list[dict[str, Any]]:
with self._lock:
return self._list(scope)
def get(self, scope: str, template_id: str) -> dict[str, Any]:
rescue_volume_name(template_id)
with self._lock:
for record in self._list(scope):
if record["id"] == template_id:
return record
raise TemplateError("救援模版不存在或不属于当前宿主机", 404)
def add(self, scope: str, record: dict[str, Any]) -> dict[str, Any]:
template_id = record.get("id")
if record.get("volume_name") != rescue_volume_name(template_id):
raise TemplateError("救援模版记录无效")
name = validate_template_name(record.get("name"))
if (isinstance(record.get("size_bytes"), bool)
or not isinstance(record.get("size_bytes"), int)
or not 0 < record["size_bytes"] <= MAX_RESCUE_ISO_BYTES):
raise TemplateError("救援 ISO 大小无效")
record = {**record, "name": name}
key = f"{scope}:{template_id}"
value = json.dumps(record, ensure_ascii=False, separators=(",", ":"))
with self._lock:
existing = self._list(scope)
if any(row["id"] == template_id for row in existing):
raise TemplateError("此救援模版已存在", 409)
if any(row["name"].casefold() == name.casefold() for row in existing):
raise TemplateError("当前宿主机已有同名救援模版", 409)
if self.store is not None:
if not self.store.insert("rescue_template", key, value):
raise TemplateError("此救援模版已存在", 409)
else:
self._memory[key] = value
return record
def delete(self, scope: str, template_id: str) -> None:
self.get(scope, template_id)
key = f"{scope}:{template_id}"
with self._lock:
if self.store is not None:
self.store.delete("rescue_template", key)
else:
self._memory.pop(key, None)