mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-11-24 06:44:34 +02:00
Merge branch '3.1' into 3.1
This commit is contained in:
51 files changed
+3155
-183
No files matched your search
@@ -15,19 +15,34 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import struct
|
||||
import uuid
|
||||
from unittest.mock import MagicMock, call, patch
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from pydantic import ValidationError
|
||||
|
||||
from gns3server.compute.base_manager import BaseManager
|
||||
from gns3server.compute.builtin.nodes.cloud import Cloud
|
||||
from gns3server.compute.error import NodeError
|
||||
from gns3server.compute.nios.nio_udp import NIOUDP
|
||||
from gns3server.compute.ubridge.ubridge_error import UbridgeError
|
||||
from gns3server.schemas.compute.cloud_nodes import Cloud as CloudSchema
|
||||
from gns3server.schemas.compute.cloud_nodes import CloudUpdate, TAPPort
|
||||
from tests.utils import asyncio_patch
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_bridge_detection():
|
||||
# Interface inventories are mocked: never mix them with the host's sysfs.
|
||||
with patch("gns3server.utils.interfaces.is_interface_bridge", return_value=False):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def nio():
|
||||
|
||||
@@ -256,3 +271,142 @@ async def test_linux_ethernet_raw_add_nio_bridge(linux_platform, compute_project
|
||||
call(f"bridge start {cloud._id}-0"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bridge", [None, "virbr0"])
|
||||
@pytest.mark.parametrize("existing_master", [False, True])
|
||||
async def test_tap_bridge_recreated(linux_platform, compute_project, manager, nio, bridge, existing_master):
|
||||
ports = [{"interface": "tap0", "name": "tap0", "port_number": 0, "type": "tap"}]
|
||||
if bridge:
|
||||
ports[0]["bridge"] = bridge
|
||||
cloud = Cloud("cloud1", str(uuid.uuid4()), compute_project, manager, ports=ports)
|
||||
# Round-trip through the API schema, as happens when a project is restored.
|
||||
restored_ports = CloudSchema(**cloud.asdict()).model_dump()["ports_mapping"]
|
||||
restored = Cloud("cloud1", cloud.id, compute_project, manager, ports=restored_ports)
|
||||
with (
|
||||
asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud._ubridge_send") as send,
|
||||
asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud._start_ubridge"),
|
||||
patch.object(restored, "_interfaces", return_value=[{"name": "virbr0"}]),
|
||||
patch("gns3server.utils.interfaces.is_interface_bridge", return_value=True),
|
||||
patch("gns3server.compute.builtin.nodes.cloud.os.path.exists", return_value=existing_master),
|
||||
patch("gns3server.compute.builtin.nodes.cloud.os.path.realpath", return_value="/sys/class/net/virbr0"),
|
||||
):
|
||||
restored._nios[0] = nio
|
||||
await restored.start()
|
||||
tap_call = call(f'bridge add_nio_tap {cloud.id}-0 "tap0"')
|
||||
assert tap_call in send.call_args_list
|
||||
attach_call = call('brctl addif "virbr0" "tap0"')
|
||||
if bridge:
|
||||
assert send.call_args_list.index(tap_call) < send.call_args_list.index(attach_call)
|
||||
else:
|
||||
assert attach_call not in send.call_args_list
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["missing", "not_bridge", "other_master", "invalid_name", "non_linux"])
|
||||
async def test_tap_bridge_validation(linux_platform, compute_project, manager, nio, failure):
|
||||
ports = [{"interface": "tap0", "name": "tap0", "port_number": 0, "type": "tap", "bridge": "virbr0"}]
|
||||
if failure == "invalid_name":
|
||||
ports[0]["interface"] = 'tap0"\nbridge delete all'
|
||||
cloud = Cloud("cloud1", str(uuid.uuid4()), compute_project, manager, ports=ports)
|
||||
with (
|
||||
asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud._ubridge_send") as send,
|
||||
patch.object(cloud, "_interfaces", return_value=[] if failure == "missing" else [{"name": "virbr0"}]),
|
||||
patch("gns3server.utils.interfaces.is_interface_bridge", return_value=failure != "not_bridge"),
|
||||
patch("gns3server.compute.builtin.nodes.cloud.os.path.exists", return_value=failure == "other_master"),
|
||||
patch("gns3server.compute.builtin.nodes.cloud.os.path.realpath", return_value="/sys/class/net/another0"),
|
||||
patch("gns3server.compute.builtin.nodes.cloud.sys.platform", "darwin" if failure == "non_linux" else "linux"),
|
||||
):
|
||||
with pytest.raises(NodeError):
|
||||
await cloud._add_ubridge_connection(nio, 0)
|
||||
assert not any("add_nio_tap" in c.args[0] or "brctl addif" in c.args[0] for c in send.call_args_list)
|
||||
|
||||
|
||||
async def test_tap_bridge_attachment_failure(linux_platform, compute_project, manager, nio):
|
||||
ports = [{"interface": "tap0", "name": "tap0", "port_number": 0, "type": "tap", "bridge": "virbr0"}]
|
||||
cloud = Cloud("cloud1", str(uuid.uuid4()), compute_project, manager, ports=ports)
|
||||
cloud.status = "started"
|
||||
|
||||
async def send(command):
|
||||
if command.startswith("brctl addif"):
|
||||
raise UbridgeError("Operation not permitted")
|
||||
|
||||
with (
|
||||
asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud._ubridge_send", side_effect=send),
|
||||
asyncio_patch("gns3server.compute.builtin.nodes.cloud.Cloud._stop_ubridge") as stop,
|
||||
patch.object(cloud, "_interfaces", return_value=[{"name": "virbr0"}]),
|
||||
patch("gns3server.utils.interfaces.is_interface_bridge", return_value=True),
|
||||
patch("gns3server.compute.builtin.nodes.cloud.os.path.exists", return_value=False),
|
||||
):
|
||||
await cloud.add_nio(nio, 0)
|
||||
stop.assert_called_once()
|
||||
assert cloud.status == "stopped"
|
||||
|
||||
|
||||
async def test_cloud_lists_linux_bridges(linux_platform, compute_project, manager):
|
||||
cloud = Cloud(
|
||||
"cloud1",
|
||||
str(uuid.uuid4()),
|
||||
compute_project,
|
||||
manager,
|
||||
ports=[{"interface": "tap0", "name": "tap0", "port_number": 0, "type": "tap"}],
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"gns3server.utils.interfaces.interfaces",
|
||||
return_value=[
|
||||
{"name": "eth0", "type": "ethernet", "special": False},
|
||||
{"name": "virbr0", "type": "ethernet", "special": True},
|
||||
],
|
||||
),
|
||||
patch("gns3server.utils.interfaces.is_interface_bridge", side_effect=lambda name: name == "virbr0"),
|
||||
):
|
||||
interfaces = CloudSchema(**cloud.asdict()).model_dump()["interfaces"]
|
||||
assert [(interface["name"], interface["is_bridge"]) for interface in interfaces] == [
|
||||
("eth0", False),
|
||||
("virbr0", True),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stored_bridge", [None, "omitted"])
|
||||
async def test_connected_tap_mapping_round_trip(compute_project, manager, stored_bridge):
|
||||
port = {"interface": "tap0", "name": "tap0", "port_number": 0, "type": "tap"}
|
||||
if stored_bridge is None:
|
||||
port["bridge"] = None
|
||||
cloud = Cloud("cloud1", str(uuid.uuid4()), compute_project, manager, ports=[port])
|
||||
response = CloudSchema(**cloud.asdict()).model_dump(mode="json")
|
||||
cloud._nios[0] = object()
|
||||
ports = jsonable_encoder(CloudUpdate(ports_mapping=response["ports_mapping"]), exclude_unset=True)["ports_mapping"]
|
||||
cloud.ports_mapping = ports
|
||||
assert cloud.ports_mapping == [{"interface": "tap0", "name": "tap0", "port_number": 0, "type": "tap"}]
|
||||
ports[0]["bridge"] = "virbr0"
|
||||
with pytest.raises(NodeError, match="already connected"):
|
||||
cloud.ports_mapping = ports
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["tap-interface-too-long", "tap bad", 'tap0"\nbridge delete all', "/dev/tap0"])
|
||||
async def test_bridged_tap_name_validation_preserves_legacy_names(name):
|
||||
port = {"interface": name, "name": name, "port_number": 0, "type": "tap"}
|
||||
assert TAPPort(**port).interface == name
|
||||
with pytest.raises(ValidationError, match="bridged TAP name"):
|
||||
TAPPort(**port, bridge="virbr0")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"caps,legacy_allowed,bridge_allowed",
|
||||
[
|
||||
(0, False, False),
|
||||
(1 << 12, False, False),
|
||||
(1 << 13, True, False),
|
||||
((1 << 12) | (1 << 13), True, True),
|
||||
],
|
||||
)
|
||||
async def test_bridged_tap_requires_net_admin(linux_platform, tmp_path, caps, legacy_allowed, bridge_allowed):
|
||||
executable = tmp_path / "ubridge"
|
||||
executable.write_text("")
|
||||
with (
|
||||
patch("os.geteuid", return_value=1000),
|
||||
patch("os.listxattr", return_value=["security.capability"]),
|
||||
patch("os.getxattr", return_value=struct.pack("<IIIII", 0x2000001, caps, 0, 0, 0)),
|
||||
):
|
||||
assert BaseManager.has_privileged_access(executable) is legacy_allowed
|
||||
assert BaseManager.has_privileged_access(executable, require_net_admin=True) is bridge_allowed
|
||||
@@ -22,6 +22,7 @@ fallback and cleanup.
|
||||
"""
|
||||
|
||||
import os
|
||||
import socket
|
||||
import uuid
|
||||
from unittest.mock import MagicMock, call, patch
|
||||
|
||||
@@ -32,6 +33,7 @@ from gns3server.compute.compute_error import ComputeError
|
||||
from gns3server.compute.docker import Docker
|
||||
from gns3server.compute.docker.docker_error import DockerError, DockerHttp404Error
|
||||
from gns3server.compute.docker.docker_vm import DockerVM
|
||||
from gns3server.compute.error import NodeError
|
||||
from gns3server.compute.nios.nio_bridge import NIOBridge
|
||||
from gns3server.compute.ubridge.ubridge_error import UbridgeError, UbridgeNamespaceError
|
||||
from tests.utils import AsyncioMagicMock
|
||||
@@ -1468,3 +1470,147 @@ async def test_stop_clears_relay_bridge_registry(vm):
|
||||
await vm.stop()
|
||||
assert vm._bridges == set()
|
||||
assert vm._ubridge_tc_caps is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cross-compute VXLAN tunnel
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
VXLAN_SPEC = {"name": "gvl01234567abcd", "vni": 1048577, "remote": "192.168.1.2", "dstport": 4789}
|
||||
|
||||
|
||||
def test_create_nio_bridge_carries_vxlan_spec(vm):
|
||||
"""
|
||||
The vxlan sub-spec of a cross-compute NIO survives the factory and the
|
||||
asdict round-trip (the node replays the NIO from asdict on restart).
|
||||
"""
|
||||
|
||||
nio = vm.manager.create_nio({"type": "nio_bridge", "bridge": BRIDGE, "vxlan": dict(VXLAN_SPEC)})
|
||||
assert isinstance(nio, NIOBridge)
|
||||
assert nio.vxlan == VXLAN_SPEC
|
||||
assert nio.asdict()["vxlan"] == VXLAN_SPEC
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_ubridge_kernel_connection_with_vxlan(vm):
|
||||
"""
|
||||
A vxlan-carrying NIO creates this end's tunnel device (lower device
|
||||
resolved locally from the peer address) and enslaves it into the link's
|
||||
kernel bridge next to the anchor.
|
||||
"""
|
||||
|
||||
async def send(command):
|
||||
if command.startswith("vxlan show"):
|
||||
raise UbridgeError("VXLAN does not exist")
|
||||
|
||||
vm._ubridge_hypervisor = MagicMock()
|
||||
vm._ubridge_hypervisor.send = AsyncioMagicMock(side_effect=send)
|
||||
vm._namespace = 42
|
||||
nio = vm.manager.create_nio({"type": "nio_bridge", "bridge": BRIDGE, "vxlan": dict(VXLAN_SPEC)})
|
||||
|
||||
with patch.object(DockerVM, "_vxlan_lowerdev", return_value="eth0"):
|
||||
await vm._add_ubridge_connection(nio, 0)
|
||||
|
||||
host_ifc, _ = vm._veth_names(0, 0)
|
||||
sends = [c.args[0] for c in vm._ubridge_hypervisor.send.call_args_list]
|
||||
show = f'vxlan show "{VXLAN_SPEC["name"]}"'
|
||||
create = (
|
||||
f'vxlan create "{VXLAN_SPEC["name"]}" {VXLAN_SPEC["vni"]} '
|
||||
f"remote={VXLAN_SPEC['remote']} dstport={VXLAN_SPEC['dstport']} dev=eth0"
|
||||
)
|
||||
assert sends.index(show) < sends.index(create)
|
||||
# The tunnel device is enslaved after the node's anchor, and the anchor
|
||||
# still goes up.
|
||||
assert sends.index(f'brctl addif "{BRIDGE}" "{host_ifc}"') < sends.index(
|
||||
f'brctl addif "{BRIDGE}" "{VXLAN_SPEC["name"]}"'
|
||||
)
|
||||
assert f'link set "{host_ifc}" up' in sends
|
||||
# A failed show (device absent) must not trigger a delete.
|
||||
assert f'vxlan delete "{VXLAN_SPEC["name"]}"' not in sends
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_ubridge_kernel_connection_replaces_vxlan_leftover(vm):
|
||||
"""
|
||||
A device found under this link's deterministic name is this link's own
|
||||
leftover (a crashed run, a node restart): deleted and re-created, which
|
||||
makes wiring idempotent.
|
||||
"""
|
||||
|
||||
vm._ubridge_hypervisor = MagicMock()
|
||||
vm._namespace = 42
|
||||
nio = vm.manager.create_nio({"type": "nio_bridge", "bridge": BRIDGE, "vxlan": dict(VXLAN_SPEC)})
|
||||
|
||||
with patch.object(DockerVM, "_vxlan_lowerdev", return_value="eth0"):
|
||||
await vm._add_ubridge_connection(nio, 0)
|
||||
|
||||
sends = [c.args[0] for c in vm._ubridge_hypervisor.send.call_args_list]
|
||||
show = f'vxlan show "{VXLAN_SPEC["name"]}"'
|
||||
delete = f'vxlan delete "{VXLAN_SPEC["name"]}"'
|
||||
create = (
|
||||
f'vxlan create "{VXLAN_SPEC["name"]}" {VXLAN_SPEC["vni"]} '
|
||||
f"remote={VXLAN_SPEC['remote']} dstport={VXLAN_SPEC['dstport']} dev=eth0"
|
||||
)
|
||||
assert sends.index(show) < sends.index(delete) < sends.index(create)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remove_kernel_nio_deletes_vxlan_device(vm):
|
||||
"""
|
||||
Link teardown deletes this end's tunnel device (the kernel un-enrolls it
|
||||
from the bridge on unregister) before the bridge delete.
|
||||
"""
|
||||
|
||||
vm._ubridge_hypervisor = MagicMock()
|
||||
vm._ubridge_send = AsyncioMagicMock()
|
||||
vm.status = "started"
|
||||
host_ifc, _ = vm._veth_names(0, 0)
|
||||
vm._kernel_veths[(0, 0)] = host_ifc
|
||||
vm._ethernet_adapters[0].add_nio(
|
||||
0, vm.manager.create_nio({"type": "nio_bridge", "bridge": BRIDGE, "vxlan": dict(VXLAN_SPEC)})
|
||||
)
|
||||
|
||||
await vm.adapter_remove_nio_binding(0)
|
||||
|
||||
vm._ubridge_send.assert_has_calls(
|
||||
[
|
||||
call(f'brctl delif "{BRIDGE}" "{host_ifc}"'),
|
||||
call(f'vxlan delete "{VXLAN_SPEC["name"]}"'),
|
||||
call(f'brctl delete "{BRIDGE}"'),
|
||||
],
|
||||
any_order=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vxlan_lowerdev_unresolvable_peer_raises(vm):
|
||||
"""
|
||||
A peer that cannot be resolved (or routed to) is a wiring error of this
|
||||
link — the controller retries and then degrades it to the relay.
|
||||
"""
|
||||
|
||||
with patch("gns3server.compute.kernel_datapath.socket.getaddrinfo", side_effect=socket.gaierror("nope")):
|
||||
with pytest.raises(NodeError):
|
||||
await vm._vxlan_lowerdev("192.0.2.1")
|
||||
|
||||
|
||||
def test_interface_with_address_matches_the_owning_interface():
|
||||
"""
|
||||
The route's chosen source address is matched back to its interface,
|
||||
scope suffixes stripped (link-local IPv6).
|
||||
"""
|
||||
|
||||
class _Addr:
|
||||
def __init__(self, address):
|
||||
self.address = address
|
||||
|
||||
with patch(
|
||||
"gns3server.compute.kernel_datapath.psutil.net_if_addrs",
|
||||
return_value={
|
||||
"eth0": [_Addr("192.168.1.1")],
|
||||
"eth1": [_Addr("fe80::1%eth1")],
|
||||
},
|
||||
):
|
||||
assert DockerVM._interface_with_address("192.168.1.1") == "eth0"
|
||||
assert DockerVM._interface_with_address("fe80::1%eth1") == "eth1"
|
||||
assert DockerVM._interface_with_address("10.0.0.1") is None
|
||||
@@ -15,9 +15,11 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -1039,3 +1041,225 @@ async def test_run_with_kvm_linux_dev_kvm_missing(linux_platform, vm):
|
||||
vm.manager.config.settings.Qemu.require_hardware_acceleration = True
|
||||
with pytest.raises(QemuError):
|
||||
await vm._run_with_hardware_acceleration("qemu-system-x86_64", "")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_two_cdrom_images(vm, images_dir):
|
||||
installer = Path(images_dir) / "installer.iso"
|
||||
drivers = Path(images_dir) / "virtio,drivers.iso"
|
||||
installer.touch()
|
||||
drivers.touch()
|
||||
vm.cdrom_image = str(installer)
|
||||
vm.cdrom2_image = str(drivers)
|
||||
assert vm._cdrom_option() == [
|
||||
"-cdrom",
|
||||
str(installer),
|
||||
"-drive",
|
||||
f"file={str(drivers).replace(',', ',,')},if=ide,index=3,media=cdrom,readonly=on",
|
||||
]
|
||||
assert vm.asdict()["cdrom2_image"].endswith("virtio,drivers.iso")
|
||||
vm.cdrom2_image = ""
|
||||
assert vm._cdrom_option() == ["-cdrom", str(installer)]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("config_disk", [False, True])
|
||||
async def test_second_cdrom_ide_conflict(vm, images_dir, config_disk):
|
||||
iso = Path(images_dir) / "drivers.iso"
|
||||
iso.touch()
|
||||
vm.cdrom2_image = str(iso)
|
||||
vm._hdd_disk_interface = "ide"
|
||||
vm._create_config_disk = config_disk
|
||||
if not config_disk:
|
||||
vm._hdd_disk_image = str(iso)
|
||||
with pytest.raises(QemuError, match="second CDROM"):
|
||||
vm._cdrom_option()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_first_cdrom_ide_conflict(vm, images_dir):
|
||||
iso = Path(images_dir) / "installer.iso"
|
||||
iso.touch()
|
||||
vm.cdrom_image = str(iso)
|
||||
vm._hdc_disk_image = str(iso)
|
||||
vm._hdc_disk_interface = "ide"
|
||||
with pytest.raises(QemuError, match="IDE hdc disk"):
|
||||
vm._cdrom_option()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("interface", ["virtio", "scsi", "sata", "nvme"])
|
||||
@pytest.mark.parametrize("cdrom_count", [1, 2])
|
||||
async def test_four_non_ide_disks_with_cdroms(vm, images_dir, interface, cdrom_count):
|
||||
iso = Path(images_dir) / "installer.iso"
|
||||
iso.touch()
|
||||
vm.cdrom_image = str(iso)
|
||||
for drive in "abcd":
|
||||
disk = Path(images_dir) / f"hd{drive}.qcow2"
|
||||
disk.touch()
|
||||
setattr(vm, f"_hd{drive}_disk_image", str(disk))
|
||||
setattr(vm, f"_hd{drive}_disk_interface", interface)
|
||||
expected = ["-cdrom", str(iso)]
|
||||
if cdrom_count == 2:
|
||||
vm.cdrom2_image = str(iso)
|
||||
expected.extend(["-drive", f"file={iso},if=ide,index=3,media=cdrom,readonly=on"])
|
||||
assert vm._cdrom_option() == expected
|
||||
vm.linked_clone = False
|
||||
with patch.object(vm, "_qemu_img_exec", new_callable=AsyncioMagicMock, return_value=0):
|
||||
disk_options = await vm._disk_options()
|
||||
assert sum(option.startswith("file=") for option in disk_options) == 4
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cdrom_monitor(vm):
|
||||
reader = asyncio.StreamReader()
|
||||
reader.feed_data(b"QEMU monitor\r\n(qemu) ")
|
||||
writer = MagicMock()
|
||||
writer.drain = AsyncioMagicMock()
|
||||
state = {"blocks": "ide1-cd0: installer.iso\r\nide1-cd1: drivers.iso\r\n", "error": ""}
|
||||
|
||||
def respond(data):
|
||||
command = data.decode("utf-8").strip()
|
||||
output = state["blocks"] if command == "info block" else state["error"]
|
||||
reader.feed_data(data.rstrip(b"\n") + b"\r\n" + output.encode("utf-8") + b"(qemu) ")
|
||||
|
||||
writer.write.side_effect = respond
|
||||
with (
|
||||
patch.object(vm, "is_running", return_value=True),
|
||||
patch.object(
|
||||
vm, "_open_qemu_monitor_connection_vm", new_callable=AsyncioMagicMock, return_value=(reader, writer)
|
||||
),
|
||||
):
|
||||
yield state, writer
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("filename", ["drivers with spaces.iso", "drivers-雪.iso", "drivers (qemu) .iso"])
|
||||
async def test_second_cdrom_update(vm, images_dir, cdrom_monitor, filename):
|
||||
iso = Path(images_dir) / filename
|
||||
iso.touch()
|
||||
state, writer = cdrom_monitor
|
||||
await vm.update_property("cdrom2_image", str(iso))
|
||||
assert writer.write.call_args_list[0] == mock.call(b"info block\n")
|
||||
command = writer.write.call_args_list[1].args[0].decode("ascii")
|
||||
encoded_filename = json.loads(command.removeprefix("change ide1-cd1 -f ").strip())
|
||||
if encoded_filename.startswith("json:"):
|
||||
assert json.loads(encoded_filename[5:])["file"]["filename"] == str(iso)
|
||||
else:
|
||||
assert encoded_filename == str(iso)
|
||||
assert vm.cdrom2_image == str(iso)
|
||||
writer.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_second_cdrom_eject(vm, cdrom_monitor):
|
||||
state, writer = cdrom_monitor
|
||||
await vm.update_property("cdrom2_image", "")
|
||||
writer.write.assert_called_with(b"eject -f ide1-cd1\n")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_second_cdrom_hot_add_requires_restart(vm, images_dir, cdrom_monitor):
|
||||
iso = Path(images_dir) / "drivers.iso"
|
||||
iso.touch()
|
||||
state, writer = cdrom_monitor
|
||||
state["blocks"] = "ide1-cd0: installer.iso\r\n"
|
||||
vm._command_line_changed = False
|
||||
with pytest.raises(QemuError, match="Stop the VM"):
|
||||
await vm.update_property("cdrom2_image", str(iso))
|
||||
assert vm.cdrom2_image == ""
|
||||
assert not vm._command_line_changed
|
||||
assert writer.write.call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_other_iso_does_not_block_media_swap(vm, images_dir, cdrom_monitor):
|
||||
iso = Path(images_dir) / "installer.iso"
|
||||
iso.touch()
|
||||
vm._cdrom2_image = str(Path(images_dir) / "deleted.iso")
|
||||
await vm.update_property("cdrom_image", str(iso))
|
||||
assert vm.cdrom_image == str(iso)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("error", ["Error: media change failed", "change: filename expected"])
|
||||
@pytest.mark.parametrize("original_deleted", [False, True])
|
||||
async def test_cdrom_monitor_error_preserves_previous_image(vm, images_dir, cdrom_monitor, error, original_deleted):
|
||||
original = Path(images_dir) / "original.iso"
|
||||
original.touch()
|
||||
replacement = Path(images_dir) / "replacement.iso"
|
||||
replacement.touch()
|
||||
vm.cdrom2_image = str(original)
|
||||
if original_deleted:
|
||||
original.unlink()
|
||||
state, writer = cdrom_monitor
|
||||
state["error"] = error + "\r\n"
|
||||
with pytest.raises(QemuError, match=error):
|
||||
await vm.update_property("cdrom2_image", str(replacement))
|
||||
assert vm.cdrom2_image == str(original)
|
||||
writer.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("slot", [0, 1])
|
||||
async def test_sata_cdrom_with_ide_disks(vm, images_dir, slot):
|
||||
iso = Path(images_dir) / "installer,drivers.iso"
|
||||
iso.touch()
|
||||
image_name = "cdrom_image" if slot == 0 else "cdrom2_image"
|
||||
interface_name = "cdrom_interface" if slot == 0 else "cdrom2_interface"
|
||||
setattr(vm, image_name, str(iso))
|
||||
setattr(vm, interface_name, "sata")
|
||||
vm._hdc_disk_image = vm._hdd_disk_image = str(iso)
|
||||
vm._hdc_disk_interface = vm._hdd_disk_interface = "ide"
|
||||
assert vm._cdrom_option() == [
|
||||
"-device",
|
||||
f"ich9-ahci,id=cdrom-ahci{slot}",
|
||||
"-drive",
|
||||
f"file={str(iso).replace(',', ',,')},if=none,id=sata-cdrom{slot},media=cdrom,readonly=on",
|
||||
"-device",
|
||||
f"ide-cd,drive=sata-cdrom{slot},bus=cdrom-ahci{slot}.0",
|
||||
]
|
||||
assert vm.asdict()[interface_name] == "sata"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("name", ["cdrom_interface", "cdrom2_interface"])
|
||||
async def test_cdrom_interface_change_requires_stopped_vm(vm, name):
|
||||
with patch.object(vm, "is_running", return_value=True):
|
||||
with pytest.raises(QemuError, match="Stop the VM"):
|
||||
await vm.update_property(name, "sata")
|
||||
assert getattr(vm, name) == "ide"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("slot", [0, 1])
|
||||
async def test_sata_cdrom_media_update(vm, images_dir, cdrom_monitor, slot):
|
||||
state, writer = cdrom_monitor
|
||||
setattr(vm, "_cdrom_interface" if slot == 0 else "_cdrom2_interface", "sata")
|
||||
state["blocks"] = f"sata-cdrom{slot} (#block123): old.iso\r\n"
|
||||
iso = Path(images_dir) / "new.iso"
|
||||
iso.touch()
|
||||
await vm.update_property("cdrom_image" if slot == 0 else "cdrom2_image", str(iso))
|
||||
writer.write.assert_called_with(f'change sata-cdrom{slot} -f "{iso}"\n'.encode())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("name", ["cdrom_image", "cdrom2_image"])
|
||||
async def test_cdrom_broken_symlink_error_includes_target(vm, images_dir, name):
|
||||
target = Path(images_dir) / "missing.iso"
|
||||
link = Path(images_dir) / "linked.iso"
|
||||
link.symlink_to(target)
|
||||
setattr(vm, f"_{name}", str(link))
|
||||
with pytest.raises(QemuError, match="linked to") as error:
|
||||
vm._cdrom_option()
|
||||
assert str(target) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("slot", [0, 1])
|
||||
async def test_sata_cdrom_eject(vm, cdrom_monitor, slot):
|
||||
state, writer = cdrom_monitor
|
||||
setattr(vm, "_cdrom_interface" if slot == 0 else "_cdrom2_interface", "sata")
|
||||
state["blocks"] = f"sata-cdrom{slot}: empty\r\n"
|
||||
await vm.update_property("cdrom_image" if slot == 0 else "cdrom2_image", "")
|
||||
writer.write.assert_called_with(f"eject -f sata-cdrom{slot}\n".encode())
|
||||
@@ -30,8 +30,10 @@ from gns3server.compute.ubridge.tc_probe import (
|
||||
probe_iol_tap_support,
|
||||
probe_tap_support,
|
||||
probe_tc_capabilities,
|
||||
probe_vxlan_support,
|
||||
)
|
||||
from gns3server.compute.ubridge.ubridge_error import UbridgeError
|
||||
from gns3server.config import Config
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
|
||||
@@ -93,6 +95,7 @@ def probe_env(monkeypatch, tmp_path):
|
||||
tc_probe._tap_cache.clear()
|
||||
tc_probe._iol_tap_cache.clear()
|
||||
tc_probe._bridge_tap_cache.clear()
|
||||
tc_probe._vxlan_cache.clear()
|
||||
FakeHypervisor.last = None
|
||||
# a real file on disk: the cache is keyed on its (path, mtime, size,
|
||||
# ctime)
|
||||
@@ -280,3 +283,51 @@ async def test_probe_bridge_tap_support_missing_binary(monkeypatch):
|
||||
monkeypatch.setattr(tc_probe.shutil, "which", lambda name: None)
|
||||
assert await probe_bridge_tap_support() is None
|
||||
assert FakeHypervisor.spawned == 0
|
||||
|
||||
|
||||
class _FixedUuid:
|
||||
"""A uuid4 stand-in whose .int/.hex pin the probe's random draws."""
|
||||
|
||||
def __init__(self, value):
|
||||
self.int = value
|
||||
self.hex = f"{value:032x}"
|
||||
|
||||
|
||||
def _probe_create_port():
|
||||
"""The dstport of the one `vxlan create` the probe issued."""
|
||||
|
||||
create = next(c for c in FakeHypervisor.last.commands if c.startswith("vxlan create "))
|
||||
return int(create.rsplit("dstport=", 1)[1])
|
||||
|
||||
|
||||
async def test_probe_vxlan_avoids_the_configured_dstport(monkeypatch, probe_env):
|
||||
"""
|
||||
A scratch draw landing exactly on the configured dstport must move: on
|
||||
that port the scratch VNI shares a demux table with the live links'
|
||||
devices, and an unlucky VNI draw would make the probe report the
|
||||
capability unknown for the process's lifetime (the result is cached).
|
||||
"""
|
||||
|
||||
# int % 10000 == 9999 -> the scratch window draws its very last value
|
||||
monkeypatch.setattr(tc_probe.uuid, "uuid4", lambda: _FixedUuid(29999))
|
||||
settings = Config.instance().settings.Server
|
||||
monkeypatch.setattr(settings, "vxlan_dstport", 29999)
|
||||
|
||||
assert await probe_vxlan_support() is True
|
||||
assert _probe_create_port() == 20000
|
||||
|
||||
|
||||
async def test_probe_vxlan_scratch_port_stays_off_the_configured_one(monkeypatch, probe_env):
|
||||
"""
|
||||
Whatever the configured dstport, the probe's socket never lands on it
|
||||
and stays inside its scratch window.
|
||||
"""
|
||||
|
||||
settings = Config.instance().settings.Server
|
||||
for configured in (4789, 20000, 25000, 29999):
|
||||
monkeypatch.setattr(settings, "vxlan_dstport", configured)
|
||||
tc_probe._vxlan_cache.clear()
|
||||
assert await probe_vxlan_support() is True
|
||||
port = _probe_create_port()
|
||||
assert 20000 <= port <= 29999, port
|
||||
assert port != configured, (port, configured)
|
||||
Reference in new issue
Block a user