Working VPCS implementation.

This commit is contained in:
grossmj committed 2014-05-18 19:12:46 -06:00
1 parent 85ef421d72
commit 0af4ea81ff
6 files changed
+260 -315

No files matched your search

+67 -149
View File
@@ -87,22 +87,16 @@ class VPCS(IModule):
# a new process start when calling IModule
IModule.__init__(self, name, *args, **kwargs)
self._vpcs_instances = {}
self._console_start_port_range = 4001
self._console_end_port_range = 4512
self._allocated_console_ports = []
self._current_console_port = self._console_start_port_range
self._udp_start_port_range = 30001
self._udp_end_port_range = 40001
self._current_udp_port = self._udp_start_port_range
self._console_start_port_range = 4512
self._console_end_port_range = 5000
self._allocated_udp_ports = []
self._udp_start_port_range = 40001
self._udp_end_port_range = 40512
self._host = kwargs["host"]
self._projects_dir = kwargs["projects_dir"]
self._tempdir = kwargs["temp_dir"]
self._working_dir = self._projects_dir
# check every 5 seconds
#self._vpcs_callback = self.add_periodic_callback(self._check_vpcs_is_alive, 5000)
#self._vpcs_callback.start()
def stop(self, signum=None):
"""
Properly stops the module.
@@ -118,27 +112,6 @@ class VPCS(IModule):
IModule.stop(self, signum) # this will stop the I/O loop
def _check_vpcs_is_alive(self):
"""
Periodic callback to check if VPCS is alive
for each VPCS instance.
Sends a notification to the client if not.
"""
for vpcs_id in self._vpcs_instances:
vpcs_instance = self._vpcs_instances[vpcs_id]
if vpcs_instance.started and (not vpcs_instance.is_running() or not vpcs_instance.is_vpcs_running()):
notification = {"module": self.name,
"id": vpcs_id,
"name": vpcs_instance.name}
if not vpcs_instance.is_running():
stdout = vpcs_instance.read_vpcs_stdout()
notification["message"] = "VPCS has stopped running"
notification["details"] = stdout
self.send_notification("{}.vpcs_stopped".format(self.name), notification)
vpcs_instance.stop()
def get_vpcs_instance(self, vpcs_id):
"""
Returns a VPCS device instance.
@@ -171,9 +144,7 @@ class VPCS(IModule):
VPCSDevice.reset()
self._vpcs_instances.clear()
self._remote_server = False
self._current_console_port = self._console_start_port_range
self._current_udp_port = self._udp_start_port_range
self._allocated_udp_ports.clear()
log.info("VPCS module has been reset")
@@ -183,6 +154,7 @@ class VPCS(IModule):
Set or update settings.
Optional request parameters:
- path (path to vpcs)
- working_dir (path to a working directory)
- project_name
- console_start_port_range
@@ -197,15 +169,18 @@ class VPCS(IModule):
self.send_param_error()
return
if "vpcs" in request and request["vpcs"]:
self._vpcs = request["vpcs"]
if "path" in request and request["path"]:
self._vpcs = request["path"]
log.info("VPCS path set to {}".format(self._vpcs))
for vpcs_id in self._vpcs_instances:
vpcs_instance = self._vpcs_instances[vpcs_id]
vpcs_instance.path = self._vpcs
if "working_dir" in request:
new_working_dir = request["working_dir"]
log.info("this server is local with working directory path to {}".format(new_working_dir))
else:
new_working_dir = os.path.join(self._projects_dir, request["project_name"] + ".gns3")
new_working_dir = os.path.join(self._projects_dir, request["project_name"])
log.info("this server is remote with working directory path to {}".format(new_working_dir))
if self._projects_dir != self._working_dir != new_working_dir:
if not os.path.isdir(new_working_dir):
@@ -234,29 +209,11 @@ class VPCS(IModule):
log.debug("received request {}".format(request))
def test_result(self, message, result="error"):
"""
"""
return {"result": result, "message": message}
@IModule.route("vpcs.test_settings")
def test_settings(self, request):
"""
"""
response = []
self.send_response(response)
@IModule.route("vpcs.create")
def vpcs_create(self, request):
"""
Creates a new VPCS instance.
Mandatory request parameters:
- path (path to the VPCS executable)
Optional request parameters:
- name (VPCS name)
@@ -269,16 +226,12 @@ class VPCS(IModule):
"""
# validate the request
if not self.validate_request(request, VPCS_CREATE_SCHEMA):
if request and not self.validate_request(request, VPCS_CREATE_SCHEMA):
return
name = None
if "name" in request:
if request and "name" in request:
name = request["name"]
base_script_file = None
if "base_script_file" in request:
base_script_file = request["base_script_file"]
vpcs_path = request["path"]
try:
try:
@@ -288,31 +241,13 @@ class VPCS(IModule):
except OSError as e:
raise VPCSError("Could not create working directory {}".format(e))
# a new base-script-file has been pushed
if "base_script_file_base64" in request:
config = base64.decodestring(request["base_script_file_base64"].encode("utf-8")).decode("utf-8")
config = "!\n" + config.replace("\r", "")
#config = config.replace('%h', vpcs_instance.name)
config_path = os.path.join(self._working_dir, "base-script-file")
try:
with open(config_path, "w") as f:
log.info("saving base-script-file to {}".format(config_path))
f.write(config)
except OSError as e:
raise VPCSError("Could not save the configuration {}: {}".format(config_path, e))
# update the request with the new local base-script-file path
request["base_script_file"] = os.path.basename(config_path)
vpcs_instance = VPCSDevice(vpcs_path, config_path, self._working_dir, host=self._host, name=name)
# find a console port
if self._current_console_port > self._console_end_port_range:
self._current_console_port = self._console_start_port_range
try:
vpcs_instance.console = find_unused_port(self._current_console_port, self._console_end_port_range, self._host)
except Exception as e:
raise VPCSError(e)
self._current_console_port += 1
vpcs_instance = VPCSDevice(self._vpcs,
self._working_dir,
self._host,
name,
self._console_start_port_range,
self._console_end_port_range)
except VPCSError as e:
self.send_custom_error(str(e))
return
@@ -367,7 +302,7 @@ class VPCS(IModule):
Optional request parameters:
- any setting to update
- base_script_file_base64 (script-file base64 encoded)
- script_file_base64 (base64 encoded)
Response parameters:
- updated settings
@@ -384,28 +319,42 @@ class VPCS(IModule):
if not vpcs_instance:
return
response = {}
config_path = os.path.join(vpcs_instance.working_dir, "startup.vpc")
try:
# a new base-script-file has been pushed
if "base_script_file_base64" in request:
config = base64.decodestring(request["base_script_file_base64"].encode("utf-8")).decode("utf-8")
config = "!\n" + config.replace("\r", "")
if "script_file_base64" in request:
# a new startup-config has been pushed
config = base64.decodestring(request["script_file_base64"].encode("utf-8")).decode("utf-8")
config = config.replace("\r", "")
config = config.replace('%h', vpcs_instance.name)
config_path = os.path.join(vpcs_instance.working_dir, "base-script-file")
try:
with open(config_path, "w") as f:
log.info("saving base-script-file to {}".format(config_path))
log.info("saving script file to {}".format(config_path))
f.write(config)
except OSError as e:
raise VPCSError("Could not save the configuration {}: {}".format(config_path, e))
# update the request with the new local base-script-file path
request["base_script_file"] = os.path.basename(config_path)
# update the request with the new local startup-config path
request["script_file"] = os.path.basename(config_path)
elif "script_file" in request:
if os.path.isfile(request["script_file"]) and request["script_file"] != config_path:
# this is a local file set in the GUI
try:
with open(request["script_file"], "r") as f:
config = f.read()
with open(config_path, "w") as f:
config = config.replace("\r", "")
config = config.replace('%h', vpcs_instance.name)
f.write(config)
request["script_file"] = os.path.basename(config_path)
except OSError as e:
raise VPCSError("Could not save the configuration from {} to {}: {}".format(request["script_file"], config_path, e))
elif not os.path.isfile(config_path):
raise VPCSError("Startup-config {} could not be found on this server".format(config_path))
except VPCSError as e:
self.send_custom_error(str(e))
return
# update the VPCS settings
response = {}
for name, value in request.items():
if hasattr(vpcs_instance, name) and getattr(vpcs_instance, name) != value:
try:
@@ -442,7 +391,6 @@ class VPCS(IModule):
try:
log.debug("starting VPCS with command: {}".format(vpcs_instance.command()))
vpcs_instance.vpcs = self._vpcs
vpcs_instance.start()
except VPCSError as e:
self.send_custom_error(str(e))
@@ -537,53 +485,24 @@ class VPCS(IModule):
return
try:
# find a UDP port
if self._current_udp_port >= self._udp_end_port_range:
self._current_udp_port = self._udp_start_port_range
try:
port = find_unused_port(self._current_udp_port, self._udp_end_port_range, host=self._host, socket_type="UDP")
except Exception as e:
raise VPCSError(e)
self._current_udp_port += 1
log.info("{} [id={}] has allocated UDP port {} with host {}".format(vpcs_instance.name,
vpcs_instance.id,
port,
self._host))
response = {"lport": port}
except VPCSError as e:
port = find_unused_port(self._udp_start_port_range,
self._udp_end_port_range,
host=self._host,
socket_type="UDP",
ignore_ports=self._allocated_udp_ports)
except Exception as e:
self.send_custom_error(str(e))
return
self._allocated_udp_ports.append(port)
log.info("{} [id={}] has allocated UDP port {} with host {}".format(vpcs_instance.name,
vpcs_instance.id,
port,
self._host))
response = {"lport": port}
response["port_id"] = request["port_id"]
self.send_response(response)
def _check_for_privileged_access(self, device):
"""
Check if VPCS can access Ethernet and TAP devices.
:param device: device name
"""
# we are root, so vpcs should have privileged access too
if os.geteuid() == 0:
return
# test if VPCS has the CAP_NET_RAW capability
if "security.capability" in os.listxattr(self._vpcs):
try:
caps = os.getxattr(self._vpcs, "security.capability")
# test the 2nd byte and check if the 13th bit (CAP_NET_RAW) is set
if struct.unpack("<IIIII", caps)[1] & 1 << 13:
return
except Exception as e:
log.error("could not determine if CAP_NET_RAW capability is set for {}: {}".format(self._vpcs, e))
return
raise VPCSError("{} has no privileged access to {}.".format(self._vpcs, device))
@IModule.route("vpcs.add_nio")
def add_nio(self, request):
"""
@@ -591,7 +510,6 @@ class VPCS(IModule):
Mandatory request parameters:
- id (VPCS instance identifier)
- slot (slot number)
- port (port number)
- port_id (unique port identifier)
- nio (one of the following)
@@ -617,7 +535,6 @@ class VPCS(IModule):
if not vpcs_instance:
return
slot = request["slot"]
port = request["port"]
try:
nio = None
@@ -634,7 +551,8 @@ class VPCS(IModule):
nio = NIO_UDP(lport, rhost, rport)
elif request["nio"]["type"] == "nio_tap":
tap_device = request["nio"]["tap_device"]
self._check_for_privileged_access(tap_device)
if not self.has_privileged_access(self._vpcs, tap_device):
raise VPCSError("{} has no privileged access to {}.".format(self._vpcs, tap_device))
nio = NIO_TAP(tap_device)
if not nio:
raise VPCSError("Requested NIO does not exist or is not supported: {}".format(request["nio"]["type"]))
@@ -643,7 +561,7 @@ class VPCS(IModule):
return
try:
vpcs_instance.slot_add_nio_binding(slot, port, nio)
vpcs_instance.port_add_nio_binding(port, nio)
except VPCSError as e:
self.send_custom_error(str(e))
return
@@ -657,7 +575,6 @@ class VPCS(IModule):
Mandatory request parameters:
- id (VPCS instance identifier)
- slot (slot identifier)
- port (port identifier)
Response parameters:
@@ -675,10 +592,11 @@ class VPCS(IModule):
if not vpcs_instance:
return
slot = request["slot"]
port = request["port"]
try:
vpcs_instance.slot_remove_nio_binding(slot, port)
nio = vpcs_instance.port_remove_nio_binding(port)
if isinstance(nio, NIO_UDP) and nio.lport in self._allocated_udp_ports:
self._allocated_udp_ports.remove(nio.lport)
except VPCSError as e:
self.send_custom_error(str(e))
return