PEP 8 clean thanks to auto pep8

This commit is contained in:
Julien Duponchelle 2015-01-20 13:24:00 +01:00
parent 7f185663d1
commit f5ed9fbcf1
124 changed files with 340 additions and 210 deletions

View File

@ -103,7 +103,7 @@ def main():
instance.change_password(passwd)
# wait for the password change to be processed. Continuing while
# a password change is processing will cause image creation to fail.
sleep(POLL_SEC*6)
sleep(POLL_SEC * 6)
env.host_string = str(instance.accessIPv4)
env.user = "root"

View File

@ -103,9 +103,9 @@ pygments_style = 'sphinx'
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
#html_theme = 'nature'
# html_theme = 'nature'
#If uncommented it's turn off the default read the doc style
# If uncommented it's turn off the default read the doc style
html_style = "/default.css"
# Theme options are theme-specific and customize the look and feel of a theme

View File

@ -175,7 +175,6 @@ class BaseCloudCtrl(object):
except Exception as e:
log.error("list_instances returned an error: {}".format(e))
def create_key_pair(self, name):
""" Create and return a new Key Pair. """

View File

@ -1,45 +1,67 @@
""" Exception classes for CloudCtrl classes. """
class ApiError(Exception):
""" Raised when the server returns 500 Compute Error. """
pass
class BadRequest(Exception):
""" Raised when the server returns 400 Bad Request. """
pass
class ComputeFault(Exception):
""" Raised when the server returns 400|500 Compute Fault. """
pass
class Forbidden(Exception):
""" Raised when the server returns 403 Forbidden. """
pass
class ItemNotFound(Exception):
""" Raised when the server returns 404 Not Found. """
pass
class KeyPairExists(Exception):
""" Raised when the server returns 409 Conflict Key pair exists. """
pass
class MethodNotAllowed(Exception):
""" Raised when the server returns 405 Method Not Allowed. """
pass
class OverLimit(Exception):
""" Raised when the server returns 413 Over Limit. """
pass
class ServerCapacityUnavailable(Exception):
""" Raised when the server returns 503 Server Capacity Uavailable. """
pass
class ServiceUnavailable(Exception):
""" Raised when the server returns 503 Service Unavailable. """
pass
class Unauthorized(Exception):
""" Raised when the server returns 401 Unauthorized. """
pass

View File

