|
|
|
|
@ -23,7 +23,10 @@ from typing import Any, Callable, Iterator
|
|
|
|
|
|
|
|
|
|
import libvirt
|
|
|
|
|
|
|
|
|
|
from virsh_panel.cloud_init import build_seed_iso, read_seed_network, validate_cloud_network
|
|
|
|
|
from virsh_panel.cloud_init import (
|
|
|
|
|
build_seed_iso, read_seed_network, replace_seed_network,
|
|
|
|
|
validate_cloud_network,
|
|
|
|
|
)
|
|
|
|
|
from virsh_panel.metrics import RawVMStats
|
|
|
|
|
from virsh_panel.user_isos import (
|
|
|
|
|
MAX_USER_ISO_BYTES, MAX_USER_ISOS, MAX_USER_ISO_TOTAL_BYTES,
|
|
|
|
|
@ -52,6 +55,8 @@ RESCUE_VOLUME_RE = re.compile(r"panel-rescue-[0-9a-f]{32}\.iso\Z")
|
|
|
|
|
_CREATE_LOCK = threading.RLock()
|
|
|
|
|
REINSTALL_SHUTDOWN_TIMEOUT = 120
|
|
|
|
|
REINSTALL_SHUTDOWN_POLL_INTERVAL = 1
|
|
|
|
|
NETWORK_CHANGE_SHUTDOWN_TIMEOUT = 120
|
|
|
|
|
NETWORK_CHANGE_SHUTDOWN_POLL_INTERVAL = 1
|
|
|
|
|
SERVICE_SUSPEND_SHUTDOWN_TIMEOUT = 30
|
|
|
|
|
SERVICE_SUSPEND_SHUTDOWN_POLL_INTERVAL = 0.5
|
|
|
|
|
MIN_RESCUE_ISO_BYTES = 1024 * 1024
|
|
|
|
|
@ -160,6 +165,27 @@ class VMService:
|
|
|
|
|
filter=CLEAN_TRAFFIC_FILTER)
|
|
|
|
|
ET.SubElement(filterref, "parameter", name="IP", value=public_ip)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _update_clean_traffic_filter(interface: ET.Element,
|
|
|
|
|
public_ip_cidr: str) -> None:
|
|
|
|
|
"""Update or add the panel anti-spoofing filter on one interface."""
|
|
|
|
|
public_ip = public_ip_cidr.split("/", 1)[0]
|
|
|
|
|
refs = [node for node in interface.findall("filterref")
|
|
|
|
|
if node.get("filter") == CLEAN_TRAFFIC_FILTER]
|
|
|
|
|
if len(refs) > 1:
|
|
|
|
|
raise VMError("虚拟机存在重复的 clean-traffic 过滤器,已停止网络修改", 409)
|
|
|
|
|
if not refs:
|
|
|
|
|
VMService._attach_clean_traffic_filter(interface, public_ip_cidr)
|
|
|
|
|
return
|
|
|
|
|
parameters = refs[0].findall("parameter")
|
|
|
|
|
if len(parameters) > 1:
|
|
|
|
|
raise VMError("虚拟机的 clean-traffic 参数重复,已停止网络修改", 409)
|
|
|
|
|
parameter = parameters[0] if parameters else ET.SubElement(
|
|
|
|
|
refs[0], "parameter", name="IP", value=public_ip)
|
|
|
|
|
if parameter.get("name") != "IP":
|
|
|
|
|
raise VMError("虚拟机的 clean-traffic 参数无效,已停止网络修改", 409)
|
|
|
|
|
parameter.set("value", public_ip)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _pool_path(reference: str) -> str | None:
|
|
|
|
|
if not reference.startswith("/"):
|
|
|
|
|
@ -2495,6 +2521,210 @@ class VMService:
|
|
|
|
|
phase("completed")
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
def change_cloud_vm_network(
|
|
|
|
|
self,
|
|
|
|
|
vm_id: str,
|
|
|
|
|
network: dict[str, Any],
|
|
|
|
|
*,
|
|
|
|
|
confirm_restart: bool = False,
|
|
|
|
|
progress: Callable[[str], None] | None = None,
|
|
|
|
|
) -> dict[str, Any]:
|
|
|
|
|
"""Replace a managed cloud VM's public IPv4 configuration.
|
|
|
|
|
|
|
|
|
|
The operation deliberately rewrites only the network-config file in
|
|
|
|
|
the existing NoCloud seed. Credentials and metadata remain opaque and
|
|
|
|
|
untouched. A running guest is gracefully stopped and started again;
|
|
|
|
|
a stopped guest remains stopped. Any transport error after QEMU has
|
|
|
|
|
started is surfaced as a 502 so the durable internal operation becomes
|
|
|
|
|
``uncertain`` instead of guessing whether the guest applied the IP.
|
|
|
|
|
"""
|
|
|
|
|
if confirm_restart is not True:
|
|
|
|
|
raise VMError("更换公网 IP 前必须确认会短暂重启虚拟机", 422)
|
|
|
|
|
if self.bridge_name is None:
|
|
|
|
|
raise VMError("公网云镜像更换 IP 需要原 Linux 网桥配置", 409)
|
|
|
|
|
if not isinstance(network, dict):
|
|
|
|
|
raise VMError("网络配置无效", 422)
|
|
|
|
|
try:
|
|
|
|
|
validated = validate_cloud_network(
|
|
|
|
|
network.get("public_ip_cidr"), network.get("gateway"),
|
|
|
|
|
network.get("dns_servers"), require_auth=False,
|
|
|
|
|
)
|
|
|
|
|
except (TypeError, ValueError) as exc:
|
|
|
|
|
raise VMError(str(exc), 422) from exc
|
|
|
|
|
|
|
|
|
|
def phase(value: str) -> None:
|
|
|
|
|
if progress is not None:
|
|
|
|
|
progress(value)
|
|
|
|
|
|
|
|
|
|
with _CREATE_LOCK, self._connect() as conn:
|
|
|
|
|
self._require_clean_traffic_filter(conn)
|
|
|
|
|
domain = self._domain(conn, vm_id)
|
|
|
|
|
if not domain.isPersistent():
|
|
|
|
|
raise VMError("只能修改持久化虚拟机", 409)
|
|
|
|
|
if getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0):
|
|
|
|
|
raise VMError("虚拟机存在托管保存状态,请先处理后再修改网络", 409)
|
|
|
|
|
if domain.snapshotNum(0) > 0:
|
|
|
|
|
raise VMError("虚拟机存在快照,请先处理后再修改网络", 409)
|
|
|
|
|
original_root = self._vm_xml(domain)
|
|
|
|
|
managed = original_root.find(f"./metadata/{{{PANEL_NS}}}managed")
|
|
|
|
|
if (managed is None or managed.get("version") != "2"
|
|
|
|
|
or managed.get("os-source") != "cloud_template"
|
|
|
|
|
or not managed.get("seed-volume")
|
|
|
|
|
or not managed.get("public-ip-cidr")):
|
|
|
|
|
raise VMError("只有面板创建的公网云镜像虚拟机支持更换 IP", 409)
|
|
|
|
|
interfaces = original_root.findall("./devices/interface")
|
|
|
|
|
if len(interfaces) != 1:
|
|
|
|
|
raise VMError("虚拟机必须只有一个公网网卡,已停止网络修改", 409)
|
|
|
|
|
interface = interfaces[0]
|
|
|
|
|
source = interface.find("source")
|
|
|
|
|
mac_node = interface.find("mac")
|
|
|
|
|
if (interface.get("type") != "bridge" or source is None
|
|
|
|
|
or source.get("bridge") != self.bridge_name
|
|
|
|
|
or mac_node is None or not mac_node.get("address")):
|
|
|
|
|
raise VMError("虚拟机网桥或 MAC 已变化,不能自动修改网络", 409)
|
|
|
|
|
mac = mac_node.get("address").lower()
|
|
|
|
|
old_ip = managed.get("public-ip-cidr")
|
|
|
|
|
if validated["public_ip_cidr"] == old_ip:
|
|
|
|
|
return {
|
|
|
|
|
"vm": self._vm_dict(domain),
|
|
|
|
|
"public_ip_cidr": old_ip,
|
|
|
|
|
"gateway": validated["gateway"],
|
|
|
|
|
"dns_servers": list(validated["dns_servers"]),
|
|
|
|
|
"network_changed": False,
|
|
|
|
|
"was_running": bool(domain.isActive()),
|
|
|
|
|
}
|
|
|
|
|
old_seed = self._owned_seed_volume(conn, domain)
|
|
|
|
|
if old_seed is None:
|
|
|
|
|
raise VMError("找不到原 cloud-init 配置盘,已停止网络修改", 409)
|
|
|
|
|
original_seed = self._download_seed_volume(conn, old_seed)
|
|
|
|
|
try:
|
|
|
|
|
original_network = read_seed_network(original_seed)
|
|
|
|
|
except (ImportError, ValueError) as exc:
|
|
|
|
|
raise VMError("原 cloud-init 配置盘不是面板生成格式,已停止网络修改", 409) from exc
|
|
|
|
|
if (original_network["mac"] != mac
|
|
|
|
|
or original_network["public_ip_cidr"] != old_ip):
|
|
|
|
|
raise VMError("原配置盘的公网 IP 或 MAC 与虚拟机不一致,已停止网络修改", 409)
|
|
|
|
|
try:
|
|
|
|
|
replacement_seed = replace_seed_network(
|
|
|
|
|
original_seed, validated["public_ip_cidr"],
|
|
|
|
|
validated["gateway"], validated["dns_servers"],
|
|
|
|
|
)
|
|
|
|
|
except ImportError as exc:
|
|
|
|
|
raise VMError("面板缺少 pycdlib,无法修改 cloud-init 配置盘", 503) from exc
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
raise VMError("原 cloud-init 网络配置格式无效,已停止网络修改", 409) from exc
|
|
|
|
|
|
|
|
|
|
phase("shutting_down")
|
|
|
|
|
was_running = bool(domain.isActive())
|
|
|
|
|
if was_running:
|
|
|
|
|
try:
|
|
|
|
|
domain.shutdown()
|
|
|
|
|
except libvirt.libvirtError as exc:
|
|
|
|
|
raise VMError("虚拟机正常关机失败,网络未修改", 409) from exc
|
|
|
|
|
deadline = time.monotonic() + NETWORK_CHANGE_SHUTDOWN_TIMEOUT
|
|
|
|
|
while domain.isActive():
|
|
|
|
|
if time.monotonic() >= deadline:
|
|
|
|
|
raise VMError("正常关机超时,网络未修改", 409)
|
|
|
|
|
time.sleep(NETWORK_CHANGE_SHUTDOWN_POLL_INTERVAL)
|
|
|
|
|
|
|
|
|
|
# Re-read inactive XML after shutdown. This protects the seed and
|
|
|
|
|
# filter update from a concurrent operator edit.
|
|
|
|
|
old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
|
|
|
|
|
inactive_root = ET.fromstring(old_xml)
|
|
|
|
|
inactive_managed = inactive_root.find(f"./metadata/{{{PANEL_NS}}}managed")
|
|
|
|
|
inactive_interface = inactive_root.find("./devices/interface")
|
|
|
|
|
inactive_mac = (inactive_interface.find("mac")
|
|
|
|
|
if inactive_interface is not None else None)
|
|
|
|
|
inactive_source = (inactive_interface.find("source")
|
|
|
|
|
if inactive_interface is not None else None)
|
|
|
|
|
if (inactive_managed is None
|
|
|
|
|
or inactive_managed.get("seed-volume") != old_seed.name()
|
|
|
|
|
or inactive_managed.get("public-ip-cidr") != old_ip
|
|
|
|
|
or inactive_interface is None
|
|
|
|
|
or inactive_mac is None
|
|
|
|
|
or (inactive_mac.get("address") or "").lower() != mac
|
|
|
|
|
or inactive_interface.get("type") != "bridge"
|
|
|
|
|
or inactive_source is None
|
|
|
|
|
or inactive_source.get("bridge") != self.bridge_name):
|
|
|
|
|
raise VMError("关机后虚拟机配置已变化,网络修改已停止", 409)
|
|
|
|
|
|
|
|
|
|
new_root = ET.fromstring(old_xml)
|
|
|
|
|
new_managed = new_root.find(f"./metadata/{{{PANEL_NS}}}managed")
|
|
|
|
|
new_interface = new_root.find("./devices/interface")
|
|
|
|
|
if new_managed is None or new_interface is None:
|
|
|
|
|
raise VMError("虚拟机配置已变化,网络修改已停止", 409)
|
|
|
|
|
new_managed.set("public-ip-cidr", validated["public_ip_cidr"])
|
|
|
|
|
self._update_clean_traffic_filter(
|
|
|
|
|
new_interface, validated["public_ip_cidr"])
|
|
|
|
|
switched = False
|
|
|
|
|
try:
|
|
|
|
|
phase("updating_network")
|
|
|
|
|
# The volume is raw and already bounded at one MiB. Grow it
|
|
|
|
|
# only when the replacement image is larger; shrinking raw
|
|
|
|
|
# volumes is not portable and is unnecessary for NoCloud.
|
|
|
|
|
current_capacity = int(old_seed.info()[1])
|
|
|
|
|
if len(replacement_seed) > current_capacity:
|
|
|
|
|
old_seed.resize(len(replacement_seed), 0)
|
|
|
|
|
self._upload_volume(
|
|
|
|
|
conn, old_seed, iter((replacement_seed,)),
|
|
|
|
|
len(replacement_seed),
|
|
|
|
|
)
|
|
|
|
|
new_domain = conn.defineXML(ET.tostring(new_root, encoding="unicode"))
|
|
|
|
|
if new_domain is None:
|
|
|
|
|
raise VMError("宿主机未能保存新的虚拟机网络配置", 502)
|
|
|
|
|
switched = True
|
|
|
|
|
if was_running:
|
|
|
|
|
phase("starting")
|
|
|
|
|
try:
|
|
|
|
|
new_domain.create()
|
|
|
|
|
except libvirt.libvirtError as exc:
|
|
|
|
|
if new_domain.isActive():
|
|
|
|
|
# The request may have reached QEMU despite a lost
|
|
|
|
|
# response. Keep the new definition and let the
|
|
|
|
|
# internal operation become uncertain.
|
|
|
|
|
raise VMError(
|
|
|
|
|
"虚拟机已发送启动指令但结果不确定,请查询任务状态", 502,
|
|
|
|
|
) from exc
|
|
|
|
|
raise
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
if switched and was_running and domain.isActive():
|
|
|
|
|
raise VMError(
|
|
|
|
|
"网络修改结果不确定,请查询任务状态;未释放原公网 IP", 502,
|
|
|
|
|
) from exc
|
|
|
|
|
restored = True
|
|
|
|
|
try:
|
|
|
|
|
self._upload_volume(conn, old_seed, iter((original_seed,)),
|
|
|
|
|
len(original_seed))
|
|
|
|
|
except Exception:
|
|
|
|
|
LOG.exception("Could not restore original seed for %s", vm_id)
|
|
|
|
|
restored = False
|
|
|
|
|
if switched:
|
|
|
|
|
try:
|
|
|
|
|
restored_domain = conn.defineXML(old_xml)
|
|
|
|
|
if restored_domain is None:
|
|
|
|
|
restored = False
|
|
|
|
|
except Exception:
|
|
|
|
|
LOG.exception("Could not restore original VM XML for %s", vm_id)
|
|
|
|
|
restored = False
|
|
|
|
|
if not restored:
|
|
|
|
|
raise VMError(
|
|
|
|
|
"网络修改失败且自动回滚不完整;原配置仍保留,请检查虚拟机", 502,
|
|
|
|
|
) from exc
|
|
|
|
|
if isinstance(exc, VMError):
|
|
|
|
|
raise
|
|
|
|
|
raise VMError("网络修改失败,已恢复原配置", 502) from exc
|
|
|
|
|
|
|
|
|
|
phase("completed")
|
|
|
|
|
result = self._vm_dict(new_domain)
|
|
|
|
|
return {
|
|
|
|
|
"vm": result,
|
|
|
|
|
"public_ip_cidr": validated["public_ip_cidr"],
|
|
|
|
|
"gateway": validated["gateway"],
|
|
|
|
|
"dns_servers": list(validated["dns_servers"]),
|
|
|
|
|
"network_changed": True,
|
|
|
|
|
"was_running": was_running,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _requested_create_uuid(spec: dict[str, Any]) -> str | None:
|
|
|
|
|
requested_uuid = spec.get("vm_uuid")
|
|
|
|
|
|