1
0
mirror of https://github.com/GNS3/gns3-server synced 2024-10-11 18:38:55 +00:00
gns3-server/gns3server/modules/vpcs/vpcs_device.py

461 lines
16 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
import subprocess
import sys
import socket
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
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
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 host: host/address to bind for console and UDP connections
2014-05-13 22:09:47 +00:00
:param name: name of this VPCS device
2014-05-06 16:06:10 +00:00
"""
_instances = []
2014-05-15 15:27:46 +00:00
def __init__(self, path, base_script_file, working_dir, host="127.0.0.1", name=None):
2014-05-06 16:06:10 +00:00
# find an instance identifier (1 <= id <= 512)
# This 512 limit is due to a restriction on the number of possible
2014-05-13 22:09:47 +00:00
# mac addresses given in VPCS using the -m option
2014-05-06 16:06:10 +00:00
self._id = 0
for identifier in range(1, 513):
2014-05-06 16:06:10 +00:00
if identifier not in self._instances:
self._id = identifier
self._instances.append(self._id)
break
if self._id == 0:
2014-05-13 22:09:47 +00:00
raise VPCSError("Maximum number of VPCS instances reached")
2014-05-06 16:06:10 +00:00
if name:
self._name = name
else:
2014-05-13 22:09:47 +00:00
self._name = "VPCS{}".format(self._id)
2014-05-06 16:06:10 +00:00
self._path = path
self._console = None
self._working_dir = None
self._command = []
self._process = None
self._vpcs_stdout_file = ""
self._host = "127.0.0.1"
2014-05-06 16:06:10 +00:00
self._started = False
2014-05-13 22:09:47 +00:00
# VPCS settings
2014-05-15 15:27:46 +00:00
self._base_script_file = base_script_file
2014-05-06 16:25:05 +00:00
self._ethernet_adapters = [EthernetAdapter()] # one adapter = 1 interfaces
self._slots = self._ethernet_adapters
2014-05-13 22:09:47 +00:00
2014-05-06 16:06:10 +00:00
# update the working directory
self.working_dir = working_dir
2014-05-13 22:09:47 +00:00
log.info("VPCS device {name} [id={id}] has been created".format(name=self._name,
2014-05-06 16:06:10 +00:00
id=self._id))
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-13 22:09:47 +00:00
"path": self._path,
2014-05-15 15:27:46 +00:00
"base_script_file": self._base_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)
"""
return(self._id)
@classmethod
def reset(cls):
"""
Resets allocated instance list.
"""
cls._instances.clear()
@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
"""
self._name = new_name
2014-05-13 22:09:47 +00:00
log.info("VPCS {name} [id={id}]: renamed to {new_name}".format(name=self._name,
2014-05-06 16:06:10 +00:00
id=self._id,
new_name=new_name))
@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
"""
return(self._path)
@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-06 16:06:10 +00:00
id=self._id,
path=path))
@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
"""
# create our own working directory
working_dir = os.path.join(working_dir, "vpcs", "device-{}".format(self._id))
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-06 16:06:10 +00:00
id=self._id,
wd=self._working_dir))
@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)
"""
self._console = 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-06 16:06:10 +00:00
id=self._id,
port=console))
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()
self._instances.remove(self._id)
2014-05-13 22:09:47 +00:00
log.info("VPCS device {name} [id={id}] has been deleted".format(name=self._name,
2014-05-06 16:06:10 +00:00
id=self._id))
@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
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 os.path.isfile(self._path):
2014-05-13 22:09:47 +00:00
raise VPCSError("VPCS image '{}' 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-13 22:09:47 +00:00
raise VPCSError("VPCS image '{}' is not executable".format(self._path))
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))
with open(self._vpcs_stdout_file, "w") as fd:
self._process = subprocess.Popen(self._command,
stdout=fd,
stderr=subprocess.STDOUT,
cwd=self._working_dir)
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 as e:
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-06 16:06:10 +00:00
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self._host, self._console))
sock.send(bytes("quit\n", 'UTF-8'))
sock.close()
except TypeError as e:
2014-05-13 22:09:47 +00:00
log.warn("VPCS instance {} PID={} is still running. Error: {}".format(self._id,
self._process.pid, e))
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) as file:
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
"""
if self._process:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self._host, self._console))
sock.close()
return True
except:
e = sys.exc_info()[0]
log.warn("Could not connect to {}:{}. Error: {}".format(self._host, self._console, e))
return False
2014-05-06 16:06:10 +00:00
return False
def slot_add_nio_binding(self, slot_id, port_id, nio):
"""
Adds a slot NIO binding.
:param slot_id: slot ID
:param port_id: port ID
:param nio: NIO instance to add to the slot/port
"""
try:
adapter = self._slots[slot_id]
except IndexError:
2014-05-13 22:09:47 +00:00
raise VPCSError("Slot {slot_id} doesn't exist on VPCS {name}".format(name=self._name,
2014-05-06 16:06:10 +00:00
slot_id=slot_id))
if not adapter.port_exists(port_id):
raise VPCSError("Port {port_id} doesn't exist in adapter {adapter}".format(adapter=adapter,
2014-05-06 16:06:10 +00:00
port_id=port_id))
adapter.add_nio(port_id, nio)
2014-05-13 22:09:47 +00:00
log.info("VPCS {name} [id={id}]: {nio} added to {slot_id}/{port_id}".format(name=self._name,
2014-05-06 16:06:10 +00:00
id=self._id,
nio=nio,
slot_id=slot_id,
port_id=port_id))
def slot_remove_nio_binding(self, slot_id, port_id):
"""
Removes a slot NIO binding.
:param slot_id: slot ID
:param port_id: port ID
"""
try:
adapter = self._slots[slot_id]
except IndexError:
2014-05-13 22:09:47 +00:00
raise VPCSError("Slot {slot_id} doesn't exist on VPCS {name}".format(name=self._name,
2014-05-06 16:06:10 +00:00
slot_id=slot_id))
if not adapter.port_exists(port_id):
raise VPCSError("Port {port_id} doesn't exist in adapter {adapter}".format(adapter=adapter,
2014-05-06 16:06:10 +00:00
port_id=port_id))
nio = adapter.get_nio(port_id)
adapter.remove_nio(port_id)
2014-05-13 22:09:47 +00:00
log.info("VPCS {name} [id={id}]: {nio} removed from {slot_id}/{port_id}".format(name=self._name,
2014-05-06 16:06:10 +00:00
id=self._id,
nio=nio,
slot_id=slot_id,
port_id=port_id))
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
-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.
-e tap mode, using /dev/tapx (linux only)
-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
hypervisor mode option:
-H port run as the hypervisor listening on the tcp 'port'
2014-05-13 22:09:47 +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]
command.extend(["-p", str(self._console)])
2014-05-06 16:25:05 +00:00
for adapter in self._slots:
for unit in adapter.ports.keys():
nio = adapter.get_nio(unit)
if nio:
if isinstance(nio, NIO_UDP):
# UDP tunnel
command.extend(["-s", str(nio.lport)])
command.extend(["-c", str(nio.rport)])
command.extend(["-t", str(nio.rhost)])
2014-05-06 16:42:38 +00:00
elif isinstance(nio, NIO_TAP):
# TAP interface
command.extend(["-e"]) #, str(nio.tap_device)]) #TODO: Fix, currently vpcs doesn't allow specific tap_device
command.extend(["-m", str(self._id)]) # The unique ID is used to set the mac address offset
command.extend(["-i", str(1)]) # Option to start only one pc instance
2014-05-15 15:27:46 +00:00
if self._base_script_file:
command.extend([self._base_script_file])
2014-05-06 16:06:10 +00:00
return command
@property
2014-05-15 15:27:46 +00:00
def base_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-06 16:52:34 +00:00
:returns: path to script-file file
2014-05-06 16:06:10 +00:00
"""
2014-05-15 15:27:46 +00:00
return self._base_script_file
2014-05-06 16:06:10 +00:00
2014-05-15 15:27:46 +00:00
@base_script_file.setter
def base_script_file(self, base_script_file):
2014-05-06 16:06:10 +00:00
"""
2014-05-15 15:27:46 +00:00
Sets the base-script-file for this VPCS instance.
2014-05-06 16:06:10 +00:00
2014-05-15 15:27:46 +00:00
:param base_script_file: path to base-script-file file
2014-05-06 16:06:10 +00:00
"""
2014-05-15 15:27:46 +00:00
self._base_script_file = base_script_file
log.info("VPCS {name} [id={id}]: base_script_file set to {config}".format(name=self._name,
2014-05-06 16:06:10 +00:00
id=self._id,
2014-05-15 15:27:46 +00:00
config=self._base_script_file))