@ -41,7 +41,7 @@ from os.path import expanduser
SCRIPT_NAME = os.path.basename(__file__)
#Is the full path when used as an import
# Is the full path when used as an import
SCRIPT_PATH = os.path.dirname(__file__)
if not SCRIPT_PATH:
@ -98,6 +98,8 @@ Options:
""" % (SCRIPT_NAME)
# Parse cmd line options
def parse_cmd_line(argv):
"""
Parse command line arguments
@ -107,22 +109,22 @@ def parse_cmd_line(argv):
short_args = "dvhk"
long_args = ("debug",
"verbose",
"help",
"cloud_user_name=",
"cloud_api_key=",
"instance_id=",
"region=",
"dead_time=",
"init-wait=",
"check-interval=",
"file=",
"background",
)
"verbose",
"help",
"cloud_user_name=",
"cloud_api_key=",
"instance_id=",
"region=",
"dead_time=",
"init-wait=",
"check-interval=",
"file=",
"background",
)
try:
opts, extra_opts = getopt.getopt(argv[1:], short_args, long_args)
except getopt.GetoptError as e:
print("Unrecognized command line option or missing required argument: %s" %(e))
print("Unrecognized command line option or missing required argument: %s" % (e))
print(usage)
sys.exit(2)
@ -133,7 +135,7 @@ def parse_cmd_line(argv):
cmd_line_option_list["cloud_api_key"] = None
cmd_line_option_list["instance_id"] = None
cmd_line_option_list["region"] = None
cmd_line_option_list["dead_time"] = 60 * 60 #minutes
cmd_line_option_list["dead_time"] = 60 * 60 # minutes
cmd_line_option_list["check-interval"] = None
cmd_line_option_list["init-wait"] = 5 * 60
cmd_line_option_list["file"] = None
@ -146,8 +148,7 @@ def parse_cmd_line(argv):
elif sys.platform == "osx":
cmd_line_option_list['syslog'] = "/var/run/syslog"
else:
cmd_line_option_list['syslog'] = ('localhost',514)
cmd_line_option_list['syslog'] = ('localhost', 514)
get_gns3secrets(cmd_line_option_list)
cmd_line_option_list["dead_time"] = int(cmd_line_option_list["dead_time"])
@ -181,7 +182,7 @@ def parse_cmd_line(argv):
elif (opt in ("--background")):
cmd_line_option_list["daemon"] = True
if cmd_line_option_list["shutdown"] == False:
if cmd_line_option_list["shutdown"] is False:
if cmd_line_option_list["check-interval"] is None:
cmd_line_option_list["check-interval"] = cmd_line_option_list["dead_time"] + 120
@ -211,9 +212,9 @@ def parse_cmd_line(argv):
print(usage)
sys.exit(2)
return cmd_line_option_list
def get_gns3secrets(cmd_line_option_list):
"""
Load cloud credentials from .gns3secrets
@ -248,10 +249,10 @@ def set_logging(cmd_options):
log_level = logging.INFO
log_level_console = logging.WARNING
if cmd_options['verbose'] == True:
if cmd_options['verbose']:
log_level_console = logging.INFO
if cmd_options['debug'] == True:
if cmd_options['debug']:
log_level_console = logging.DEBUG
log_level = logging.DEBUG
@ -275,6 +276,7 @@ def set_logging(cmd_options):
return log
def send_shutdown(pid_file):
"""
Sends the daemon process a kill signal
@ -291,8 +293,9 @@ def send_shutdown(pid_file):
def _get_file_age(filename):
return datetime.datetime.fromtimestamp(
os.path.getmtime(filename)
)
os.path.getmtime(filename)
)
def monitor_loop(options):
"""
@ -307,7 +310,7 @@ def monitor_loop(options):
terminate_attempts = 0
while options['shutdown'] == False:
while options['shutdown'] is False:
log.debug("In monitor_loop for : %s" % (
datetime.datetime.now() - options['starttime'])
)
@ -320,15 +323,15 @@ def monitor_loop(options):
if delta.seconds > options["dead_time"]:
log.warning("Dead time exceeded, terminating instance ...")
#Terminate involves many layers of HTTP / API calls, lots of
#different errors types could occur here.
# Terminate involves many layers of HTTP / API calls, lots of
# different errors types could occur here.
try:
rksp = Rackspace(options)
rksp.terminate()
except Exception as e:
log.critical("Exception during terminate: %s" % (e))
terminate_attempts+=1
terminate_attempts += 1
log.warning("Termination sent, attempt: %s" % (terminate_attempts))
time.sleep(600)
else:
@ -372,14 +375,13 @@ def main():
for key, value in iter(sorted(options.items())):
log.debug("%s : %s" % (key, value))
log.debug("Checking file ....")
if os.path.isfile(options["file"]) == False:
if os.path.isfile(options["file"]) is False:
log.critical("File does not exist!!!")
sys.exit(1)
test_acess = _get_file_age(options["file"])
if type(test_acess) is not datetime.datetime:
if not isinstance(test_acess, datetime.datetime):
log.critical("Can't get file modification time!!!")
sys.exit(1)
@ -390,13 +392,11 @@ def main():
class MyDaemon(daemon.daemon):
def run(self):
monitor_loop(self.options)
if __name__ == "__main__":
result = main()
sys.exit(result)

View File

@ -21,4 +21,4 @@
# three numbers are the components of the version number. The fourth
# is zero for an official release, positive for a development branch,
# or negative for a release candidate or beta (after the base version
# number has been incremented)
# number has been incremented)

View File

@ -1,8 +1,14 @@
"""Generic linux daemon base class for python 3.x."""
import sys, os, time, atexit, signal
import sys
import os
import time
import atexit
import signal
class daemon:
"""A generic daemon class.
Usage: subclass the daemon class and override the run() method."""
@ -54,7 +60,7 @@ class daemon:
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
with open(self.pidfile, 'w+') as f:
f.write(pid + '\n')
def delpid(self):
@ -74,7 +80,7 @@ class daemon:
# Check for a pidfile to see if the daemon already runs
try:
with open(self.pidfile,'r') as pf:
with open(self.pidfile, 'r') as pf:
pid = int(pf.read().strip())
except IOError:
@ -101,20 +107,20 @@ class daemon:
# Get the pid from the pidfile
try:
with open(self.pidfile,'r') as pf:
with open(self.pidfile, 'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
while True:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
@ -123,7 +129,7 @@ class daemon:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print (str(err.args))
print(str(err.args))
sys.exit(1)
def restart(self):

View File

@ -23,7 +23,8 @@
# or negative for a release candidate or beta (after the base version
# number has been incremented)
import os, sys
import os
import sys
import json
import logging
import socket
@ -34,7 +35,9 @@ from gns3dms.cloud.rackspace_ctrl import RackspaceCtrl
LOG_NAME = "gns3dms.rksp"
log = logging.getLogger("%s" % (LOG_NAME))
class Rackspace(object):
def __init__(self, options):
self.username = options["cloud_user_name"]
self.apikey = options["cloud_api_key"]
@ -54,7 +57,7 @@ class Rackspace(object):
for region in self.rksp.list_regions():
log.debug("Rackspace regions: %s" % (region))
log.debug("Checking region: %s" % (self.region))
self.rksp.set_region(self.region)
for server in self.rksp.list_instances():

View File

@ -30,6 +30,7 @@ CLOUD_SERVER = 'CLOUD_SERVER'
class Config(object):
"""
Configuration file management using configparser.
"""
@ -117,7 +118,7 @@ class Config(object):
:returns: configparser section
"""
if not section in self._config:
if section is not in self._config:
return self._config["DEFAULT"]
return self._config[section]

