2014-07-12 19:18:25 +00:00
|
|
|
#
|
2015-01-18 23:26:56 +00:00
|
|
|
# Copyright (C) 2015 GNS3 Technologies Inc.
|
2014-07-12 19:18:25 +00:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
"""
|
|
|
|
VirtualBox server module.
|
|
|
|
"""
|
|
|
|
|
2015-01-24 00:57:54 +00:00
|
|
|
import os
|
2019-03-18 16:29:18 +00:00
|
|
|
import re
|
2015-01-24 00:57:54 +00:00
|
|
|
import sys
|
|
|
|
import shutil
|
|
|
|
import asyncio
|
|
|
|
import subprocess
|
2015-02-03 00:00:29 +00:00
|
|
|
import logging
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
2015-01-24 00:57:54 +00:00
|
|
|
|
2015-01-18 23:26:56 +00:00
|
|
|
from ..base_manager import BaseManager
|
2014-07-12 19:18:25 +00:00
|
|
|
from .virtualbox_vm import VirtualBoxVM
|
2015-01-24 00:57:54 +00:00
|
|
|
from .virtualbox_error import VirtualBoxError
|
2014-07-12 19:18:25 +00:00
|
|
|
|
|
|
|
|
2015-01-18 23:26:56 +00:00
|
|
|
class VirtualBox(BaseManager):
|
2015-01-24 00:57:54 +00:00
|
|
|
|
2016-05-11 17:35:36 +00:00
|
|
|
_NODE_CLASS = VirtualBoxVM
|
2015-01-24 00:57:54 +00:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
|
|
super().__init__()
|
|
|
|
self._vboxmanage_path = None
|
2015-04-14 13:00:45 +00:00
|
|
|
self._execute_lock = asyncio.Lock()
|
2015-01-24 00:57:54 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def vboxmanage_path(self):
|
|
|
|
"""
|
|
|
|
Returns the path to VBoxManage.
|
|
|
|
|
|
|
|
:returns: path
|
|
|
|
"""
|
|
|
|
|
|
|
|
return self._vboxmanage_path
|
|
|
|
|
|
|
|
def find_vboxmanage(self):
|
|
|
|
|
|
|
|
# look for VBoxManage
|
2021-04-12 07:32:23 +00:00
|
|
|
vboxmanage_path = self.config.settings.VirtualBox.vboxmanage_path
|
2018-01-11 09:33:15 +00:00
|
|
|
if vboxmanage_path:
|
|
|
|
if not os.path.isabs(vboxmanage_path):
|
|
|
|
vboxmanage_path = shutil.which(vboxmanage_path)
|
|
|
|
else:
|
|
|
|
log.info("A path to VBoxManage has not been configured, trying to find it...")
|
2022-01-19 11:58:36 +00:00
|
|
|
if sys.platform.startswith("darwin"):
|
2018-01-11 09:33:15 +00:00
|
|
|
vboxmanage_path_osx = "/Applications/VirtualBox.app/Contents/MacOS/VBoxManage"
|
|
|
|
if os.path.exists(vboxmanage_path_osx):
|
|
|
|
vboxmanage_path = vboxmanage_path_osx
|
|
|
|
if not vboxmanage_path:
|
|
|
|
vboxmanage_path = shutil.which("vboxmanage")
|
2016-08-29 09:27:35 +00:00
|
|
|
|
2018-01-12 06:17:16 +00:00
|
|
|
if vboxmanage_path and not os.path.exists(vboxmanage_path):
|
2021-04-13 09:07:58 +00:00
|
|
|
log.error(f"VBoxManage path '{vboxmanage_path}' doesn't exist")
|
2015-01-24 00:57:54 +00:00
|
|
|
|
|
|
|
if not vboxmanage_path:
|
2018-01-11 09:33:15 +00:00
|
|
|
raise VirtualBoxError("Could not find VBoxManage, please reboot if VirtualBox has just been installed")
|
2015-01-24 00:57:54 +00:00
|
|
|
if not os.path.isfile(vboxmanage_path):
|
2021-04-13 09:07:58 +00:00
|
|
|
raise VirtualBoxError(f"VBoxManage '{vboxmanage_path}' is not accessible")
|
2015-01-24 00:57:54 +00:00
|
|
|
if not os.access(vboxmanage_path, os.X_OK):
|
|
|
|
raise VirtualBoxError("VBoxManage is not executable")
|
2015-04-01 15:36:22 +00:00
|
|
|
if os.path.basename(vboxmanage_path) not in ["VBoxManage", "VBoxManage.exe", "vboxmanage"]:
|
2021-04-13 09:07:58 +00:00
|
|
|
raise VirtualBoxError(f"Invalid VBoxManage executable name {os.path.basename(vboxmanage_path)}")
|
2015-01-24 00:57:54 +00:00
|
|
|
|
|
|
|
self._vboxmanage_path = vboxmanage_path
|
|
|
|
return vboxmanage_path
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
async def execute(self, subcommand, args, timeout=60):
|
2015-01-24 00:57:54 +00:00
|
|
|
|
2016-05-18 09:23:45 +00:00
|
|
|
# We use a lock prevent parallel execution due to strange errors
|
|
|
|
# reported by a user and reproduced by us.
|
2015-04-14 13:00:45 +00:00
|
|
|
# https://github.com/GNS3/gns3-gui/issues/261
|
2018-10-15 10:05:49 +00:00
|
|
|
async with self._execute_lock:
|
2015-04-14 13:00:45 +00:00
|
|
|
vboxmanage_path = self.vboxmanage_path
|
|
|
|
if not vboxmanage_path:
|
|
|
|
vboxmanage_path = self.find_vboxmanage()
|
2016-12-12 14:03:32 +00:00
|
|
|
if not vboxmanage_path:
|
2017-05-12 10:54:54 +00:00
|
|
|
raise VirtualBoxError("Could not find VBoxManage")
|
2016-12-12 14:03:32 +00:00
|
|
|
|
2015-04-14 13:00:45 +00:00
|
|
|
command = [vboxmanage_path, "--nologo", subcommand]
|
|
|
|
command.extend(args)
|
2015-06-17 23:05:58 +00:00
|
|
|
command_string = " ".join(command)
|
2021-04-13 09:07:58 +00:00
|
|
|
log.info(f"Executing VBoxManage with command: {command_string}")
|
2023-09-19 11:14:05 +00:00
|
|
|
env = os.environ.copy()
|
|
|
|
env["LANG"] = "en" # force english output because we rely on it to parse the output
|
2015-04-14 13:00:45 +00:00
|
|
|
try:
|
2021-04-13 09:16:50 +00:00
|
|
|
process = await asyncio.create_subprocess_exec(
|
2023-09-19 11:14:05 +00:00
|
|
|
*command,
|
|
|
|
stdout=asyncio.subprocess.PIPE,
|
|
|
|
stderr=asyncio.subprocess.PIPE,
|
|
|
|
env=env
|
2021-04-13 09:16:50 +00:00
|
|
|
)
|
2015-04-14 13:00:45 +00:00
|
|
|
except (OSError, subprocess.SubprocessError) as e:
|
2021-04-13 09:07:58 +00:00
|
|
|
raise VirtualBoxError(f"Could not execute VBoxManage: {e}")
|
2015-04-14 13:00:45 +00:00
|
|
|
|
|
|
|
try:
|
2018-10-15 10:05:49 +00:00
|
|
|
stdout_data, stderr_data = await asyncio.wait_for(process.communicate(), timeout=timeout)
|
2015-04-14 13:00:45 +00:00
|
|
|
except asyncio.TimeoutError:
|
2021-04-13 09:07:58 +00:00
|
|
|
raise VirtualBoxError(f"VBoxManage has timed out after {timeout} seconds!")
|
2015-04-14 13:00:45 +00:00
|
|
|
|
|
|
|
if process.returncode:
|
|
|
|
vboxmanage_error = stderr_data.decode("utf-8", errors="ignore")
|
2021-04-13 09:07:58 +00:00
|
|
|
raise VirtualBoxError(f"VirtualBox has returned an error: {vboxmanage_error}")
|
2015-04-14 13:00:45 +00:00
|
|
|
|
|
|
|
return stdout_data.decode("utf-8", errors="ignore").splitlines()
|
2015-01-24 00:57:54 +00:00
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
async def _find_inaccessible_hdd_files(self):
|
2015-04-28 18:02:21 +00:00
|
|
|
"""
|
|
|
|
Finds inaccessible disk files (to clean up the VirtualBox media manager)
|
|
|
|
"""
|
|
|
|
|
|
|
|
hdds = []
|
2015-04-29 12:21:02 +00:00
|
|
|
try:
|
2018-10-15 10:05:49 +00:00
|
|
|
properties = await self.execute("list", ["hdds"])
|
2015-04-29 12:21:02 +00:00
|
|
|
# If VirtualBox is not available we have no inaccessible hdd
|
|
|
|
except VirtualBoxError:
|
|
|
|
return hdds
|
|
|
|
|
2015-04-28 18:02:21 +00:00
|
|
|
flag_inaccessible = False
|
|
|
|
for prop in properties:
|
|
|
|
try:
|
2021-04-13 09:16:50 +00:00
|
|
|
name, value = prop.split(":", 1)
|
2015-04-28 18:02:21 +00:00
|
|
|
except ValueError:
|
|
|
|
continue
|
|
|
|
if name.strip() == "State" and value.strip() == "inaccessible":
|
|
|
|
flag_inaccessible = True
|
|
|
|
if flag_inaccessible and name.strip() == "Location":
|
|
|
|
hdds.append(value.strip())
|
|
|
|
flag_inaccessible = False
|
|
|
|
return reversed(hdds)
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
async def project_closed(self, project):
|
2015-04-28 18:02:21 +00:00
|
|
|
"""
|
|
|
|
Called when a project is closed.
|
|
|
|
|
|
|
|
:param project: Project instance
|
|
|
|
"""
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
await super().project_closed(project)
|
|
|
|
hdd_files_to_close = await self._find_inaccessible_hdd_files()
|
2015-04-28 18:02:21 +00:00
|
|
|
for hdd_file in hdd_files_to_close:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.info(f"Closing VirtualBox VM disk file {os.path.basename(hdd_file)}")
|
2015-04-28 18:02:21 +00:00
|
|
|
try:
|
2018-10-15 10:05:49 +00:00
|
|
|
await self.execute("closemedium", ["disk", hdd_file])
|
2015-04-28 18:02:21 +00:00
|
|
|
except VirtualBoxError as e:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.warning(f"Could not close VirtualBox VM disk file {os.path.basename(hdd_file)}: {e}")
|
2015-04-28 18:02:21 +00:00
|
|
|
continue
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
async def list_vms(self, allow_clone=False):
|
2015-01-24 00:57:54 +00:00
|
|
|
"""
|
|
|
|
Gets VirtualBox VM list.
|
|
|
|
"""
|
|
|
|
|
2016-05-11 17:35:36 +00:00
|
|
|
vbox_vms = []
|
2018-10-15 10:05:49 +00:00
|
|
|
result = await self.execute("list", ["vms"])
|
2015-01-24 00:57:54 +00:00
|
|
|
for line in result:
|
2015-06-03 09:59:53 +00:00
|
|
|
if len(line) == 0 or line[0] != '"' or line[-1:] != "}":
|
2015-07-13 01:03:15 +00:00
|
|
|
continue # Broken output (perhaps a carriage return in VM name)
|
2019-03-18 16:29:18 +00:00
|
|
|
match = re.search(r"\"(.*)\"\ {(.*)}", line)
|
|
|
|
if not match:
|
|
|
|
continue
|
|
|
|
vmname = match.group(1)
|
|
|
|
uuid = match.group(2)
|
2015-01-24 00:57:54 +00:00
|
|
|
if vmname == "<inaccessible>":
|
|
|
|
continue # ignore inaccessible VMs
|
2019-03-18 16:29:18 +00:00
|
|
|
extra_data = await self.execute("getextradata", [uuid, "GNS3/Clone"])
|
2017-01-31 17:58:43 +00:00
|
|
|
if allow_clone or len(extra_data) == 0 or not extra_data[0].strip() == "Value: yes":
|
2015-03-13 23:13:36 +00:00
|
|
|
# get the amount of RAM
|
2019-03-18 16:29:18 +00:00
|
|
|
info_results = await self.execute("showvminfo", [uuid, "--machinereadable"])
|
2015-04-25 15:36:28 +00:00
|
|
|
ram = 0
|
2015-03-13 23:13:36 +00:00
|
|
|
for info in info_results:
|
|
|
|
try:
|
2021-04-13 09:16:50 +00:00
|
|
|
name, value = info.split("=", 1)
|
2015-03-13 23:13:36 +00:00
|
|
|
if name.strip() == "memory":
|
|
|
|
ram = int(value.strip())
|
|
|
|
break
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2016-05-11 17:35:36 +00:00
|
|
|
vbox_vms.append({"vmname": vmname, "ram": ram})
|
|
|
|
return vbox_vms
|
2015-02-09 01:10:04 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2015-02-26 01:55:35 +00:00
|
|
|
def get_legacy_vm_workdir(legacy_vm_id, name):
|
2015-02-09 01:10:04 +00:00
|
|
|
"""
|
2016-05-11 17:35:36 +00:00
|
|
|
Returns the name of the legacy working directory name for a node.
|
2015-02-09 01:10:04 +00:00
|
|
|
|
2016-05-11 17:35:36 +00:00
|
|
|
:param legacy_vm_id: legacy node identifier (not used)
|
|
|
|
:param name: node name
|
2015-02-26 01:55:35 +00:00
|
|
|
|
2015-02-09 01:10:04 +00:00
|
|
|
:returns: working directory name
|
|
|
|
"""
|
|
|
|
|
2021-04-13 09:07:58 +00:00
|
|
|
return os.path.join("vbox", f"{name}")
|