refactor: remove platform-specific code for Darwin and Windows. Clean up Qemu options handling

This commit is contained in:
grossmj committed 2026-10-31 16:49:23 +07:00
1 parent 4d1b9e4700
commit bad48286a5
20 files changed
+77 -532

No files matched your search

-4
View File
@@ -307,10 +307,6 @@ class BaseManager:
:returns: True or False
"""
if sys.platform.startswith("darwin"):
if os.stat(executable).st_uid == 0:
return True
if os.geteuid() == 0:
# we are root, so we should have privileged access.
return True
+1 -28
View File
@@ -340,12 +340,7 @@ class Cloud(BaseNode):
f"Interface '{port_info['interface']}' could not be found on this system, please update '{self.name}'"
)
if sys.platform.startswith("linux") or sys.platform.startswith("openbsd"):
await self._add_linux_ethernet(port_info, bridge_name)
elif sys.platform.startswith("darwin"):
await self._add_osx_ethernet(port_info, bridge_name)
else:
await self._add_windows_ethernet(port_info, bridge_name)
await self._add_linux_ethernet(port_info, bridge_name)
elif port_info["type"] == "tap":
await self._add_tap_interface(port_info, bridge_name)
@@ -410,28 +405,6 @@ class Cloud(BaseNode):
else:
await self._ubridge_send(f'bridge add_nio_linux_raw {bridge_name} "{interface}"')
async def _add_osx_ethernet(self, port_info, bridge_name):
"""
Connects an Ethernet interface on OSX using libpcap.
"""
# Wireless adapters are not well supported by the libpcap on OSX
if await self._is_wifi_adapter_osx(port_info["interface"]):
raise NodeError("Connecting to a Wireless adapter is not supported on Mac OS")
if port_info["interface"].startswith("vmnet"):
# Use a special NIO to connect to VMware vmnet interfaces on OSX (libpcap doesn't support them)
await self._ubridge_send(
'bridge add_nio_fusion_vmnet {name} "{interface}"'.format(
name=bridge_name, interface=port_info["interface"]
)
)
return
if not gns3server.utils.interfaces.has_netmask(port_info["interface"]):
raise NodeError(f"Interface {port_info['interface']} has no netmask, interface down?")
await self._ubridge_send(
'bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=port_info["interface"])
)
async def _add_windows_ethernet(self, port_info, bridge_name):
"""
Connects an Ethernet interface on Windows.
-11
View File
@@ -26,7 +26,6 @@ import re
import shlex
import shutil
import subprocess
import sys
from ...utils.asyncio import subprocess_check_output
from ...utils.get_resource import get_resource
@@ -113,16 +112,6 @@ class Qemu(BaseManager):
paths.update(os.environ["PATH"].split(os.pathsep))
else:
log.warning("The PATH environment variable doesn't exist")
# look for Qemu binaries in the current working directory and $PATH
if sys.platform.startswith("darwin") and hasattr(sys, "frozen"):
# add specific locations on Mac OS X regardless of what's in $PATH
paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"])
try:
exec_dir = os.path.dirname(os.path.abspath(sys.executable))
paths.add(os.path.abspath(os.path.join(exec_dir, "qemu/bin")))
# If the user run the server by hand from outside
except FileNotFoundError:
paths.add("/Applications/GNS3.app/Contents/MacOS/qemu/bin")
return paths
@staticmethod
+7 -33
View File
@@ -30,7 +30,6 @@ import shutil
import socket
import struct
import subprocess
import sys
import time
from pathlib import Path
@@ -1014,25 +1013,13 @@ class QemuVM(KernelDatapathMixin, BaseNode):
log.debug(f'QEMU VM "{self._name}" [{self._id}] has set the QEMU options to {options}')
# "-no-kvm" and "-no-hax' are deprecated since Qemu v5.2
# "-no-kvm" is deprecated since Qemu v5.2
# https://www.qemu.org/docs/master/about/removed-features.html#no-kvm-removed-in-5-2
if "-no-kvm" in options:
options = options.replace("-no-kvm", "-machine accel=tcg")
if "-no-hax" in options:
options = options.replace("-no-hax", "-machine accel=tcg")
if "-enable-kvm" in options:
if not sys.platform.startswith("linux"):
# KVM can only be enabled on Linux
options = options.replace("-enable-kvm", "")
else:
options = options.replace("-enable-kvm", "-machine accel=kvm")
if "-enable-hax" in options:
if not sys.platform.startswith("darwin"):
# HAXM is only available on macOS
options = options.replace("-enable-hax", "")
else:
options = options.replace("-enable-hax", "-machine accel=hax")
options = options.replace("-enable-kvm", "-machine accel=kvm")
self._options = options.strip()
@@ -1263,7 +1250,7 @@ class QemuVM(KernelDatapathMixin, BaseNode):
await self._set_process_priority()
if self._cpu_throttling:
self._set_cpu_throttling()
if "-enable-kvm" in command_string or "-enable-hax" in command_string:
if "-machine accel=kvm" in command_string:
self._hw_virtualization = True
set_link_commands = []
@@ -2774,23 +2761,13 @@ class QemuVM(KernelDatapathMixin, BaseNode):
else:
return False
if sys.platform.startswith("linux") and not os.path.exists("/dev/kvm"):
if not os.path.exists("/dev/kvm"):
if require_hardware_accel:
raise QemuError(
"KVM acceleration cannot be used (/dev/kvm doesn't exist). It is possible to turn off KVM support in the gns3_server.conf by adding enable_hardware_acceleration = false to the [Qemu] section."
)
else:
return False
elif sys.platform.startswith("darwin"):
process = await asyncio.create_subprocess_shell("kextstat | grep com.intel.kext.intelhaxm")
await process.wait()
if process.returncode != 0:
if require_hardware_accel:
raise QemuError(
"HAXM acceleration support is not installed on this host (com.intel.kext.intelhaxm extension not loaded)"
)
else:
return False
return True
return False
@@ -2933,11 +2910,8 @@ class QemuVM(KernelDatapathMixin, BaseNode):
command.extend(["-smp", f"cpus={self._cpus},maxcpus={maxcpus},sockets=1"])
kvm = False
if await self._run_with_hardware_acceleration(self.qemu_path, self._options):
if sys.platform.startswith("linux"):
command.extend(["-enable-kvm"])
kvm = True
elif sys.platform.startswith("darwin"):
command.extend(["-enable-hax"])
command.extend(["-machine", "accel=kvm"])
kvm = True
command.extend(["-boot", f"order={self._boot_priority}"])
command.extend(self._cdrom_option())
command.extend(await self._disk_options())
@@ -24,7 +24,6 @@ import os
import re
import shutil
import subprocess
import sys
log = logging.getLogger(__name__)
@@ -61,10 +60,6 @@ class VirtualBox(BaseManager):
vboxmanage_path = shutil.which(vboxmanage_path)
else:
log.info("A path to VBoxManage has not been configured, trying to find it...")
if sys.platform.startswith("darwin"):
vboxmanage_path_osx = "/Applications/VirtualBox.app/Contents/MacOS/VBoxManage"
if os.path.exists(vboxmanage_path_osx):
vboxmanage_path = vboxmanage_path_osx
if not vboxmanage_path:
vboxmanage_path = shutil.which("vboxmanage")
if not vboxmanage_path:
+5 -29
View File
@@ -92,10 +92,7 @@ class VMware(BaseManager):
# look for vmrun
vmrun_path = self.config.settings.VMware.vmrun_path
if not vmrun_path:
if sys.platform.startswith("darwin"):
vmrun_path = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
else:
vmrun_path = "vmrun"
vmrun_path = "vmrun"
if vmrun_path and not os.path.isabs(vmrun_path):
vmrun_path = shutil.which(vmrun_path)
@@ -186,14 +183,6 @@ class VMware(BaseManager):
Check VMware version
"""
if sys.platform.startswith("darwin"):
if not os.path.isdir("/Applications/VMware Fusion.app"):
raise VMwareError(
"VMware Fusion is not installed in the standard location /Applications/VMware Fusion.app"
)
self._host_type = "fusion"
return # FIXME: no version checking on Mac OS X but we support all versions of fusion
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path is None:
raise VMwareError("VMware is not installed (vmware or vmplayer executable could not be found in $PATH)")
@@ -223,11 +212,7 @@ class VMware(BaseManager):
@staticmethod
def _get_vmnet_interfaces():
if sys.platform.startswith("darwin"):
vmware_networking_file = "/Library/Preferences/VMware Fusion/networking"
else:
# location on Linux
vmware_networking_file = "/etc/vmware/networking"
vmware_networking_file = "/etc/vmware/networking"
vmnet_interfaces = {}
try:
with open(vmware_networking_file, encoding="utf-8") as f:
@@ -620,10 +605,7 @@ class VMware(BaseManager):
:returns: path to the inventory file
"""
if sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Application Support/VMware Fusion/vmInventory")
else:
return os.path.expanduser("~/.vmware/inventory.vmls")
return os.path.expanduser("~/.vmware/inventory.vmls")
@staticmethod
def get_vmware_preferences_path():
@@ -633,10 +615,7 @@ class VMware(BaseManager):
:returns: path to the preferences file
"""
if sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Preferences/VMware Fusion/preferences")
else:
return os.path.expanduser("~/.vmware/preferences")
return os.path.expanduser("~/.vmware/preferences")
@staticmethod
def get_vmware_default_vm_paths():
@@ -646,10 +625,7 @@ class VMware(BaseManager):
:returns: path to the default VM directory
"""
if sys.platform.startswith("darwin"):
return [os.path.expanduser("~/Documents/Virtual Machines.localized")]
else:
return [os.path.expanduser("~/vmware")]
return [os.path.expanduser("~/vmware")]
async def list_vms(self):
"""
+2 -21
View File
@@ -22,7 +22,6 @@ import asyncio
import logging
import os
import platform
import sys
import tempfile
from collections import OrderedDict
@@ -260,12 +259,7 @@ class VMwareVM(BaseNode):
if self._get_vmx_setting(connected):
del self._vmx_pairs[connected]
use_ubridge = True
# use alternative method to find vmnet interfaces on macOS >= 11.0 (BigSur)
# because "bridge" interfaces are used instead and they are only created on the VM starts
if sys.platform.startswith("darwin") and parse_version(platform.mac_ver()[0]) >= parse_version("11.0.0"):
use_ubridge = False
self.manager.refresh_vmnet_list(ubridge=use_ubridge)
self.manager.refresh_vmnet_list(ubridge=True)
# then configure VMware network adapters
for adapter_number in range(0, self._adapters):
custom_adapter = self._get_custom_adapter_settings(adapter_number)
@@ -350,20 +344,7 @@ class VMwareVM(BaseNode):
await self._ubridge_send(f"bridge create {vnet}")
vmnet_interface = os.path.basename(self._vmx_pairs[vnet])
block_host_traffic = self.manager.config.settings.VMware.block_host_traffic
if sys.platform.startswith("darwin"):
if parse_version(platform.mac_ver()[0]) >= parse_version("11.0.0"):
# a bridge interface (bridge100, bridge101 etc.) is used instead of a vmnet interface
# on macOS >= 11.0 (Big Sur)
vmnet_interface = self.manager.find_bridge_interface(vmnet_interface)
if not vmnet_interface:
raise VMwareError(f"Could not find bridge interface linked with {vmnet_interface}")
await self._add_ubridge_ethernet_connection(vnet, vmnet_interface, block_host_traffic)
else:
# special case on macOS, we cannot bind VMnet interfaces using the libpcap
await self._ubridge_send(f'bridge add_nio_fusion_vmnet {vnet} "{vmnet_interface}"')
else:
await self._add_ubridge_ethernet_connection(vnet, vmnet_interface, block_host_traffic)
await self._add_ubridge_ethernet_connection(vnet, vmnet_interface, block_host_traffic)
if isinstance(nio, NIOUDP):
await self._ubridge_send(f"bridge add_nio_udp {vnet} {nio.lport} {nio.rhost} {nio.rport}")
+2 -4
View File
@@ -68,10 +68,8 @@ class GNS3VM:
"support_headless": True,
"support_ram": True,
}
if sys.platform.startswith("darwin"):
vmware_info["name"] = "VMware Fusion (recommended)"
else:
vmware_info["name"] = "VMware Workstation / Player (recommended)"
vmware_info["name"] = "VMware Workstation / Player (recommended)"
download_url = (
f"https://github.com/GNS3/gns3-gui/releases/download/v{__version__}/GNS3.VM.Hyper-V.{__version__}.zip"
@@ -275,23 +275,10 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
f'VM "{self.vmname}" must have a NAT interface or NAT Network configured in order to start'
)
if sys.platform.startswith("darwin") and parse_version(self._system_properties["API version"]) >= parse_version(
"7_0"
):
# VirtualBox 7.0+ on macOS requires a host-only network interface
backend_type = "hostonly-network"
backend_description = "host-only network"
vboxnet_type = "hostonlynets"
interface_number = await self._look_for_interface("hostonlynetwork")
if interface_number < 0:
raise GNS3VMError(
f'VM "{self.vmname}" must have a network adapter attached to a host-only network in order to start'
)
else:
backend_type = "hostonlyadapter"
backend_description = "host-only adapter"
vboxnet_type = "hostonlyifs"
interface_number = await self._look_for_interface("hostonly")
backend_type = "hostonlyadapter"
backend_description = "host-only adapter"
vboxnet_type = "hostonlyifs"
interface_number = await self._look_for_interface("hostonly")
if interface_number < 0:
raise GNS3VMError(
+3 -14
View File
@@ -22,11 +22,7 @@ import shutil
import sys
from collections import OrderedDict
if sys.platform.startswith("darwin"):
VMWARE_NETWORKING_FILE = "/Library/Preferences/VMware Fusion/networking"
else:
# location on Linux
VMWARE_NETWORKING_FILE = "/etc/vmware/networking"
VMWARE_NETWORKING_FILE = "/etc/vmware/networking"
if sys.platform.startswith("win"):
DEFAULT_RANGE = [1, 19]
@@ -74,15 +70,8 @@ def write_networking_file(version, pairs):
raise SystemExit(f"Cannot open {VMWARE_NETWORKING_FILE}: {e}")
# restart VMware networking service
if sys.platform.startswith("darwin"):
if not os.path.exists("/Applications/VMware Fusion.app/Contents/Library/vmnet-cli"):
raise SystemExit("VMware Fusion is not installed in Applications")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --configure")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --stop")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --start")
else:
os.system("vmware-networks --stop")
os.system("vmware-networks --start")
os.system("vmware-networks --stop")
os.system("vmware-networks --start")
def parse_vmnet_range(start, end):