View File

@ -27,32 +27,37 @@ import tornado.websocket
import logging
log = logging.getLogger(__name__)
class GNS3BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
if 'required_user' not in self.settings:
return "FakeUser"
user = self.get_secure_cookie("user")
if not user:
return None
return None
if self.settings['required_user'] == user.decode("utf-8"):
return user
return user
class GNS3WebSocketBaseHandler(tornado.websocket.WebSocketHandler):
def get_current_user(self):
if 'required_user' not in self.settings:
return "FakeUser"
user = self.get_secure_cookie("user")
if not user:
return None
return None
if self.settings['required_user'] == user.decode("utf-8"):
return user
return user
class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.write('<html><body><form action="/login" method="post">'
'Name: <input type="text" name="name">'
@ -61,10 +66,10 @@ class LoginHandler(tornado.web.RequestHandler):
'</form></body></html>')
try:
redirect_to = self.get_argument("next")
self.set_secure_cookie("login_success_redirect_to", redirect_to)
redirect_to = self.get_argument("next")
self.set_secure_cookie("login_success_redirect_to", redirect_to)
except tornado.web.MissingArgumentError:
pass
pass
def post(self):
@ -72,21 +77,21 @@ class LoginHandler(tornado.web.RequestHandler):
password = self.get_argument("password")
if self.settings['required_user'] == user and self.settings['required_pass'] == password:
self.set_secure_cookie("user", user)
auth_status = "successful"
self.set_secure_cookie("user", user)
auth_status = "successful"
else:
self.set_secure_cookie("user", "None")
auth_status = "failure"
self.set_secure_cookie("user", "None")
auth_status = "failure"
log.info("Authentication attempt {}: {}, {}".format(auth_status, user, password))
try:
redirect_to = self.get_secure_cookie("login_success_redirect_to")
redirect_to = self.get_secure_cookie("login_success_redirect_to")
except tornado.web.MissingArgumentError:
redirect_to = "/"
redirect_to = "/"
if redirect_to is None:
self.write({'result': auth_status})
else:
log.info('Redirecting to {}'.format(redirect_to))
self.redirect(redirect_to)
self.redirect(redirect_to)

View File

@ -34,6 +34,7 @@ log = logging.getLogger(__name__)
class FileUploadHandler(GNS3BaseHandler):
"""
File upload handler.

View File

@ -22,6 +22,7 @@ from aiohttp.web import HTTPConflict
class ProjectHandler:
@classmethod
@Route.post(
r"/project",

View File

@ -22,6 +22,7 @@ from ..modules.virtualbox import VirtualBox
class VirtualBoxHandler:
"""
API entry points for VirtualBox.
"""

View File

@ -23,6 +23,7 @@ from ..modules.vpcs import VPCS
class VPCSHandler:
"""
API entry points for VPCS.
"""

View File

@ -27,6 +27,7 @@ from gns3server.version import __version__
import logging
log = logging.getLogger(__name__)
def locale_check():
"""
Checks if this application runs with a correct locale (i.e. supports UTF-8 encoding) and attempt to fix
@ -71,11 +72,10 @@ def main():
Entry point for GNS3 server
"""
#TODO: migrate command line options to argparse (don't forget the quiet mode).
# TODO: migrate command line options to argparse (don't forget the quiet mode).
current_year = datetime.date.today().year
# TODO: Renable the test when we will have command line
# user_log = logging.getLogger('user_facing')
# if not options.quiet:
@ -95,7 +95,7 @@ def main():
user_log.info("GNS3 server version {}".format(__version__))
user_log.info("Copyright (c) 2007-{} GNS3 Technologies Inc.".format(current_year))
#TODO: end todo
# TODO: end todo
# we only support Python 3 version >= 3.3
if sys.version_info < (3, 3):
@ -115,7 +115,7 @@ def main():
return
# TODO: Renable console_bind_to_any when we will have command line parsing
#server = Server(options.host, options.port, options.console_bind_to_any)
# server = Server(options.host, options.port, options.console_bind_to_any)
server = Server("127.0.0.1", 8000, False)
server.run()

View File

@ -17,6 +17,7 @@
class Adapter(object):
"""
Base class for adapters.

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class EthernetAdapter(Adapter):
"""
VPCS Ethernet adapter.
"""

