Merge branch 'devl/cleanup' of https://github.com/OPENNETWORKINGLAB/ONLabTest into cleanup
Conflicts:
TestON/drivers/common/cli/onosdriver.py
TestON/drivers/common/clidriver.py
diff --git a/TestON/drivers/common/api/controllerdriver.py b/TestON/drivers/common/api/controllerdriver.py
index f6b941f..5ac112f 100644
--- a/TestON/drivers/common/api/controllerdriver.py
+++ b/TestON/drivers/common/api/controllerdriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
-Created on 29-Nov-2012
+"""
+Created on 29-Nov-2012
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,15 +16,17 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import sys
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.apidriver import API
-class Controller(API):
+
+class Controller( API ):
# The common functions for emulator included in emulatordriver
- def __init__(self):
- super(API, self).__init__()
-
+
+ def __init__( self ):
+ super( API, self ).__init__()
+
diff --git a/TestON/drivers/common/api/fvtapidriver.py b/TestON/drivers/common/api/fvtapidriver.py
index 620b3e9..8203166 100644
--- a/TestON/drivers/common/api/fvtapidriver.py
+++ b/TestON/drivers/common/api/fvtapidriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
+"""
Created on 26-Oct-2012
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,18 +16,18 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
fvtapidriver is the basic driver which will handle the fvtapidriver functions
-'''
-'''
+"""
+"""
There are two changes required in flowvisor-test framework :
1. In ~/flowvisortests/tests/templatetest.py line : 15 comment 'basic_logger = None'
2. In ~/flowvisortests/tests/testutils.py line : 50 specify config file path CONFIG_FILE = "~/flowvisor-test/tests/tests-base.json"
-'''
+"""
import pexpect
import struct
import fcntl
@@ -35,12 +35,12 @@
import signal
import re
import sys
-sys.path.append("../")
+sys.path.append( "../" )
from common.apidriver import API
import logging
-sys.path.append(path+"/lib/flowvisor-test/tests")
-sys.path.append(path+"/lib/flowvisor-test/src/python/")
+sys.path.append( path + "/lib/flowvisor-test/tests" )
+sys.path.append( path + "/lib/flowvisor-test/src/python/" )
import templatetest
import testutils
@@ -53,29 +53,30 @@
import __builtin__
config_default = {
- "param" : None,
- "fv_cmd" : "/home/openflow/flowvisor/scripts/flowvisor.sh",
- "platform" : "local",
- "controller_host" : "127.0.0.1",
- "controller_port" : 6633,
- "timeout" : 3,
- "port_count" : 4,
- "base_of_port" : 1,
- "base_if_index" : 1,
- "test_spec" : "all",
- "test_dir" : ".",
- "log_file" : "/home/openflow/fvt.log",
- "list" : False,
- "debug" : "debug",
- "dbg_level" : logging.DEBUG,
- "port_map" : {},
- "test_params" : "None"
+ "param": None,
+ "fv_cmd": "/home/openflow/flowvisor/scripts/flowvisor.sh",
+ "platform": "local",
+ "controller_host": "127.0.0.1",
+ "controller_port": 6633,
+ "timeout": 3,
+ "port_count": 4,
+ "base_of_port": 1,
+ "base_if_index": 1,
+ "test_spec": "all",
+ "test_dir": ".",
+ "log_file": "/home/openflow/fvt.log",
+ "list": False,
+ "debug": "debug",
+ "dbg_level": logging.DEBUG,
+ "port_map": {},
+ "test_params": "None"
}
-def test_set_init(config):
+
+def test_set_init( config ):
"""
Set up function for basic test classes
- @param config The configuration dictionary; see fvt
+ config: The configuration dictionary; see fvt
"""
global basic_port_map
global basic_fv_cmd
@@ -84,88 +85,89 @@
global basic_config
global baisc_logger
- basic_fv_cmd = config["fv_cmd"]
- basic_timeout = config["timeout"]
- basic_port_map = config["port_map"]
+ basic_fv_cmd = config[ "fv_cmd" ]
+ basic_timeout = config[ "timeout" ]
+ basic_port_map = config[ "port_map" ]
basic_config = config
-class FvtApiDriver(API,templatetest.TemplateTest):
- def __init__(self):
- super(API, self).__init__()
+class FvtApiDriver( API, templatetest.TemplateTest ):
+
+ def __init__( self ):
+ super( API, self ).__init__()
print 'init'
-
- def connect(self,**connectargs):
+ def connect( self, **connectargs ):
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- connect_result = super(API,self).connect()
- self.logFileName = main.logdir+"/"+self.name+".session"
- config_default["log_file"] = self.logFileName
- test_set_init(config_default)
- __builtin__.basic_logger = vars(main)[self.name+'log']
- __builtin__.basic_logger.info("Calling my test setup")
- self.setUp(basic_logger)
+ vars( self )[ key ] = connectargs[ key ]
- (self.fv, self.sv, sv_ret, ctl_ret, sw_ret) = testutils.setUpTestEnv(self, fv_cmd=basic_fv_cmd)
-
- self.chkSetUpCondition(self.fv, sv_ret, ctl_ret, sw_ret)
+ self.name = self.options[ 'name' ]
+ connect_result = super( API, self ).connect()
+ self.logFileName = main.logdir + "/" + self.name + ".session"
+ config_default[ "log_file" ] = self.logFileName
+ test_set_init( config_default )
+ __builtin__.basic_logger = vars( main )[ self.name + 'log' ]
+ __builtin__.basic_logger.info( "Calling my test setup" )
+ self.setUp( basic_logger )
+
+ ( self.fv, self.sv, sv_ret, ctl_ret, sw_ret ) = testutils.setUpTestEnv(
+ self, fv_cmd=basic_fv_cmd )
+
+ self.chkSetUpCondition( self.fv, sv_ret, ctl_ret, sw_ret )
return main.TRUE
- def simplePacket(self,dl_src):
- dl_src = vars(testutils)[dl_src]
- return testutils.simplePacket(dl_src = dl_src)
-
- def genPacketIn(self, in_port, pkt):
- return testutils.genPacketIn(in_port=in_port, pkt=pkt)
-
- def ofmsgSndCmp(self, snd_list, exp_list, xid_ignore=True, hdr_only=True):
- return testutils.ofmsgSndCmp(self, snd_list, exp_list, xid_ignore, hdr_only)
-
- def setRule(self,sv,rule,num_try) :
- return testutils.setRule(self,sv,rule,num_try)
-
- def chkFlowdb(self,controller_number,switch_number,exp_count,exp_rewrites) :
- return testutils.chkFlowdb(self,controller_number,switch_number,exp_count,exp_rewrites)
-
- def chkSwitchStats(self, switch_number, ofproto, exp_snd_count, exp_rcv_count):
- return testutils.chkSwitchStats(self, switch_number, ofproto, exp_snd_count, exp_rcv_count)
-
- def chkSliceStats(self,controller_number,ofproto,exp_snd_count,exp_rcv_count) :
- return testutils.chkSliceStats(self,controller_number,ofproto,exp_snd_count,exp_rcv_count)
-
- def recvStats(self,swId,typ) :
- return testutils.recvStats(self,swId,typ)
-
- def ofmsgSndCmpWithXid(self,snd_list,exp_list,xid_ignore,hdr_only) :
- return testutils.ofmsgSndCmpWithXid(self,snd_list,exp_list,xid_ignore,hdr_only)
-
- def genPacketOut(self,xid,buffer_id,in_port,action_ports,pkt) :
- return testutils.genPacketOut(self,xid,buffer_id,in_port,action_ports,pkt)
-
- def genFlowModFlush(self) :
+ def simplePacket( self, dl_src ):
+ dl_src = vars( testutils )[ dl_src ]
+ return testutils.simplePacket( dl_src=dl_src )
+
+ def genPacketIn( self, in_port, pkt ):
+ return testutils.genPacketIn( in_port=in_port, pkt=pkt )
+
+ def ofmsgSndCmp( self, snd_list, exp_list, xid_ignore=True, hdr_only=True ):
+ return testutils.ofmsgSndCmp( self, snd_list, exp_list, xid_ignore, hdr_only )
+
+ def setRule( self, sv, rule, num_try ):
+ return testutils.setRule( self, sv, rule, num_try )
+
+ def chkFlowdb( self, controller_number, switch_number, exp_count, exp_rewrites ):
+ return testutils.chkFlowdb( self, controller_number, switch_number, exp_count, exp_rewrites )
+
+ def chkSwitchStats( self, switch_number, ofproto, exp_snd_count, exp_rcv_count ):
+ return testutils.chkSwitchStats( self, switch_number, ofproto, exp_snd_count, exp_rcv_count )
+
+ def chkSliceStats( self, controller_number, ofproto, exp_snd_count, exp_rcv_count ):
+ return testutils.chkSliceStats( self, controller_number, ofproto, exp_snd_count, exp_rcv_count )
+
+ def recvStats( self, swId, typ ):
+ return testutils.recvStats( self, swId, typ )
+
+ def ofmsgSndCmpWithXid( self, snd_list, exp_list, xid_ignore, hdr_only ):
+ return testutils.ofmsgSndCmpWithXid( self, snd_list, exp_list, xid_ignore, hdr_only )
+
+ def genPacketOut( self, xid, buffer_id, in_port, action_ports, pkt ):
+ return testutils.genPacketOut( self, xid, buffer_id, in_port, action_ports, pkt )
+
+ def genFlowModFlush( self ):
return testutils.genFlowModFlush()
-
- def genPhyPort(self,name,addr,port_no) :
- return testutils.genPhyPort(name,addr,port_no)
-
- def disconnect(self,handle):
+
+ def genPhyPort( self, name, addr, port_no ):
+ return testutils.genPhyPort( name, addr, port_no )
+
+ def disconnect( self, handle ):
response = ''
- '''
+ """
if self.handle:
self.handle = handle
- response = self.execute(cmd="exit",prompt="(.*)",timeout=120)
+ response = self.execute( cmd="exit",prompt="(.*)",timeout=120 )
else :
- main.log.error("Connection failed to the host")
+ main.log.error( "Connection failed to the host" )
response = main.FALSE
- '''
- return response
-
- def setUp(self,basic_logger):
+ """
+ return response
+
+ def setUp( self, basic_logger ):
self.logger = basic_logger
- #basic_logger.info("** START TEST CASE " + str(self))
+ # basic_logger.info( "** START TEST CASE " + str( self ) )
if basic_timeout == 0:
self.timeout = None
else:
@@ -174,13 +176,12 @@
self.sv = None
self.controllers = []
self.switches = []
-
- def close_log_handles(self) :
- self.tearDown()
- vars(main)[self.name+'log'].removeHandler(self.log_handler)
- #if self.logfile_handler:
+
+ def close_log_handles( self ):
+ self.tearDown()
+ vars( main )[ self.name + 'log' ].removeHandler( self.log_handler )
+ # if self.logfile_handler:
# self.logfile_handler.close()
-
+
return main.TRUE
-
diff --git a/TestON/drivers/common/apidriver.py b/TestON/drivers/common/apidriver.py
index 254ab1b..7de283c 100644
--- a/TestON/drivers/common/apidriver.py
+++ b/TestON/drivers/common/apidriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
-Created on 22-Nov-2012
+"""
+Created on 22-Nov-2012
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,29 +16,37 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
-
-import struct, fcntl, os, sys, signal
-import sys, re
-sys.path.append("../")
+"""
+import struct
+import fcntl
+import os
+import sys
+import signal
+import sys
+import re
+sys.path.append( "../" )
from drivers.component import Component
-class API(Component):
- '''
+
+
+class API( Component ):
+
+ """
This will define common functions for CLI included.
- '''
- def __init__(self):
- super(Component, self).__init__()
-
- def connect(self):
- '''
+ """
+ def __init__( self ):
+ super( Component, self ).__init__()
+
+ def connect( self ):
+ """
Connection will establish to the remote host using ssh.
It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
- super(API, self).connect()
-
- return main.TRUE
+ and will return the handle.
+ """
+ super( API, self ).connect()
+
+ return main.TRUE
+
diff --git a/TestON/drivers/common/cli/dpclidriver.py b/TestON/drivers/common/cli/dpclidriver.py
index 1e7015c..057a3f1 100644
--- a/TestON/drivers/common/cli/dpclidriver.py
+++ b/TestON/drivers/common/cli/dpclidriver.py
@@ -1,147 +1,190 @@
-'''
-Driver for blank dataplane VMs. Created for SDNIP test.
-'''
-
+"""
+Driver for blank dataplane VMs. Created for SDNIP test.
+"""
import time
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
+import sys
+import signal
import sys
import re
import json
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class DPCliDriver(CLI):
- def __init__(self):
- super(CLI, self).__init__()
+class DPCliDriver( CLI ):
- def connect(self,**connectargs):
+ def __init__( self ):
+ super( CLI, self ).__init__()
+
+ def connect( self, **connectargs ):
for key in connectargs:
- vars(self)[key] = connectargs[key]
+ vars( self )[ key ] = connectargs[ key ]
-
- self.name = self.options['name']
- self.handle = super(DPCliDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
+ self.name = self.options[ 'name' ]
+ self.handle = super( DPCliDriver, self ).connect( user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd )
if self.handle:
return self.handle
- else :
- main.log.info("NO HANDLE")
+ else:
+ main.log.info( "NO HANDLE" )
return main.FALSE
- def create_interfaces(self, net, number, start):
- '''
+ def create_interfaces( self, net, number, start ):
+ """
Creates a number,specified by 'number,' of subinterfaces on eth0. Ip addresses start at 'net'.'start'.1.1 with a 24 bit netmask. Addresses increment sequentially in the third quad,
therefore all interfaces are in different subnets on the same machine. When the third quad reaches 255, it is reset to 1 and the second quad is incremented.
Every single ip address is placed in a file in /tmp titled 'ip_table{net}.txt'
The file is used by 'pingall_interfaces()' as a fping argument
This method returns true if all interfaces are created without a hitch, and false if a single interface has issues
- '''
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
- self.handle.sendline("")
- self.handle.expect("\$")
+ self.handle.sendline( "rm /tmp/local_ip.txt" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "touch /tmp/local_ip.txt" )
+ self.handle.expect( "\$" )
- self.handle.sendline("rm /tmp/local_ip.txt")
- self.handle.expect("\$")
- self.handle.sendline("touch /tmp/local_ip.txt")
- self.handle.expect("\$")
-
- main.log.info("Creating interfaces")
+ main.log.info( "Creating interfaces" )
k = 0
intf = 0
while number != 0:
- k= k + 1
+ k = k + 1
if k == 256:
k = 1
start = start + 1
number = number - 1
intf = intf + 1
- ip = net+"."+str(start)+"."+str(k)+".1"
- self.handle.sendline("sudo ifconfig eth0:"+str(intf)+" "+ip+" netmask 255.255.255.0")
+ ip = net + "." + str( start ) + "." + str( k ) + ".1"
+ self.handle.sendline(
+ "sudo ifconfig eth0:" + str(
+ intf ) + " " + ip + " netmask 255.255.255.0" )
- i = self.handle.expect(["\$","password",pexpect.TIMEOUT,pexpect.EOF], timeout = 120)
- if i == 0:
- self.handle.sendline("echo "+str(ip)+" >> /tmp/local_ip.txt")
- self.handle.expect("\$")
- elif i == 1:
- main.log.info("Sending sudo password")
- self.handle.sendline(self.pwd)
- self.handle.expect("\$")
- else:
- main.log.error("INTERFACES NOT CREATED")
- return main.FALSE
+ i = self.handle.expect( [
+ "\$",
+ "password",
+ pexpect.TIMEOUT,
+ pexpect.EOF ],
+ timeout=120 )
+ if i == 0:
+ self.handle.sendline(
+ "echo " + str( ip ) + " >> /tmp/local_ip.txt" )
+ self.handle.expect( "\$" )
+ elif i == 1:
+ main.log.info( "Sending sudo password" )
+ self.handle.sendline( self.pwd )
+ self.handle.expect( "\$" )
+ else:
+ main.log.error( "INTERFACES NOT CREATED" )
+ return main.FALSE
- def pingall_interfaces(self, netsrc, netstrt, netdst, destlogin, destip):
- '''
- Copies the /tmp/ip_table{net}.txt file from the machine you wish to ping, then runs fping with a source address of {netsrc}.{netstrt}.1.1 on the copied file.
+ def pingall_interfaces( self, netsrc, netstrt, netdst, destlogin, destip ):
+ """
+ Copies the /tmp/ip_table{ net }.txt file from the machine you wish to ping, then runs fping with a source address of { netsrc }.{ netstrt }.1.1 on the copied file.
Check every single response for reachable or unreachable. If all are reachable, function returns true. If a SINGLE host is unreachable, then the function stops and returns false
If fping is not installed, this function will install fping then run the same command
- '''
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
- self.handle.sendline("")
- self.handle.expect("\$")
-
- self.handle.sendline("scp "+str(destlogin)+"@"+str(destip)+":/tmp/local_ip.txt /tmp/ip_table"+str(net)+".txt")
- i = self.handle.expect(["100%","password",pexpect.TIMEOUT], timeout = 30)
+ self.handle.sendline( "scp " + str( destlogin ) + "@" +
+ str( destip ) + ":/tmp/local_ip.txt /tmp/ip_table" +
+ str( net ) + ".txt" )
+
+ i = self.handle.expect( [
+ "100%",
+ "password",
+ pexpect.TIMEOUT ],
+ timeout=30 )
+
if i == 0:
- main.log.info("Copied ping file successfully")
+ main.log.info( "Copied ping file successfully" )
elif i == 1:
- self.handle.sendline(self.pwd)
- self.handle.expect("100%")
- main.log.info("Copied ping file successfully")
+ self.handle.sendline( self.pwd )
+ self.handle.expect( "100%" )
+ main.log.info( "Copied ping file successfully" )
elif i == 2:
- main.log.error("COULD NOT COPY PING FILE FROM "+str(destip))
+ main.log.error( "COULD NOT COPY PING FILE FROM " + str( destip ) )
result = main.FALSE
return result
-
- self.handle.sendline("")
- self.handle.expect("\$")
- main.log.info("Pinging interfaces on the "+str(netdst)+" network from "+str(netsrc)+"."+str(netstrt)+".1.1")
- self.handle.sendline("sudo fping -S "+str(netsrc)+"."+str(netstrt)+".1.1 -f /tmp/ip_table"+str(netdst)+".txt")
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+
+ main.log.info( "Pinging interfaces on the " + str( netdst ) +
+ " network from " + str( netsrc ) + "." +
+ str( netstrt ) + ".1.1" )
+ self.handle.sendline( "sudo fping -S " + str( netsrc ) + "." +
+ str( netstrt ) + ".1.1 -f /tmp/ip_table" +
+ str( netdst ) + ".txt" )
while 1:
- i = self.handle.expect(["reachable","unreachable","\$","password",pexpect.TIMEOUT,"not installed"], timeout=45)
+ i = self.handle.expect( [
+ "reachable",
+ "unreachable",
+ "\$",
+ "password",
+ pexpect.TIMEOUT,
+ "not installed" ],
+ timeout=45 )
if i == 0:
result = main.TRUE
elif i == 1:
- main.log.error("An interface was unreachable")
+ main.log.error( "An interface was unreachable" )
result = main.FALSE
return result
elif i == 2:
- main.log.info("All interfaces reachable")
+ main.log.info( "All interfaces reachable" )
return result
elif i == 3:
- self.handle.sendline(self.pwd)
+ self.handle.sendline( self.pwd )
elif i == 4:
- main.log.error("Unable to fping")
+ main.log.error( "Unable to fping" )
result = main.FALSE
return result
elif i == 5:
- main.log.info("fping not installed, installing fping")
- self.handle.sendline("sudo apt-get install fping")
- i = self.handle.expect(["password","\$",pexpect.TIMEOUT], timeout = 60)
+ main.log.info( "fping not installed, installing fping" )
+ self.handle.sendline( "sudo apt-get install fping" )
+ i = self.handle.expect(
+ [ "password",
+ "\$",
+ pexpect.TIMEOUT ],
+ timeout=60 )
if i == 0:
- self.handle.sendline(self.pwd)
- self.handle.expect("\$", timeout = 30)
- main.log.info("fping installed, now pinging interfaces")
- self.handle.sendline("sudo fping -S "+str(netsrc)+"."+str(netstrt)+".1.1 -f /tmp/ip_table"+str(netdst)+".txt")
+ self.handle.sendline( self.pwd )
+ self.handle.expect( "\$", timeout=30 )
+ main.log.info( "fping installed, now pinging interfaces" )
+ self.handle.sendline(
+ "sudo fping -S " + str(
+ netsrc ) + "." + str(
+ netstrt ) + ".1.1 -f /tmp/ip_table" + str(
+ netdst ) + ".txt" )
elif i == 1:
- main.log.info("fping installed, now pinging interfaces")
- self.handle.sendline("sudo fping -S "+str(netsrc)+"."+str(netstrt)+".1.1 -f /tmp/ip_table"+str(netdst)+".txt")
+ main.log.info( "fping installed, now pinging interfaces" )
+ self.handle.sendline(
+ "sudo fping -S " + str(
+ netsrc ) + "." + str(
+ netstrt ) + ".1.1 -f /tmp/ip_table" + str(
+ netdst ) + ".txt" )
elif i == 2:
- main.log.error("Could not install fping")
+ main.log.error( "Could not install fping" )
result = main.FALSE
return result
- def disconnect(self):
+ def disconnect( self ):
response = ''
try:
- self.handle.sendline("exit")
- self.handle.expect("closed")
+ self.handle.sendline( "exit" )
+ self.handle.expect( "closed" )
except:
- main.log.error("Connection failed to the host")
+ main.log.error( "Connection failed to the host" )
response = main.FALSE
return response
diff --git a/TestON/drivers/common/cli/emulator/flowvisordriver.py b/TestON/drivers/common/cli/emulator/flowvisordriver.py
index 66946bd..d0e6ea5 100644
--- a/TestON/drivers/common/cli/emulator/flowvisordriver.py
+++ b/TestON/drivers/common/cli/emulator/flowvisordriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
+"""
Created on 26-Mar-2013
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,12 +16,11 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
FlowVisorDriver is the basic driver which will handle the Mininet functions
-'''
-
+"""
import pexpect
import struct
import fcntl
@@ -30,150 +29,197 @@
import re
import sys
import core.teston
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.cli.emulatordriver import Emulator
from drivers.common.clidriver import CLI
-class FlowVisorDriver(Emulator):
- '''
- FlowVisorDriver is the basic driver which will handle the Mininet functions
- '''
- def __init__(self):
- super(Emulator, self).__init__()
- self.handle = self
- self.wrapped = sys.modules[__name__]
- def connect(self, **connectargs):
- #,user_name, ip_address, pwd,options):
- # Here the main is the TestON instance after creating all the log handles.
+class FlowVisorDriver( Emulator ):
+
+ """
+ FlowVisorDriver is the basic driver which will handle the Mininet functions
+ """
+ def __init__( self ):
+ super( Emulator, self ).__init__()
+ self.handle = self
+ self.wrapped = sys.modules[ __name__ ]
+
+ def connect( self, **connectargs ):
+ #,user_name, ip_address, pwd,options ):
+ # Here the main is the TestON instance after creating all the log
+ # handles.
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- self.handle = super(FlowVisorDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = None, pwd = self.pwd)
-
+ vars( self )[ key ] = connectargs[ key ]
+
+ self.name = self.options[ 'name' ]
+ self.handle = super(
+ FlowVisorDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=None,
+ pwd=self.pwd )
+
self.ssh_handle = self.handle
-
- # Copying the readme file to process the
- if self.handle :
- self.execute(cmd='\r',prompt='\$',timeout=10)
- self.options['path'] = '/home/openflow/flowvisor/scripts/'
+
+ # Copying the readme file to process the
+ if self.handle:
+ self.execute( cmd='\r', prompt='\$', timeout=10 )
+ self.options[ 'path' ] = '/home/openflow/flowvisor/scripts/'
#self.handle.logfile = sys.stdout
- self.execute(cmd='cd '+self.options['path'],prompt='\$',timeout=10)
- main.log.info("Starting FlowVisor ")
-
- response = self.execute(cmd='./flowvisor.sh &',prompt='---\sSetting\slogging\slevel\sto\sNOTE',timeout=10)
-
+ self.execute(
+ cmd='cd ' +
+ self.options[ 'path' ],
+ prompt='\$',
+ timeout=10 )
+ main.log.info( "Starting FlowVisor " )
+
+ response = self.execute(
+ cmd='./flowvisor.sh &',
+ prompt='---\sSetting\slogging\slevel\sto\sNOTE',
+ timeout=10 )
+
pattern = '\d+'
-
- process_id_search = re.search("\[\d+\]\s+(\d+)", str(response))
+
+ process_id_search = re.search( "\[\d+\]\s+(\d+)", str( response ) )
self.fvprocess_id = "None"
if process_id_search:
- self.fvprocess_id = process_id_search.group(1)
-
- utilities.assert_matches(expect=pattern,actual=response,onpass="FlowVisor Started Successfully : Proceess Id :"+self.fvprocess_id,onfail="Failed to start FlowVisor")
- main.log.info(response)
+ self.fvprocess_id = process_id_search.group( 1 )
+
+ utilities.assert_matches(
+ expect=pattern,
+ actual=response,
+ onpass="FlowVisor Started Successfully : Proceess Id :" +
+ self.fvprocess_id,
+ onfail="Failed to start FlowVisor" )
+ main.log.info( response )
#import time
- #time.sleep(10)
- #response = self.execute(cmd='./start_visualizer.sh & \r',prompt='\$',timeout=10)
-
+ # time.sleep( 10 )
+ #response = self.execute( cmd='./start_visualizer.sh & \r',prompt='\$',timeout=10 )
+
return main.TRUE
- else :
- main.log.error("Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error("Failed to connect to the FlowVisor")
+ else:
+ main.log.error(
+ "Connection failed to the host " +
+ self.user_name +
+ "@" +
+ self.ip_address )
+ main.log.error( "Failed to connect to the FlowVisor" )
return main.FALSE
- def removeFlowSpace(self,id):
+
+ def removeFlowSpace( self, id ):
if id == "all":
flow_space = self.listFlowSpace()
- flow_ids = re.findall("\,id=\[(\d+)\]", flow_space)
- for id in flow_ids :
- self.removeFlowSpace(id)
- else :
- self.execute(cmd="clear",prompt="\$",timeout=10)
- self.execute(cmd="./fvctl.sh removeFlowSpace "+id,prompt="passwd:",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- main.log.info("Removed flowSpace which is having id :"+id)
-
+ flow_ids = re.findall( "\,id=\[(\d+)\]", flow_space )
+ for id in flow_ids:
+ self.removeFlowSpace( id )
+ else:
+ self.execute( cmd="clear", prompt="\$", timeout=10 )
+ self.execute(
+ cmd="./fvctl.sh removeFlowSpace " +
+ id,
+ prompt="passwd:",
+ timeout=10 )
+ self.execute( cmd="\n", prompt="\$", timeout=10 )
+ main.log.info( "Removed flowSpace which is having id :" + id )
+
return main.TRUE
-
- def addFlowSpace(self,**flowspace_args):
+
+ def addFlowSpace( self, **flowspace_args ):
temp_string = None
for key in flowspace_args:
- if temp_string :
- temp_string = temp_string +','+ key+'='+flowspace_args[key]
- else :
+ if temp_string:
+ temp_string = temp_string + ',' + \
+ key + '=' + flowspace_args[ key ]
+ else:
temp_string = ''
- temp_string = temp_string + key+'='+flowspace_args[key]
-
- src_search = re.search('dl_src', temp_string)
- if src_search :
- flowspace = "any 100 dl_type=0x806,nw_proto=6,"+temp_string +" Slice:SSH=4"
- else :
- flowspace = "any 100 dl_type=0x800,nw_proto=6,"+temp_string +" Slice:SSH=4"
-
- '''
+ temp_string = temp_string + key + '=' + flowspace_args[ key ]
+
+ src_search = re.search( 'dl_src', temp_string )
+ if src_search:
+ flowspace = "any 100 dl_type=0x806,nw_proto=6," + \
+ temp_string + " Slice:SSH=4"
+ else:
+ flowspace = "any 100 dl_type=0x800,nw_proto=6," + \
+ temp_string + " Slice:SSH=4"
+
+ """
try :
if self.dl_src and self.nw_dst:
flowspace = "any 100 dl_type=0x806,dl_src="+self.dl_src+",nw_dst="+self.nw_dst+" Slice:"+self.Slice+"=4"
except :
try :
if self.nw_src and self.tp_dst:
- flowspace = "any 100 dl_type=0x800,nw_proto=6,nw_src="+self.nw_src+",tp_dst="+self.tp_dst+" Slice:"+self.Slice+"=4"
+ flowspace = "any 100 dl_type=0x800,nw_proto=6,nw_src="+self.nw_src+",tp_dst="+self.tp_dst+" Slice:"+self.Slice+"=4"
except :
try :
if self.nw_src and self.tp_src:
flowspace = "any 100 dl_type=0x800,nw_proto=6,nw_src="+self.nw_src+",tp_src="+self.tp_dst+" Slice:"+self.Slice+"=4"
except :
- main.log.error("Please specify flowspace properly")
- '''
-
- #self.execute(cmd="clear",prompt="\$",timeout=10)
- self.execute(cmd="./fvctl.sh addFlowSpace "+flowspace,prompt="passwd:",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- sucess_match = re.search("success\:\s+(\d+)", main.last_response)
- if sucess_match :
- main.log.info("Added flow Space and id is "+sucess_match.group(1))
+ main.log.error( "Please specify flowspace properly" )
+ """
+ # self.execute( cmd="clear",prompt="\$",timeout=10 )
+ self.execute(
+ cmd="./fvctl.sh addFlowSpace " +
+ flowspace,
+ prompt="passwd:",
+ timeout=10 )
+ self.execute( cmd="\n", prompt="\$", timeout=10 )
+ sucess_match = re.search( "success\:\s+(\d+)", main.last_response )
+ if sucess_match:
+ main.log.info(
+ "Added flow Space and id is " +
+ sucess_match.group( 1 ) )
return main.TRUE
- else :
+ else:
return main.FALSE
-
-
-
- def listFlowSpace(self):
- self.execute(cmd="clear",prompt="\$",timeout=10)
- self.execute(cmd="./fvctl.sh listFlowSpace ",prompt="passwd:",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
+
+ def listFlowSpace( self ):
+ self.execute( cmd="clear", prompt="\$", timeout=10 )
+ self.execute(
+ cmd="./fvctl.sh listFlowSpace ",
+ prompt="passwd:",
+ timeout=10 )
+ self.execute( cmd="\n", prompt="\$", timeout=10 )
flow_space = main.last_response
- flow_space = self.remove_contol_chars( flow_space)
- flow_space = re.sub("rule\s(\d+)\:", "\nrule "+r'\1'+":",flow_space)
- main.log.info(flow_space)
-
+ flow_space = self.remove_contol_chars( flow_space )
+ flow_space = re.sub(
+ "rule\s(\d+)\:",
+ "\nrule " +
+ r'\1' +
+ ":",
+ flow_space )
+ main.log.info( flow_space )
+
return flow_space
-
- def listDevices(self):
- #self.execute(cmd="clear",prompt="\$",timeout=10)
- #self.execute(cmd="./fvctl.sh listDevices ",prompt="passwd:",timeout=10)
- #self.execute(cmd="\n",prompt="\$",timeout=10)
+
+ def listDevices( self ):
+ # self.execute( cmd="clear",prompt="\$",timeout=10 )
+ #self.execute( cmd="./fvctl.sh listDevices ",prompt="passwd:",timeout=10 )
+ # self.execute( cmd="\n",prompt="\$",timeout=10 )
devices_list = ''
- last_response = re.findall("(Device\s\d+\:\s((\d|[a-z])(\d|[a-z])\:)+(\d|[a-z])(\d|[a-z]))", main.last_response)
-
- for resp in last_response :
- devices_match = re.search("(Device\s\d+\:\s((\d|[a-z])(\d|[a-z])\:)+(\d|[a-z])(\d|[a-z]))", str(resp))
+ last_response = re.findall(
+ "(Device\s\d+\:\s((\d|[a-z])(\d|[a-z])\:)+(\d|[a-z])(\d|[a-z]))",
+ main.last_response )
+
+ for resp in last_response:
+ devices_match = re.search(
+ "(Device\s\d+\:\s((\d|[a-z])(\d|[a-z])\:)+(\d|[a-z])(\d|[a-z]))",
+ str( resp ) )
if devices_match:
- devices_list = devices_list+devices_match.group(0)+"\n"
+ devices_list = devices_list + devices_match.group( 0 ) + "\n"
devices_list = "Device 0: 00:00:00:00:00:00:00:02 \n Device 1: 00:00:00:00:00:00:00:03"
- main.log.info("List of Devices \n"+devices_list)
-
+ main.log.info( "List of Devices \n" + devices_list )
+
return main.TRUE
-
-
- def disconnect(self):
-
+
+ def disconnect( self ):
+
response = ''
- main.log.info("Stopping the FlowVisor")
+ main.log.info( "Stopping the FlowVisor" )
if self.handle:
- self.handle.sendline("kill -9 "+str(self.fvprocess_id))
- else :
- main.log.error("Connection failed to the host")
+ self.handle.sendline( "kill -9 " + str( self.fvprocess_id ) )
+ else:
+ main.log.error( "Connection failed to the host" )
response = main.FALSE
- return response
+ return response
diff --git a/TestON/drivers/common/cli/emulator/lincoedriver.py b/TestON/drivers/common/cli/emulator/lincoedriver.py
index 2cb7c98..944eded 100644
--- a/TestON/drivers/common/cli/emulator/lincoedriver.py
+++ b/TestON/drivers/common/cli/emulator/lincoedriver.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-'''
+"""
This driver handles the optical switch emulator linc-oe.
Please follow the coding style demonstrated by existing
@@ -13,8 +13,7 @@
shreya@onlab.us
OCT 20 2014
-'''
-
+"""
import traceback
import pexpect
import struct
@@ -25,117 +24,122 @@
import sys
import core.teston
import time
-sys.path.append("../")
+sys.path.append( "../" )
from math import pow
from drivers.common.cli.emulatordriver import Emulator
from drivers.common.clidriver import CLI
-class LincOEDriver(Emulator):
- '''
- LincOEDriver class will handle all emulator functions
- '''
- def __init__(self):
- super(Emulator, self).__init__()
+
+class LincOEDriver( Emulator ):
+
+ """
+ LincOEDriver class will handle all emulator functions
+ """
+ def __init__( self ):
+ super( Emulator, self ).__init__()
self.handle = self
- self.wrapped = sys.modules[__name__]
+ self.wrapped = sys.modules[ __name__ ]
self.flag = 0
- def connect(self, **connectargs):
- '''
+ def connect( self, **connectargs ):
+ """
Create ssh handle for Linc-OE cli
- '''
+ """
import time
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
+ vars( self )[ key ] = connectargs[ key ]
+
+ self.name = self.options[ 'name' ]
self.handle = \
- super(LincOEDriver, self).connect(\
- user_name = self.user_name,
- ip_address = self.ip_address,
- port = None,
- pwd = self.pwd)
-
+ super( LincOEDriver, self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=None,
+ pwd=self.pwd )
+
self.ssh_handle = self.handle
-
- if self.handle :
- main.log.info("Handle successfully created")
+
+ if self.handle:
+ main.log.info( "Handle successfully created" )
self.home = "~/linc-oe"
-
- self.handle.sendline("cd "+self.home)
- self.handle.expect("oe$")
-
- #self.handle.sendline("pgrep -g linc")
- #self.handle.expect("\$")
- print "handle = ", self.handle.before
-
- return main.TRUE
- '''
- main.log.info("Building Linc-OE")
- self.handle.sendline("make rel")
- i = self.handle.expect(["ERROR","linc-oe\$"],timeout=60)
+
+ self.handle.sendline( "cd " + self.home )
+ self.handle.expect( "oe$" )
+
+ #self.handle.sendline( "pgrep -g linc" )
+ # self.handle.expect( "\$" )
+ print "handle = ", self.handle.before
+
+ return main.TRUE
+ """
+ main.log.info( "Building Linc-OE" )
+ self.handle.sendline( "make rel" )
+ i = self.handle.expect( [ "ERROR","linc-oe\$" ],timeout=60 )
if i == 0:
- self.handle.sendline("sudo pkill -9 epmd")
- self.handle.expect("\$")
- self.handle.sendline("make rel")
- x = self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- main.log.info("make rel returned: "+ str(x))
- else:
-
- main.log.info(self.name+": Starting Linc-OE CLI.. This may take a while")
- time.sleep(30)
- self.handle.sendline("sudo ./rel/linc/bin/linc console")
- j = self.handle.expect(["linc@",pexpect.EOF,pexpect.TIMEOUT])
+ self.handle.sendline( "sudo pkill -9 epmd" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "make rel" )
+ x = self.handle.expect( [ "\$",pexpect.EOF,pexpect.TIMEOUT ] )
+ main.log.info( "make rel returned: "+ str( x ) )
+ else:
+
+ main.log.info( self.name+": Starting Linc-OE CLI.. This may take a while" )
+ time.sleep( 30 )
+ self.handle.sendline( "sudo ./rel/linc/bin/linc console" )
+ j = self.handle.expect( [ "linc@",pexpect.EOF,pexpect.TIMEOUT ] )
if j == 0:
- main.log.info("Linc-OE CLI started")
+ main.log.info( "Linc-OE CLI started" )
return main.TRUE
- '''
+ """
else:
- main.log.error(self.name+
- ": Connection failed to the host "+
- self.user_name+"@"+self.ip_address)
- main.log.error(self.name+
- ": Failed to connect to Linc-OE")
+ main.log.error( self.name +
+ ": Connection failed to the host " +
+ self.user_name + "@" + self.ip_address )
+ main.log.error( self.name +
+ ": Failed to connect to Linc-OE" )
return main.FALSE
-
- def start_console(self):
+ def start_console( self ):
import time
- main.log.info(self.name+": Starting Linc-OE CLI.. This may take a while")
- time.sleep(30)
- self.handle.sendline("sudo ./rel/linc/bin/linc console")
- j = self.handle.expect(["linc@",pexpect.EOF,pexpect.TIMEOUT])
+ main.log.info(
+ self.name +
+ ": Starting Linc-OE CLI.. This may take a while" )
+ time.sleep( 30 )
+ self.handle.sendline( "sudo ./rel/linc/bin/linc console" )
+ j = self.handle.expect( [ "linc@", pexpect.EOF, pexpect.TIMEOUT ] )
start_result = self.handle.before
if j == 0:
- main.log.info("Linc-OE CLI started")
+ main.log.info( "Linc-OE CLI started" )
return main.TRUE
else:
- main.log.error(self.name+
- ": Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error(self.name+
- ": Failed to connect to Linc-OE")
+ main.log.error(
+ self.name +
+ ": Connection failed to the host " +
+ self.user_name +
+ "@" +
+ self.ip_address )
+ main.log.error( self.name +
+ ": Failed to connect to Linc-OE" )
return main.FALSE
-
-
- def build(self):
- '''
+ def build( self ):
+ """
Build Linc-OE with the specified settings
- '''
+ """
try:
- self.handle.sendline("make rel")
- i = self.handle.expect([
+ self.handle.sendline( "make rel" )
+ i = self.handle.expect( [
"ERROR",
- "\$"])
+ "\$" ] )
if i == 0:
- #If error, try to resolve the most common error
- #(epmd running and cannot compile)
- self.handle.sendline("sudo pkill -9 epmd")
- self.handle.sendline("make rel")
- self.handle.expect("\$")
-
+ # If error, try to resolve the most common error
+ #( epmd running and cannot compile )
+ self.handle.sendline( "sudo pkill -9 epmd" )
+ self.handle.sendline( "make rel" )
+ self.handle.expect( "\$" )
+
handle = self.handle.before
return handle
@@ -143,226 +147,225 @@
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
- def set_interface_up(self, intfs):
- '''
+ def set_interface_up( self, intfs ):
+ """
Specify interface to bring up.
When Linc-OE is started, tap interfaces should
be created. They must be brought up manually
- '''
+ """
try:
- self.handle.sendline("ifconfig "+str(intfs)+" up")
- self.handle.expect("linc@")
-
+ self.handle.sendline( "ifconfig " + str( intfs ) + " up" )
+ self.handle.expect( "linc@" )
+
handle = self.handle.before
return handle
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
- def start_switch(self, sw_id):
- '''
+ def start_switch( self, sw_id ):
+ """
Start a logical switch using switch id
- '''
+ """
try:
- self.handle.sendline("linc:start_switch("+str(sw_id)+").")
- self.handle.expect("linc@")
+ self.handle.sendline( "linc:start_switch(" + str( sw_id ) + ")." )
+ self.handle.expect( "linc@" )
handle = self.handle.before
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
- def stop_switch(self, sw_id):
- '''
+ def stop_switch( self, sw_id ):
+ """
Stop a logical switch using switch id
- '''
+ """
try:
- self.handle.sendline("linc:stop_switch("+str(sw_id)+").")
- self.handle.expect("linc@")
+ self.handle.sendline( "linc:stop_switch(" + str( sw_id ) + ")." )
+ self.handle.expect( "linc@" )
handle = self.handle.before
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
-
- def get_datapath_id(self, sw_id):
- '''
+
+ def get_datapath_id( self, sw_id ):
+ """
Get datapath id of a specific switch by switch id
- '''
+ """
try:
- self.handle.sendline("linc_logic:get_datapath_id("+
- str(sw_id)+").")
- self.handle.expect("linc@")
+ self.handle.sendline( "linc_logic:get_datapath_id(" +
+ str( sw_id ) + ")." )
+ self.handle.expect( "linc@" )
handle = self.handle.before
-
+
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
- def list_ports(self, sw_id):
- '''
+ def list_ports( self, sw_id ):
+ """
List all ports of a switch by switch id
- '''
+ """
try:
- self.handle.sendline("linc:ports("+str(sw_id)+").")
- self.handle.expect("linc@")
+ self.handle.sendline( "linc:ports(" + str( sw_id ) + ")." )
+ self.handle.expect( "linc@" )
handle = self.handle.before
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
- def port_up(self, sw_id, pt_id):
- '''
+ def port_up( self, sw_id, pt_id ):
+ """
Bring port up using switch id and port id
- '''
+ """
try:
- self.handle.sendline("linc:port_up("+
- str(sw_id)+", "+str(pt_id)+").")
- self.handle.expect("linc@")
+ self.handle.sendline( "linc:port_up(" +
+ str( sw_id ) + ", " + str( pt_id ) + ")." )
+ self.handle.expect( "linc@" )
handle = self.handle.before
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
-
- def port_down(self, sw_id, pt_id):
- '''
+
+ def port_down( self, sw_id, pt_id ):
+ """
Bring port down using switch id and port id
- '''
+ """
try:
- self.handle.sendline("linc:port_down("+
- str(sw_id)+", "+str(pt_id)+").")
- self.handle.expect("linc@")
+ self.handle.sendline( "linc:port_down(" +
+ str( sw_id ) + ", " + str( pt_id ) + ")." )
+ self.handle.expect( "linc@" )
handle = self.handle.before
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
-
- def stopLincOEConsole(self):
- '''
+
+ def stopLincOEConsole( self ):
+ """
This function is only used for packet optical testing
Send disconnect prompt to Linc-OE CLI
- (CTRL+C) and kill the linc process
- '''
+ ( CTRL+C ) and kill the linc process
+ """
try:
cmd = "pgrep -f linc"
- self.handle.sendline("pgrep -f linc")
- self.handle.expect("linc")
+ self.handle.sendline( "pgrep -f linc" )
+ self.handle.expect( "linc" )
print "stophandle = ", self.handle.before
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
- def disconnect(self):
- '''
+ def disconnect( self ):
+ """
Send disconnect prompt to Linc-OE CLI
- (CTRL+C) and kill the linc process
- '''
+ ( CTRL+C ) and kill the linc process
+ """
try:
- #Send CTRL+C twice to exit CLI
- self.handle.send("\x03")
- self.handle.send("\x03")
- self.handle.expect("\$")
+ # Send CTRL+C twice to exit CLI
+ self.handle.send( "\x03" )
+ self.handle.send( "\x03" )
+ self.handle.expect( "\$" )
handle1 = self.handle.before
cmd = "pgrep -f linc"
- self.handle.sendline(cmd)
- self.handle.expect("\$")
+ self.handle.sendline( cmd )
+ self.handle.expect( "\$" )
handle2 = self.handle.before
- main.log.info("pid's = "+handle2)
+ main.log.info( "pid's = " + handle2 )
cmd = "sudo kill -9 `pgrep -f linc`"
- self.handle.sendline(cmd)
- self.handle.expect("\$")
-
+ self.handle.sendline( cmd )
+ self.handle.expect( "\$" )
+
except pexpect.EOF:
- main.log.error(self.name+ ": EOF exception")
- main.log.error(self.name+ ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" :::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" :::::::")
+ main.log.info( self.name + " :::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " :::::::" )
main.cleanup()
main.exit()
if __name__ != "__main__":
import sys
- sys.modules[__name__] = LincOEDriver()
-
+ sys.modules[ __name__ ] = LincOEDriver()
diff --git a/TestON/drivers/common/cli/emulator/mininetclidriver.py b/TestON/drivers/common/cli/emulator/mininetclidriver.py
index c125fca..bc0fcc5 100644
--- a/TestON/drivers/common/cli/emulator/mininetclidriver.py
+++ b/TestON/drivers/common/cli/emulator/mininetclidriver.py
@@ -88,10 +88,10 @@
main.log.info( self.name + ": building fresh mininet" )
# for reactive/PARP enabled tests
cmdString = "sudo mn " + self.options[ 'arg1' ] +\
- " " + self.options[ 'arg2' ] +\
- " --mac --controller " +\
- self.options[ 'controller' ] + " " +\
- self.options[ 'arg3' ]
+ " " + self.options[ 'arg2' ] +\
+ " --mac --controller " +\
+ self.options[ 'controller' ] + " " +\
+ self.options[ 'arg3' ]
argList = self.options[ 'arg1' ].split( "," )
global topoArgList
@@ -170,7 +170,7 @@
total_num_hosts = num_switches * num_hosts_per_sw
num_links = total_num_hosts + ( num_switches - 1 )
print "num_switches for %s(%d,%d) = %d and links=%d" %\
- ( topoType, depth, fanout, num_switches, num_links )
+ ( topoType, depth, fanout, num_switches, num_links )
topoDict = {}
topoDict = {
"num_switches": int( num_switches ),
@@ -212,7 +212,7 @@
# NOTE: mininet's pingall rounds, so we will check the number of
# passed and number of failed
pattern = "Results\:\s0\%\sdropped\s\(" +\
- "(?P<passed>[\d]+)/(?P=passed)"
+ "(?P<passed>[\d]+)/(?P=passed)"
if re.search( pattern, response ):
main.log.info( self.name + ": All hosts are reachable" )
return main.TRUE
@@ -308,11 +308,11 @@
main.exit()
pattern = "inet\s(addr|Mask):([0-1]{1}[0-9]{1,2}|" +\
- "2[0-4][0-9]|25[0-5]|[0-9]{1,2}).([0-1]{1}" +\
- "[0-9]{1,2}|2[0-4][0-9]|25[0-5]|[0-9]{1,2})." +\
- "([0-1]{1}[0-9]{1,2}|2[0-4][0-9]|25[0-5]|" +\
- "[0-9]{1,2}).([0-1]{1}[0-9]{1,2}|2[0-4]" +\
- "[0-9]|25[0-5]|[0-9]{1,2})"
+ "2[0-4][0-9]|25[0-5]|[0-9]{1,2}).([0-1]{1}" +\
+ "[0-9]{1,2}|2[0-4][0-9]|25[0-5]|[0-9]{1,2})." +\
+ "([0-1]{1}[0-9]{1,2}|2[0-4][0-9]|25[0-5]|" +\
+ "[0-9]{1,2}).([0-1]{1}[0-9]{1,2}|2[0-4]" +\
+ "[0-9]|25[0-5]|[0-9]{1,2})"
# pattern = "inet addr:10.0.0.6"
if re.search( pattern, response ):
main.log.info( self.name + ": Host Ip configured properly" )
@@ -573,7 +573,7 @@
return information dict about interfaces connected to the node"""
if self.handle:
cmd = 'py "\\n".join(["name=%s,mac=%s,ip=%s,enabled=%s"' +\
- ' % (i.name, i.MAC(), i.IP(), i.isUp())'
+ ' % (i.name, i.MAC(), i.IP(), i.isUp())'
cmd += ' for i in %s.intfs.values()])' % node
try:
response = self.execute(
@@ -836,7 +836,7 @@
sw = args[ "SW" ] if args[ "SW" ] is not None else ""
ptcpA = int( args[ "PORT1" ] ) + \
- int( sw ) if args[ "PORT1" ] is not None else ""
+ int( sw ) if args[ "PORT1" ] is not None else ""
ptcpB = "ptcp:" + str( ptcpA ) if ptcpA != "" else ""
command = "sh ovs-vsctl set-controller s" + \
@@ -856,7 +856,7 @@
"PORT" +
str( i ) ] is not None else ""
tcp = "tcp:" + str( ip ) + ":" + str( port ) + \
- " " if ip != "" else ""
+ " " if ip != "" else ""
command = command + tcp
try:
self.execute( cmd=command, prompt="mininet>", timeout=5 )
@@ -868,7 +868,7 @@
except:
main.log.info( self.name + ":" * 50 )
main.log.error( traceback.print_exc() )
- main.log.info(":" * 50 )
+ main.log.info( ":" * 50 )
main.cleanup()
main.exit()
@@ -1229,7 +1229,7 @@
except:
main.log.info( self.name + ":" * 50 )
main.log.error( traceback.print_exc() )
- main.log.info(":" * 50 )
+ main.log.info( ":" * 50 )
main.cleanup()
main.exit()
@@ -1248,7 +1248,7 @@
except:
main.log.info( self.name + ":" * 50 )
main.log.error( traceback.print_exc() )
- main.log.info(":" * 50 )
+ main.log.info( ":" * 50 )
main.cleanup()
main.exit()
@@ -1268,7 +1268,7 @@
for port in switch.ports.values():
ports.append( { 'of_port': port.port_no,
'mac': str( port.hw_addr ).replace( '\'',
- ''),
+ '' ),
'name': port.name } )
output[ 'switches' ].append( {
"name": switch.name,
@@ -1322,7 +1322,7 @@
main.log.report( str( list1 ) )
main.log.report( "Switches in ONOS but not in MN:" )
list2 = [ switch for switch in onosDPIDs if switch not in mnDPIDs ]
- main.log.report(str( list2 ) )
+ main.log.report( str( list2 ) )
else: # list of dpid's match in onos and mn
switch_results = main.TRUE
return switch_results
@@ -1454,7 +1454,7 @@
# print port.hw_addr.toStr( separator='' )
ports.append( { 'of_port': port.port_no,
'mac': str( port.hw_addr ).replace( '\'',
- ''),
+ '' ),
'name': port.name } )
output[ 'switches' ].append( {
"name": switch.name,
@@ -1546,7 +1546,7 @@
elif ( str( onos_node1 ) == str( node2 ) and
str( onos_node2 ) == str( node1 ) ):
if ( int( onos_port1 ) == int( port2 )
- and int( onos_port2 ) == int( port1 ) ):
+ and int( onos_port2 ) == int( port1 ) ):
second_dir = main.TRUE
else:
main.log.warn(
diff --git a/TestON/drivers/common/cli/emulator/poxclidriver.py b/TestON/drivers/common/cli/emulator/poxclidriver.py
index a562274..291e916 100644
--- a/TestON/drivers/common/cli/emulator/poxclidriver.py
+++ b/TestON/drivers/common/cli/emulator/poxclidriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
+"""
Created on 26-Oct-2012
-
-@author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
+
+author:: Raghav Kashyap( raghavkashyap@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,112 +16,141 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
pox driver provides the basic functions of POX controller
-'''
+"""
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
+import sys
+import signal
import sys
from drivers.common.cli.emulatordriver import Emulator
-class PoxCliDriver(Emulator):
- '''
- PoxCliDriver driver provides the basic functions of POX controller
- '''
- def __init__(self):
- super(Emulator, self).__init__()
- self.handle = self
- self.wrapped = sys.modules[__name__]
- def connect(self, **connectargs):
- #,user_name, ip_address, pwd,options):
- '''
- this subroutine is to launch pox controller . It must have arguments as :
+class PoxCliDriver( Emulator ):
+
+ """
+ PoxCliDriver driver provides the basic functions of POX controller
+ """
+ def __init__( self ):
+ super( Emulator, self ).__init__()
+ self.handle = self
+ self.wrapped = sys.modules[ __name__ ]
+
+ def connect( self, **connectargs ):
+ #,user_name, ip_address, pwd,options ):
+ """
+ this subroutine is to launch pox controller . It must have arguments as :
user_name = host name ,
ip_address = ip address of the host ,
pwd = password of host ,
options = it is a topology hash which will consists the component's details for the test run
*** host is here a virtual mahine or system where pox framework hierarchy exists
- '''
-
+ """
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
-
+ vars( self )[ key ] = connectargs[ key ]
+
+ self.name = self.options[ 'name' ]
+
poxLibPath = 'default'
- copy = super(PoxCliDriver, self).secureCopy(self.user_name, self.ip_address,'/home/openflow/pox/pox/core.py', self.pwd,path+'/lib/pox/')
- self.handle = super(PoxCliDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = None, pwd = self.pwd)
-
+ copy = super(
+ PoxCliDriver,
+ self ).secureCopy(
+ self.user_name,
+ self.ip_address,
+ '/home/openflow/pox/pox/core.py',
+ self.pwd,
+ path +
+ '/lib/pox/' )
+ self.handle = super(
+ PoxCliDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=None,
+ pwd=self.pwd )
+
if self.handle:
- self.handle.expect("openflow")
- command = self.getcmd(self.options)
- #print command
- main.log.info("Entering into POX hierarchy")
- if self.options['pox_lib_location'] != 'default':
- self.execute(cmd="cd "+self.options['pox_lib_location'],prompt="/pox\$",timeout=120)
- else:
- self.execute(cmd="cd ~/TestON/lib/pox/",prompt="/pox\$",timeout=120)
- ### launching pox with components
- main.log.info("launching POX controller with given components")
- self.execute(cmd=command,prompt="DEBUG:",timeout=120)
+ self.handle.expect( "openflow" )
+ command = self.getcmd( self.options )
+ # print command
+ main.log.info( "Entering into POX hierarchy" )
+ if self.options[ 'pox_lib_location' ] != 'default':
+ self.execute(
+ cmd="cd " +
+ self.options[ 'pox_lib_location' ],
+ prompt="/pox\$",
+ timeout=120 )
+ else:
+ self.execute(
+ cmd="cd ~/TestON/lib/pox/",
+ prompt="/pox\$",
+ timeout=120 )
+ # launching pox with components
+ main.log.info( "launching POX controller with given components" )
+ self.execute( cmd=command, prompt="DEBUG:", timeout=120 )
return main.TRUE
- else :
- main.log.error("Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error("Failed to connect to the POX controller")
+ else:
+ main.log.error(
+ "Connection failed to the host " +
+ self.user_name +
+ "@" +
+ self.ip_address )
+ main.log.error( "Failed to connect to the POX controller" )
return main.FALSE
-
-
- def disconnect(self,handle):
+
+ def disconnect( self, handle ):
if self.handle:
- self.execute(cmd="exit()",prompt="/pox\$",timeout=120)
- else :
- main.log.error("Connection failed to the host")
+ self.execute( cmd="exit()", prompt="/pox\$", timeout=120 )
+ else:
+ main.log.error( "Connection failed to the host" )
-
- def get_version(self):
- file_input = path+'/lib/pox/core.py'
- version = super(PoxCliDriver, self).get_version()
+ def get_version( self ):
+ file_input = path + '/lib/pox/core.py'
+ version = super( PoxCliDriver, self ).get_version()
pattern = '\s*self\.version(.*)'
import re
- for line in open(file_input,'r').readlines():
- result = re.match(pattern, line)
+ for line in open( file_input, 'r' ).readlines():
+ result = re.match( pattern, line )
if result:
- version = result.group(0)
- version = re.sub("\s*self\.version\s*=\s*|\(|\)",'',version)
- version = re.sub(",",'.',version)
- version = "POX "+version
-
-
- return version
-
+ version = result.group( 0 )
+ version = re.sub(
+ "\s*self\.version\s*=\s*|\(|\)",
+ '',
+ version )
+ version = re.sub( ",", '.', version )
+ version = "POX " + version
- def getcmd(self,options):
- command = "./pox.py "
+ return version
+
+ def getcmd( self, options ):
+ command = "./pox.py "
for item in options.keys():
- if isinstance(options[item],dict):
+ if isinstance( options[ item ], dict ):
command = command + item
- for items in options[item].keys():
- if options[item][items] == "None":
+ for items in options[ item ].keys():
+ if options[ item ][ items ] == "None":
command = command + " --" + items + " "
- else :
- command = command + " --" + items + "=" + options[item][items] + " "
+ else:
+ command = command + " --" + items + \
+ "=" + options[ item ][ items ] + " "
else:
if item == 'pox_lib_location':
- poxLibPath = options[item]
+ poxLibPath = options[ item ]
elif item == 'type' or item == 'name':
pass
- else :
+ else:
command = command + item
+ return command
- return command
-
if __name__ != "__main__":
import sys
- sys.modules[__name__] = PoxCliDriver()
+ sys.modules[ __name__ ] = PoxCliDriver()
diff --git a/TestON/drivers/common/cli/emulator/remotemininetdriver.py b/TestON/drivers/common/cli/emulator/remotemininetdriver.py
index 48d3389..a8aedea 100644
--- a/TestON/drivers/common/cli/emulator/remotemininetdriver.py
+++ b/TestON/drivers/common/cli/emulator/remotemininetdriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
+"""
Created on 26-Oct-2012
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -20,449 +20,536 @@
MininetCliDriver is the basic driver which will handle the Mininet functions
-'''
+"""
import traceback
import pexpect
import re
import sys
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.cli.emulatordriver import Emulator
-class RemoteMininetDriver(Emulator):
- '''
+
+class RemoteMininetDriver( Emulator ):
+
+ """
RemoteMininetCliDriver is the basic driver which will handle the Mininet functions
The main different between this and the MininetCliDriver is that this one does not build the mininet.
It assumes that there is already a mininet running on the target.
- '''
- def __init__(self):
- super(Emulator, self).__init__()
+ """
+ def __init__( self ):
+ super( Emulator, self ).__init__()
self.handle = self
- self.wrapped = sys.modules[__name__]
+ self.wrapped = sys.modules[ __name__ ]
self.flag = 0
- def connect(self, **connectargs):
- #,user_name, ip_address, pwd,options):
- # Here the main is the TestON instance after creating all the log handles.
+ def connect( self, **connectargs ):
+ #,user_name, ip_address, pwd,options ):
+ # Here the main is the TestON instance after creating all the log
+ # handles.
for key in connectargs:
- vars(self)[key] = connectargs[key]
+ vars( self )[ key ] = connectargs[ key ]
- self.name = self.options['name']
- self.handle = super(RemoteMininetDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = None, pwd = self.pwd)
+ self.name = self.options[ 'name' ]
+ self.handle = super(
+ RemoteMininetDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=None,
+ pwd=self.pwd )
self.ssh_handle = self.handle
# Copying the readme file to process the
- if self.handle :
+ if self.handle:
return main.TRUE
- else :
- main.log.error("Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error("Failed to connect to the Mininet")
+ else:
+ main.log.error(
+ "Connection failed to the host " +
+ self.user_name +
+ "@" +
+ self.ip_address )
+ main.log.error( "Failed to connect to the Mininet" )
return main.FALSE
-#*********************************************************************************************
-#*********************************************************************************************
+#*************************************************************************
+#*************************************************************************
# checkForLoss will determine if any of the pings had any packets lost during the course of
# the pingLong.
-#*********************************************************************************************
-#*********************************************************************************************
+#*************************************************************************
+#*************************************************************************
- def checkForLoss(self, pingList):
- '''
+ def checkForLoss( self, pingList ):
+ """
Returns main.FALSE for 0% packet loss and
Returns main.ERROR if "found multiple mininet" is found and
Returns main.TRUE else
- '''
- #TODO: maybe we want to return the % loss instead? This way we can set an acceptible loss %.
- #EX: 393 packets transmitted, 380 received, 3% packet loss, time 78519ms
+ """
+ # TODO: maybe we want to return the % loss instead? This way we can set an acceptible loss %.
+ # EX: 393 packets transmitted, 380 received, 3% packet loss, time 78519ms
# we may need to return a float to get around rounding errors
- self.handle.sendline("")
- self.handle.expect("\$")
- #Clear any output waiting in the bg from killing pings
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("cat " + pingList)
- self.handle.expect(pingList)
- self.handle.expect("\$")
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ # Clear any output waiting in the bg from killing pings
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "cat " + pingList )
+ self.handle.expect( pingList )
+ self.handle.expect( "\$" )
outputs = self.handle.before + self.handle.after
- if re.search(" 0% packet loss",outputs):
+ if re.search( " 0% packet loss", outputs ):
return main.FALSE
- elif re.search("found multiple mininet",outputs):
+ elif re.search( "found multiple mininet", outputs ):
return main.ERROR
else:
- main.log.error("Error, unexpected output in the ping file")
+ main.log.error( "Error, unexpected output in the ping file" )
main.log.warn( outputs )
return main.TRUE
-
-
- def pingLong(self,**pingParams):
- '''
+ def pingLong( self, **pingParams ):
+ """
Starts a continuous ping on the mininet host outputing to a file in the /tmp dir.
- '''
- self.handle.sendline("")
- self.handle.expect("\$")
- args = utilities.parse_args(["SRC","TARGET","PINGTIME"],**pingParams)
- precmd = "sudo rm /tmp/ping." + args["SRC"]
- self.execute(cmd=precmd,prompt="(.*)",timeout=10)
- command = "sudo mininet/util/m " + args["SRC"] + " ping "+args ["TARGET"]+" -i .2 -w " + str(args['PINGTIME']) + " -D > /tmp/ping." + args["SRC"] + " &"
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ args = utilities.parse_args(
+ [ "SRC", "TARGET", "PINGTIME" ], **pingParams )
+ precmd = "sudo rm /tmp/ping." + args[ "SRC" ]
+ self.execute( cmd=precmd, prompt="(.*)", timeout=10 )
+ command = "sudo mininet/util/m " + args[ "SRC" ] + " ping " + args[
+ "TARGET" ] + " -i .2 -w " + str( args[ 'PINGTIME' ] ) + " -D > /tmp/ping." + args[ "SRC" ] + " &"
main.log.info( command )
- self.execute(cmd=command,prompt="(.*)",timeout=10)
- self.handle.sendline("")
- self.handle.expect("\$")
+ self.execute( cmd=command, prompt="(.*)", timeout=10 )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
return main.TRUE
- def pingstatus(self,**pingParams):
- '''
+ def pingstatus( self, **pingParams ):
+ """
Tails the respective ping output file and check that there is a moving "64 bytes"
- '''
- self.handle.sendline("")
- self.handle.expect("\$")
- args = utilities.parse_args(["SRC"],**pingParams)
- self.handle.sendline("tail /tmp/ping." + args["SRC"])
- self.handle.expect("tail")
- self.handle.expect("\$")
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ args = utilities.parse_args( [ "SRC" ], **pingParams )
+ self.handle.sendline( "tail /tmp/ping." + args[ "SRC" ] )
+ self.handle.expect( "tail" )
+ self.handle.expect( "\$" )
result = self.handle.before + self.handle.after
- self.handle.sendline("")
- self.handle.expect("\$")
- if re.search('Unreachable', result ):
- main.log.info("Unreachable found in ping logs...")
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ if re.search( 'Unreachable', result ):
+ main.log.info( "Unreachable found in ping logs..." )
return main.FALSE
- elif re.search('64\sbytes', result):
- main.log.info("Pings look good")
+ elif re.search( '64\sbytes', result ):
+ main.log.info( "Pings look good" )
return main.TRUE
else:
- main.log.info("No, or faulty ping data...")
+ main.log.info( "No, or faulty ping data..." )
return main.FALSE
- def pingKill(self, testONUser, testONIP):
- '''
+ def pingKill( self, testONUser, testONIP ):
+ """
Kills all continuous ping processes.
Then copies all the ping files to the TestStation.
- '''
- self.handle.sendline("")
- self.handle.expect("\$")
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
command = "sudo kill -SIGINT `pgrep ping`"
main.log.info( command )
- self.execute(cmd=command,prompt="(.*)",timeout=10)
+ self.execute( cmd=command, prompt="(.*)", timeout=10 )
main.log.info( "Transferring ping files to TestStation" )
- command = "scp /tmp/ping.* "+ str(testONUser) + "@" + str(testONIP) + ":/tmp/"
- self.execute(cmd=command,prompt="100%",timeout=20)
- #Make sure the output is cleared
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("")
- i=self.handle.expect(["password","\$"])
+ command = "scp /tmp/ping.* " + \
+ str( testONUser ) + "@" + str( testONIP ) + ":/tmp/"
+ self.execute( cmd=command, prompt="100%", timeout=20 )
+ # Make sure the output is cleared
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "" )
+ i = self.handle.expect( [ "password", "\$" ] )
if i == 0:
- main.log.error("Error, sudo asking for password")
- main.log.error(self.handle.before)
+ main.log.error( "Error, sudo asking for password" )
+ main.log.error( self.handle.before )
return main.FALSE
else:
return main.TRUE
- def pingLongKill(self):
- self.handle.sendline("")
- self.handle.expect("\$")
+ def pingLongKill( self ):
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
command = "sudo kill -SIGING `pgrep ping`"
- main.log.info(command)
- self.execute(cmd=command,prompt="(.*)",timeout=10)
- self.handle.sendline("")
- self.handle.expect("\$")
+ main.log.info( command )
+ self.execute( cmd=command, prompt="(.*)", timeout=10 )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
return main.TRUE
- def pingHostOptical(self,**pingParams):
- '''
+ def pingHostOptical( self, **pingParams ):
+ """
This function is only for Packey Optical related ping
- Use the next pingHost() function for all normal scenarios)
+ Use the next pingHost() function for all normal scenarios )
Ping from one mininet host to another
Currently the only supported Params: SRC and TARGET
- '''
- args = utilities.parse_args(["SRC","TARGET"],**pingParams)
- #command = args["SRC"] + " ping -" + args["CONTROLLER"] + " " +args ["TARGET"]
- command = args["SRC"] + " ping "+args ["TARGET"]+" -c 1 -i 1 -W 8"
+ """
+ args = utilities.parse_args( [ "SRC", "TARGET" ], **pingParams )
+ #command = args[ "SRC" ] + " ping -" + args[ "CONTROLLER" ] + " " +args [ "TARGET" ]
+ command = args[ "SRC" ] + " ping " + \
+ args[ "TARGET" ] + " -c 1 -i 1 -W 8"
try:
- main.log.warn("Sending: " + command)
- #response = self.execute(cmd=command,prompt="mininet",timeout=10 )
- self.handle.sendline(command)
- i = self.handle.expect([command,pexpect.TIMEOUT])
+ main.log.warn( "Sending: " + command )
+ #response = self.execute( cmd=command,prompt="mininet",timeout=10 )
+ self.handle.sendline( command )
+ i = self.handle.expect( [ command, pexpect.TIMEOUT ] )
if i == 1:
- main.log.error(self.name + ": timeout when waiting for response from mininet")
- main.log.error("response: " + str(self.handle.before))
- i = self.handle.expect(["mininet>",pexpect.TIMEOUT])
+ main.log.error(
+ self.name +
+ ": timeout when waiting for response from mininet" )
+ main.log.error( "response: " + str( self.handle.before ) )
+ i = self.handle.expect( [ "mininet>", pexpect.TIMEOUT ] )
if i == 1:
- main.log.error(self.name + ": timeout when waiting for response from mininet")
- main.log.error("response: " + str(self.handle.before))
+ main.log.error(
+ self.name +
+ ": timeout when waiting for response from mininet" )
+ main.log.error( "response: " + str( self.handle.before ) )
response = self.handle.before
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
- main.log.info(self.name+": Ping Response: "+ response )
- #if utilities.assert_matches(expect=',\s0\%\spacket\sloss',actual=response,onpass="No Packet loss",onfail="Host is not reachable"):
- if re.search(',\s0\%\spacket\sloss',response):
- main.log.info(self.name+": no packets lost, host is reachable")
+ main.log.info( self.name + ": Ping Response: " + response )
+ # if utilities.assert_matches(
+ # expect=',\s0\%\spacket\sloss',actual=response,onpass="No Packet
+ # loss",onfail="Host is not reachable" ):
+ if re.search( ',\s0\%\spacket\sloss', response ):
+ main.log.info( self.name + ": no packets lost, host is reachable" )
main.last_result = main.TRUE
return main.TRUE
- else :
- main.log.error(self.name+": PACKET LOST, HOST IS NOT REACHABLE")
+ else:
+ main.log.error(
+ self.name +
+ ": PACKET LOST, HOST IS NOT REACHABLE" )
main.last_result = main.FALSE
return main.FALSE
- def pingHost(self,**pingParams):
- '''
+ def pingHost( self, **pingParams ):
+ """
Pings between two hosts on remote mininet
- '''
- self.handle.sendline("")
- self.handle.expect("\$")
- args = utilities.parse_args(["SRC","TARGET"],**pingParams)
- #command = "mininet/util/m " + args["SRC"] + " ping "+args ["TARGET"]+" -c 4 -W 1 -i .2"
- command = "mininet/util/m " + args["SRC"] + " ping "+args ["TARGET"]+" -c 4 -W 1 -i .2"
- main.log.info ( command )
- response = self.execute(cmd=command,prompt="rtt",timeout=10 )
- #self.handle.sendline("")
- #self.handle.expect("\$")
- if utilities.assert_matches(expect=',\s0\%\spacket\sloss',actual=response,onpass="No Packet loss",onfail="Host is not reachable"):
- main.log.info("NO PACKET LOSS, HOST IS REACHABLE")
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ args = utilities.parse_args( [ "SRC", "TARGET" ], **pingParams )
+ #command = "mininet/util/m " + args[ "SRC" ] + " ping "+args [ "TARGET" ]+" -c 4 -W 1 -i .2"
+ command = "mininet/util/m " + \
+ args[ "SRC" ] + " ping " + args[ "TARGET" ] + " -c 4 -W 1 -i .2"
+ main.log.info( command )
+ response = self.execute( cmd=command, prompt="rtt", timeout=10 )
+ # self.handle.sendline( "" )
+ # self.handle.expect( "\$" )
+ if utilities.assert_matches(
+ expect=',\s0\%\spacket\sloss',
+ actual=response,
+ onpass="No Packet loss",
+ onfail="Host is not reachable" ):
+ main.log.info( "NO PACKET LOSS, HOST IS REACHABLE" )
main.last_result = main.TRUE
return main.TRUE
- else :
- main.log.error("PACKET LOST, HOST IS NOT REACHABLE")
+ else:
+ main.log.error( "PACKET LOST, HOST IS NOT REACHABLE" )
main.last_result = main.FALSE
return main.FALSE
-
- def checknum(self,num):
- '''
+ def checknum( self, num ):
+ """
Verifies the correct number of switches are running
- '''
- if self.handle :
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline('ifconfig -a | grep "sw.. " | wc -l')
- self.handle.expect("wc")
- self.handle.expect("\$")
+ """
+ if self.handle:
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( 'ifconfig -a | grep "sw.. " | wc -l' )
+ self.handle.expect( "wc" )
+ self.handle.expect( "\$" )
response = self.handle.before
- self.handle.sendline('ps -ef | grep "bash -ms mininet:sw" | grep -v color | wc -l')
- self.handle.expect("color")
- self.handle.expect("\$")
+ self.handle.sendline(
+ 'ps -ef | grep "bash -ms mininet:sw" | grep -v color | wc -l' )
+ self.handle.expect( "color" )
+ self.handle.expect( "\$" )
response2 = self.handle.before
- if re.search(num, response):
- if re.search(num, response2):
+ if re.search( num, response ):
+ if re.search( num, response2 ):
return main.TRUE
else:
return main.FALSE
else:
return main.FALSE
- else :
- main.log.error("Connection failed to the host")
+ else:
+ main.log.error( "Connection failed to the host" )
- def start_tcpdump(self, filename, intf = "eth0", port = "port 6633", user="admin"):
- '''
+ def start_tcpdump(
+ self,
+ filename,
+ intf="eth0",
+ port="port 6633",
+ user="admin" ):
+ """
Runs tpdump on an intferface and saves the file
intf can be specified, or the default eth0 is used
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.sendline("sudo tcpdump -n -i "+ intf + " " + port + " -w " + filename.strip() + " -Z " + user + " &")
- self.handle.sendline("")
- self.handle.sendline("")
- i=self.handle.expect(['No\ssuch\device','listening\son',pexpect.TIMEOUT,"\$"],timeout=10)
- main.log.warn(self.handle.before + self.handle.after)
+ self.handle.sendline( "" )
+ self.handle.sendline(
+ "sudo tcpdump -n -i " +
+ intf +
+ " " +
+ port +
+ " -w " +
+ filename.strip() +
+ " -Z " +
+ user +
+ " &" )
+ self.handle.sendline( "" )
+ self.handle.sendline( "" )
+ i = self.handle.expect(
+ [ 'No\ssuch\device', 'listening\son', pexpect.TIMEOUT, "\$" ], timeout=10 )
+ main.log.warn( self.handle.before + self.handle.after )
if i == 0:
- main.log.error(self.name + ": tcpdump - No such device exists. tcpdump attempted on: " + intf)
+ main.log.error(
+ self.name +
+ ": tcpdump - No such device exists. tcpdump attempted on: " +
+ intf )
return main.FALSE
elif i == 1:
- main.log.info(self.name + ": tcpdump started on " + intf)
+ main.log.info( self.name + ": tcpdump started on " + intf )
return main.TRUE
elif i == 2:
- main.log.error(self.name + ": tcpdump command timed out! Check interface name, given interface was: " + intf)
+ main.log.error(
+ self.name +
+ ": tcpdump command timed out! Check interface name, given interface was: " +
+ intf )
return main.FALSE
- elif i ==3:
- main.log.info(self.name +": " + self.handle.before)
+ elif i == 3:
+ main.log.info( self.name + ": " + self.handle.before )
return main.TRUE
else:
- main.log.error(self.name + ": tcpdump - unexpected response")
+ main.log.error( self.name + ": tcpdump - unexpected response" )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ self.name +
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def stop_tcpdump(self):
+ def stop_tcpdump( self ):
"pkills tcpdump"
try:
- self.handle.sendline("sudo pkill tcpdump")
- self.handle.sendline("")
- self.handle.sendline("")
- self.handle.expect("\$")
+ self.handle.sendline( "sudo pkill tcpdump" )
+ self.handle.sendline( "" )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ self.name +
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def run_optical_mn_script(self):
- '''
+ def run_optical_mn_script( self ):
+ """
This function is only meant for Packet Optical.
- It runs the python script "optical.py" to create the packet layer(mn)
+ It runs the python script "optical.py" to create the packet layer( mn )
topology
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("cd ~")
- self.handle.expect("\$")
- self.handle.sendline("sudo python optical.py")
- self.handle.expect(">")
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "cd ~" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "sudo python optical.py" )
+ self.handle.expect( ">" )
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
return main.FALSE
- def disconnect(self):
- '''
+ def disconnect( self ):
+ """
Called at the end of the test to disconnect the handle.
- '''
+ """
response = ''
- #print "Disconnecting Mininet"
+ # print "Disconnecting Mininet"
if self.handle:
- self.handle.sendline("exit")
- self.handle.expect("exit")
- self.handle.expect("(.*)")
+ self.handle.sendline( "exit" )
+ self.handle.expect( "exit" )
+ self.handle.expect( "(.*)" )
response = self.handle.before
- else :
- main.log.error("Connection failed to the host")
+ else:
+ main.log.error( "Connection failed to the host" )
response = main.FALSE
return response
- def get_flowTable(self, protoVersion, sw):
- #TODO document usage
- #TODO add option to look at cookies. ignoreing them for now
- self.handle.sendline("cd")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- #print "get_flowTable(" + str(protoVersion) +" " + str(sw) +")"
- #NOTE: Use format to force consistent flow table output across versions
- if protoVersion==1.0:
- command = "sudo ovs-ofctl dump-flows " + sw + " -F OpenFlow10-table_id | awk '{OFS=\",\" ; print $1 $3 $6 $7 $8}' | cut -d ',' -f 2- | sort -n -k1 -r"
- self.handle.sendline(command)
- self.handle.expect(["k1 -r",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["OFPST_FLOW",pexpect.EOF,pexpect.TIMEOUT])
+ def get_flowTable( self, protoVersion, sw ):
+ # TODO document usage
+ # TODO add option to look at cookies. ignoreing them for now
+ self.handle.sendline( "cd" )
+ self.handle.expect( [ "\$", pexpect.EOF, pexpect.TIMEOUT ] )
+ # print "get_flowTable(" + str( protoVersion ) +" " + str( sw ) +")"
+ # NOTE: Use format to force consistent flow table output across
+ # versions
+ if protoVersion == 1.0:
+ command = "sudo ovs-ofctl dump-flows " + sw + \
+ " -F OpenFlow10-table_id | awk '{OFS=\",\" ; print $1 $3 $6 $7 $8}' | cut -d ',' -f 2- | sort -n -k1 -r"
+ self.handle.sendline( command )
+ self.handle.expect( [ "k1 -r", pexpect.EOF, pexpect.TIMEOUT ] )
+ self.handle.expect(
+ [ "OFPST_FLOW", pexpect.EOF, pexpect.TIMEOUT ] )
response = self.handle.before
- #print "response=", response
+ # print "response=", response
return response
- elif protoVersion==1.3:
- command = "sudo ovs-ofctl dump-flows " + sw + " -O OpenFlow13 | awk '{OFS=\",\" ; print $1 $3 $6 $7}' | cut -d ',' -f 2- | sort -n -k1 -r"
- self.handle.sendline(command)
- self.handle.expect(["k1 -r",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["OFPST_FLOW",pexpect.EOF,pexpect.TIMEOUT])
+ elif protoVersion == 1.3:
+ command = "sudo ovs-ofctl dump-flows " + sw + \
+ " -O OpenFlow13 | awk '{OFS=\",\" ; print $1 $3 $6 $7}' | cut -d ',' -f 2- | sort -n -k1 -r"
+ self.handle.sendline( command )
+ self.handle.expect( [ "k1 -r", pexpect.EOF, pexpect.TIMEOUT ] )
+ self.handle.expect(
+ [ "OFPST_FLOW", pexpect.EOF, pexpect.TIMEOUT ] )
response = self.handle.before
- #print "response=", response
+ # print "response=", response
return response
else:
- main.log.error("Unknown protoVersion in get_flowTable(). given: ("+str(type(protoVersion))+") '"+str(protoVersion)+"'")
+ main.log.error(
+ "Unknown protoVersion in get_flowTable(). given: (" +
+ str(
+ type( protoVersion ) ) +
+ ") '" +
+ str(protoVersion) +
+ "'" )
-
- def flow_comp(self,flow1,flow2):
- if flow1==flow2:
+ def flow_comp( self, flow1, flow2 ):
+ if flow1 == flow2:
return main.TRUE
else:
- main.log.info("Flow tables do not match, printing tables:")
- main.log.info("Flow Table 1:")
- main.log.info(flow1)
- main.log.info("Flow Table 2:")
- main.log.info(flow2)
+ main.log.info( "Flow tables do not match, printing tables:" )
+ main.log.info( "Flow Table 1:" )
+ main.log.info( flow1 )
+ main.log.info( "Flow Table 2:" )
+ main.log.info( flow2 )
return main.FALSE
- def setIpTablesOUTPUT(self, dst_ip, dst_port, action='add', packet_type='tcp',rule='DROP'):
- '''
+ def setIpTablesOUTPUT(
+ self,
+ dst_ip,
+ dst_port,
+ action='add',
+ packet_type='tcp',
+ rule='DROP' ):
+ """
Description:
- add or remove iptables rule to DROP (default) packets from specific IP and PORT
+ add or remove iptables rule to DROP ( default ) packets from specific IP and PORT
Usage:
- * specify action ('add' or 'remove')
+ * specify action ( 'add' or 'remove' )
when removing, pass in the same argument as you would add. It will
delete that specific rule.
* specify the destination ip to block with dst_ip
* specify destination port to block to dst_port
- * optional packet type to block (default tcp)
- * optional iptables rule (default DROP)
+ * optional packet type to block ( default tcp )
+ * optional iptables rule ( default DROP )
WARNING:
* This function uses root privilege iptables command which may result in
unwanted network errors. USE WITH CAUTION
- '''
+ """
import re
import time
- #NOTE*********
+ # NOTE*********
# The strict checking methods of this driver function is intentional
# to discourage any misuse or error of iptables, which can cause
# severe network errors
#*************
- #NOTE: Sleep needed to give some time for rule to be added and registered
+ # NOTE: Sleep needed to give some time for rule to be added and registered
# to the instance
- time.sleep(5)
+ time.sleep( 5 )
action_type = action.lower()
- if action_type != 'add' and action_type !='remove':
- main.log.error("Invalid action type. 'add' or 'remove' table rule")
+ if action_type != 'add' and action_type != 'remove':
+ main.log.error(
+ "Invalid action type. 'add' or 'remove' table rule" )
if rule != 'DROP' and rule != 'ACCEPT' and rule != 'LOG':
- #NOTE: Currently only supports rules DROP, ACCEPT, and LOG
- main.log.error("Invalid rule. 'DROP' or 'ACCEPT' or 'LOG' only.")
+ # NOTE: Currently only supports rules DROP, ACCEPT, and LOG
+ main.log.error(
+ "Invalid rule. 'DROP' or 'ACCEPT' or 'LOG' only." )
return
return
else:
- #If there is no existing rule in the iptables, we will see an
+ # If there is no existing rule in the iptables, we will see an
#'iptables:'... message. We expect to see this message.
- #Otherwise, if there IS an existing rule, we will get the prompt
+ # Otherwise, if there IS an existing rule, we will get the prompt
# back, hence why we expect $ for remove type. We want to remove
# an already existing rule
if action_type == 'add':
- #NOTE: "iptables:" expect is a result of return from the command
+ # NOTE: "iptables:" expect is a result of return from the command
# iptables -C ...
# Any changes by the iptables command return string
- # will result in failure of the function. (deemed unlikely
- # at the time of writing this function)
- #Check for existing rules on current input
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("sudo iptables -C OUTPUT -p "+str(packet_type)+
- " -d "+ str(dst_ip)+" --dport "+str(dst_port)+" -j "+str(rule))
- i = self.handle.expect(["iptables:", "\$"])
+ # will result in failure of the function. ( deemed unlikely
+ # at the time of writing this function )
+ # Check for existing rules on current input
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline(
+ "sudo iptables -C OUTPUT -p " +
+ str( packet_type ) +
+ " -d " +
+ str( dst_ip ) +
+ " --dport " +
+ str( dst_port ) +
+ " -j " +
+ str( rule ) )
+ i = self.handle.expect( [ "iptables:", "\$" ] )
print i
print self.handle.before
print "after: "
print self.handle.after
elif action_type == 'remove':
- #Check for existing rules on current input
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("sudo iptables -C OUTPUT -p "+str(packet_type)+
- " -d "+ str(dst_ip)+" --dport "+str(dst_port)+" -j "+str(rule))
- self.handle.expect("\$")
+ # Check for existing rules on current input
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline(
+ "sudo iptables -C OUTPUT -p " +
+ str( packet_type ) +
+ " -d " +
+ str( dst_ip ) +
+ " --dport " +
+ str( dst_port ) +
+ " -j " +
+ str( rule ) )
+ self.handle.expect( "\$" )
print "before: "
print self.handle.before
actual_string = self.handle.after
@@ -470,73 +557,104 @@
print "Actual String:"
print actual_string
- if re.search(expect_string, actual_string):
+ if re.search( expect_string, actual_string ):
match_result = main.TRUE
else:
match_result = main.FALSE
- #If match_result is main.TRUE, it means there is no matching rule.
+ # If match_result is main.TRUE, it means there is no matching rule.
- #If tables does not exist and expected prompt is returned, go ahead and
- #add iptables rule
+ # If tables does not exist and expected prompt is returned, go ahead and
+ # add iptables rule
if match_result == main.TRUE:
- #Ensure action type is add
+ # Ensure action type is add
if action_type == 'add':
#-A is the 'append' action of iptables
action_add = '-A'
try:
- self.handle.sendline("")
- self.handle.sendline("sudo iptables "+action_add+" OUTPUT -p "+str(packet_type)+
- " -d "+ str(dst_ip)+" --dport "+str(dst_port)+" -j "+str(rule))
+ self.handle.sendline( "" )
+ self.handle.sendline(
+ "sudo iptables " +
+ action_add +
+ " OUTPUT -p " +
+ str( packet_type ) +
+ " -d " +
+ str( dst_ip ) +
+ " --dport " +
+ str( dst_port ) +
+ " -j " +
+ str( rule ) )
- info_string = "Rules added to "+str(self.name)
- info_string += "iptable rule added to block IP: "+str(dst_ip)
- info_string += "Port: "+str(dst_port)+" Rule: "+str(rule)
+ info_string = "Rules added to " + str( self.name )
+ info_string += "iptable rule added to block IP: " + \
+ str( dst_ip )
+ info_string += "Port: " + \
+ str( dst_port ) + " Rule: " + str( rule )
- main.log.info(info_string)
+ main.log.info( info_string )
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
+ self.handle.expect(
+ [ "\$", pexpect.EOF, pexpect.TIMEOUT ] )
except pexpect.TIMEOUT:
- main.log.error(self.name + ": Timeout exception in setIpTables function")
+ main.log.error(
+ self.name +
+ ": Timeout exception in setIpTables function" )
except:
- main.log.error( traceback.print_exc())
+ main.log.error( traceback.print_exc() )
main.cleanup()
main.exit()
else:
- main.log.error("Given rule already exists, but attempted to add it")
- #If match_result is 0, it means there IS a matching rule provided
+ main.log.error(
+ "Given rule already exists, but attempted to add it" )
+ # If match_result is 0, it means there IS a matching rule provided
elif match_result == main.FALSE:
- #Ensure action type is remove
+ # Ensure action type is remove
if action_type == 'remove':
#-D is the 'delete' rule of iptables
action_remove = '-D'
try:
- self.handle.sendline("")
- #Delete a specific rule specified into the function
- self.handle.sendline("sudo iptables "+action_remove+" OUTPUT -p "+str(packet_type)+
- " -d "+ str(dst_ip)+" --dport "+str(dst_port)+" -j "+str(rule))
+ self.handle.sendline( "" )
+ # Delete a specific rule specified into the function
+ self.handle.sendline(
+ "sudo iptables " +
+ action_remove +
+ " OUTPUT -p " +
+ str( packet_type ) +
+ " -d " +
+ str( dst_ip ) +
+ " --dport " +
+ str( dst_port ) +
+ " -j " +
+ str( rule ) )
- info_string = "Rules removed from "+str(self.name)
- info_string += " iptables rule removed from blocking IP: "+str(dst_ip)
- info_string += " Port: "+str(dst_port)+" Rule: "+str(rule)
+ info_string = "Rules removed from " + str( self.name )
+ info_string += " iptables rule removed from blocking IP: " + \
+ str( dst_ip )
+ info_string += " Port: " + \
+ str( dst_port ) + " Rule: " + str( rule )
- main.log.info(info_string)
+ main.log.info( info_string )
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
+ self.handle.expect(
+ [ "\$", pexpect.EOF, pexpect.TIMEOUT ] )
except pexpect.TIMEOUT:
- main.log.error(self.name + ": Timeout exception in setIpTables function")
+ main.log.error(
+ self.name +
+ ": Timeout exception in setIpTables function" )
except:
- main.log.error( traceback.print_exc())
+ main.log.error( traceback.print_exc() )
main.cleanup()
main.exit()
else:
- main.log.error("Given rule does not exist, but attempted to remove it")
+ main.log.error(
+ "Given rule does not exist, but attempted to remove it" )
else:
- #NOTE: If a bad usage of this function occurs, exit the entire test
- main.log.error("Bad rule given for iptables. Exiting...")
+ # NOTE: If a bad usage of this function occurs, exit the entire
+ # test
+ main.log.error( "Bad rule given for iptables. Exiting..." )
main.cleanup()
main.exit()
if __name__ != "__main__":
import sys
- sys.modules[__name__] = RemoteMininetDriver()
+ sys.modules[ __name__ ] = RemoteMininetDriver()
diff --git a/TestON/drivers/common/cli/emulatordriver.py b/TestON/drivers/common/cli/emulatordriver.py
index b561e9c..bb8da7c 100644
--- a/TestON/drivers/common/cli/emulatordriver.py
+++ b/TestON/drivers/common/cli/emulatordriver.py
@@ -1,13 +1,13 @@
#!/usr/bin/env python
-'''
-Created on 26-Oct-2012
+"""
+Created on 26-Oct-2012
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -15,18 +15,24 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
import sys
-sys.path.append("../")
+import signal
+import sys
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class Emulator(CLI):
+
+class Emulator( CLI ):
# The common functions for emulator included in emulatordriver
- def __init__(self):
- super(CLI, self).__init__()
-
+
+ def __init__( self ):
+ super( CLI, self ).__init__()
+
diff --git a/TestON/drivers/common/cli/onosclidriver.py b/TestON/drivers/common/cli/onosclidriver.py
index 7e86272..b8a2bd5 100644
--- a/TestON/drivers/common/cli/onosclidriver.py
+++ b/TestON/drivers/common/cli/onosclidriver.py
@@ -1,9 +1,9 @@
#!/usr/bin/env python
-'''
+"""
This driver enters the onos> prompt to issue commands.
-Please follow the coding style demonstrated by existing
+Please follow the coding style demonstrated by existing
functions and document properly.
If you are a contributor to the driver, please
@@ -15,367 +15,370 @@
OCT 13 2014
-'''
-
+"""
import sys
import pexpect
import re
import traceback
#import os.path
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class OnosCliDriver(CLI):
- def __init__(self):
- '''
- Initialize client
- '''
- super(CLI, self).__init__()
+class OnosCliDriver( CLI ):
- def connect(self,**connectargs):
- '''
+ def __init__( self ):
+ """
+ Initialize client
+ """
+ super( CLI, self ).__init__()
+
+ def connect( self, **connectargs ):
+ """
Creates ssh handle for ONOS cli.
- '''
+ """
try:
for key in connectargs:
- vars(self)[key] = connectargs[key]
+ vars( self )[ key ] = connectargs[ key ]
self.home = "~/ONOS"
for key in self.options:
if key == "home":
- self.home = self.options['home']
+ self.home = self.options[ 'home' ]
break
+ self.name = self.options[ 'name' ]
+ self.handle = super( OnosCliDriver, self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd,
+ home=self.home )
- self.name = self.options['name']
- self.handle = super(OnosCliDriver,self).connect(
- user_name = self.user_name,
- ip_address = self.ip_address,
- port = self.port,
- pwd = self.pwd,
- home = self.home)
-
- self.handle.sendline("cd "+ self.home)
- self.handle.expect("\$")
+ self.handle.sendline( "cd " + self.home )
+ self.handle.expect( "\$" )
if self.handle:
return self.handle
- else :
- main.log.info("NO ONOS HANDLE")
+ else:
+ main.log.info( "NO ONOS HANDLE" )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::")
+ main.log.info( self.name + ":::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::")
+ main.log.info( ":::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def disconnect(self):
- '''
+ def disconnect( self ):
+ """
Called when Test is complete to disconnect the ONOS handle.
- '''
+ """
response = ''
try:
- self.handle.sendline("")
- i = self.handle.expect(["onos>","\$"])
+ self.handle.sendline( "" )
+ i = self.handle.expect( [ "onos>", "\$" ] )
if i == 0:
- self.handle.sendline("system:shutdown")
- self.handle.expect("Confirm")
- self.handle.sendline("yes")
- self.handle.expect("\$")
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("exit")
- self.handle.expect("closed")
+ self.handle.sendline( "system:shutdown" )
+ self.handle.expect( "Confirm" )
+ self.handle.sendline( "yes" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "exit" )
+ self.handle.expect( "closed" )
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
except:
- main.log.error(self.name + ": Connection failed to the host")
+ main.log.error( self.name + ": Connection failed to the host" )
response = main.FALSE
return response
- def logout(self):
- '''
+ def logout( self ):
+ """
Sends 'logout' command to ONOS cli
- '''
+ """
try:
- self.handle.sendline("")
- i = self.handle.expect([
+ self.handle.sendline( "" )
+ i = self.handle.expect( [
"onos>",
- "\$"], timeout=10)
+ "\$" ], timeout=10 )
if i == 0:
- self.handle.sendline("logout")
- self.handle.expect("\$")
+ self.handle.sendline( "logout" )
+ self.handle.expect( "\$" )
elif i == 1:
return main.TRUE
-
+
except pexpect.EOF:
- main.log.error(self.name + ": eof exception found")
- main.log.error(self.name + ": " +
- self.handle.before)
+ main.log.error( self.name + ": eof exception found" )
+ main.log.error( self.name + ": " +
+ self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def set_cell(self, cellname):
- '''
+ def set_cell( self, cellname ):
+ """
Calls 'cell <name>' to set the environment variables on ONOSbench
-
+
Before issuing any cli commands, set the environment variable first.
- '''
+ """
try:
if not cellname:
- main.log.error("Must define cellname")
+ main.log.error( "Must define cellname" )
main.cleanup()
main.exit()
else:
- self.handle.sendline("cell "+str(cellname))
- #Expect the cellname in the ONOS_CELL variable.
- #Note that this variable name is subject to change
+ self.handle.sendline( "cell " + str( cellname ) )
+ # Expect the cellname in the ONOS_CELL variable.
+ # Note that this variable name is subject to change
# and that this driver will have to change accordingly
- self.handle.expect("ONOS_CELL="+str(cellname))
+ self.handle.expect( "ONOS_CELL=" + str( cellname ) )
handle_before = self.handle.before
handle_after = self.handle.after
- #Get the rest of the handle
- self.handle.sendline("")
- self.handle.expect("\$")
+ # Get the rest of the handle
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
handle_more = self.handle.before
- main.log.info("Cell call returned: "+handle_before+
- handle_after + handle_more)
+ main.log.info( "Cell call returned: " + handle_before +
+ handle_after + handle_more )
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": eof exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": eof exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def start_onos_cli(self, ONOS_ip, karafTimeout=""):
- '''
- karafTimeout is an optional arugument. karafTimeout value passed by user would be used to set the
+
+ def start_onos_cli( self, ONOS_ip, karafTimeout="" ):
+ """
+ karafTimeout is an optional arugument. karafTimeout value passed by user would be used to set the
current karaf shell idle timeout. Note that when ever this property is modified the shell will exit and
the subsequent login would reflect new idle timeout.
- Below is an example to start a session with 60 seconds idle timeout (input value is in milliseconds):
-
+ Below is an example to start a session with 60 seconds idle timeout ( input value is in milliseconds ):
+
tValue = "60000"
- main.ONOScli1.start_onos_cli(ONOS_ip, karafTimeout=tValue)
-
+ main.ONOScli1.start_onos_cli( ONOS_ip, karafTimeout=tValue )
+
Note: karafTimeout is left as str so that this could be read and passed to start_onos_cli from PARAMS file as str.
- '''
+ """
try:
- self.handle.sendline("")
- x = self.handle.expect([
- "\$", "onos>"], timeout=10)
+ self.handle.sendline( "" )
+ x = self.handle.expect( [
+ "\$", "onos>" ], timeout=10 )
if x == 1:
- main.log.info("ONOS cli is already running")
+ main.log.info( "ONOS cli is already running" )
return main.TRUE
- #Wait for onos start (-w) and enter onos cli
- self.handle.sendline("onos -w "+str(ONOS_ip))
- i = self.handle.expect([
- "onos>",
- pexpect.TIMEOUT],timeout=60)
+ # Wait for onos start ( -w ) and enter onos cli
+ self.handle.sendline( "onos -w " + str( ONOS_ip ) )
+ i = self.handle.expect( [
+ "onos>",
+ pexpect.TIMEOUT ], timeout=60 )
if i == 0:
- main.log.info(str(ONOS_ip)+" CLI Started successfully")
+ main.log.info( str( ONOS_ip ) + " CLI Started successfully" )
if karafTimeout:
- self.handle.sendline("config:property-set -p org.apache.karaf.shell sshIdleTimeout "+karafTimeout)
- self.handle.expect("\$")
- self.handle.sendline("onos -w "+str(ONOS_ip))
- self.handle.expect("onos>")
+ self.handle.sendline(
+ "config:property-set -p org.apache.karaf.shell sshIdleTimeout " +
+ karafTimeout )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos -w " + str( ONOS_ip ) )
+ self.handle.expect( "onos>" )
return main.TRUE
else:
- #If failed, send ctrl+c to process and try again
- main.log.info("Starting CLI failed. Retrying...")
- self.handle.send("\x03")
- self.handle.sendline("onos -w "+str(ONOS_ip))
- i = self.handle.expect(["onos>",pexpect.TIMEOUT],
- timeout=30)
+ # If failed, send ctrl+c to process and try again
+ main.log.info( "Starting CLI failed. Retrying..." )
+ self.handle.send( "\x03" )
+ self.handle.sendline( "onos -w " + str( ONOS_ip ) )
+ i = self.handle.expect( [ "onos>", pexpect.TIMEOUT ],
+ timeout=30 )
if i == 0:
- main.log.info(str(ONOS_ip)+" CLI Started "+
- "successfully after retry attempt")
+ main.log.info( str( ONOS_ip ) + " CLI Started " +
+ "successfully after retry attempt" )
if karafTimeout:
- self.handle.sendline("config:property-set -p org.apache.karaf.shell sshIdleTimeout "+karafTimeout)
- self.handle.expect("\$")
- self.handle.sendline("onos -w "+str(ONOS_ip))
- self.handle.expect("onos>")
+ self.handle.sendline(
+ "config:property-set -p org.apache.karaf.shell sshIdleTimeout " +
+ karafTimeout )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos -w " + str( ONOS_ip ) )
+ self.handle.expect( "onos>" )
return main.TRUE
else:
- main.log.error("Connection to CLI "+\
- str(ONOS_ip)+" timeout")
+ main.log.error( "Connection to CLI " +
+ str( ONOS_ip ) + " timeout" )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def sendline(self, cmd_str):
- '''
+ def sendline( self, cmd_str ):
+ """
Send a completely user specified string to
the onos> prompt. Use this function if you have
a very specific command to send.
Warning: There are no sanity checking to commands
sent using this method.
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("onos>")
+ self.handle.sendline( "" )
+ self.handle.expect( "onos>" )
- self.handle.sendline("log:log \"Sending CLI command: '"
- + cmd_str + "'\"")
- self.handle.expect("onos>")
+ self.handle.sendline( "log:log \"Sending CLI command: '"
+ + cmd_str + "'\"" )
+ self.handle.expect( "onos>" )
self.handle.sendline( cmd_str )
self.handle.expect( cmd_str )
- self.handle.expect("onos>")
+ self.handle.expect( "onos>" )
handle = self.handle.before
- self.handle.sendline("")
- self.handle.expect("onos>")
+ self.handle.sendline( "" )
+ self.handle.expect( "onos>" )
#handle += self.handle.before
#handle += self.handle.after
- main.log.info("Command '" + str( cmd_str ) + "' sent to "
- + self.name + ".")
- ansi_escape = re.compile(r'\x1b[^m]*m')
- handle = ansi_escape.sub('', handle)
+ main.log.info( "Command '" + str(cmd_str) + "' sent to "
+ + self.name + "." )
+ ansi_escape = re.compile( r'\x1b[^m]*m' )
+ handle = ansi_escape.sub( '', handle )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- #IMPORTANT NOTE:
- #For all cli commands, naming convention should match
- #the cli command replacing ':' with '_'.
- #Ex) onos:topology > onos_topology
+ # IMPORTANT NOTE:
+ # For all cli commands, naming convention should match
+ # the cli command replacing ':' with '_'.
+ # Ex ) onos:topology > onos_topology
# onos:links > onos_links
# feature:list > feature_list
- def add_node(self, node_id, ONOS_ip, tcp_port=""):
- '''
+ def add_node( self, node_id, ONOS_ip, tcp_port="" ):
+ """
Adds a new cluster node by ID and address information.
Required:
* node_id
* ONOS_ip
Optional:
* tcp_port
- '''
+ """
try:
- cmd_str = "add-node " + str(node_id) + " " +\
- str(ONOS_ip) + " " + str(tcp_port)
+ cmd_str = "add-node " + str( node_id ) + " " +\
+ str( ONOS_ip ) + " " + str( tcp_port )
handle = self.sendline( cmd_str )
- if re.search("Error", handle):
- main.log.error("Error in adding node")
- main.log.error(handle)
+ if re.search( "Error", handle ):
+ main.log.error( "Error in adding node" )
+ main.log.error( handle )
return main.FALSE
else:
- main.log.info("Node "+str(ONOS_ip)+" added")
+ main.log.info( "Node " + str( ONOS_ip ) + " added" )
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def remove_node(self, node_id):
- '''
+ def remove_node( self, node_id ):
+ """
Removes a cluster by ID
Issues command: 'remove-node [<node-id>]'
Required:
* node_id
- '''
+ """
try:
- cmd_str = "remove-node " + str(node_id)
+ cmd_str = "remove-node " + str( node_id )
self.sendline( cmd_str )
# TODO: add error checking. Does ONOS give any errors?
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def nodes(self):
- '''
+ def nodes( self ):
+ """
List the nodes currently visible
Issues command: 'nodes'
Returns: entire handle of list of nodes
- '''
+ """
try:
cmd_str = "nodes"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def topology(self):
- '''
+ def topology( self ):
+ """
Shows the current state of the topology
by issusing command: 'onos> onos:topology'
- '''
+ """
try:
# either onos:topology or 'topology' will work in CLI
cmd_str = "onos:topology"
@@ -383,197 +386,197 @@
main.log.info( "onos:topology returned: " + str( handle ) )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def feature_install(self, feature_str):
- '''
+ def feature_install( self, feature_str ):
+ """
Installs a specified feature
by issuing command: 'onos> feature:install <feature_str>'
- '''
+ """
try:
cmd_str = "feature:install " + str( feature_str )
self.sendline( cmd_str )
# TODO: Check for possible error responses from karaf
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.log.report("Failed to install feature")
- main.log.report("Exiting test")
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
+ main.log.report( "Failed to install feature" )
+ main.log.report( "Exiting test" )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.report("Failed to install feature")
- main.log.report("Exiting test")
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.report( "Failed to install feature" )
+ main.log.report( "Exiting test" )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def feature_uninstall(self, feature_str):
- '''
+ def feature_uninstall( self, feature_str ):
+ """
Uninstalls a specified feature
by issuing command: 'onos> feature:uninstall <feature_str>'
- '''
+ """
try:
cmd_str = "feature:uninstall " + str( feature_str )
self.sendline( cmd_str )
# TODO: Check for possible error responses from karaf
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def devices(self, json_format=True):
- '''
+ def devices( self, json_format=True ):
+ """
Lists all infrastructure devices or switches
Optional argument:
* json_format - boolean indicating if you want output in json
- '''
+ """
try:
if json_format:
cmd_str = "devices -j"
handle = self.sendline( cmd_str )
- '''
+ """
handle variable here contains some ANSI escape color code
sequences at the end which are invisible in the print command
output. To make that escape sequence visible, use repr()
- function. The repr(handle) output when printed shows the
- ANSI escape sequences. In json.loads(somestring), this
- somestring variable is actually repr(somestring) and
+ function. The repr( handle ) output when printed shows the
+ ANSI escape sequences. In json.loads( somestring ), this
+ somestring variable is actually repr( somestring ) and
json.loads would fail with the escape sequence. So we take off
that escape sequence using:
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
- '''
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
+ """
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
return handle1
else:
cmd_str = "devices"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def balance_masters(self):
- '''
+ def balance_masters( self ):
+ """
This balances the devices across all controllers
by issuing command: 'onos> onos:balance-masters'
If required this could be extended to return devices balanced output.
- '''
+ """
try:
cmd_str = "onos:balance-masters"
self.sendline( cmd_str )
# TODO: Check for error responses from ONOS
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def links(self, json_format=True):
- '''
+ def links( self, json_format=True ):
+ """
Lists all core links
Optional argument:
* json_format - boolean indicating if you want output in json
- '''
+ """
try:
if json_format:
cmd_str = "links -j"
handle = self.sendline( cmd_str )
- '''
+ """
handle variable here contains some ANSI escape color code
sequences at the end which are invisible in the print command
output. To make that escape sequence visible, use repr()
- function. The repr(handle) output when printed shows the ANSI
- escape sequences. In json.loads(somestring), this somestring
- variable is actually repr(somestring) and json.loads would
+ function. The repr( handle ) output when printed shows the ANSI
+ escape sequences. In json.loads( somestring ), this somestring
+ variable is actually repr( somestring ) and json.loads would
fail with the escape sequence. So we take off that escape
sequence using:
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
- '''
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
+ """
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
return handle1
else:
cmd_str = "links"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def ports(self, json_format=True):
- '''
+ def ports( self, json_format=True ):
+ """
Lists all ports
Optional argument:
* json_format - boolean indicating if you want output in json
- '''
+ """
try:
if json_format:
cmd_str = "ports -j"
handle = self.sendline( cmd_str )
- '''
+ """
handle variable here contains some ANSI escape color code
sequences at the end which are invisible in the print command
output. To make that escape sequence visible, use repr()
- function. The repr(handle) output when printed shows the ANSI
- escape sequences. In json.loads(somestring), this somestring
- variable is actually repr(somestring) and json.loads would
+ function. The repr( handle ) output when printed shows the ANSI
+ escape sequences. In json.loads( somestring ), this somestring
+ variable is actually repr( somestring ) and json.loads would
fail with the escape sequence. So we take off that escape
sequence using the following commads:
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
- '''
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
+ """
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
return handle1
else:
@@ -581,45 +584,44 @@
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def roles(self, json_format=True):
- '''
+ def roles( self, json_format=True ):
+ """
Lists all devices and the controllers with roles assigned to them
Optional argument:
* json_format - boolean indicating if you want output in json
- '''
+ """
try:
if json_format:
cmd_str = "roles -j"
handle = self.sendline( cmd_str )
- '''
+ """
handle variable here contains some ANSI escape color code
sequences at the end which are invisible in the print command
output. To make that escape sequence visible, use repr()
- function. The repr(handle) output when printed shows the ANSI
- escape sequences. In json.loads(somestring), this somestring
- variable is actually repr(somestring) and json.loads would
+ function. The repr( handle ) output when printed shows the ANSI
+ escape sequences. In json.loads( somestring ), this somestring
+ variable is actually repr( somestring ) and json.loads would
fail with the escape sequence.
So we take off that escape sequence using the following
commads:
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
- '''
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
+ """
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
return handle1
else:
@@ -627,19 +629,19 @@
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def get_role(self, device_id):
- '''
+ def get_role( self, device_id ):
+ """
Given the a string containing the json representation of the "roles"
cli command and a partial or whole device id, returns a json object
containing the roles output for the first device whose id contains
@@ -648,280 +650,289 @@
Returns:
A dict of the role assignments for the given device or
None if no match
- '''
+ """
try:
import json
- if device_id == None:
+ if device_id is None:
return None
else:
raw_roles = self.roles()
- roles_json = json.loads(raw_roles)
- #search json for the device with id then return the device
+ roles_json = json.loads( raw_roles )
+ # search json for the device with id then return the device
for device in roles_json:
- #print device
- if str(device_id) in device['id']:
+ # print device
+ if str( device_id ) in device[ 'id' ]:
return device
return None
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def roles_not_null(self):
- '''
+ def roles_not_null( self ):
+ """
Iterates through each device and checks if there is a master assigned
Returns: main.TRUE if each device has a master
main.FALSE any device has no master
- '''
+ """
try:
import json
raw_roles = self.roles()
- roles_json = json.loads(raw_roles)
- #search json for the device with id then return the device
+ roles_json = json.loads( raw_roles )
+ # search json for the device with id then return the device
for device in roles_json:
- #print device
- if device['master'] == "none":
- main.log.warn("Device has no master: " + str(device) )
+ # print device
+ if device[ 'master' ] == "none":
+ main.log.warn( "Device has no master: " + str( device ) )
return main.FALSE
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def paths(self, src_id, dst_id):
- '''
+ def paths( self, src_id, dst_id ):
+ """
Returns string of paths, and the cost.
Issues command: onos:paths <src> <dst>
- '''
+ """
try:
- cmd_str = "onos:paths " + str(src_id) + " " + str(dst_id)
+ cmd_str = "onos:paths " + str( src_id ) + " " + str( dst_id )
handle = self.sendline( cmd_str )
if re.search( "Error", handle ):
- main.log.error("Error in getting paths")
- return (handle, "Error")
+ main.log.error( "Error in getting paths" )
+ return ( handle, "Error" )
else:
- path = handle.split(";")[0]
- cost = handle.split(";")[1]
- return (path, cost)
+ path = handle.split( ";" )[ 0 ]
+ cost = handle.split( ";" )[ 1 ]
+ return ( path, cost )
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def hosts(self, json_format=True):
- '''
+ def hosts( self, json_format=True ):
+ """
Lists all discovered hosts
Optional argument:
* json_format - boolean indicating if you want output in json
- '''
+ """
try:
if json_format:
cmd_str = "hosts -j"
handle = self.sendline( cmd_str )
- '''
+ """
handle variable here contains some ANSI escape color code
sequences at the end which are invisible in the print command
output. To make that escape sequence visible, use repr()
- function. The repr(handle) output when printed shows the ANSI
- escape sequences. In json.loads(somestring), this somestring
- variable is actually repr(somestring) and json.loads would
+ function. The repr( handle ) output when printed shows the ANSI
+ escape sequences. In json.loads( somestring ), this somestring
+ variable is actually repr( somestring ) and json.loads would
fail with the escape sequence. So we take off that escape
sequence using:
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
- '''
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
+ """
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
return handle1
else:
cmd_str = "hosts"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def get_host(self, mac):
- '''
+ def get_host( self, mac ):
+ """
Return the first host from the hosts api whose 'id' contains 'mac'
Note: mac must be a colon seperated mac address, but could be a
partial mac address
Return None if there is no match
- '''
+ """
import json
try:
- if mac == None:
+ if mac is None:
return None
else:
mac = mac
raw_hosts = self.hosts()
- hosts_json = json.loads(raw_hosts)
- #search json for the host with mac then return the device
+ hosts_json = json.loads( raw_hosts )
+ # search json for the host with mac then return the device
for host in hosts_json:
- #print "%s in %s?" % (mac, host['id'])
- if mac in host['id']:
+ # print "%s in %s?" % ( mac, host[ 'id' ] )
+ if mac in host[ 'id' ]:
return host
return None
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def get_hosts_id(self, host_list):
- '''
- Obtain list of hosts
+ def get_hosts_id( self, host_list ):
+ """
+ Obtain list of hosts
Issues command: 'onos> hosts'
-
+
Required:
* host_list: List of hosts obtained by Mininet
IMPORTANT:
This function assumes that you started your
- topology with the option '--mac'.
+ topology with the option '--mac'.
Furthermore, it assumes that value of VLAN is '-1'
Description:
- Converts mininet hosts (h1, h2, h3...) into
- ONOS format (00:00:00:00:00:01/-1 , ...)
- '''
-
+ Converts mininet hosts ( h1, h2, h3... ) into
+ ONOS format ( 00:00:00:00:00:01/-1 , ... )
+ """
try:
onos_host_list = []
for host in host_list:
- host = host.replace("h", "")
- host_hex = hex(int(host)).zfill(12)
- host_hex = str(host_hex).replace('x','0')
- i = iter(str(host_hex))
- host_hex = ":".join(a+b for a,b in zip(i,i))
+ host = host.replace( "h", "" )
+ host_hex = hex( int( host ) ).zfill( 12 )
+ host_hex = str( host_hex ).replace( 'x', '0' )
+ i = iter( str( host_hex ) )
+ host_hex = ":".join( a + b for a, b in zip( i, i ) )
host_hex = host_hex + "/-1"
- onos_host_list.append(host_hex)
+ onos_host_list.append( host_hex )
- return onos_host_list
+ return onos_host_list
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def add_host_intent(self, host_id_one, host_id_two):
- '''
+ def add_host_intent( self, host_id_one, host_id_two ):
+ """
Required:
* host_id_one: ONOS host id for host1
* host_id_two: ONOS host id for host2
Description:
- Adds a host-to-host intent (bidrectional) by
+ Adds a host-to-host intent ( bidrectional ) by
specifying the two hosts.
- '''
+ """
try:
- cmd_str = "add-host-intent " + str(host_id_one) +\
- " " + str(host_id_two)
+ cmd_str = "add-host-intent " + str( host_id_one ) +\
+ " " + str( host_id_two )
handle = self.sendline( cmd_str )
- main.log.info("Host intent installed between "+
- str(host_id_one) + " and " + str(host_id_two))
+ main.log.info( "Host intent installed between " +
+ str( host_id_one ) + " and " + str( host_id_two ) )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def add_optical_intent(self, ingress_device, egress_device):
- '''
+ def add_optical_intent( self, ingress_device, egress_device ):
+ """
Required:
* ingress_device: device id of ingress device
* egress_device: device id of egress device
Optional:
TODO: Still needs to be implemented via dev side
- '''
+ """
try:
cmd_str = "add-optical-intent " + str( ingress_device ) +\
- " " + str( egress_device )
+ " " + str( egress_device )
handle = self.sendline( cmd_str )
- #If error, return error message
+ # If error, return error message
if re.search( "Error", handle ):
return handle
else:
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def add_point_intent(self, ingress_device, egress_device,
- port_ingress="", port_egress="", ethType="", ethSrc="",
- ethDst="", bandwidth="", lambda_alloc=False,
- ipProto="", ipSrc="", ipDst="", tcpSrc="", tcpDst=""):
- '''
+ def add_point_intent(
+ self,
+ ingress_device,
+ egress_device,
+ port_ingress="",
+ port_egress="",
+ ethType="",
+ ethSrc="",
+ ethDst="",
+ bandwidth="",
+ lambda_alloc=False,
+ ipProto="",
+ ipSrc="",
+ ipDst="",
+ tcpSrc="",
+ tcpDst="" ):
+ """
Required:
* ingress_device: device id of ingress device
* egress_device: device id of egress device
Optional:
* ethType: specify ethType
- * ethSrc: specify ethSrc (i.e. src mac addr)
- * ethDst: specify ethDst (i.e. dst mac addr)
+ * ethSrc: specify ethSrc ( i.e. src mac addr )
+ * ethDst: specify ethDst ( i.e. dst mac addr )
* bandwidth: specify bandwidth capacity of link
* lambda_alloc: if True, intent will allocate lambda
for the specified intent
@@ -931,100 +942,112 @@
* tcpSrc: specify tcp source port
* tcpDst: specify tcp destination port
Description:
- Adds a point-to-point intent (uni-directional) by
+ Adds a point-to-point intent ( uni-directional ) by
specifying device id's and optional fields
NOTE: This function may change depending on the
options developers provide for point-to-point
intent via cli
- '''
+ """
try:
cmd = ""
- #If there are no optional arguments
+ # If there are no optional arguments
if not ethType and not ethSrc and not ethDst\
and not bandwidth and not lambda_alloc \
and not ipProto and not ipSrc and not ipDst \
and not tcpSrc and not tcpDst:
cmd = "add-point-intent"
-
else:
cmd = "add-point-intent"
if ethType:
- cmd += " --ethType " + str(ethType)
+ cmd += " --ethType " + str( ethType )
if ethSrc:
- cmd += " --ethSrc " + str(ethSrc)
+ cmd += " --ethSrc " + str( ethSrc )
if ethDst:
- cmd += " --ethDst " + str(ethDst)
+ cmd += " --ethDst " + str( ethDst )
if bandwidth:
- cmd += " --bandwidth " + str(bandwidth)
+ cmd += " --bandwidth " + str( bandwidth )
if lambda_alloc:
cmd += " --lambda "
if ipProto:
- cmd += " --ipProto " + str(ipProto)
+ cmd += " --ipProto " + str( ipProto )
if ipSrc:
- cmd += " --ipSrc " + str(ipSrc)
+ cmd += " --ipSrc " + str( ipSrc )
if ipDst:
- cmd += " --ipDst " + str(ipDst)
+ cmd += " --ipDst " + str( ipDst )
if tcpSrc:
- cmd += " --tcpSrc " + str(tcpSrc)
+ cmd += " --tcpSrc " + str( tcpSrc )
if tcpDst:
- cmd += " --tcpDst " + str(tcpDst)
+ cmd += " --tcpDst " + str( tcpDst )
- #Check whether the user appended the port
- #or provided it as an input
+ # Check whether the user appended the port
+ # or provided it as an input
if "/" in ingress_device:
- cmd += " "+str(ingress_device)
+ cmd += " " + str( ingress_device )
else:
if not port_ingress:
- main.log.error("You must specify "+
- "the ingress port")
- #TODO: perhaps more meaningful return
+ main.log.error( "You must specify " +
+ "the ingress port" )
+ # TODO: perhaps more meaningful return
return main.FALSE
- cmd += " "+ \
- str(ingress_device) + "/" +\
- str(port_ingress) + " "
+ cmd += " " + \
+ str( ingress_device ) + "/" +\
+ str( port_ingress ) + " "
if "/" in egress_device:
- cmd += " "+str(egress_device)
+ cmd += " " + str( egress_device )
else:
if not port_egress:
- main.log.error("You must specify "+
- "the egress port")
+ main.log.error( "You must specify " +
+ "the egress port" )
return main.FALSE
- cmd += " "+\
- str(egress_device) + "/" +\
- str(port_egress)
+ cmd += " " +\
+ str( egress_device ) + "/" +\
+ str( port_egress )
- handle = self.sendline(cmd)
+ handle = self.sendline( cmd )
if re.search( "Error", handle ):
- main.log.error("Error in adding point-to-point intent")
+ main.log.error( "Error in adding point-to-point intent" )
return main.FALSE
else:
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def add_multipoint_to_singlepoint_intent(self, ingress_device1,
- ingress_device2, egress_device, port_ingress="", port_egress="",
- ethType="", ethSrc="", ethDst="", bandwidth="", lambda_alloc=False,
- ipProto="", ipSrc="", ipDst="", tcpSrc="", tcpDst="", setEthSrc="",
- setEthDst=""):
- '''
+ def add_multipoint_to_singlepoint_intent(
+ self,
+ ingress_device1,
+ ingress_device2,
+ egress_device,
+ port_ingress="",
+ port_egress="",
+ ethType="",
+ ethSrc="",
+ ethDst="",
+ bandwidth="",
+ lambda_alloc=False,
+ ipProto="",
+ ipSrc="",
+ ipDst="",
+ tcpSrc="",
+ tcpDst="",
+ setEthSrc="",
+ setEthDst="" ):
+ """
Note:
This function assumes that there would be 2 ingress devices and
one egress device. For more number of ingress devices, this
@@ -1035,8 +1058,8 @@
* egress_device: device id of egress device
Optional:
* ethType: specify ethType
- * ethSrc: specify ethSrc (i.e. src mac addr)
- * ethDst: specify ethDst (i.e. dst mac addr)
+ * ethSrc: specify ethSrc ( i.e. src mac addr )
+ * ethDst: specify ethDst ( i.e. dst mac addr )
* bandwidth: specify bandwidth capacity of link
* lambda_alloc: if True, intent will allocate lambda
for the specified intent
@@ -1048,17 +1071,17 @@
* setEthSrc: action to Rewrite Source MAC Address
* setEthDst: action to Rewrite Destination MAC Address
Description:
- Adds a multipoint-to-singlepoint intent (uni-directional) by
+ Adds a multipoint-to-singlepoint intent ( uni-directional ) by
specifying device id's and optional fields
NOTE: This function may change depending on the
options developers provide for multipointpoint-to-singlepoint
intent via cli
- '''
+ """
try:
cmd = ""
- #If there are no optional arguments
+ # If there are no optional arguments
if not ethType and not ethSrc and not ethDst\
and not bandwidth and not lambda_alloc\
and not ipProto and not ipSrc and not ipDst\
@@ -1070,212 +1093,212 @@
cmd = "add-multi-to-single-intent"
if ethType:
- cmd += " --ethType " + str(ethType)
+ cmd += " --ethType " + str( ethType )
if ethSrc:
- cmd += " --ethSrc " + str(ethSrc)
+ cmd += " --ethSrc " + str( ethSrc )
if ethDst:
- cmd += " --ethDst " + str(ethDst)
+ cmd += " --ethDst " + str( ethDst )
if bandwidth:
- cmd += " --bandwidth " + str(bandwidth)
+ cmd += " --bandwidth " + str( bandwidth )
if lambda_alloc:
cmd += " --lambda "
if ipProto:
- cmd += " --ipProto " + str(ipProto)
+ cmd += " --ipProto " + str( ipProto )
if ipSrc:
- cmd += " --ipSrc " + str(ipSrc)
+ cmd += " --ipSrc " + str( ipSrc )
if ipDst:
- cmd += " --ipDst " + str(ipDst)
+ cmd += " --ipDst " + str( ipDst )
if tcpSrc:
- cmd += " --tcpSrc " + str(tcpSrc)
+ cmd += " --tcpSrc " + str( tcpSrc )
if tcpDst:
- cmd += " --tcpDst " + str(tcpDst)
+ cmd += " --tcpDst " + str( tcpDst )
if setEthSrc:
- cmd += " --setEthSrc "+ str(setEthSrc)
+ cmd += " --setEthSrc " + str( setEthSrc )
if setEthDst:
- cmd += " --setEthDst "+ str(setEthDst)
+ cmd += " --setEthDst " + str( setEthDst )
- #Check whether the user appended the port
- #or provided it as an input
+ # Check whether the user appended the port
+ # or provided it as an input
if "/" in ingress_device1:
- cmd += " "+str(ingress_device1)
+ cmd += " " + str( ingress_device1 )
else:
if not port_ingress1:
- main.log.error("You must specify "+
- "the ingress port1")
- #TODO: perhaps more meaningful return
+ main.log.error( "You must specify " +
+ "the ingress port1" )
+ # TODO: perhaps more meaningful return
return main.FALSE
- cmd += " "+ \
- str(ingress_device1) + "/" +\
- str(port_ingress1) + " "
+ cmd += " " + \
+ str( ingress_device1 ) + "/" +\
+ str( port_ingress1 ) + " "
if "/" in ingress_device2:
- cmd += " "+str(ingress_device2)
+ cmd += " " + str( ingress_device2 )
else:
if not port_ingress2:
- main.log.error("You must specify "+
- "the ingress port2")
- #TODO: perhaps more meaningful return
+ main.log.error( "You must specify " +
+ "the ingress port2" )
+ # TODO: perhaps more meaningful return
return main.FALSE
- cmd += " "+ \
- str(ingress_device2) + "/" +\
- str(port_ingress2) + " "
+ cmd += " " + \
+ str( ingress_device2 ) + "/" +\
+ str( port_ingress2 ) + " "
if "/" in egress_device:
- cmd += " "+str(egress_device)
+ cmd += " " + str( egress_device )
else:
if not port_egress:
- main.log.error("You must specify "+
- "the egress port")
+ main.log.error( "You must specify " +
+ "the egress port" )
return main.FALSE
- cmd += " "+\
- str(egress_device) + "/" +\
- str(port_egress)
- print "cmd= ",cmd
- handle = self.sendline(cmd)
+ cmd += " " +\
+ str( egress_device ) + "/" +\
+ str( port_egress )
+ print "cmd= ", cmd
+ handle = self.sendline( cmd )
if re.search( "Error", handle ):
- main.log.error("Error in adding point-to-point intent")
+ main.log.error( "Error in adding point-to-point intent" )
return self.handle
else:
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def remove_intent(self, intent_id):
- '''
+ def remove_intent( self, intent_id ):
+ """
Remove intent for specified intent id
Returns:
main.False on error and
cli output otherwise
- '''
+ """
try:
cmd_str = "remove-intent " + str( intent_id )
handle = self.sendline( cmd_str )
if re.search( "Error", handle ):
- main.log.error("Error in removing intent")
+ main.log.error( "Error in removing intent" )
return main.FALSE
else:
# TODO: Should this be main.TRUE
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def routes(self, json_format=False):
- '''
+ def routes( self, json_format=False ):
+ """
NOTE: This method should be used after installing application:
onos-app-sdnip
Optional:
* json_format: enable output formatting in json
Description:
Obtain all routes in the system
- '''
+ """
try:
if json_format:
cmd_str = "routes -j"
handle_tmp = self.sendline( cmd_str )
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle = ansi_escape.sub('', handle_tmp)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle = ansi_escape.sub( '', handle_tmp )
else:
cmd_str = "routes"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + " ::::::")
- main.log.error(traceback.print_exc())
- main.log.info(self.name + " ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def intents(self, json_format = True):
- '''
+ def intents( self, json_format=True ):
+ """
Optional:
* json_format: enable output formatting in json
Description:
Obtain intents currently installed
- '''
+ """
try:
if json_format:
cmd_str = "intents -j"
handle = self.sendline( cmd_str )
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle = ansi_escape.sub( '', handle )
else:
cmd_str = "intents"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def flows(self, json_format = True):
- '''
+ def flows( self, json_format=True ):
+ """
Optional:
* json_format: enable output formatting in json
Description:
Obtain flows currently installed
- '''
+ """
try:
if json_format:
cmd_str = "flows -j"
handle = self.sendline( cmd_str )
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle = ansi_escape.sub( '', handle )
else:
cmd_str = "flows"
handle = self.sendline( cmd_str )
- if re.search("Error\sexecuting\scommand:", handle):
+ if re.search( "Error\sexecuting\scommand:", handle ):
main.log.error( self.name + ".flows() response: " +
- str( handle ) )
+ str( handle ) )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def push_test_intents(self, dpid_src, dpid_dst, num_intents,
- num_mult="", app_id="", report=True):
- '''
+ def push_test_intents( self, dpid_src, dpid_dst, num_intents,
+ num_mult="", app_id="", report=True ):
+ """
Description:
Push a number of intents in a batch format to
a specific point-to-point intent definition
@@ -1289,280 +1312,280 @@
* app_id: specify the application id init to further
modularize the intents
* report: default True, returns latency information
- '''
+ """
try:
- cmd = "push-test-intents "+\
- str(dpid_src)+" "+str(dpid_dst)+" "+\
- str(num_intents)
+ cmd = "push-test-intents " +\
+ str( dpid_src ) + " " + str( dpid_dst ) + " " +\
+ str( num_intents )
if num_mult:
- cmd += " " + str(num_mult)
- #If app id is specified, then num_mult
- #must exist because of the way this command
+ cmd += " " + str( num_mult )
+ # If app id is specified, then num_mult
+ # must exist because of the way this command
#takes in arguments
if app_id:
- cmd += " " + str(app_id)
+ cmd += " " + str( app_id )
handle = self.sendline( cmd )
- #Some color thing that we want to escape
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle = ansi_escape.sub('', handle)
+ # Some color thing that we want to escape
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle = ansi_escape.sub( '', handle )
if report:
lat_result = []
- main.log.info(handle)
- #Split result by newline
- newline = handle.split("\r\r\n")
- #Ignore the first object of list, which is empty
- newline = newline[1:]
- #Some sloppy parsing method to get the latency
+ main.log.info( handle )
+ # Split result by newline
+ newline = handle.split( "\r\r\n" )
+ # Ignore the first object of list, which is empty
+ newline = newline[ 1: ]
+ # Some sloppy parsing method to get the latency
for result in newline:
- result = result.split(": ")
- #Append the first result of second parse
- lat_result.append(result[1].split(" ")[0])
- main.log.info(lat_result)
+ result = result.split( ": " )
+ # Append the first result of second parse
+ lat_result.append( result[ 1 ].split( " " )[ 0 ] )
+ main.log.info( lat_result )
return lat_result
else:
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def intents_events_metrics(self, json_format=True):
- '''
+ def intents_events_metrics( self, json_format=True ):
+ """
Description:Returns topology metrics
Optional:
* json_format: enable json formatting of output
- '''
+ """
try:
if json_format:
cmd_str = "intents-events-metrics -j"
handle = self.sendline( cmd_str )
# Some color thing that we want to escape
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle = ansi_escape.sub( '', handle )
else:
cmd_str = "intents-events-metrics"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def topology_events_metrics(self, json_format=True):
- '''
- Description:Returns topology metrics
+ def topology_events_metrics( self, json_format=True ):
+ """
+ Description:Returns topology metrics
Optional:
* json_format: enable json formatting of output
- '''
+ """
try:
if json_format:
cmd_str = "topology-events-metrics -j"
handle = self.sendline( cmd_str )
- #Some color thing that we want to escape
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle = ansi_escape.sub('', handle)
+ # Some color thing that we want to escape
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle = ansi_escape.sub( '', handle )
else:
cmd_str = "topology-events-metrics"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- #Wrapper functions ****************
- #Wrapper functions use existing driver
- #functions and extends their use case.
- #For example, we may use the output of
- #a normal driver function, and parse it
- #using a wrapper function
+ # Wrapper functions ****************
+ # Wrapper functions use existing driver
+ # functions and extends their use case.
+ # For example, we may use the output of
+ # a normal driver function, and parse it
+ # using a wrapper function
- def get_all_intents_id(self):
- '''
+ def get_all_intents_id( self ):
+ """
Description:
Obtain all intent id's in a list
- '''
+ """
try:
- #Obtain output of intents function
+ # Obtain output of intents function
intents_str = self.intents()
all_intent_list = []
intent_id_list = []
- #Parse the intents output for ID's
- intents_list = [s.strip() for s in intents_str.splitlines()]
+ # Parse the intents output for ID's
+ intents_list = [ s.strip() for s in intents_str.splitlines() ]
for intents in intents_list:
if "onos>" in intents:
continue
elif "intents" in intents:
continue
else:
- line_list = intents.split(" ")
- all_intent_list.append(line_list[0])
-
- all_intent_list = all_intent_list[1:-2]
+ line_list = intents.split( " " )
+ all_intent_list.append( line_list[ 0 ] )
+
+ all_intent_list = all_intent_list[ 1:-2 ]
for intents in all_intent_list:
if not intents:
continue
else:
- intent_id_list.append(intents)
+ intent_id_list.append( intents )
return intent_id_list
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def get_all_devices_id(self):
- '''
+ def get_all_devices_id( self ):
+ """
Use 'devices' function to obtain list of all devices
and parse the result to obtain a list of all device
id's. Returns this list. Returns empty list if no
devices exist
- List is ordered sequentially
-
+ List is ordered sequentially
+
This function may be useful if you are not sure of the
- device id, and wish to execute other commands using
+ device id, and wish to execute other commands using
the ids. By obtaining the list of device ids on the fly,
you can iterate through the list to get mastership, etc.
- '''
+ """
try:
- #Call devices and store result string
- devices_str = self.devices(json_format=False)
+ # Call devices and store result string
+ devices_str = self.devices( json_format=False )
id_list = []
-
+
if not devices_str:
- main.log.info("There are no devices to get id from")
+ main.log.info( "There are no devices to get id from" )
return id_list
-
- #Split the string into list by comma
- device_list = devices_str.split(",")
- #Get temporary list of all arguments with string 'id='
- temp_list = [dev for dev in device_list if "id=" in dev]
- #Split list further into arguments before and after string
- # 'id='. Get the latter portion (the actual device id) and
+
+ # Split the string into list by comma
+ device_list = devices_str.split( "," )
+ # Get temporary list of all arguments with string 'id='
+ temp_list = [ dev for dev in device_list if "id=" in dev ]
+ # Split list further into arguments before and after string
+ # 'id='. Get the latter portion ( the actual device id ) and
# append to id_list
for arg in temp_list:
- id_list.append(arg.split("id=")[1])
+ id_list.append( arg.split( "id=" )[ 1 ] )
return id_list
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def get_all_nodes_id(self):
- '''
+ def get_all_nodes_id( self ):
+ """
Uses 'nodes' function to obtain list of all nodes
and parse the result of nodes to obtain just the
- node id's.
+ node id's.
Returns:
list of node id's
- '''
+ """
try:
nodes_str = self.nodes()
id_list = []
if not nodes_str:
- main.log.info("There are no nodes to get id from")
+ main.log.info( "There are no nodes to get id from" )
return id_list
- #Sample nodes_str output
- #id=local, address=127.0.0.1:9876, state=ACTIVE *
+ # Sample nodes_str output
+ # id=local, address=127.0.0.1:9876, state=ACTIVE *
- #Split the string into list by comma
- nodes_list = nodes_str.split(",")
- temp_list = [node for node in nodes_list if "id=" in node]
+ # Split the string into list by comma
+ nodes_list = nodes_str.split( "," )
+ temp_list = [ node for node in nodes_list if "id=" in node ]
for arg in temp_list:
- id_list.append(arg.split("id=")[1])
+ id_list.append( arg.split( "id=" )[ 1 ] )
return id_list
-
+
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def get_device(self, dpid=None):
- '''
+ def get_device( self, dpid=None ):
+ """
Return the first device from the devices api whose 'id' contains 'dpid'
Return None if there is no match
- '''
+ """
import json
try:
- if dpid == None:
+ if dpid is None:
return None
else:
- dpid = dpid.replace(':', '')
+ dpid = dpid.replace( ':', '' )
raw_devices = self.devices()
- devices_json = json.loads(raw_devices)
- #search json for the device with dpid then return the device
+ devices_json = json.loads( raw_devices )
+ # search json for the device with dpid then return the device
for device in devices_json:
- #print "%s in %s?" % (dpid, device['id'])
- if dpid in device['id']:
+ # print "%s in %s?" % ( dpid, device[ 'id' ] )
+ if dpid in device[ 'id' ]:
return device
return None
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def check_status(self, ip, numoswitch, numolink, log_level="info"):
- '''
- Checks the number of swithes & links that ONOS sees against the
- supplied values. By default this will report to main.log, but the
+ def check_status( self, ip, numoswitch, numolink, log_level="info" ):
+ """
+ Checks the number of swithes & links that ONOS sees against the
+ supplied values. By default this will report to main.log, but the
log level can be specifid.
-
+
Params: ip = ip used for the onos cli
numoswitch = expected number of switches
numlink = expected number of links
@@ -1571,56 +1594,55 @@
log_level can
- Returns: main.TRUE if the number of switchs and links are correct,
+ Returns: main.TRUE if the number of switchs and links are correct,
main.FALSE if the numer of switches and links is incorrect,
and main.ERROR otherwise
- '''
-
+ """
try:
- topology = self.get_topology(ip)
+ topology = self.get_topology( ip )
if topology == {}:
return main.ERROR
output = ""
- #Is the number of switches is what we expected
- devices = topology.get('devices',False)
- links = topology.get('links',False)
+ # Is the number of switches is what we expected
+ devices = topology.get( 'devices', False )
+ links = topology.get( 'links', False )
if devices == False or links == False:
return main.ERROR
- switch_check = ( int(devices) == int(numoswitch) )
- #Is the number of links is what we expected
- link_check = ( int(links) == int(numolink) )
- if (switch_check and link_check):
- #We expected the correct numbers
+ switch_check = ( int( devices ) == int( numoswitch ) )
+ # Is the number of links is what we expected
+ link_check = ( int( links ) == int( numolink ) )
+ if ( switch_check and link_check ):
+ # We expected the correct numbers
output = output + "The number of links and switches match "\
- + "what was expected"
+ + "what was expected"
result = main.TRUE
else:
output = output + \
- "The number of links and switches does not match what was expected"
+ "The number of links and switches does not match what was expected"
result = main.FALSE
- output = output + "\n ONOS sees %i devices (%i expected) and %i links (%i expected)"\
- % ( int(devices), int(numoswitch), int(links), int(numolink) )
+ output = output + "\n ONOS sees %i devices (%i expected) and %i links (%i expected)" % (
+ int( devices ), int( numoswitch ), int( links ), int( numolink ) )
if log_level == "report":
- main.log.report(output)
+ main.log.report( output )
elif log_level == "warn":
- main.log.warn(output)
+ main.log.warn( output )
else:
- main.log.info(output)
- return result
+ main.log.info( output )
+ return result
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def device_role(self, device_id, onos_node, role="master"):
- '''
+ def device_role( self, device_id, onos_node, role="master" ):
+ """
Calls the device-role cli command.
device_id must be the id of a device as seen in the onos devices command
onos_node is the ip of one of the onos nodes in the cluster
@@ -1629,216 +1651,216 @@
Returns:
main.TRUE or main.FALSE based on argument verification and
main.ERROR if command returns and error
- '''
+ """
try:
if role.lower() == "master" or role.lower() == "standby" or\
role.lower() == "none":
- cmd_str = "device-role " +\
- str(device_id) + " " +\
- str(onos_node) + " " +\
- str(role)
- handle = self.sendline( cmd_str )
- if re.search( "Error", handle ):
- # end color output to escape any colours
- # from the cli
- main.log.error( self.name + ": " +\
+ cmd_str = "device-role " +\
+ str( device_id ) + " " +\
+ str( onos_node ) + " " +\
+ str( role )
+ handle = self.sendline( cmd_str )
+ if re.search( "Error", handle ):
+ # end color output to escape any colours
+ # from the cli
+ main.log.error( self.name + ": " +
handle + '\033[0m' )
- return main.ERROR
- return main.TRUE
+ return main.ERROR
+ return main.TRUE
else:
- main.log.error("Invalid 'role' given to device_role(). " +
- "Value was '" + str( role ) + "'.")
+ main.log.error( "Invalid 'role' given to device_role(). " +
+ "Value was '" + str(role) + "'." )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def clusters(self, json_format=True):
- '''
+ def clusters( self, json_format=True ):
+ """
Lists all clusters
Optional argument:
* json_format - boolean indicating if you want output in json
- '''
+ """
try:
if json_format:
cmd_str = "clusters -j"
handle = self.sendline( cmd_str )
- '''
+ """
handle variable here contains some ANSI escape color code
sequences at the end which are invisible in the print command
output. To make that escape sequence visible, use repr()
- function. The repr(handle) output when printed shows the ANSI
- escape sequences. In json.loads(somestring), this somestring
- variable is actually repr(somestring) and json.loads would fail
+ function. The repr( handle ) output when printed shows the ANSI
+ escape sequences. In json.loads( somestring ), this somestring
+ variable is actually repr( somestring ) and json.loads would fail
with the escape sequence. So we take off that escape sequence
using:
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
- '''
- ansi_escape = re.compile(r'\r\r\n\x1b[^m]*m')
- handle1 = ansi_escape.sub('', handle)
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
+ """
+ ansi_escape = re.compile( r'\r\r\n\x1b[^m]*m' )
+ handle1 = ansi_escape.sub( '', handle )
return handle1
else:
cmd_str = "clusters"
handle = self.sendline( cmd_str )
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def election_test_leader(self):
- '''
+ def election_test_leader( self ):
+ """
CLI command to get the current leader for the Election test application
NOTE: Requires installation of the onos-app-election feature
Returns: Node IP of the leader if one exists
None if none exists
Main.FALSE on error
- '''
+ """
try:
cmd_str = "election-test-leader"
response = self.sendline( cmd_str )
# Leader
leaderPattern = "The\scurrent\sleader\sfor\sthe\sElection\s" +\
- "app\sis\s(?P<node>.+)\."
- node_search = re.search(leaderPattern, response)
+ "app\sis\s(?P<node>.+)\."
+ node_search = re.search( leaderPattern, response )
if node_search:
- node = node_search.group('node')
+ node = node_search.group( 'node' )
main.log.info( "Election-test-leader on " + str( self.name ) +
- " found " + node + " as the leader" )
+ " found " + node + " as the leader" )
return node
# no leader
nullPattern = "There\sis\scurrently\sno\sleader\selected\sfor\s" +\
- "the\sElection\sapp"
- null_search = re.search(nullPattern, response)
+ "the\sElection\sapp"
+ null_search = re.search( nullPattern, response )
if null_search:
main.log.info( "Election-test-leader found no leader on " +
- self.name )
+ self.name )
return None
- #error
+ # error
errorPattern = "Command\snot\sfound"
- if re.search(errorPattern, response):
- main.log.error("Election app is not loaded on " + self.name)
+ if re.search( errorPattern, response ):
+ main.log.error( "Election app is not loaded on " + self.name )
# TODO: Should this be main.ERROR?
return main.FALSE
else:
- main.log.error("Error in election_test_leader: " +
- "unexpected response")
- main.log.error( repr(response) )
+ main.log.error( "Error in election_test_leader: " +
+ "unexpected response" )
+ main.log.error( repr( response ) )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def election_test_run(self):
- '''
+ def election_test_run( self ):
+ """
CLI command to run for leadership of the Election test application.
NOTE: Requires installation of the onos-app-election feature
Returns: Main.TRUE on success
Main.FALSE on error
- '''
+ """
try:
cmd_str = "election-test-run"
response = self.sendline( cmd_str )
- #success
+ # success
successPattern = "Entering\sleadership\selections\sfor\sthe\s" +\
- "Election\sapp."
+ "Election\sapp."
search = re.search( successPattern, response )
if search:
main.log.info( self.name + " entering leadership elections " +
- "for the Election app." )
+ "for the Election app." )
return main.TRUE
- #error
+ # error
errorPattern = "Command\snot\sfound"
if re.search( errorPattern, response ):
main.log.error( "Election app is not loaded on " + self.name )
return main.FALSE
else:
main.log.error( "Error in election_test_run: " +
- "unexpected response" )
+ "unexpected response" )
main.log.error( repr( response ) )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def election_test_withdraw(self):
- '''
+ def election_test_withdraw( self ):
+ """
* CLI command to withdraw the local node from leadership election for
* the Election test application.
#NOTE: Requires installation of the onos-app-election feature
Returns: Main.TRUE on success
Main.FALSE on error
- '''
+ """
try:
cmd_str = "election-test-withdraw"
response = self.sendline( cmd_str )
- #success
+ # success
successPattern = "Withdrawing\sfrom\sleadership\selections\sfor" +\
- "\sthe\sElection\sapp."
+ "\sthe\sElection\sapp."
if re.search( successPattern, response ):
main.log.info( self.name + " withdrawing from leadership " +
- "elections for the Election app." )
+ "elections for the Election app." )
return main.TRUE
- #error
+ # error
errorPattern = "Command\snot\sfound"
if re.search( errorPattern, response ):
main.log.error( "Election app is not loaded on " + self.name )
return main.FALSE
else:
main.log.error( "Error in election_test_withdraw: " +
- "unexpected response" )
+ "unexpected response" )
main.log.error( repr( response ) )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
#***********************************
- def getDevicePortsEnabledCount(self,dpid):
- '''
+ def getDevicePortsEnabledCount( self, dpid ):
+ """
Get the count of all enabled ports on a particular device/switch
- '''
+ """
try:
dpid = str( dpid )
cmd_str = "onos:ports -e " + dpid + " | wc -l"
@@ -1849,46 +1871,46 @@
else:
return output
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def getDeviceLinksActiveCount(self,dpid):
- '''
+ def getDeviceLinksActiveCount( self, dpid ):
+ """
Get the count of all enabled ports on a particular device/switch
- '''
+ """
try:
- dpid = str(dpid)
+ dpid = str( dpid )
cmd_str = "onos:links " + dpid + " | grep ACTIVE | wc -l"
output = self.sendline( cmd_str )
if re.search( "No such device", output ):
- main.log.error( "Error in getting ports ")
- return ( output, "Error ")
+ main.log.error( "Error in getting ports " )
+ return ( output, "Error " )
else:
return output
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def getAllIntentIds(self):
- '''
+ def getAllIntentIds( self ):
+ """
Return a list of all Intent IDs
- '''
+ """
try:
cmd_str = "onos:intents | grep id="
output = self.sendline( cmd_str )
@@ -1898,13 +1920,13 @@
else:
return output
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
diff --git a/TestON/drivers/common/cli/onosdriver.py b/TestON/drivers/common/cli/onosdriver.py
index 46ec33a..58ba929 100644
--- a/TestON/drivers/common/cli/onosdriver.py
+++ b/TestON/drivers/common/cli/onosdriver.py
@@ -1,10 +1,10 @@
#!/usr/bin/env python
-'''
-This driver interacts with ONOS bench, the OSGi platform
-that configures the ONOS nodes. (aka ONOS-next)
+"""
+This driver interacts with ONOS bench, the OSGi platform
+that configures the ONOS nodes. ( aka ONOS-next )
-Please follow the coding style demonstrated by existing
+Please follow the coding style demonstrated by existing
functions and document properly.
If you are a contributor to the driver, please
@@ -15,125 +15,126 @@
OCT 9 2014
-'''
-
+"""
import sys
import time
import pexpect
import traceback
import os.path
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class OnosDriver(CLI):
- def __init__(self):
- '''
- Initialize client
- '''
- super(CLI, self).__init__()
+class OnosDriver( CLI ):
- def connect(self,**connectargs):
- '''
+ def __init__( self ):
+ """
+ Initialize client
+ """
+ super( CLI, self ).__init__()
+
+ def connect( self, **connectargs ):
+ """
Creates ssh handle for ONOS "bench".
- '''
+ """
try:
for key in connectargs:
- vars(self)[key] = connectargs[key]
+ vars( self )[ key ] = connectargs[ key ]
self.home = "~/ONOS"
for key in self.options:
if key == "home":
- self.home = self.options['home']
+ self.home = self.options[ 'home' ]
break
+ self.name = self.options[ 'name' ]
+ self.handle = super( OnosDriver, self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd,
+ home=self.home )
- self.name = self.options['name']
- self.handle = super(OnosDriver,self).connect(
- user_name = self.user_name,
- ip_address = self.ip_address,
- port = self.port,
- pwd = self.pwd,
- home = self.home)
-
- self.handle.sendline("cd "+ self.home)
- self.handle.expect("\$")
+ self.handle.sendline( "cd " + self.home )
+ self.handle.expect( "\$" )
if self.handle:
return self.handle
- else :
- main.log.info("NO ONOS HANDLE")
+ else:
+ main.log.info( "NO ONOS HANDLE" )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ self.name +
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def disconnect(self):
- '''
+ def disconnect( self ):
+ """
Called when Test is complete to disconnect the ONOS handle.
- '''
+ """
response = ''
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("exit")
- self.handle.expect("closed")
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "exit" )
+ self.handle.expect( "closed" )
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
except:
- main.log.error(self.name + ": Connection failed to the host")
+ main.log.error( self.name + ": Connection failed to the host" )
response = main.FALSE
return response
- def onos_package(self):
- '''
+ def onos_package( self ):
+ """
Produce a self-contained tar.gz file that can be deployed
- and executed on any platform with Java 7 JRE.
- '''
-
+ and executed on any platform with Java 7 JRE.
+ """
try:
- self.handle.sendline("onos-package")
- self.handle.expect("onos-package")
- self.handle.expect("tar.gz",timeout=30)
- handle = str(self.handle.before)
- main.log.info("onos-package command returned: "+
- handle)
- #As long as the sendline does not time out,
- #return true. However, be careful to interpret
- #the results of the onos-package command return
+ self.handle.sendline( "onos-package" )
+ self.handle.expect( "onos-package" )
+ self.handle.expect( "tar.gz", timeout=30 )
+ handle = str( self.handle.before )
+ main.log.info( "onos-package command returned: " +
+ handle )
+ # As long as the sendline does not time out,
+ # return true. However, be careful to interpret
+ # the results of the onos-package command return
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
except:
- main.log.error("Failed to package ONOS")
+ main.log.error( "Failed to package ONOS" )
main.cleanup()
main.exit()
- def onos_build(self):
- '''
+ def onos_build( self ):
+ """
Use the pre defined script to build onos via mvn
- '''
-
+ """
try:
- self.handle.sendline("onos-build")
- self.handle.expect("onos-build")
- i = self.handle.expect([
- "BUILD SUCCESS",
- "ERROR",
- "BUILD FAILED"], timeout=120)
- handle = str(self.handle.before)
+ self.handle.sendline( "onos-build" )
+ self.handle.expect( "onos-build" )
+ i = self.handle.expect( [
+ "BUILD SUCCESS",
+ "ERROR",
+ "BUILD FAILED" ],
+ timeout=120 )
+ handle = str( self.handle.before )
- main.log.info("onos-build command returned: "+
- handle)
+ main.log.info( "onos-build command returned: " +
+ handle )
if i == 0:
return main.TRUE
@@ -141,859 +142,917 @@
return handle
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
except:
- main.log.error("Failed to build ONOS")
+ main.log.error( "Failed to build ONOS" )
main.cleanup()
main.exit()
- def clean_install(self):
- '''
- Runs mvn clean install in the root of the ONOS directory.
- This will clean all ONOS artifacts then compile each module
+ def clean_install( self ):
+ """
+ Runs mvn clean install in the root of the ONOS directory.
+ This will clean all ONOS artifacts then compile each module
- Returns: main.TRUE on success
+ Returns: main.TRUE on success
On Failure, exits the test
- '''
+ """
try:
- main.log.info("Running 'mvn clean install' on " + str(self.name) +
- ". This may take some time.")
- self.handle.sendline("cd "+ self.home)
- self.handle.expect("\$")
+ main.log.info( "Running 'mvn clean install' on " + str( self.name ) +
+ ". This may take some time." )
+ self.handle.sendline( "cd " + self.home )
+ self.handle.expect( "\$" )
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("mvn clean install")
- self.handle.expect("mvn clean install")
- while 1:
- i=self.handle.expect([
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "mvn clean install" )
+ self.handle.expect( "mvn clean install" )
+ while True:
+ i = self.handle.expect( [
'There\sis\sinsufficient\smemory\sfor\sthe\sJava\s\
Runtime\sEnvironment\sto\scontinue',
'BUILD\sFAILURE',
'BUILD\sSUCCESS',
'ONOS\$',
- pexpect.TIMEOUT],timeout=600)
+ pexpect.TIMEOUT ], timeout=600 )
if i == 0:
- main.log.error(self.name + ":There is insufficient memory \
- for the Java Runtime Environment to continue.")
- #return main.FALSE
+ main.log.error( self.name + ":There is insufficient memory \
+ for the Java Runtime Environment to continue." )
+ # return main.FALSE
main.cleanup()
main.exit()
if i == 1:
- main.log.error(self.name + ": Build failure!")
- #return main.FALSE
+ main.log.error( self.name + ": Build failure!" )
+ # return main.FALSE
main.cleanup()
main.exit()
elif i == 2:
- main.log.info(self.name + ": Build success!")
+ main.log.info( self.name + ": Build success!" )
elif i == 3:
- main.log.info(self.name + ": Build complete")
- #Print the build time
+ main.log.info( self.name + ": Build complete" )
+ # Print the build time
for line in self.handle.before.splitlines():
if "Total time:" in line:
- main.log.info(line)
- self.handle.sendline("")
- self.handle.expect("\$", timeout=60)
+ main.log.info( line )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$", timeout=60 )
return main.TRUE
elif i == 4:
- main.log.error(self.name + ": mvn clean install TIMEOUT!")
- #return main.FALSE
+ main.log.error(
+ self.name +
+ ": mvn clean install TIMEOUT!" )
+ # return main.FALSE
main.cleanup()
main.exit()
else:
- main.log.error(self.name + ": unexpected response from \
- mvn clean install")
- #return main.FALSE
+ main.log.error( self.name + ": unexpected response from \
+ mvn clean install" )
+ # return main.FALSE
main.cleanup()
main.exit()
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ self.name +
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def git_pull(self, comp1=""):
- '''
+ def git_pull( self, comp1="" ):
+ """
Assumes that "git pull" works without login
This function will perform a git pull on the ONOS instance.
- If used as git_pull("NODE") it will do git pull + NODE. This is
+ If used as git_pull( "NODE" ) it will do git pull + NODE. This is
for the purpose of pulling from other nodes if necessary.
Otherwise, this function will perform a git pull in the
ONOS repository. If it has any problems, it will return main.ERROR
- If it successfully does a git_pull, it will return a 1 (main.TRUE)
+ If it successfully does a git_pull, it will return a 1 ( main.TRUE )
If it has no updates, it will return 3.
- '''
+ """
try:
- # main.log.info(self.name + ": Stopping ONOS")
- #self.stop()
- self.handle.sendline("cd " + self.home)
- self.handle.expect("ONOS\$")
- if comp1=="":
- self.handle.sendline("git pull")
+ # main.log.info( self.name + ": Stopping ONOS" )
+ # self.stop()
+ self.handle.sendline( "cd " + self.home )
+ self.handle.expect( "ONOS\$" )
+ if comp1 == "":
+ self.handle.sendline( "git pull" )
else:
- self.handle.sendline("git pull " + comp1)
+ self.handle.sendline( "git pull " + comp1 )
- i=self.handle.expect(['fatal',
- 'Username\sfor\s(.*):\s',
- '\sfile(s*) changed,\s',
- 'Already up-to-date',
- 'Aborting',
- 'You\sare\snot\scurrently\son\sa\sbranch',
- 'You\sasked\sme\sto\spull\swithout\stelling\sme\swhich\sbranch\syou',
- 'Pull\sis\snot\spossible\sbecause\syou\shave\sunmerged\sfiles',
- pexpect.TIMEOUT],
- timeout=300)
- #debug
- #main.log.report(self.name +": DEBUG: \n"+"git pull response: " + str(self.handle.before) + str(self.handle.after))
- if i==0:
- main.log.error(self.name + ": Git pull had some issue...")
+ i = self.handle.expect( [ 'fatal',
+ 'Username\sfor\s(.*):\s',
+ '\sfile(s*) changed,\s',
+ 'Already up-to-date',
+ 'Aborting',
+ 'You\sare\snot\scurrently\son\sa\sbranch',
+ 'You\sasked\sme\sto\spull\swithout\stelling\sme\swhich\sbranch\syou',
+ 'Pull\sis\snot\spossible\sbecause\syou\shave\sunmerged\sfiles',
+ pexpect.TIMEOUT ],
+ timeout=300 )
+ # debug
+ # main.log.report( self.name +": DEBUG: \n"+"git pull response: " +
+ # str( self.handle.before ) + str( self.handle.after ) )
+ if i == 0:
+ main.log.error( self.name + ": Git pull had some issue..." )
return main.ERROR
- elif i==1:
- main.log.error(self.name + ": Git Pull Asking for username. ")
+ elif i == 1:
+ main.log.error(
+ self.name +
+ ": Git Pull Asking for username. " )
return main.ERROR
- elif i==2:
- main.log.info(self.name + ": Git Pull - pulling repository now")
- self.handle.expect("ONOS\$", 120)
- return main.TRUE # So that only when git pull is done, we do mvn clean compile
- elif i==3:
- main.log.info(self.name + ": Git Pull - Already up to date")
+ elif i == 2:
+ main.log.info(
+ self.name +
+ ": Git Pull - pulling repository now" )
+ self.handle.expect( "ONOS\$", 120 )
+ return main.TRUE # So that only when git pull is done, we do mvn clean compile
+ elif i == 3:
+ main.log.info( self.name + ": Git Pull - Already up to date" )
return i
- elif i==4:
- main.log.info(self.name + ": Git Pull - Aborting... Are there conflicting git files?")
+ elif i == 4:
+ main.log.info(
+ self.name +
+ ": Git Pull - Aborting... Are there conflicting git files?" )
return main.ERROR
- elif i==5:
- main.log.info(self.name + ": Git Pull - You are not currently on a branch so git pull failed!")
+ elif i == 5:
+ main.log.info(
+ self.name +
+ ": Git Pull - You are not currently on a branch so git pull failed!" )
return main.ERROR
- elif i==6:
- main.log.info(self.name + ": Git Pull - You have not configured an upstream branch to pull from. Git pull failed!")
+ elif i == 6:
+ main.log.info(
+ self.name +
+ ": Git Pull - You have not configured an upstream branch to pull from. Git pull failed!" )
return main.ERROR
- elif i==7:
- main.log.info(self.name + ": Git Pull - Pull is not possible because you have unmerged files.")
+ elif i == 7:
+ main.log.info(
+ self.name +
+ ": Git Pull - Pull is not possible because you have unmerged files." )
return main.ERROR
- elif i==8:
- main.log.error(self.name + ": Git Pull - TIMEOUT")
- main.log.error(self.name + " Response was: " + str(self.handle.before))
+ elif i == 8:
+ main.log.error( self.name + ": Git Pull - TIMEOUT" )
+ main.log.error(
+ self.name + " Response was: " + str(
+ self.handle.before ) )
return main.ERROR
else:
- main.log.error(self.name + ": Git Pull - Unexpected response, check for pull errors")
+ main.log.error(
+ self.name +
+ ": Git Pull - Unexpected response, check for pull errors" )
return main.ERROR
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ self.name +
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def git_checkout(self, branch="master"):
- '''
+ def git_checkout( self, branch="master" ):
+ """
Assumes that "git pull" works without login
-
+
This function will perform a git git checkout on the ONOS instance.
- If used as git_checkout("branch") it will do git checkout of the "branch".
+ If used as git_checkout( "branch" ) it will do git checkout of the "branch".
Otherwise, this function will perform a git checkout of the master
- branch of the ONOS repository. If it has any problems, it will return
- main.ERROR.
- If the branch was already the specified branch, or the git checkout was
+ branch of the ONOS repository. If it has any problems, it will return
+ main.ERROR.
+ If the branch was already the specified branch, or the git checkout was
successful then the function will return main.TRUE.
- '''
+ """
try:
- self.handle.sendline("cd " + self.home)
- self.handle.expect("ONOS\$")
- main.log.info(self.name + ": Checking out git branch: " + branch + "...")
- cmd = "git checkout "+branch
- self.handle.sendline(cmd)
- self.handle.expect(cmd)
- i=self.handle.expect(['fatal',
- 'Username\sfor\s(.*):\s',
- 'Already\son\s\'',
- 'Switched\sto\sbranch\s\'' + str(branch),
- pexpect.TIMEOUT,
- 'error: Your local changes to the following files would be overwritten by checkout:',
- 'error: you need to resolve your current index first'],timeout=60)
+ self.handle.sendline( "cd " + self.home )
+ self.handle.expect( "ONOS\$" )
+ main.log.info(
+ self.name +
+ ": Checking out git branch: " +
+ branch +
+ "..." )
+ cmd = "git checkout " + branch
+ self.handle.sendline( cmd )
+ self.handle.expect( cmd )
+ i = self.handle.expect( [ 'fatal',
+ 'Username\sfor\s(.*):\s',
+ 'Already\son\s\'',
+ 'Switched\sto\sbranch\s\'' +
+ str( branch ),
+ pexpect.TIMEOUT,
+ 'error: Your local changes to the following files would be overwritten by checkout:',
+ 'error: you need to resolve your current index first' ], timeout=60 )
- if i==0:
- main.log.error(self.name + ": Git checkout had some issue...")
- main.log.error(self.name + ": " + self.handle.before)
+ if i == 0:
+ main.log.error(
+ self.name +
+ ": Git checkout had some issue..." )
+ main.log.error( self.name + ": " + self.handle.before )
return main.ERROR
- elif i==1:
- main.log.error(self.name + ": Git checkout asking for username."\
- +" Please configure your local git repository to be able "\
- +"to access your remote repository passwordlessly")
+ elif i == 1:
+ main.log.error( self.name + ": Git checkout asking for username."
+ + " Please configure your local git repository to be able "
+ + "to access your remote repository passwordlessly" )
return main.ERROR
- elif i==2:
- main.log.info(self.name + ": Git Checkout %s : Already on this branch" %branch)
- self.handle.expect("ONOS\$")
- #main.log.info("DEBUG: after checkout cmd = "+ self.handle.before)
+ elif i == 2:
+ main.log.info(
+ self.name +
+ ": Git Checkout %s : Already on this branch" %
+ branch )
+ self.handle.expect( "ONOS\$" )
+ # main.log.info( "DEBUG: after checkout cmd = "+
+ # self.handle.before )
return main.TRUE
- elif i==3:
- main.log.info(self.name + ": Git checkout %s - Switched to this branch" %branch)
- self.handle.expect("ONOS\$")
- #main.log.info("DEBUG: after checkout cmd = "+ self.handle.before)
+ elif i == 3:
+ main.log.info(
+ self.name +
+ ": Git checkout %s - Switched to this branch" %
+ branch )
+ self.handle.expect( "ONOS\$" )
+ # main.log.info( "DEBUG: after checkout cmd = "+
+ # self.handle.before )
return main.TRUE
- elif i==4:
- main.log.error(self.name + ": Git Checkout- TIMEOUT")
- main.log.error(self.name + " Response was: " + str(self.handle.before))
+ elif i == 4:
+ main.log.error( self.name + ": Git Checkout- TIMEOUT" )
+ main.log.error(
+ self.name + " Response was: " + str(
+ self.handle.before ) )
return main.ERROR
- elif i==5:
- self.handle.expect("Aborting")
- main.log.error(self.name + ": Git checkout error: \n" + \
- "Your local changes to the following files would be overwritten by checkout:" + \
- str(self.handle.before))
- self.handle.expect("ONOS\$")
+ elif i == 5:
+ self.handle.expect( "Aborting" )
+ main.log.error( self.name + ": Git checkout error: \n" +
+ "Your local changes to the following files would be overwritten by checkout:" +
+ str( self.handle.before ) )
+ self.handle.expect( "ONOS\$" )
return main.ERROR
- elif i==6:
- main.log.error(self.name + ": Git checkout error: \n" + \
- "You need to resolve your current index first:" + \
- str(self.handle.before))
- self.handle.expect("ONOS\$")
+ elif i == 6:
+ main.log.error( self.name + ": Git checkout error: \n" +
+ "You need to resolve your current index first:" +
+ str( self.handle.before ) )
+ self.handle.expect( "ONOS\$" )
return main.ERROR
else:
- main.log.error(self.name + ": Git Checkout - Unexpected response, check for pull errors")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error(
+ self.name +
+ ": Git Checkout - Unexpected response, check for pull errors" )
+ main.log.error( self.name + ": " + self.handle.before )
return main.ERROR
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ self.name +
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def get_version(self, report=False):
- '''
+ def get_version( self, report=False ):
+ """
Writes the COMMIT number to the report to be parsed by Jenkins data collecter.
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("cd " + self.home + "; git log -1 --pretty=fuller --decorate=short | grep -A 6 \"commit\" --color=never")
- #NOTE: for some reason there are backspaces inserted in this phrase when run from Jenkins on some tests
- self.handle.expect("never")
- self.handle.expect("\$")
- response=(self.name +": \n"+ str(self.handle.before + self.handle.after))
- self.handle.sendline("cd " + self.home)
- self.handle.expect("\$")
- lines=response.splitlines()
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline(
+ "cd " +
+ self.home +
+ "; git log -1 --pretty=fuller --decorate=short | grep -A 6 \"commit\" --color=never" )
+ # NOTE: for some reason there are backspaces inserted in this
+ # phrase when run from Jenkins on some tests
+ self.handle.expect( "never" )
+ self.handle.expect( "\$" )
+ response = ( self.name + ": \n" + str(
+ self.handle.before + self.handle.after ) )
+ self.handle.sendline( "cd " + self.home )
+ self.handle.expect( "\$" )
+ lines = response.splitlines()
for line in lines:
print line
if report:
- for line in lines[2:-1]:
- #Bracket replacement is for Wiki-compliant
- #formatting. '<' or '>' are interpreted
- #as xml specific tags that cause errors
- line = line.replace("<","[")
- line = line.replace(">","]")
- main.log.report("\t" + line)
- return lines[2]
+ for line in lines[ 2:-1 ]:
+ # Bracket replacement is for Wiki-compliant
+ # formatting. '<' or '>' are interpreted
+ # as xml specific tags that cause errors
+ line = line.replace( "<", "[" )
+ line = line.replace( ">", "]" )
+ main.log.report( "\t" + line )
+ return lines[ 2 ]
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except pexpect.TIMEOUT:
- main.log.error(self.name + ": TIMEOUT exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": TIMEOUT exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ self.name +
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
+ main.log.info(
+ ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" )
main.cleanup()
main.exit()
- def create_cell_file(self, bench_ip, file_name, mn_ip_addrs,
- extra_feature_string, *onos_ip_addrs):
- '''
+ def create_cell_file( self, bench_ip, file_name, mn_ip_addrs,
+ extra_feature_string, *onos_ip_addrs ):
+ """
Creates a cell file based on arguments
Required:
- * Bench IP address (bench_ip)
+ * Bench IP address ( bench_ip )
- Needed to copy the cell file over
- * File name of the cell file (file_name)
- * Mininet IP address (mn_ip_addrs)
- - Note that only 1 ip address is
+ * File name of the cell file ( file_name )
+ * Mininet IP address ( mn_ip_addrs )
+ - Note that only 1 ip address is
supported currently
- * ONOS IP addresses (onos_ip_addrs)
+ * ONOS IP addresses ( onos_ip_addrs )
- Must be passed in as last arguments
-
+
NOTE: Assumes cells are located at:
~/<self.home>/tools/test/cells/
- '''
-
- #Variable initialization
+ """
+ # Variable initialization
cell_directory = self.home + "/tools/test/cells/"
- #We want to create the cell file in the dependencies directory
- #of TestON first, then copy over to ONOS bench
+ # We want to create the cell file in the dependencies directory
+ # of TestON first, then copy over to ONOS bench
temp_directory = "/tmp/"
- #Create the cell file in the directory for writing (w+)
- cell_file = open(temp_directory+file_name , 'w+')
-
- #Feature string is hardcoded environment variables
- #That you may wish to use by default on startup.
- #Note that you may not want certain features listed
- #on here.
- core_feature_string = "export ONOS_FEATURES=webconsole,onos-api,"+\
- "onos-cli,onos-openflow,"+extra_feature_string
+ # Create the cell file in the directory for writing ( w+ )
+ cell_file = open( temp_directory + file_name, 'w+' )
+
+ # Feature string is hardcoded environment variables
+ # That you may wish to use by default on startup.
+ # Note that you may not want certain features listed
+ # on here.
+ core_feature_string = "export ONOS_FEATURES=webconsole,onos-api," +\
+ "onos-cli,onos-openflow," + extra_feature_string
mn_string = "export OCN="
onos_string = "export OC"
temp_count = 1
-
- #Create ONOS_NIC ip address prefix
- temp_onos_ip = onos_ip_addrs[0]
+
+ # Create ONOS_NIC ip address prefix
+ temp_onos_ip = onos_ip_addrs[ 0 ]
temp_list = []
- temp_list = temp_onos_ip.split(".")
- #Omit last element of list to format for NIC
- temp_list = temp_list[:-1]
- #Structure the nic string ip
- nic_addr = ".".join(temp_list) + ".*"
- onos_nic_string = "export ONOS_NIC="+nic_addr
+ temp_list = temp_onos_ip.split( "." )
+ # Omit last element of list to format for NIC
+ temp_list = temp_list[ :-1 ]
+ # Structure the nic string ip
+ nic_addr = ".".join( temp_list ) + ".*"
+ onos_nic_string = "export ONOS_NIC=" + nic_addr
try:
- #Start writing to file
- cell_file.write(onos_nic_string + "\n")
+ # Start writing to file
+ cell_file.write( onos_nic_string + "\n" )
for arg in onos_ip_addrs:
- #For each argument in onos_ip_addrs, write to file
- #Output should look like the following:
+ # For each argument in onos_ip_addrs, write to file
+ # Output should look like the following:
# export OC1="10.128.20.11"
# export OC2="10.128.20.12"
- cell_file.write(onos_string + str(temp_count) +
- "=" + "\"" + arg + "\"" + "\n" )
+ cell_file.write( onos_string + str( temp_count ) +
+ "=" + "\"" + arg + "\"" + "\n" )
temp_count = temp_count + 1
-
- cell_file.write(mn_string +"\""+ mn_ip_addrs +"\""+ "\n")
- cell_file.write(core_feature_string + "\n")
+
+ cell_file.write( mn_string + "\"" + mn_ip_addrs + "\"" + "\n" )
+ cell_file.write( core_feature_string + "\n" )
cell_file.close()
- #We use os.system to send the command to TestON cluster
- #to account for the case in which TestON is not located
- #on the same cluster as the ONOS bench
- #Note that even if TestON is located on the same cluster
- #as ONOS bench, you must setup passwordless ssh
- #between TestON and ONOS bench in order to automate the test.
- os.system("scp "+temp_directory+file_name+
- " admin@"+bench_ip+":"+cell_directory)
+ # We use os.system to send the command to TestON cluster
+ # to account for the case in which TestON is not located
+ # on the same cluster as the ONOS bench
+ # Note that even if TestON is located on the same cluster
+ # as ONOS bench, you must setup passwordless ssh
+ # between TestON and ONOS bench in order to automate the test.
+ os.system( "scp " + temp_directory + file_name +
+ " admin@" + bench_ip + ":" + cell_directory )
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name + ":::::::::")
+ main.log.info( self.name + ":::::::::" )
main.log.error( traceback.print_exc() )
- main.log.info(":::::::")
+ main.log.info( ":::::::" )
main.cleanup()
main.exit()
- def set_cell(self, cellname):
- '''
+ def set_cell( self, cellname ):
+ """
Calls 'cell <name>' to set the environment variables on ONOSbench
- '''
+ """
try:
if not cellname:
- main.log.error("Must define cellname")
+ main.log.error( "Must define cellname" )
main.cleanup()
main.exit()
else:
- self.handle.sendline("cell "+str(cellname))
- #Expect the cellname in the ONOS_CELL variable.
- #Note that this variable name is subject to change
+ self.handle.sendline( "cell " + str( cellname ) )
+ # Expect the cellname in the ONOS_CELL variable.
+ # Note that this variable name is subject to change
# and that this driver will have to change accordingly
- self.handle.expect("ONOS_CELL="+str(cellname))
+ self.handle.expect( "ONOS_CELL=" + str( cellname ) )
handle_before = self.handle.before
handle_after = self.handle.after
- #Get the rest of the handle
- self.handle.sendline("")
- self.handle.expect("\$")
+ # Get the rest of the handle
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
handle_more = self.handle.before
- main.log.info("Cell call returned: "+handle_before+
- handle_after + handle_more)
+ main.log.info( "Cell call returned: " + handle_before +
+ handle_after + handle_more )
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def verify_cell(self):
- '''
+ def verify_cell( self ):
+ """
Calls 'onos-verify-cell' to check for cell installation
- '''
- #TODO: Add meaningful expect value
+ """
+ # TODO: Add meaningful expect value
try:
- #Clean handle by sending empty and expecting $
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("onos-verify-cell")
- self.handle.expect("\$")
+ # Clean handle by sending empty and expecting $
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos-verify-cell" )
+ self.handle.expect( "\$" )
handle_before = self.handle.before
handle_after = self.handle.after
- #Get the rest of the handle
- self.handle.sendline("")
- self.handle.expect("\$")
+ # Get the rest of the handle
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
handle_more = self.handle.before
- main.log.info("Verify cell returned: "+handle_before+
- handle_after + handle_more)
+ main.log.info( "Verify cell returned: " + handle_before +
+ handle_after + handle_more )
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def onos_cli(self, ONOS_ip, cmdstr):
- '''
+ def onos_cli( self, ONOS_ip, cmdstr ):
+ """
Uses 'onos' command to send various ONOS CLI arguments.
Required:
* ONOS_ip: specify the ip of the cell machine
* cmdstr: specify the command string to send
-
- This function is intended to expose the entire karaf
+
+ This function is intended to expose the entire karaf
CLI commands for ONOS. Try to use this function first
before attempting to write a ONOS CLI specific driver
- function.
- You can see a list of available 'cmdstr' arguments
+ function.
+ You can see a list of available 'cmdstr' arguments
by starting onos, and typing in 'onos' to enter the
onos> CLI. Then, type 'help' to see the list of
- available commands.
- '''
+ available commands.
+ """
try:
if not ONOS_ip:
- main.log.error("You must specify the IP address")
+ main.log.error( "You must specify the IP address" )
return main.FALSE
if not cmdstr:
- main.log.error("You must specify the command string")
+ main.log.error( "You must specify the command string" )
return main.FALSE
- cmdstr = str(cmdstr)
- self.handle.sendline("")
- self.handle.expect("\$")
+ cmdstr = str( cmdstr )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
- self.handle.sendline("onos -w " + ONOS_ip + " " + cmdstr)
- self.handle.expect("\$")
+ self.handle.sendline( "onos -w " + ONOS_ip + " " + cmdstr )
+ self.handle.expect( "\$" )
handle_before = self.handle.before
print "handle_before = ", self.handle.before
- #handle_after = str(self.handle.after)
+ # handle_after = str( self.handle.after )
- #self.handle.sendline("")
- #self.handle.expect("\$")
- #handle_more = str(self.handle.before)
+ # self.handle.sendline( "" )
+ # self.handle.expect( "\$" )
+ # handle_more = str( self.handle.before )
- main.log.info("Command sent successfully")
+ main.log.info( "Command sent successfully" )
- #Obtain return handle that consists of result from
- #the onos command. The string may need to be
- #configured further.
- #return_string = handle_before + handle_after
+ # Obtain return handle that consists of result from
+ # the onos command. The string may need to be
+ # configured further.
+ # return_string = handle_before + handle_after
return_string = handle_before
print "return_string = ", return_string
return return_string
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def onos_install(self, options="-f", node = ""):
- '''
+ def onos_install( self, options="-f", node="" ):
+ """
Installs ONOS bits on the designated cell machine.
- If -f option is provided, it also forces an uninstall.
- Presently, install also includes onos-push-bits and
+ If -f option is provided, it also forces an uninstall.
+ Presently, install also includes onos-push-bits and
onos-config within.
- The node option allows you to selectively only push the jar
+ The node option allows you to selectively only push the jar
files to certain onos nodes
Returns: main.TRUE on success and main.FALSE on failure
- '''
+ """
try:
if options:
- self.handle.sendline("onos-install " + options + " " + node)
+ self.handle.sendline( "onos-install " + options + " " + node )
else:
- self.handle.sendline("onos-install "+node)
- self.handle.expect("onos-install ")
- #NOTE: this timeout may need to change depending on the network and size of ONOS
- i=self.handle.expect(["Network\sis\sunreachable",
- "onos\sstart/running,\sprocess",
- "ONOS\sis\salready\sinstalled",
- pexpect.TIMEOUT],timeout=60)
+ self.handle.sendline( "onos-install " + node )
+ self.handle.expect( "onos-install " )
+ # NOTE: this timeout may need to change depending on the network
+ # and size of ONOS
+ i = self.handle.expect( [ "Network\sis\sunreachable",
+ "onos\sstart/running,\sprocess",
+ "ONOS\sis\salready\sinstalled",
+ pexpect.TIMEOUT ], timeout=60 )
if i == 0:
- main.log.warn("Network is unreachable")
+ main.log.warn( "Network is unreachable" )
return main.FALSE
elif i == 1:
- main.log.info("ONOS was installed on " + node + " and started")
+ main.log.info(
+ "ONOS was installed on " +
+ node +
+ " and started" )
return main.TRUE
elif i == 2:
- main.log.info("ONOS is already installed on "+node)
+ main.log.info( "ONOS is already installed on " + node )
return main.TRUE
- elif i == 3:
- main.log.info("Installation of ONOS on " + node + " timed out")
+ elif i == 3:
+ main.log.info(
+ "Installation of ONOS on " +
+ node +
+ " timed out" )
return main.FALSE
-
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def onos_start(self, node_ip):
- '''
+ def onos_start( self, node_ip ):
+ """
Calls onos command: 'onos-service [<node-ip>] start'
This command is a remote management of the ONOS upstart daemon
- '''
-
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("onos-service "+str(node_ip)+
- " start")
- i = self.handle.expect([
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos-service " + str( node_ip ) +
+ " start" )
+ i = self.handle.expect( [
"Job\sis\salready\srunning",
"start/running",
"Unknown\sinstance",
- pexpect.TIMEOUT],timeout=120)
+ pexpect.TIMEOUT ], timeout=120 )
if i == 0:
- main.log.info("Service is already running")
+ main.log.info( "Service is already running" )
return main.TRUE
elif i == 1:
- main.log.info("ONOS service started")
+ main.log.info( "ONOS service started" )
return main.TRUE
else:
- main.log.error("ONOS service failed to start")
+ main.log.error( "ONOS service failed to start" )
main.cleanup()
main.exit()
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def onos_stop(self, node_ip):
- '''
+ def onos_stop( self, node_ip ):
+ """
Calls onos command: 'onos-service [<node-ip>] stop'
This command is a remote management of the ONOS upstart daemon
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("onos-service "+str(node_ip)+
- " stop")
- i = self.handle.expect([
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos-service " + str( node_ip ) +
+ " stop" )
+ i = self.handle.expect( [
"stop/waiting",
"Unknown\sinstance",
- pexpect.TIMEOUT],timeout=60)
+ pexpect.TIMEOUT ], timeout=60 )
if i == 0:
- main.log.info("ONOS service stopped")
+ main.log.info( "ONOS service stopped" )
return main.TRUE
elif i == 1:
- main.log.info("Unknown ONOS instance specified: "+
- str(node_ip))
+ main.log.info( "Unknown ONOS instance specified: " +
+ str( node_ip ) )
return main.FALSE
else:
- main.log.error("ONOS service failed to stop")
+ main.log.error( "ONOS service failed to stop" )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def onos_uninstall(self, node_ip=""):
- '''
+
+ def onos_uninstall( self, node_ip="" ):
+ """
Calls the command: 'onos-uninstall'
- Uninstalls ONOS from the designated cell machine, stopping
+ Uninstalls ONOS from the designated cell machine, stopping
if needed
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline( "onos-uninstall "+str(node_ip) )
- self.handle.expect("\$")
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos-uninstall " + str( node_ip ) )
+ self.handle.expect( "\$" )
- main.log.info("ONOS "+node_ip+" was uninstalled")
+ main.log.info( "ONOS " + node_ip + " was uninstalled" )
- #onos-uninstall command does not return any text
+ # onos-uninstall command does not return any text
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def onos_die(self, node_ip):
- '''
+ def onos_die( self, node_ip ):
+ """
Issues the command 'onos-die <node-ip>'
This command calls onos-kill and also stops the node
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- cmd_str = "onos-kill "+str(node_ip)
- self.handle.sendline(cmd_str)
- i = self.handle.expect([
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ cmd_str = "onos-kill " + str( node_ip )
+ self.handle.sendline( cmd_str )
+ i = self.handle.expect( [
"Killing\sONOS",
"ONOS\sprocess\sis\snot\srunning",
- pexpect.TIMEOUT], timeout=20)
+ pexpect.TIMEOUT ], timeout=20 )
if i == 0:
- main.log.info("ONOS instance "+str(node_ip)+
- " was killed and stopped")
+ main.log.info( "ONOS instance " + str( node_ip ) +
+ " was killed and stopped" )
return main.TRUE
elif i == 1:
- main.log.info("ONOS process was not running")
+ main.log.info( "ONOS process was not running" )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def onos_kill(self, node_ip):
- '''
+ def onos_kill( self, node_ip ):
+ """
Calls the command: 'onos-kill [<node-ip>]'
"Remotely, and unceremoniously kills the ONOS instance running on
the specified cell machine" - Tom V
- '''
-
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("onos-kill " + str(node_ip))
- i = self.handle.expect([
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos-kill " + str( node_ip ) )
+ i = self.handle.expect( [
"\$",
"No\sroute\sto\shost",
"password:",
- pexpect.TIMEOUT], timeout=20)
-
+ pexpect.TIMEOUT ], timeout=20 )
+
if i == 0:
- main.log.info("ONOS instance "+str(node_ip)+" was killed")
+ main.log.info(
+ "ONOS instance " + str(
+ node_ip ) + " was killed" )
return main.TRUE
elif i == 1:
- main.log.info("No route to host")
+ main.log.info( "No route to host" )
return main.FALSE
elif i == 2:
- main.log.info("Passwordless login for host: "+str(node_ip)+
- " not configured")
+ main.log.info( "Passwordless login for host: " + str( node_ip ) +
+ " not configured" )
return main.FALSE
else:
- main.log.info("ONOS instasnce was not killed")
+ main.log.info( "ONOS instasnce was not killed" )
return main.FALSE
-
+
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def onos_remove_raft_logs(self):
- '''
+ def onos_remove_raft_logs( self ):
+ """
Removes Raft / Copy cat files from ONOS to ensure
a cleaner environment.
Description:
Stops all ONOS defined in the cell,
wipes the raft / copycat log files
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("onos-remove-raft-logs")
- #Sometimes this command hangs
- i = self.handle.expect(["\$", pexpect.TIMEOUT],
- timeout=120)
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos-remove-raft-logs" )
+ # Sometimes this command hangs
+ i = self.handle.expect( [ "\$", pexpect.TIMEOUT ],
+ timeout=120 )
if i == 1:
- i = self.handle.expect(["\$", pexpect.TIMEOUT],
- timeout=120)
+ i = self.handle.expect( [ "\$", pexpect.TIMEOUT ],
+ timeout=120 )
if i == 1:
return main.FALSE
- self.handle.sendline("")
- self.handle.expect("\$")
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
return main.TRUE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def onos_start_network(self, mntopo):
- '''
- Calls the command 'onos-start-network [<mininet-topo>]
- "remotely starts the specified topology on the cell's
+ def onos_start_network( self, mntopo ):
+ """
+ Calls the command 'onos-start-network [ <mininet-topo> ]
+ "remotely starts the specified topology on the cell's
mininet machine against all controllers configured in the
- cell."
+ cell."
* Specify mininet topology file name for mntopo
* Topo files should be placed at:
~/<your-onos-directory>/tools/test/topos
-
+
NOTE: This function will take you to the mininet prompt
- '''
+ """
try:
if not mntopo:
- main.log.error("You must specify a topo file to execute")
+ main.log.error( "You must specify a topo file to execute" )
return main.FALSE
-
- mntopo = str(mntopo)
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("onos-start-network " + mntopo)
- self.handle.expect("mininet>")
- main.log.info("Network started, entered mininet prompt")
+ mntopo = str( mntopo )
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
- #TODO: Think about whether return is necessary or not
+ self.handle.sendline( "onos-start-network " + mntopo )
+ self.handle.expect( "mininet>" )
+ main.log.info( "Network started, entered mininet prompt" )
+
+ # TODO: Think about whether return is necessary or not
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
- def isup(self, node = ""):
- '''
- Run's onos-wait-for-start which only returns once ONOS is at run
- level 100(ready for use)
+ def isup( self, node="" ):
+ """
+ Run's onos-wait-for-start which only returns once ONOS is at run
+ level 100( ready for use )
Returns: main.TRUE if ONOS is running and main.FALSE on timeout
- '''
+ """
try:
- self.handle.sendline("onos-wait-for-start " + node )
- self.handle.expect("onos-wait-for-start")
- #NOTE: this timeout is arbitrary"
- i = self.handle.expect(["\$", pexpect.TIMEOUT], timeout = 120)
+ self.handle.sendline( "onos-wait-for-start " + node )
+ self.handle.expect( "onos-wait-for-start" )
+ # NOTE: this timeout is arbitrary"
+ i = self.handle.expect( [ "\$", pexpect.TIMEOUT ], timeout=120 )
if i == 0:
- main.log.info(self.name + ": " + node + " is up")
+ main.log.info( self.name + ": " + node + " is up" )
return main.TRUE
elif i == 1:
- #NOTE: since this function won't return until ONOS is ready,
+ # NOTE: since this function won't return until ONOS is ready,
# we will kill it on timeout
- main.log.error("ONOS has not started yet")
- self.handle.send("\x03") #Control-C
- self.handle.expect("\$")
+ main.log.error( "ONOS has not started yet" )
+ self.handle.send( "\x03" ) # Control-C
+ self.handle.expect( "\$" )
return main.FALSE
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def push_test_intents_shell(self, dpid_src, dpid_dst, num_intents,
- dir_file, onos_ip, num_mult="", app_id="", report=True,
- options=""):
- '''
+ def push_test_intents_shell( self, dpid_src, dpid_dst, num_intents,
+ dir_file, onos_ip, num_mult="", app_id="", report=True,
+ options="" ):
+ """
Description:
- Use the linux prompt to push test intents to
+ Use the linux prompt to push test intents to
better parallelize the results than the CLI
Required:
* dpid_src: specify source dpid
@@ -1002,105 +1061,107 @@
* dir_file: specify directory and file name to save
results
* onos_ip: specify the IP of ONOS to install on
- NOTE:
+ NOTE:
You must invoke this command at linux shell prompt
- '''
- try:
- #Create the string to sendline
+ """
+ try:
+ # Create the string to sendline
if options:
- base_cmd = "onos "+str(onos_ip)+" push-test-intents "+\
- options+" "
+ base_cmd = "onos " + str( onos_ip ) + " push-test-intents " +\
+ options + " "
else:
- base_cmd = "onos "+str(onos_ip)+" push-test-intents "
-
- add_dpid = base_cmd + str(dpid_src) + " " + str(dpid_dst)
+ base_cmd = "onos " + str( onos_ip ) + " push-test-intents "
+
+ add_dpid = base_cmd + str( dpid_src ) + " " + str( dpid_dst )
if not num_mult:
- add_intents = add_dpid + " " + str(num_intents)
+ add_intents = add_dpid + " " + str( num_intents )
elif num_mult:
- add_intents = add_dpid + " " + str(num_intents) + " " +\
- str(num_mult)
+ add_intents = add_dpid + " " + str( num_intents ) + " " +\
+ str( num_mult )
if app_id:
- add_app = add_intents + " " + str(app_id)
+ add_app = add_intents + " " + str( app_id )
else:
add_app = add_intents
if report:
- send_cmd = add_app + " > " + str(dir_file) + " &"
+ send_cmd = add_app + " > " + str( dir_file ) + " &"
else:
send_cmd = add_app + " &"
- main.log.info("Send cmd: "+send_cmd)
+ main.log.info( "Send cmd: " + send_cmd )
- self.handle.sendline(send_cmd)
+ self.handle.sendline( send_cmd )
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
- main.exit()
+ main.exit()
- def get_topology(self,topology_output):
- '''
+ def get_topology( self, topology_output ):
+ """
parses the onos:topology output
- Returns: a topology dict populated by the key values found in
+ Returns: a topology dict populated by the key values found in
the cli command.
- '''
-
+ """
try:
- #call the cli to get the topology summary
- #cmdstr = "onos:topology"
- #cli_result = self.onos_cli(ip, cmdstr)
- #print "cli_result = ", cli_result
+ # call the cli to get the topology summary
+ # cmdstr = "onos:topology"
+ # cli_result = self.onos_cli( ip, cmdstr )
+ # print "cli_result = ", cli_result
- #Parse the output
+ # Parse the output
topology = {}
- #for line in cli_result.split("\n"):
+ # for line in cli_result.split( "\n" ):
for line in topology_output.splitlines():
- if not line.startswith("time="):
+ if not line.startswith( "time=" ):
continue
- #else
- #print line
- for var in line.split(","):
- #print "'"+var+"'"
- #print "'"+var.strip()+"'"
- key, value = var.strip().split("=")
- topology[key] = value
- #print "topology = ", topology
- #devices = topology.get('devices', False)
- #print "devices = ", devices
- #links = topology.get('links', False)
- #print "links = ", links
- #SCCs = topology.get('SCC(s)', False)
- #print "SCCs = ", SCCs
- #paths = topology.get('paths', False)
- #print "paths = ", paths
+ # else
+ # print line
+ for var in line.split( "," ):
+ # print "'"+var+"'"
+ # print "'"+var.strip()+"'"
+ key, value = var.strip().split( "=" )
+ topology[ key ] = value
+ # print "topology = ", topology
+ # devices = topology.get( 'devices', False )
+ # print "devices = ", devices
+ # links = topology.get( 'links', False )
+ # print "links = ", links
+ # SCCs = topology.get( 'SCC(s)', False )
+ # print "SCCs = ", SCCs
+ # paths = topology.get( 'paths', False )
+ # print "paths = ", paths
return topology
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
-
-
- def check_status(self, topology_result, numoswitch, numolink, log_level="info"):
- '''
- Checks the number of swithes & links that ONOS sees against the
- supplied values. By default this will report to main.log, but the
+ def check_status(
+ self,
+ topology_result,
+ numoswitch,
+ numolink,
+ log_level="info" ):
+ """
+ Checks the number of swithes & links that ONOS sees against the
+ supplied values. By default this will report to main.log, but the
log level can be specifid.
-
+
Params: ip = ip used for the onos cli
numoswitch = expected number of switches
numlink = expected number of links
@@ -1109,283 +1170,280 @@
log_level can
- Returns: main.TRUE if the number of switchs and links are correct,
+ Returns: main.TRUE if the number of switchs and links are correct,
main.FALSE if the numer of switches and links is incorrect,
and main.ERROR otherwise
- '''
-
+ """
try:
- topology = self.get_topology(topology_result)
+ topology = self.get_topology( topology_result )
if topology == {}:
return main.ERROR
output = ""
- #Is the number of switches is what we expected
- devices = topology.get('devices',False)
- links = topology.get('links',False)
+ # Is the number of switches is what we expected
+ devices = topology.get( 'devices', False )
+ links = topology.get( 'links', False )
if devices == False or links == False:
return main.ERROR
- switch_check = ( int(devices) == int(numoswitch) )
- #Is the number of links is what we expected
- link_check = ( int(links) == int(numolink) )
- if (switch_check and link_check):
- #We expected the correct numbers
+ switch_check = ( int( devices ) == int( numoswitch ) )
+ # Is the number of links is what we expected
+ link_check = ( int( links ) == int( numolink ) )
+ if ( switch_check and link_check ):
+ # We expected the correct numbers
output = output + "The number of links and switches match "\
- + "what was expected"
+ + "what was expected"
result = main.TRUE
else:
output = output + \
- "The number of links and switches does not match what was expected"
+ "The number of links and switches does not match what was expected"
result = main.FALSE
output = output + "\n ONOS sees %i devices (%i expected) and %i links (%i expected)"\
- % ( int(devices), int(numoswitch), int(links), int(numolink) )
+ % ( int( devices ), int( numoswitch ), int( links ), int( numolink ) )
if log_level == "report":
- main.log.report(output)
+ main.log.report( output )
elif log_level == "warn":
- main.log.warn(output)
+ main.log.warn( output )
else:
- main.log.info(output)
- return result
+ main.log.info( output )
+ return result
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def tshark_pcap(self, interface, dir_file):
- '''
+ def tshark_pcap( self, interface, dir_file ):
+ """
Capture all packet activity and store in specified
directory/file
Required:
* interface: interface to capture
* dir: directory/filename to store pcap
- '''
- self.handle.sendline("")
- self.handle.expect("\$")
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
- self.handle.sendline("tshark -i "+str(interface)+
- " -t e -w "+str(dir_file)+ " &")
- self.handle.sendline("\r")
- self.handle.expect("Capturing on")
- self.handle.sendline("\r")
- self.handle.expect("\$")
+ self.handle.sendline( "tshark -i " + str( interface ) +
+ " -t e -w " + str( dir_file ) + " &" )
+ self.handle.sendline( "\r" )
+ self.handle.expect( "Capturing on" )
+ self.handle.sendline( "\r" )
+ self.handle.expect( "\$" )
- main.log.info("Tshark started capturing files on "+
- str(interface)+ " and saving to directory: "+
- str(dir_file))
+ main.log.info( "Tshark started capturing files on " +
+ str( interface ) + " and saving to directory: " +
+ str( dir_file ) )
-
- def run_onos_topo_cfg(self, instance_name, json_file):
- '''
+ def run_onos_topo_cfg( self, instance_name, json_file ):
+ """
On ONOS bench, run this command: ./~/ONOS/tools/test/bin/onos-topo-cfg $OC1 filename
which starts the rest and copies the json file to the onos instance
- '''
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("cd ~/ONOS/tools/test/bin")
- self.handle.expect("/bin$")
- cmd = "./onos-topo-cfg " +instance_name +" " +json_file
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "cd ~/ONOS/tools/test/bin" )
+ self.handle.expect( "/bin$" )
+ cmd = "./onos-topo-cfg " + instance_name + " " + json_file
print "cmd = ", cmd
- self.handle.sendline(cmd)
- self.handle.expect("\$")
- self.handle.sendline("cd ~")
- self.handle.expect("\$")
+ self.handle.sendline( cmd )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "cd ~" )
+ self.handle.expect( "\$" )
return main.TRUE
except:
return main.FALSE
-
- def tshark_grep(self, grep, directory, interface='eth0'):
- '''
+
+ def tshark_grep( self, grep, directory, interface='eth0' ):
+ """
Required:
- * grep string
+ * grep string
* directory to store results
Optional:
* interface - default: eth0
Description:
Uses tshark command to grep specific group of packets
and stores the results to specified directory.
- The timestamp is hardcoded to be in epoch
- '''
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("")
- self.handle.sendline("tshark -i "+str(interface)+
- " -t e | grep --line-buffered \""+str(grep)+"\" >"+directory+" &")
- self.handle.sendline("\r")
- self.handle.expect("Capturing on")
- self.handle.sendline("\r")
- self.handle.expect("\$")
+ The timestamp is hardcoded to be in epoch
+ """
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "" )
+ self.handle.sendline( "tshark -i " + str( interface ) +
+ " -t e | grep --line-buffered \"" + str(grep) + "\" >" + directory + " &" )
+ self.handle.sendline( "\r" )
+ self.handle.expect( "Capturing on" )
+ self.handle.sendline( "\r" )
+ self.handle.expect( "\$" )
- def tshark_stop(self):
- '''
+ def tshark_stop( self ):
+ """
Removes wireshark files from /tmp and kills all tshark processes
- '''
- #Remove all pcap from previous captures
- self.execute(cmd="sudo rm /tmp/wireshark*")
- self.handle.sendline("")
- self.handle.sendline("sudo kill -9 `ps -ef | grep \"tshark -i\" |"+
- " grep -v grep | awk '{print $2}'`")
- self.handle.sendline("")
- main.log.info("Tshark stopped")
+ """
+ # Remove all pcap from previous captures
+ self.execute( cmd="sudo rm /tmp/wireshark*" )
+ self.handle.sendline( "" )
+ self.handle.sendline( "sudo kill -9 `ps -ef | grep \"tshark -i\" |" +
+ " grep -v grep | awk '{print $2}'`" )
+ self.handle.sendline( "" )
+ main.log.info( "Tshark stopped" )
- def ptpd(self, args):
- '''
+ def ptpd( self, args ):
+ """
Initiate ptp with user-specified args.
Required:
* args: specify string of args after command
'sudo ptpd'
- '''
+ """
try:
- self.handle.sendline("sudo ptpd "+str(args))
- i = self.handle.expect([
+ self.handle.sendline( "sudo ptpd " + str( args ) )
+ i = self.handle.expect( [
"Multiple",
"Error",
- "\$"])
- self.handle.expect("\$")
+ "\$" ] )
+ self.handle.expect( "\$" )
if i == 0:
handle = self.handle.before
- main.log.info("ptpd returned an error: "+
- str(handle))
+ main.log.info( "ptpd returned an error: " +
+ str( handle ) )
return handle
elif i == 1:
handle = self.handle.before
- main.log.error("ptpd returned an error: "+
- str(handle))
+ main.log.error( "ptpd returned an error: " +
+ str( handle ) )
return handle
else:
return main.TRUE
-
+
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
- def cp_logs_to_dir(self, log_to_copy,
- dest_dir, copy_file_name=""):
- '''
- Copies logs to a desired directory.
+ def cp_logs_to_dir( self, log_to_copy,
+ dest_dir, copy_file_name="" ):
+ """
+ Copies logs to a desired directory.
Current implementation of ONOS deletes its karaf
logs on every iteration. For debugging purposes,
- you may want to use this function to capture
- certain karaf logs. (or any other logs if needed)
+ you may want to use this function to capture
+ certain karaf logs. ( or any other logs if needed )
Localtime will be attached to the filename
Required:
* log_to_copy: specify directory and log name to
copy.
- ex) /opt/onos/log/karaf.log.1
+ ex ) /opt/onos/log/karaf.log.1
For copying multiple files, leave copy_file_name
- empty and only specify dest_dir -
- ex) /opt/onos/log/karaf*
+ empty and only specify dest_dir -
+ ex ) /opt/onos/log/karaf*
* dest_dir: specify directory to copy to.
- ex) /tmp/
- Optional:
+ ex ) /tmp/
+ Optional:
* copy_file_name: If you want to rename the log
file, specify copy_file_name. This will not work
with multiple file copying
- '''
+ """
try:
- localtime = time.strftime('%x %X')
- localtime = localtime.replace("/","")
- localtime = localtime.replace(" ","_")
- localtime = localtime.replace(":","")
- if dest_dir[-1:] != "/":
+ localtime = time.strftime( '%x %X' )
+ localtime = localtime.replace( "/", "" )
+ localtime = localtime.replace( " ", "_" )
+ localtime = localtime.replace( ":", "" )
+ if dest_dir[ -1: ] != "/":
dest_dir += "/"
if copy_file_name:
- self.handle.sendline("cp "+str(log_to_copy)+
- " "+str(dest_dir)+str(copy_file_name)+
- localtime)
- self.handle.expect("cp")
- self.handle.expect("\$")
+ self.handle.sendline( "cp " + str( log_to_copy ) +
+ " " + str( dest_dir ) + str( copy_file_name ) +
+ localtime )
+ self.handle.expect( "cp" )
+ self.handle.expect( "\$" )
else:
- self.handle.sendline("cp "+str(log_to_copy)+
- " "+str(dest_dir))
- self.handle.expect("cp")
- self.handle.expect("\$")
-
- return self.handle.before
-
- except pexpect.EOF:
- main.log.error("Copying files failed")
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- except:
- main.log.error("Copying files failed")
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ self.handle.sendline( "cp " + str( log_to_copy ) +
+ " " + str( dest_dir ) )
+ self.handle.expect( "cp" )
+ self.handle.expect( "\$" )
- def check_logs(self, onos_ip):
- '''
+ return self.handle.before
+
+ except pexpect.EOF:
+ main.log.error( "Copying files failed" )
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
+ except:
+ main.log.error( "Copying files failed" )
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
+
+ def check_logs( self, onos_ip ):
+ """
runs onos-check-logs on the given onos node
returns the response
- '''
+ """
try:
- cmd = "onos-check-logs " + str(onos_ip)
- self.handle.sendline(cmd)
- self.handle.expect(cmd)
- self.handle.expect("\$")
+ cmd = "onos-check-logs " + str( onos_ip )
+ self.handle.sendline( cmd )
+ self.handle.expect( cmd )
+ self.handle.expect( "\$" )
response = self.handle.before
return response
except pexpect.EOF:
- main.log.error("Lost ssh connection")
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( "Lost ssh connection" )
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
except:
- main.log.error("Some error in check_logs:")
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.error( "Some error in check_logs:" )
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
- def onos_status(self, node=""):
- '''
+ def onos_status( self, node="" ):
+ """
Calls onos command: 'onos-service [<node-ip>] status'
- '''
-
+ """
try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("onos-service "+str(node)+
- " status")
- i = self.handle.expect([
+ self.handle.sendline( "" )
+ self.handle.expect( "\$" )
+ self.handle.sendline( "onos-service " + str( node ) +
+ " status" )
+ i = self.handle.expect( [
"start/running",
"stop/waiting",
- pexpect.TIMEOUT],timeout=120)
+ pexpect.TIMEOUT ], timeout=120 )
if i == 0:
- main.log.info("ONOS is running")
+ main.log.info( "ONOS is running" )
return main.TRUE
elif i == 1:
- main.log.info("ONOS is stopped")
+ main.log.info( "ONOS is stopped" )
return main.FALSE
else:
- main.log.error("ONOS service failed to check the status")
+ main.log.error( "ONOS service failed to check the status" )
main.cleanup()
main.exit()
except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
+ main.log.error( self.name + ": EOF exception found" )
+ main.log.error( self.name + ": " + self.handle.before )
main.cleanup()
main.exit()
except:
- main.log.info(self.name+" ::::::")
- main.log.error( traceback.print_exc())
- main.log.info(self.name+" ::::::")
+ main.log.info( self.name + " ::::::" )
+ main.log.error( traceback.print_exc() )
+ main.log.info( self.name + " ::::::" )
main.cleanup()
main.exit()
diff --git a/TestON/drivers/common/cli/quaggaclidriver.py b/TestON/drivers/common/cli/quaggaclidriver.py
index 8314941..28f95af 100644
--- a/TestON/drivers/common/cli/quaggaclidriver.py
+++ b/TestON/drivers/common/cli/quaggaclidriver.py
@@ -2,93 +2,111 @@
import time
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
+import sys
+import signal
import sys
import re
import json
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class QuaggaCliDriver(CLI):
- def __init__(self):
- super(CLI, self).__init__()
+class QuaggaCliDriver( CLI ):
+
+ def __init__( self ):
+ super( CLI, self ).__init__()
# TODO: simplify this method
- def connect(self, **connectargs):
+ def connect( self, **connectargs ):
for key in connectargs:
- vars(self)[key] = connectargs[key]
+ vars( self )[ key ] = connectargs[ key ]
- self.name = self.options['name']
- # self.handle = super(QuaggaCliDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
- self.handle = super(QuaggaCliDriver, self).connect(user_name=self.user_name, ip_address="1.1.1.1", port=self.port, pwd=self.pwd)
- main.log.info("connect parameters:" + str(self.user_name) + ";" + str(self.ip_address) + ";" + str(self.port) + ";" + str(self.pwd))
+ self.name = self.options[ 'name' ]
+ # self.handle = super( QuaggaCliDriver,self ).connect(
+ # user_name=self.user_name, ip_address=self.ip_address,port=self.port,
+ # pwd=self.pwd )
+ self.handle = super(
+ QuaggaCliDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address="1.1.1.1",
+ port=self.port,
+ pwd=self.pwd )
+ main.log.info(
+ "connect parameters:" + str(
+ self.user_name ) + ";" + str(
+ self.ip_address ) + ";" + str(
+ self.port ) + ";" + str(
+ self.pwd ) )
if self.handle:
- #self.handle.expect("",timeout=10)
- #self.handle.expect("\$",timeout=10)
- self.handle.sendline("telnet localhost 2605")
- #self.handle.expect("Password:", timeout=5)
- self.handle.expect("Password:")
- self.handle.sendline("hello")
- #self.handle.expect("bgpd", timeout=5)
- self.handle.expect("bgpd")
- self.handle.sendline("enable")
- #self.handle.expect("bgpd#", timeout=5)
- self.handle.expect("bgpd#")
+ # self.handle.expect( "",timeout=10 )
+ # self.handle.expect( "\$",timeout=10 )
+ self.handle.sendline( "telnet localhost 2605" )
+ # self.handle.expect( "Password:", timeout=5 )
+ self.handle.expect( "Password:" )
+ self.handle.sendline( "hello" )
+ # self.handle.expect( "bgpd", timeout=5 )
+ self.handle.expect( "bgpd" )
+ self.handle.sendline( "enable" )
+ # self.handle.expect( "bgpd#", timeout=5 )
+ self.handle.expect( "bgpd#" )
return self.handle
- else :
- main.log.info("NO HANDLE")
+ else:
+ main.log.info( "NO HANDLE" )
return main.FALSE
- def loginQuagga(self, ip_address):
- self.name = self.options['name']
- self.handle = super(QuaggaCliDriver, self).connect(
+ def loginQuagga( self, ip_address ):
+ self.name = self.options[ 'name' ]
+ self.handle = super( QuaggaCliDriver, self ).connect(
user_name=self.user_name, ip_address=ip_address,
- port=self.port, pwd=self.pwd)
- main.log.info("connect parameters:" + str(self.user_name) + ";"
- + str(self.ip_address) + ";" + str(self.port) + ";" + str(self.pwd))
+ port=self.port, pwd=self.pwd )
+ main.log.info( "connect parameters:" + str( self.user_name ) + ";"
+ + str( self.ip_address ) + ";" + str( self.port ) + ";" + str( self.pwd ) )
if self.handle:
- #self.handle.expect("")
- #self.handle.expect("\$")
- self.handle.sendline("telnet localhost 2605")
- #self.handle.expect("Password:", timeout=5)
- self.handle.expect("Password:")
- self.handle.sendline("hello")
- #self.handle.expect("bgpd", timeout=5)
- self.handle.expect("bgpd")
- self.handle.sendline("enable")
- #self.handle.expect("bgpd#", timeout=5)
- self.handle.expect("bgpd#")
- main.log.info("I in quagga on host " + str(ip_address))
+ # self.handle.expect( "" )
+ # self.handle.expect( "\$" )
+ self.handle.sendline( "telnet localhost 2605" )
+ # self.handle.expect( "Password:", timeout=5 )
+ self.handle.expect( "Password:" )
+ self.handle.sendline( "hello" )
+ # self.handle.expect( "bgpd", timeout=5 )
+ self.handle.expect( "bgpd" )
+ self.handle.sendline( "enable" )
+ # self.handle.expect( "bgpd#", timeout=5 )
+ self.handle.expect( "bgpd#" )
+ main.log.info( "I in quagga on host " + str( ip_address ) )
return self.handle
else:
- main.log.info("NO HANDLE")
+ main.log.info( "NO HANDLE" )
return main.FALSE
- def enter_config(self, asn):
- main.log.info("I am in enter_config method!")
+ def enter_config( self, asn ):
+ main.log.info( "I am in enter_config method!" )
try:
- self.handle.sendline("")
- self.handle.expect("bgpd#")
+ self.handle.sendline( "" )
+ self.handle.expect( "bgpd#" )
except:
- main.log.warn("Probably not currently in enable mode!")
+ main.log.warn( "Probably not currently in enable mode!" )
self.disconnect()
return main.FALSE
- self.handle.sendline("configure terminal")
- self.handle.expect("config", timeout=5)
- routerAS = "router bgp " + str(asn)
+ self.handle.sendline( "configure terminal" )
+ self.handle.expect( "config", timeout=5 )
+ routerAS = "router bgp " + str( asn )
try:
- self.handle.sendline(routerAS)
- self.handle.expect("config-router", timeout=5)
+ self.handle.sendline( routerAS )
+ self.handle.expect( "config-router", timeout=5 )
return main.TRUE
except:
return main.FALSE
- def generate_prefixes(self, net, numRoutes):
- main.log.info("I am in generate_prefixes method!")
+ def generate_prefixes( self, net, numRoutes ):
+ main.log.info( "I am in generate_prefixes method!" )
# each IP prefix will be composed by "net" + "." + m + "." + n + "." + x
# the length of each IP prefix is 24
@@ -97,248 +115,298 @@
m = numRoutes / 256
n = numRoutes % 256
- for i in range(0, m):
- for j in range(0, 256):
- network = str(net) + "." + str(i) + "." + str(j) + ".0/24"
- routes.append(network)
+ for i in range( 0, m ):
+ for j in range( 0, 256 ):
+ network = str(
+ net ) + "." + str(
+ i ) + "." + str(
+ j ) + ".0/24"
+ routes.append( network )
routes_gen = routes_gen + 1
- for j in range(0, n):
- network = str(net) + "." + str(m) + "." + str(j) + ".0/24"
- routes.append(network)
+ for j in range( 0, n ):
+ network = str( net ) + "." + str( m ) + "." + str( j ) + ".0/24"
+ routes.append( network )
routes_gen = routes_gen + 1
if routes_gen == numRoutes:
- main.log.info("Successfully generated " + str(numRoutes)
- + " prefixes!")
+ main.log.info( "Successfully generated " + str( numRoutes )
+ + " prefixes!" )
return routes
return main.FALSE
- # This method generates a multiple to single point intent(MultiPointToSinglePointIntent) for a given route
- def generate_expected_singleRouteIntent(self, prefix, nextHop, nextHopMac, sdnip_data):
+ # This method generates a multiple to single point intent(
+ # MultiPointToSinglePointIntent ) for a given route
+ def generate_expected_singleRouteIntent( self, prefix, nextHop, nextHopMac, sdnip_data ):
ingress = []
egress = ""
- for peer in sdnip_data['bgpPeers']:
- if peer['ipAddress'] == nextHop:
- egress = "of:" + str(peer['attachmentDpid']).replace(":", "") + ":" + str(peer['attachmentPort'])
+ for peer in sdnip_data[ 'bgpPeers' ]:
+ if peer[ 'ipAddress' ] == nextHop:
+ egress = "of:" + str( peer[ 'attachmentDpid' ] ).replace( ":", "" ) + ":" + str( peer[ 'attachmentPort' ] )
else:
- ingress.append("of:" + str(peer['attachmentDpid']).replace(":", "") + ":" + str(peer['attachmentPort']))
+ ingress.append( "of:" + \
+ str( peer[ 'attachmentDpid' ] ).replace( ":",
+ "" ) + ":" + str( peer[ 'attachmentPort' ] ) )
selector = "ETH_TYPE{ethType=800},IPV4_DST{ip=" + prefix + "}"
- treatment = "[ETH_DST{mac=" + str(nextHopMac) + "}]"
+ treatment = "[ETH_DST{mac=" + str( nextHopMac ) + "}]"
- intent = egress + "/" + str(sorted(ingress)) + "/" + selector + "/" + treatment
+ intent = egress + "/" + \
+ str( sorted( ingress ) ) + "/" + selector + "/" + treatment
return intent
- def generate_expected_onePeerRouteIntents(self, prefixes, nextHop, nextHopMac, sdnip_json_file_path):
+ def generate_expected_onePeerRouteIntents( self, prefixes, nextHop, nextHopMac, sdnip_json_file_path ):
intents = []
- sdnip_json_file = open(sdnip_json_file_path).read()
+ sdnip_json_file = open( sdnip_json_file_path ).read()
- sdnip_data = json.loads(sdnip_json_file)
+ sdnip_data = json.loads( sdnip_json_file )
for prefix in prefixes:
- intents.append(self.generate_expected_singleRouteIntent(prefix, nextHop, nextHopMac, sdnip_data))
- return sorted(intents)
+ intents.append(
+ self.generate_expected_singleRouteIntent(
+ prefix,
+ nextHop,
+ nextHopMac,
+ sdnip_data ) )
+ return sorted( intents )
# TODO
# This method generates all expected route intents for all BGP peers
- def generate_expected_routeIntents(self):
+ def generate_expected_routeIntents( self ):
intents = []
return intents
# This method extracts all actual routes from ONOS CLI
- def extract_actual_routes(self, get_routes_result):
- routes_json_obj = json.loads(get_routes_result)
+ def extract_actual_routes( self, get_routes_result ):
+ routes_json_obj = json.loads( get_routes_result )
allRoutes_actual = []
for route in routes_json_obj:
- if route['prefix'] == '172.16.10.0/24':
+ if route[ 'prefix' ] == '172.16.10.0/24':
continue
- allRoutes_actual.append(route['prefix'] + "/" + route['nextHop'])
+ allRoutes_actual.append(
+ route[ 'prefix' ] + "/" + route[ 'nextHop' ] )
- return sorted(allRoutes_actual)
+ return sorted( allRoutes_actual )
# This method extracts all actual route intents from ONOS CLI
- def extract_actual_routeIntents(self, get_intents_result):
+ def extract_actual_routeIntents( self, get_intents_result ):
intents = []
# TODO: delete the line below when change to Mininet demo script
- # get_intents_result=open("../tests/SdnIpTest/intents.json").read()
- intents_json_obj = json.loads(get_intents_result)
+ # get_intents_result=open( "../tests/SdnIpTest/intents.json" ).read()
+ intents_json_obj = json.loads( get_intents_result )
for intent in intents_json_obj:
- if intent['appId'] != "org.onosproject.sdnip" :
+ if intent[ 'appId' ] != "org.onosproject.sdnip":
continue
- if intent['type'] == "MultiPointToSinglePointIntent" and intent['state'] == 'INSTALLED':
- egress = str(intent['egress']['device']) + ":" + str(intent['egress']['port'])
+ if intent[ 'type' ] == "MultiPointToSinglePointIntent" and intent[ 'state' ] == 'INSTALLED':
+ egress = str( intent[ 'egress' ][ 'device' ] ) + ":" + str(
+ intent[ 'egress' ][ 'port' ] )
ingress = []
- for attachmentPoint in intent['ingress']:
- ingress.append(str(attachmentPoint['device']) + ":" + str(attachmentPoint['port']))
+ for attachmentPoint in intent[ 'ingress' ]:
+ ingress.append(
+ str( attachmentPoint[ 'device' ] ) + ":" + str( attachmentPoint[ 'port' ] ) )
- selector = intent['selector'].replace("[" , "").replace("]" , "").replace(" ", "")
- if str(selector).startswith("IPV4"):
- str1, str2 = str(selector).split(",")
+ selector = intent[ 'selector' ].replace(
+ "[", "" ).replace( "]", "" ).replace( " ", "" )
+ if str( selector ).startswith( "IPV4" ):
+ str1, str2 = str( selector ).split( "," )
selector = str2 + "," + str1
- intent = egress + "/" + str(sorted(ingress)) + "/" + selector + "/" + intent['treatment']
- intents.append(intent)
- return sorted(intents)
+ intent = egress + "/" + \
+ str( sorted( ingress ) ) + "/" + \
+ selector + "/" + intent[ 'treatment' ]
+ intents.append( intent )
+ return sorted( intents )
# This method extracts all actual BGP intents from ONOS CLI
- def extract_actual_bgpIntents(self, get_intents_result):
+ def extract_actual_bgpIntents( self, get_intents_result ):
intents = []
# TODO: delete the line below when change to Mininet demo script
- # get_intents_result=open("../tests/SdnIpTest/intents.json").read()
- intents_json_obj = json.loads(get_intents_result)
+ # get_intents_result=open( "../tests/SdnIpTest/intents.json" ).read()
+ intents_json_obj = json.loads( get_intents_result )
for intent in intents_json_obj:
- if intent['appId'] != "org.onosproject.sdnip":
+ if intent[ 'appId' ] != "org.onosproject.sdnip":
continue
- if intent['type'] == "PointToPointIntent" and "protocol=6" in str(intent['selector']):
- ingress = str(intent['ingress']['device']) + ":" + str(intent['ingress']['port'])
- egress = str(intent['egress']['device']) + ":" + str(intent['egress']['port'])
- selector = str(intent['selector']).replace(" ", "").replace("[", "").replace("]", "").split(",")
- intent = ingress + "/" + egress + "/" + str(sorted(selector))
- intents.append(intent)
+ if intent[ 'type' ] == "PointToPointIntent" and "protocol=6" in str( intent[ 'selector' ] ):
+ ingress = str( intent[ 'ingress' ][ 'device' ] ) + ":" + str(
+ intent[ 'ingress' ][ 'port' ] )
+ egress = str( intent[ 'egress' ][ 'device' ] ) + ":" + str(
+ intent[ 'egress' ][ 'port' ] )
+ selector = str(
+ intent[ 'selector' ] ).replace( " ", "" ).replace( "[", "" ).replace( "]", "" ).split( "," )
+ intent = ingress + "/" + egress + \
+ "/" + str( sorted( selector ) )
+ intents.append( intent )
- return sorted(intents)
+ return sorted( intents )
- # This method generates a single point to single point intent(PointToPointIntent) for BGP path
- def generate_expected_bgpIntents(self, sdnip_json_file_path):
+ # This method generates a single point to single point intent(
+ # PointToPointIntent ) for BGP path
+ def generate_expected_bgpIntents( self, sdnip_json_file_path ):
from operator import eq
- sdnip_json_file = open(sdnip_json_file_path).read()
- sdnip_data = json.loads(sdnip_json_file)
+ sdnip_json_file = open( sdnip_json_file_path ).read()
+ sdnip_data = json.loads( sdnip_json_file )
intents = []
bgpPeerAttachmentPoint = ""
- bgpSpeakerAttachmentPoint = "of:" + str(sdnip_data['bgpSpeakers'][0]['attachmentDpid']).replace(":", "") + ":" + str(sdnip_data['bgpSpeakers'][0]['attachmentPort'])
- for peer in sdnip_data['bgpPeers']:
- bgpPeerAttachmentPoint = "of:" + str(peer['attachmentDpid']).replace(":", "") + ":" + str(peer['attachmentPort'])
+ bgpSpeakerAttachmentPoint = "of:" + str(
+ sdnip_data[ 'bgpSpeakers' ][ 0 ][ 'attachmentDpid' ] ).replace( ":",
+ "" ) + ":" + str( sdnip_data[ 'bgpSpeakers' ][ 0 ][ 'attachmentPort' ] )
+ for peer in sdnip_data[ 'bgpPeers' ]:
+ bgpPeerAttachmentPoint = "of:" + str(
+ peer[ 'attachmentDpid' ] ).replace( ":", "" ) + ":" + str( peer[ 'attachmentPort' ] )
# find out the BGP speaker IP address for this BGP peer
bgpSpeakerIpAddress = ""
- for interfaceAddress in sdnip_data['bgpSpeakers'][0]['interfaceAddresses']:
- # if eq(interfaceAddress['interfaceDpid'],sdnip_data['bgpSpeakers'][0]['attachmentDpid']) and eq(interfaceAddress['interfacePort'], sdnip_data['bgpSpeakers'][0]['attachmentPort']):
- if eq(interfaceAddress['interfaceDpid'], peer['attachmentDpid']) and eq(interfaceAddress['interfacePort'], peer['attachmentPort']):
- bgpSpeakerIpAddress = interfaceAddress['ipAddress']
+ for interfaceAddress in sdnip_data[ 'bgpSpeakers' ][ 0 ][ 'interfaceAddresses' ]:
+ # if eq( interfaceAddress[ 'interfaceDpid' ],sdnip_data[
+ # 'bgpSpeakers' ][ 0 ][ 'attachmentDpid' ] ) and eq(
+ # interfaceAddress[ 'interfacePort' ], sdnip_data[
+ # 'bgpSpeakers' ][ 0 ][ 'attachmentPort' ] ):
+ if eq( interfaceAddress[ 'interfaceDpid' ], peer[ 'attachmentDpid' ] ) and eq( interfaceAddress[ 'interfacePort' ], peer[ 'attachmentPort' ] ):
+ bgpSpeakerIpAddress = interfaceAddress[ 'ipAddress' ]
break
else:
continue
- # from bgpSpeakerAttachmentPoint to bgpPeerAttachmentPoint direction
- selector_str = "IPV4_SRC{ip=" + bgpSpeakerIpAddress + "/32}," + "IPV4_DST{ip=" + peer['ipAddress'] + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_DST{tcpPort=179}"
- selector = selector_str.replace(" ", "").replace("[", "").replace("]", "").split(",")
- intent = bgpSpeakerAttachmentPoint + "/" + bgpPeerAttachmentPoint + "/" + str(sorted(selector))
- intents.append(intent)
+ # from bgpSpeakerAttachmentPoint to bgpPeerAttachmentPoint
+ # direction
+ selector_str = "IPV4_SRC{ip=" + bgpSpeakerIpAddress + "/32}," + "IPV4_DST{ip=" + peer[
+ 'ipAddress' ] + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_DST{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpSpeakerAttachmentPoint + "/" + \
+ bgpPeerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
- selector_str = "IPV4_SRC{ip=" + bgpSpeakerIpAddress + "/32}," + "IPV4_DST{ip=" + peer['ipAddress'] + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_SRC{tcpPort=179}"
- selector = selector_str.replace(" ", "").replace("[", "").replace("]", "").split(",")
- intent = bgpSpeakerAttachmentPoint + "/" + bgpPeerAttachmentPoint + "/" + str(sorted(selector))
- intents.append(intent)
+ selector_str = "IPV4_SRC{ip=" + bgpSpeakerIpAddress + "/32}," + "IPV4_DST{ip=" + peer[
+ 'ipAddress' ] + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_SRC{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpSpeakerAttachmentPoint + "/" + \
+ bgpPeerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
- # from bgpPeerAttachmentPoint to bgpSpeakerAttachmentPoint direction
- selector_str = "IPV4_SRC{ip=" + peer['ipAddress'] + "/32}," + "IPV4_DST{ip=" + bgpSpeakerIpAddress + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_DST{tcpPort=179}"
- selector = selector_str.replace(" ", "").replace("[", "").replace("]", "").split(",")
- intent = bgpPeerAttachmentPoint + "/" + bgpSpeakerAttachmentPoint + "/" + str(sorted(selector))
- intents.append(intent)
+ # from bgpPeerAttachmentPoint to bgpSpeakerAttachmentPoint
+ # direction
+ selector_str = "IPV4_SRC{ip=" + peer[ 'ipAddress' ] + "/32}," + "IPV4_DST{ip=" + bgpSpeakerIpAddress + "/32}," + \
+ "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_DST{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpPeerAttachmentPoint + "/" + \
+ bgpSpeakerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
- selector_str = "IPV4_SRC{ip=" + peer['ipAddress'] + "/32}," + "IPV4_DST{ip=" + bgpSpeakerIpAddress + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_SRC{tcpPort=179}"
- selector = selector_str.replace(" ", "").replace("[", "").replace("]", "").split(",")
- intent = bgpPeerAttachmentPoint + "/" + bgpSpeakerAttachmentPoint + "/" + str(sorted(selector))
- intents.append(intent)
+ selector_str = "IPV4_SRC{ip=" + peer[ 'ipAddress' ] + "/32}," + "IPV4_DST{ip=" + bgpSpeakerIpAddress + "/32}," + \
+ "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_SRC{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpPeerAttachmentPoint + "/" + \
+ bgpSpeakerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
- return sorted(intents)
+ return sorted( intents )
- def add_routes(self, routes, routeRate):
- main.log.info("I am in add_routes method!")
+ def add_routes( self, routes, routeRate ):
+ main.log.info( "I am in add_routes method!" )
routes_added = 0
try:
- self.handle.sendline("")
- # self.handle.expect("config-router")
- self.handle.expect("config-router", timeout=5)
+ self.handle.sendline( "" )
+ # self.handle.expect( "config-router" )
+ self.handle.expect( "config-router", timeout=5 )
except:
- main.log.warn("Probably not in config-router mode!")
+ main.log.warn( "Probably not in config-router mode!" )
self.disconnect()
- main.log.info("Start to add routes")
+ main.log.info( "Start to add routes" )
- for i in range(0, len(routes)):
- routeCmd = "network " + routes[i]
+ for i in range( 0, len( routes ) ):
+ routeCmd = "network " + routes[ i ]
try:
- self.handle.sendline(routeCmd)
- self.handle.expect("bgpd", timeout=5)
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd", timeout=5 )
except:
- main.log.warn("Failed to add route")
+ main.log.warn( "Failed to add route" )
self.disconnect()
waitTimer = 1.00 / routeRate
- time.sleep(waitTimer)
- if routes_added == len(routes):
- main.log.info("Finished adding routes")
+ time.sleep( waitTimer )
+ if routes_added == len( routes ):
+ main.log.info( "Finished adding routes" )
return main.TRUE
return main.FALSE
- def delete_routes(self, routes, routeRate):
- main.log.info("I am in delete_routes method!")
+ def delete_routes( self, routes, routeRate ):
+ main.log.info( "I am in delete_routes method!" )
routes_added = 0
try:
- self.handle.sendline("")
- # self.handle.expect("config-router")
- self.handle.expect("config-router", timeout=5)
+ self.handle.sendline( "" )
+ # self.handle.expect( "config-router" )
+ self.handle.expect( "config-router", timeout=5 )
except:
- main.log.warn("Probably not in config-router mode!")
+ main.log.warn( "Probably not in config-router mode!" )
self.disconnect()
- main.log.info("Start to delete routes")
+ main.log.info( "Start to delete routes" )
- for i in range(0, len(routes)):
- routeCmd = "no network " + routes[i]
+ for i in range( 0, len( routes ) ):
+ routeCmd = "no network " + routes[ i ]
try:
- self.handle.sendline(routeCmd)
- self.handle.expect("bgpd", timeout=5)
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd", timeout=5 )
except:
- main.log.warn("Failed to add route")
+ main.log.warn( "Failed to add route" )
self.disconnect()
waitTimer = 1.00 / routeRate
- time.sleep(waitTimer)
- if routes_added == len(routes):
- main.log.info("Finished deleting routes")
+ time.sleep( waitTimer )
+ if routes_added == len( routes ):
+ main.log.info( "Finished deleting routes" )
return main.TRUE
return main.FALSE
- def ping_test(self, ip_address, ping_test_file, ping_test_result_file):
- main.log.info("Start the ping test on host:" + str(ip_address))
+ def ping_test( self, ip_address, ping_test_file, ping_test_result_file ):
+ main.log.info( "Start the ping test on host:" + str( ip_address ) )
- self.name = self.options['name']
- self.handle = super(QuaggaCliDriver, self).connect(
+ self.name = self.options[ 'name' ]
+ self.handle = super( QuaggaCliDriver, self ).connect(
user_name=self.user_name, ip_address=ip_address,
- port=self.port, pwd=self.pwd)
- main.log.info("connect parameters:" + str(self.user_name) + ";"
- + str(self.ip_address) + ";" + str(self.port) + ";" + str(self.pwd))
+ port=self.port, pwd=self.pwd )
+ main.log.info( "connect parameters:" + str( self.user_name ) + ";"
+ + str( self.ip_address ) + ";" + str( self.port ) + ";" + str( self.pwd ) )
if self.handle:
- #self.handle.expect("")
- #self.handle.expect("\$")
- main.log.info("I in host " + str(ip_address))
- main.log.info(ping_test_file + " > " + ping_test_result_file + " &")
- self.handle.sendline(ping_test_file + " > " + ping_test_result_file + " &")
- self.handle.expect("\$", timeout=60)
+ # self.handle.expect( "" )
+ # self.handle.expect( "\$" )
+ main.log.info( "I in host " + str( ip_address ) )
+ main.log.info(
+ ping_test_file +
+ " > " +
+ ping_test_result_file +
+ " &" )
+ self.handle.sendline(
+ ping_test_file +
+ " > " +
+ ping_test_result_file +
+ " &" )
+ self.handle.expect( "\$", timeout=60 )
handle = self.handle.before
return handle
else:
- main.log.info("NO HANDLE")
+ main.log.info( "NO HANDLE" )
return main.FALSE
-
# Please use the generate_routes plus add_routes instead of this one
- def add_route(self, net, numRoutes, routeRate):
+ def add_route( self, net, numRoutes, routeRate ):
try:
- self.handle.sendline("")
- self.handle.expect("config-router")
+ self.handle.sendline( "" )
+ self.handle.expect( "config-router" )
except:
- main.log.warn("Probably not in config-router mode!")
+ main.log.warn( "Probably not in config-router mode!" )
self.disconnect()
- main.log.info("Adding Routes")
+ main.log.info( "Adding Routes" )
j = 0
k = 0
while numRoutes > 255:
@@ -348,44 +416,47 @@
routes_added = 0
if numRoutes > 255:
numRoutes = 255
- for m in range(1, j + 1):
- for n in range(1, numRoutes + 1):
- network = str(net) + "." + str(m) + "." + str(n) + ".0/24"
+ for m in range( 1, j + 1 ):
+ for n in range( 1, numRoutes + 1 ):
+ network = str( net ) + "." + str( m ) + "." + str( n ) + ".0/24"
routeCmd = "network " + network
try:
- self.handle.sendline(routeCmd)
- self.handle.expect("bgpd")
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
except:
- main.log.warn("failed to add route")
+ main.log.warn( "failed to add route" )
self.disconnect()
waitTimer = 1.00 / routeRate
- time.sleep(waitTimer)
+ time.sleep( waitTimer )
routes_added = routes_added + 1
- for d in range(j + 1, j + 2):
- for e in range(1, k + 1):
- network = str(net) + "." + str(d) + "." + str(e) + ".0/24"
+ for d in range( j + 1, j + 2 ):
+ for e in range( 1, k + 1 ):
+ network = str(
+ net ) + "." + str(
+ d ) + "." + str(
+ e ) + ".0/24"
routeCmd = "network " + network
try:
- self.handle.sendline(routeCmd)
- self.handle.expect("bgpd")
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
except:
- main.log.warn("failed to add route")
+ main.log.warn( "failed to add route" )
self.disconnect
waitTimer = 1.00 / routeRate
- time.sleep(waitTimer)
+ time.sleep( waitTimer )
routes_added = routes_added + 1
if routes_added == numRoutes:
return main.TRUE
return main.FALSE
- def del_route(self, net, numRoutes, routeRate):
+ def del_route( self, net, numRoutes, routeRate ):
try:
- self.handle.sendline("")
- self.handle.expect("config-router")
+ self.handle.sendline( "" )
+ self.handle.expect( "config-router" )
except:
- main.log.warn("Probably not in config-router mode!")
+ main.log.warn( "Probably not in config-router mode!" )
self.disconnect()
- main.log.info("Deleting Routes")
+ main.log.info( "Deleting Routes" )
j = 0
k = 0
while numRoutes > 255:
@@ -395,100 +466,106 @@
routes_deleted = 0
if numRoutes > 255:
numRoutes = 255
- for m in range(1, j + 1):
- for n in range(1, numRoutes + 1):
- network = str(net) + "." + str(m) + "." + str(n) + ".0/24"
+ for m in range( 1, j + 1 ):
+ for n in range( 1, numRoutes + 1 ):
+ network = str( net ) + "." + str( m ) + "." + str( n ) + ".0/24"
routeCmd = "no network " + network
try:
- self.handle.sendline(routeCmd)
- self.handle.expect("bgpd")
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
except:
- main.log.warn("Failed to delete route")
+ main.log.warn( "Failed to delete route" )
self.disconnect()
waitTimer = 1.00 / routeRate
- time.sleep(waitTimer)
+ time.sleep( waitTimer )
routes_deleted = routes_deleted + 1
- for d in range(j + 1, j + 2):
- for e in range(1, k + 1):
- network = str(net) + "." + str(d) + "." + str(e) + ".0/24"
+ for d in range( j + 1, j + 2 ):
+ for e in range( 1, k + 1 ):
+ network = str( net ) + "." + str( d ) + "." + str( e ) + ".0/24"
routeCmd = "no network " + network
try:
- self.handle.sendline(routeCmd)
- self.handle.expect("bgpd")
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
except:
- main.log.warn("Failed to delete route")
+ main.log.warn( "Failed to delete route" )
self.disconnect()
waitTimer = 1.00 / routeRate
- time.sleep(waitTimer)
+ time.sleep( waitTimer )
routes_deleted = routes_deleted + 1
if routes_deleted == numRoutes:
return main.TRUE
return main.FALSE
- def check_routes(self, brand, ip, user, pw):
- def pronto(ip, user, passwd):
+ def check_routes( self, brand, ip, user, pw ):
+ def pronto( ip, user, passwd ):
print "Connecting to Pronto switch"
- child = pexpect.spawn("telnet " + ip)
- i = child.expect(["login:", "CLI#", pexpect.TIMEOUT])
+ child = pexpect.spawn( "telnet " + ip )
+ i = child.expect( [ "login:", "CLI#", pexpect.TIMEOUT ] )
if i == 0:
print "Username and password required. Passing login info."
- child.sendline(user)
- child.expect("Password:")
- child.sendline(passwd)
- child.expect("CLI#")
+ child.sendline( user )
+ child.expect( "Password:" )
+ child.sendline( passwd )
+ child.expect( "CLI#" )
print "Logged in, getting flowtable."
- child.sendline("flowtable brief")
- for t in range (9):
+ child.sendline( "flowtable brief" )
+ for t in range( 9 ):
t2 = 9 - t
- print "\r" + str(t2)
- sys.stdout.write("\033[F")
- time.sleep(1)
+ print "\r" + str( t2 )
+ sys.stdout.write( "\033[F" )
+ time.sleep( 1 )
print "Scanning flowtable"
- child.expect("Flow table show")
+ child.expect( "Flow table show" )
count = 0
- while 1:
- i = child.expect(['17\d\.\d{1,3}\.\d{1,3}\.\d{1,3}', 'CLI#', pexpect.TIMEOUT])
+ while True:
+ i = child.expect(
+ [ '17\d\.\d{1,3}\.\d{1,3}\.\d{1,3}',
+ 'CLI#',
+ pexpect.TIMEOUT ] )
if i == 0:
count = count + 1
elif i == 1:
- print "Pronto flows: " + str(count) + "\nDone\n"
+ print "Pronto flows: " + str( count ) + "\nDone\n"
break
else:
break
- def cisco(ip, user, passwd):
+
+ def cisco( ip, user, passwd ):
print "Establishing Cisco switch connection"
- child = pexpect.spawn("ssh " + user + "@" + ip)
- i = child.expect(["Password:", "CLI#", pexpect.TIMEOUT])
+ child = pexpect.spawn( "ssh " + user + "@" + ip )
+ i = child.expect( [ "Password:", "CLI#", pexpect.TIMEOUT ] )
if i == 0:
print "Password required. Passing now."
- child.sendline(passwd)
- child.expect("#")
+ child.sendline( passwd )
+ child.expect( "#" )
print "Logged in. Retrieving flow table then counting flows."
- child.sendline("show openflow switch all flows all")
- child.expect("Logical Openflow Switch")
+ child.sendline( "show openflow switch all flows all" )
+ child.expect( "Logical Openflow Switch" )
print "Flow table retrieved. Counting flows"
count = 0
- while 1:
- i = child.expect(["nw_src=17", "#", pexpect.TIMEOUT])
+ while True:
+ i = child.expect( [ "nw_src=17", "#", pexpect.TIMEOUT ] )
if i == 0:
count = count + 1
elif i == 1:
- print "Cisco flows: " + str(count) + "\nDone\n"
+ print "Cisco flows: " + str( count ) + "\nDone\n"
break
else:
break
if brand == "pronto" or brand == "PRONTO":
- pronto(ip, user, passwd)
+ pronto( ip, user, passwd )
# elif brand == "cisco" or brand == "CISCO":
- # cisco(ip,user,passwd)
- def disconnect(self):
- '''
- Called when Test is complete to disconnect the Quagga handle.
- '''
+ # cisco( ip,user,passwd )
+
+ def disconnect( self ):
+ """
+ Called when Test is complete to disconnect the Quagga handle.
+ """
response = ''
try:
self.handle.close()
except:
- main.log.error("Connection failed to the host")
+ main.log.error( "Connection failed to the host" )
response = main.FALSE
return response
+
diff --git a/TestON/drivers/common/cli/quaggaclidriver.py.fixed b/TestON/drivers/common/cli/quaggaclidriver.py.fixed
new file mode 100644
index 0000000..09b7614
--- /dev/null
+++ b/TestON/drivers/common/cli/quaggaclidriver.py.fixed
@@ -0,0 +1,596 @@
+#!/usr/bin/env python
+
+import time
+import pexpect
+import struct
+import fcntl
+import os
+import sys
+import signal
+import sys
+import re
+import json
+sys.path.append( "../" )
+from drivers.common.clidriver import CLI
+
+
+class QuaggaCliDriver( CLI ):
+
+ def __init__( self ):
+ super( CLI, self ).__init__()
+
+ # TODO: simplify this method
+ def connect( self, **connectargs ):
+ for key in connectargs:
+ vars( self )[ key ] = connectargs[ key ]
+
+ self.name = self.options[ 'name' ]
+ # self.handle = super( QuaggaCliDriver,self ).connect(
+ # user_name=self.user_name, ip_address=self.ip_address,port=self.port,
+ # pwd=self.pwd )
+ self.handle = super(
+ QuaggaCliDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address="1.1.1.1",
+ port=self.port,
+ pwd=self.pwd )
+ main.log.info(
+ "connect parameters:" + str(
+ self.user_name ) + ";" + str(
+ self.ip_address ) + ";" + str(
+ self.port ) + ";" + str(
+ self.pwd ) )
+
+ if self.handle:
+ # self.handle.expect( "",timeout=10 )
+ # self.handle.expect( "\$",timeout=10 )
+ self.handle.sendline( "telnet localhost 2605" )
+ # self.handle.expect( "Password:", timeout=5 )
+ self.handle.expect( "Password:" )
+ self.handle.sendline( "hello" )
+ # self.handle.expect( "bgpd", timeout=5 )
+ self.handle.expect( "bgpd" )
+ self.handle.sendline( "enable" )
+ # self.handle.expect( "bgpd#", timeout=5 )
+ self.handle.expect( "bgpd#" )
+ return self.handle
+ else:
+ main.log.info( "NO HANDLE" )
+ return main.FALSE
+
+ def loginQuagga( self, ip_address ):
+ self.name = self.options[ 'name' ]
+ self.handle = super( QuaggaCliDriver, self ).connect(
+ user_name=self.user_name, ip_address=ip_address,
+ port=self.port, pwd=self.pwd )
+ main.log.info( "connect parameters:" + str( self.user_name ) + ";"
+ + str( self.ip_address ) + ";" + str( self.port ) + ";" + str( self.pwd ) )
+
+ if self.handle:
+ # self.handle.expect( "" )
+ # self.handle.expect( "\$" )
+ self.handle.sendline( "telnet localhost 2605" )
+ # self.handle.expect( "Password:", timeout=5 )
+ self.handle.expect( "Password:" )
+ self.handle.sendline( "hello" )
+ # self.handle.expect( "bgpd", timeout=5 )
+ self.handle.expect( "bgpd" )
+ self.handle.sendline( "enable" )
+ # self.handle.expect( "bgpd#", timeout=5 )
+ self.handle.expect( "bgpd#" )
+ main.log.info( "I in quagga on host " + str( ip_address ) )
+
+ return self.handle
+ else:
+ main.log.info( "NO HANDLE" )
+ return main.FALSE
+
+ def enter_config( self, asn ):
+ main.log.info( "I am in enter_config method!" )
+ try:
+ self.handle.sendline( "" )
+ self.handle.expect( "bgpd#" )
+ except:
+ main.log.warn( "Probably not currently in enable mode!" )
+ self.disconnect()
+ return main.FALSE
+ self.handle.sendline( "configure terminal" )
+ self.handle.expect( "config", timeout=5 )
+ routerAS = "router bgp " + str( asn )
+ try:
+ self.handle.sendline( routerAS )
+ self.handle.expect( "config-router", timeout=5 )
+ return main.TRUE
+ except:
+ return main.FALSE
+
+ def generate_prefixes( self, net, numRoutes ):
+ main.log.info( "I am in generate_prefixes method!" )
+
+ # each IP prefix will be composed by "net" + "." + m + "." + n + "." + x
+ # the length of each IP prefix is 24
+ routes = []
+ routes_gen = 0
+ m = numRoutes / 256
+ n = numRoutes % 256
+
+ for i in range( 0, m ):
+ for j in range( 0, 256 ):
+ network = str(
+ net ) + "." + str(
+ i ) + "." + str(
+ j ) + ".0/24"
+ routes.append( network )
+ routes_gen = routes_gen + 1
+
+ for j in range( 0, n ):
+ network = str( net ) + "." + str( m ) + "." + str( j ) + ".0/24"
+ routes.append( network )
+ routes_gen = routes_gen + 1
+
+ if routes_gen == numRoutes:
+ main.log.info( "Successfully generated " + str( numRoutes )
+ + " prefixes!" )
+ return routes
+ return main.FALSE
+
+ # This method generates a multiple to single point intent(
+ # MultiPointToSinglePointIntent ) for a given route
+ def generate_expected_singleRouteIntent(
+ self,
+ prefix,
+ nextHop,
+ nextHopMac,
+ sdnip_data ):
+
+ ingress = []
+ egress = ""
+ for peer in sdnip_data[ 'bgpPeers' ]:
+ if peer[ 'ipAddress' ] == nextHop:
+ egress = "of:" + str(
+ peer[ 'attachmentDpid' ] ).replace( ":",
+ "" ) + ":" + str( peer[ 'attachmentPort' ] )
+ else:
+ ingress.append(
+ "of:" + str( peer[ 'attachmentDpid' ] ).replace( ":",
+ "" ) + ":" + str( peer[ 'attachmentPort' ] ) )
+
+ selector = "ETH_TYPE{ethType=800},IPV4_DST{ip=" + prefix + "}"
+ treatment = "[ETH_DST{mac=" + str( nextHopMac ) + "}]"
+
+ intent = egress + "/" + \
+ str( sorted( ingress ) ) + "/" + selector + "/" + treatment
+ return intent
+
+ def generate_expected_onePeerRouteIntents(
+ self,
+ prefixes,
+ nextHop,
+ nextHopMac,
+ sdnip_json_file_path ):
+ intents = []
+ sdnip_json_file = open( sdnip_json_file_path ).read()
+
+ sdnip_data = json.loads( sdnip_json_file )
+
+ for prefix in prefixes:
+ intents.append(
+ self.generate_expected_singleRouteIntent(
+ prefix,
+ nextHop,
+ nextHopMac,
+ sdnip_data ) )
+ return sorted( intents )
+
+ # TODO
+ # This method generates all expected route intents for all BGP peers
+ def generate_expected_routeIntents( self ):
+ intents = []
+ return intents
+
+ # This method extracts all actual routes from ONOS CLI
+ def extract_actual_routes( self, get_routes_result ):
+ routes_json_obj = json.loads( get_routes_result )
+
+ allRoutes_actual = []
+ for route in routes_json_obj:
+ if route[ 'prefix' ] == '172.16.10.0/24':
+ continue
+ allRoutes_actual.append(
+ route[ 'prefix' ] + "/" + route[ 'nextHop' ] )
+
+ return sorted( allRoutes_actual )
+
+ # This method extracts all actual route intents from ONOS CLI
+ def extract_actual_routeIntents( self, get_intents_result ):
+ intents = []
+ # TODO: delete the line below when change to Mininet demo script
+ # get_intents_result=open( "../tests/SdnIpTest/intents.json" ).read()
+ intents_json_obj = json.loads( get_intents_result )
+
+ for intent in intents_json_obj:
+ if intent[ 'appId' ] != "org.onosproject.sdnip":
+ continue
+ if intent[ 'type' ] == "MultiPointToSinglePointIntent" and intent[ 'state' ] == 'INSTALLED':
+ egress = str( intent[ 'egress' ][ 'device' ] ) + ":" + str(
+ intent[ 'egress' ][ 'port' ] )
+ ingress = []
+ for attachmentPoint in intent[ 'ingress' ]:
+ ingress.append(
+ str( attachmentPoint[ 'device' ] ) + ":" + str( attachmentPoint[ 'port' ] ) )
+
+ selector = intent[ 'selector' ].replace(
+ "[", "" ).replace( "]", "" ).replace( " ", "" )
+ if str( selector ).startswith( "IPV4" ):
+ str1, str2 = str( selector ).split( "," )
+ selector = str2 + "," + str1
+
+ intent = egress + "/" + \
+ str( sorted( ingress ) ) + "/" + \
+ selector + "/" + intent[ 'treatment' ]
+ intents.append( intent )
+ return sorted( intents )
+
+ # This method extracts all actual BGP intents from ONOS CLI
+ def extract_actual_bgpIntents( self, get_intents_result ):
+ intents = []
+ # TODO: delete the line below when change to Mininet demo script
+ # get_intents_result=open( "../tests/SdnIpTest/intents.json" ).read()
+ intents_json_obj = json.loads( get_intents_result )
+
+ for intent in intents_json_obj:
+ if intent[ 'appId' ] != "org.onosproject.sdnip":
+ continue
+ if intent[ 'type' ] == "PointToPointIntent" and "protocol=6" in str( intent[ 'selector' ] ):
+ ingress = str( intent[ 'ingress' ][ 'device' ] ) + ":" + str(
+ intent[ 'ingress' ][ 'port' ] )
+ egress = str( intent[ 'egress' ][ 'device' ] ) + ":" + str(
+ intent[ 'egress' ][ 'port' ] )
+ selector = str(
+ intent[ 'selector' ] ).replace( " ",
+ "" ).replace( "[",
+ "" ).replace( "]",
+ "" ).split( "," )
+ intent = ingress + "/" + egress + \
+ "/" + str( sorted( selector ) )
+ intents.append( intent )
+
+ return sorted( intents )
+
+ # This method generates a single point to single point intent(
+ # PointToPointIntent ) for BGP path
+ def generate_expected_bgpIntents( self, sdnip_json_file_path ):
+ from operator import eq
+
+ sdnip_json_file = open( sdnip_json_file_path ).read()
+ sdnip_data = json.loads( sdnip_json_file )
+
+ intents = []
+ bgpPeerAttachmentPoint = ""
+ bgpSpeakerAttachmentPoint = "of:" + str(
+ sdnip_data[ 'bgpSpeakers' ][ 0 ][ 'attachmentDpid' ] ).replace( ":",
+ "" ) + ":" + str( sdnip_data[ 'bgpSpeakers' ][ 0 ][ 'attachmentPort' ] )
+ for peer in sdnip_data[ 'bgpPeers' ]:
+ bgpPeerAttachmentPoint = "of:" + str(
+ peer[ 'attachmentDpid' ] ).replace( ":",
+ "" ) + ":" + str( peer[ 'attachmentPort' ] )
+ # find out the BGP speaker IP address for this BGP peer
+ bgpSpeakerIpAddress = ""
+ for interfaceAddress in sdnip_data[ 'bgpSpeakers' ][ 0 ][ 'interfaceAddresses' ]:
+ # if eq( interfaceAddress[ 'interfaceDpid' ],sdnip_data[
+ # 'bgpSpeakers' ][ 0 ][ 'attachmentDpid' ] ) and eq(
+ # interfaceAddress[ 'interfacePort' ], sdnip_data[
+ # 'bgpSpeakers' ][ 0 ][ 'attachmentPort' ] ):
+ if eq( interfaceAddress[ 'interfaceDpid' ], peer[ 'attachmentDpid' ] ) and eq( interfaceAddress[ 'interfacePort' ], peer[ 'attachmentPort' ] ):
+ bgpSpeakerIpAddress = interfaceAddress[ 'ipAddress' ]
+ break
+ else:
+ continue
+
+ # from bgpSpeakerAttachmentPoint to bgpPeerAttachmentPoint
+ # direction
+ selector_str = "IPV4_SRC{ip=" + bgpSpeakerIpAddress + "/32}," + "IPV4_DST{ip=" + peer[
+ 'ipAddress' ] + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_DST{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpSpeakerAttachmentPoint + "/" + \
+ bgpPeerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
+
+ selector_str = "IPV4_SRC{ip=" + bgpSpeakerIpAddress + "/32}," + "IPV4_DST{ip=" + peer[
+ 'ipAddress' ] + "/32}," + "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_SRC{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpSpeakerAttachmentPoint + "/" + \
+ bgpPeerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
+
+ # from bgpPeerAttachmentPoint to bgpSpeakerAttachmentPoint
+ # direction
+ selector_str = "IPV4_SRC{ip=" + peer[ 'ipAddress' ] + "/32}," + "IPV4_DST{ip=" + bgpSpeakerIpAddress + "/32}," + \
+ "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_DST{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpPeerAttachmentPoint + "/" + \
+ bgpSpeakerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
+
+ selector_str = "IPV4_SRC{ip=" + peer[ 'ipAddress' ] + "/32}," + "IPV4_DST{ip=" + bgpSpeakerIpAddress + "/32}," + \
+ "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, TCP_SRC{tcpPort=179}"
+ selector = selector_str.replace( " ", "" ).replace(
+ "[", "" ).replace( "]", "" ).split( "," )
+ intent = bgpPeerAttachmentPoint + "/" + \
+ bgpSpeakerAttachmentPoint + "/" + str( sorted( selector ) )
+ intents.append( intent )
+
+ return sorted( intents )
+
+ def add_routes( self, routes, routeRate ):
+ main.log.info( "I am in add_routes method!" )
+
+ routes_added = 0
+ try:
+ self.handle.sendline( "" )
+ # self.handle.expect( "config-router" )
+ self.handle.expect( "config-router", timeout=5 )
+ except:
+ main.log.warn( "Probably not in config-router mode!" )
+ self.disconnect()
+ main.log.info( "Start to add routes" )
+
+ for i in range( 0, len( routes ) ):
+ routeCmd = "network " + routes[ i ]
+ try:
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd", timeout=5 )
+ except:
+ main.log.warn( "Failed to add route" )
+ self.disconnect()
+ waitTimer = 1.00 / routeRate
+ time.sleep( waitTimer )
+ if routes_added == len( routes ):
+ main.log.info( "Finished adding routes" )
+ return main.TRUE
+ return main.FALSE
+
+ def delete_routes( self, routes, routeRate ):
+ main.log.info( "I am in delete_routes method!" )
+
+ routes_added = 0
+ try:
+ self.handle.sendline( "" )
+ # self.handle.expect( "config-router" )
+ self.handle.expect( "config-router", timeout=5 )
+ except:
+ main.log.warn( "Probably not in config-router mode!" )
+ self.disconnect()
+ main.log.info( "Start to delete routes" )
+
+ for i in range( 0, len( routes ) ):
+ routeCmd = "no network " + routes[ i ]
+ try:
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd", timeout=5 )
+ except:
+ main.log.warn( "Failed to add route" )
+ self.disconnect()
+ waitTimer = 1.00 / routeRate
+ time.sleep( waitTimer )
+ if routes_added == len( routes ):
+ main.log.info( "Finished deleting routes" )
+ return main.TRUE
+ return main.FALSE
+
+ def ping_test( self, ip_address, ping_test_file, ping_test_result_file ):
+ main.log.info( "Start the ping test on host:" + str( ip_address ) )
+
+ self.name = self.options[ 'name' ]
+ self.handle = super( QuaggaCliDriver, self ).connect(
+ user_name=self.user_name, ip_address=ip_address,
+ port=self.port, pwd=self.pwd )
+ main.log.info( "connect parameters:" + str( self.user_name ) + ";"
+ + str( self.ip_address ) + ";" + str( self.port ) + ";" + str( self.pwd ) )
+
+ if self.handle:
+ # self.handle.expect( "" )
+ # self.handle.expect( "\$" )
+ main.log.info( "I in host " + str( ip_address ) )
+ main.log.info(
+ ping_test_file +
+ " > " +
+ ping_test_result_file +
+ " &" )
+ self.handle.sendline(
+ ping_test_file +
+ " > " +
+ ping_test_result_file +
+ " &" )
+ self.handle.expect( "\$", timeout=60 )
+ handle = self.handle.before
+
+ return handle
+ else:
+ main.log.info( "NO HANDLE" )
+ return main.FALSE
+
+ # Please use the generate_routes plus add_routes instead of this one
+ def add_route( self, net, numRoutes, routeRate ):
+ try:
+ self.handle.sendline( "" )
+ self.handle.expect( "config-router" )
+ except:
+ main.log.warn( "Probably not in config-router mode!" )
+ self.disconnect()
+ main.log.info( "Adding Routes" )
+ j = 0
+ k = 0
+ while numRoutes > 255:
+ numRoutes = numRoutes - 255
+ j = j + 1
+ k = numRoutes % 254
+ routes_added = 0
+ if numRoutes > 255:
+ numRoutes = 255
+ for m in range( 1, j + 1 ):
+ for n in range( 1, numRoutes + 1 ):
+ network = str(
+ net ) + "." + str(
+ m ) + "." + str(
+ n ) + ".0/24"
+ routeCmd = "network " + network
+ try:
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
+ except:
+ main.log.warn( "failed to add route" )
+ self.disconnect()
+ waitTimer = 1.00 / routeRate
+ time.sleep( waitTimer )
+ routes_added = routes_added + 1
+ for d in range( j + 1, j + 2 ):
+ for e in range( 1, k + 1 ):
+ network = str(
+ net ) + "." + str(
+ d ) + "." + str(
+ e ) + ".0/24"
+ routeCmd = "network " + network
+ try:
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
+ except:
+ main.log.warn( "failed to add route" )
+ self.disconnect
+ waitTimer = 1.00 / routeRate
+ time.sleep( waitTimer )
+ routes_added = routes_added + 1
+ if routes_added == numRoutes:
+ return main.TRUE
+ return main.FALSE
+
+ def del_route( self, net, numRoutes, routeRate ):
+ try:
+ self.handle.sendline( "" )
+ self.handle.expect( "config-router" )
+ except:
+ main.log.warn( "Probably not in config-router mode!" )
+ self.disconnect()
+ main.log.info( "Deleting Routes" )
+ j = 0
+ k = 0
+ while numRoutes > 255:
+ numRoutes = numRoutes - 255
+ j = j + 1
+ k = numRoutes % 254
+ routes_deleted = 0
+ if numRoutes > 255:
+ numRoutes = 255
+ for m in range( 1, j + 1 ):
+ for n in range( 1, numRoutes + 1 ):
+ network = str(
+ net ) + "." + str(
+ m ) + "." + str(
+ n ) + ".0/24"
+ routeCmd = "no network " + network
+ try:
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
+ except:
+ main.log.warn( "Failed to delete route" )
+ self.disconnect()
+ waitTimer = 1.00 / routeRate
+ time.sleep( waitTimer )
+ routes_deleted = routes_deleted + 1
+ for d in range( j + 1, j + 2 ):
+ for e in range( 1, k + 1 ):
+ network = str(
+ net ) + "." + str(
+ d ) + "." + str(
+ e ) + ".0/24"
+ routeCmd = "no network " + network
+ try:
+ self.handle.sendline( routeCmd )
+ self.handle.expect( "bgpd" )
+ except:
+ main.log.warn( "Failed to delete route" )
+ self.disconnect()
+ waitTimer = 1.00 / routeRate
+ time.sleep( waitTimer )
+ routes_deleted = routes_deleted + 1
+ if routes_deleted == numRoutes:
+ return main.TRUE
+ return main.FALSE
+
+ def check_routes( self, brand, ip, user, pw ):
+ def pronto( ip, user, passwd ):
+ print "Connecting to Pronto switch"
+ child = pexpect.spawn( "telnet " + ip )
+ i = child.expect( [ "login:", "CLI#", pexpect.TIMEOUT ] )
+ if i == 0:
+ print "Username and password required. Passing login info."
+ child.sendline( user )
+ child.expect( "Password:" )
+ child.sendline( passwd )
+ child.expect( "CLI#" )
+ print "Logged in, getting flowtable."
+ child.sendline( "flowtable brief" )
+ for t in range( 9 ):
+ t2 = 9 - t
+ print "\r" + str( t2 )
+ sys.stdout.write( "\033[F" )
+ time.sleep( 1 )
+ print "Scanning flowtable"
+ child.expect( "Flow table show" )
+ count = 0
+ while True:
+ i = child.expect(
+ [ '17\d\.\d{1,3}\.\d{1,3}\.\d{1,3}',
+ 'CLI#',
+ pexpect.TIMEOUT ] )
+ if i == 0:
+ count = count + 1
+ elif i == 1:
+ print "Pronto flows: " + str( count ) + "\nDone\n"
+ break
+ else:
+ break
+
+ def cisco( ip, user, passwd ):
+ print "Establishing Cisco switch connection"
+ child = pexpect.spawn( "ssh " + user + "@" + ip )
+ i = child.expect( [ "Password:", "CLI#", pexpect.TIMEOUT ] )
+ if i == 0:
+ print "Password required. Passing now."
+ child.sendline( passwd )
+ child.expect( "#" )
+ print "Logged in. Retrieving flow table then counting flows."
+ child.sendline( "show openflow switch all flows all" )
+ child.expect( "Logical Openflow Switch" )
+ print "Flow table retrieved. Counting flows"
+ count = 0
+ while True:
+ i = child.expect( [ "nw_src=17", "#", pexpect.TIMEOUT ] )
+ if i == 0:
+ count = count + 1
+ elif i == 1:
+ print "Cisco flows: " + str( count ) + "\nDone\n"
+ break
+ else:
+ break
+ if brand == "pronto" or brand == "PRONTO":
+ pronto( ip, user, passwd )
+ # elif brand == "cisco" or brand == "CISCO":
+ # cisco( ip,user,passwd )
+
+ def disconnect( self ):
+ """
+ Called when Test is complete to disconnect the Quagga handle.
+ """
+ response = ''
+ try:
+ self.handle.close()
+ except:
+ main.log.error( "Connection failed to the host" )
+ response = main.FALSE
+ return response
+
diff --git a/TestON/drivers/common/cli/remotesysdriver.py b/TestON/drivers/common/cli/remotesysdriver.py
index 374e502..a536e02 100644
--- a/TestON/drivers/common/cli/remotesysdriver.py
+++ b/TestON/drivers/common/cli/remotesysdriver.py
@@ -1,13 +1,13 @@
#!/usr/bin/env python
-'''
-Created on 26-Oct-2012
+"""
+Created on 26-Oct-2012
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -15,41 +15,52 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import time
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
import sys
-sys.path.append("../")
+import signal
+import sys
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class RemoteSysDriver(CLI):
+
+class RemoteSysDriver( CLI ):
# The common functions for emulator included in emulatordriver
- def __init__(self):
- super(CLI, self).__init__()
-
- def connect(self,**connectargs):
+
+ def __init__( self ):
+ super( CLI, self ).__init__()
+
+ def connect( self, **connectargs ):
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
+ vars( self )[ key ] = connectargs[ key ]
- self.handle = super(RemoteSysDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
- '''
+ self.name = self.options[ 'name' ]
+
+ self.handle = super(
+ RemoteSysDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd )
+ """
if self.handle:
- self.execute(cmd= "\n",prompt= "\$|>|#",timeout= 10)
- self.execute(cmd= "ssh -l paxterra 10.128.4.1",prompt= "paxterra@10.128.4.1's password:",timeout= 10)
- self.execute(cmd= "\n",prompt= "paxterra@10.128.4.1's password:",timeout= 10)
- self.execute(cmd = "0nLab_gu3st",prompt = "\$",timeout = 10)
- self.execute(cmd = "cd TestON/bin/",prompt = "\$",timeout = 10)
- self.execute(cmd = "./cli.py run Assert example 1",prompt = "\$",timeout = 10)
- self.execute(cmd= "\n",prompt= "$",timeout= 10)
- #self.execute(cmd = "help",prompt = ">",timeout = 10)
-
- #self.execute(cmd = "~.",prompt= ".*",timeout= 10)
- return main.TRUE
- '''
+ self.execute( cmd= "\n",prompt= "\$|>|#",timeout= 10 )
+ self.execute( cmd= "ssh -l paxterra 10.128.4.1",prompt= "paxterra@10.128.4.1's password:",timeout= 10 )
+ self.execute( cmd= "\n",prompt= "paxterra@10.128.4.1's password:",timeout= 10 )
+ self.execute( cmd="0nLab_gu3st",prompt="\$",timeout=10 )
+ self.execute( cmd="cd TestON/bin/",prompt="\$",timeout=10 )
+ self.execute( cmd="./cli.py run Assert example 1",prompt="\$",timeout=10 )
+ self.execute( cmd= "\n",prompt= "$",timeout= 10 )
+ #self.execute( cmd="help",prompt=">",timeout=10 )
+ #self.execute( cmd="~.",prompt= ".*",timeout= 10 )
+ return main.TRUE
+ """
diff --git a/TestON/drivers/common/cli/remotetestbed/floodlightclidriver.py b/TestON/drivers/common/cli/remotetestbed/floodlightclidriver.py
index 8b25b2f..10e7a85 100644
--- a/TestON/drivers/common/cli/remotetestbed/floodlightclidriver.py
+++ b/TestON/drivers/common/cli/remotetestbed/floodlightclidriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
+"""
Created on 12-Feb-2013
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,12 +16,11 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
FloodLightCliDriver is the basic driver which will handle the Mininet functions
-'''
-
+"""
import pexpect
import struct
import fcntl
@@ -31,30 +30,44 @@
import sys
import time
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.cli.remotetestbeddriver import RemoteTestBedDriver
-class FloodLightCliDriver(RemoteTestBedDriver):
- '''
- FloodLightCliDriver is the basic driver which will handle the Mininet functions
- '''
- def __init__(self):
- super(RemoteTestBedDriver, self).__init__()
-
- def connect(self,**connectargs):
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- self.handle = super(FloodLightCliDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
- if self.handle :
- main.log.info("Connected "+self.name)
- self.execute(cmd="\r",prompt="\$",timeout=10)
- self.execute(cmd="cd /home/openflow/floodlight/",prompt="floodlight\$",timeout=3)
- self.execute(cmd="java -jar target/floodlight.jar &",prompt="\$",timeout=3)
- self.execute(cmd="\r",prompt="\$",timeout=10)
+class FloodLightCliDriver( RemoteTestBedDriver ):
+
+ """
+ FloodLightCliDriver is the basic driver which will handle the Mininet functions
+ """
+ def __init__( self ):
+ super( RemoteTestBedDriver, self ).__init__()
+
+ def connect( self, **connectargs ):
+ for key in connectargs:
+ vars( self )[ key ] = connectargs[ key ]
+
+ self.name = self.options[ 'name' ]
+
+ self.handle = super(
+ FloodLightCliDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd )
+ if self.handle:
+ main.log.info( "Connected " + self.name )
+ self.execute( cmd="\r", prompt="\$", timeout=10 )
+ self.execute(
+ cmd="cd /home/openflow/floodlight/",
+ prompt="floodlight\$",
+ timeout=3 )
+ self.execute(
+ cmd="java -jar target/floodlight.jar &",
+ prompt="\$",
+ timeout=3 )
+ self.execute( cmd="\r", prompt="\$", timeout=10 )
return self.handle
- else :
+ else:
return main.FALSE
diff --git a/TestON/drivers/common/cli/remotetestbed/necswitchdriver.py b/TestON/drivers/common/cli/remotetestbed/necswitchdriver.py
index f5e652a..07fb668 100644
--- a/TestON/drivers/common/cli/remotetestbed/necswitchdriver.py
+++ b/TestON/drivers/common/cli/remotetestbed/necswitchdriver.py
@@ -1,545 +1,757 @@
class NEC:
+
def __init__( self ):
self.prompt = '(.*)'
- self.timeout = 60
+ self.timeout = 60
- def show(self, *options, **def_args ):
- '''Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-status ', ' cpu ', ' dhcp ', ' dot1x ', ' dumpfile ', ' efmoam ', ' environment ', ' file ', ' flash ', ' gsrp ', ' history ', ' igmp-snooping ', ' interfaces ', ' ip ', ' ip-dual ', ' ipv6-dhcp ', ' license ', ' lldp ', ' logging ', ' loop-detection ', ' mac-address-table ', ' mc ', ' memory ', ' mld-snooping ', ' netconf ', ' netstat ', ' ntp ', ' oadp ', ' openflow ', ' port ', ' power ', ' processes ', ' qos ', ' qos-flow ', ' sessions ', ' sflow ', ' spanning-tree ', ' ssh ', ' system ', ' tcpdump ', ' tech-support ', ' track ', ' version ', ' vlan ', ' vrrpstatus ', ' whoami ']'''
- arguments= ''
+ def show( self, *options, **def_args ):
+ "Possible Options :[' access-filter ', ' accounting ', ' acknowledgments ', ' auto-config ', ' axrp ', ' cfm ', ' channel-group ', ' clock ', ' config-lock-status ', ' cpu ', ' dhcp ', ' dot1x ', ' dumpfile ', ' efmoam ', ' environment ', ' file ', ' flash ', ' gsrp ', ' history ', ' igmp-snooping ', ' interfaces ', ' ip ', ' ip-dual ', ' ipv6-dhcp ', ' license ', ' lldp ', ' logging ', ' loop-detection ', ' mac-address-table ', ' mc ', ' memory ', ' mld-snooping ', ' netconf ', ' netstat ', ' ntp ', ' oadp ', ' openflow ', ' port ', ' power ', ' processes ', ' qos ', ' qos-flow ', ' sessions ', ' sflow ', ' spanning-tree ', ' ssh ', ' system ', ' tcpdump ', ' tech-support ', ' track ', ' version ', ' vlan ', ' vrrpstatus ', ' whoami ']"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute( cmd="show " + arguments, prompt=prompt, timeout=timeout )
return main.TRUE
- def show_ip(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_ip( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show ip "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show ip " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_mc(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_mc( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show mc "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show mc " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_cfm(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_cfm( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show cfm "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show cfm " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_ntp(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_ntp( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show ntp "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show ntp " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_ssh(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_ssh( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show ssh "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show ssh " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_qos(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_qos( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show qos "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show qos " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_cpu(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_cpu( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show cpu "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show cpu " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_vlan(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_vlan( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show vlan "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show vlan " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_lldp(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_lldp( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show lldp "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show lldp " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_dhcp(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_dhcp( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show dhcp "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show dhcp " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_axrp(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_axrp( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show axrp "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show axrp " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_oadp(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_oadp( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show oadp "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show oadp " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_gsrp(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_gsrp( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show gsrp "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show gsrp " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_port(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_port( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show port "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show port " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_file(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_file( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show file "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show file " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_power(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_power( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show power "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show power " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_clock(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_clock( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show clock "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show clock " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_dot1x(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_dot1x( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show dot1x "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show dot1x " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_sflow(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_sflow( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show sflow "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show sflow " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_track(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_track( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show track "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show track " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_flash(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_flash( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show flash "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show flash " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_system(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_system( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show system "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show system " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_whoami(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_whoami( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show whoami "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show whoami " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_efmoam(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_efmoam( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show efmoam "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show efmoam " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_memory(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_memory( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show memory "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show memory " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_tcpdump(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_tcpdump( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show tcpdump "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show tcpdump " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_history(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_history( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show history "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show history " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_logging(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_logging( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show logging "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show logging " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_license(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_license( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show license "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show license " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_netstat(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_netstat( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show netstat "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show netstat " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_version(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_version( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show version "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show version " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_netconf(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_netconf( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show netconf "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show netconf " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_ipdual(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_ipdual( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show ip-dual "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show ip-dual " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_sessions(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_sessions( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show sessions "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show sessions " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_qosflow(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_qosflow( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show qos-flow "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show qos-flow " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_openflow(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_openflow( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show openflow "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show openflow " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_dumpfile(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_dumpfile( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show dumpfile "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show dumpfile " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_ipv6dhcp(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_ipv6dhcp( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show ipv6-dhcp "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show ipv6-dhcp " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_processes(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_processes( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show processes "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show processes " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_vrrpstatus(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_vrrpstatus( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show vrrpstatus "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show vrrpstatus " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_interfaces(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_interfaces( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show interfaces "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show interfaces " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_environment(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_environment( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show environment "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show environment " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_autoconfig(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_autoconfig( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show auto-config "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show auto-config " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_techsupport(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_techsupport( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show tech-support "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show tech-support " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_mldsnooping(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_mldsnooping( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show mld-snooping "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show mld-snooping " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_igmpsnooping(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_igmpsnooping( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show igmp-snooping "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show igmp-snooping " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_channelgroup(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_channelgroup( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show channel-group "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show channel-group " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_spanningtree(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_spanningtree( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show spanning-tree "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show spanning-tree " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_loopdetection(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_loopdetection( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show loop-detection "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show loop-detection " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_acknowledgments(self, *options, **def_args ):
- '''Possible Options :[' interface ']'''
- arguments= ''
+ def show_acknowledgments( self, *options, **def_args ):
+ "Possible Options :[' interface ']"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show acknowledgments "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show acknowledgments " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_macaddresstable(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_macaddresstable( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show mac-address-table "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show mac-address-table " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_configlockstatus(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_configlockstatus( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show config-lock-status "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show config-lock-status " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
- def show_acknowledgments_interface(self, *options, **def_args ):
- '''Possible Options :[]'''
- arguments= ''
+ def show_acknowledgments_interface( self, *options, **def_args ):
+ "Possible Options :[]"
+ arguments = ''
for option in options:
- arguments = arguments + option +' '
- prompt = def_args.setdefault('prompt',self.prompt)
- timeout = def_args.setdefault('timeout',self.timeout)
- self.execute( cmd= "show acknowledgments interface "+ arguments, prompt = prompt, timeout = timeout )
+ arguments = arguments + option + ' '
+ prompt = def_args.setdefault( 'prompt', self.prompt )
+ timeout = def_args.setdefault( 'timeout', self.timeout )
+ self.execute(
+ cmd="show acknowledgments interface " +
+ arguments,
+ prompt=prompt,
+ timeout=timeout )
return main.TRUE
-
diff --git a/TestON/drivers/common/cli/remotetestbed/remotepoxdriver.py b/TestON/drivers/common/cli/remotetestbed/remotepoxdriver.py
index f0d2a16..44951aa 100644
--- a/TestON/drivers/common/cli/remotetestbed/remotepoxdriver.py
+++ b/TestON/drivers/common/cli/remotetestbed/remotepoxdriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
+"""
Created on 12-Feb-2013
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,12 +16,11 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
RemoteVMDriver is the basic driver which will handle the Mininet functions
-'''
-
+"""
import pexpect
import struct
import fcntl
@@ -31,34 +30,49 @@
import sys
import time
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.cli.remotetestbeddriver import RemoteTestBedDriver
-class RemotePoxDriver(RemoteTestBedDriver):
- '''
- RemoteVMDriver is the basic driver which will handle the Mininet functions
- '''
- def __init__(self):
- super(RemoteTestBedDriver, self).__init__()
-
- def connect(self,**connectargs):
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- self.handle = super(RemotePoxDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
- if self.handle :
- main.log.info(self.name+" connected successfully ")
-
- self.execute(cmd="cd "+self.options['pox_lib_location'],prompt="/pox\$",timeout=120)
- self.execute(cmd='./pox.py samples.of_tutorial',prompt="DEBUG:",timeout=120)
+class RemotePoxDriver( RemoteTestBedDriver ):
+
+ """
+ RemoteVMDriver is the basic driver which will handle the Mininet functions
+ """
+ def __init__( self ):
+ super( RemoteTestBedDriver, self ).__init__()
+
+ def connect( self, **connectargs ):
+ for key in connectargs:
+ vars( self )[ key ] = connectargs[ key ]
+
+ self.name = self.options[ 'name' ]
+
+ self.handle = super(
+ RemotePoxDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd )
+ if self.handle:
+ main.log.info( self.name + " connected successfully " )
+
+ self.execute(
+ cmd="cd " +
+ self.options[ 'pox_lib_location' ],
+ prompt="/pox\$",
+ timeout=120 )
+ self.execute(
+ cmd='./pox.py samples.of_tutorial',
+ prompt="DEBUG:",
+ timeout=120 )
return self.handle
return main.TRUE
-
- def disconnect(self,handle):
+
+ def disconnect( self, handle ):
if self.handle:
- self.execute(cmd="exit()",prompt="/pox\$",timeout=120)
- else :
- main.log.error("Connection failed to the host")
+ self.execute( cmd="exit()", prompt="/pox\$", timeout=120 )
+ else:
+ main.log.error( "Connection failed to the host" )
diff --git a/TestON/drivers/common/cli/remotetestbed/remotevmdriver.py b/TestON/drivers/common/cli/remotetestbed/remotevmdriver.py
index 4592e71..4f97854 100644
--- a/TestON/drivers/common/cli/remotetestbed/remotevmdriver.py
+++ b/TestON/drivers/common/cli/remotetestbed/remotevmdriver.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python
-'''
+"""
Created on 12-Feb-2013
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,12 +16,11 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
RemoteVMDriver is the basic driver which will handle the Mininet functions
-'''
-
+"""
import pexpect
import struct
import fcntl
@@ -31,68 +30,100 @@
import sys
import time
-sys.path.append("../")
+sys.path.append( "../" )
from drivers.common.cli.remotetestbeddriver import RemoteTestBedDriver
-class RemoteVMDriver(RemoteTestBedDriver):
- '''
- RemoteVMDriver is the basic driver which will handle the Mininet functions
- '''
- def __init__(self):
- super(RemoteTestBedDriver, self).__init__()
-
- def connect(self,**connectargs):
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- self.handle = super(RemoteVMDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
- if self.handle :
- main.log.info(self.name+" connected successfully ")
+class RemoteVMDriver( RemoteTestBedDriver ):
+
+ """
+ RemoteVMDriver is the basic driver which will handle the Mininet functions
+ """
+ def __init__( self ):
+ super( RemoteTestBedDriver, self ).__init__()
+
+ def connect( self, **connectargs ):
+ for key in connectargs:
+ vars( self )[ key ] = connectargs[ key ]
+
+ self.name = self.options[ 'name' ]
+
+ self.handle = super(
+ RemoteVMDriver,
+ self ).connect(
+ user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd )
+ if self.handle:
+ main.log.info( self.name + " connected successfully " )
return self.handle
return main.TRUE
- def SSH(self,**connectargs):
+
+ def SSH( self, **connectargs ):
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- '''
+ vars( self )[ key ] = connectargs[ key ]
+
+ """
Connection will establish to the remote host using ssh.
It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
+ and will return the handle.
+ """
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
+ vars( self )[ key ] = connectargs[ key ]
+
ssh_newkey = 'Are you sure you want to continue connecting'
- refused = "ssh: connect to host "+self.ip_address+" port 22: Connection refused"
+ refused = "ssh: connect to host " + \
+ self.ip_address + " port 22: Connection refused"
if self.port:
- self.handle.sendline('ssh -p '+self.port+' '+self.user_name+'@'+self.ip_address)
- else :
- self.handle.sendline('ssh '+self.user_name+'@'+self.ip_address)
- self.handle.sendline("\r")
-
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused],120)
-
- if i==0:
- main.log.info("ssh key confirmation received, send yes")
- self.handle.sendline('yes')
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
- if i==1:
- main.log.info("ssh connection asked for password, gave password")
- self.handle.sendline(self.pwd)
- self.handle.expect('>|#|$')
-
- elif i==2:
- main.log.error("Connection timeout")
+ self.handle.sendline(
+ 'ssh -p ' +
+ self.port +
+ ' ' +
+ self.user_name +
+ '@' +
+ self.ip_address )
+ else:
+ self.handle.sendline(
+ 'ssh ' +
+ self.user_name +
+ '@' +
+ self.ip_address )
+ self.handle.sendline( "\r" )
+
+ i = self.handle.expect( [ ssh_newkey,
+ 'password:',
+ pexpect.EOF,
+ pexpect.TIMEOUT,
+ refused ],
+ 120 )
+
+ if i == 0:
+ main.log.info( "ssh key confirmation received, send yes" )
+ self.handle.sendline( 'yes' )
+ i = self.handle.expect( [ ssh_newkey, 'password:', pexpect.EOF ] )
+ if i == 1:
+ main.log.info( "ssh connection asked for password, gave password" )
+ self.handle.sendline( self.pwd )
+ self.handle.expect( '>|#|$' )
+
+ elif i == 2:
+ main.log.error( "Connection timeout" )
return main.FALSE
- elif i==3: #timeout
- main.log.error("No route to the Host "+self.user_name+"@"+self.ip_address)
+ elif i == 3: # timeout
+ main.log.error(
+ "No route to the Host " +
+ self.user_name +
+ "@" +
+ self.ip_address )
return main.FALSE
- elif i==4:
- main.log.error("ssh: connect to host "+self.ip_address+" port 22: Connection refused")
+ elif i == 4:
+ main.log.error(
+ "ssh: connect to host " +
+ self.ip_address +
+ " port 22: Connection refused" )
return main.FALSE
- self.handle.sendline("\r")
+ self.handle.sendline( "\r" )
return main.TRUE
diff --git a/TestON/drivers/common/cli/remotetestbeddriver.py b/TestON/drivers/common/cli/remotetestbeddriver.py
index 79fbf1c..eaeacd9 100644
--- a/TestON/drivers/common/cli/remotetestbeddriver.py
+++ b/TestON/drivers/common/cli/remotetestbeddriver.py
@@ -1,13 +1,13 @@
#!/usr/bin/env python
-'''
-Created on 26-Oct-2012
+"""
+Created on 26-Oct-2012
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
+author:: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -15,44 +15,66 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import time
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
import sys
-sys.path.append("../")
+import signal
+import sys
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class RemoteTestBedDriver(CLI):
- # The common functions for emulator included in RemoteTestBedDriver
- def __init__(self):
- super(CLI, self).__init__()
-
- def connect(self,**connectargs):
- for key in connectargs:
- vars(self)['vm_'+key] = connectargs[key]
- remote_user_name = main.componentDictionary[self.name]['remote_user_name']
- remote_ip_address = main.componentDictionary[self.name]['remote_ip_address']
- remote_port = main.componentDictionary[self.name]['remote_port']
- remote_pwd = main.componentDictionary[self.name]['remote_pwd']
-
- self.handle = super(RemoteTestBedDriver,self).connect(user_name = remote_user_name,
- ip_address = remote_ip_address,
- port = remote_port, pwd = remote_pwd)
-
+class RemoteTestBedDriver( CLI ):
+ # The common functions for emulator included in RemoteTestBedDriver
+
+ def __init__( self ):
+ super( CLI, self ).__init__()
+
+ def connect( self, **connectargs ):
+ for key in connectargs:
+ vars( self )[ 'vm_' + key ] = connectargs[ key ]
+
+ remote_user_name = main.componentDictionary[
+ self.name ][ 'remote_user_name' ]
+ remote_ip_address = main.componentDictionary[
+ self.name ][ 'remote_ip_address' ]
+ remote_port = main.componentDictionary[ self.name ][ 'remote_port' ]
+ remote_pwd = main.componentDictionary[ self.name ][ 'remote_pwd' ]
+
+ self.handle = super(
+ RemoteTestBedDriver,
+ self ).connect(
+ user_name=remote_user_name,
+ ip_address=remote_ip_address,
+ port=remote_port,
+ pwd=remote_pwd )
+
if self.handle:
- self.execute(cmd= "\n",prompt= "\$|>|#",timeout= 10)
- self.execute(cmd= "SET CYGWIN=notty",prompt= "\$|>|#",timeout= 10)
- self.execute(cmd= "\n",prompt= "\$|>|#",timeout= 10)
- main.log.info("ssh "+self.vm_user_name+'@'+self.vm_ip_address)
- self.execute(cmd= "ssh "+self.vm_user_name+'@'+self.vm_ip_address,prompt= "(.*)",timeout= 10)
- self.execute(cmd= "\n",prompt= "assword:",timeout= 10)
- self.execute(cmd = self.vm_pwd,prompt = "\$",timeout = 10)
-
+ self.execute( cmd="\n", prompt="\$|>|#", timeout=10 )
+ self.execute( cmd="SET CYGWIN=notty", prompt="\$|>|#", timeout=10 )
+ self.execute( cmd="\n", prompt="\$|>|#", timeout=10 )
+ main.log.info(
+ "ssh " +
+ self.vm_user_name +
+ '@' +
+ self.vm_ip_address )
+ self.execute(
+ cmd="ssh " +
+ self.vm_user_name +
+ '@' +
+ self.vm_ip_address,
+ prompt="(.*)",
+ timeout=10 )
+ self.execute( cmd="\n", prompt="assword:", timeout=10 )
+ self.execute( cmd=self.vm_pwd, prompt="\$", timeout=10 )
+
return self.handle
- else :
+ else:
return main.FALSE
diff --git a/TestON/drivers/common/cli/tool/dpctlclidriver.py b/TestON/drivers/common/cli/tool/dpctlclidriver.py
index 3ad5bba..252fb8c 100644
--- a/TestON/drivers/common/cli/tool/dpctlclidriver.py
+++ b/TestON/drivers/common/cli/tool/dpctlclidriver.py
@@ -1,14 +1,14 @@
#/usr/bin/env python
-'''
+"""
Created on 26-Nov-2012
-
-@author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
+
+author:: Raghav Kashyap( raghavkashyap@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,14 +16,18 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
DPCTL driver class provides the basic functions of DPCTL controller
-'''
+"""
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
+import sys
+import signal
import sys
from drivers.common.cli.toolsdriver import Tools
import pydoc
@@ -32,214 +36,280 @@
import os
import sys
-class DpctlCliDriver(Tools):
- '''
+
+class DpctlCliDriver( Tools ):
+
+ """
DpctlCliDriver driver class provides the basic functions of DPCTL controller
- '''
- def __init__(self):
- super(DpctlCliDriver, self).__init__()
+ """
+ def __init__( self ):
+ super( DpctlCliDriver, self ).__init__()
self.handle = self
- self.wrapped = sys.modules[__name__]
-
- def connect(self,**connectargs):
-
+ self.wrapped = sys.modules[ __name__ ]
+
+ def connect( self, **connectargs ):
+
for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
-
- self.handle = super(DpctlCliDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = None, pwd = self.pwd)
- if self.handle :
- main.log.info("Connected to the host")
- return main.TRUE
- else :
- main.log.error("Connection failed to the host "+self.user_name+"@"+self.ip_address)
- return main.FALSE
+ vars( self )[ key ] = connectargs[ key ]
- def addFlow(self,**flowParameters):
- '''
+ self.name = self.options[ 'name' ]
+
+ self.handle = super(
+ DpctlCliDriver, self ).connect( user_name=self.user_name,
+ ip_address=self.ip_address,
+ port=None,
+ pwd=self.pwd )
+ if self.handle:
+ main.log.info( "Connected to the host" )
+ return main.TRUE
+ else:
+ main.log.error(
+ "Connection failed to the host " +
+ self.user_name +
+ "@" +
+ self.ip_address )
+ return main.FALSE
+
+ def addFlow( self, **flowParameters ):
+ """
addFlow create a new flow entry into flow table using "dpctl"
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT","INPORT","ACTION","TIMEOUT"],**flowParameters)
+ """
+ args = utilities.parse_args( [
+ "TCPIP",
+ "TCPPORT",
+ "INPORT",
+ "ACTION",
+ "TIMEOUT" ],
+ **flowParameters )
+
cmd = "dpctl add-flow tcp:"
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- timeOut = args["TIMEOUT"] if args["TIMEOUT"] != None else 120
- cmd = cmd + tcpIP + ":" + tcpPort + " in_port=" + str(args["INPORT"]) + ",idle_timeout=" + str(args["TIMEOUT"]) +",actions=" + args["ACTION"]
- response = self.execute(cmd=cmd,prompt="\~\$",timeout=60 )
- if utilities.assert_matches(expect="openflow",actual=response,onpass="Flow Added Successfully",onfail="Adding Flow Failed!!!"):
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ timeOut = args[ "TIMEOUT" ] if args[ "TIMEOUT" ] is not None else 120
+ cmd = cmd + tcpIP + ":" + tcpPort + " in_port=" + \
+ str( args[ "INPORT" ] ) + ",idle_timeout=" + str(
+ args[ "TIMEOUT" ] ) + ",actions=" + args[ "ACTION" ]
+ response = self.execute( cmd=cmd, prompt="\~\$", timeout=60 )
+ if utilities.assert_matches( expect="openflow", actual=response, onpass="Flow Added Successfully", onfail="Adding Flow Failed!!!" ):
return main.TRUE
- else :
+ else:
return main.FALSE
- def showFlow(self,**flowParameters):
- '''
+ def showFlow( self, **flowParameters ):
+ """
showFlow dumps the flow entries of flow table using "dpctl"
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- command = "dpctl show tcp:" + str(tcpIP) + ":" + str(tcpPort)
- response = self.execute(cmd=command,prompt="get_config_reply",timeout=240)
- if utilities.assert_matches(expect='features_reply',actual=response,onpass="Show flow executed",onfail="Show flow execution Failed"):
+ """
+ args = utilities.parse_args( [ "TCPIP", "TCPPORT" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ command = "dpctl show tcp:" + str( tcpIP ) + ":" + str( tcpPort )
+ response = self.execute(
+ cmd=command,
+ prompt="get_config_reply",
+ timeout=240 )
+ if utilities.assert_matches( expect='features_reply', actual=response, onpass="Show flow executed", onfail="Show flow execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
- def dumpFlow(self,**flowParameters):
- '''
+ def dumpFlow( self, **flowParameters ):
+ """
dumpFlow gives installed flow information
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- command = "dpctl dump-flows tcp:" + str(tcpIP) + ":" + str(tcpPort)
- response = self.execute(cmd=command,prompt="type=",timeout=240)
- if utilities.assert_matches(expect='stats_reply',actual=response,onpass="Dump flow executed",onfail="Dump flow execution Failed"):
+ """
+ args = utilities.parse_args( [ "TCPIP", "TCPPORT" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ command = "dpctl dump-flows tcp:" + str( tcpIP ) + ":" + str( tcpPort )
+ response = self.execute( cmd=command, prompt="type=", timeout=240 )
+ if utilities.assert_matches( expect='stats_reply', actual=response, onpass="Dump flow executed", onfail="Dump flow execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
-
- def dumpTables(self,**flowParameters):
- '''
+ def dumpTables( self, **flowParameters ):
+ """
dumpTables gives statistics for each of the flow tables used by datapath switch.
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- command = "dpctl dump-tables tcp:" + str(tcpIP) + ":" + str(tcpPort)
- response = self.execute(cmd=command,prompt="matched",timeout=240)
- if utilities.assert_matches(expect='lookup=3',actual=response,onpass="Dump Tables executed",onfail="Dump Tables execution Failed"):
+ """
+ args = utilities.parse_args( [ "TCPIP", "TCPPORT" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ command = "dpctl dump-tables tcp:" + \
+ str( tcpIP ) + ":" + str( tcpPort )
+ response = self.execute( cmd=command, prompt="matched", timeout=240 )
+ if utilities.assert_matches( expect='lookup=3', actual=response, onpass="Dump Tables executed", onfail="Dump Tables execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
-
- def dumpPorts(self,**flowParameters):
- '''
+
+ def dumpPorts( self, **flowParameters ):
+ """
dumpPorts gives ports information
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- command = "dpctl dump-ports tcp:" + str(tcpIP) + ":" + str(tcpPort)
- response = self.execute(cmd=command,prompt="rx pkts",timeout=240)
- if utilities.assert_matches(expect='ports',actual=response,onpass="Dump Ports executed",onfail="Dump Ports execution Failed"):
+ """
+ args = utilities.parse_args( [ "TCPIP", "TCPPORT" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ command = "dpctl dump-ports tcp:" + str( tcpIP ) + ":" + str( tcpPort )
+ response = self.execute( cmd=command, prompt="rx pkts", timeout=240 )
+ if utilities.assert_matches( expect='ports', actual=response, onpass="Dump Ports executed", onfail="Dump Ports execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
-
- def dumpAggregate(self,**flowParameters):
- '''
+ def dumpAggregate( self, **flowParameters ):
+ """
dumpAggregate gives installed flow information.ggregate statistics for flows in datapath WITCH's tables that match flows.
If flows is omitted, the statistics are aggregated across all flows in the datapath's flow tables
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT","FLOW"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- flow = args["FLOW"] if args["FLOW"] != None else ""
- command = "dpctl dump-aggregate tcp:" + str(tcpIP) + ":" + str(tcpPort) + " " + str (flow)
- response = self.execute(cmd=command,prompt="flow_count=",timeout=240)
- if utilities.assert_matches(expect='stats_reply',actual=response,onpass="Dump Aggregate executed",onfail="Dump Aggregate execution Failed"):
+ """
+ args = utilities.parse_args(
+ [ "TCPIP", "TCPPORT", "FLOW" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ flow = args[ "FLOW" ] if args[ "FLOW" ] is not None else ""
+ command = "dpctl dump-aggregate tcp:" + \
+ str( tcpIP ) + ":" + str( tcpPort ) + " " + str( flow )
+ response = self.execute(
+ cmd=command,
+ prompt="flow_count=",
+ timeout=240 )
+ if utilities.assert_matches( expect='stats_reply', actual=response, onpass="Dump Aggregate executed", onfail="Dump Aggregate execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
- def delFlow(self,**flowParameters):
- '''
+ def delFlow( self, **flowParameters ):
+ """
delFlow Deletes entries from the datapath switch's tables that match flow
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT","FLOW"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- flow = args["FLOW"] if args["FLOW"] != None else ""
- command = "dpctl del-flows tcp:" + str(tcpIP) + ":" + str(tcpPort) + " " +str(flow)
- response = self.execute(cmd=command,prompt="ETH-Tutorial",timeout=240)
- if utilities.assert_matches(expect='@',actual=response,onpass="Delete flow executed",onfail="Delete flow execution Failed"):
+ """
+ args = utilities.parse_args(
+ [ "TCPIP", "TCPPORT", "FLOW" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ flow = args[ "FLOW" ] if args[ "FLOW" ] is not None else ""
+ command = "dpctl del-flows tcp:" + \
+ str( tcpIP ) + ":" + str( tcpPort ) + " " + str( flow )
+ response = self.execute(
+ cmd=command,
+ prompt="ETH-Tutorial",
+ timeout=240 )
+ if utilities.assert_matches( expect='@', actual=response, onpass="Delete flow executed", onfail="Delete flow execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
- def show(self,**flowParameters):
- '''
+ def show( self, **flowParameters ):
+ """
show gives information on datapath switch including information on its flow tables and ports.
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- command = "dpctl show tcp:" + str(tcpIP) + ":" + str(tcpPort)
- response = self.execute(cmd=command,prompt="miss_send_len=",timeout=240)
- if utilities.assert_matches(expect='get_config_reply',actual=response,onpass="show command executed",onfail="show command execution Failed"):
+ """
+ args = utilities.parse_args( [ "TCPIP", "TCPPORT" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ command = "dpctl show tcp:" + str( tcpIP ) + ":" + str( tcpPort )
+ response = self.execute(
+ cmd=command,
+ prompt="miss_send_len=",
+ timeout=240 )
+ if utilities.assert_matches( expect='get_config_reply', actual=response, onpass="show command executed", onfail="show command execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
- def showStatus(self,**flowParameters):
- '''
- showStatus gives a series of key-value pairs that report the status of switch.
- If key is specified, only the key-value pairs whose key names begin with key are printed.
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT","KEY"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- key = args["KEY"] if args["KEY"] != None else ""
- command = "dpctl status tcp:" + str(tcpIP) + ":" + str(tcpPort) + " " + key
- response = self.execute(cmd=command,prompt="(.*)",timeout=240)
- if utilities.assert_matches(expect='(.*)',actual=response,onpass="show command executed",onfail="show command execution Failed"):
+ def showStatus( self, **flowParameters ):
+ """
+ showStatus gives a series of key-value pairs that report the status of switch.
+ If key is specified, only the key-value pairs whose key names begin with key are printed.
+ """
+ args = utilities.parse_args(
+ [ "TCPIP", "TCPPORT", "KEY" ], **flowParameters )
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ key = args[ "KEY" ] if args[ "KEY" ] is not None else ""
+ command = "dpctl status tcp:" + \
+ str( tcpIP ) + ":" + str( tcpPort ) + " " + key
+ response = self.execute( cmd=command, prompt="(.*)", timeout=240 )
+ if utilities.assert_matches( expect='(.*)', actual=response, onpass="show command executed", onfail="show command execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
- def desc_set(self,**flowParameters):
- '''
- desc_set Sets the switch description (as returned in ofp_desc_stats) to string (max length is DESC_STR_LEN)
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT","STRING"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- string = " " + args["STRING"] if args["STRING"] != None else " DESC_STR_LEN"
- command = "dpctl desc tcp:" + str(tcpIP) + ":" + str(tcpPort) + str(string)
- response = self.execute(cmd=command,prompt="ETH-Tutorial",timeout=240)
- if utilities.assert_matches(expect='@',actual=response,onpass="desc command executed",onfail="desc command execution Failed"):
+ def desc_set( self, **flowParameters ):
+ """
+ desc_set Sets the switch description ( as returned in ofp_desc_stats ) to string ( max length is DESC_STR_LEN )
+ """
+ args = utilities.parse_args( [
+ "TCPIP",
+ "TCPPORT",
+ "STRING" ],
+ **flowParameters )
+
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ string = " " + args[ "STRING" ] if args[
+ "STRING" ] is not None else " DESC_STR_LEN"
+ command = "dpctl desc tcp:" + \
+ str( tcpIP ) + ":" + str( tcpPort ) + str( string )
+ response = self.execute(
+ cmd=command,
+ prompt="ETH-Tutorial",
+ timeout=240 )
+ if utilities.assert_matches( expect='@', actual=response, onpass="desc command executed", onfail="desc command execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
- def dumpDesc(self,**flowParameters):
- '''
- dumpDesc Sets the switch description (as returned in ofp_desc_stats) to string (max length is DESC_STR_LEN)
- '''
- args = utilities.parse_args(["TCPIP","TCPPORT","STRING"],**flowParameters)
- tcpIP = args["TCPIP"] if args["TCPIP"] != None else "127.0.0.1"
- tcpPort = args["TCPPORT"] if args["TCPPORT"] != None else "6634"
- command = "dpctl dump-desc tcp:" + str(tcpIP) + ":" + str(tcpPort)
- response = self.execute(cmd=command,prompt="Serial Num:",timeout=240)
- if utilities.assert_matches(expect='stats_reply',actual=response,onpass="desc command executed",onfail="desc command execution Failed"):
+ def dumpDesc( self, **flowParameters ):
+ """
+ dumpDesc Sets the switch description ( as returned in ofp_desc_stats ) to string ( max length is DESC_STR_LEN )
+ """
+ args = utilities.parse_args( [
+ "TCPIP",
+ "TCPPORT",
+ "STRING" ],
+ **flowParameters )
+
+ tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
+ tcpPort = args[ "TCPPORT" ] if args[
+ "TCPPORT" ] is not None else "6634"
+ command = "dpctl dump-desc tcp:" + str( tcpIP ) + ":" + str( tcpPort )
+ response = self.execute(
+ cmd=command,
+ prompt="Serial Num:",
+ timeout=240 )
+ if utilities.assert_matches( expect='stats_reply', actual=response, onpass="desc command executed", onfail="desc command execution Failed" ):
main.last_result = main.TRUE
return main.TRUE
- else :
+ else:
main.last_result = main.FALSE
return main.FALSE
if __name__ != "__main__":
import sys
- sys.modules[__name__] = DpctlCliDriver()
+ sys.modules[ __name__ ] = DpctlCliDriver()
+
diff --git a/TestON/drivers/common/cli/toolsdriver.py b/TestON/drivers/common/cli/toolsdriver.py
index 2c165f9..ec4585f 100644
--- a/TestON/drivers/common/cli/toolsdriver.py
+++ b/TestON/drivers/common/cli/toolsdriver.py
@@ -1,13 +1,13 @@
#!/usr/bin/env python
-'''
+"""
Created on 26-Nov-2012
-@author: Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
+author:: Raghav Kashyap( raghavkashyap@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -15,18 +15,23 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
import pexpect
-import struct, fcntl, os, sys, signal
+import struct
+import fcntl
+import os
import sys
-sys.path.append("../")
+import signal
+import sys
+sys.path.append( "../" )
from drivers.common.clidriver import CLI
-class Tools(CLI):
+class Tools( CLI ):
# The common functions for Tools included in toolsdriver
- def __init__(self):
- super(CLI, self).__init__()
+
+ def __init__( self ):
+ super( CLI, self ).__init__()
diff --git a/TestON/drivers/common/clidriver.py b/TestON/drivers/common/clidriver.py
index eed6478..6d7fb2a 100644
--- a/TestON/drivers/common/clidriver.py
+++ b/TestON/drivers/common/clidriver.py
@@ -1,15 +1,15 @@
#!/usr/bin/env python
-'''
+"""
Created on 24-Oct-2012
-
-@authors: Anil Kumar (anilkumar.s@paxterrasolutions.com),
- Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
+
+author:s: Anil Kumar ( anilkumar.s@paxterrasolutions.com ),
+ Raghav Kashyap( raghavkashyap@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -17,78 +17,117 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-'''
+
+"""
import pexpect
-import struct, fcntl, os, sys, signal
-import sys, re
-sys.path.append("../")
+import struct
+import fcntl
+import os
+import sys
+import signal
+import sys
+import re
+sys.path.append( "../" )
from drivers.component import Component
-class CLI(Component):
- '''
+
+
+class CLI( Component ):
+
+ """
This will define common functions for CLI included.
- '''
- def __init__(self):
- super(Component, self).__init__()
-
- def connect(self,**connectargs):
- '''
+ """
+ def __init__( self ):
+ super( Component, self ).__init__()
+
+ def connect( self, **connectargs ):
+ """
Connection will establish to the remote host using ssh.
It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
+ and will return the handle.
+ """
for key in connectargs:
- vars(self)[key] = connectargs[key]
+ vars( self )[ key ] = connectargs[ key ]
- connect_result = super(CLI, self).connect()
+ connect_result = super( CLI, self ).connect()
ssh_newkey = 'Are you sure you want to continue connecting'
- refused = "ssh: connect to host "+self.ip_address+" port 22: Connection refused"
+ refused = "ssh: connect to host " + \
+ self.ip_address + " port 22: Connection refused"
if self.port:
- self.handle =pexpect.spawn('ssh -p '+self.port+' '+self.user_name+'@'+self.ip_address, env = {"TERM": "xterm-mono"} , maxread=50000)
- else :
- self.handle =pexpect.spawn('ssh -X '+self.user_name+'@'+self.ip_address, env = {"TERM": "xterm-mono"} ,maxread=1000000,timeout=60)
+ self.handle = pexpect.spawn(
+ 'ssh -p ' +
+ self.port +
+ ' ' +
+ self.user_name +
+ '@' +
+ self.ip_address,
+ env={ "TERM": "xterm-mono" },
+ maxread=50000 )
+ else:
+ self.handle = pexpect.spawn(
+ 'ssh -X ' +
+ self.user_name +
+ '@' +
+ self.ip_address,
+ env={ "TERM": "xterm-mono" },
+ maxread=1000000,
+ timeout=60 )
self.handle.logfile = self.logfile_handler
- i = 5
- while i == 5:
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused,'teston>','>|#|\$'],120)
- if i==0:
- main.log.info("ssh key confirmation received, send yes")
- self.handle.sendline('yes')
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
- if i==1:
- main.log.info("ssh connection asked for password, gave password")
- self.handle.sendline(self.pwd)
- self.handle.expect('>|#|\$')
- elif i==2:
- main.log.error("Connection timeout")
- return main.FALSE
- elif i==3: #timeout
- main.log.error("No route to the Host "+self.user_name+"@"+self.ip_address)
- return main.FALSE
- elif i==4:
- main.log.error("ssh: connect to host "+self.ip_address+" port 22: Connection refused")
- return main.FALSE
- elif i==6:
- main.log.info("Password not required logged in")
+ i = 5
+ while i == 5:
+ i = self.handle.expect( [
+ ssh_newkey,
+ 'password:',
+ pexpect.EOF,
+ pexpect.TIMEOUT,
+ refused,
+ 'teston>',
+ '>|#|\$' ],
+ 120 )
+ if i == 0:
+ main.log.info( "ssh key confirmation received, send yes" )
+ self.handle.sendline( 'yes' )
+ i = self.handle.expect(
+ [ ssh_newkey, 'password:', pexpect.EOF ] )
+ if i == 1:
+ main.log.info(
+ "ssh connection asked for password, gave password" )
+ self.handle.sendline( self.pwd )
+ self.handle.expect( '>|#|\$' )
+ elif i == 2:
+ main.log.error( "Connection timeout" )
+ return main.FALSE
+ elif i == 3: # timeout
+ main.log.error(
+ "No route to the Host " +
+ self.user_name +
+ "@" +
+ self.ip_address )
+ return main.FALSE
+ elif i == 4:
+ main.log.error(
+ "ssh: connect to host " +
+ self.ip_address +
+ " port 22: Connection refused" )
+ return main.FALSE
+ elif i == 6:
+ main.log.info( "Password not required logged in" )
- self.handle.sendline("")
- self.handle.expect('>|#|\$')
+ self.handle.sendline( "" )
+ self.handle.expect( '>|#|\$' )
return self.handle
-
- def disconnect(self):
- result = super(CLI, self).disconnect(self)
+ def disconnect( self ):
+ result = super( CLI, self ).disconnect( self )
result = main.TRUE
- #self.execute(cmd="exit",timeout=120,prompt="(.*)")
-
-
- def execute(self, **execparams):
- '''
+ # self.execute( cmd="exit",timeout=120,prompt="(.*)" )
+
+ def execute( self, **execparams ):
+ """
It facilitates the command line execution of a given command. It has arguments as :
cmd => represents command to be executed,
prompt => represents expect command prompt or output,
@@ -96,127 +135,171 @@
more => to provide a key press if it is on.
It will return output of command exection.
- '''
-
- result = super(CLI, self).execute(self)
+ """
+ result = super( CLI, self ).execute( self )
defaultPrompt = '.*[$>\#]'
- args = utilities.parse_args(["CMD", "TIMEOUT", "PROMPT", "MORE"], **execparams)
- expectPrompt = args["PROMPT"] if args["PROMPT"] else defaultPrompt
+ args = utilities.parse_args( [
+ "CMD",
+ "TIMEOUT",
+ "PROMPT",
+ "MORE" ],
+ **execparams )
+
+ expectPrompt = args[ "PROMPT" ] if args[ "PROMPT" ] else defaultPrompt
self.LASTRSP = ""
- timeoutVar = args["TIMEOUT"] if args["TIMEOUT"] else 10
+ timeoutVar = args[ "TIMEOUT" ] if args[ "TIMEOUT" ] else 10
cmd = ''
- if args["CMD"]:
- cmd = args["CMD"]
- else :
+ if args[ "CMD" ]:
+ cmd = args[ "CMD" ]
+ else:
return 0
- if args["MORE"] == None:
- args["MORE"] = " "
- self.handle.sendline(cmd)
+ if args[ "MORE" ] is None:
+ args[ "MORE" ] = " "
+ self.handle.sendline( cmd )
self.lastCommand = cmd
- index = self.handle.expect([expectPrompt, "--More--", 'Command not found.', pexpect.TIMEOUT,"^:$"], timeout = timeoutVar)
+ index = self.handle.expect( [
+ expectPrompt,
+ "--More--",
+ 'Command not found.',
+ pexpect.TIMEOUT,
+ "^:$" ],
+ timeout=timeoutVar )
if index == 0:
- self.LASTRSP = self.LASTRSP + self.handle.before + self.handle.after
- main.log.info("Executed :"+str(cmd)+" \t\t Expected Prompt '"+ str(expectPrompt)+"' Found")
+ self.LASTRSP = self.LASTRSP + \
+ self.handle.before + self.handle.after
+ main.log.info(
+ "Executed :" + str(
+ cmd ) + " \t\t Expected Prompt '" + str(
+ expectPrompt) + "' Found" )
elif index == 1:
self.LASTRSP = self.LASTRSP + self.handle.before
- self.handle.send(args["MORE"])
- main.log.info("Found More screen to go , Sending a key to proceed")
- indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
+ self.handle.send( args[ "MORE" ] )
+ main.log.info(
+ "Found More screen to go , Sending a key to proceed" )
+ indexMore = self.handle.expect(
+ [ "--More--", expectPrompt ], timeout=timeoutVar )
while indexMore == 0:
- main.log.info("Found anoother More screen to go , Sending a key to proceed")
- self.handle.send(args["MORE"])
- indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
+ main.log.info(
+ "Found anoother More screen to go , Sending a key to proceed" )
+ self.handle.send( args[ "MORE" ] )
+ indexMore = self.handle.expect(
+ [ "--More--", expectPrompt ], timeout=timeoutVar )
self.LASTRSP = self.LASTRSP + self.handle.before
- elif index ==2:
- main.log.error("Command not found")
+ elif index == 2:
+ main.log.error( "Command not found" )
self.LASTRSP = self.LASTRSP + self.handle.before
- elif index ==3:
- main.log.error("Expected Prompt not found , Time Out!!")
- main.log.error( expectPrompt )
+ elif index == 3:
+ main.log.error( "Expected Prompt not found , Time Out!!" )
+ main.log.error( expectPrompt )
return "Expected Prompt not found , Time Out!!"
-
+
elif index == 4:
self.LASTRSP = self.LASTRSP + self.handle.before
- #self.handle.send(args["MORE"])
- self.handle.sendcontrol("D")
- main.log.info("Found More screen to go , Sending a key to proceed")
- indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
+ # self.handle.send( args[ "MORE" ] )
+ self.handle.sendcontrol( "D" )
+ main.log.info(
+ "Found More screen to go , Sending a key to proceed" )
+ indexMore = self.handle.expect(
+ [ "^:$", expectPrompt ], timeout=timeoutVar )
while indexMore == 0:
- main.log.info("Found another More screen to go , Sending a key to proceed")
- self.handle.sendcontrol("D")
- indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
+ main.log.info(
+ "Found another More screen to go , Sending a key to proceed" )
+ self.handle.sendcontrol( "D" )
+ indexMore = self.handle.expect(
+ [ "^:$", expectPrompt ], timeout=timeoutVar )
self.LASTRSP = self.LASTRSP + self.handle.before
-
- main.last_response = self.remove_contol_chars(self.LASTRSP)
+
+ main.last_response = self.remove_contol_chars( self.LASTRSP )
return self.LASTRSP
-
- def remove_contol_chars(self,response):
- #RE_XML_ILLEGAL = '([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])|([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])'%(unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff))
- #response = re.sub(RE_XML_ILLEGAL, "\n", response)
- response = re.sub(r"[\x01-\x1F\x7F]", "", response)
- #response = re.sub(r"\[\d+\;1H", "\n", response)
- response = re.sub(r"\[\d+\;\d+H", "", response)
+
+ def remove_contol_chars( self, response ):
+ # RE_XML_ILLEGAL = '([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])|([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])'%( unichr( 0xd800 ),unichr( 0xdbff ),unichr( 0xdc00 ),unichr( 0xdfff ),unichr( 0xd800 ),unichr( 0xdbff ),unichr( 0xdc00 ),unichr( 0xdfff ),unichr( 0xd800 ),unichr( 0xdbff ),unichr( 0xdc00 ),unichr( 0xdfff ) )
+ # response = re.sub( RE_XML_ILLEGAL, "\n", response )
+ response = re.sub( r"[\x01-\x1F\x7F]", "", response )
+ # response = re.sub( r"\[\d+\;1H", "\n", response )
+ response = re.sub( r"\[\d+\;\d+H", "", response )
return response
-
- def runAsSudoUser(self,handle,pwd,default):
-
- i = handle.expect([".ssword:*",default, pexpect.EOF])
- if i==0:
- handle.sendline(pwd)
- handle.sendline("\r")
- if i==1:
- handle.expect(default)
-
- if i==2:
- main.log.error("Unable to run as Sudo user")
-
+ def runAsSudoUser( self, handle, pwd, default ):
+
+ i = handle.expect( [ ".ssword:*", default, pexpect.EOF ] )
+ if i == 0:
+ handle.sendline( pwd )
+ handle.sendline( "\r" )
+
+ if i == 1:
+ handle.expect( default )
+
+ if i == 2:
+ main.log.error( "Unable to run as Sudo user" )
+
return handle
-
- def onfail(self):
- if main.componentDictionary[self.name].has_key('onfail'):
- commandList = main.componentDictionary[self.name]['onfail'].split(",")
- for command in commandList :
- response = self.execute(cmd=command,prompt="(.*)",timeout=120)
- def secureCopy(self,user_name, ip_address,filepath, pwd,dst_path):
-
- #scp openflow@192.168.56.101:/home/openflow/sample /home/paxterra/Desktop/
+ def onfail( self ):
+ if 'onfail' in main.componentDictionary[ self.name ]:
+ commandList = main.componentDictionary[
+ self.name ][ 'onfail' ].split( "," )
+ for command in commandList:
+ response = self.execute(
+ cmd=command,
+ prompt="(.*)",
+ timeout=120 )
- '''
+ def secureCopy( self, user_name, ip_address, filepath, pwd, dst_path ):
+
+ # scp openflow@192.168.56.101:/home/openflow/sample
+ # /home/paxterra/Desktop/
+ """
Connection will establish to the remote host using ssh.
It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
+ and will return the handle.
+ """
ssh_newkey = 'Are you sure you want to continue connecting'
- refused = "ssh: connect to host "+ip_address+" port 22: Connection refused"
- cmd = 'scp '+str(user_name)+'@'+str(ip_address)+':'+str(filepath)+' '+str(dst_path)
- main.log.info("Sending: " + cmd )
- self.handle =pexpect.spawn( cmd )
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused],120)
+ refused = "ssh: connect to host " + \
+ ip_address + " port 22: Connection refused"
- if i==0:
- main.log.info("ssh key confirmation received, send yes")
- self.handle.sendline('yes')
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
- if i==1:
- main.log.info("ssh connection asked for password, gave password")
- self.handle.sendline(pwd)
- #self.handle.expect(user_name)
-
- elif i==2:
- main.log.error("Connection timeout")
+ cmd = 'scp ' + str( user_name ) + '@' + str( ip_address ) + ':' + \
+ str( filepath ) + ' ' + str(dst_path )
+
+ main.log.info( "Sending: " + cmd )
+ self.handle = pexpect.spawn( cmd )
+ i = self.handle.expect( [
+ ssh_newkey,
+ 'password:',
+ pexpect.EOF,
+ pexpect.TIMEOUT,
+ refused ],
+ 120 )
+
+ if i == 0:
+ main.log.info( "ssh key confirmation received, send yes" )
+ self.handle.sendline( 'yes' )
+ i = self.handle.expect( [ ssh_newkey, 'password:', pexpect.EOF ] )
+ if i == 1:
+ main.log.info( "ssh connection asked for password, gave password" )
+ self.handle.sendline( pwd )
+ # self.handle.expect( user_name )
+
+ elif i == 2:
+ main.log.error( "Connection timeout" )
pass
- elif i==3: #timeout
- main.log.error("No route to the Host "+user_name+"@"+ip_address)
+ elif i == 3: # timeout
+ main.log.error(
+ "No route to the Host " +
+ user_name +
+ "@" +
+ ip_address )
return main.FALSE
- elif i==4:
- main.log.error("ssh: connect to host "+ip_address+" port 22: Connection refused")
+ elif i == 4:
+ main.log.error(
+ "ssh: connect to host " +
+ ip_address +
+ " port 22: Connection refused" )
return main.FALSE
- self.handle.sendline("")
- self.handle.expect("$")
+ self.handle.sendline( "" )
+ self.handle.expect( "$" )
print self.handle.before
-
+
return self.handle
-
+
diff --git a/TestON/drivers/component.py b/TestON/drivers/component.py
index ec94283..1e87d03 100644
--- a/TestON/drivers/component.py
+++ b/TestON/drivers/component.py
@@ -1,16 +1,16 @@
#!/usr/bin/env python
import logging
-'''
+"""
Created on 24-Oct-2012
-
-@authors: Anil Kumar (anilkumar.s@paxterrasolutions.com),
- Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
+
+author:s: Anil Kumar ( anilkumar.s@paxterrasolutions.com ),
+ Raghav Kashyap( raghavkashyap@paxterrasolutions.com )
TestON 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 2 of the License, or
- (at your option) any later version.
+ ( at your option ) any later version.
TestON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -18,99 +18,104 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
+ along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-'''
+"""
import re
from logging import Logger
-class Component(object):
- '''
+
+class Component( object ):
+
+ """
This is the tempalte class for components
- '''
- def __init__(self):
+ """
+ def __init__( self ):
self.default = ''
- self.wrapped = sys.modules[__name__]
-
- def __getattr__(self, name):
- '''
+ self.wrapped = sys.modules[ __name__ ]
+
+ def __getattr__( self, name ):
+ """
This will invoke, if the attribute wasn't found the usual ways.
Here it will look for assert_attribute and will execute when AttributeError occurs.
It will return the result of the assert_attribute.
- '''
+ """
try:
- return getattr(self.wrapped, name)
+ return getattr( self.wrapped, name )
except AttributeError:
try:
- def experimentHandling(**kwargs):
+ def experimentHandling( **kwargs ):
if main.EXPERIMENTAL_MODE == main.TRUE:
- result = self.experimentRun(**kwargs)
- main.log.info("EXPERIMENTAL MODE. API "+str(name)+" not yet implemented. Returning dummy values")
- return result
+ result = self.experimentRun( **kwargs )
+ main.log.info( "EXPERIMENTAL MODE. API " + str(
+ name ) + " not yet implemented. Returning dummy values" )
+ return result
else:
return main.FALSE
return experimentHandling
- except TypeError,e:
- main.log.error("Arguments for experimental mode does not have key 'retruns'" + e)
-
-
- def connect(self):
-
- vars(main)[self.name+'log'] = logging.getLogger(self.name)
-
- session_file = main.logdir+"/"+self.name+".session"
- self.log_handler = logging.FileHandler(session_file)
- self.log_handler.setLevel(logging.DEBUG)
-
- vars(main)[self.name+'log'].setLevel(logging.DEBUG)
- _formatter = logging.Formatter("%(asctime)s %(name)-10s: %(levelname)-8s: %(message)s")
- self.log_handler.setFormatter(_formatter)
- vars(main)[self.name+'log'].addHandler(self.log_handler)
- # Adding header for the component log
- vars(main)[self.name+'log'].info(main.logHeader)
+ except TypeError as e:
+ main.log.error(
+ "Arguments for experimental mode does not have key 'retruns'" +
+ e )
+
+ def connect( self ):
+
+ vars( main )[ self.name + 'log' ] = logging.getLogger( self.name )
+
+ session_file = main.logdir + "/" + self.name + ".session"
+ self.log_handler = logging.FileHandler( session_file )
+ self.log_handler.setLevel( logging.DEBUG )
+
+ vars( main )[ self.name + 'log' ].setLevel( logging.DEBUG )
+ _formatter = logging.Formatter(
+ "%(asctime)s %(name)-10s: %(levelname)-8s: %(message)s" )
+ self.log_handler.setFormatter( _formatter )
+ vars( main )[ self.name + 'log' ].addHandler( self.log_handler )
+ # Adding header for the component log
+ vars( main )[ self.name + 'log' ].info( main.logHeader )
# Opening the session log to append command's execution output
- self.logfile_handler = open(session_file,"a")
-
+ self.logfile_handler = open( session_file, "a" )
+
return "Dummy"
-
- def execute(self,cmd):
+
+ def execute( self, cmd ):
return main.TRUE
- #import commands
- #return commands.getoutput(cmd)
-
- def disconnect(self):
- return main.TRUE
-
- def config(self):
+ # import commands
+ # return commands.getoutput( cmd )
+
+ def disconnect( self ):
+ return main.TRUE
+
+ def config( self ):
self = self
# Need to update the configuration code
-
- def cleanup(self):
+
+ def cleanup( self ):
return main.TRUE
-
- def log(self,message):
- '''
- Here finding the for the component to which the
+
+ def log( self, message ):
+ """
+ Here finding the for the component to which the
log message based on the called child object.
- '''
- vars(main)[self.name+'log'].info("\n"+message+"\n")
-
- def close_log_handles(self) :
- vars(main)[self.name+'log'].removeHandler(self.log_handler)
+ """
+ vars( main )[ self.name + 'log' ].info( "\n" + message + "\n" )
+
+ def close_log_handles( self ):
+ vars( main )[ self.name + 'log' ].removeHandler( self.log_handler )
if self.logfile_handler:
self.logfile_handler.close()
-
- def get_version(self):
+
+ def get_version( self ):
return "Version unknown"
- def experimentRun(self,**kwargs):
- args = utilities.parse_args(["RETURNS"],**kwargs)
- return args["RETURNS"]
+ def experimentRun( self, **kwargs ):
+ args = utilities.parse_args( [ "RETURNS" ], **kwargs )
+ return args[ "RETURNS" ]
if __name__ != "__main__":
import sys
- sys.modules[__name__] = Component()
+ sys.modules[ __name__ ] = Component()
+