diff --git a/gns3server/api/routes/compute/__init__.py b/gns3server/api/routes/compute/__init__.py index 8e48ee48d..f99de579c 100644 --- a/gns3server/api/routes/compute/__init__.py +++ b/gns3server/api/routes/compute/__init__.py @@ -31,7 +31,6 @@ from gns3server.compute.compute_error import ( ) from gns3server.compute.error import ImageMissingError, NodeError from gns3server.compute.ubridge.ubridge_error import UbridgeError -from gns3server.controller.gns3vm.gns3_vm_error import GNS3VMError from gns3server.version import __api_version__ from . import ( @@ -115,15 +114,6 @@ async def compute_not_found_error_handler(request: Request, exc: ComputeNotFound ) -@compute_api.exception_handler(GNS3VMError) -async def compute_gns3vm_error_handler(request: Request, exc: GNS3VMError): - log.error(f"Compute GNS3 VM error: {exc}") - return JSONResponse( - status_code=409, - content={"message": str(exc)}, - ) - - @compute_api.exception_handler(ImageMissingError) async def image_missing_error_handler(request: Request, exc: ImageMissingError): log.error(f"Compute image missing error: {exc}") diff --git a/gns3server/api/routes/controller/__init__.py b/gns3server/api/routes/controller/__init__.py index 0de9cdc2a..b7f334f78 100644 --- a/gns3server/api/routes/controller/__init__.py +++ b/gns3server/api/routes/controller/__init__.py @@ -70,7 +70,6 @@ from . import ( computes, controller, drawings, - gns3vm, groups, images, links, @@ -134,10 +133,6 @@ router.include_router(netmiko.router, prefix="/netmiko", tags=["Netmiko"]) router.include_router(pools.router, prefix="/pools", tags=["Resource pools"]) -router.include_router( - gns3vm.router, dependencies=[Depends(get_current_active_user)], deprecated=True, prefix="/gns3vm", tags=["GNS3 VM"] -) - router.include_router( _llm_router, prefix="/access", diff --git a/gns3server/api/routes/controller/gns3vm.py b/gns3server/api/routes/controller/gns3vm.py deleted file mode 100644 index 21d2cdf49..000000000 --- a/gns3server/api/routes/controller/gns3vm.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (C) 2020 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 . - -""" -API routes for managing the GNS3 VM. -""" - -from typing import List - -from fastapi import APIRouter -from fastapi.encoders import jsonable_encoder - -from gns3server import schemas -from gns3server.controller import Controller - -router = APIRouter() - - -@router.get("/engines", response_model=List[schemas.GNS3VMEngineInfo]) -async def get_engines() -> List[dict]: - """ - Return the list of supported engines for the GNS3VM. - """ - - gns3_vm = Controller().instance().gns3vm - return gns3_vm.engine_list() - - -@router.get("/engines/{engine}/vms", response_model=List[schemas.GNS3VMInfo]) -async def get_vms(engine: str) -> List[dict]: - """ - Return all the available VMs for a specific virtualization engine. - """ - - vms = await Controller.instance().gns3vm.list(engine) - return vms - - -@router.get("", response_model=schemas.GNS3VM) -async def get_gns3vm_settings() -> schemas.GNS3VM: - """ - Return the GNS3 VM settings. - """ - - return Controller.instance().gns3vm.asdict() - - -@router.put("", response_model=schemas.GNS3VM, response_model_exclude_unset=True) -async def update_gns3vm_settings(gns3vm_data: schemas.GNS3VM) -> schemas.GNS3VM: - """ - Update the GNS3 VM settings. - """ - - controller = Controller().instance() - gns3_vm = controller.gns3vm - await gns3_vm.update_settings(jsonable_encoder(gns3vm_data, exclude_unset=True)) - controller.save() - return gns3_vm.asdict() diff --git a/gns3server/compute/base_manager.py b/gns3server/compute/base_manager.py index 5ed7fa5df..758e59679 100644 --- a/gns3server/compute/base_manager.py +++ b/gns3server/compute/base_manager.py @@ -23,7 +23,6 @@ import shutil import socket import stat import struct -import sys import aiofiles @@ -317,9 +316,9 @@ class BaseManager: # the executable has set UID bit. return True - # test if the executable has the CAP_NET_RAW capability (Linux only) + # test if the executable has the CAP_NET_RAW capability try: - if sys.platform.startswith("linux") and "security.capability" in os.listxattr(executable): + if "security.capability" in os.listxattr(executable): caps = os.getxattr(executable, "security.capability") required = (1 << 13) | ((1 << 12) if require_net_admin else 0) if struct.unpack(". import logging -import sys import gns3server.utils.interfaces from gns3server.config import Config @@ -38,39 +37,18 @@ class Nat(Cloud): allowed_interfaces = Config.instance().settings.Server.allowed_interfaces if allowed_interfaces and isinstance(allowed_interfaces, str): allowed_interfaces = allowed_interfaces.split(",") - if sys.platform.startswith("linux"): - nat_interface = Config.instance().settings.Server.default_nat_interface - if not nat_interface: - nat_interface = "virbr0" - if allowed_interfaces and nat_interface not in allowed_interfaces: - raise NodeError( - f"NAT interface {nat_interface} is not allowed be used on this server. " - "Please check the server configuration file." - ) - if nat_interface not in [interface["name"] for interface in gns3server.utils.interfaces.interfaces()]: - raise NodeError(f"NAT interface {nat_interface} is missing, please install libvirt") - interface = nat_interface - else: - nat_interface = Config.instance().settings.Server.default_nat_interface - if not nat_interface: - nat_interface = "vmnet8" - if allowed_interfaces and nat_interface not in allowed_interfaces: - raise NodeError( - f"NAT interface {nat_interface} is not allowed be used on this server. " - "Please check the server configuration file." - ) - interfaces = list( - filter( - lambda x: nat_interface in x.lower(), - [interface["name"] for interface in gns3server.utils.interfaces.interfaces()], - ) + + nat_interface = Config.instance().settings.Server.default_nat_interface + if not nat_interface: + nat_interface = "virbr0" + if allowed_interfaces and nat_interface not in allowed_interfaces: + raise NodeError( + f"NAT interface {nat_interface} is not allowed be used on this server. " + "Please check the server configuration file." ) - if not len(interfaces): - raise NodeError( - f"NAT interface {nat_interface} is missing. " - f"You need to install VMware or use the NAT node on GNS3 VM" - ) - interface = interfaces[0] # take the first available interface containing the vmnet8 name + if nat_interface not in [interface["name"] for interface in gns3server.utils.interfaces.interfaces()]: + raise NodeError(f"NAT interface {nat_interface} is missing, please install libvirt") + interface = nat_interface log.debug(f"NAT node '{name}' configured to use NAT interface '{interface}'") ports = [{"name": "nat0", "type": "ethernet", "interface": interface, "port_number": 0}] diff --git a/gns3server/compute/vmware/__init__.py b/gns3server/compute/vmware/__init__.py index 6bdf65d89..ed02eb71b 100644 --- a/gns3server/compute/vmware/__init__.py +++ b/gns3server/compute/vmware/__init__.py @@ -27,7 +27,6 @@ import re import shlex import shutil import subprocess -import sys from collections import OrderedDict from gns3server.utils import parse_version @@ -525,11 +524,9 @@ class VMware(BaseManager): except LookupError: log.warning(f"Invalid file encoding detected in '{path}': {file_encoding}") with open(path, "w", encoding=encoding, errors="ignore") as f: - if sys.platform.startswith("linux"): - # write the shebang on the first line on Linux - vmware_path = VMware._get_linux_vmware_binary() - if vmware_path: - f.write(f"#!{vmware_path}\n") + vmware_path = VMware._get_linux_vmware_binary() + if vmware_path: + f.write(f"#!{vmware_path}\n") for key, value in pairs.items(): entry = f'{key} = "{value}"\n' f.write(entry) diff --git a/gns3server/compute/vmware/vmware_vm.py b/gns3server/compute/vmware/vmware_vm.py index ff630d535..d42701b06 100644 --- a/gns3server/compute/vmware/vmware_vm.py +++ b/gns3server/compute/vmware/vmware_vm.py @@ -343,8 +343,7 @@ class VMwareVM(BaseNode): vnet = self._get_vnet(adapter_number) 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 - await self._add_ubridge_ethernet_connection(vnet, vmnet_interface, block_host_traffic) + await self._add_ubridge_ethernet_connection(vnet, vmnet_interface) if isinstance(nio, NIOUDP): await self._ubridge_send(f"bridge add_nio_udp {vnet} {nio.lport} {nio.rhost} {nio.rport}") diff --git a/gns3server/compute/vpcs/vpcs_vm.py b/gns3server/compute/vpcs/vpcs_vm.py index f94c73676..16d70a8b2 100644 --- a/gns3server/compute/vpcs/vpcs_vm.py +++ b/gns3server/compute/vpcs/vpcs_vm.py @@ -24,10 +24,8 @@ import logging import os import re import shutil -import signal import socket import subprocess -import sys from gns3server.utils import parse_version from gns3server.utils.asyncio import monitor_process, subprocess_check_output, wait_for_process_termination @@ -262,13 +260,10 @@ class VPCSVM(KernelDatapathMixin, BaseNode): log.info(f"Starting VPCS: {command}") self._vpcs_stdout_file = os.path.join(self.working_dir, "vpcs.log") log.info(f"Logging to {self._vpcs_stdout_file}") - flags = 0 - if sys.platform.startswith("win32"): - flags = subprocess.CREATE_NEW_PROCESS_GROUP with open(self._vpcs_stdout_file, "w", encoding="utf-8") as fd: self.command_line = " ".join(command) self._process = await asyncio.create_subprocess_exec( - *command, stdout=fd, stderr=subprocess.STDOUT, cwd=self.working_dir, creationflags=flags + *command, stdout=fd, stderr=subprocess.STDOUT, cwd=self.working_dir ) monitor_process(self._process, self._termination_callback) @@ -480,17 +475,11 @@ class VPCSVM(KernelDatapathMixin, BaseNode): """ log.info(f"Stopping VPCS instance {self.name} PID={self._process.pid}") - if sys.platform.startswith("win32"): - try: - self._process.send_signal(signal.CTRL_BREAK_EVENT) - except (SystemError, OSError): - pass - else: - try: - self._process.terminate() - # Sometime the process may already be dead when we garbage collect - except ProcessLookupError: - pass + try: + self._process.terminate() + # Sometime the process may already be dead when we garbage collect + except ProcessLookupError: + pass def read_vpcs_stdout(self): """ diff --git a/gns3server/config_samples/gns3_server.conf b/gns3server/config_samples/gns3_server.conf index b200029dd..357940199 100644 --- a/gns3server/config_samples/gns3_server.conf +++ b/gns3server/config_samples/gns3_server.conf @@ -59,8 +59,7 @@ symbols_path = /home/gns3/GNS3/symbols configs_path = /home/gns3/GNS3/configs ; Path where files like built-in appliances and Docker resources are stored -; The default path is the local user data directory -; (Linux: "~/.local/share/GNS3", macOS: "~/Library/Application Support/GNS3", Windows: "%APPDATA%\GNS3") +; The default path is the local user data directory ("~/.local/share/GNS3") ; resources_path = /home/gns3/GNS3/resources ; Default symbol theme @@ -172,10 +171,8 @@ vboxmanage_path = vboxmanage vmrun_path = vmrun ; First vmnet interface of the range that can be managed by the GNS3 server vmnet_start_range = 2 -; Last vmnet interface of the range that can be managed by the GNS3 server. It must be maximum 19 on Windows. +; Last vmnet interface of the range that can be managed by the GNS3 server vmnet_end_range = 255 -; block network traffic originating from the host OS -block_host_traffic = False [Qemu] ; Use Qemu monitor feature to communicate with Qemu VMs diff --git a/gns3server/controller/__init__.py b/gns3server/controller/__init__.py index 456d7eaf7..c9d294e29 100644 --- a/gns3server/controller/__init__.py +++ b/gns3server/controller/__init__.py @@ -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') diff --git a/gns3server/controller/compute.py b/gns3server/controller/compute.py index 28adc2708..71d69011a 100644 --- a/gns3server/controller/compute.py +++ b/gns3server/controller/compute.py @@ -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}") diff --git a/gns3server/controller/gns3vm/__init__.py b/gns3server/controller/gns3vm/__init__.py deleted file mode 100644 index c2023db92..000000000 --- a/gns3server/controller/gns3vm/__init__.py +++ /dev/null @@ -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 . - -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.
The GNS3 VM can be downloaded here.', - "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)
The GNS3 VM can be downloaded here', - "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
The GNS3 VM can be downloaded here', - "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() diff --git a/gns3server/controller/gns3vm/base_gns3_vm.py b/gns3server/controller/gns3vm/base_gns3_vm.py deleted file mode 100644 index 3abe8679c..000000000 --- a/gns3server/controller/gns3vm/base_gns3_vm.py +++ /dev/null @@ -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 . - -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 diff --git a/gns3server/controller/gns3vm/gns3_vm_error.py b/gns3server/controller/gns3vm/gns3_vm_error.py deleted file mode 100644 index 4f8a4d39e..000000000 --- a/gns3server/controller/gns3vm/gns3_vm_error.py +++ /dev/null @@ -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 . - - -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}" diff --git a/gns3server/controller/gns3vm/hyperv_gns3_vm.py b/gns3server/controller/gns3vm/hyperv_gns3_vm.py deleted file mode 100644 index 6505e0349..000000000 --- a/gns3server/controller/gns3vm/hyperv_gns3_vm.py +++ /dev/null @@ -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 . - -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 diff --git a/gns3server/controller/gns3vm/remote_gns3_vm.py b/gns3server/controller/gns3vm/remote_gns3_vm.py deleted file mode 100644 index aa3ad4147..000000000 --- a/gns3server/controller/gns3vm/remote_gns3_vm.py +++ /dev/null @@ -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 . - -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 diff --git a/gns3server/controller/gns3vm/virtualbox_gns3_vm.py b/gns3server/controller/gns3vm/virtualbox_gns3_vm.py deleted file mode 100644 index 9f9112ce4..000000000 --- a/gns3server/controller/gns3vm/virtualbox_gns3_vm.py +++ /dev/null @@ -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 . - -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}"' - ) diff --git a/gns3server/controller/gns3vm/vmware_gns3_vm.py b/gns3server/controller/gns3vm/vmware_gns3_vm.py deleted file mode 100644 index f1d7f7c14..000000000 --- a/gns3server/controller/gns3vm/vmware_gns3_vm.py +++ /dev/null @@ -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 . - -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 diff --git a/gns3server/controller/import_project.py b/gns3server/controller/import_project.py index 399827989..001029e3e 100644 --- a/gns3server/controller/import_project.py +++ b/gns3server/controller/import_project.py @@ -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"]: diff --git a/gns3server/main.py b/gns3server/main.py index 70ed5ea47..b905e2aca 100644 --- a/gns3server/main.py +++ b/gns3server/main.py @@ -126,8 +126,6 @@ def main(): Entry point for GNS3 server """ - if sys.platform.startswith("win"): - raise SystemExit("Windows is not a supported platform to run the GNS3 server") _raise_open_files_limit() if "--daemon" in sys.argv: daemonize() diff --git a/gns3server/schemas/__init__.py b/gns3server/schemas/__init__.py index 74ddfe4af..24a7acaf5 100644 --- a/gns3server/schemas/__init__.py +++ b/gns3server/schemas/__init__.py @@ -29,7 +29,6 @@ from .controller.computes import ( IdlePC, ) from .controller.drawings import Drawing -from .controller.gns3vm import GNS3VM, GNS3VMEngineInfo, GNS3VMInfo from .controller.images import ( Image, ImageInstallCreated, @@ -201,7 +200,6 @@ from .qemu_disk_image import QemuDiskImageCreate, QemuDiskImageFormat, QemuDiskI __all__ = [ "ACE", - "GNS3VM", "IOU", "NAT", "TAPNIO", @@ -285,8 +283,6 @@ __all__ = [ "FrameRelaySwitch", "FrameRelaySwitchCreate", "FrameRelaySwitchUpdate", - "GNS3VMEngineInfo", - "GNS3VMInfo", "IOUCreate", "IOULicense", "IOUStart", diff --git a/gns3server/schemas/config.py b/gns3server/schemas/config.py index 1f20eeffe..a2c513ddd 100644 --- a/gns3server/schemas/config.py +++ b/gns3server/schemas/config.py @@ -112,8 +112,8 @@ class VirtualBoxSettings(BaseModel): class VMwareSettings(BaseModel): vmrun_path: Optional[str] = None vmnet_start_range: int = Field(2, ge=1, le=255) - vmnet_end_range: int = Field(255, ge=1, le=255) # should be limited to 19 on Windows - block_host_traffic: bool = False + vmnet_end_range: int = Field(255, ge=1, le=255) + block_host_traffic: bool = False # deprecated, will be removed in a future version model_config = ConfigDict(validate_assignment=True, str_strip_whitespace=True) @model_validator(mode="after") diff --git a/gns3server/schemas/controller/gns3vm.py b/gns3server/schemas/controller/gns3vm.py deleted file mode 100644 index 1006b4ea1..000000000 --- a/gns3server/schemas/controller/gns3vm.py +++ /dev/null @@ -1,78 +0,0 @@ -# -# Copyright (C) 2020 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 . - -from enum import StrEnum -from typing import Optional - -from pydantic import BaseModel, Field - - -class WhenExit(StrEnum): - """ - What to do with the VM when GNS3 VM exits. - """ - - stop = "stop" - suspend = "suspend" - keep = "keep" - - -class Engine(StrEnum): - """ - "The engine to use for the GNS3 VM. - """ - - vmware = "vmware" - virtualbox = "virtualbox" - hyperv = "hyper-v" - none = "none" - - -class GNS3VM(BaseModel): - """ - GNS3 VM data. - """ - - enable: Optional[bool] = Field(None, description="Enable/disable the GNS3 VM") - vmname: Optional[str] = Field(None, description="GNS3 VM name") - when_exit: Optional[WhenExit] = Field(None, description="Action when the GNS3 VM exits") - headless: Optional[bool] = Field(None, description="Start the GNS3 VM GUI or not") - engine: Optional[Engine] = Field(None, description="The engine to use for the GNS3 VM") - allocate_vcpus_ram: Optional[bool] = Field(None, description="Allocate vCPUS and RAM settings") - vcpus: Optional[int] = Field(None, description="Number of CPUs to allocate for the GNS3 VM") - ram: Optional[int] = Field(None, description="Amount of memory to allocate for the GNS3 VM") - port: Optional[int] = Field(None, gt=0, le=65535) - - -class GNS3VMEngineInfo(BaseModel): - """ - A virtualization engine supported by the GNS3 VM. - """ - - engine_id: str = Field(..., description="Engine identifier") - name: str = Field(..., description="Engine display name") - description: str = Field(..., description="Engine description (may contain HTML)") - support_when_exit: bool = Field(..., description="The engine supports the 'when exit' action") - support_headless: bool = Field(..., description="The engine supports headless mode") - support_ram: bool = Field(..., description="The engine supports RAM and vCPUs allocation") - - -class GNS3VMInfo(BaseModel): - """ - A virtual machine available on a virtualization engine. - """ - - vmname: str = Field(..., description="Virtual machine name") diff --git a/gns3server/utils/interfaces.py b/gns3server/utils/interfaces.py index 719d340c0..f9bc6eee1 100644 --- a/gns3server/utils/interfaces.py +++ b/gns3server/utils/interfaces.py @@ -15,23 +15,16 @@ # along with this program. If not, see . +import logging import os import socket import struct -import sys import psutil from gns3server.compute.compute_error import ComputeError from gns3server.config import Config -if psutil.version_info < (3, 0, 0): - raise Exception( - "psutil version should >= 3.0.0. If you are under Ubuntu/Debian install gns3 via apt instead of pip" - ) - -import logging - log = logging.getLogger(__name__) @@ -60,25 +53,21 @@ def is_interface_up(interface): :returns: boolean """ - if sys.platform.startswith("linux") or sys.platform.startswith("openbsd"): - if interface not in psutil.net_if_addrs(): - return False + if interface not in psutil.net_if_addrs(): + return False - import fcntl + import fcntl - SIOCGIFFLAGS = 0x8913 - try: - with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: - result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + "\0" * 256) - (flags,) = struct.unpack("H", result[16:18]) - if flags & 1: # check if the up bit is set - return True - return False - except OSError as e: - raise ComputeError(f"Exception when checking if {interface} is up: {e}") - else: - # TODO: Windows & OSX support - return True + SIOCGIFFLAGS = 0x8913 + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + "\0" * 256) + (flags,) = struct.unpack("H", result[16:18]) + if flags & 1: # check if the up bit is set + return True + return False + except OSError as e: + raise ComputeError(f"Exception when checking if {interface} is up: {e}") def is_interface_bridge(interface): diff --git a/gns3server/utils/vmnet.py b/gns3server/utils/vmnet.py index f49c1bc87..1d97b44bb 100644 --- a/gns3server/utils/vmnet.py +++ b/gns3server/utils/vmnet.py @@ -18,16 +18,10 @@ import argparse import ipaddress import os -import shutil -import sys from collections import OrderedDict VMWARE_NETWORKING_FILE = "/etc/vmware/networking" - -if sys.platform.startswith("win"): - DEFAULT_RANGE = [1, 19] -else: - DEFAULT_RANGE = [10, 99] +DEFAULT_RANGE = [10, 99] def parse_networking_file(): @@ -90,107 +84,18 @@ def parse_vmnet_range(start, end): return Range -def find_vnetlib_registry(regkey): - - import winreg - - try: - # default path not used, let's look in the registry - hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, regkey) - install_path, _ = winreg.QueryValueEx(hkey, "InstallPath") - winreg.CloseKey(hkey) - vnetlib_path = os.path.join(install_path, "vnetlib64.exe") - if os.path.exists(vnetlib_path): - return vnetlib_path - vnetlib_path = os.path.join(install_path, "vnetlib.exe") - if os.path.exists(vnetlib_path): - return vnetlib_path - except OSError: - pass - return None - - -def find_vnetlib_on_windows(): - - # look for vnetlib in PATH - vnetlib_path = shutil.which("vnetlib64") - - if vnetlib_path is None: - vnetlib_path = shutil.which("vnetlib") - - if vnetlib_path is None: - # look for vnetlib using the directory listed in the registry (for VMware Workstation) - vnetlib_path = find_vnetlib_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation") - - if vnetlib_path is None: - # look for vnetlib using the directory listed in the registry (for VMware Player) - vnetlib_path = find_vnetlib_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Player") - - if vnetlib_path is None: - # look for vnetlib in default VMware Workstation directory - vnetlib_ws = os.path.expandvars(r"%PROGRAMFILES(X86)%\VMware\VMware Workstation\vnetlib64.exe") - if not os.path.exists(vnetlib_ws): - vnetlib_ws = os.path.expandvars(r"%PROGRAMFILES(X86)%\VMware\VMware Workstation\vnetlib.exe") - if os.path.exists(vnetlib_ws): - vnetlib_path = vnetlib_ws - - if vnetlib_path is None: - # look for vnetlib in default VMware VIX directory - vnetlib_vix = os.path.expandvars(r"%PROGRAMFILES(X86)%\VMware\VMware VIX\vnetlib64.exe") - if not os.path.exists(vnetlib_vix): - vnetlib_vix = os.path.expandvars(r"%PROGRAMFILES(X86)%\VMware\VMware VIX\vnetlib.exe") - if os.path.exists(vnetlib_vix): - vnetlib_path = vnetlib_vix - - return vnetlib_path - - -def vmnet_windows(args, vmnet_range_start, vmnet_range_end): - - vnetlib_path = find_vnetlib_on_windows() - if not vnetlib_path: - raise SystemExit("VMware is not installed, could not find vnetlib.exe") - from win32com.shell import shell - - if not shell.IsUserAnAdmin(): - raise SystemExit("You must run this script as an administrator") - - print("Using", vnetlib_path, "for controlling vmnet") - - if args.list: - raise SystemExit("Not implemented") - - if args.clean: - # clean all vmnets but vmnet1 and vmnet8 - for vmnet_number in range(1, 20): - if vmnet_number in (1, 8): - continue - print(f"Removing vmnet{vmnet_number}...") - os.system(f'"{vnetlib_path}" -- remove adapter vmnet{vmnet_number}') - else: - for vmnet_number in range(vmnet_range_start, vmnet_range_end + 1): - if vmnet_number in (1, 8): - continue - print(f"Adding vmnet{vmnet_number}...") - os.system(f'"{vnetlib_path}" -- add adapter vmnet{vmnet_number}') - os.system("net stop npf") - os.system("net start npf") - os.system("net stop npcap") - os.system("net start npcap") - - -def vmnet_unix(args, vmnet_range_start, vmnet_range_end): +def vmnet(args, vmnet_range_start, vmnet_range_end): """ - Implementation on Linux and Mac OS X. + Add or remove vmnet interfaces. """ if not os.path.exists(VMWARE_NETWORKING_FILE): - raise SystemExit("VMware Player, Workstation or Fusion is not installed") + raise SystemExit("VMware Player or Workstation is not installed") if not os.access(VMWARE_NETWORKING_FILE, os.W_OK): raise SystemExit("You must run this script as root") version, pairs, allocated_subnets = parse_networking_file() - if args.list and not sys.platform.startswith("win"): + if args.list: for vmnet_number in range(1, 256): vmnet_name = f"VNET_{vmnet_number}_VIRTUAL_ADAPTER" if vmnet_name in pairs: @@ -243,7 +148,7 @@ def main(): help=f"vmnet range to add (default is {DEFAULT_RANGE[0]} {DEFAULT_RANGE[1]})", ) parser.add_argument("-C", "--clean", action="store_true", help="remove all vmnets excepting vmnet1 and vmnet8") - parser.add_argument("-l", "--list", action="store_true", help="list all existing vmnets (UNIX only)") + parser.add_argument("-l", "--list", action="store_true", help="list all existing vmnets") try: args = parser.parse_args() @@ -251,14 +156,7 @@ def main(): raise SystemExit(e) vmnet_range = args.range if args.range is not None else DEFAULT_RANGE - if sys.platform.startswith("win"): - try: - vmnet_windows(args, vmnet_range[0], vmnet_range[1]) - except SystemExit: - os.system("pause") - raise - else: - vmnet_unix(args, vmnet_range[0], vmnet_range[1]) + vmnet(args, vmnet_range[0], vmnet_range[1]) if __name__ == "__main__": diff --git a/tests/api/routes/controller/test_gns3vm.py b/tests/api/routes/controller/test_gns3vm.py deleted file mode 100644 index c3782eb4d..000000000 --- a/tests/api/routes/controller/test_gns3vm.py +++ /dev/null @@ -1,50 +0,0 @@ -# -# Copyright (C) 2020 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 . - -import pytest -from fastapi import FastAPI, status -from httpx import AsyncClient - -from tests.utils import asyncio_patch - -pytestmark = pytest.mark.asyncio - - -class TestGNS3VMRoutes: - async def test_list_vms(self, app: FastAPI, client: AsyncClient) -> None: - - with asyncio_patch( - "gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.list", return_value=[{"vmname": "test"}] - ): - response = await client.get(app.url_path_for("get_vms", engine="vmware")) - assert response.status_code == status.HTTP_200_OK - assert response.json() == [{"vmname": "test"}] - - async def test_engines(self, app: FastAPI, client: AsyncClient) -> None: - - response = await client.get(app.url_path_for("get_engines")) - assert response.status_code == status.HTTP_200_OK - assert len(response.json()) > 0 - - async def test_put_gns3vm(self, app: FastAPI, client: AsyncClient) -> None: - - response = await client.put(app.url_path_for("update_gns3vm_settings"), json={"vmname": "TEST VM"}) - assert response.status_code == status.HTTP_200_OK - assert response.json()["vmname"] == "TEST VM" - - async def test_get_gns3vm(self, app: FastAPI, client: AsyncClient) -> None: - response = await client.get(app.url_path_for("get_gns3vm_settings")) - assert response.status_code == status.HTTP_200_OK diff --git a/tests/api/routes/controller/test_response_models.py b/tests/api/routes/controller/test_response_models.py index 476ac8466..4712a8775 100644 --- a/tests/api/routes/controller/test_response_models.py +++ b/tests/api/routes/controller/test_response_models.py @@ -60,8 +60,6 @@ TYPED_OPERATIONS = [ ("post", "/v3/projects/{project_id}/links/{link_id}/capture/wireshark/restart"), ("get", "/v3/projects/{project_id}/nodes/{node_id}/dynamips/auto_idlepc"), ("post", "/v3/computes/{compute_id}/dynamips/auto_idlepc"), - ("get", "/v3/gns3vm/engines"), - ("get", "/v3/gns3vm/engines/{engine}/vms"), ("get", "/v3/access/acl/endpoints"), ] diff --git a/tests/conftest.py b/tests/conftest.py index f56f59ae2..0c76f5066 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -320,7 +320,7 @@ def free_console_port(port_manager, compute_project): @pytest.fixture def on_gns3vm(): """ - Mock the hostname to emulate the GNS3 VM + Mock the hostname to emulate the GNS3 VM """ with patch( diff --git a/tests/controller/gns3vm/__init__.py b/tests/controller/gns3vm/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/controller/gns3vm/test_remote_gns3_vm.py b/tests/controller/gns3vm/test_remote_gns3_vm.py deleted file mode 100644 index be1620869..000000000 --- a/tests/controller/gns3vm/test_remote_gns3_vm.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (C) 2020 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 . - -import pytest -from pydantic import SecretStr - -from gns3server.controller.gns3vm.gns3_vm_error import GNS3VMError -from gns3server.controller.gns3vm.remote_gns3_vm import RemoteGNS3VM - - -@pytest.fixture -def gns3vm(controller): - - return RemoteGNS3VM(controller) - - -@pytest.mark.asyncio -async def test_list(gns3vm, controller): - - await controller.add_compute("r1", name="R1", host="r1.local", connect=False) - res = await gns3vm.list() - assert res == [{"vmname": "R1"}] - - -@pytest.mark.asyncio -async def test_start(gns3vm, controller): - - await controller.add_compute( - "r1", - name="R1", - protocol="https", - host="r1.local", - port=8484, - user="hello", - password=SecretStr("world"), - connect=False, - ) - - gns3vm.vmname = "R1" - await gns3vm.start() - assert gns3vm.running - assert gns3vm.protocol == "https" - assert gns3vm.ip_address == "r1.local" - assert gns3vm.port == 8484 - assert gns3vm.user == "hello" - assert gns3vm.password.get_secret_value() == "world" - - -@pytest.mark.asyncio -async def test_start_invalid_vm(gns3vm, controller): - - await controller.add_compute( - "r1", - connect=False, - name="R1", - protocol="https", - host="r1.local", - port=8484, - user="hello", - password=SecretStr("world"), - ) - - gns3vm.vmname = "R2" - with pytest.raises(GNS3VMError): - await gns3vm.start() - assert not gns3vm.running diff --git a/tests/controller/gns3vm/test_virtualbox_gns3_vm.py b/tests/controller/gns3vm/test_virtualbox_gns3_vm.py deleted file mode 100644 index fe8f453c3..000000000 --- a/tests/controller/gns3vm/test_virtualbox_gns3_vm.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (C) 2020 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 . - -import pytest -import pytest_asyncio - -from gns3server.controller.gns3vm.virtualbox_gns3_vm import VirtualBoxGNS3VM -from gns3server.utils.asyncio import wait_run_in_executor -from tests.utils import asyncio_patch - - -@pytest_asyncio.fixture -async def gns3vm(controller): - - vm = VirtualBoxGNS3VM(controller) - vm.vmname = "GNS3 VM" - return vm - - -@pytest.mark.asyncio -async def test_look_for_interface(gns3vm): - - showvminfo = """ -nic1="hostonly" -nictype1="82540EM" -nicspeed1="0" -nic2="nat" -nictype2="82540EM" -nicspeed2="0" -nic3="none" -nic4="none" -nic5="none" -nic6="none" -nic7="none" -nic8="none" -vcpwidth=1024 -vcpheight=768 -vcprate=512 -vcpfps=25 -GuestMemoryBalloon=0 - """ - - with asyncio_patch( - "gns3server.controller.gns3vm.virtualbox_gns3_vm.VirtualBoxGNS3VM._execute", return_value=showvminfo - ) as mock: - res = await gns3vm._look_for_interface("nat") - mock.assert_called_with("showvminfo", ["GNS3 VM", "--machinereadable"]) - assert res == 2 - - # with asyncio_patch("gns3server.controller.gns3vm.virtualbox_gns3_vm.VirtualBoxGNS3VM._execute") as mock: - # mock.side_effect = execute_mock - # res = await gns3vm._look_for_interface("dummy") - # assert mock.called - # assert res == -1 - - -@pytest.mark.asyncio -async def test_cpu_vendor_id(gns3vm): - - from cpuinfo import get_cpu_info - - cpu_info = await wait_run_in_executor(get_cpu_info) - vendor_id = cpu_info.get("vendor_id_raw") - assert vendor_id # vendor id should not be empty diff --git a/tests/controller/gns3vm/test_vmware_gns3_vm.py b/tests/controller/gns3vm/test_vmware_gns3_vm.py deleted file mode 100644 index 92d8a9cd7..000000000 --- a/tests/controller/gns3vm/test_vmware_gns3_vm.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (C) 2020 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 . - -import pytest -import pytest_asyncio - -from gns3server.controller.gns3vm.vmware_gns3_vm import VMwareGNS3VM - - -@pytest_asyncio.fixture -async def gns3vm(controller): - - vm = VMwareGNS3VM(controller) - vm.vmname = "GNS3 VM" - return vm - - -@pytest.fixture -def vmx_path(tmpdir): - - return str(tmpdir / "vmwware_vm.vmx") diff --git a/tests/controller/test_controller.py b/tests/controller/test_controller.py index 0914c5d3d..c075dde3a 100644 --- a/tests/controller/test_controller.py +++ b/tests/controller/test_controller.py @@ -342,8 +342,6 @@ async def test_getProject(controller): @pytest.mark.asyncio async def test_start(controller): - controller.gns3vm.settings = {"enable": False, "engine": "vmware", "vmname": "GNS3 VM"} - # with asyncio_patch("gns3server.controller.compute.Compute.connect") as mock: with asyncio_patch("gns3server.controller.Controller._install_builtin_disks", return_value=[]): await controller.start() @@ -352,25 +350,6 @@ async def test_start(controller): assert controller.computes["local"].name == f"{socket.gethostname()} (controller)" -@pytest.mark.asyncio -async def test_start_vm(controller): - """ - Start the controller with a GNS3 VM - """ - - controller.gns3vm.settings = {"enable": True, "engine": "vmware", "vmname": "GNS3 VM"} - - with asyncio_patch("gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.start") as mock: - with asyncio_patch("gns3server.controller.gns3vm.GNS3VM._check_network"): - with asyncio_patch("gns3server.controller.compute.Compute.connect"): - with asyncio_patch("gns3server.controller.Controller._install_builtin_disks", return_value=[]): - await controller.start() - assert mock.called - assert "local" in controller.computes - assert "vm" in controller.computes - assert len(controller.computes) == 2 # Local compute and vm are created - - @pytest.mark.asyncio async def test_stop(controller): @@ -380,48 +359,6 @@ async def test_stop(controller): assert c.connected is False -@pytest.mark.asyncio -async def test_stop_vm(controller): - """ - Stop GNS3 VM if configured - """ - - controller.gns3vm.settings = {"enable": True, "engine": "vmware", "when_exit": "stop", "vmname": "GNS3 VM"} - - controller.gns3vm.current_engine().running = True - with asyncio_patch("gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.stop") as mock: - await controller.stop() - assert mock.called - - -@pytest.mark.asyncio -async def test_suspend_vm(controller): - """ - Suspend GNS3 VM if configured - """ - - controller.gns3vm.settings = {"enable": True, "engine": "vmware", "when_exit": "suspend", "vmname": "GNS3 VM"} - - controller.gns3vm.current_engine().running = True - with asyncio_patch("gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.suspend") as mock: - await controller.stop() - assert mock.called - - -@pytest.mark.asyncio -async def test_keep_vm(controller): - """ - Keep GNS3 VM if configured - """ - - controller.gns3vm.settings = {"enable": True, "engine": "vmware", "when_exit": "keep", "vmname": "GNS3 VM"} - - controller.gns3vm.current_engine().running = True - with asyncio_patch("gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.suspend") as mock: - await controller.stop() - assert not mock.called - - @pytest.mark.asyncio async def test_get_free_project_name(controller): diff --git a/tests/controller/test_gns3vm.py b/tests/controller/test_gns3vm.py deleted file mode 100644 index f0f03a0d2..000000000 --- a/tests/controller/test_gns3vm.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (C) 2020 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 . - - -import pytest -from pydantic import SecretStr - -from gns3server.controller.gns3vm import GNS3VM -from gns3server.controller.gns3vm.gns3_vm_error import GNS3VMError -from tests.utils import AsyncioMagicMock, asyncio_patch - - -@pytest.fixture -def dummy_engine(): - - engine = AsyncioMagicMock() - engine.running = False - engine.ip_address = "vm.local" - engine.protocol = "https" - engine.port = 8442 - engine.user = "hello" - engine.password = SecretStr("world") - return engine - - -@pytest.fixture -def dummy_gns3vm(controller, dummy_engine): - - vm = GNS3VM(controller) - vm._settings["engine"] = "dummy" - vm._settings["vmname"] = "Test VM" - vm._settings["enable"] = True - vm._engines["dummy"] = dummy_engine - return vm - - -@pytest.mark.asyncio -async def test_list(controller): - - vm = GNS3VM(controller) - with asyncio_patch( - "gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.list", - return_value=[{"vmname": "test", "vmx_path": "test"}], - ): - res = await vm.list("vmware") - assert res == [{"vmname": "test"}] # Information specific to VMware is stripped - with asyncio_patch( - "gns3server.controller.gns3vm.virtualbox_gns3_vm.VirtualBoxGNS3VM.list", return_value=[{"vmname": "test"}] - ): - res = await vm.list("virtualbox") - assert res == [{"vmname": "test"}] - with pytest.raises(NotImplementedError): - await vm.list("hyperv") - - -@pytest.mark.asyncio -async def test_json(controller): - - vm = GNS3VM(controller) - assert vm.asdict() == vm._settings - - -@pytest.mark.asyncio -async def test_update_settings(controller): - - vm = GNS3VM(controller) - vm.settings = {"enable": True, "engine": "vmware", "vmname": "GNS3 VM"} - - with asyncio_patch("gns3server.controller.gns3vm.vmware_gns3_vm.VMwareGNS3VM.start"): - with asyncio_patch("gns3server.controller.gns3vm.GNS3VM._check_network"): - await vm.auto_start_vm() - assert "vm" in controller.computes - await vm.update_settings({"enable": False}) - assert "vm" not in controller.computes - - -@pytest.mark.asyncio -async def test_auto_start(controller, dummy_gns3vm, dummy_engine): - """ - When start the compute should be add to the controller - """ - - with asyncio_patch("gns3server.controller.gns3vm.GNS3VM._check_network"): - await dummy_gns3vm.auto_start_vm() - assert dummy_engine.start.called - assert controller.computes["vm"].name == "GNS3 VM (Test VM)" - assert controller.computes["vm"].host == "vm.local" - assert controller.computes["vm"].port == 80 - assert controller.computes["vm"].protocol == "https" - assert controller.computes["vm"].user == "hello" - assert controller.computes["vm"].password.get_secret_value() == "world" - - -@pytest.mark.asyncio -async def test_auto_start_with_error(controller, dummy_gns3vm, dummy_engine): - - dummy_engine.start.side_effect = GNS3VMError("Dummy error") - await dummy_gns3vm.auto_start_vm() - assert dummy_engine.start.called - assert controller.computes["vm"].name == "GNS3 VM (Test VM)"