View File

@ -24,6 +24,7 @@ from .project_manager import ProjectManager
class BaseManager:
"""
Base class for all Manager.
Responsible of management of a VM pool

View File

@ -95,6 +95,7 @@ log = logging.getLogger(__name__)
class Dynamips(IModule):
"""
Dynamips module.
@ -140,7 +141,7 @@ class Dynamips(IModule):
self._console_host = dynamips_config.get("console_host", kwargs["console_host"])
if not sys.platform.startswith("win32"):
#FIXME: pickle issues Windows
# FIXME: pickle issues Windows
self._callback = self.add_periodic_callback(self._check_hypervisors, 5000)
self._callback.start()
@ -323,7 +324,7 @@ class Dynamips(IModule):
log.debug("received request {}".format(request))
#TODO: JSON schema validation
# TODO: JSON schema validation
if not self._hypervisor_manager:
if "path" in request:
@ -407,7 +408,7 @@ class Dynamips(IModule):
rhost = request["nio"]["rhost"]
rport = request["nio"]["rport"]
try:
#TODO: handle IPv6
# TODO: handle IPv6
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect((rhost, rport))
except OSError as e:

View File

@ -17,6 +17,7 @@
class Adapter(object):
"""
Base class for adapters.

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C1700_MB_1FE(Adapter):
"""
Integrated 1 port FastEthernet adapter for c1700 platform.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C1700_MB_WIC1(Adapter):
"""
Fake module to provide a placeholder for slot 1 interfaces when WICs
are inserted into WIC slot 1.

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C2600_MB_1E(Adapter):
"""
Integrated 1 port Ethernet adapter for the c2600 platform.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C2600_MB_1FE(Adapter):
"""
Integrated 1 port FastEthernet adapter for the c2600 platform.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C2600_MB_2E(Adapter):
"""
Integrated 2 port Ethernet adapter for the c2600 platform.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C2600_MB_2FE(Adapter):
"""
Integrated 2 port FastEthernet adapter for the c2600 platform.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C7200_IO_2FE(Adapter):
"""
C7200-IO-2FE FastEthernet Input/Ouput controller.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C7200_IO_FE(Adapter):
"""
C7200-IO-FE FastEthernet Input/Ouput controller.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class C7200_IO_GE_E(Adapter):
"""
C7200-IO-GE-E GigabitEthernet Input/Ouput controller.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class Leopard_2FE(Adapter):
"""
Integrated 2 port FastEthernet adapter for c3660 router.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class NM_16ESW(Adapter):
"""
NM-16ESW FastEthernet network module.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class NM_1E(Adapter):
"""
NM-1E Ethernet network module.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class NM_1FE_TX(Adapter):
"""
NM-1FE-TX FastEthernet network module.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class NM_4E(Adapter):
"""
NM-4E Ethernet network module.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class NM_4T(Adapter):
"""
NM-4T Serial network module.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_2FE_TX(Adapter):
"""
PA-2FE-TX FastEthernet port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_4E(Adapter):
"""
PA-4E Ethernet port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_4T(Adapter):
"""
PA-4T+ Serial port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_8E(Adapter):
"""
PA-8E Ethernet port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_8T(Adapter):
"""
PA-8T Serial port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_A1(Adapter):
"""
PA-A1 ATM port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_FE_TX(Adapter):
"""
PA-FE-TX FastEthernet port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_GE(Adapter):
"""
PA-GE GigabitEthernet port adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class PA_POS_OC3(Adapter):
"""
PA-POS-OC3 port adapter.
"""

View File

@ -17,6 +17,7 @@
class WIC_1ENET(object):
"""
WIC-1ENET Ethernet
"""

View File

@ -17,6 +17,7 @@
class WIC_1T(object):
"""
WIC-1T Serial
"""

View File

@ -17,6 +17,7 @@
class WIC_2T(object):
"""
WIC-2T Serial
"""

View File

