1
0
mirror of https://github.com/GNS3/gns3-server synced 2024-11-28 03:08:14 +00:00

%guest-cid% variable implementation for Qemu VMs. Fixes https://github.com/GNS3/gns3-gui/issues/2804

This commit is contained in:
grossmj 2019-06-04 18:00:44 +02:00
parent e9154f6af6
commit 9cce4de190
6 changed files with 75 additions and 4 deletions

View File

@ -30,6 +30,7 @@ from ...utils.asyncio import subprocess_check_output
from ..base_manager import BaseManager from ..base_manager import BaseManager
from .qemu_error import QemuError from .qemu_error import QemuError
from .qemu_vm import QemuVM from .qemu_vm import QemuVM
from .utils.guest_cid import get_next_guest_cid
import logging import logging
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -40,6 +41,26 @@ class Qemu(BaseManager):
_NODE_CLASS = QemuVM _NODE_CLASS = QemuVM
_NODE_TYPE = "qemu" _NODE_TYPE = "qemu"
def __init__(self):
super().__init__()
self._guest_cid_lock = asyncio.Lock()
async def create_node(self, *args, **kwargs):
"""
Creates a new Qemu VM.
:returns: QemuVM instance
"""
async with self._guest_cid_lock:
# wait for a node to be completely created before adding a new one
# this is important otherwise we allocate the same application ID
# when creating multiple Qemu VMs at the same time
guest_cid = get_next_guest_cid(self.nodes)
node = await super().create_node(*args, guest_cid=guest_cid, **kwargs)
return node
@staticmethod @staticmethod
async def get_kvm_archs(): async def get_kvm_archs():
""" """

View File

@ -36,6 +36,7 @@ import json
from gns3server.utils import parse_version from gns3server.utils import parse_version
from gns3server.utils.asyncio import subprocess_check_output, cancellable_wait_run_in_executor from gns3server.utils.asyncio import subprocess_check_output, cancellable_wait_run_in_executor
from .qemu_error import QemuError from .qemu_error import QemuError
from .utils.qcow2 import Qcow2, Qcow2Error
from ..adapters.ethernet_adapter import EthernetAdapter from ..adapters.ethernet_adapter import EthernetAdapter
from ..nios.nio_udp import NIOUDP from ..nios.nio_udp import NIOUDP
from ..nios.nio_tap import NIOTAP from ..nios.nio_tap import NIOTAP
@ -43,7 +44,6 @@ from ..base_node import BaseNode
from ...schemas.qemu import QEMU_OBJECT_SCHEMA, QEMU_PLATFORMS from ...schemas.qemu import QEMU_OBJECT_SCHEMA, QEMU_PLATFORMS
from ...utils.asyncio import monitor_process from ...utils.asyncio import monitor_process
from ...utils.images import md5sum from ...utils.images import md5sum
from .qcow2 import Qcow2, Qcow2Error
from ...utils import macaddress_to_int, int_to_macaddress from ...utils import macaddress_to_int, int_to_macaddress
@ -67,7 +67,7 @@ class QemuVM(BaseNode):
:param platform: Platform to emulate :param platform: Platform to emulate
""" """
def __init__(self, name, node_id, project, manager, linked_clone=True, qemu_path=None, console=None, console_type="telnet", platform=None): def __init__(self, name, node_id, project, manager, guest_cid=None, linked_clone=True, qemu_path=None, console=None, console_type="telnet", platform=None):
super().__init__(name, node_id, project, manager, console=console, console_type=console_type, linked_clone=linked_clone, wrap_console=True) super().__init__(name, node_id, project, manager, console=console, console_type=console_type, linked_clone=linked_clone, wrap_console=True)
server_config = manager.config.get_section_config("Server") server_config = manager.config.get_section_config("Server")
@ -80,6 +80,7 @@ class QemuVM(BaseNode):
self._qemu_img_stdout_file = "" self._qemu_img_stdout_file = ""
self._execute_lock = asyncio.Lock() self._execute_lock = asyncio.Lock()
self._local_udp_tunnels = {} self._local_udp_tunnels = {}
self._guest_cid = guest_cid
# QEMU VM settings # QEMU VM settings
if qemu_path: if qemu_path:
@ -124,6 +125,16 @@ class QemuVM(BaseNode):
self.adapters = 1 # creates 1 adapter by default self.adapters = 1 # creates 1 adapter by default
log.info('QEMU VM "{name}" [{id}] has been created'.format(name=self._name, id=self._id)) log.info('QEMU VM "{name}" [{id}] has been created'.format(name=self._name, id=self._id))
@property
def guest_cid(self):
"""
Returns guest_cid (console ID) which unique identifier between 3 and 65535
:returns: integer between 3 and 65535
"""
return self._guest_cid
@property @property
def monitor(self): def monitor(self):
""" """
@ -1917,7 +1928,8 @@ class QemuVM(BaseNode):
additional_options = additional_options.replace("%vm-id%", self._id) additional_options = additional_options.replace("%vm-id%", self._id)
additional_options = additional_options.replace("%project-id%", self.project.id) additional_options = additional_options.replace("%project-id%", self.project.id)
additional_options = additional_options.replace("%project-path%", '"' + self.project.path.replace('"', '\\"') + '"') additional_options = additional_options.replace("%project-path%", '"' + self.project.path.replace('"', '\\"') + '"')
if self._console: additional_options = additional_options.replace("%guest-cid%", str(self._guest_cid))
if self._console_type != "none" and self._console:
additional_options = additional_options.replace("%console-port%", str(self._console)) additional_options = additional_options.replace("%console-port%", str(self._console))
command = [self.qemu_path] command = [self.qemu_path]
command.extend(["-name", self._name]) command.extend(["-name", self._name])

View File

@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from ..qemu_error import QemuError
import logging
log = logging.getLogger(__name__)
def get_next_guest_cid(nodes):
"""
Calculates free guest_id from given nodes
:param nodes:
:raises QemuError when exceeds number
:return: integer first free cid
"""
used = set([n.guest_cid for n in nodes])
pool = set(range(3, 65535))
try:
return (pool - used).pop()
except KeyError:
raise QemuError("Cannot create a new Qemu VM (limit of 65535 guest ID on one host reached)")

View File

@ -20,7 +20,7 @@ import pytest
import shutil import shutil
import asyncio import asyncio
from gns3server.compute.qemu.qcow2 import Qcow2, Qcow2Error from gns3server.compute.qemu.utils.qcow2 import Qcow2, Qcow2Error
def qemu_img(): def qemu_img():