fix: avoid Debian first-boot network rename race

dev
admin 2 months ago
parent 99b4e96405
commit 26ca956431

@ -199,33 +199,6 @@ 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():

@ -17,15 +17,6 @@ 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"
)
@ -755,26 +746,6 @@ 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
@ -1734,29 +1705,14 @@ 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) as seed_builder:
create=True):
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(
@ -2047,24 +2003,6 @@ 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"]

@ -21,7 +21,6 @@ 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",
@ -237,8 +236,6 @@ 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:
@ -255,10 +252,6 @@ 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"),
@ -298,20 +291,23 @@ 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": public_network,
# ``public0`` is only a stable Netplan/cloud-init configuration
# identifier. Do not rename the guest interface: Debian 12 can
# apply a first-boot rename after network activation has already
# run, leaving the renamed device up but without its static IP.
# Matching the libvirt MAC applies this configuration directly to
# the kernel-provided interface name (for example ``enp1s0``).
"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"]},
},
},
}

@ -46,7 +46,6 @@ 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
@ -2034,17 +2033,6 @@ 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 = {
@ -2157,7 +2145,6 @@ class VMService:
try:
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
@ -2330,7 +2317,6 @@ class VMService:
try:
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

Loading…
Cancel
Save