@ -466,7 +466,7 @@ class VM(object):
adapter_name = value
adapter = ADAPTER_MATRIX[adapter_name]()
try:
if router.slots[slot_id] and type(router.slots[slot_id]) != type(adapter):
if router.slots[slot_id] and not isinstance(router.slots[slot_id], type(adapter)):
router.slot_remove_binding(slot_id)
router.slot_add_binding(slot_id, adapter)
response[name] = value
@ -487,14 +487,14 @@ class VM(object):
wic_name = value
wic = WIC_MATRIX[wic_name]()
try:
if router.slots[0].wics[wic_slot_id] and type(router.slots[0].wics[wic_slot_id]) != type(wic):
if router.slots[0].wics[wic_slot_id] and not isinstance(router.slots[0].wics[wic_slot_id], type(wic)):
router.uninstall_wic(wic_slot_id)
router.install_wic(wic_slot_id, wic)
response[name] = value
except DynamipsError as e:
self.send_custom_error(str(e))
return
elif name.startswith("wic") and value == None:
elif name.startswith("wic") and value is None:
wic_slot_id = int(name[-1])
if router.slots[0].wics and router.slots[0].wics[wic_slot_id]:
try:

View File

@ -30,6 +30,7 @@ log = logging.getLogger(__name__)
class DynamipsHypervisor(object):
"""
Creates a new connection to a Dynamips server (also called hypervisor)

View File

@ -32,6 +32,7 @@ log = logging.getLogger(__name__)
class Hypervisor(DynamipsHypervisor):
"""
Hypervisor.

View File

@ -34,6 +34,7 @@ log = logging.getLogger(__name__)
class HypervisorManager(object):
"""
Manages Dynamips hypervisors.

View File

@ -27,6 +27,7 @@ log = logging.getLogger(__name__)
class NIO(object):
"""
Base NIO class

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_FIFO(NIO):
"""
Dynamips FIFO NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_GenericEthernet(NIO):
"""
Dynamips generic Ethernet NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_LinuxEthernet(NIO):
"""
Dynamips Linux Ethernet NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_Mcast(NIO):
"""
Dynamips Linux Ethernet NIO.
@ -103,5 +104,5 @@ class NIO_Mcast(NIO):
"""
self._hypervisor.send("nio set_mcast_ttl {name} {ttl}".format(name=self._name,
ttl=ttl))
ttl=ttl))
self._ttl = ttl

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_Null(NIO):
"""
Dynamips NULL NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_TAP(NIO):
"""
Dynamips TAP NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_UDP(NIO):
"""
Dynamips UDP NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_UDP_auto(NIO):
"""
Dynamips auto UDP NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_UNIX(NIO):
"""
Dynamips UNIX NIO.

View File

@ -26,6 +26,7 @@ log = logging.getLogger(__name__)
class NIO_VDE(NIO):
"""
Dynamips VDE NIO.

View File

@ -24,6 +24,7 @@ from ..dynamips_error import DynamipsError
class ATMBridge(object):
"""
Dynamips bridge switch.
@ -33,7 +34,7 @@ class ATMBridge(object):
def __init__(self, hypervisor, name):
#FIXME: instance tracking
# FIXME: instance tracking
self._hypervisor = hypervisor
self._name = '"' + name + '"' # put name into quotes to protect spaces
self._hypervisor.send("atm_bridge create {}".format(self._name))

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class ATMSwitch(object):
"""
Dynamips ATM switch.

View File

@ -22,6 +22,7 @@ http://github.com/GNS3/dynamips/blob/master/README.hypervisor#L538
class Bridge(object):
"""
Dynamips bridge.

View File

@ -29,6 +29,7 @@ log = logging.getLogger(__name__)
class C1700(Router):
"""
Dynamips c1700 router.

View File

@ -31,6 +31,7 @@ log = logging.getLogger(__name__)
class C2600(Router):
"""
Dynamips c2600 router.

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class C2691(Router):
"""
Dynamips c2691 router.

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class C3600(Router):
"""
Dynamips c3600 router.

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class C3725(Router):
"""
Dynamips c3725 router.

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class C3745(Router):
"""
Dynamips c3745 router.

View File

