refactor: remove local gns3vm support and remove more platform-specific code

This commit is contained in:
grossmj committed 2026-10-31 17:51:37 +07:00
1 parent bad48286a5
commit c7e085e23c
36 files changed
+63 -2739

No files matched your search

-14
View File
@@ -44,8 +44,6 @@ from .appliance import Appliance as Appliance
from .appliance_manager import ApplianceManager
from .compute import Compute, ComputeError
from .controller_error import ControllerError, ControllerNotFoundError
from .gns3vm import GNS3VM
from .gns3vm.gns3_vm_error import GNS3VMError
from .node import Node
from .notification import Notification
from .project import Project
@@ -131,7 +129,6 @@ class Controller:
self._projects = {}
self._ssl_context = None
self._notification = Notification(self)
self.gns3vm = GNS3VM(self)
self.symbols = Symbols()
self._appliance_manager = ApplianceManager()
self._iou_license_settings = {"iourc_content": "", "license_check": False}
@@ -213,11 +210,6 @@ class Controller:
except (ControllerError, KeyError):
pass # Skip not available servers at loading
try:
await self.gns3vm.auto_start_vm()
except GNS3VMError as e:
log.warning(str(e))
await self.load_projects()
self._start_projects_monitor()
@@ -273,7 +265,6 @@ class Controller:
# We don't care if a compute is down at this step
except (ComputeError, ControllerError, OSError):
pass
await self.gns3vm.exit_vm()
self.save()
self._computes = {}
self._projects = {}
@@ -607,11 +598,6 @@ class Controller:
if (compute_id == "local" or compute_id == "vm") and not force:
return None
# It seem we have error with a gns3vm imported as a remote server and conflict
# with GNS3 VM settings. That's why we ignore server name gns3vm
if name == "gns3vm":
return None
for compute in self._computes.values():
if name and compute.name == name and not force:
raise ControllerError(f'Compute name "{name}" already exists')
-2
View File
@@ -383,8 +383,6 @@ class Compute:
# a manually disconnected compute is not lazily reconnected either: the
# request fails like for any unreachable compute
if not self._connected and not self._manual_disconnect and not dont_connect:
if self._id == "vm" and not self._controller.gns3vm.running:
await self._controller.gns3vm.start()
await self.connect()
if not self._connected and not dont_connect:
raise ComputeError(f"Cannot connect to compute '{self._name}' with request {method} {path}")
-401
View File
@@ -1,401 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 asyncio
import copy
import ipaddress
import logging
import sys
from ...utils.asyncio import locking
from ...version import __version__
from ..compute import ComputeError
from ..controller_error import ControllerError
from .gns3_vm_error import GNS3VMError
from .hyperv_gns3_vm import HyperVGNS3VM
from .remote_gns3_vm import RemoteGNS3VM
from .virtualbox_gns3_vm import VirtualBoxGNS3VM
from .vmware_gns3_vm import VMwareGNS3VM
log = logging.getLogger(__name__)
class GNS3VM:
"""
Proxy between the controller and the GNS3 VM engine
"""
def __init__(self, controller):
self._controller = controller
# Keep instance of the loaded engines
self._engines = {}
self._settings = {
"vmname": None,
"when_exit": "stop",
"headless": False,
"enable": False,
"engine": "vmware",
"allocate_vcpus_ram": True,
"ram": 2048,
"vcpus": 1,
"port": 80,
}
def engine_list(self):
"""
:returns: Return list of engines supported by GNS3 for the GNS3VM
"""
download_url = f"https://github.com/GNS3/gns3-gui/releases/download/v{__version__}/GNS3.VM.VMware.Workstation.{__version__}.zip"
vmware_info = {
"engine_id": "vmware",
"description": f'VMware is the recommended choice for best performances.<br>The GNS3 VM can be <a href="{download_url}">downloaded here</a>.',
"support_when_exit": True,
"support_headless": True,
"support_ram": True,
}
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"
)
hyperv_info = {
"engine_id": "hyper-v",
"name": "Hyper-V",
"description": f'Hyper-V support (Windows 10/Server 2016 and above). Nested virtualization must be supported and enabled (Intel processor only)<br>The GNS3 VM can be <a href="{download_url}">downloaded here</a>',
"support_when_exit": True,
"support_headless": False,
"support_ram": True,
}
download_url = (
f"https://github.com/GNS3/gns3-gui/releases/download/v{__version__}/GNS3.VM.VirtualBox.{__version__}.zip"
)
virtualbox_info = {
"engine_id": "virtualbox",
"name": "VirtualBox",
"description": f'VirtualBox support. Nested virtualization for both Intel and AMD processors is supported since version 6.1<br>The GNS3 VM can be <a href="{download_url}">downloaded here</a>',
"support_when_exit": True,
"support_headless": True,
"support_ram": True,
}
remote_info = {
"engine_id": "remote",
"name": "Remote",
"description": "Use a remote GNS3 server as the GNS3 VM.",
"support_when_exit": False,
"support_headless": False,
"support_ram": False,
}
engines = [vmware_info, virtualbox_info, remote_info]
if sys.platform.startswith("win"):
engines.append(hyperv_info)
return engines
def current_engine(self):
return self._get_engine(self._settings["engine"])
@property
def engine(self):
return self._settings["engine"]
@property
def ip_address(self):
"""
Returns the GNS3 VM IP address.
:returns: VM IP address
"""
return self.current_engine().ip_address
@property
def running(self):
"""
Returns if the GNS3 VM is running.
:returns: Boolean
"""
return self.current_engine().running
@property
def user(self):
"""
Returns the GNS3 VM user.
:returns: VM user
"""
return self.current_engine().user
@property
def password(self):
"""
Returns the GNS3 VM password.
:returns: VM password
"""
return self.current_engine().password
@property
def port(self):
"""
Returns the GNS3 VM port.
:returns: VM port
"""
return self.current_engine().port
@property
def protocol(self):
"""
Returns the GNS3 VM protocol.
:returns: VM protocol
"""
return self.current_engine().protocol
@property
def enable(self):
"""
The GNSVM is activated
"""
return self._settings.get("enable", False)
@property
def when_exit(self):
"""
What should be done when exit
"""
return self._settings["when_exit"]
@property
def settings(self):
return self._settings
@settings.setter
def settings(self, val):
self._settings.update(val)
async def update_settings(self, settings):
"""
Update settings and will restart the VM if require
"""
new_settings = copy.copy(self._settings)
new_settings.update(settings)
if self.settings != new_settings:
try:
await self._stop()
finally:
self._settings = settings
self._controller.save()
if self.enable:
await self.start()
else:
# When user fix something on his system and try again
if self.enable and not self.current_engine().running:
await self.start()
def _get_engine(self, engine):
"""
Load an engine
"""
if engine in self._engines:
return self._engines[engine]
if engine == "vmware":
self._engines["vmware"] = VMwareGNS3VM(self._controller)
return self._engines["vmware"]
elif engine == "hyper-v":
self._engines["hyper-v"] = HyperVGNS3VM(self._controller)
return self._engines["hyper-v"]
elif engine == "virtualbox":
self._engines["virtualbox"] = VirtualBoxGNS3VM(self._controller)
return self._engines["virtualbox"]
elif engine == "remote":
self._engines["remote"] = RemoteGNS3VM(self._controller)
return self._engines["remote"]
raise NotImplementedError(f"The engine {engine} for the GNS3 VM is not supported")
def asdict(self):
return self._settings
@locking
async def list(self, engine):
"""
List VMS for an engine
"""
engine = self._get_engine(engine)
vms = []
try:
for vm in await engine.list():
vms.append({"vmname": vm["vmname"]})
except GNS3VMError as e:
# We raise error only if user activated the GNS3 VM
# otherwise you have noise when VMware is not installed
if self.enable:
raise e
return vms
async def auto_start_vm(self):
"""
Auto start the GNS3 VM if require
"""
if self.enable:
try:
await self.start()
except GNS3VMError as e:
# User will receive the error later when they will try to use the node
try:
compute = await self._controller.add_compute(
compute_id="vm", name=f"GNS3 VM ({self.current_engine().vmname})", host=None, force=True
)
compute.set_last_error(str(e))
except ControllerError:
pass
log.error(f"Cannot start the GNS3 VM: {e}")
async def exit_vm(self):
if self.enable:
try:
if self._settings["when_exit"] == "stop":
await self._stop()
elif self._settings["when_exit"] == "suspend":
await self._suspend()
except GNS3VMError as e:
log.warning(str(e))
@locking
async def start(self):
"""
Start the GNS3 VM
"""
engine = self.current_engine()
if not engine.running:
if self._settings["vmname"] is None:
return
log.info("Start the GNS3 VM")
engine.allocate_vcpus_ram = self._settings["allocate_vcpus_ram"]
engine.vmname = self._settings["vmname"]
engine.ram = self._settings["ram"]
engine.vcpus = self._settings["vcpus"]
engine.headless = self._settings["headless"]
engine.port = self._settings["port"]
compute = await self._controller.add_compute(
compute_id="vm", name=f"GNS3 VM is starting ({engine.vmname})", host=None, force=True, connect=False
)
try:
await engine.start()
except Exception as e:
await self._controller.delete_compute("vm")
log.error(f"Cannot start the GNS3 VM: {e!s}")
await compute.update(name=f"GNS3 VM ({engine.vmname})")
compute.set_last_error(str(e))
raise e
await compute.connect() # we can connect now that the VM has started
await compute.update(
name=f"GNS3 VM ({engine.vmname})",
protocol=self.protocol,
host=self.ip_address,
port=self.port,
user=self.user,
password=self.password,
)
# check if the VM is in the same subnet as the local server, start 10 seconds later to give
# some time for the compute in the VM to be ready for requests
asyncio.get_event_loop().call_later(10, lambda: asyncio.ensure_future(self._check_network(compute)))
async def _check_network(self, compute):
"""
Check that the VM is in the same subnet as the local server
"""
try:
vm_interfaces = await compute.interfaces()
vm_interface_netmask = None
for interface in vm_interfaces:
if interface["ip_address"] == self.ip_address:
vm_interface_netmask = interface["netmask"]
break
if vm_interface_netmask:
vm_network = ipaddress.ip_interface(f"{compute.host_ip}/{vm_interface_netmask}").network
for compute_id in self._controller.computes:
if compute_id == "local":
compute = self._controller.get_compute(compute_id)
interfaces = await compute.interfaces()
netmask = None
for interface in interfaces:
if interface["ip_address"] == compute.host_ip:
netmask = interface["netmask"]
break
if netmask:
compute_network = ipaddress.ip_interface(f"{compute.host_ip}/{netmask}").network
if vm_network.compare_networks(compute_network) != 0:
msg = f"The GNS3 VM (IP={self.ip_address}, NETWORK={vm_network}) is not on the same network as the {compute_id} server (IP={compute.host_ip}, NETWORK={compute_network}), please make sure the local server binding is in the same network as the GNS3 VM"
self._controller.notification.controller_emit("log.warning", {"message": msg})
except ComputeError as e:
log.warning(f"Could not check the VM is in the same subnet as the local server: {e}")
except ControllerError as e:
log.warning(f"Could not check the VM is in the same subnet as the local server: {e}")
@locking
async def _suspend(self):
"""
Suspend the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
await self._controller.delete_compute("vm")
if engine.running:
log.info("Suspend the GNS3 VM")
await engine.suspend()
@locking
async def _stop(self):
"""
Stop the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
await self._controller.delete_compute("vm")
if engine.running:
log.info("Stop the GNS3 VM")
await engine.stop()
@@ -1,303 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 logging
import psutil
log = logging.getLogger(__name__)
class BaseGNS3VM:
def __init__(self, controller):
self._controller = controller
self._vmname = None
self._ip_address = None
self._port = 80 # value not used, will be overwritten
self._headless = False
self._allocate_vcpus_ram = True
self._vcpus = 1
self._ram = 1024
self._user = ""
self.password = ""
self._protocol = "http"
self._running = False
# limit the number of vCPUs to the number of physical cores (hyper thread CPUs are excluded)
# because this is likely to degrade performances.
self._vcpus = psutil.cpu_count(logical=False)
# we want to allocate half of the available physical memory
# ram = int(psutil.virtual_memory().total / (1024 * 1024) / 2)
# value must be a multiple of 4 (VMware requirement)
# ram -= ram % 4
ram = 2048
self._ram = ram
@property
def vmname(self):
"""
Returns the GNS3 VM name.
:returns: VM name
"""
return self._vmname
@vmname.setter
def vmname(self, new_name):
"""
Sets the GNS3 VM name
:param new_name: new VM name
"""
self._vmname = new_name
@property
def protocol(self):
"""
Get the GNS3 VM protocol
:returns: Protocol as string
"""
return self._protocol
@protocol.setter
def protocol(self, val):
"""
Sets the GNS3 VM protocol
:param val: new VM protocol
"""
self._protocol = val
@property
def user(self):
"""
Get the GNS3 VM user
:returns: User as string
"""
return self._user
@user.setter
def user(self, val):
"""
Sets the GNS3 VM user
:param val: new VM user
"""
self._user = val
@property
def password(self):
"""
Get the GNS3 VM password
:returns: Password as string
"""
return self._password
@password.setter
def password(self, val):
"""
Sets the GNS3 VM password
:param val: new VM password
"""
self._password = val
@property
def port(self):
"""
Returns the GNS3 VM port.
:returns: VM port
"""
return self._port
@port.setter
def port(self, new_port):
"""
Sets the GNS3 VM port
:param new_port: new VM port
"""
self._port = new_port
@property
def ip_address(self):
"""
Returns the GNS3 VM IP address.
:returns: VM IP address
"""
return self._ip_address
@ip_address.setter
def ip_address(self, new_ip_address):
"""
Sets the GNS3 VM IP address.
:param new_ip_address: new VM IP address
"""
self._ip_address = new_ip_address
@property
def running(self):
"""
Returns whether the GNS3 VM is running or not.
:returns: boolean
"""
return self._running
@running.setter
def running(self, value):
"""
Sets whether the GNS3 VM is running or not.
:param value: boolean
"""
self._running = value
@property
def headless(self):
"""
Returns whether the GNS3 VM is headless or not.
:returns: boolean
"""
return self._headless
@headless.setter
def headless(self, value):
"""
Sets whether the GNS3 VM is headless or not.
:param value: boolean
"""
self._headless = value
@property
def allocate_vcpus_ram(self):
"""
Returns whether VCPUs and RAM settings should be configured for the GNS3 VM.
:returns: boolean
"""
return self._allocate_vcpus_ram
@allocate_vcpus_ram.setter
def allocate_vcpus_ram(self, value):
"""
Sets whether VCPUs and RAM settings should be configured for the GNS3 VM.
:param value: boolean
"""
self._allocate_vcpus_ram = value
@property
def vcpus(self):
"""
Returns the number of allocated vCPUs.
:returns: number of vCPUs.
"""
return self._vcpus
@vcpus.setter
def vcpus(self, new_vcpus):
"""
Sets the number of allocated vCPUs.
:param new_vcpus: new number of vCPUs.
"""
self._vcpus = new_vcpus
@property
def ram(self):
"""
Returns the amount of allocated RAM.
:returns: number of vCPUs.
"""
return self._ram
@ram.setter
def ram(self, new_ram):
"""
Sets the amount of allocated RAM.
:param new_ram: new amount of RAM.
"""
self._ram = new_ram
@property
def engine(self):
"""
Returns the engine (virtualization technology used to run the GNS3 VM).
:returns: engine name
"""
return self._engine
async def list(self):
"""
List all VMs
"""
raise NotImplementedError
async def start(self):
"""
Starts the GNS3 VM.
"""
raise NotImplementedError
async def suspend(self):
"""
Suspend the GNS3 VM.
"""
raise NotImplementedError
async def stop(self):
"""
Stops the GNS3 VM.
"""
raise NotImplementedError
@@ -1,28 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class GNS3VMError(Exception):
def __init__(self, message):
super().__init__(message)
self._message = message
def __repr__(self):
return self._message
def __str__(self):
return f"GNS3VM: {self._message}"
@@ -1,346 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2018 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 asyncio
import ipaddress
import logging
import sys
import psutil
from .base_gns3_vm import BaseGNS3VM
from .gns3_vm_error import GNS3VMError
log = logging.getLogger(__name__)
class HyperVGNS3VM(BaseGNS3VM):
_HYPERV_VM_STATE_ENABLED = 2
_HYPERV_VM_STATE_DISABLED = 3
_HYPERV_VM_STATE_SHUTDOWN = 4
_HYPERV_VM_STATE_PAUSED = 9
_WMI_JOB_STATUS_STARTED = 4096
_WMI_JOB_STATE_RUNNING = 4
_WMI_JOB_STATE_COMPLETED = 7
def __init__(self, controller):
self._engine = "hyper-v"
super().__init__(controller)
self._conn = None
self._vm = None
self._management = None
self._wmi = None
def _check_requirements(self):
"""
Checks if the GNS3 VM can run on Hyper-V.
"""
if not sys.platform.startswith("win"):
raise GNS3VMError("Hyper-V is only supported on Windows")
if sys.getwindowsversion().platform_version[0] < 10:
raise GNS3VMError(
f"Windows 10/Windows Server 2016 or a later version is required to run Hyper-V with nested virtualization enabled (version {sys.getwindowsversion().platform_version[0]} detected)"
)
is_windows_10 = (
sys.getwindowsversion().platform_version[0] == 10 and sys.getwindowsversion().platform_version[1] == 0
)
if is_windows_10 and sys.getwindowsversion().platform_version[2] < 14393:
raise GNS3VMError(
"Hyper-V with nested virtualization is only supported on Windows 10 Anniversary Update (build 10.0.14393) or later"
)
try:
import pythoncom
pythoncom.CoInitialize()
import wmi
self._wmi = wmi
conn = self._wmi.WMI()
except self._wmi.x_wmi as e:
raise GNS3VMError(f"Could not connect to WMI: {e}")
if not conn.Win32_ComputerSystem()[0].HypervisorPresent:
raise GNS3VMError("Hyper-V is not installed or activated")
if conn.Win32_Processor()[0].Manufacturer != "GenuineIntel":
if is_windows_10 and conn.Win32_Processor()[0].Manufacturer == "AuthenticAMD":
if sys.getwindowsversion().platform_version[2] < 19640:
raise GNS3VMError(
"Windows 10 (build 10.0.19640) or later is required by Hyper-V to support nested virtualization with AMD processors"
)
else:
raise GNS3VMError(
"An Intel processor is required by Hyper-V to support nested virtualization on this version of Windows"
)
# This is not reliable
# if not conn.Win32_Processor()[0].VirtualizationFirmwareEnabled:
# raise GNS3VMError("Nested Virtualization (VT-x) is not enabled on this system")
def _connect(self):
"""
Connects to local host using WMI.
"""
self._check_requirements()
try:
self._conn = self._wmi.WMI(namespace=r"root\virtualization\v2")
except self._wmi.x_wmi as e:
raise GNS3VMError(f"Could not connect to WMI: {e}")
if not self._conn.Msvm_VirtualSystemManagementService():
raise GNS3VMError("The Windows account running GNS3 does not have the required permissions for Hyper-V")
self._management = self._conn.Msvm_VirtualSystemManagementService()[0]
def _find_vm(self, vm_name):
"""
Finds a Hyper-V VM.
"""
if self._conn is None:
self._connect()
vms = self._conn.Msvm_ComputerSystem(ElementName=vm_name)
nb_vms = len(vms)
if nb_vms == 0:
return None
elif nb_vms > 1:
raise GNS3VMError(f"Duplicate VM name found for {vm_name}")
else:
return vms[0]
def _is_running(self):
"""
Checks if the VM is running.
"""
if self._vm is not None and self._vm.EnabledState == HyperVGNS3VM._HYPERV_VM_STATE_ENABLED:
return True
return False
def _get_vm_setting_data(self, vm):
"""
Gets the VM settings.
:param vm: VM instance
"""
vm_settings = vm.associators(wmi_result_class="Msvm_VirtualSystemSettingData")
return [s for s in vm_settings if s.VirtualSystemType == "Microsoft:Hyper-V:System:Realized"][0]
def _get_vm_resources(self, vm, resource_class):
"""
Gets specific VM resource.
:param vm: VM instance
:param resource_class: resource class name
"""
setting_data = self._get_vm_setting_data(vm)
return setting_data.associators(wmi_result_class=resource_class)
def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
"""
available_vcpus = psutil.cpu_count(logical=False)
if vcpus > available_vcpus:
raise GNS3VMError(
f"You have allocated too many vCPUs for the GNS3 VM! (max available is {available_vcpus} vCPUs)"
)
try:
mem_settings = self._get_vm_resources(self._vm, "Msvm_MemorySettingData")[0]
cpu_settings = self._get_vm_resources(self._vm, "Msvm_ProcessorSettingData")[0]
mem_settings.VirtualQuantity = ram
mem_settings.Reservation = ram
mem_settings.Limit = ram
self._management.ModifyResourceSettings(ResourceSettings=[mem_settings.GetText_(1)])
cpu_settings.VirtualQuantity = vcpus
cpu_settings.Reservation = vcpus
cpu_settings.Limit = 100000 # use 100% of CPU
cpu_settings.ExposeVirtualizationExtensions = True # allow the VM to use nested virtualization
self._management.ModifyResourceSettings(ResourceSettings=[cpu_settings.GetText_(1)])
log.info(f"GNS3 VM vCPU count set to {vcpus} and RAM amount set to {ram}")
except Exception as e:
raise GNS3VMError(f"Could not set to {vcpus} and RAM amount set to {ram}: {e}")
async def list(self):
"""
List all Hyper-V VMs
"""
if self._conn is None or self._management is None:
self._connect()
vms = []
try:
for vm in self._conn.Msvm_ComputerSystem():
if vm.ElementName != self._management.SystemName:
vms.append({"vmname": vm.ElementName})
except self._wmi.x_wmi as e:
raise GNS3VMError(f"Could not list Hyper-V VMs: {e}")
return vms
def _get_wmi_obj(self, path):
"""
Gets the WMI object.
"""
return self._wmi.WMI(moniker=path.replace("\\", "/"))
async def _set_state(self, state):
"""
Set the desired state of the VM
"""
if not self._vm:
self._vm = self._find_vm(self.vmname)
if not self._vm:
raise GNS3VMError(f"Could not find Hyper-V VM {self.vmname}")
job_path, ret = self._vm.RequestStateChange(state)
if ret == HyperVGNS3VM._WMI_JOB_STATUS_STARTED:
job = self._get_wmi_obj(job_path)
while job.JobState == HyperVGNS3VM._WMI_JOB_STATE_RUNNING:
await asyncio.sleep(0.1)
job = self._get_wmi_obj(job_path)
if job.JobState != HyperVGNS3VM._WMI_JOB_STATE_COMPLETED:
raise GNS3VMError(f"Error while changing state: {job.ErrorSummaryDescription}")
elif ret != 0 or ret != 32775:
raise GNS3VMError(f"Failed to change state to {state}")
async def _is_vm_network_active(self):
"""
Check if WMI is updated with VM virtual network adapters
and wait until their count becomes > 0
ProtocolIFType Unknown (0)
Other (1)
IPv4 (4096)
IPv6 (4097)
IPv4/v6 (4098)
"""
wql = (
"SELECT * FROM Msvm_GuestNetworkAdapterConfiguration WHERE InstanceID like \
'Microsoft:GuestNetwork\\"
+ self._vm.Name
+ "%' and ProtocolIFType > 0 "
)
nic_count = len(self._conn.query(wql))
while nic_count == 0:
await asyncio.sleep(0.1) # 100ms
nic_count = len(self._conn.query(wql))
async def start(self):
"""
Starts the GNS3 VM.
"""
self._vm = self._find_vm(self.vmname)
if not self._vm:
raise GNS3VMError(f"Could not find Hyper-V VM {self.vmname}")
if not self._is_running():
if self.allocate_vcpus_ram:
log.info("Update GNS3 VM settings (CPU and RAM)")
# set the number of vCPUs and amount of RAM
self._set_vcpus_ram(self.vcpus, self.ram)
# start the VM
try:
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_ENABLED)
except GNS3VMError as e:
raise GNS3VMError(f"Failed to start the GNS3 VM: {e}")
log.info("GNS3 VM has been started")
# check if VM network is active
await self._is_vm_network_active()
# Get the guest IP address
# LIS (Linux Integration Services) must be installed on the guest
# See https://oitibs.com/hyper-v-lis-on-ubuntu-18-04/ for details.
trial = 120
guest_ip_address = ""
log.info("Waiting for GNS3 VM IP")
ports = self._get_vm_resources(self._vm, "Msvm_EthernetPortAllocationSettingData")
vnics = self._get_vm_resources(self._vm, "Msvm_SyntheticEthernetPortSettingData")
while True:
for port in ports:
try:
vnic = [v for v in vnics if port.Parent == v.path_()][0]
except IndexError:
continue
config = vnic.associators(wmi_result_class="Msvm_GuestNetworkAdapterConfiguration")
ip_addresses = config[0].IPAddresses
for ip_address in ip_addresses:
# take the first valid IPv4 address
try:
ipaddress.IPv4Address(ip_address)
guest_ip_address = ip_address
except ipaddress.AddressValueError:
continue
if len(ip_addresses):
guest_ip_address = ip_addresses[0]
break
trial -= 1
if guest_ip_address:
break
elif trial == 0:
raise GNS3VMError(f"Could not find guest IP address for {self.vmname}")
await asyncio.sleep(1)
self.ip_address = guest_ip_address
log.info(f"GNS3 VM IP address set to {guest_ip_address}")
self.running = True
async def suspend(self):
"""
Suspends the GNS3 VM.
"""
try:
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_PAUSED)
except GNS3VMError as e:
raise GNS3VMError(f"Failed to suspend the GNS3 VM: {e}")
log.info("GNS3 VM has been suspended")
self.running = False
async def stop(self):
"""
Stops the GNS3 VM.
"""
try:
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_SHUTDOWN)
except GNS3VMError as e:
raise GNS3VMError(f"Failed to stop the GNS3 VM: {e}")
log.info("GNS3 VM has been stopped")
self.running = False
@@ -1,72 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 logging
from .base_gns3_vm import BaseGNS3VM
from .gns3_vm_error import GNS3VMError
log = logging.getLogger(__name__)
class RemoteGNS3VM(BaseGNS3VM):
def __init__(self, controller):
self._engine = "remote"
super().__init__(controller)
async def list(self):
"""
List all VMs
"""
res = []
for compute in self._controller.computes.values():
if compute.id not in ["local", "vm"]:
res.append({"vmname": compute.name})
return res
async def start(self):
"""
Starts the GNS3 VM.
"""
if not self.vmname:
return
for compute in self._controller.computes.values():
if compute.name == self.vmname:
self.running = True
self.protocol = compute.protocol
self.ip_address = compute.host
self.port = compute.port
self.user = compute.user
self.password = compute.password
return
raise GNS3VMError(f"Can't start the GNS3 VM remote VM {self.vmname} not found")
async def suspend(self):
"""
Suspend do nothing for remote server
"""
self.running = False
async def stop(self):
"""
Stops the GNS3 VM.
"""
self.running = False
@@ -1,509 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 asyncio
import ipaddress
import logging
import re
import socket
import sys
import aiohttp
from gns3server.utils import parse_version
from gns3server.utils.asyncio import wait_run_in_executor
from gns3server.utils.http_client import HTTPClient
from ...compute.virtualbox import VirtualBox, VirtualBoxError
from .base_gns3_vm import BaseGNS3VM
from .gns3_vm_error import GNS3VMError
log = logging.getLogger(__name__)
class VirtualBoxGNS3VM(BaseGNS3VM):
def __init__(self, controller):
self._engine = "virtualbox"
super().__init__(controller)
self._system_properties = {}
self._virtualbox_manager = VirtualBox()
async def _execute(self, subcommand, args, timeout=60): # noqa: ASYNC109 - operation-specific timeout is intentional
try:
result = await self._virtualbox_manager.execute(subcommand, args, timeout)
return "\n".join(result)
except VirtualBoxError as e:
raise GNS3VMError(f"Error while executing VBoxManage command: {e}")
async def _get_state(self):
"""
Returns the VM state (e.g. running, paused etc.)
:returns: state (string)
"""
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if "=" in info:
name, value = info.split("=", 1)
if name == "VMState":
return value.strip('"')
return "unknown"
async def _get_system_properties(self):
"""
Returns the VM state (e.g. running, paused etc.)
:returns: state (string)
"""
properties = await self._execute("list", ["systemproperties"])
for prop in properties.splitlines():
try:
name, value = prop.split(":", 1)
except ValueError:
continue
self._system_properties[name.strip()] = value.strip()
async def _check_requirements(self):
"""
Checks if the GNS3 VM can run on VirtualBox
"""
if not self._system_properties:
await self._get_system_properties()
if "API version" not in self._system_properties:
raise VirtualBoxError(f"Can't access to VirtualBox API version:\n{self._system_properties}")
from cpuinfo import get_cpu_info
cpu_info = await wait_run_in_executor(get_cpu_info)
vendor_id = cpu_info.get("vendor_id_raw")
if vendor_id == "GenuineIntel":
if parse_version(self._system_properties["API version"]) < parse_version("6_1"):
raise VirtualBoxError(
"VirtualBox version 6.1 or above is required to run the GNS3 VM with nested virtualization enabled on Intel processors"
)
elif vendor_id == "AuthenticAMD":
if parse_version(self._system_properties["API version"]) < parse_version("6_0"):
raise VirtualBoxError(
"VirtualBox version 6.0 or above is required to run the GNS3 VM with nested virtualization enabled on AMD processors"
)
else:
log.warning(f"Could not determine CPU vendor: {vendor_id}")
async def _look_for_interface(self, network_backend):
"""
Look for an interface with a specific network backend.
:returns: interface number or -1 if none is found
"""
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
interface = -1
for info in result.splitlines():
if "=" in info:
name, value = info.split("=", 1)
if name.startswith("nic") and value.strip('"') == network_backend:
try:
interface = int(name[3:])
break
except ValueError:
continue
return interface
async def _look_for_vboxnet(self, backend_type, interface_number):
"""
Look for the VirtualBox network name associated with an interface.
:returns: None or vboxnet name
"""
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if "=" in info:
name, value = info.split("=", 1)
if name == f"{backend_type}{interface_number}":
return value.strip('"')
return None
async def _check_dhcp_server(self, vboxnet):
"""
Check if the DHCP server associated with a vboxnet is enabled.
:param vboxnet: vboxnet name
:returns: boolean
"""
properties = await self._execute("list", ["dhcpservers"])
flag_dhcp_server_found = False
for prop in properties.splitlines():
try:
name, value = prop.split(":", 1)
except ValueError:
continue
if name.strip() == "NetworkName" and value.strip().endswith(vboxnet):
flag_dhcp_server_found = True
if flag_dhcp_server_found and name.strip() == "Enabled":
if value.strip() == "Yes":
return True
return False
async def _add_dhcp_server(self, vboxnet):
"""
Add a DHCP server for vboxnet.
:param vboxnet: vboxnet name
"""
hostonlyifs = await self._execute("list", ["hostonlyifs"])
pattern = r"IPAddress:\s+(\d+\.\d+\.\d+\.\d+)\nNetworkMask:\s+(\d+\.\d+\.\d+\.\d+)"
match = re.search(pattern, hostonlyifs)
if match:
ip_address = match.group(1)
netmask = match.group(2)
else:
raise GNS3VMError(f"Could not find IP address and netmask for vboxnet {vboxnet}")
try:
interface = ipaddress.IPv4Interface(f"{ip_address}/{netmask}")
subnet = ipaddress.IPv4Network(str(interface.network))
dhcp_server_ip = str(interface.ip + 1)
netmask = str(subnet.netmask)
lower_ip = str(interface.ip + 2)
upper_ip = str(subnet.network_address + subnet.num_addresses - 2)
except ValueError:
raise GNS3VMError(f"Invalid IP address and netmask for vboxnet {vboxnet}: {ip_address}/{netmask}")
dhcp_server_args = [
"add",
f"--network=HostInterfaceNetworking-{vboxnet}",
f"--server-ip={dhcp_server_ip}",
f"--netmask={netmask}",
f"--lower-ip={lower_ip}",
f"--upper-ip={upper_ip}",
"--enable",
]
await self._execute("dhcpserver", dhcp_server_args)
async def _check_vboxnet_exists(self, vboxnet, vboxnet_type):
"""
Check if the vboxnet interface exists
:param vboxnet: vboxnet name
:returns: boolean
"""
properties = await self._execute("list", [f"{vboxnet_type}"])
for prop in properties.splitlines():
try:
name, value = prop.split(":", 1)
except ValueError:
continue
if name.strip() == "Name" and value.strip() == vboxnet:
return True
return False
async def _find_first_available_vboxnet(self):
"""
Find the first available vboxnet.
"""
properties = await self._execute("list", ["hostonlyifs"])
for prop in properties.splitlines():
try:
name, value = prop.split(":", 1)
except ValueError:
continue
if name.strip() == "Name":
return value.strip()
return None
async def _check_vbox_port_forwarding(self):
"""
Checks if the NAT port forwarding rule exists.
:returns: boolean
"""
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if "=" in info:
name, value = info.split("=", 1)
if name.startswith("Forwarding") and value.strip('"').startswith("GNS3VM"):
return True
return False
async def list(self):
"""
List all VirtualBox VMs
"""
try:
await self._check_requirements()
return await self._virtualbox_manager.list_vms()
except VirtualBoxError as e:
raise GNS3VMError(f"Could not list VirtualBox VMs: {e!s}")
async def start(self):
"""
Start the GNS3 VM.
"""
await self._check_requirements()
# get a NAT interface number
nat_interface_number = await self._look_for_interface("nat")
if nat_interface_number < 0 and await self._look_for_interface("natnetwork") < 0:
raise GNS3VMError(
f'VM "{self.vmname}" must have a NAT interface or NAT Network configured in order to start'
)
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(
f'VM "{self.vmname}" must have a network adapter attached to a {backend_description} in order to start'
)
vboxnet = await self._look_for_vboxnet(backend_type, interface_number)
if vboxnet is None:
raise GNS3VMError(
f'A VirtualBox host-only network could not be found on network adapter {interface_number} for "{self._vmname}"'
)
if not (await self._check_vboxnet_exists(vboxnet, vboxnet_type)):
if sys.platform.startswith("win") and vboxnet == "vboxnet0":
# The GNS3 VM is configured with vboxnet0 by default which is not available
# on Windows. Try to patch this with the first available vboxnet we find.
first_available_vboxnet = await self._find_first_available_vboxnet()
if first_available_vboxnet is None:
raise GNS3VMError(
f'Please add a VirtualBox host-only network with DHCP enabled and attached it to network adapter {interface_number} for "{self._vmname}"'
)
await self.set_hostonly_network(interface_number, first_available_vboxnet)
vboxnet = first_available_vboxnet
else:
try:
await self._execute("hostonlyif", ["create"])
except GNS3VMError:
raise GNS3VMError(
f'VirtualBox host-only network "{vboxnet}" does not exist and could not be automatically created, please make the sure the network adapter {interface_number} configuration is valid for "{self._vmname}"'
)
if backend_type == "hostonlyadapter" and not (await self._check_dhcp_server(vboxnet)):
try:
await self._add_dhcp_server(vboxnet)
except GNS3VMError as e:
raise GNS3VMError(f"Could not add DHCP server for vboxnet {vboxnet}: {e}, please configure manually")
vm_state = await self._get_state()
log.info(f'"{self._vmname}" state is {vm_state}')
if vm_state == "poweroff":
if self.allocate_vcpus_ram:
log.info("Update GNS3 VM vCPUs and RAM settings")
await self.set_vcpus(self.vcpus)
await self.set_ram(self.ram)
log.info("Update GNS3 VM Hardware Virtualization setting")
await self.enable_nested_hw_virt()
if vm_state in ("poweroff", "saved"):
# start the VM if it is not running
args = [self._vmname]
if self._headless:
args.extend(["--type", "headless"])
await self._execute("startvm", args)
elif vm_state == "paused":
args = [self._vmname, "resume"]
await self._execute("controlvm", args)
log.info("Retrieving IP address from GNS3 VM...")
ip = await self._get_ip_from_guest_property()
if ip:
self.ip_address = ip
else:
# if we can't get the IP address from the guest property, we try to get it from the GNS3 server (a NAT interface is required)
if nat_interface_number < 0:
raise GNS3VMError(f"Could not find guest IP address for {self.vmname}")
log.warning("Could not find IP address from guest property, trying to get it from GNS3 server")
ip_address = "127.0.0.1"
try:
# get a random port on localhost
with socket.socket() as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip_address, 0))
api_port = s.getsockname()[1]
except OSError as e:
raise GNS3VMError(f"Error while getting random port: {e}")
if await self._check_vbox_port_forwarding():
# delete the GNS3VM NAT port forwarding rule if it exists
log.info(f"Removing GNS3VM NAT port forwarding rule from interface {nat_interface_number}")
await self._execute("controlvm", [self._vmname, f"natpf{nat_interface_number}", "delete", "GNS3VM"])
# add a GNS3VM NAT port forwarding rule to redirect 127.0.0.1 with random port to the port in the VM
log.info(f"Adding GNS3VM NAT port forwarding rule with port {api_port} to interface {nat_interface_number}")
await self._execute(
"controlvm",
[
self._vmname,
f"natpf{nat_interface_number}",
f"GNS3VM,tcp,{ip_address},{api_port},,{self.port}",
],
)
self.ip_address = await self._get_ip_from_server(interface_number, api_port)
log.info(f"GNS3 VM has been started with IP '{self.ip_address}'")
self.running = True
async def _get_ip_from_guest_property(self):
"""
Get the IP from VirtualBox by retrieving the guest property (Guest Additions must be installed).
"""
remaining_try = 180 # try for 3 minutes
while remaining_try > 0:
result = await self._execute("guestproperty", ["get", self._vmname, "/VirtualBox/GuestInfo/Net/0/V4/IP"])
for info in result.splitlines():
if ":" in info:
name, value = info.split(":", 1)
if name == "Value":
return value.strip()
remaining_try -= 1
await asyncio.sleep(1)
return None
async def _get_ip_from_server(self, hostonly_interface_number, api_port):
"""
Get the IP from VirtualBox by sending a request to the GNS3 server.
Due to VirtualBox limitation the only way is to send request each
second to a GNS3 endpoint in order to get the list of the interfaces and
their IP and after that match it with VirtualBox host only.
"""
remaining_try = 180 # try for 3 minutes
while remaining_try > 0:
try:
async with HTTPClient.get(f"http://127.0.0.1:{api_port}/v3/compute/network/interfaces") as resp:
if resp.status < 300:
try:
json_data = await resp.json()
if json_data:
for interface in json_data:
if (
"name" in interface
and interface["name"] == f"eth{hostonly_interface_number - 1}"
):
if "ip_address" in interface and len(interface["ip_address"]) > 0:
return interface["ip_address"]
except ValueError:
pass
except (OSError, aiohttp.ClientError, TimeoutError):
pass
remaining_try -= 1
await asyncio.sleep(1)
raise GNS3VMError(f"Could not find guest IP address for {self.vmname}")
async def suspend(self):
"""
Suspend the GNS3 VM.
"""
await self._execute("controlvm", [self._vmname, "savestate"], timeout=3)
log.info("GNS3 VM has been suspend")
self.running = False
async def stop(self):
"""
Stops the GNS3 VM.
"""
vm_state = await self._get_state()
if vm_state == "poweroff":
self.running = False
return
await self._execute("controlvm", [self._vmname, "acpipowerbutton"], timeout=3)
trial = 120
while True:
try:
vm_state = await self._get_state()
# During a small amount of time the command will fail
except GNS3VMError:
vm_state = "running"
if vm_state == "poweroff":
break
trial -= 1
if trial == 0:
await self._execute("controlvm", [self._vmname, "poweroff"], timeout=3)
break
await asyncio.sleep(1)
log.info("GNS3 VM has been stopped")
self.running = False
async def set_vcpus(self, vcpus):
"""
Set the number of vCPU cores for the GNS3 VM.
:param vcpus: number of vCPU cores
"""
await self._execute("modifyvm", [self._vmname, "--cpus", str(vcpus)], timeout=3)
log.info(f"GNS3 VM vCPU count set to {vcpus}")
async def set_ram(self, ram):
"""
Set the RAM amount for the GNS3 VM.
:param ram: amount of memory
"""
await self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
log.info(f"GNS3 VM RAM amount set to {ram}")
async def enable_nested_hw_virt(self):
"""
Enable nested hardware virtualization for the GNS3 VM.
"""
await self._execute("modifyvm", [self._vmname, "--nested-hw-virt", "on"], timeout=3)
log.info("Nested hardware virtualization enabled")
async def set_hostonly_network(self, adapter_number, hostonly_network_name):
"""
Set a VirtualBox host-only network on a network adapter for the GNS3 VM.
:param adapter_number: network adapter number
:param hostonly_network_name: name of the VirtualBox host-only network
"""
await self._execute(
"modifyvm", [self._vmname, f"--hostonlyadapter{adapter_number}", hostonly_network_name], timeout=3
)
log.info(
f'VirtualBox host-only network "{hostonly_network_name}" set on network adapter {adapter_number} for "{self._vmname}"'
)
@@ -1,217 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 asyncio
import logging
import os
import psutil
from gns3server.compute.vmware import VMware, VMwareError
from .base_gns3_vm import BaseGNS3VM
from .gns3_vm_error import GNS3VMError
log = logging.getLogger(__name__)
class VMwareGNS3VM(BaseGNS3VM):
def __init__(self, controller):
self._engine = "vmware"
super().__init__(controller)
self._vmware_manager = VMware()
self._vmx_path = None
@property
def vmx_path(self):
return self._vmx_path
async def _execute(self, subcommand, args, timeout=60, log_level=logging.INFO): # noqa: ASYNC109 - operation-specific timeout is intentional
try:
result = await self._vmware_manager.execute(subcommand, args, timeout, log_level=log_level)
return "".join(result)
except VMwareError as e:
raise GNS3VMError(f"Error while executing VMware command: {e}")
async def _is_running(self):
result = await self._vmware_manager.execute("list", [])
if self._vmx_path in result:
return True
return False
async def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
"""
# memory must be a multiple of 4 (VMware requirement)
if ram % 4 != 0:
raise GNS3VMError(f"Allocated memory {ram} for the GNS3 VM must be a multiple of 4")
available_vcpus = psutil.cpu_count(logical=True)
if not float(vcpus).is_integer():
raise GNS3VMError(f"The allocated vCPUs value is not an integer: {vcpus}")
if vcpus > available_vcpus:
raise GNS3VMError(
f"You have allocated too many vCPUs for the GNS3 VM! (max available is {available_vcpus} vCPUs)"
)
try:
pairs = VMware.parse_vmware_file(self._vmx_path)
if vcpus > 1:
pairs["numvcpus"] = str(vcpus)
cores_per_sockets = int(vcpus / psutil.cpu_count(logical=False))
if cores_per_sockets > 1:
pairs["cpuid.corespersocket"] = str(cores_per_sockets)
pairs["memsize"] = str(ram)
VMware.write_vmx_file(self._vmx_path, pairs)
log.info(f"GNS3 VM vCPU count set to {vcpus} and RAM amount set to {ram}")
except OSError as e:
raise GNS3VMError(f'Could not read/write VMware VMX file "{self._vmx_path}": {e}')
async def _set_extra_options(self):
try:
"""
Due to bug/change in VMWare 14 we're not able to pass Hardware Virtualization in GNS3VM.
We only enable this when it's not present in current configuration and user hasn't deactivated that.
"""
extra_config = (("vhv.enable", "TRUE"),)
pairs = VMware.parse_vmware_file(self._vmx_path)
updated = False
for key, value in extra_config:
if key not in pairs.keys():
pairs[key] = value
updated = True
log.info(f"GNS3 VM VMX `{key}` set to `{value}`")
if updated:
VMware.write_vmx_file(self._vmx_path, pairs)
log.info("GNS3 VM VMX has been updated.")
except OSError as e:
raise GNS3VMError(f'Could not read/write VMware VMX file "{self._vmx_path}": {e}')
async def list(self):
"""
List all VMware VMs
"""
try:
return await self._vmware_manager.list_vms()
except VMwareError as e:
raise GNS3VMError(f"Could not list VMware VMs: {e!s}")
async def start(self):
"""
Starts the GNS3 VM.
"""
vms = await self.list()
for vm in vms:
if vm["vmname"] == self.vmname:
self._vmx_path = vm["vmx_path"]
break
# check we have a valid VMX file path
if not self._vmx_path:
raise GNS3VMError(f"VMWare VM {self.vmname} not found")
if not os.path.exists(self._vmx_path):
raise GNS3VMError(f"VMware VMX file {self._vmx_path} doesn't exist")
# check if the VMware guest tools are installed
vmware_tools_state = await self._execute("checkToolsState", [self._vmx_path])
if vmware_tools_state not in ("installed", "running"):
raise GNS3VMError(f"VMware tools are not installed in {self.vmname}")
try:
running = await self._is_running()
except VMwareError as e:
raise GNS3VMError(f"Could not list VMware VMs: {e!s}")
if not running:
# set the number of vCPUs and amount of RAM
if self.allocate_vcpus_ram:
log.info("Update GNS3 VM vCPUs and RAM settings")
await self._set_vcpus_ram(self.vcpus, self.ram)
log.info("Update GNS3 VM Hardware Virtualization setting")
await self._set_extra_options()
# start the VM
args = [self._vmx_path]
if self._headless:
args.extend(["nogui"])
await self._execute("start", args)
log.info("GNS3 VM has been started")
# get the guest IP address (first adapter only)
trial = 120
guest_ip_address = ""
log.info("Waiting for GNS3 VM IP")
while True:
try:
guest_ip_address = await self._execute(
"readVariable", [self._vmx_path, "guestVar", "gns3.eth0"], timeout=120, log_level=logging.DEBUG
)
guest_ip_address = guest_ip_address.strip()
if len(guest_ip_address) != 0:
break
trial -= 1
# If IP address not found then fallback an old method
if trial == 0:
log.warning("No IP found for the VM via readVariable fallback to getGuestIPAddress")
guest_ip_address = await self._execute("getGuestIPAddress", [self._vmx_path, "-wait"], timeout=120)
break
except GNS3VMError as e:
log.debug(f"{e}")
await asyncio.sleep(1)
if not guest_ip_address:
raise GNS3VMError(f"Could not find guest IP address for {self.vmname}")
self.ip_address = guest_ip_address
log.info(f"GNS3 VM IP address set to {guest_ip_address}")
self.running = True
async def suspend(self):
"""
Suspend the GNS3 VM.
"""
if self._vmx_path is None:
raise GNS3VMError("No VMX path configured, can't suspend the VM")
try:
await self._execute("suspend", [self._vmx_path])
except GNS3VMError as e:
log.warning(f"Error when suspending the VM: {e!s}")
log.info("GNS3 VM has been suspended")
self.running = False
async def stop(self):
"""
Stops the GNS3 VM.
"""
if self._vmx_path is None:
raise GNS3VMError("No VMX path configured, can't stop the VM")
try:
await self._execute("stop", [self._vmx_path, "soft"])
except GNS3VMError as e:
log.warning(f"Error when stopping the VM: {e!s}")
log.info("GNS3 VM has been stopped")
self.running = False
+11 -19
View File
@@ -21,7 +21,6 @@ import logging
import os
import shutil
import stat
import sys
import tempfile
import uuid
@@ -131,26 +130,19 @@ async def import_project(
# Modify the compute id of the node depending on compute capacity
if not keep_compute_ids:
# For some VM type we move them to the GNS3 VM if possible
# unless it's a linux host without GNS3 VM
if not sys.platform.startswith("linux") or controller.has_compute("vm"):
# Round-robin through available compute resources.
# Only use computes that are connected to avoid import failures
available_computes = {
compute_id: compute for compute_id, compute in controller.computes.items() if compute.connected
}
if available_computes:
compute_nodes = itertools.cycle(available_computes)
for node in topology["topology"]["nodes"]:
if node["node_type"] in ("docker", "qemu", "iou", "nat"):
node["compute_id"] = "vm"
node["compute_id"] = next(compute_nodes)
else:
# Round-robin through available compute resources.
# Only use computes that are connected to avoid import failures
available_computes = {
compute_id: compute for compute_id, compute in controller.computes.items() if compute.connected
}
if available_computes:
compute_nodes = itertools.cycle(available_computes)
for node in topology["topology"]["nodes"]:
node["compute_id"] = next(compute_nodes)
else:
# No remote computes are connected, use local only
for node in topology["topology"]["nodes"]:
node["compute_id"] = "local"
# No remote computes are connected, use local only
for node in topology["topology"]["nodes"]:
node["compute_id"] = "local"
compute_created = set()
for node in topology["topology"]["nodes"]: