mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-11-03 05:51:15 +02:00
Use black with -l 120 param.
This commit is contained in:
1 parent
f928738bd5
commit
c021e21309
194 files changed
+6034
-4564
No files matched your search
@@ -31,6 +31,7 @@ from ..compute import ComputeError
|
||||
from ..controller_error import ControllerError
|
||||
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -60,37 +61,47 @@ class GNS3VM:
|
||||
:returns: Return list of engines supported by GNS3 for the GNS3VM
|
||||
"""
|
||||
|
||||
download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VMware.Workstation.{version}.zip".format(version=__version__)
|
||||
download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VMware.Workstation.{version}.zip".format(
|
||||
version=__version__
|
||||
)
|
||||
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
|
||||
"support_ram": True,
|
||||
}
|
||||
if sys.platform.startswith("darwin"):
|
||||
vmware_info["name"] = "VMware Fusion (recommended)"
|
||||
else:
|
||||
vmware_info["name"] = "VMware Workstation / Player (recommended)"
|
||||
|
||||
download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.Hyper-V.{version}.zip".format(version=__version__)
|
||||
download_url = (
|
||||
"https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.Hyper-V.{version}.zip".format(
|
||||
version=__version__
|
||||
)
|
||||
)
|
||||
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
|
||||
"support_ram": True,
|
||||
}
|
||||
|
||||
download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VirtualBox.{version}.zip".format(version=__version__)
|
||||
download_url = (
|
||||
"https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VirtualBox.{version}.zip".format(
|
||||
version=__version__
|
||||
)
|
||||
)
|
||||
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
|
||||
"support_ram": True,
|
||||
}
|
||||
|
||||
remote_info = {
|
||||
@@ -99,12 +110,10 @@ class GNS3VM:
|
||||
"description": "Use a remote GNS3 server as the GNS3 VM.",
|
||||
"support_when_exit": False,
|
||||
"support_headless": False,
|
||||
"support_ram": False
|
||||
"support_ram": False,
|
||||
}
|
||||
|
||||
engines = [vmware_info,
|
||||
virtualbox_info,
|
||||
remote_info]
|
||||
engines = [vmware_info, virtualbox_info, remote_info]
|
||||
|
||||
if sys.platform.startswith("win"):
|
||||
engines.append(hyperv_info)
|
||||
@@ -260,7 +269,7 @@ class GNS3VM:
|
||||
engine = self._get_engine(engine)
|
||||
vms = []
|
||||
try:
|
||||
for vm in (await engine.list()):
|
||||
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
|
||||
@@ -280,10 +289,9 @@ class GNS3VM:
|
||||
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 = 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:
|
||||
@@ -318,11 +326,9 @@ class GNS3VM:
|
||||
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)
|
||||
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()
|
||||
@@ -333,12 +339,14 @@ class GNS3VM:
|
||||
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)
|
||||
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
|
||||
@@ -370,11 +378,9 @@ class GNS3VM:
|
||||
if netmask:
|
||||
compute_network = ipaddress.ip_interface(f"{compute.host_ip}/{netmask}").network
|
||||
if vm_network.compare_networks(compute_network) != 0:
|
||||
msg = "The GNS3 VM (IP={}, NETWORK={}) is not on the same network as the {} server (IP={}, NETWORK={}), please make sure the local server binding is in the same network as the GNS3 VM".format(self.ip_address,
|
||||
vm_network,
|
||||
compute_id,
|
||||
compute.host_ip,
|
||||
compute_network)
|
||||
msg = "The GNS3 VM (IP={}, NETWORK={}) is not on the same network as the {} server (IP={}, NETWORK={}), please make sure the local server binding is in the same network as the GNS3 VM".format(
|
||||
self.ip_address, vm_network, compute_id, compute.host_ip, compute_network
|
||||
)
|
||||
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}")
|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
import psutil
|
||||
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BaseGNS3VM:
|
||||
|
||||
def __init__(self, controller):
|
||||
|
||||
self._controller = controller
|
||||
@@ -42,9 +42,9 @@ class BaseGNS3VM:
|
||||
# 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)
|
||||
# ram = int(psutil.virtual_memory().total / (1024 * 1024) / 2)
|
||||
# value must be a multiple of 4 (VMware requirement)
|
||||
#ram -= ram % 4
|
||||
# ram -= ram % 4
|
||||
|
||||
ram = 2048
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
|
||||
|
||||
class GNS3VMError(Exception):
|
||||
|
||||
def __init__(self, message):
|
||||
super().__init__(message)
|
||||
self._message = message
|
||||
|
||||
@@ -23,6 +23,7 @@ import ipaddress
|
||||
|
||||
from .base_gns3_vm import BaseGNS3VM
|
||||
from .gns3_vm_error import GNS3VMError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -55,17 +56,25 @@ class HyperVGNS3VM(BaseGNS3VM):
|
||||
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)")
|
||||
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
|
||||
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")
|
||||
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:
|
||||
@@ -77,12 +86,16 @@ class HyperVGNS3VM(BaseGNS3VM):
|
||||
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")
|
||||
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")
|
||||
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:
|
||||
# if not conn.Win32_Processor()[0].VirtualizationFirmwareEnabled:
|
||||
# raise GNS3VMError("Nested Virtualization (VT-x) is not enabled on this system")
|
||||
|
||||
def _connect(self):
|
||||
@@ -134,8 +147,8 @@ class HyperVGNS3VM(BaseGNS3VM):
|
||||
: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]
|
||||
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):
|
||||
"""
|
||||
@@ -158,11 +171,13 @@ class HyperVGNS3VM(BaseGNS3VM):
|
||||
|
||||
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)")
|
||||
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 = 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
|
||||
@@ -201,7 +216,7 @@ class HyperVGNS3VM(BaseGNS3VM):
|
||||
Gets the WMI object.
|
||||
"""
|
||||
|
||||
return self._wmi.WMI(moniker=path.replace('\\', '/'))
|
||||
return self._wmi.WMI(moniker=path.replace("\\", "/"))
|
||||
|
||||
async def _set_state(self, state):
|
||||
"""
|
||||
@@ -234,8 +249,12 @@ class HyperVGNS3VM(BaseGNS3VM):
|
||||
IPv4/v6 (4098)
|
||||
"""
|
||||
|
||||
wql = "SELECT * FROM Msvm_GuestNetworkAdapterConfiguration WHERE InstanceID like \
|
||||
'Microsoft:GuestNetwork\\" + self._vm.Name + "%' and ProtocolIFType > 0 "
|
||||
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
|
||||
@@ -272,15 +291,15 @@ class HyperVGNS3VM(BaseGNS3VM):
|
||||
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')
|
||||
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')
|
||||
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
|
||||
|
||||
@@ -20,11 +20,11 @@ from .gns3_vm_error import GNS3VMError
|
||||
|
||||
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RemoteGNS3VM(BaseGNS3VM):
|
||||
|
||||
def __init__(self, controller):
|
||||
|
||||
self._engine = "remote"
|
||||
|
||||
@@ -27,16 +27,12 @@ from gns3server.utils import parse_version
|
||||
from gns3server.utils.http_client import HTTPClient
|
||||
from gns3server.utils.asyncio import wait_run_in_executor
|
||||
|
||||
from ...compute.virtualbox import (
|
||||
VirtualBox,
|
||||
VirtualBoxError
|
||||
)
|
||||
from ...compute.virtualbox import VirtualBox, VirtualBoxError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
|
||||
def __init__(self, controller):
|
||||
|
||||
self._engine = "virtualbox"
|
||||
@@ -48,7 +44,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
|
||||
try:
|
||||
result = await self._virtualbox_manager.execute(subcommand, args, timeout)
|
||||
return ("\n".join(result))
|
||||
return "\n".join(result)
|
||||
except VirtualBoxError as e:
|
||||
raise GNS3VMError(f"Error while executing VBoxManage command: {e}")
|
||||
|
||||
@@ -61,8 +57,8 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
|
||||
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
|
||||
for info in result.splitlines():
|
||||
if '=' in info:
|
||||
name, value = info.split('=', 1)
|
||||
if "=" in info:
|
||||
name, value = info.split("=", 1)
|
||||
if name == "VMState":
|
||||
return value.strip('"')
|
||||
return "unknown"
|
||||
@@ -77,7 +73,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
properties = await self._execute("list", ["systemproperties"])
|
||||
for prop in properties.splitlines():
|
||||
try:
|
||||
name, value = prop.split(':', 1)
|
||||
name, value = prop.split(":", 1)
|
||||
except ValueError:
|
||||
continue
|
||||
self._system_properties[name.strip()] = value.strip()
|
||||
@@ -92,14 +88,19 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
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')
|
||||
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")
|
||||
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")
|
||||
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}")
|
||||
|
||||
@@ -113,8 +114,8 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
|
||||
interface = -1
|
||||
for info in result.splitlines():
|
||||
if '=' in info:
|
||||
name, value = info.split('=', 1)
|
||||
if "=" in info:
|
||||
name, value = info.split("=", 1)
|
||||
if name.startswith("nic") and value.strip('"') == network_backend:
|
||||
try:
|
||||
interface = int(name[3:])
|
||||
@@ -132,8 +133,8 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
|
||||
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
|
||||
for info in result.splitlines():
|
||||
if '=' in info:
|
||||
name, value = info.split('=', 1)
|
||||
if "=" in info:
|
||||
name, value = info.split("=", 1)
|
||||
if name == f"hostonlyadapter{interface_number}":
|
||||
return value.strip('"')
|
||||
return None
|
||||
@@ -150,7 +151,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
flag_dhcp_server_found = False
|
||||
for prop in properties.splitlines():
|
||||
try:
|
||||
name, value = prop.split(':', 1)
|
||||
name, value = prop.split(":", 1)
|
||||
except ValueError:
|
||||
continue
|
||||
if name.strip() == "NetworkName" and value.strip().endswith(vboxnet):
|
||||
@@ -171,7 +172,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
properties = await self._execute("list", ["hostonlyifs"])
|
||||
for prop in properties.splitlines():
|
||||
try:
|
||||
name, value = prop.split(':', 1)
|
||||
name, value = prop.split(":", 1)
|
||||
except ValueError:
|
||||
continue
|
||||
if name.strip() == "Name" and value.strip() == vboxnet:
|
||||
@@ -186,7 +187,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
properties = await self._execute("list", ["hostonlyifs"])
|
||||
for prop in properties.splitlines():
|
||||
try:
|
||||
name, value = prop.split(':', 1)
|
||||
name, value = prop.split(":", 1)
|
||||
except ValueError:
|
||||
continue
|
||||
if name.strip() == "Name":
|
||||
@@ -202,8 +203,8 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
|
||||
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
|
||||
for info in result.splitlines():
|
||||
if '=' in info:
|
||||
name, value = info.split('=', 1)
|
||||
if "=" in info:
|
||||
name, value = info.split("=", 1)
|
||||
if name.startswith("Forwarding") and value.strip('"').startswith("GNS3VM"):
|
||||
return True
|
||||
return False
|
||||
@@ -237,7 +238,9 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
|
||||
vboxnet = await self._look_for_vboxnet(hostonly_interface_number)
|
||||
if vboxnet is None:
|
||||
raise GNS3VMError(f'A VirtualBox host-only network could not be found on network adapter {hostonly_interface_number} for "{self._vmname}"')
|
||||
raise GNS3VMError(
|
||||
f'A VirtualBox host-only network could not be found on network adapter {hostonly_interface_number} for "{self._vmname}"'
|
||||
)
|
||||
|
||||
if not (await self._check_vboxnet_exists(vboxnet)):
|
||||
if sys.platform.startswith("win") and vboxnet == "vboxnet0":
|
||||
@@ -245,13 +248,17 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
# 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 {hostonly_interface_number} for "{self._vmname}"')
|
||||
raise GNS3VMError(
|
||||
f'Please add a VirtualBox host-only network with DHCP enabled and attached it to network adapter {hostonly_interface_number} for "{self._vmname}"'
|
||||
)
|
||||
await self.set_hostonly_network(hostonly_interface_number, first_available_vboxnet)
|
||||
vboxnet = first_available_vboxnet
|
||||
else:
|
||||
raise GNS3VMError('VirtualBox host-only network "{}" does not exist, please make the sure the network adapter {} configuration is valid for "{}"'.format(vboxnet,
|
||||
hostonly_interface_number,
|
||||
self._vmname))
|
||||
raise GNS3VMError(
|
||||
'VirtualBox host-only network "{}" does not exist, please make the sure the network adapter {} configuration is valid for "{}"'.format(
|
||||
vboxnet, hostonly_interface_number, self._vmname
|
||||
)
|
||||
)
|
||||
|
||||
if not (await self._check_dhcp_server(vboxnet)):
|
||||
raise GNS3VMError(f'DHCP must be enabled on VirtualBox host-only network "{vboxnet}"')
|
||||
@@ -287,15 +294,17 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
except OSError as e:
|
||||
raise GNS3VMError(f"Error while getting random port: {e}")
|
||||
|
||||
if (await self._check_vbox_port_forwarding()):
|
||||
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}"])
|
||||
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(hostonly_interface_number, api_port)
|
||||
log.info(f"GNS3 VM has been started with IP {self.ip_address}")
|
||||
@@ -320,7 +329,8 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
if json_data:
|
||||
for interface in json_data:
|
||||
if "name" in interface and interface["name"] == "eth{}".format(
|
||||
hostonly_interface_number - 1):
|
||||
hostonly_interface_number - 1
|
||||
):
|
||||
if "ip_address" in interface and len(interface["ip_address"]) > 0:
|
||||
return interface["ip_address"]
|
||||
except ValueError:
|
||||
@@ -405,7 +415,11 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
|
||||
: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('VirtualBox host-only network "{}" set on network adapter {} for "{}"'.format(hostonly_network_name,
|
||||
adapter_number,
|
||||
self._vmname))
|
||||
await self._execute(
|
||||
"modifyvm", [self._vmname, f"--hostonlyadapter{adapter_number}", hostonly_network_name], timeout=3
|
||||
)
|
||||
log.info(
|
||||
'VirtualBox host-only network "{}" set on network adapter {} for "{}"'.format(
|
||||
hostonly_network_name, adapter_number, self._vmname
|
||||
)
|
||||
)
|
||||
@@ -20,18 +20,15 @@ import logging
|
||||
import asyncio
|
||||
import psutil
|
||||
|
||||
from gns3server.compute.vmware import (
|
||||
VMware,
|
||||
VMwareError
|
||||
)
|
||||
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"
|
||||
@@ -47,7 +44,7 @@ class VMwareGNS3VM(BaseGNS3VM):
|
||||
|
||||
try:
|
||||
result = await self._vmware_manager.execute(subcommand, args, timeout, log_level=log_level)
|
||||
return (''.join(result))
|
||||
return "".join(result)
|
||||
except VMwareError as e:
|
||||
raise GNS3VMError(f"Error while executing VMware command: {e}")
|
||||
|
||||
@@ -73,7 +70,9 @@ class VMwareGNS3VM(BaseGNS3VM):
|
||||
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)")
|
||||
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)
|
||||
@@ -94,9 +93,7 @@ class VMwareGNS3VM(BaseGNS3VM):
|
||||
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"),
|
||||
)
|
||||
extra_config = (("vhv.enable", "TRUE"),)
|
||||
pairs = VMware.parse_vmware_file(self._vmx_path)
|
||||
updated = False
|
||||
for key, value in extra_config:
|
||||
@@ -117,7 +114,7 @@ class VMwareGNS3VM(BaseGNS3VM):
|
||||
"""
|
||||
|
||||
try:
|
||||
return (await self._vmware_manager.list_vms())
|
||||
return await self._vmware_manager.list_vms()
|
||||
except VMwareError as e:
|
||||
raise GNS3VMError(f"Could not list VMware VMs: {str(e)}")
|
||||
|
||||
@@ -169,7 +166,9 @@ class VMwareGNS3VM(BaseGNS3VM):
|
||||
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 = 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
|
||||
|
||||
Reference in new issue
Block a user