@ -30,6 +30,7 @@ log = logging.getLogger(__name__)
class C7200(Router):
"""
Dynamips c7200 router (model is 7206).
@ -227,9 +228,9 @@ class C7200(Router):
powered_on=power_supply))
log.info("router {name} [id={id}]: power supply {power_supply_id} state updated to {powered_on}".format(name=self._name,
id=self._id,
power_supply_id=power_supply_id,
powered_on=power_supply))
id=self._id,
power_supply_id=power_supply_id,
powered_on=power_supply))
power_supply_id += 1
self._power_supplies = power_supplies

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class EthernetSwitch(object):
"""
Dynamips Ethernet switch.
@ -268,9 +269,9 @@ class EthernetSwitch(object):
outer_vlan=outer_vlan))
log.info("Ethernet switch {name} [id={id}]: port {port} set as a QinQ port with outer VLAN {vlan_id}".format(name=self._name,
id=self._id,
port=port,
vlan_id=outer_vlan))
id=self._id,
port=port,
vlan_id=outer_vlan))
self._mapping[port] = ("qinq", outer_vlan)
def get_mac_addr_table(self):

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class FrameRelaySwitch(object):
"""
Dynamips Frame Relay switch.

View File

@ -28,6 +28,7 @@ log = logging.getLogger(__name__)
class Hub(Bridge):
"""
Dynamips hub (based on Bridge)

View File

@ -33,6 +33,7 @@ log = logging.getLogger(__name__)
class Router(object):
"""
Dynamips router implementation.
@ -575,7 +576,7 @@ class Router(object):
try:
reply = self._hypervisor.send("vm extract_config {}".format(self._name))[0].rsplit(' ', 2)[-2:]
except IOError:
#for some reason Dynamips gets frozen when it does not find the magic number in the NVRAM file.
# for some reason Dynamips gets frozen when it does not find the magic number in the NVRAM file.
return None, None
startup_config = reply[0][1:-1] # get statup-config and remove single quotes
private_config = reply[1][1:-1] # get private-config and remove single quotes

View File

@ -44,7 +44,7 @@ ETHSW_DELETE_SCHEMA = {
"required": ["id"]
}
#TODO: ports {'1': {'vlan': 1, 'type': 'qinq'}
# TODO: ports {'1': {'vlan': 1, 'type': 'qinq'}
ETHSW_UPDATE_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Request validation to update an Ethernet switch instance",
@ -59,20 +59,20 @@ ETHSW_UPDATE_SCHEMA = {
"type": "string",
"minLength": 1,
},
# "ports": {
# "type": "object",
# "properties": {
# "type": {
# "description": "Port type",
# "enum": ["access", "dot1q", "qinq"],
# },
# "vlan": {
# "description": "VLAN number",
# "type": "integer",
# "minimum": 1
# },
# },
# },
# "ports": {
# "type": "object",
# "properties": {
# "type": {
# "description": "Port type",
# "enum": ["access", "dot1q", "qinq"],
# },
# "vlan": {
# "description": "VLAN number",
# "type": "integer",
# "minimum": 1
# },
# },
# },
},
#"additionalProperties": False,
"required": ["id"]

View File

@ -147,7 +147,7 @@ VM_RELOAD_SCHEMA = {
"required": ["id"]
}
#TODO: improve platform specific properties (dependencies?)
# TODO: improve platform specific properties (dependencies?)
VM_UPDATE_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Request validation to update a VM instance",

View File

@ -56,6 +56,7 @@ log = logging.getLogger(__name__)
class IOU(IModule):
"""
IOU module.
@ -635,7 +636,7 @@ class IOU(IModule):
rhost = request["nio"]["rhost"]
rport = request["nio"]["rport"]
try:
#TODO: handle IPv6
# TODO: handle IPv6
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect((rhost, rport))
except OSError as e:

View File

@ -17,6 +17,7 @@
class Adapter(object):
"""
Base class for adapters.

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class EthernetAdapter(Adapter):
"""
IOU Ethernet adapter.
"""

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class SerialAdapter(Adapter):
"""
IOU Serial adapter.
"""

View File

@ -43,6 +43,7 @@ log = logging.getLogger(__name__)
class IOUDevice(object):
"""
IOU device implementation.

View File

@ -56,22 +56,22 @@ EXIT_ABORT = 2
# Mostly from:
# https://code.google.com/p/miniboa/source/browse/trunk/miniboa/telnet.py
#--[ Telnet Commands ]---------------------------------------------------------
SE = 240 # End of sub-negotiation parameters
NOP = 241 # No operation
DATMK = 242 # Data stream portion of a sync.
BREAK = 243 # NVT Character BRK
IP = 244 # Interrupt Process
AO = 245 # Abort Output
AYT = 246 # Are you there
EC = 247 # Erase Character
EL = 248 # Erase Line
GA = 249 # The Go Ahead Signal
SB = 250 # Sub-option to follow
WILL = 251 # Will; request or confirm option begin
WONT = 252 # Wont; deny option request
DO = 253 # Do = Request or confirm remote option
DONT = 254 # Don't = Demand or confirm option halt
IAC = 255 # Interpret as Command
SE = 240 # End of sub-negotiation parameters
NOP = 241 # No operation
DATMK = 242 # Data stream portion of a sync.
BREAK = 243 # NVT Character BRK
IP = 244 # Interrupt Process
AO = 245 # Abort Output
AYT = 246 # Are you there
EC = 247 # Erase Character
EL = 248 # Erase Line
GA = 249 # The Go Ahead Signal
SB = 250 # Sub-option to follow
WILL = 251 # Will; request or confirm option begin
WONT = 252 # Wont; deny option request
DO = 253 # Do = Request or confirm remote option
DONT = 254 # Don't = Demand or confirm option halt
IAC = 255 # Interpret as Command
SEND = 1 # Sub-process negotiation SEND command
IS = 0 # Sub-process negotiation IS command
#--[ Telnet Options ]----------------------------------------------------------
@ -154,6 +154,7 @@ class FileLock:
class Console:
def fileno(self):
raise NotImplementedError("Only routers have fileno()")

