Drop Python 3.4 and switch to async / await syntax for asyncio. Fixes #1425

This commit is contained in:
grossmj committed 2018-10-15 17:05:49 +07:00
1 parent 8baa480b79
commit 76af98404a
119 files changed
+2432 -3084

No files matched your search

+30 -38
View File
@@ -21,7 +21,7 @@ import asyncio
import aiohttp
import ipaddress
from ...utils.asyncio import locking, asyncio_ensure_future
from ...utils.asyncio import locking
from .vmware_gns3_vm import VMwareGNS3VM
from .virtualbox_gns3_vm import VirtualBoxGNS3VM
from .hyperv_gns3_vm import HyperVGNS3VM
@@ -204,8 +204,7 @@ class GNS3VM:
self._settings.update(val)
@asyncio.coroutine
def update_settings(self, settings):
async def update_settings(self, settings):
"""
Update settings and will restart the VM if require
"""
@@ -213,15 +212,15 @@ class GNS3VM:
new_settings = copy.copy(self._settings)
new_settings.update(settings)
if self.settings != new_settings:
yield from self._stop()
await self._stop()
self._settings = settings
self._controller.save()
if self.enable:
yield from self.start()
await self.start()
else:
# When user fix something on his system and try again
if self.enable and not self.current_engine().running:
yield from self.start()
await self.start()
def _get_engine(self, engine):
"""
@@ -248,8 +247,7 @@ class GNS3VM:
def __json__(self):
return self._settings
@asyncio.coroutine
def list(self, engine):
async def list(self, engine):
"""
List VMS for an engine
"""
@@ -257,7 +255,7 @@ class GNS3VM:
engine = self._get_engine(engine)
vms = []
try:
for vm in (yield from engine.list()):
for vm in (await engine.list()):
vms.append({"vmname": vm["vmname"]})
except GNS3VMError as e:
# We raise error only if user activated the GNS3 VM
@@ -266,19 +264,18 @@ class GNS3VM:
raise e
return vms
@asyncio.coroutine
def auto_start_vm(self):
async def auto_start_vm(self):
"""
Auto start the GNS3 VM if require
"""
if self.enable:
try:
yield from self.start()
await self.start()
except GNS3VMError as e:
# User will receive the error later when they will try to use the node
try:
compute = yield from self._controller.add_compute(compute_id="vm",
compute = await self._controller.add_compute(compute_id="vm",
name="GNS3 VM ({})".format(self.current_engine().vmname),
host=None,
force=True)
@@ -288,21 +285,19 @@ class GNS3VM:
pass
log.error("Cannot start the GNS3 VM: {}".format(e))
@asyncio.coroutine
def exit_vm(self):
async def exit_vm(self):
if self.enable:
try:
if self._settings["when_exit"] == "stop":
yield from self._stop()
await self._stop()
elif self._settings["when_exit"] == "suspend":
yield from self._suspend()
await self._suspend()
except GNS3VMError as e:
log.warning(str(e))
@locking
@asyncio.coroutine
def start(self):
async def start(self):
"""
Start the GNS3 VM
"""
@@ -316,22 +311,22 @@ class GNS3VM:
engine.ram = self._settings["ram"]
engine.vcpus = self._settings["vcpus"]
engine.headless = self._settings["headless"]
compute = yield from self._controller.add_compute(compute_id="vm",
compute = await self._controller.add_compute(compute_id="vm",
name="GNS3 VM is starting ({})".format(engine.vmname),
host=None,
force=True,
connect=False)
try:
yield from engine.start()
await engine.start()
except Exception as e:
yield from self._controller.delete_compute("vm")
await self._controller.delete_compute("vm")
log.error("Cannot start the GNS3 VM: {}".format(str(e)))
yield from compute.update(name="GNS3 VM ({})".format(engine.vmname))
await compute.update(name="GNS3 VM ({})".format(engine.vmname))
compute.set_last_error(str(e))
raise e
yield from compute.connect() # we can connect now that the VM has started
yield from compute.update(name="GNS3 VM ({})".format(engine.vmname),
await compute.connect() # we can connect now that the VM has started
await compute.update(name="GNS3 VM ({})".format(engine.vmname),
protocol=self.protocol,
host=self.ip_address,
port=self.port,
@@ -340,16 +335,15 @@ class GNS3VM:
# 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)))
asyncio.get_event_loop().call_later(10, lambda: asyncio.ensure_future(self._check_network(compute)))
@asyncio.coroutine
def _check_network(self, compute):
async def _check_network(self, compute):
"""
Check that the VM is in the same subnet as the local server
"""
try:
vm_interfaces = yield from compute.interfaces()
vm_interfaces = await compute.interfaces()
vm_interface_netmask = None
for interface in vm_interfaces:
if interface["ip_address"] == self.ip_address:
@@ -360,7 +354,7 @@ class GNS3VM:
for compute_id in self._controller.computes:
if compute_id == "local":
compute = self._controller.get_compute(compute_id)
interfaces = yield from compute.interfaces()
interfaces = await compute.interfaces()
netmask = None
for interface in interfaces:
if interface["ip_address"] == compute.host_ip:
@@ -378,27 +372,25 @@ class GNS3VM:
log.warning("Could not check the VM is in the same subnet as the local server: {}".format(e.text))
@locking
@asyncio.coroutine
def _suspend(self):
async def _suspend(self):
"""
Suspend the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
yield from self._controller.delete_compute("vm")
await self._controller.delete_compute("vm")
if engine.running:
log.info("Suspend the GNS3 VM")
yield from engine.suspend()
await engine.suspend()
@locking
@asyncio.coroutine
def _stop(self):
async def _stop(self):
"""
Stop the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
yield from self._controller.delete_compute("vm")
await self._controller.delete_compute("vm")
if engine.running:
log.info("Stop the GNS3 VM")
yield from engine.stop()
await engine.stop()
+4 -8
View File
@@ -254,32 +254,28 @@ class BaseGNS3VM:
return self._engine
@asyncio.coroutine
def list(self):
async def list(self):
"""
List all VMs
"""
raise NotImplementedError
@asyncio.coroutine
def start(self):
async def start(self):
"""
Starts the GNS3 VM.
"""
raise NotImplementedError
@asyncio.coroutine
def suspend(self):
async def suspend(self):
"""
Suspend the GNS3 VM.
"""
raise NotImplementedError
@asyncio.coroutine
def stop(self):
async def stop(self):
"""
Stops the GNS3 VM.
"""
+10 -15
View File
@@ -164,8 +164,7 @@ class HyperVGNS3VM(BaseGNS3VM):
except Exception as e:
raise GNS3VMError("Could not set to {} and RAM amount set to {}: {}".format(vcpus, ram, e))
@asyncio.coroutine
def list(self):
async def list(self):
"""
List all Hyper-V VMs
"""
@@ -189,8 +188,7 @@ class HyperVGNS3VM(BaseGNS3VM):
return wmi.WMI(moniker=path.replace('\\', '/'))
@asyncio.coroutine
def _set_state(self, state):
async def _set_state(self, state):
"""
Set the desired state of the VM
"""
@@ -203,15 +201,14 @@ class HyperVGNS3VM(BaseGNS3VM):
if ret == HyperVGNS3VM._WMI_JOB_STATUS_STARTED:
job = self._get_wmi_obj(job_path)
while job.JobState == HyperVGNS3VM._WMI_JOB_STATE_RUNNING:
yield from asyncio.sleep(0.1)
await asyncio.sleep(0.1)
job = self._get_wmi_obj(job_path)
if job.JobState != HyperVGNS3VM._WMI_JOB_STATE_COMPLETED:
raise GNS3VMError("Error while changing state: {}".format(job.ErrorSummaryDescription))
elif ret != 0 or ret != 32775:
raise GNS3VMError("Failed to change state to {}".format(state))
@asyncio.coroutine
def start(self):
async def start(self):
"""
Starts the GNS3 VM.
"""
@@ -228,7 +225,7 @@ class HyperVGNS3VM(BaseGNS3VM):
# start the VM
try:
yield from self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_ENABLED)
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_ENABLED)
except GNS3VMError as e:
raise GNS3VMError("Failed to start the GNS3 VM: {}".format(e))
log.info("GNS3 VM has been started")
@@ -259,32 +256,30 @@ class HyperVGNS3VM(BaseGNS3VM):
break
elif trial == 0:
raise GNS3VMError("Could not find guest IP address for {}".format(self.vmname))
yield from asyncio.sleep(1)
await asyncio.sleep(1)
self.ip_address = guest_ip_address
log.info("GNS3 VM IP address set to {}".format(guest_ip_address))
self.running = True
@asyncio.coroutine
def suspend(self):
async def suspend(self):
"""
Suspends the GNS3 VM.
"""
try:
yield from self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_PAUSED)
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_PAUSED)
except GNS3VMError as e:
raise GNS3VMError("Failed to suspend the GNS3 VM: {}".format(e))
log.info("GNS3 VM has been suspended")
self.running = False
@asyncio.coroutine
def stop(self):
async def stop(self):
"""
Stops the GNS3 VM.
"""
try:
yield from self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_SHUTDOWN)
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_SHUTDOWN)
except GNS3VMError as e:
raise GNS3VMError("Failed to stop the GNS3 VM: {}".format(e))
log.info("GNS3 VM has been stopped")
@@ -32,8 +32,7 @@ class RemoteGNS3VM(BaseGNS3VM):
self._engine = "remote"
super().__init__(controller)
@asyncio.coroutine
def list(self):
async def list(self):
"""
List all VMs
"""
@@ -45,8 +44,7 @@ class RemoteGNS3VM(BaseGNS3VM):
res.append({"vmname": compute.name})
return res
@asyncio.coroutine
def start(self):
async def start(self):
"""
Starts the GNS3 VM.
"""
@@ -65,15 +63,13 @@ class RemoteGNS3VM(BaseGNS3VM):
return
raise GNS3VMError("Can't start the GNS3 VM remote VM {} not found".format(self.vmname))
@asyncio.coroutine
def suspend(self):
async def suspend(self):
"""
Suspend do nothing for remote server
"""
self.running = False
@asyncio.coroutine
def stop(self):
async def stop(self):
"""
Stops the GNS3 VM.
"""
@@ -40,24 +40,22 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
super().__init__(controller)
self._virtualbox_manager = VirtualBox()
@asyncio.coroutine
def _execute(self, subcommand, args, timeout=60):
async def _execute(self, subcommand, args, timeout=60):
try:
result = yield from self._virtualbox_manager.execute(subcommand, args, timeout)
result = await self._virtualbox_manager.execute(subcommand, args, timeout)
return ("\n".join(result))
except VirtualBoxError as e:
raise GNS3VMError("Error while executing VBoxManage command: {}".format(e))
@asyncio.coroutine
def _get_state(self):
async def _get_state(self):
"""
Returns the VM state (e.g. running, paused etc.)
:returns: state (string)
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
@@ -65,15 +63,14 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
return value.strip('"')
return "unknown"
@asyncio.coroutine
def _look_for_interface(self, network_backend):
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 = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
interface = -1
for info in result.splitlines():
if '=' in info:
@@ -86,15 +83,14 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
continue
return interface
@asyncio.coroutine
def _look_for_vboxnet(self, interface_number):
async def _look_for_vboxnet(self, interface_number):
"""
Look for the VirtualBox network name associated with a host only interface.
:returns: None or vboxnet name
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
@@ -102,8 +98,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
return value.strip('"')
return None
@asyncio.coroutine
def _check_dhcp_server(self, vboxnet):
async def _check_dhcp_server(self, vboxnet):
"""
Check if the DHCP server associated with a vboxnet is enabled.
@@ -111,7 +106,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
:returns: boolean
"""
properties = yield from self._execute("list", ["dhcpservers"])
properties = await self._execute("list", ["dhcpservers"])
flag_dhcp_server_found = False
for prop in properties.splitlines():
try:
@@ -125,8 +120,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
return True
return False
@asyncio.coroutine
def _check_vboxnet_exists(self, vboxnet):
async def _check_vboxnet_exists(self, vboxnet):
"""
Check if the vboxnet interface exists
@@ -134,7 +128,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
:returns: boolean
"""
properties = yield from self._execute("list", ["hostonlyifs"])
properties = await self._execute("list", ["hostonlyifs"])
for prop in properties.splitlines():
try:
name, value = prop.split(':', 1)
@@ -144,13 +138,12 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
return True
return False
@asyncio.coroutine
def _find_first_available_vboxnet(self):
async def _find_first_available_vboxnet(self):
"""
Find the first available vboxnet.
"""
properties = yield from self._execute("list", ["hostonlyifs"])
properties = await self._execute("list", ["hostonlyifs"])
for prop in properties.splitlines():
try:
name, value = prop.split(':', 1)
@@ -160,15 +153,14 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
return value.strip()
return None
@asyncio.coroutine
def _check_vbox_port_forwarding(self):
async def _check_vbox_port_forwarding(self):
"""
Checks if the NAT port forwarding rule exists.
:returns: boolean
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
result = await self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
@@ -176,66 +168,64 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
return True
return False
@asyncio.coroutine
def list(self):
async def list(self):
"""
List all VirtualBox VMs
"""
return (yield from self._virtualbox_manager.list_vms())
return (await self._virtualbox_manager.list_vms())
@asyncio.coroutine
def start(self):
async def start(self):
"""
Start the GNS3 VM.
"""
# get a NAT interface number
nat_interface_number = yield from self._look_for_interface("nat")
nat_interface_number = await self._look_for_interface("nat")
if nat_interface_number < 0:
raise GNS3VMError('VM "{}" must have a NAT interface configured in order to start'.format(self.vmname))
hostonly_interface_number = yield from self._look_for_interface("hostonly")
hostonly_interface_number = await self._look_for_interface("hostonly")
if hostonly_interface_number < 0:
raise GNS3VMError('VM "{}" must have a host-only interface configured in order to start'.format(self.vmname))
vboxnet = yield from self._look_for_vboxnet(hostonly_interface_number)
vboxnet = await self._look_for_vboxnet(hostonly_interface_number)
if vboxnet is None:
raise GNS3VMError('A VirtualBox host-only network could not be found on network adapter {} for "{}"'.format(hostonly_interface_number, self._vmname))
if not (yield from self._check_vboxnet_exists(vboxnet)):
if not (await self._check_vboxnet_exists(vboxnet)):
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 = yield from self._find_first_available_vboxnet()
first_available_vboxnet = await self._find_first_available_vboxnet()
if first_available_vboxnet is None:
raise GNS3VMError('Please add a VirtualBox host-only network with DHCP enabled and attached it to network adapter {} for "{}"'.format(hostonly_interface_number, self._vmname))
yield from self.set_hostonly_network(hostonly_interface_number, first_available_vboxnet)
await self.set_hostonly_network(hostonly_interface_number, first_available_vboxnet)
vboxnet = first_available_vboxnet
else:
raise GNS3VMError('VirtualBox host-only network "{}" does not exist, please make the sure the network adapter {} configuration is valid for "{}"'.format(vboxnet,
hostonly_interface_number,
self._vmname))
if not (yield from self._check_dhcp_server(vboxnet)):
if not (await self._check_dhcp_server(vboxnet)):
raise GNS3VMError('DHCP must be enabled on VirtualBox host-only network "{}"'.format(vboxnet))
vm_state = yield from self._get_state()
vm_state = await self._get_state()
log.info('"{}" state is {}'.format(self._vmname, vm_state))
if vm_state == "poweroff":
yield from self.set_vcpus(self.vcpus)
yield from self.set_ram(self.ram)
await self.set_vcpus(self.vcpus)
await self.set_ram(self.ram)
if vm_state in ("poweroff", "saved"):
# start the VM if it is not running
args = [self._vmname]
if self._headless:
args.extend(["--type", "headless"])
yield from self._execute("startvm", args)
await self._execute("startvm", args)
elif vm_state == "paused":
args = [self._vmname, "resume"]
yield from self._execute("controlvm", args)
await self._execute("controlvm", args)
ip_address = "127.0.0.1"
try:
# get a random port on localhost
@@ -246,23 +236,22 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
except OSError as e:
raise GNS3VMError("Error while getting random port: {}".format(e))
if (yield from self._check_vbox_port_forwarding()):
if (await self._check_vbox_port_forwarding()):
# delete the GNS3VM NAT port forwarding rule if it exists
log.info("Removing GNS3VM NAT port forwarding rule from interface {}".format(nat_interface_number))
yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "delete", "GNS3VM"])
await self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "delete", "GNS3VM"])
# add a GNS3VM NAT port forwarding rule to redirect 127.0.0.1 with random port to port 3080 in the VM
log.info("Adding GNS3VM NAT port forwarding rule with port {} to interface {}".format(api_port, nat_interface_number))
yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number),
await self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number),
"GNS3VM,tcp,{},{},,3080".format(ip_address, api_port)])
self.ip_address = yield from self._get_ip(hostonly_interface_number, api_port)
self.ip_address = await self._get_ip(hostonly_interface_number, api_port)
self.port = 3080
log.info("GNS3 VM has been started with IP {}".format(self.ip_address))
self.running = True
@asyncio.coroutine
def _get_ip(self, hostonly_interface_number, api_port):
async def _get_ip(self, hostonly_interface_number, api_port):
"""
Get the IP from VirtualBox.
@@ -276,14 +265,14 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
session = aiohttp.ClientSession()
try:
resp = None
resp = yield from session.get('http://127.0.0.1:{}/v2/compute/network/interfaces'.format(api_port))
resp = await session.get('http://127.0.0.1:{}/v2/compute/network/interfaces'.format(api_port))
except (OSError, aiohttp.ClientError, TimeoutError, asyncio.TimeoutError):
pass
if resp:
if resp.status < 300:
try:
json_data = yield from resp.json()
json_data = await resp.json()
except ValueError:
pass
resp.close()
@@ -296,35 +285,33 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
if "ip_address" in interface and len(interface["ip_address"]) > 0:
return interface["ip_address"]
remaining_try -= 1
yield from asyncio.sleep(1)
await asyncio.sleep(1)
raise GNS3VMError("Could not get the GNS3 VM ip make sure the VM receive an IP from VirtualBox")
@asyncio.coroutine
def suspend(self):
async def suspend(self):
"""
Suspend the GNS3 VM.
"""
yield from self._execute("controlvm", [self._vmname, "savestate"], timeout=3)
await self._execute("controlvm", [self._vmname, "savestate"], timeout=3)
log.info("GNS3 VM has been suspend")
self.running = False
@asyncio.coroutine
def stop(self):
async def stop(self):
"""
Stops the GNS3 VM.
"""
vm_state = yield from self._get_state()
vm_state = await self._get_state()
if vm_state == "poweroff":
self.running = False
return
yield from self._execute("controlvm", [self._vmname, "acpipowerbutton"], timeout=3)
await self._execute("controlvm", [self._vmname, "acpipowerbutton"], timeout=3)
trial = 120
while True:
try:
vm_state = yield from self._get_state()
vm_state = await self._get_state()
# During a small amount of time the command will fail
except GNS3VMError:
vm_state = "running"
@@ -332,37 +319,34 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
break
trial -= 1
if trial == 0:
yield from self._execute("controlvm", [self._vmname, "poweroff"], timeout=3)
await self._execute("controlvm", [self._vmname, "poweroff"], timeout=3)
break
yield from asyncio.sleep(1)
await asyncio.sleep(1)
log.info("GNS3 VM has been stopped")
self.running = False
@asyncio.coroutine
def set_vcpus(self, vcpus):
async def set_vcpus(self, vcpus):
"""
Set the number of vCPU cores for the GNS3 VM.
:param vcpus: number of vCPU cores
"""
yield from self._execute("modifyvm", [self._vmname, "--cpus", str(vcpus)], timeout=3)
await self._execute("modifyvm", [self._vmname, "--cpus", str(vcpus)], timeout=3)
log.info("GNS3 VM vCPU count set to {}".format(vcpus))
@asyncio.coroutine
def set_ram(self, ram):
async def set_ram(self, ram):
"""
Set the RAM amount for the GNS3 VM.
:param ram: amount of memory
"""
yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
await self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
log.info("GNS3 VM RAM amount set to {}".format(ram))
@asyncio.coroutine
def set_hostonly_network(self, adapter_number, hostonly_network_name):
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.
@@ -370,7 +354,7 @@ class VirtualBoxGNS3VM(BaseGNS3VM):
:param hostonly_network_name: name of the VirtualBox host-only network
"""
yield from self._execute("modifyvm", [self._vmname, "--hostonlyadapter{}".format(adapter_number), hostonly_network_name], timeout=3)
await self._execute("modifyvm", [self._vmname, "--hostonlyadapter{}".format(adapter_number), hostonly_network_name], timeout=3)
log.info('VirtualBox host-only network "{}" set on network adapter {} for "{}"'.format(hostonly_network_name,
adapter_number,
self._vmname))
+22 -30
View File
@@ -43,24 +43,21 @@ class VMwareGNS3VM(BaseGNS3VM):
def vmx_path(self):
return self._vmx_path
@asyncio.coroutine
def _execute(self, subcommand, args, timeout=60, log_level=logging.INFO):
async def _execute(self, subcommand, args, timeout=60, log_level=logging.INFO):
try:
result = yield from self._vmware_manager.execute(subcommand, args, timeout, log_level=log_level)
result = await self._vmware_manager.execute(subcommand, args, timeout, log_level=log_level)
return (''.join(result))
except VMwareError as e:
raise GNS3VMError("Error while executing VMware command: {}".format(e))
@asyncio.coroutine
def _is_running(self):
result = yield from self._vmware_manager.execute("list", [])
async def _is_running(self):
result = await self._vmware_manager.execute("list", [])
if self._vmx_path in result:
return True
return False
@asyncio.coroutine
def _set_vcpus_ram(self, vcpus, ram):
async def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
@@ -85,8 +82,7 @@ class VMwareGNS3VM(BaseGNS3VM):
except OSError as e:
raise GNS3VMError('Could not read/write VMware VMX file "{}": {}'.format(self._vmx_path, e))
@asyncio.coroutine
def _set_extra_options(self):
async def _set_extra_options(self):
try:
"""
Due to bug/change in VMWare 14 we're not able to pass Hardware Virtualization in GNS3VM.
@@ -109,23 +105,21 @@ class VMwareGNS3VM(BaseGNS3VM):
except OSError as e:
raise GNS3VMError('Could not read/write VMware VMX file "{}": {}'.format(self._vmx_path, e))
@asyncio.coroutine
def list(self):
async def list(self):
"""
List all VMware VMs
"""
try:
return (yield from self._vmware_manager.list_vms())
return (await self._vmware_manager.list_vms())
except VMwareError as e:
raise GNS3VMError("Could not list VMware VMs: {}".format(str(e)))
@asyncio.coroutine
def start(self):
async def start(self):
"""
Starts the GNS3 VM.
"""
vms = yield from self.list()
vms = await self.list()
for vm in vms:
if vm["vmname"] == self.vmname:
self._vmx_path = vm["vmx_path"]
@@ -138,25 +132,25 @@ class VMwareGNS3VM(BaseGNS3VM):
raise GNS3VMError("VMware VMX file {} doesn't exist".format(self._vmx_path))
# check if the VMware guest tools are installed
vmware_tools_state = yield from self._execute("checkToolsState", [self._vmx_path])
vmware_tools_state = await self._execute("checkToolsState", [self._vmx_path])
if vmware_tools_state not in ("installed", "running"):
raise GNS3VMError("VMware tools are not installed in {}".format(self.vmname))
try:
running = yield from self._is_running()
running = await self._is_running()
except VMwareError as e:
raise GNS3VMError("Could not list VMware VMs: {}".format(str(e)))
if not running:
log.info("Update GNS3 VM settings")
# set the number of vCPUs and amount of RAM
yield from self._set_vcpus_ram(self.vcpus, self.ram)
yield from self._set_extra_options()
await self._set_vcpus_ram(self.vcpus, self.ram)
await self._set_extra_options()
# start the VM
args = [self._vmx_path]
if self._headless:
args.extend(["nogui"])
yield from self._execute("start", args)
await self._execute("start", args)
log.info("GNS3 VM has been started")
# get the guest IP address (first adapter only)
@@ -164,7 +158,7 @@ class VMwareGNS3VM(BaseGNS3VM):
guest_ip_address = ""
log.info("Waiting for GNS3 VM IP")
while True:
guest_ip_address = yield from self._execute("readVariable", [self._vmx_path, "guestVar", "gns3.eth0"], timeout=120, log_level=logging.DEBUG)
guest_ip_address = await self._execute("readVariable", [self._vmx_path, "guestVar", "gns3.eth0"], timeout=120, log_level=logging.DEBUG)
guest_ip_address = guest_ip_address.strip()
if len(guest_ip_address) != 0:
break
@@ -172,15 +166,14 @@ class VMwareGNS3VM(BaseGNS3VM):
# If ip not found fallback on old method
if trial == 0:
log.warning("No IP found for the VM via readVariable fallback to getGuestIPAddress")
guest_ip_address = yield from self._execute("getGuestIPAddress", [self._vmx_path, "-wait"], timeout=120)
guest_ip_address = await self._execute("getGuestIPAddress", [self._vmx_path, "-wait"], timeout=120)
break
yield from asyncio.sleep(1)
await asyncio.sleep(1)
self.ip_address = guest_ip_address
log.info("GNS3 VM IP address set to {}".format(guest_ip_address))
self.running = True
@asyncio.coroutine
def suspend(self):
async def suspend(self):
"""
Suspend the GNS3 VM.
"""
@@ -188,14 +181,13 @@ class VMwareGNS3VM(BaseGNS3VM):
if self._vmx_path is None:
raise GNS3VMError("No VMX path configured, can't suspend the VM")
try:
yield from self._execute("suspend", [self._vmx_path])
await self._execute("suspend", [self._vmx_path])
except GNS3VMError as e:
log.warning("Error when suspending the VM: {}".format(str(e)))
log.info("GNS3 VM has been suspended")
self.running = False
@asyncio.coroutine
def stop(self):
async def stop(self):
"""
Stops the GNS3 VM.
"""
@@ -203,7 +195,7 @@ class VMwareGNS3VM(BaseGNS3VM):
if self._vmx_path is None:
raise GNS3VMError("No VMX path configured, can't stop the VM")
try:
yield from self._execute("stop", [self._vmx_path, "soft"])
await self._execute("stop", [self._vmx_path, "soft"])
except GNS3VMError as e:
log.warning("Error when stopping the VM: {}".format(str(e)))
log.info("GNS3 VM has been stopped")