From 99b4e96405d1e35dcbab1e3add1f3cfc44f356ce Mon Sep 17 00:00:00 2001 From: admin Date: Tue, 29 Sep 2026 07:45:06 +0800 Subject: [PATCH] fix: bring Debian 12 network up on first boot --- engine/tests/test_cloud_init.py | 28 ++++++++++++ engine/tests/test_libvirt_service.py | 64 ++++++++++++++++++++++++++- engine/virsh_panel/cloud_init.py | 26 +++++++---- engine/virsh_panel/libvirt_service.py | 22 ++++++++- 4 files changed, 129 insertions(+), 11 deletions(-) diff --git a/engine/tests/test_cloud_init.py b/engine/tests/test_cloud_init.py index eb57deb5..2b70fd3f 100644 --- a/engine/tests/test_cloud_init.py +++ b/engine/tests/test_cloud_init.py @@ -178,6 +178,7 @@ def test_seed_iso_has_nocloud_files_and_mac_specific_static_network(): 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'"set-name"' not in seed user_data = _user_data(seed) assert user_data["disable_root"] is False assert user_data["ssh_pwauth"] is False @@ -198,6 +199,33 @@ def test_seed_iso_has_nocloud_files_and_mac_specific_static_network(): } +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_seed_can_explicitly_rename_mac_matched_interface_on_first_boot(): + validated = validate_cloud_network( + "8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY, + ) + seed = build_seed_iso( + str(uuid.uuid4()), "debian-12-vm", "52:54:00:12:34:56", validated, + set_name="public0", + ) + + assert b'"set-name": "public0"' in seed + assert read_seed_network(seed)["mac"] == "52:54:00:12:34:56" + + +@pytest.mark.parametrize("invalid", ["", "public interface", "a" * 16, 12, False]) +def test_seed_rejects_invalid_explicit_interface_name(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="虚拟网卡名称"): + build_seed_iso( + str(uuid.uuid4()), "debian-12-vm", "52:54:00:12:34:56", + validated, set_name=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(): diff --git a/engine/tests/test_libvirt_service.py b/engine/tests/test_libvirt_service.py index 39ffa1a7..935648d4 100644 --- a/engine/tests/test_libvirt_service.py +++ b/engine/tests/test_libvirt_service.py @@ -17,6 +17,15 @@ from unittest.mock import patch SERVICE_PATH = pathlib.Path(__file__).resolve().parents[1] / "virsh_panel" / "libvirt_service.py" TEMPLATE_NAME = "panel-template-alma10-12345678-0123456789abcdef.qcow2" +DEBIAN_12_TEMPLATE_NAME = ( + "panel-template-debian12-12345678-0123456789abcdef.qcow2" +) +DEBIAN_12_TEMPLATE_REPLICA = ( + "panel-template-debian12-12345678-0123456789abcdef-1111111111111111.qcow2" +) +DEBIAN_13_TEMPLATE_NAME = ( + "panel-template-debian13-12345678-0123456789abcdef.qcow2" +) TEMPLATE_REPLICA_ONE = ( "panel-template-alma10-12345678-0123456789abcdef-1111111111111111.qcow2" ) @@ -746,6 +755,26 @@ class VMServiceTests(unittest.TestCase): with self.subTest(value=value), self.assertRaises(self.error_type): self.service._validate_create(self.spec(bandwidth_mbps=value)) + def test_only_debian_12_seed_requests_explicit_public_interface_name(self): + for template_name in ( + DEBIAN_12_TEMPLATE_NAME, + DEBIAN_12_TEMPLATE_REPLICA, + ): + with self.subTest(template_name=template_name): + self.assertEqual( + self.service._cloud_seed_set_name(template_name), + "public0", + ) + for template_name in ( + TEMPLATE_NAME, + DEBIAN_13_TEMPLATE_NAME, + "panel-template-debian12-not-a-valid-volume.qcow2", + ): + with self.subTest(template_name=template_name): + self.assertIsNone( + self.service._cloud_seed_set_name(template_name), + ) + @staticmethod def cloud_spec(**changes): # Public examples are used only as parser fixtures; these addresses @@ -1705,14 +1734,29 @@ class VMServiceTests(unittest.TestCase): self.backend.pools["images"], alma9_volume, capacity=2 * 1024**3, ) with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED", - create=True): + create=True) as seed_builder: created = service.create_cloud_vm( self.cloud_spec(os_name="AlmaLinux 9"), alma9_volume, ) + self.assertIsNone(seed_builder.call_args.kwargs["set_name"]) self.assertEqual(created["os_name"], "AlmaLinux 9") self.assertEqual(self.backend.pools["images"].volumes["cloud-vm.qcow2"].cloned_from, alma9_volume) + def test_debian_12_cloud_vm_seed_renames_interface_on_first_boot(self): + service = self.cloud_service() + self.backend.pools["images"].volumes[DEBIAN_12_TEMPLATE_NAME] = FakeVolume( + self.backend.pools["images"], DEBIAN_12_TEMPLATE_NAME, + capacity=2 * 1024**3, + ) + with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED", + create=True) as seed_builder: + service.create_cloud_vm( + self.cloud_spec(os_name="Debian 12"), DEBIAN_12_TEMPLATE_NAME, + ) + + self.assertEqual(seed_builder.call_args.kwargs["set_name"], "public0") + def test_cloud_vm_accepts_generated_template_replica_volume(self): service = self.cloud_service() self.backend.pools["images"].volumes[TEMPLATE_REPLICA_ONE] = FakeVolume( @@ -2003,6 +2047,24 @@ class VMServiceTests(unittest.TestCase): }) self.assertEqual(self.backend.opened, self.backend.closed) + def test_reinstall_to_debian_12_seed_renames_interface_on_first_boot(self): + (service, created, spec, _domain, + _old_seed_name) = self.cloud_vm_with_real_seed() + pool = self.backend.pools["images"] + pool.volumes[DEBIAN_12_TEMPLATE_NAME] = FakeVolume( + pool, DEBIAN_12_TEMPLATE_NAME, capacity=2 * 1024**3, + ) + + with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED", + create=True) as seed_builder: + service.reinstall_cloud_vm( + created["uuid"], DEBIAN_12_TEMPLATE_NAME, + os_name="Debian 12", + ssh_public_key=spec["guest_ssh_public_key"], + ) + + self.assertEqual(seed_builder.call_args.kwargs["set_name"], "public0") + def test_reinstall_waits_for_graceful_shutdown_and_times_out_without_touching_disks(self): service, created, spec, domain, _seed_name = self.cloud_vm_with_real_seed() pool = self.backend.pools["images"] diff --git a/engine/virsh_panel/cloud_init.py b/engine/virsh_panel/cloud_init.py index 90f8870b..b86be096 100644 --- a/engine/virsh_panel/cloud_init.py +++ b/engine/virsh_panel/cloud_init.py @@ -21,6 +21,7 @@ from typing import Any _VM_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z") _MAC = re.compile(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\Z") +_INTERFACE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z") _SSH_TYPES = { "ssh-ed25519", "ssh-rsa", @@ -236,6 +237,8 @@ def build_seed_iso( name: str, mac: str, validated_network: dict[str, Any], + *, + set_name: str | None = None, ) -> bytes: """Build a CIDATA ISO with user-data, meta-data, and network-config.""" try: @@ -252,6 +255,10 @@ def build_seed_iso( raise ValueError("虚拟机 MAC 地址不能是组播或全零地址") if not isinstance(validated_network, dict): raise ValueError("网络配置无效") + if (set_name is not None + and (not isinstance(set_name, str) + or _INTERFACE_NAME.fullmatch(set_name) is None)): + raise ValueError("虚拟网卡名称无效") network = validate_cloud_network( validated_network.get("public_ip_cidr"), validated_network.get("gateway"), @@ -291,17 +298,20 @@ def build_seed_iso( }], } metadata = {"instance-id": instance_id, "local-hostname": hostname} + public_network = { + "match": {"macaddress": normalized_mac}, + "dhcp4": False, + "dhcp6": False, + "addresses": [network["public_ip_cidr"]], + "routes": [{"to": "0.0.0.0/0", "via": network["gateway"]}], + "nameservers": {"addresses": network["dns_servers"]}, + } + if set_name is not None: + public_network["set-name"] = set_name network_config = { "version": 2, "ethernets": { - "public0": { - "match": {"macaddress": normalized_mac}, - "dhcp4": False, - "dhcp6": False, - "addresses": [network["public_ip_cidr"]], - "routes": [{"to": "0.0.0.0/0", "via": network["gateway"]}], - "nameservers": {"addresses": network["dns_servers"]}, - }, + "public0": public_network, }, } diff --git a/engine/virsh_panel/libvirt_service.py b/engine/virsh_panel/libvirt_service.py index 6350dd2b..ab53b7f4 100644 --- a/engine/virsh_panel/libvirt_service.py +++ b/engine/virsh_panel/libvirt_service.py @@ -46,6 +46,7 @@ TEMPLATE_VOLUME_STEM = ( TEMPLATE_SOURCE_VOLUME_RE = re.compile(TEMPLATE_VOLUME_STEM + r"\.qcow2\Z") TEMPLATE_VOLUME_RE = re.compile( TEMPLATE_VOLUME_STEM + r"(?:-[0-9a-f]{16})?\.qcow2\Z") +DEBIAN_12_TEMPLATE_VOLUME_PREFIX = "panel-template-debian12-" RESCUE_VOLUME_RE = re.compile(r"panel-rescue-[0-9a-f]{32}\.iso\Z") _CREATE_LOCK = threading.RLock() REINSTALL_SHUTDOWN_TIMEOUT = 120 @@ -2033,6 +2034,17 @@ class VMService: raise VMError("原系统已启动但仍显示救援模式,请检查虚拟机配置", 502) return {"vm": vm} + @staticmethod + def _cloud_seed_set_name(template_volume_name: str) -> str | None: + """Return the explicit guest NIC name needed by affected images.""" + if (TEMPLATE_VOLUME_RE.fullmatch(template_volume_name) is not None + and template_volume_name.startswith( + DEBIAN_12_TEMPLATE_VOLUME_PREFIX)): + # Debian 12's ENI renderer otherwise writes a persistent rename + # rule on first boot but may not apply it until the second boot. + return "public0" + return None + @staticmethod def _mac_for_new_vm(conn: Any) -> str: used = { @@ -2143,7 +2155,10 @@ class VMService: raise VMError("同名虚拟磁盘或配置盘已存在,不会覆盖", 409) mac = self._mac_for_new_vm(conn) try: - seed_data = build_seed_iso(vm_uuid, validated["name"], mac, network) + seed_data = build_seed_iso( + vm_uuid, validated["name"], mac, network, + set_name=self._cloud_seed_set_name(template_volume_name), + ) except ImportError as exc: raise VMError("面板缺少 pycdlib,需安装 requirements.txt 中的依赖", 503) from exc created: list[tuple[Any, str]] = [] @@ -2313,7 +2328,10 @@ 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, display_name, mac, network) + seed_data = build_seed_iso( + seed_uuid, display_name, mac, network, + set_name=self._cloud_seed_set_name(template_volume_name), + ) except ImportError as exc: raise VMError("面板缺少 pycdlib,需安装 requirements.txt 中的依赖", 503) from exc created: list[Any] = []