View File

@ -21,6 +21,7 @@ Base interface for NIOs.
class NIO(object):
"""
Network Input/Output.
"""

View File

@ -23,6 +23,7 @@ from .nio import NIO
class NIO_GenericEthernet(NIO):
"""
Generic Ethernet NIO.

View File

@ -23,6 +23,7 @@ from .nio import NIO
class NIO_TAP(NIO):
"""
TAP NIO.

View File

@ -23,6 +23,7 @@ from .nio import NIO
class NIO_UDP(NIO):
"""
UDP NIO.

View File

@ -21,6 +21,7 @@ Interface for TAP NIOs (UNIX based OSes only).
class NIO_TAP(object):
"""
TAP NIO.

View File

@ -21,6 +21,7 @@ Interface for UDP NIOs.
class NIO_UDP(object):
"""
UDP NIO.

View File

@ -21,6 +21,7 @@ import asyncio
class PortManager:
"""
:param host: IP address to bind for console connections
"""

View File

@ -21,6 +21,7 @@ from uuid import uuid4
class Project:
"""
A project contains a list of VM.
In theory VM are isolated project/project.

View File

@ -20,6 +20,7 @@ from .project import Project
class ProjectManager:
"""
This singleton keeps track of available projects.
"""

View File

@ -49,6 +49,7 @@ log = logging.getLogger(__name__)
class Qemu(IModule):
"""
QEMU module.
@ -551,7 +552,7 @@ class Qemu(IModule):
rhost = request["nio"]["rhost"]
rport = request["nio"]["rport"]
try:
#TODO: handle IPv6
# TODO: handle IPv6
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect((rhost, rport))
except OSError as e:

View File

@ -17,6 +17,7 @@
class Adapter(object):
"""
Base class for adapters.

View File

@ -19,6 +19,7 @@ from .adapter import Adapter
class EthernetAdapter(Adapter):
"""
QEMU Ethernet adapter.
"""

View File

@ -21,6 +21,7 @@ Base interface for NIOs.
class NIO(object):
"""
Network Input/Output.
"""

View File

