1
0
mirror of https://github.com/GNS3/gns3-server synced 2024-12-11 01:28:09 +00:00
gns3-server/gns3server/modules/old_vpcs/vpcs_device.py

558 lines
19 KiB
Python
Raw Normal View History

2014-05-06 16:06:10 +00:00
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 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/>.
"""
2014-05-13 22:09:47 +00:00
VPCS device management (creates command line, processes, files etc.) in
order to run an VPCS instance.
2014-05-06 16:06:10 +00:00
"""
import os
2014-05-22 01:11:28 +00:00
import sys
2014-05-06 16:06:10 +00:00
import subprocess
2014-05-19 01:12:46 +00:00
import signal
2014-05-19 18:05:30 +00:00
import shutil
2014-07-02 21:04:39 +00:00
import re
2014-05-19 18:05:30 +00:00
2014-07-02 21:04:39 +00:00
from pkg_resources import parse_version
2014-05-13 21:00:35 +00:00
from .vpcs_error import VPCSError
2014-05-06 16:25:05 +00:00
from .adapters.ethernet_adapter import EthernetAdapter
2014-05-06 16:06:10 +00:00
from .nios.nio_udp import NIO_UDP
from .nios.nio_tap import NIO_TAP
2014-05-19 01:12:46 +00:00
from ..attic import find_unused_port
2014-05-06 16:06:10 +00:00
import logging
log = logging.getLogger(__name__)
2014-05-13 21:00:35 +00:00
class VPCSDevice(object):
2014-05-06 16:06:10 +00:00
"""
2014-05-13 22:09:47 +00:00
VPCS device implementation.
2014-05-06 16:06:10 +00:00
:param name: name of this VPCS device
2014-05-13 22:09:47 +00:00
:param path: path to VPCS executable
2014-05-06 16:06:10 +00:00
:param working_dir: path to a working directory
:param vpcs_id: VPCS instance ID
:param console: TCP console port
:param console_host: IP address to bind for console connections
2014-05-19 01:12:46 +00:00
:param console_start_port_range: TCP console port range start
:param console_end_port_range: TCP console port range end
2014-05-06 16:06:10 +00:00
"""
_instances = []
2014-05-19 01:12:46 +00:00
_allocated_console_ports = []
def __init__(self,
2014-05-27 17:23:06 +00:00
name,
2014-05-19 01:12:46 +00:00
path,
working_dir,
vpcs_id=None,
console=None,
console_host="0.0.0.0",
2014-05-19 01:12:46 +00:00
console_start_port_range=4512,
console_end_port_range=5000):
2014-05-06 16:06:10 +00:00
if not vpcs_id:
# find an instance identifier is none is provided (1 <= id <= 255)
# This 255 limit is due to a restriction on the number of possible
# MAC addresses given in VPCS using the -m option
self._id = 0
for identifier in range(1, 256):
if identifier not in self._instances:
self._id = identifier
self._instances.append(self._id)
break
if self._id == 0:
raise VPCSError("Maximum number of VPCS instances reached")
else:
if vpcs_id in self._instances:
raise VPCSError("VPCS identifier {} is already used by another VPCS device".format(vpcs_id))
self._id = vpcs_id
self._instances.append(self._id)
2014-05-06 16:06:10 +00:00
self._name = name
2014-05-06 16:06:10 +00:00
self._path = path
self._console = console
self._working_dir = None
self._console_host = console_host
2014-05-06 16:06:10 +00:00
self._command = []
self._process = None
self._vpcs_stdout_file = ""
self._started = False
2014-05-19 01:12:46 +00:00
self._console_start_port_range = console_start_port_range
self._console_end_port_range = console_end_port_range
2014-05-06 16:06:10 +00:00
2014-05-13 22:09:47 +00:00
# VPCS settings
2014-05-19 01:12:46 +00:00
self._script_file = ""
self._ethernet_adapter = EthernetAdapter() # one adapter with 1 Ethernet interface
2014-05-13 22:09:47 +00:00
working_dir_path = os.path.join(working_dir, "vpcs", "pc-{}".format(self._id))
if vpcs_id and not os.path.isdir(working_dir_path):
raise VPCSError("Working directory {} doesn't exist".format(working_dir_path))
# create the device own working directory
self.working_dir = working_dir_path
2014-05-06 16:06:10 +00:00
if not self._console:
# allocate a console port
try:
self._console = find_unused_port(self._console_start_port_range,
self._console_end_port_range,
self._console_host,
ignore_ports=self._allocated_console_ports)
except Exception as e:
raise VPCSError(e)
if self._console in self._allocated_console_ports:
raise VPCSError("Console port {} is already used by another VPCS device".format(console))
2014-05-19 01:12:46 +00:00
self._allocated_console_ports.append(self._console)
2014-05-13 22:09:47 +00:00
log.info("VPCS device {name} [id={id}] has been created".format(name=self._name,
2014-05-19 01:12:46 +00:00
id=self._id))
2014-05-06 16:06:10 +00:00
def defaults(self):
"""
2014-05-13 22:09:47 +00:00
Returns all the default attribute values for VPCS.
2014-05-06 16:06:10 +00:00
:returns: default values (dictionary)
"""
vpcs_defaults = {"name": self._name,
2014-05-19 01:12:46 +00:00
"script_file": self._script_file,
2014-05-13 22:09:47 +00:00
"console": self._console}
2014-05-06 16:06:10 +00:00
return vpcs_defaults
@property
def id(self):
"""
2014-05-13 22:09:47 +00:00
Returns the unique ID for this VPCS device.
2014-05-06 16:06:10 +00:00
:returns: id (integer)
"""
2014-05-28 12:26:20 +00:00
return self._id
2014-05-06 16:06:10 +00:00
@classmethod
def reset(cls):
"""
Resets allocated instance list.
"""
cls._instances.clear()
2014-05-19 01:12:46 +00:00
cls._allocated_console_ports.clear()
2014-05-06 16:06:10 +00:00
@property
def name(self):
"""
2014-05-13 22:09:47 +00:00
Returns the name of this VPCS device.
2014-05-06 16:06:10 +00:00
:returns: name
"""
return self._name
@name.setter
def name(self, new_name):
"""
2014-05-13 22:09:47 +00:00
Sets the name of this VPCS device.
2014-05-06 16:06:10 +00:00
:param new_name: name
"""
2014-05-19 19:14:57 +00:00
if self._script_file:
# update the startup.vpc
2014-05-28 12:26:20 +00:00
config_path = os.path.join(self._working_dir, "startup.vpc")
2014-05-19 19:14:57 +00:00
if os.path.isfile(config_path):
try:
with open(config_path, "r+", errors="replace") as f:
2014-05-19 19:14:57 +00:00
old_config = f.read()
new_config = old_config.replace(self._name, new_name)
f.seek(0)
f.write(new_config)
except OSError as e:
raise VPCSError("Could not amend the configuration {}: {}".format(config_path, e))
2014-05-13 22:09:47 +00:00
log.info("VPCS {name} [id={id}]: renamed to {new_name}".format(name=self._name,
2014-05-28 12:26:20 +00:00
id=self._id,
new_name=new_name))
2014-05-19 19:14:57 +00:00
self._name = new_name
2014-05-06 16:06:10 +00:00
@property
def path(self):
"""
2014-05-13 22:09:47 +00:00
Returns the path to the VPCS executable.
2014-05-06 16:06:10 +00:00
2014-05-13 22:09:47 +00:00
:returns: path to VPCS
2014-05-06 16:06:10 +00:00
"""
2014-05-28 12:26:20 +00:00
return self._path
2014-05-06 16:06:10 +00:00
@path.setter
def path(self, path):
"""
2014-05-13 22:09:47 +00:00
Sets the path to the VPCS executable.
2014-05-06 16:06:10 +00:00
2014-05-13 22:09:47 +00:00
:param path: path to VPCS
2014-05-06 16:06:10 +00:00
"""
self._path = path
2014-05-13 22:09:47 +00:00
log.info("VPCS {name} [id={id}]: path changed to {path}".format(name=self._name,
2014-05-28 12:26:20 +00:00
id=self._id,
path=path))
2014-05-06 16:06:10 +00:00
@property
def working_dir(self):
"""
Returns current working directory
:returns: path to the working directory
"""
return self._working_dir
@working_dir.setter
def working_dir(self, working_dir):
"""
2014-05-13 22:09:47 +00:00
Sets the working directory for VPCS.
2014-05-06 16:06:10 +00:00
:param working_dir: path to the working directory
"""
try:
os.makedirs(working_dir)
except FileExistsError:
pass
except OSError as e:
raise VPCSError("Could not create working directory {}: {}".format(working_dir, e))
2014-05-06 16:06:10 +00:00
self._working_dir = working_dir
2014-05-13 22:09:47 +00:00
log.info("VPCS {name} [id={id}]: working directory changed to {wd}".format(name=self._name,
2014-05-28 12:26:20 +00:00
id=self._id,
wd=self._working_dir))
2014-05-06 16:06:10 +00:00
@property
def console(self):
"""
Returns the TCP console port.
:returns: console port (integer)
"""
return self._console
@console.setter
def console(self, console):
"""
Sets the TCP console port.
:param console: console port (integer)
"""
2014-05-19 01:12:46 +00:00
if console in self._allocated_console_ports:
raise VPCSError("Console port {} is already used by another VPCS device".format(console))
2014-05-19 01:12:46 +00:00
self._allocated_console_ports.remove(self._console)
2014-05-06 16:06:10 +00:00
self._console = console
2014-05-19 01:12:46 +00:00
self._allocated_console_ports.append(self._console)
2014-05-13 22:09:47 +00:00
log.info("VPCS {name} [id={id}]: console port set to {port}".format(name=self._name,
2014-05-28 12:26:20 +00:00
id=self._id,
port=console))
2014-05-06 16:06:10 +00:00
def command(self):
"""
2014-05-13 22:09:47 +00:00
Returns the VPCS command line.
2014-05-06 16:06:10 +00:00
2014-05-13 22:09:47 +00:00
:returns: VPCS command line (string)
2014-05-06 16:06:10 +00:00
"""
return " ".join(self._build_command())
def delete(self):
"""
2014-05-13 22:09:47 +00:00
Deletes this VPCS device.
2014-05-06 16:06:10 +00:00
"""
self.stop()
if self._id in self._instances:
self._instances.remove(self._id)
2014-05-19 01:12:46 +00:00
if self.console and self.console in self._allocated_console_ports:
2014-05-19 01:12:46 +00:00
self._allocated_console_ports.remove(self.console)
2014-05-13 22:09:47 +00:00
log.info("VPCS device {name} [id={id}] has been deleted".format(name=self._name,
2014-05-28 12:26:20 +00:00
id=self._id))
2014-05-06 16:06:10 +00:00
2014-05-19 18:05:30 +00:00
def clean_delete(self):
"""
Deletes this VPCS device & all files (configs, logs etc.)
"""
self.stop()
if self._id in self._instances:
self._instances.remove(self._id)
2014-05-19 18:05:30 +00:00
if self.console:
self._allocated_console_ports.remove(self.console)
try:
shutil.rmtree(self._working_dir)
except OSError as e:
log.error("could not delete VPCS device {name} [id={id}]: {error}".format(name=self._name,
id=self._id,
error=e))
return
2014-05-19 19:14:57 +00:00
log.info("VPCS device {name} [id={id}] has been deleted (including associated files)".format(name=self._name,
id=self._id))
2014-05-19 18:05:30 +00:00
2014-05-06 16:06:10 +00:00
@property
def started(self):
"""
2014-05-13 22:09:47 +00:00
Returns either this VPCS device has been started or not.
2014-05-06 16:06:10 +00:00
:returns: boolean
"""
return self._started
2014-07-02 21:04:39 +00:00
def _check_vpcs_version(self):
"""
Checks if the VPCS executable version is >= 0.5b1.
"""
try:
2014-09-18 21:47:43 +00:00
output = subprocess.check_output([self._path, "-v"], cwd=self._working_dir)
2014-07-02 21:04:39 +00:00
match = re.search("Welcome to Virtual PC Simulator, version ([0-9a-z\.]+)", output.decode("utf-8"))
if match:
version = match.group(1)
if parse_version(version) < parse_version("0.5b1"):
raise VPCSError("VPCS executable version must be >= 0.5b1")
else:
raise VPCSError("Could not determine the VPCS version for {}".format(self._path))
except (OSError, subprocess.SubprocessError) as e:
2014-07-02 21:04:39 +00:00
raise VPCSError("Error while looking for the VPCS version: {}".format(e))
2014-05-06 16:06:10 +00:00
def start(self):
"""
2014-05-13 22:09:47 +00:00
Starts the VPCS process.
2014-05-06 16:06:10 +00:00
"""
if not self.is_running():
if not self._path:
raise VPCSError("No path to a VPCS executable has been set")
2014-05-06 16:06:10 +00:00
if not os.path.isfile(self._path):
2014-05-28 12:26:20 +00:00
raise VPCSError("VPCS program '{}' is not accessible".format(self._path))
2014-05-06 16:06:10 +00:00
if not os.access(self._path, os.X_OK):
2014-05-28 12:26:20 +00:00
raise VPCSError("VPCS program '{}' is not executable".format(self._path))
2014-05-19 01:12:46 +00:00
2014-07-02 21:04:39 +00:00
self._check_vpcs_version()
2014-05-19 01:12:46 +00:00
if not self._ethernet_adapter.get_nio(0):
raise VPCSError("This VPCS instance must be connected in order to start")
2014-05-06 16:06:10 +00:00
self._command = self._build_command()
try:
2014-05-13 22:09:47 +00:00
log.info("starting VPCS: {}".format(self._command))
2014-05-06 16:06:10 +00:00
self._vpcs_stdout_file = os.path.join(self._working_dir, "vpcs.log")
log.info("logging to {}".format(self._vpcs_stdout_file))
flags = 0
2014-05-22 01:11:28 +00:00
if sys.platform.startswith("win32"):
flags = subprocess.CREATE_NEW_PROCESS_GROUP
2014-05-06 16:06:10 +00:00
with open(self._vpcs_stdout_file, "w") as fd:
self._process = subprocess.Popen(self._command,
stdout=fd,
stderr=subprocess.STDOUT,
2014-05-22 01:11:28 +00:00
cwd=self._working_dir,
creationflags=flags)
2014-05-13 22:09:47 +00:00
log.info("VPCS instance {} started PID={}".format(self._id, self._process.pid))
2014-05-06 16:06:10 +00:00
self._started = True
except (OSError, subprocess.SubprocessError) as e:
2014-05-06 16:06:10 +00:00
vpcs_stdout = self.read_vpcs_stdout()
2014-05-13 22:09:47 +00:00
log.error("could not start VPCS {}: {}\n{}".format(self._path, e, vpcs_stdout))
raise VPCSError("could not start VPCS {}: {}\n{}".format(self._path, e, vpcs_stdout))
2014-05-06 16:06:10 +00:00
def stop(self):
"""
2014-05-13 22:09:47 +00:00
Stops the VPCS process.
2014-05-06 16:06:10 +00:00
"""
2014-05-13 22:09:47 +00:00
# stop the VPCS process
2014-05-06 16:06:10 +00:00
if self.is_running():
2014-05-13 22:09:47 +00:00
log.info("stopping VPCS instance {} PID={}".format(self._id, self._process.pid))
2014-05-22 01:11:28 +00:00
if sys.platform.startswith("win32"):
self._process.send_signal(signal.CTRL_BREAK_EVENT)
else:
self._process.terminate()
2014-05-19 01:12:46 +00:00
self._process.wait()
2014-05-06 16:06:10 +00:00
self._process = None
self._started = False
def read_vpcs_stdout(self):
"""
2014-05-13 22:09:47 +00:00
Reads the standard output of the VPCS process.
2014-05-06 16:06:10 +00:00
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._vpcs_stdout_file:
try:
with open(self._vpcs_stdout_file, errors="replace") as file:
2014-05-06 16:06:10 +00:00
output = file.read()
except OSError as e:
log.warn("could not read {}: {}".format(self._vpcs_stdout_file, e))
return output
def is_running(self):
"""
2014-05-13 22:09:47 +00:00
Checks if the VPCS process is running
2014-05-06 16:06:10 +00:00
:returns: True or False
"""
2014-05-28 12:26:20 +00:00
if self._process and self._process.poll() is None:
2014-05-19 01:12:46 +00:00
return True
2014-05-06 16:06:10 +00:00
return False
2014-05-19 01:12:46 +00:00
def port_add_nio_binding(self, port_id, nio):
2014-05-06 16:06:10 +00:00
"""
2014-05-19 01:12:46 +00:00
Adds a port NIO binding.
2014-05-06 16:06:10 +00:00
:param port_id: port ID
:param nio: NIO instance to add to the slot/port
"""
2014-05-19 01:12:46 +00:00
if not self._ethernet_adapter.port_exists(port_id):
raise VPCSError("Port {port_id} doesn't exist in adapter {adapter}".format(adapter=self._ethernet_adapter,
2014-05-28 12:26:20 +00:00
port_id=port_id))
2014-05-06 16:06:10 +00:00
2014-05-19 01:12:46 +00:00
self._ethernet_adapter.add_nio(port_id, nio)
log.info("VPCS {name} [id={id}]: {nio} added to port {port_id}".format(name=self._name,
id=self._id,
nio=nio,
port_id=port_id))
2014-05-06 16:06:10 +00:00
2014-05-19 01:12:46 +00:00
def port_remove_nio_binding(self, port_id):
2014-05-06 16:06:10 +00:00
"""
2014-05-19 01:12:46 +00:00
Removes a port NIO binding.
2014-05-06 16:06:10 +00:00
:param port_id: port ID
2014-05-19 01:12:46 +00:00
:returns: NIO instance
"""
2014-05-06 16:06:10 +00:00
2014-05-19 01:12:46 +00:00
if not self._ethernet_adapter.port_exists(port_id):
raise VPCSError("Port {port_id} doesn't exist in adapter {adapter}".format(adapter=self._ethernet_adapter,
2014-05-06 16:06:10 +00:00
port_id=port_id))
2014-05-19 01:12:46 +00:00
nio = self._ethernet_adapter.get_nio(port_id)
self._ethernet_adapter.remove_nio(port_id)
log.info("VPCS {name} [id={id}]: {nio} removed from port {port_id}".format(name=self._name,
id=self._id,
nio=nio,
port_id=port_id))
return nio
2014-05-06 16:06:10 +00:00
def _build_command(self):
"""
2014-05-13 22:09:47 +00:00
Command to start the VPCS process.
2014-05-06 16:06:10 +00:00
(to be passed to subprocess.Popen())
2014-05-13 22:09:47 +00:00
VPCS command line:
2014-05-06 16:06:10 +00:00
usage: vpcs [options] [scriptfile]
Option:
-h print this help then exit
-v print version information then exit
2014-05-19 01:12:46 +00:00
-i num number of vpc instances to start (default is 9)
2014-05-06 16:06:10 +00:00
-p port run as a daemon listening on the tcp 'port'
-m num start byte of ether address, default from 0
-r file load and execute script file
compatible with older versions, DEPRECATED.
2014-05-19 01:12:46 +00:00
-e tap mode, using /dev/tapx by default (linux only)
2014-05-06 16:06:10 +00:00
-u udp mode, default
udp mode options:
-s port local udp base port, default from 20000
-c port remote udp base port (dynamips udp port), default from 30000
-t ip remote host IP, default 127.0.0.1
2014-05-19 01:12:46 +00:00
tap mode options:
-d device device name, works only when -i is set to 1
2014-05-06 16:06:10 +00:00
hypervisor mode option:
-H port run as the hypervisor listening on the tcp 'port'
2014-05-19 01:12:46 +00:00
If no 'scriptfile' specified, vpcs will read and execute the file named
2014-05-06 16:06:10 +00:00
'startup.vpc' if it exsits in the current directory.
"""
command = [self._path]
2014-05-19 01:12:46 +00:00
command.extend(["-p", str(self._console)]) # listen to console port
nio = self._ethernet_adapter.get_nio(0)
if nio:
if isinstance(nio, NIO_UDP):
# UDP tunnel
command.extend(["-s", str(nio.lport)]) # source UDP port
command.extend(["-c", str(nio.rport)]) # destination UDP port
command.extend(["-t", nio.rhost]) # destination host
elif isinstance(nio, NIO_TAP):
# TAP interface
command.extend(["-e"])
command.extend(["-d", nio.tap_device])
command.extend(["-m", str(self._id)]) # the unique ID is used to set the MAC address offset
command.extend(["-i", "1"]) # option to start only one VPC instance
command.extend(["-F"]) # option to avoid the daemonization of VPCS
if self._script_file:
command.extend([self._script_file])
2014-05-06 16:06:10 +00:00
return command
@property
2014-05-19 01:12:46 +00:00
def script_file(self):
2014-05-06 16:06:10 +00:00
"""
2014-05-13 22:09:47 +00:00
Returns the script-file for this VPCS instance.
2014-05-06 16:06:10 +00:00
2014-05-19 01:12:46 +00:00
:returns: path to script-file
2014-05-06 16:06:10 +00:00
"""
2014-05-19 01:12:46 +00:00
return self._script_file
2014-05-06 16:06:10 +00:00
2014-05-19 01:12:46 +00:00
@script_file.setter
def script_file(self, script_file):
2014-05-06 16:06:10 +00:00
"""
2014-05-19 01:12:46 +00:00
Sets the script-file for this VPCS instance.
2014-05-06 16:06:10 +00:00
2014-05-28 12:26:20 +00:00
:param script_file: path to base-script-file
2014-05-06 16:06:10 +00:00
"""
2014-05-19 01:12:46 +00:00
self._script_file = script_file
log.info("VPCS {name} [id={id}]: script_file set to {config}".format(name=self._name,
id=self._id,
config=self._script_file))