@ -23,6 +23,7 @@ from .nio import NIO
class NIO_UDP(NIO):
"""
UDP NIO.

View File

@ -43,6 +43,7 @@ log = logging.getLogger(__name__)
class QemuVM(object):
"""
QEMU VM implementation.
@ -462,7 +463,6 @@ class QemuVM(object):
disk_image=hdb_disk_image))
self._hdb_disk_image = hdb_disk_image
@property
def adapters(self):
"""
@ -586,7 +586,6 @@ class QemuVM(object):
priority=process_priority))
self._process_priority = process_priority
@property
def ram(self):
"""
@ -999,18 +998,18 @@ class QemuVM(object):
if self._legacy_networking:
self._control_vm("host_net_remove {} gns3-{}".format(adapter_id, adapter_id))
self._control_vm("host_net_add udp vlan={},name=gns3-{},sport={},dport={},daddr={}".format(adapter_id,
adapter_id,
nio.lport,
nio.rport,
nio.rhost))
adapter_id,
nio.lport,
nio.rport,
nio.rhost))
else:
self._control_vm("host_net_remove {} gns3-{}".format(adapter_id, adapter_id))
self._control_vm("host_net_add socket vlan={},name=gns3-{},udp={}:{},localaddr={}:{}".format(adapter_id,
adapter_id,
nio.rhost,
nio.rport,
self._host,
nio.lport))
adapter_id,
nio.rhost,
nio.rport,
self._host,
nio.lport))
adapter.add_nio(0, nio)
log.info("QEMU VM {name} [id={id}]: {nio} added to adapter {adapter_id}".format(name=self._name,
@ -1154,8 +1153,8 @@ class QemuVM(object):
if not os.path.exists(hdb_disk):
try:
retcode = subprocess.call([qemu_img_path, "create", "-o",
"backing_file={}".format(self._hdb_disk_image),
"-f", "qcow2", hdb_disk])
"backing_file={}".format(self._hdb_disk_image),
"-f", "qcow2", hdb_disk])
log.info("{} returned with {}".format(qemu_img_path, retcode))
except (OSError, subprocess.SubprocessError) as e:
raise QemuError("Could not create disk image {}".format(e))
@ -1190,24 +1189,24 @@ class QemuVM(object):
network_options = []
adapter_id = 0
for adapter in self._ethernet_adapters:
#TODO: let users specify a base mac address
# TODO: let users specify a base mac address
mac = "00:00:ab:%02x:%02x:%02d" % (random.randint(0x00, 0xff), random.randint(0x00, 0xff), adapter_id)
network_options.extend(["-net", "nic,vlan={},macaddr={},model={}".format(adapter_id, mac, self._adapter_type)])
nio = adapter.get_nio(0)
if nio and isinstance(nio, NIO_UDP):
if self._legacy_networking:
network_options.extend(["-net", "udp,vlan={},name=gns3-{},sport={},dport={},daddr={}".format(adapter_id,
adapter_id,
nio.lport,
nio.rport,
nio.rhost)])
adapter_id,
nio.lport,
nio.rport,
nio.rhost)])
else:
network_options.extend(["-net", "socket,vlan={},name=gns3-{},udp={}:{},localaddr={}:{}".format(adapter_id,
adapter_id,
nio.rhost,
nio.rport,
self._host,
nio.lport)])
adapter_id,
nio.rhost,
nio.rport,
self._host,
nio.lport)])
else:
network_options.extend(["-net", "user,vlan={},name=gns3-{}".format(adapter_id, adapter_id)])
adapter_id += 1

View File

@ -31,6 +31,7 @@ if sys.platform.startswith("win"):
class TelnetServer(threading.Thread):
"""
Mini Telnet Server.
@ -226,37 +227,38 @@ class TelnetServer(threading.Thread):
# Mostly from https://code.google.com/p/miniboa/source/browse/trunk/miniboa/telnet.py
# Telnet Commands
SE = 240 # End of sub-negotiation parameters
NOP = 241 # No operation
DATMK = 242 # Data stream portion of a sync.
BREAK = 243 # NVT Character BRK
IP = 244 # Interrupt Process
AO = 245 # Abort Output
AYT = 246 # Are you there
EC = 247 # Erase Character
EL = 248 # Erase Line
GA = 249 # The Go Ahead Signal
SB = 250 # Sub-option to follow
WILL = 251 # Will; request or confirm option begin
WONT = 252 # Wont; deny option request
DO = 253 # Do = Request or confirm remote option
DONT = 254 # Don't = Demand or confirm option halt
IAC = 255 # Interpret as Command
SEND = 1 # Sub-process negotiation SEND command
IS = 0 # Sub-process negotiation IS command
SE = 240 # End of sub-negotiation parameters
NOP = 241 # No operation
DATMK = 242 # Data stream portion of a sync.
BREAK = 243 # NVT Character BRK
IP = 244 # Interrupt Process
AO = 245 # Abort Output
AYT = 246 # Are you there
EC = 247 # Erase Character
EL = 248 # Erase Line
GA = 249 # The Go Ahead Signal
SB = 250 # Sub-option to follow
WILL = 251 # Will; request or confirm option begin
WONT = 252 # Wont; deny option request
DO = 253 # Do = Request or confirm remote option
DONT = 254 # Don't = Demand or confirm option halt
IAC = 255 # Interpret as Command
SEND = 1 # Sub-process negotiation SEND command
IS = 0 # Sub-process negotiation IS command
# Telnet Options
BINARY = 0 # Transmit Binary
ECHO = 1 # Echo characters back to sender
RECON = 2 # Reconnection
SGA = 3 # Suppress Go-Ahead
TMARK = 6 # Timing Mark
TTYPE = 24 # Terminal Type
NAWS = 31 # Negotiate About Window Size
LINEMO = 34 # Line Mode
BINARY = 0 # Transmit Binary
ECHO = 1 # Echo characters back to sender
RECON = 2 # Reconnection
SGA = 3 # Suppress Go-Ahead
TMARK = 6 # Timing Mark
TTYPE = 24 # Terminal Type
NAWS = 31 # Negotiate About Window Size
LINEMO = 34 # Line Mode
class TelnetClient(object):
"""
Represents a Telnet client connection.

Some files were not shown because too many files have changed in this diff Show More