[ONOS-7104]: Style fixes to the drivers directory in TestON
Change-Id: Ie151a956c15f1b1cc6ebc09a2e7474f8e4066459
diff --git a/TestON/drivers/common/api/controller/onosrestdriver.py b/TestON/drivers/common/api/controller/onosrestdriver.py
index 312f1f1..cf3eec6 100755
--- a/TestON/drivers/common/api/controller/onosrestdriver.py
+++ b/TestON/drivers/common/api/controller/onosrestdriver.py
@@ -48,7 +48,7 @@
except Exception as e:
main.log.exception( e )
try:
- if os.getenv( str( self.ip_address ) ) != None:
+ if os.getenv( str( self.ip_address ) ) is not None:
self.ip_address = os.getenv( str( self.ip_address ) )
else:
main.log.info( self.name + ": ip set to " + self.ip_address )
@@ -74,7 +74,7 @@
if isinstance( jsonObject, str ):
jsonObject = json.loads( jsonObject )
return json.dumps( jsonObject, sort_keys=True,
- indent=4, separators=(',', ': '))
+ indent=4, separators=( ',', ': ' ) )
except ( TypeError, ValueError ):
main.log.exception( "Error parsing jsonObject" )
return None
@@ -99,20 +99,20 @@
# TODO: Do we need to allow for other protocols besides http?
# ANSWER: Not yet, but potentially https with certificates
if ip == "DEFAULT":
- main.log.warn( "No ip given, reverting to ip from topo file" )
- ip = self.ip_address
+ main.log.warn( "No ip given, reverting to ip from topo file" )
+ ip = self.ip_address
if port == "DEFAULT":
- main.log.warn( "No port given, reverting to port " +
- "from topo file" )
- port = self.port
+ main.log.warn( "No port given, reverting to port " +
+ "from topo file" )
+ port = self.port
try:
path = "http://" + str( ip ) + ":" + str( port ) + base + url
if self.user_name and self.pwd:
- main.log.info("user/passwd is: " + self.user_name + "/" + self.pwd)
- auth = (self.user_name, self.pwd)
+ main.log.info( "user/passwd is: " + self.user_name + "/" + self.pwd )
+ auth = ( self.user_name, self.pwd )
else:
- auth=None
+ auth = None
main.log.info( "Sending request " + path + " using " +
method.upper() + " method." )
response = requests.request( method.upper(),
@@ -273,7 +273,7 @@
query = "/" + str( appName ) + "/active"
response = self.send( method="POST",
url="/applications" + query,
- ip = ip, port = port)
+ ip = ip, port = port )
if response:
output = response[ 1 ]
app = json.loads( output )
@@ -414,17 +414,17 @@
error on requests; Returns None for exceptions
"""
try:
- intentJson = {"two": str( hostIdTwo ),
- "selector": {"criteria": []}, "priority": 7,
- "treatment": {"deferred": [], "instructions": []},
- "appId": appId, "one": str( hostIdOne ),
- "type": "HostToHostIntent",
- "constraints": [{"type": "LinkTypeConstraint",
- "types": ["OPTICAL"],
- "inclusive": 'false' }]}
+ intentJson = { "two": str( hostIdTwo ),
+ "selector": { "criteria": [] }, "priority": 7,
+ "treatment": { "deferred": [], "instructions": [] },
+ "appId": appId, "one": str( hostIdOne ),
+ "type": "HostToHostIntent",
+ "constraints": [ { "type": "LinkTypeConstraint",
+ "types": [ "OPTICAL" ],
+ "inclusive": 'false' } ] }
if vlanId:
- intentJson[ 'selector' ][ 'criteria' ].append( { "type":"VLAN_VID",
- "vlanId":vlanId } )
+ intentJson[ 'selector' ][ 'criteria' ].append( { "type": "VLAN_VID",
+ "vlanId": vlanId } )
output = None
if ip == "DEFAULT":
main.log.warn( "No ip given, reverting to ip from topo file" )
@@ -520,63 +520,63 @@
main.log.debug( self.name + ": Egress port not specified" )
return main.FALSE
- intentJson ={ "ingressPoint": { "device": ingressDevice,
- "port": ingressPort },
- "selector": { "criteria": [] },
- "priority": 55,
- "treatment": { "deferred": [],
- "instructions": [] },
- "egressPoint": { "device": egressDevice,
- "port": egressPort },
- "appId": appId,
- "type": "PointToPointIntent",
- "constraints": [ { "type": "LinkTypeConstraint",
- "types": [ "OPTICAL" ],
- "inclusive": "false" } ] }
+ intentJson = { "ingressPoint": { "device": ingressDevice,
+ "port": ingressPort },
+ "selector": { "criteria": [] },
+ "priority": 55,
+ "treatment": { "deferred": [],
+ "instructions": [] },
+ "egressPoint": { "device": egressDevice,
+ "port": egressPort },
+ "appId": appId,
+ "type": "PointToPointIntent",
+ "constraints": [ { "type": "LinkTypeConstraint",
+ "types": [ "OPTICAL" ],
+ "inclusive": "false" } ] }
# if protected:
# intentJson['constraints'].append( { "type": "Protection", "types": ["Protection"], "inclusive": "true" } )
if ethType == "IPV4":
intentJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_TYPE",
- "ethType":2048 } )
+ "type": "ETH_TYPE",
+ "ethType": 2048 } )
elif ethType:
intentJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_TYPE",
- "ethType":ethType } )
+ "type": "ETH_TYPE",
+ "ethType": ethType } )
if ethSrc:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"ETH_SRC",
- "mac":ethSrc } )
+ { "type": "ETH_SRC",
+ "mac": ethSrc } )
if ethDst:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"ETH_DST",
- "mac":ethDst } )
+ { "type": "ETH_DST",
+ "mac": ethDst } )
if ipSrc:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"IPV4_SRC",
- "ip":ipSrc } )
+ { "type": "IPV4_SRC",
+ "ip": ipSrc } )
if ipDst:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"IPV4_DST",
- "ip":ipDst } )
+ { "type": "IPV4_DST",
+ "ip": ipDst } )
if tcpSrc:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"TCP_SRC",
+ { "type": "TCP_SRC",
"tcpPort": tcpSrc } )
if tcpDst:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"TCP_DST",
+ { "type": "TCP_DST",
"tcpPort": tcpDst } )
if ipProto:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"IP_PROTO",
+ { "type": "IP_PROTO",
"protocol": ipProto } )
if vlanId:
intentJson[ 'selector' ][ 'criteria' ].append(
- { "type":"VLAN_VID",
+ { "type": "VLAN_VID",
"vlanId": vlanId } )
# TODO: Bandwidth and Lambda will be implemented if needed
@@ -613,26 +613,26 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def addSinglepointToMultipointIntent(self,
- ingressDevice,
- egressDeviceList,
- portEgressList,
- appId='org.onosproject.cli',
- portIngress="",
- ethType="",
- ethSrc="",
- ethDst="",
- bandwidth="",
- lambdaAlloc=False,
- ipProto="",
- ipSrc="",
- ipDst="",
- tcpSrc="",
- tcpDst="",
- partial=False,
- ip="DEFAULT",
- port="DEFAULT",
- vlanId="" ):
+ def addSinglepointToMultipointIntent( self,
+ ingressDevice,
+ egressDeviceList,
+ portEgressList,
+ appId='org.onosproject.cli',
+ portIngress="",
+ ethType="",
+ ethSrc="",
+ ethDst="",
+ bandwidth="",
+ lambdaAlloc=False,
+ ipProto="",
+ ipSrc="",
+ ipDst="",
+ tcpSrc="",
+ tcpDst="",
+ partial=False,
+ ip="DEFAULT",
+ port="DEFAULT",
+ vlanId="" ):
"""
Description:
Adds a point-to-multi point intent ( uni-directional ) by
@@ -694,7 +694,7 @@
"appId": appId,
"type": "SinglePointToMultiPointIntent",
"constraints": [ { "type": "LinkTypeConstraint",
- "types": ["OPTICAL"],
+ "types": [ "OPTICAL" ],
"inclusive": "false" } ] }
index = 0
@@ -752,16 +752,16 @@
"from topo file" )
port = self.port
response = self.send( method="POST",
- url="/intents", ip=ip, port=port,
- data=json.dumps( intentJson ) )
+ url="/intents", ip=ip, port=port,
+ data=json.dumps( intentJson ) )
- main.log.debug(intentJson)
+ main.log.debug( intentJson )
if response:
if "201" in str( response[ 0 ] ):
main.log.info( self.name + ": Successfully POST point" +
" intent between ingress: " + ingressDevice +
- " and egress: " + str(egressDeviceList) + " devices" )
+ " and egress: " + str( egressDeviceList ) + " devices" )
return main.TRUE
else:
main.log.error( "Error with REST request, response was: " + str( response ) )
@@ -834,7 +834,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def removeAllIntents( self, intentIdList ='ALL',appId='org.onosproject.cli',
+ def removeAllIntents( self, intentIdList ='ALL', appId='org.onosproject.cli',
ip="DEFAULT", port="DEFAULT", delay=5 ):
"""
Description:
@@ -864,7 +864,7 @@
import time
time.sleep( delay )
intentRemain = len( json.loads( self.intents() ) )
- if all( result==main.TRUE for result in results ) and \
+ if all( result == main.TRUE for result in results ) and \
intentRemain == 0:
main.log.info( self.name + ": All intents are removed " )
return main.TRUE
@@ -947,10 +947,10 @@
query = "/" + mac + "/" + vlan
response = self.send( url="/hosts" + query, ip = ip, port = port )
if response:
- # NOTE: What if the person wants other values? would it be better
- # to have a function that gets a key and return a value instead?
- # This function requires mac and vlan and returns an ID which
- # makes this current function useless
+ # NOTE: What if the person wants other values? would it be better
+ # to have a function that gets a key and return a value instead?
+ # This function requires mac and vlan and returns an ID which
+ # makes this current function useless
if 200 <= response[ 0 ] <= 299:
output = response[ 1 ]
hostId = json.loads( output ).get( 'id' )
@@ -1095,7 +1095,7 @@
main.cleanAndExit()
def checkIntentState( self, intentsId="ALL", expectedState='INSTALLED',
- ip="DEFAULT", port="DEFAULT"):
+ ip="DEFAULT", port="DEFAULT" ):
"""
Description:
Check intents state based on expected state which defaults to
@@ -1264,7 +1264,8 @@
"""
try:
- if debug: main.log.debug( "Adding flow: " + self.pprint( flowJson ) )
+ if debug:
+ main.log.debug( "Adding flow: " + self.pprint( flowJson ) )
output = None
if ip == "DEFAULT":
main.log.warn( "No ip given, reverting to ip from topo file" )
@@ -1344,75 +1345,75 @@
of the ONOS node
"""
try:
- flowJson = { "priority":priority,
- "isPermanent":"true",
- "timeout":0,
- "deviceId":deviceId,
- "treatment":{"instructions":[]},
- "selector": {"criteria":[]}}
+ flowJson = { "priority": priority,
+ "isPermanent": "true",
+ "timeout": 0,
+ "deviceId": deviceId,
+ "treatment": { "instructions": [] },
+ "selector": { "criteria": [] }}
if appId:
flowJson[ "appId" ] = appId
if groupId:
flowJson[ 'treatment' ][ 'instructions' ].append( {
- "type":"GROUP",
- "groupId":groupId } )
+ "type": "GROUP",
+ "groupId": groupId } )
if egressPort:
flowJson[ 'treatment' ][ 'instructions' ].append( {
- "type":"OUTPUT",
- "port":egressPort } )
+ "type": "OUTPUT",
+ "port": egressPort } )
if ingressPort:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"IN_PORT",
- "port":ingressPort } )
+ "type": "IN_PORT",
+ "port": ingressPort } )
if ethType:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_TYPE",
- "ethType":ethType } )
+ "type": "ETH_TYPE",
+ "ethType": ethType } )
if ethSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_SRC",
- "mac":ethSrc } )
+ "type": "ETH_SRC",
+ "mac": ethSrc } )
if ethDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_DST",
- "mac":ethDst } )
+ "type": "ETH_DST",
+ "mac": ethDst } )
if vlan:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"VLAN_VID",
- "vlanId":vlan } )
+ "type": "VLAN_VID",
+ "vlanId": vlan } )
if mpls:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"MPLS_LABEL",
- "label":mpls } )
+ "type": "MPLS_LABEL",
+ "label": mpls } )
if ipSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":ipSrc[0],
- "ip":ipSrc[1] } )
+ "type": ipSrc[ 0 ],
+ "ip": ipSrc[ 1 ] } )
if ipDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":ipDst[0],
- "ip":ipDst[1] } )
+ "type": ipDst[ 0 ],
+ "ip": ipDst[ 1 ] } )
if tcpSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"TCP_SRC",
+ "type": "TCP_SRC",
"tcpPort": tcpSrc } )
if tcpDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"TCP_DST",
+ "type": "TCP_DST",
"tcpPort": tcpDst } )
if udpSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"UDP_SRC",
+ "type": "UDP_SRC",
"udpPort": udpSrc } )
if udpDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"UDP_DST",
+ "type": "UDP_DST",
"udpPort": udpDst } )
if ipProto:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"IP_PROTO",
+ "type": "IP_PROTO",
"protocol": ipProto } )
return self.sendFlow( deviceId=deviceId, flowJson=flowJson, debug=debug )
@@ -1628,30 +1629,30 @@
main.cleanAndExit()
def createFlowBatch( self,
- numSw = 1,
- swIndex = 1,
- batchSize = 1,
- batchIndex = 1,
- deviceIdpreFix = "of:",
- appId=0,
- deviceID="",
- ingressPort="",
- egressPort="",
- ethType="",
- ethSrc="",
- ethDst="",
- vlan="",
- ipProto="",
- ipSrc=(),
- ipDst=(),
- tcpSrc="",
- tcpDst="",
- udpDst="",
- udpSrc="",
- mpls="",
- ip="DEFAULT",
- port="DEFAULT",
- debug=False ):
+ numSw = 1,
+ swIndex = 1,
+ batchSize = 1,
+ batchIndex = 1,
+ deviceIdpreFix = "of:",
+ appId=0,
+ deviceID="",
+ ingressPort="",
+ egressPort="",
+ ethType="",
+ ethSrc="",
+ ethDst="",
+ vlan="",
+ ipProto="",
+ ipSrc=(),
+ ipDst=(),
+ tcpSrc="",
+ tcpDst="",
+ udpDst="",
+ udpSrc="",
+ mpls="",
+ ip="DEFAULT",
+ port="DEFAULT",
+ debug=False ):
"""
Description:
Creates batches of MAC-rule flows for POST.
@@ -1681,111 +1682,110 @@
The ip and port option are for the requests input's ip and port
of the ONOS node
"""
- #from pprint import pprint
+ # from pprint import pprint
flowJsonList = []
- flowJsonBatch = {"flows":flowJsonList}
+ flowJsonBatch = { "flows": flowJsonList }
dev = swIndex
- for fl in range(1, batchSize + 1):
- flowJson = { "priority":100,
- "deviceId":"",
- "isPermanent":"true",
- "timeout":0,
- "treatment":{"instructions":[]},
- "selector": {"criteria":[]}}
+ for fl in range( 1, batchSize + 1 ):
+ flowJson = { "priority": 100,
+ "deviceId": "",
+ "isPermanent": "true",
+ "timeout": 0,
+ "treatment": { "instructions": [] },
+ "selector": { "criteria": [] }}
- #main.log.info("fl: " + str(fl))
+ # main.log.info("fl: " + str(fl))
if dev <= numSw:
- deviceId = deviceIdpreFix + "{0:0{1}x}".format(dev,16)
- #print deviceId
- flowJson['deviceId'] = deviceId
+ deviceId = deviceIdpreFix + "{0:0{1}x}".format( dev, 16 )
+ # print deviceId
+ flowJson[ 'deviceId' ] = deviceId
dev += 1
else:
dev = 1
- deviceId = deviceIdpreFix + "{0:0{1}x}".format(dev,16)
- #print deviceId
- flowJson['deviceId'] = deviceId
+ deviceId = deviceIdpreFix + "{0:0{1}x}".format( dev, 16 )
+ # print deviceId
+ flowJson[ 'deviceId' ] = deviceId
dev += 1
# ethSrc starts with "0"; ethDst starts with "1"
# 2 Hex digit of device number; 5 digits of batch index number; 5 digits of batch size
- ethS = "%02X" %int( "0" + "{0:0{1}b}".format(dev,7), 2 ) + \
- "{0:0{1}x}".format(batchIndex,5) + "{0:0{1}x}".format(fl,5)
- ethSrc = ':'.join(ethS[i:i+2] for i in range(0,len(ethS),2))
- ethD = "%02X" %int( "1" + "{0:0{1}b}".format(dev,7), 2 ) + \
- "{0:0{1}x}".format(batchIndex,5) + "{0:0{1}x}".format(fl,5)
- ethDst = ':'.join(ethD[i:i+2] for i in range(0,len(ethD),2))
+ ethS = "%02X" % int( "0" + "{0:0{1}b}".format( dev, 7 ), 2 ) + \
+ "{0:0{1}x}".format( batchIndex, 5 ) + "{0:0{1}x}".format( fl, 5 )
+ ethSrc = ':'.join( ethS[ i: i+2 ] for i in range( 0, len( ethS ), 2 ) )
+ ethD = "%02X" % int( "1" + "{0:0{1}b}".format( dev, 7 ), 2 ) + \
+ "{0:0{1}x}".format( batchIndex, 5 ) + "{0:0{1}x}".format( fl, 5 )
+ ethDst = ':'.join( ethD[ i: i+2 ] for i in range( 0, len( ethD ), 2 ) )
if appId:
flowJson[ "appId" ] = appId
if egressPort:
flowJson[ 'treatment' ][ 'instructions' ].append( {
- "type":"OUTPUT",
- "port":egressPort } )
+ "type": "OUTPUT",
+ "port": egressPort } )
if ingressPort:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"IN_PORT",
- "port":ingressPort } )
+ "type": "IN_PORT",
+ "port": ingressPort } )
if ethType:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_TYPE",
- "ethType":ethType } )
+ "type": "ETH_TYPE",
+ "ethType": ethType } )
if ethSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_SRC",
- "mac":ethSrc } )
+ "type": "ETH_SRC",
+ "mac": ethSrc } )
if ethDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"ETH_DST",
- "mac":ethDst } )
+ "type": "ETH_DST",
+ "mac": ethDst } )
if vlan:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"VLAN_VID",
- "vlanId":vlan } )
+ "type": "VLAN_VID",
+ "vlanId": vlan } )
if mpls:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"MPLS_LABEL",
- "label":mpls } )
+ "type": "MPLS_LABEL",
+ "label": mpls } )
if ipSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":ipSrc[0],
- "ip":ipSrc[1] } )
+ "type": ipSrc[ 0 ],
+ "ip": ipSrc[ 1 ] } )
if ipDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":ipDst[0],
- "ip":ipDst[1] } )
+ "type": ipDst[ 0 ],
+ "ip": ipDst[ 1 ] } )
if tcpSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"TCP_SRC",
+ "type": "TCP_SRC",
"tcpPort": tcpSrc } )
if tcpDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"TCP_DST",
+ "type": "TCP_DST",
"tcpPort": tcpDst } )
if udpSrc:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"UDP_SRC",
+ "type": "UDP_SRC",
"udpPort": udpSrc } )
if udpDst:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"UDP_DST",
+ "type": "UDP_DST",
"udpPort": udpDst } )
if ipProto:
flowJson[ 'selector' ][ 'criteria' ].append( {
- "type":"IP_PROTO",
+ "type": "IP_PROTO",
"protocol": ipProto } )
- #pprint(flowJson)
- flowJsonList.append(flowJson)
+ # pprint(flowJson)
+ flowJsonList.append( flowJson )
- main.log.info("Number of flows in batch: " + str( len(flowJsonList) ) )
- flowJsonBatch['flows'] = flowJsonList
- #pprint(flowJsonBatch)
+ main.log.info( "Number of flows in batch: " + str( len( flowJsonList ) ) )
+ flowJsonBatch[ 'flows' ] = flowJsonList
+ # pprint(flowJsonBatch)
return flowJsonBatch
-
def sendFlowBatch( self, batch={}, ip="DEFAULT", port="DEFAULT", debug=False ):
"""
Description:
@@ -1803,7 +1803,8 @@
import time
try:
- if debug: main.log.debug( "Adding flow: " + self.pprint( batch ) )
+ if debug:
+ main.log.debug( "Adding flow: " + self.pprint( batch ) )
output = None
if ip == "DEFAULT":
main.log.warn( "No ip given, reverting to ip from topo file" )
@@ -1816,8 +1817,8 @@
response = self.send( method="POST",
url=url, ip = ip, port = port,
data=json.dumps( batch ) )
- #main.log.info("Post response is: ", str(response[0]))
- if response[0] == 200:
+ # main.log.info("Post response is: ", str(response[0]))
+ if response[ 0 ] == 200:
main.log.info( self.name + ": Successfully POST flow batch" )
return main.TRUE, response
else:
@@ -1834,7 +1835,7 @@
main.cleanAndExit()
def removeFlowBatch( self, batch={},
- ip="DEFAULT", port="DEFAULT" ):
+ ip="DEFAULT", port="DEFAULT" ):
"""
Description:
Remove a batch of flows
@@ -1857,7 +1858,7 @@
response = self.send( method="DELETE",
url="/flows/", ip = ip, port = port,
- data = json.dumps(batch) )
+ data = json.dumps( batch ) )
if response:
if 200 <= response[ 0 ] <= 299:
return main.TRUE
@@ -1882,7 +1883,7 @@
import json
try:
# either onos:topology or 'topology' will work in CLI
- topology = json.loads(topologyOutput)
+ topology = json.loads( topologyOutput )
main.log.debug( topology )
return topology
except pexpect.EOF:
@@ -1914,7 +1915,7 @@
"""
try:
topology = self.getTopology( self.topology() )
- #summary = self.summary()
+ # summary = self.summary()
if topology == {}:
return main.ERROR
output = ""
@@ -1978,7 +1979,7 @@
"appCookie": appCookie,
"groupId": groupId,
"buckets": bucketList
- }
+ }
return self.sendGroup( deviceId=deviceId, groupJson=groupJson, ip="DEFAULT", port="DEFAULT", debug=False )
except ( AttributeError, TypeError ):
@@ -2004,7 +2005,8 @@
of the ONOS node
"""
try:
- if debug: main.log.debug( "Adding group: " + self.pprint( groupJson ) )
+ if debug:
+ main.log.debug( "Adding group: " + self.pprint( groupJson ) )
output = None
if ip == "DEFAULT":
main.log.warn( "No ip given, reverting to ip from topo file" )
@@ -2064,7 +2066,7 @@
if deviceId:
url += "/" + deviceId
if appCookie:
- url += "/" + appCookie
+ url += "/" + appCookie
response = self.send( url=url, ip = ip, port = port )
if response:
if 200 <= response[ 0 ] <= 299:
@@ -2126,4 +2128,3 @@
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
diff --git a/TestON/drivers/common/api/controllerdriver.py b/TestON/drivers/common/api/controllerdriver.py
index 956374c..863b643 100644
--- a/TestON/drivers/common/api/controllerdriver.py
+++ b/TestON/drivers/common/api/controllerdriver.py
@@ -32,4 +32,3 @@
def __init__( self ):
super( Controller, self ).__init__()
-
diff --git a/TestON/drivers/common/api/dockerapidriver.py b/TestON/drivers/common/api/dockerapidriver.py
index 3fac610..1393e18 100644
--- a/TestON/drivers/common/api/dockerapidriver.py
+++ b/TestON/drivers/common/api/dockerapidriver.py
@@ -55,7 +55,7 @@
self.home = "/var/tmp"
self.handle = super( DockerApiDriver, self ).connect()
- self.dockerClient = Client(base_url='unix://var/run/docker.sock')
+ self.dockerClient = Client( base_url='unix://var/run/docker.sock' )
return self.handle
except Exception as e:
main.log.exception( e )
@@ -72,7 +72,7 @@
if imageDict[ 'RepoTags' ] is not None:
if len( imageDict[ 'RepoTags' ] ) > 1:
duplicateTagDetected = 1
- imageListToSend.append( imageDict['RepoTags'][0].encode('UTF8').split(':')[1] )
+ imageListToSend.append( imageDict[ 'RepoTags' ][ 0 ].encode( 'UTF8' ).split( ':' )[ 1 ] )
return imageListToSend, duplicateTagDetected
except Exception as e:
main.log.exception( e )
@@ -83,18 +83,18 @@
"""
try:
main.log.info( self.name +
- ": Pulling Docker image " + onosRepo + ":"+ onosTag )
- for line in self.dockerClient.pull( repository = onosRepo, \
- tag = onosTag, stream = True ):
- print "#",
- main.log.info(json.dumps(json.loads(line), indent =4))
+ ": Pulling Docker image " + onosRepo + ":" + onosTag )
+ for line in self.dockerClient.pull( repository = onosRepo,
+ tag = onosTag, stream = True ):
+ print "#",
+ main.log.info( json.dumps( json.loads( line ), indent =4 ))
- #response = json.dumps( json.load( pullResult ), indent=4 )
+ # response = json.dumps( json.load( pullResult ), indent=4 )
if re.search( "for onosproject/onos:" + onosTag, line ):
main.log.info( "onos docker image pulled is: " + line )
return main.TRUE
else:
- main.log.error( "Failed to download image from: " + onosRepo +":"+ onosTag )
+ main.log.error( "Failed to download image from: " + onosRepo + ":" + onosTag )
main.log.error( "Error respone: " )
main.log.error( line )
return main.FALSE
@@ -109,17 +109,17 @@
try:
main.log.info( self.name +
": Creating Docker container for node: " + onosNode )
- response = self.dockerClient.create_container( image=onosImage, \
- tty=True, name=onosNode, detach=True )
- #print response
- #print response.get("Id")
- #print response.get("Warnings")
- if( str( response.get("Warnings") ) == 'None' ):
- main.log.info( "Created container for node: " + onosNode + "; container id is: " + response.get("Id") )
- return ( main.TRUE, response.get("Id") )
+ response = self.dockerClient.create_container( image=onosImage,
+ tty=True, name=onosNode, detach=True )
+ # print response
+ # print response.get("Id")
+ # print response.get("Warnings")
+ if( str( response.get( "Warnings" ) ) == 'None' ):
+ main.log.info( "Created container for node: " + onosNode + "; container id is: " + response.get( "Id" ) )
+ return( main.TRUE, response.get( "Id" ) )
else:
main.log.info( "Noticed warnings during create" )
- return ( main.FALSE, null)
+ return( main.FALSE, null )
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
@@ -157,11 +157,11 @@
main.log.info( "Noticed warnings during stop" )
return main.FALSE
except errors.NotFound:
- main.log.info( ctName + " not found! Continue on tests...")
+ main.log.info( ctName + " not found! Continue on tests..." )
return main.TRUE
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
- #main.cleanAndExit()
+ # main.cleanAndExit()
def dockerRestartCT( self, ctName ):
"""
@@ -181,27 +181,27 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def dockerCheckCTName( self, ctName):
+ def dockerCheckCTName( self, ctName ):
"""
Check Docker conatiner status
"""
try:
main.log.info( self.name +
": Checking Docker Status for CT with 'Names' " + ctName )
- namelist = [response["Names"] for response in self.dockerClient.containers(all=True) if not []]
- main.log.info("Name list is: " + str(namelist) )
- if( [ctName] in namelist):
+ namelist = [ response[ "Names" ] for response in self.dockerClient.containers( all=True ) if not [] ]
+ main.log.info( "Name list is: " + str( namelist ) )
+ if( [ ctName ] in namelist ):
main.log.info( "Container " + ctName + " exists" )
return main.TRUE
else:
main.log.info( "Container " + ctName + " does not exist" )
return main.FALSE
except errors.NotFound:
- main.log.warn( ctName + "not found! Continue with the tests...")
+ main.log.warn( ctName + "not found! Continue with the tests..." )
return main.FALSE
except Exception:
main.log.exception( self.name + ": Uncaught exception! Continue tests..." )
- #main.cleanAndExit()
+ # main.cleanAndExit()
def dockerRemoveCT( self, ctName ):
"""
@@ -215,15 +215,15 @@
main.log.info( "Removed container for node: " + ctName )
return main.TRUE
else:
- main.log.info( "Noticed warnings during Remove " + ctName)
+ main.log.info( "Noticed warnings during Remove " + ctName )
return main.FALSE
- main.log.exception(self.name + ": not found, continuing...")
+ main.log.exception( self.name + ": not found, continuing..." )
except errors.NotFound:
- main.log.warn( ctName + "not found! Continue with the tests...")
+ main.log.warn( ctName + "not found! Continue with the tests..." )
return main.TRUE
except Exception:
main.log.exception( self.name + ": Uncaught exception! Continuing..." )
- #main.cleanAndExit()
+ # main.cleanAndExit()
def dockerRemoveImage( self, imageRepoTag=None ):
"""
@@ -234,13 +234,13 @@
main.log.info( "No docker image found" )
return rmResult
else:
- imageList = [ image["Id"] for image in self.dockerClient.images()
- if image["RepoTags"] is None
- or imageRepoTag in image["RepoTags"] ]
+ imageList = [ image[ "Id" ] for image in self.dockerClient.images()
+ if image[ "RepoTags" ] is None
+ or imageRepoTag in image[ "RepoTags" ] ]
for id in imageList:
try:
main.log.info( self.name + ": Removing Docker image " + id )
- response = self.dockerClient.remove_image(id, force = True)
+ response = self.dockerClient.remove_image( id, force = True )
if response is None:
main.log.info( "Removed Docker image: " + id )
rmResult = rmResult and main.TRUE
@@ -248,12 +248,12 @@
main.log.info( "Noticed warnings during Remove " + id )
rmResult = rmResult and main.FALSE
except errors.NotFound:
- main.log.warn( image + "not found! Continue with the tests...")
+ main.log.warn( image + "not found! Continue with the tests..." )
rmResult = rmResult and main.TRUE
except Exception:
main.log.exception( self.name + ": Uncaught exception! Continuing..." )
rmResult = rmResult and main.FALSE
- #main.cleanAndExit()
+ # main.cleanAndExit()
return rmResult
def fetchLatestClusterFile( self, branch="master" ):
@@ -263,7 +263,7 @@
try:
command = "wget -N https://raw.githubusercontent.com/opennetworkinglab/\
onos/" + branch + "/tools/package/bin/onos-form-cluster"
- subprocess.call( command ) # output checks are missing for now
+ subprocess.call( command ) # output checks are missing for now
command = "chmod u+x " + "onos-form-cluster"
subprocess.call( command )
return main.TRUE
@@ -276,7 +276,7 @@
From ONOS cluster for IP addresses in onosIPs list
"""
try:
- onosIPs = " ".join(onosIPs)
+ onosIPs = " ".join( onosIPs )
command = "{}/onos-form-cluster -u {} -p {} {}".format( cmdPath,
user,
passwd,
@@ -285,7 +285,7 @@
if result == 0:
return main.TRUE
else:
- main.log.info("Something is not right in forming cluster>")
+ main.log.info( "Something is not right in forming cluster>" )
return main.FALSE
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
@@ -297,11 +297,10 @@
"""
try:
output = self.dockerClient.inspect_container( ctName )
- nodeIP = output['NetworkSettings']['IPAddress']
- main.log.info( " Docker IP " + str(nodeIP) )
- return str(nodeIP)
+ nodeIP = output[ 'NetworkSettings' ][ 'IPAddress' ]
+ main.log.info( " Docker IP " + str( nodeIP ) )
+ return str( nodeIP )
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
diff --git a/TestON/drivers/common/api/fvtapidriver.py b/TestON/drivers/common/api/fvtapidriver.py
index 4f20c89..2a1c0cb 100644
--- a/TestON/drivers/common/api/fvtapidriver.py
+++ b/TestON/drivers/common/api/fvtapidriver.py
@@ -188,4 +188,3 @@
# self.logfile_handler.close()
return main.TRUE
-
diff --git a/TestON/drivers/common/apidriver.py b/TestON/drivers/common/apidriver.py
index ec416ee..3e5615f 100644
--- a/TestON/drivers/common/apidriver.py
+++ b/TestON/drivers/common/apidriver.py
@@ -44,4 +44,3 @@
super( API, self ).connect()
return main.TRUE
-
diff --git a/TestON/drivers/common/cli/dpclidriver.py b/TestON/drivers/common/cli/dpclidriver.py
index 2386c45..a152273 100644
--- a/TestON/drivers/common/cli/dpclidriver.py
+++ b/TestON/drivers/common/cli/dpclidriver.py
@@ -38,9 +38,9 @@
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 )
+ ip_address=self.ip_address,
+ port=self.port,
+ pwd=self.pwd )
if self.handle:
return self.handle
@@ -148,7 +148,7 @@
self.handle.sendline( "sudo fping -S " + str( netsrc ) + "." +
str( netstrt ) + ".1.1 -f /tmp/ip_table" +
str( netdst ) + ".txt" )
- while 1:
+ while True:
i = self.handle.expect( [
"reachable",
"unreachable",
@@ -210,4 +210,3 @@
main.log.exception( "Connection failed to the host" )
response = main.FALSE
return response
-
diff --git a/TestON/drivers/common/cli/emulator/lincoemininetdriver.py b/TestON/drivers/common/cli/emulator/lincoemininetdriver.py
index bfa466f..df1abd7 100644
--- a/TestON/drivers/common/cli/emulator/lincoemininetdriver.py
+++ b/TestON/drivers/common/cli/emulator/lincoemininetdriver.py
@@ -32,6 +32,7 @@
class LincOEMininetDriver( MininetCliDriver ):
+
def runOpticalMnScript( self, onosDirectory = 'onos', ctrllerIP = None, topology = 'opticalTest' ):
import time
import types
@@ -49,14 +50,14 @@
$OC1 can be accepted
"""
try:
- if ctrllerIP == None:
+ if ctrllerIP is None:
main.log.error( "You need to specify the IP" )
return main.FALSE
else:
controller = ''
if isinstance( ctrllerIP, types.ListType ):
for i in xrange( len( ctrllerIP ) ):
- controller += ctrllerIP[i] + ' '
+ controller += ctrllerIP[ i ] + ' '
main.log.info( "Mininet topology is being loaded with " +
"controllers: " + controller )
elif isinstance( ctrllerIP, types.StringType ):
@@ -70,12 +71,12 @@
cmd = "sudo -E python {0} {1}".format( topoFile, controller )
main.log.info( self.name + ": cmd = " + cmd )
self.handle.sendline( cmd )
- lincStart = self.handle.expect( [ "mininet>", pexpect.TIMEOUT ],timeout=120 )
+ lincStart = self.handle.expect( [ "mininet>", pexpect.TIMEOUT ], timeout=120 )
if lincStart == 1:
self.handle.sendline( "\x03" )
self.handle.sendline( "sudo mn -c" )
self.handle.sendline( cmd )
- lincStart = self.handle.expect( [ "mininet>", pexpect.TIMEOUT ],timeout=120 )
+ lincStart = self.handle.expect( [ "mininet>", pexpect.TIMEOUT ], timeout=120 )
if lincStart == 1:
main.log.error( "OpticalTest.py failed to start." )
return main.FALSE
@@ -85,7 +86,7 @@
main.log.error( self.name + ": " + self.handle.before )
return main.FALSE
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
return main.FALSE
@@ -120,7 +121,7 @@
main.log.error( self.name + ": " + self.handle.before )
main.cleanAndExit()
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
main.log.info( self.name + ": Ping Response: " + response )
if re.search( ',\s0\%\spacket\sloss', response ):
diff --git a/TestON/drivers/common/cli/emulator/mininetclidriver.py b/TestON/drivers/common/cli/emulator/mininetclidriver.py
index d69fbeb..25cafe0 100644
--- a/TestON/drivers/common/cli/emulator/mininetclidriver.py
+++ b/TestON/drivers/common/cli/emulator/mininetclidriver.py
@@ -45,6 +45,7 @@
class MininetCliDriver( Emulator ):
+
"""
MininetCliDriver is the basic driver which will handle
the Mininet functions"""
@@ -184,7 +185,7 @@
main.log.info(
"Starting Mininet from topo file " +
topoFile )
- cmdString += "-E python " + topoFile + " "
+ cmdString += "-E python " + topoFile + " "
if args is None:
args = ''
# TODO: allow use of args from .topo file?
@@ -434,7 +435,6 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
def pingallHosts( self, hostList, wait=1 ):
"""
Ping all specified IPv4 hosts
@@ -462,7 +462,7 @@
pingList = hostList[ :listIndex ] + \
hostList[ ( listIndex + 1 ): ]
- pingResponse += str(str(host) + " -> ")
+ pingResponse += str( str( host ) + " -> " )
for temp in pingList:
# Current host pings all other hosts specified
@@ -471,14 +471,14 @@
self.handle.expect( "mininet>", timeout=wait + 1 )
response = self.handle.before
if re.search( ',\s0\%\spacket\sloss', response ):
- pingResponse += str(" h" + str( temp[1:] ))
+ pingResponse += str( " h" + str( temp[ 1: ] ) )
else:
pingResponse += " X"
# One of the host to host pair is unreachable
isReachable = main.FALSE
failedPings += 1
pingResponse += "\n"
- main.log.info( pingResponse + "Failed pings: " + str(failedPings) )
+ main.log.info( pingResponse + "Failed pings: " + str( failedPings ) )
return isReachable
except pexpect.TIMEOUT:
main.log.exception( self.name + ": TIMEOUT exception" )
@@ -513,23 +513,23 @@
pingList = hostList[ :listIndex ] + \
hostList[ ( listIndex + 1 ): ]
- pingResponse += str(str(host) + " -> ")
+ pingResponse += str( str( host ) + " -> " )
for temp in pingList:
# Current host pings all other hosts specified
- pingCmd = str( host ) + cmd + str( self.getIPAddress(temp,proto='IPv6') )
+ pingCmd = str( host ) + cmd + str( self.getIPAddress( temp, proto='IPv6' ) )
self.handle.sendline( pingCmd )
self.handle.expect( "mininet>", timeout=wait + 1 )
response = self.handle.before
if re.search( ',\s0\%\spacket\sloss', response ):
- pingResponse += str(" h" + str( temp[1:] ))
+ pingResponse += str( " h" + str( temp[ 1: ] ) )
else:
pingResponse += " X"
# One of the host to host pair is unreachable
isReachable = main.FALSE
failedPings += 1
pingResponse += "\n"
- main.log.info( pingResponse + "Failed pings: " + str(failedPings) )
+ main.log.info( pingResponse + "Failed pings: " + str( failedPings ) )
return isReachable
except pexpect.TIMEOUT:
@@ -549,7 +549,7 @@
Currently the only supported Params: SRC, TARGET, and WAIT
"""
args = utilities.parse_args( [ "SRC", "TARGET", 'WAIT' ], **pingParams )
- wait = args['WAIT']
+ wait = args[ 'WAIT' ]
wait = int( wait if wait else 1 )
command = args[ "SRC" ] + " ping " + \
args[ "TARGET" ] + " -c 1 -i 1 -W " + str( wait ) + " "
@@ -594,7 +594,7 @@
Example: main.Mininet1.ping6pair( src="h1", target="1000::2" )
"""
args = utilities.parse_args( [ "SRC", "TARGET", 'WAIT' ], **pingParams )
- wait = args['WAIT']
+ wait = args[ 'WAIT' ]
wait = int( wait if wait else 1 )
command = args[ "SRC" ] + " ping6 " + \
args[ "TARGET" ] + " -c 1 -i 1 -W " + str( wait ) + " "
@@ -838,8 +838,8 @@
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -877,7 +877,7 @@
self.handle.expect( "mininet>" )
# Determine ip and mac address of the host-oldSw interface
- cmd = "px ipaddr = " + str(IP)
+ cmd = "px ipaddr = " + str( IP )
print "cmd3= ", cmd
self.handle.sendline( cmd )
self.handle.expect( "mininet>" )
@@ -888,7 +888,7 @@
self.handle.expect( "mininet>" )
# Detach interface between oldSw-host
- cmd = "px " + oldSw + ".detach( sintf )"
+ cmd = "px " + oldSw + ".detach(sintf)"
print "cmd4= ", cmd
self.handle.sendline( cmd )
self.handle.expect( "mininet>" )
@@ -907,31 +907,31 @@
self.handle.expect( "mininet>" )
# Attach interface between newSw-host
- cmd = "px " + newSw + ".attach( sintf )"
+ cmd = "px " + newSw + ".attach(sintf)"
print "cmd6= ", cmd
self.handle.sendline( cmd )
self.handle.expect( "mininet>" )
# Set macaddress of the host-newSw interface
- cmd = "px " + host + ".setMAC( mac = macaddr, intf = hintf)"
+ cmd = "px " + host + ".setMAC(mac = macaddr, intf = hintf)"
print "cmd7 = ", cmd
self.handle.sendline( cmd )
self.handle.expect( "mininet>" )
# Set ipaddress of the host-newSw interface
- cmd = "px " + host + ".setIP( ip = ipaddr, intf = hintf)"
+ cmd = "px " + host + ".setIP(ip = ipaddr, intf = hintf)"
print "cmd8 = ", cmd
self.handle.sendline( cmd )
self.handle.expect( "mininet>" )
cmd = host + " ifconfig"
- print "cmd9 =",cmd
- response = self.execute( cmd = cmd, prompt="mininet>" ,timeout=10 )
+ print "cmd9 =", cmd
+ response = self.execute( cmd = cmd, prompt="mininet>", timeout=10 )
print response
pattern = "h\d-eth([\w])"
ipAddressSearch = re.search( pattern, response )
- print ipAddressSearch.group(1)
- intf= host + "-eth" + str(ipAddressSearch.group(1))
+ print ipAddressSearch.group( 1 )
+ intf = host + "-eth" + str( ipAddressSearch.group( 1 ) )
cmd = host + " ip -6 addr add %s dev %s" % ( IP, intf )
print "cmd10 = ", cmd
self.handle.sendline( cmd )
@@ -952,8 +952,8 @@
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -982,8 +982,8 @@
newIP )
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1011,8 +1011,8 @@
newGW )
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1040,8 +1040,8 @@
macaddr )
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1064,8 +1064,8 @@
main.log.info( host + " arp -an = " + response )
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1138,7 +1138,7 @@
else:
main.log.error( "Connection failed to the host" )
- def getIPAddress( self, host , proto='IPV4'):
+ def getIPAddress( self, host , proto='IPV4' ):
"""
Verifies the host's ip configured or not."""
if self.handle:
@@ -1214,8 +1214,8 @@
response = self.handle.before
return response
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1307,7 +1307,7 @@
main.cleanAndExit()
return response
- def iperftcpAll(self, hosts, timeout=6):
+ def iperftcpAll( self, hosts, timeout=6 ):
'''
Runs the iperftcp function with a given set of hosts and specified timeout.
@@ -1319,13 +1319,13 @@
for host1 in hosts:
for host2 in hosts:
if host1 != host2:
- if self.iperftcp(host1, host2, timeout) == main.FALSE:
- main.log.error(self.name + ": iperftcp test failed for " + host1 + " and " + host2)
+ if self.iperftcp( host1, host2, timeout ) == main.FALSE:
+ main.log.error( self.name + ": iperftcp test failed for " + host1 + " and " + host2 )
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def iperftcp(self, host1="h1", host2="h2", timeout=6):
+ def iperftcp( self, host1="h1", host2="h2", timeout=6 ):
'''
Creates an iperf TCP test between two hosts. Returns main.TRUE if test results
are valid.
@@ -1344,26 +1344,26 @@
# checks if there are results in the mininet response
if "Results:" in response:
- main.log.report(self.name + ": iperf test completed")
+ main.log.report( self.name + ": iperf test completed" )
# parse the mn results
- response = response.split("\r\n")
- response = response[len(response)-2]
- response = response.split(": ")
- response = response[len(response)-1]
- response = response.replace("[", "")
- response = response.replace("]", "")
- response = response.replace("\'", "")
+ response = response.split( "\r\n" )
+ response = response[ len( response )-2 ]
+ response = response.split( ": " )
+ response = response[ len( response )-1 ]
+ response = response.replace( "[", "" )
+ response = response.replace( "]", "" )
+ response = response.replace( "\'", "" )
# this is the bandwith two and from the two hosts
- bandwidth = response.split(", ")
+ bandwidth = response.split( ", " )
# there should be two elements in the bandwidth list
# ['host1 to host2', 'host2 to host1"]
- if len(bandwidth) == 2:
- main.log.report(self.name + ": iperf test successful")
+ if len( bandwidth ) == 2:
+ main.log.report( self.name + ": iperf test successful" )
return main.TRUE
else:
- main.log.error(self.name + ": invalid iperf results")
+ main.log.error( self.name + ": invalid iperf results" )
return main.FALSE
else:
main.log.error( self.name + ": iperf test failed" )
@@ -1385,22 +1385,22 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def iperftcpipv6(self, host1="h1", host2="h2", timeout=50):
+ def iperftcpipv6( self, host1="h1", host2="h2", timeout=50 ):
main.log.info( self.name + ": Simple iperf TCP test between two hosts" )
try:
IP1 = self.getIPAddress( host1, proto='IPV6' )
- cmd1 = host1 +' iperf -V -sD -B '+ str(IP1)
+ cmd1 = host1 + ' iperf -V -sD -B ' + str( IP1 )
self.handle.sendline( cmd1 )
- outcome1 = self.handle.expect( "mininet>")
- cmd2 = host2 +' iperf -V -c '+ str(IP1) +' -t 5'
+ outcome1 = self.handle.expect( "mininet>" )
+ cmd2 = host2 + ' iperf -V -c ' + str( IP1 ) + ' -t 5'
self.handle.sendline( cmd2 )
- outcome2 = self.handle.expect( "mininet>")
+ outcome2 = self.handle.expect( "mininet>" )
response1 = self.handle.before
response2 = self.handle.after
- print response1,response2
- pattern = "connected with "+ str(IP1)
+ print response1, response2
+ pattern = "connected with " + str( IP1 )
if pattern in response1:
- main.log.report(self.name + ": iperf test completed")
+ main.log.report( self.name + ": iperf test completed" )
return main.TRUE
else:
main.log.error( self.name + ": iperf test failed" )
@@ -1420,7 +1420,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def iperfudpAll(self, hosts, bandwidth="10M"):
+ def iperfudpAll( self, hosts, bandwidth="10M" ):
'''
Runs the iperfudp function with a given set of hosts and specified
bandwidth
@@ -1432,17 +1432,16 @@
for host1 in hosts:
for host2 in hosts:
if host1 != host2:
- if self.iperfudp(host1, host2, bandwidth) == main.FALSE:
- main.log.error(self.name + ": iperfudp test failed for " + host1 + " and " + host2)
+ if self.iperfudp( host1, host2, bandwidth ) == main.FALSE:
+ main.log.error( self.name + ": iperfudp test failed for " + host1 + " and " + host2 )
except TypeError:
- main.log.exception(self.name + ": Object not as expected")
+ main.log.exception( self.name + ": Object not as expected" )
return main.FALSE
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def iperfudp( self, bandwidth="10M", host1="h1", host2="h2"):
-
+ def iperfudp( self, bandwidth="10M", host1="h1", host2="h2" ):
'''
Creates an iperf UDP test with a specific bandwidth.
Returns true if results are valid.
@@ -1450,47 +1449,47 @@
@param:
bandwidth: the targeted bandwidth, in megabits ('M'), to run the test
'''
- main.log.info(self.name + ": Simple iperf UDP test between two hosts")
+ main.log.info( self.name + ": Simple iperf UDP test between two hosts" )
try:
# setup the mininet command
cmd = 'iperfudp ' + bandwidth + " " + host1 + " " + host2
- self.handle.sendline(cmd)
- self.handle.expect("mininet>")
+ self.handle.sendline( cmd )
+ self.handle.expect( "mininet>" )
response = self.handle.before
# check if there are in results in the mininet response
if "Results:" in response:
- main.log.report(self.name + ": iperfudp test completed")
+ main.log.report( self.name + ": iperfudp test completed" )
# parse the results
- response = response.split("\r\n")
- response = response[len(response)-2]
- response = response.split(": ")
- response = response[len(response)-1]
- response = response.replace("[", "")
- response = response.replace("]", "")
- response = response.replace("\'", "")
+ response = response.split( "\r\n" )
+ response = response[ len( response )-2 ]
+ response = response.split( ": " )
+ response = response[ len( response )-1 ]
+ response = response.replace( "[", "" )
+ response = response.replace( "]", "" )
+ response = response.replace( "\'", "" )
- mnBandwidth = response.split(", ")
+ mnBandwidth = response.split( ", " )
# check to see if there are at least three entries
# ['bandwidth', 'host1 to host2', 'host2 to host1']
- if len(mnBandwidth) == 3:
+ if len( mnBandwidth ) == 3:
# if one entry is blank then something is wrong
for item in mnBandwidth:
if item == "":
- main.log.error(self.name + ": Could not parse iperf output")
- main.log.error(self.name + ": invalid iperfudp results")
+ main.log.error( self.name + ": Could not parse iperf output" )
+ main.log.error( self.name + ": invalid iperfudp results" )
return main.FALSE
# otherwise results are vaild
- main.log.report(self.name + ": iperfudp test successful")
+ main.log.report( self.name + ": iperfudp test successful" )
return main.TRUE
else:
- main.log.error(self.name + ": invalid iperfudp results")
+ main.log.error( self.name + ": invalid iperfudp results" )
return main.FALSE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1579,8 +1578,8 @@
self.handle.sendline( command )
self.handle.expect( "mininet>" )
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1622,7 +1621,7 @@
args = utilities.parse_args( [ "SW", "INTF" ], **yankargs )
sw = args[ "SW" ] if args[ "SW" ] is not None else ""
intf = args[ "INTF" ] if args[ "INTF" ] is not None else ""
- command = "py " + str( sw ) + '.detach("' + str(intf) + '")'
+ command = "py " + str( sw ) + '.detach("' + str( intf ) + '")'
try:
response = self.execute(
cmd=command,
@@ -1644,7 +1643,7 @@
args = utilities.parse_args( [ "SW", "INTF" ], **plugargs )
sw = args[ "SW" ] if args[ "SW" ] is not None else ""
intf = args[ "INTF" ] if args[ "INTF" ] is not None else ""
- command = "py " + str( sw ) + '.attach("' + str(intf) + '")'
+ command = "py " + str( sw ) + '.attach("' + str( intf ) + '")'
try:
response = self.execute(
cmd=command,
@@ -1966,11 +1965,11 @@
candidateSwitches.append( switchName )
else:
graphDict = self.getGraphDict( timeout=timeout, useId=False )
- if graphDict == None:
+ if graphDict is None:
return None
self.graph.update( graphDict )
candidateSwitches = self.graph.getNonCutVertices()
- if candidateSwitches == None:
+ if candidateSwitches is None:
return None
elif len( candidateSwitches ) == 0:
main.log.info( self.name + ": No candidate switch for deletion" )
@@ -2000,7 +1999,7 @@
"""
try:
switch = self.getSwitchRandom( timeout, nonCut )
- if switch == None:
+ if switch is None:
return None
else:
deletionResult = self.delSwitch( switch )
@@ -2105,11 +2104,11 @@
candidateLinks.append( [ link[ 'node1' ], link[ 'node2' ] ] )
else:
graphDict = self.getGraphDict( timeout=timeout, useId=False )
- if graphDict == None:
+ if graphDict is None:
return None
self.graph.update( graphDict )
candidateLinks = self.graph.getNonCutEdges()
- if candidateLinks == None:
+ if candidateLinks is None:
return None
elif len( candidateLinks ) == 0:
main.log.info( self.name + ": No candidate link for deletion" )
@@ -2139,7 +2138,7 @@
"""
try:
link = self.getLinkRandom( timeout, nonCut )
- if link == None:
+ if link is None:
return None
else:
deletionResult = self.delLink( link[ 0 ], link[ 1 ] )
@@ -2302,8 +2301,8 @@
fileName +
"\" | grep -v grep | awk '{print $2}'\`" )
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -2331,7 +2330,7 @@
ethDevice = '-I ' + ethDevice + ' '
cmd = srcHost + " arping -c1 "
if noResult:
- cmd += "-w10 " # If we don't want the actural arping result, set -w10, arping will exit after 10 ms.
+ cmd += "-w10 " # If we don't want the actural arping result, set -w10, arping will exit after 10 ms.
cmd += ethDevice + dstHost
try:
if output:
@@ -2416,11 +2415,11 @@
assert flowTable1, "flowTable1 is empty or None"
assert flowTable2, "flowTable2 is empty or None"
returnValue = main.TRUE
- if len(flowTable1) != len(flowTable2):
+ if len( flowTable1 ) != len( flowTable2 ):
main.log.warn( "Flow table lengths do not match" )
returnValue = main.FALSE
- dFields = ["n_bytes", "cookie", "n_packets", "duration"]
- for flow1, flow2 in zip(flowTable1, flowTable2):
+ dFields = [ "n_bytes", "cookie", "n_packets", "duration" ]
+ for flow1, flow2 in zip( flowTable1, flowTable2 ):
for field in dFields:
try:
flow1.pop( field )
@@ -2430,10 +2429,10 @@
flow2.pop( field )
except KeyError:
pass
- for i in range( len(flowTable1) ):
- if flowTable1[i] not in flowTable2:
+ for i in range( len( flowTable1 ) ):
+ if flowTable1[ i ] not in flowTable2:
main.log.warn( "Flow tables do not match:" )
- main.log.warn( "Old flow:\n{}\n not in new flow table".format( flowTable1[i] ) )
+ main.log.warn( "Old flow:\n{}\n not in new flow table".format( flowTable1[ i ] ) )
returnValue = main.FALSE
break
return returnValue
@@ -2461,63 +2460,64 @@
for flow in flowTable:
jsonFlow = {}
# split up the fields of the flow
- parsedFlow = flow.split(", ")
+ parsedFlow = flow.split( ", " )
# get rid of any spaces in front of the field
- for i in range( len(parsedFlow) ):
- item = parsedFlow[i]
- if item[0] == " ":
- parsedFlow[i] = item[1:]
+ for i in range( len( parsedFlow ) ):
+ item = parsedFlow[ i ]
+ if item[ 0 ] == " ":
+ parsedFlow[ i ] = item[ 1: ]
# grab the selector and treatment from the parsed flow
# the last element is the selector and the treatment
- temp = parsedFlow.pop(-1)
+ temp = parsedFlow.pop( -1 )
# split up the selector and the treatment
- temp = temp.split(" ")
+ temp = temp.split( " " )
index = 0
# parse the flags
# NOTE: This only parses one flag
flag = {}
if version == "1.3":
- flag = {"flag":[temp[index]]}
+ flag = { "flag": [ temp[ index ] ] }
index += 1
# the first element is the selector and split it up
- sel = temp[index]
+ sel = temp[ index ]
index += 1
- sel = sel.split(",")
+ sel = sel.split( "," )
# the priority is stuck in the selecter so put it back
# in the flow
- parsedFlow.append(sel.pop(0))
+ parsedFlow.append( sel.pop( 0 ) )
# parse selector
criteria = []
for item in sel:
# this is the type of the packet e.g. "arp"
if "=" not in item:
- criteria.append( {"type":item} )
+ criteria.append( { "type": item } )
else:
- field = item.split("=")
- criteria.append( {field[0]:field[1]} )
- selector = {"selector": {"criteria":sorted(criteria)} }
- treat = temp[index]
+ field = item.split( "=" )
+ criteria.append( { field[ 0 ]: field[ 1 ] } )
+ selector = { "selector": { "criteria": sorted( criteria ) } }
+ treat = temp[ index ]
# get rid of the action part e.g. "action=output:2"
# we will add it back later
- treat = treat.split("=")
- treat.pop(0)
+ treat = treat.split( "=" )
+ treat.pop( 0 )
# parse treatment
action = []
for item in treat:
- field = item.split(":")
- action.append( {field[0]:field[1]} )
+ field = item.split( ":" )
+ action.append( { field[ 0 ]: field[ 1 ] } )
# create the treatment field and add the actions
- treatment = {"treatment": {"action":sorted(action)} }
+ treatment = { "treatment": { "action": sorted( action ) } }
# parse the rest of the flow
for item in parsedFlow:
- field = item.split("=")
- jsonFlow.update( {field[0]:field[1]} )
+ field = item.split( "=" )
+ jsonFlow.update( { field[ 0 ]: field[ 1 ] } )
# add the treatment and the selector to the json flow
jsonFlow.update( selector )
jsonFlow.update( treatment )
jsonFlow.update( flag )
- if debug: main.log.debug( "\033[94mJson flow:\033[0m\n{}\n".format(jsonFlow) )
+ if debug:
+ main.log.debug( "\033[94mJson flow:\033[0m\n{}\n".format( jsonFlow ) )
# add the json flow to the json flow table
jsonFlowTable.append( jsonFlow )
@@ -2535,7 +2535,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def getFlowTable( self, sw, version="", debug=False):
+ def getFlowTable( self, sw, version="", debug=False ):
'''
Discription: Returns the flow table(s) on a switch or switches in a list.
Each element is a flow.
@@ -2549,9 +2549,10 @@
'''
try:
switches = []
- if type(sw) is list:
- switches.extend(sw)
- else: switches.append(sw)
+ if isinstance( sw, list ):
+ switches.extend( sw )
+ else:
+ switches.append( sw )
flows = []
for s in switches:
@@ -2571,10 +2572,11 @@
# the first element is the command that was sent
# the second is the table header
# the last element is empty
- response = response[2:-1]
+ response = response[ 2:-1 ]
flows.extend( response )
- if debug: print "Flows:\n{}\n\n".format(flows)
+ if debug:
+ print "Flows:\n{}\n\n".format( flows )
return self.parseFlowTable( flows, version, debug )
@@ -2602,13 +2604,14 @@
try:
main.log.info( "Getting flows from Mininet" )
flows = self.getFlowTable( sw, version, debug )
- if flows == None:
+ if flows is None:
return main.ERROR
- if debug: print "flow ids:\n{}\n\n".format(flowId)
+ if debug:
+ print "flow ids:\n{}\n\n".format( flowId )
# Check flowId is a list or a string
- if type( flowId ) is str:
+ if isinstance( flowId, str ):
result = False
for f in flows:
if flowId in f.get( 'cookie' ):
@@ -2622,7 +2625,8 @@
# Save the IDs that are not in Mininet
absentIds = [ x for x in flowId if x not in mnFlowIds ]
- if debug: print "mn flow ids:\n{}\n\n".format(mnFlowIds)
+ if debug:
+ print "mn flow ids:\n{}\n\n".format( mnFlowIds )
# Print out the IDs that are not in Mininet
if absentIds:
@@ -2639,7 +2643,6 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
def startTcpdump( self, filename, intf="eth0", port="port 6653" ):
"""
Runs tpdump on an interface and saves the file
@@ -2704,8 +2707,8 @@
self.handle.sendline( "" )
self.handle.expect( "mininet>" )
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -2948,7 +2951,7 @@
"""
try:
self.update()
- response = self.links(timeout=timeout).split( '\n' )
+ response = self.links( timeout=timeout ).split( '\n' )
# Examples:
# s1-eth3<->s2-eth1 (OK OK)
@@ -3271,11 +3274,11 @@
main.log.info( output )
return hostResults
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.cleanAndExit()
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
def getHostsOld( self ):
@@ -3304,8 +3307,8 @@
return hostList
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -3357,8 +3360,8 @@
return switchList
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -3414,7 +3417,7 @@
# Get port index from OVS
# The index extracted from port name may be inconsistent with ONOS
portIndex = -1
- if not nodeName1 in portDict.keys():
+ if nodeName1 not in portDict.keys():
portList = self.getOVSPorts( nodeName1 )
if len( portList ) == 0:
main.log.warn( self.name + ": No port found on switch " + nodeName1 )
@@ -3433,21 +3436,21 @@
else:
node1 = nodeName1
node2 = nodeName2
- if not node1 in graphDict.keys():
+ if node1 not in graphDict.keys():
if useId:
- graphDict[ node1 ] = { 'edges':{},
- 'dpid':switches[ nodeName1 ][ 'dpid' ],
- 'name':nodeName1,
- 'ports':switches[ nodeName1 ][ 'ports' ],
- 'swClass':switches[ nodeName1 ][ 'swClass' ],
- 'pid':switches[ nodeName1 ][ 'pid' ],
- 'options':switches[ nodeName1 ][ 'options' ] }
+ graphDict[ node1 ] = { 'edges': {},
+ 'dpid': switches[ nodeName1 ][ 'dpid' ],
+ 'name': nodeName1,
+ 'ports': switches[ nodeName1 ][ 'ports' ],
+ 'swClass': switches[ nodeName1 ][ 'swClass' ],
+ 'pid': switches[ nodeName1 ][ 'pid' ],
+ 'options': switches[ nodeName1 ][ 'options' ] }
else:
- graphDict[ node1 ] = { 'edges':{} }
+ graphDict[ node1 ] = { 'edges': {} }
else:
# Assert node2 is not connected to any current links of node1
assert node2 not in graphDict[ node1 ][ 'edges' ].keys()
- graphDict[ node1 ][ 'edges' ][ node2 ] = { 'port':portIndex }
+ graphDict[ node1 ][ 'edges' ][ node2 ] = { 'port': portIndex }
# Swap two nodes/ports
nodeName1, nodeName2 = nodeName2, nodeName1
port1, port2 = port2, port1
@@ -3484,8 +3487,8 @@
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -3545,8 +3548,8 @@
return main.TRUE
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.cleanAndExit()
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -3572,8 +3575,8 @@
getattr( main, name )
except AttributeError:
# namespace is clear, creating component
- main.componentDictionary[name] = main.componentDictionary[self.name].copy()
- main.componentDictionary[name]['connect_order'] = str( int( main.componentDictionary[name]['connect_order'] ) + 1 )
+ main.componentDictionary[ name ] = main.componentDictionary[ self.name ].copy()
+ main.componentDictionary[ name ][ 'connect_order' ] = str( int( main.componentDictionary[ name ][ 'connect_order' ] ) + 1 )
main.componentInit( name )
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -3606,7 +3609,7 @@
# Delete component
delattr( main, name )
# Delete component from ComponentDictionary
- del( main.componentDictionary[name] )
+ del( main.componentDictionary[ name ] )
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
main.log.error( self.name + ": " + self.handle.before )
@@ -3656,25 +3659,24 @@
try:
cmd = devicename + " ifconfig " + intf + " " + status
self.handle.sendline( cmd )
- self.handle.expect("mininet>")
+ self.handle.expect( "mininet>" )
return main.TRUE
except pexpect.TIMEOUT:
- main.log.exception(self.name + ": Command timed out")
+ main.log.exception( self.name + ": Command timed out" )
return main.FALSE
except pexpect.EOF:
- main.log.exception(self.name + ": connection closed.")
+ main.log.exception( self.name + ": connection closed." )
main.cleanAndExit()
except TypeError:
- main.log.exception(self.name + ": TypeError")
+ main.log.exception( self.name + ": TypeError" )
main.cleanAndExit()
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
else:
- main.log.warn("Interface status should be up or down!")
+ main.log.warn( "Interface status should be up or down!" )
return main.FALSE
-
if __name__ != "__main__":
sys.modules[ __name__ ] = MininetCliDriver()
diff --git a/TestON/drivers/common/cli/emulator/remotemininetdriver.py b/TestON/drivers/common/cli/emulator/remotemininetdriver.py
index 71de94c..41284cb 100644
--- a/TestON/drivers/common/cli/emulator/remotemininetdriver.py
+++ b/TestON/drivers/common/cli/emulator/remotemininetdriver.py
@@ -56,7 +56,7 @@
self.name = self.options[ 'name' ]
try:
- if os.getenv( str( self.ip_address ) ) != None:
+ if os.getenv( str( self.ip_address ) ) is not None:
self.ip_address = os.getenv( str( self.ip_address ) )
else:
main.log.info( self.name +
@@ -152,7 +152,7 @@
self.handle.expect( self.prompt )
return main.TRUE
except TypeError:
- main.log.exception(self.name + ": Object not as expected")
+ main.log.exception( self.name + ": Object not as expected" )
return main.FALSE
except pexpect.TIMEOUT:
main.log.exception( self.name + ": TIMEOUT exception found in pingLong" )
@@ -166,7 +166,6 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
def pingstatus( self, **pingParams ):
"""
Tails the respective ping output file and check that
@@ -203,7 +202,7 @@
main.log.error( self.name + ": " + self.handle.before )
main.cleanAndExit()
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
def pingKill( self, testONUser, testONIP ):
@@ -262,11 +261,11 @@
main.log.error( self.name + ": " + self.handle.before )
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.cleanAndExit()
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
def pingHostOptical( self, **pingParams ):
@@ -336,11 +335,11 @@
main.lastResult = main.FALSE
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.cleanAndExit()
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
def checknum( self, num ):
@@ -407,7 +406,7 @@
self.handle.sendline( "" )
self.handle.sendline( "" )
i = self.handle.expect( [ 'No\ssuch\device', 'listening\son',
- pexpect.TIMEOUT, self.prompt ], timeout=10 )
+ pexpect.TIMEOUT, self.prompt ], timeout=10 )
main.log.info( self.handle.before + self.handle.after )
if i == 0:
main.log.error( self.name + ": tcpdump - No such device exists.\
@@ -468,15 +467,15 @@
self.handle.sendline( "" )
self.handle.expect( self.prompt )
self.handle.sendline( "cd ~/" + name + "/tools/test/topos" )
- self.handle.expect( "topos"+ self.prompt )
- if ctrllerIP == None:
+ self.handle.expect( "topos" + self.prompt )
+ if ctrllerIP is None:
main.log.info( "You need to specify the IP" )
return main.FALSE
else:
controller = ''
if isinstance( ctrllerIP, types.ListType ):
for i in xrange( len( ctrllerIP ) ):
- controller += ctrllerIP[i] + ' '
+ controller += ctrllerIP[ i ] + ' '
main.log.info( "Mininet topology is being loaded with " +
"controllers: " + controller )
elif isinstance( ctrllerIP, types.StringType ):
@@ -489,10 +488,10 @@
cmd = "sudo -E python opticalTest.py " + controller
main.log.info( self.name + ": cmd = " + cmd )
self.handle.sendline( cmd )
- time.sleep(30)
+ time.sleep( 30 )
self.handle.sendline( "" )
self.handle.sendline( "" )
- self.handle.expect("mininet>")
+ self.handle.expect( "mininet>" )
return main.TRUE
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -536,7 +535,7 @@
elif i == 1:
self.handle.sendline( "exit" )
self.handle.expect( "exit" )
- self.handle.expect(self.prompt)
+ self.handle.expect( self.prompt )
self.handle.sendline( "exit" )
self.handle.expect( "exit" )
self.handle.expect( "closed" )
@@ -548,11 +547,11 @@
main.log.error( self.name + ": " + self.handle.before )
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.cleanAndExit()
except Exception:
- main.log.exception(self.name + ": Uncaught exception!")
+ main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
def setIpTablesOUTPUT( self, dstIp, dstPort, action='add',
diff --git a/TestON/drivers/common/cli/emulator/scapyclidriver.py b/TestON/drivers/common/cli/emulator/scapyclidriver.py
index 74905f8..6ef63c4 100644
--- a/TestON/drivers/common/cli/emulator/scapyclidriver.py
+++ b/TestON/drivers/common/cli/emulator/scapyclidriver.py
@@ -199,8 +199,8 @@
getattr( main, name )
except AttributeError:
# namespace is clear, creating component
- main.componentDictionary[name] = main.componentDictionary[self.name].copy()
- main.componentDictionary[name]['connect_order'] = str( int( main.componentDictionary[name]['connect_order'] ) + 1 )
+ main.componentDictionary[ name ] = main.componentDictionary[ self.name ].copy()
+ main.componentDictionary[ name ][ 'connect_order' ] = str( int( main.componentDictionary[ name ][ 'connect_order' ] ) + 1 )
main.componentInit( name )
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
@@ -228,7 +228,7 @@
# Delete component
delattr( main, name )
# Delete component from ComponentDictionary
- del( main.componentDictionary[name] )
+ del( main.componentDictionary[ name ] )
return main.TRUE
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
@@ -267,12 +267,12 @@
mplsPath - The path where the MPLS class is located
NOTE: This can be a relative path from the user's home dir
"""
- mplsLines = ['import imp',
- 'imp.load_source( "mplsClass", "{}mplsClass.py" )'.format(mplsPath),
- 'from mplsClass import MPLS',
- 'bind_layers(Ether, MPLS, type = 0x8847)',
- 'bind_layers(MPLS, MPLS, bottom_of_label_stack = 0)',
- 'bind_layers(MPLS, IP)']
+ mplsLines = [ 'import imp',
+ 'imp.load_source( "mplsClass", "{}mplsClass.py" )'.format( mplsPath ),
+ 'from mplsClass import MPLS',
+ 'bind_layers(Ether, MPLS, type = 0x8847)',
+ 'bind_layers(MPLS, MPLS, bottom_of_label_stack = 0)',
+ 'bind_layers(MPLS, IP)' ]
try:
self.handle.sendline( "scapy" )
@@ -649,7 +649,7 @@
self.handle.sendline( "packet = ether/ipv6/sctp" )
else:
main.log.error( "Unrecognized option for ipVersion, given " +
- repr( ipVersion ) )
+ repr( ipVersion ) )
return main.FALSE
self.handle.expect( self.scapyPrompt )
if "Traceback" in self.handle.before:
@@ -777,7 +777,7 @@
self.handle.sendline( "packet = ether/ipv6/icmp6" )
else:
main.log.error( "Unrecognized option for ipVersion, given " +
- repr( ipVersion ) )
+ repr( ipVersion ) )
return main.FALSE
self.handle.expect( self.scapyPrompt )
if "Traceback" in self.handle.before:
@@ -991,7 +991,7 @@
match = re.search( pattern, self.handle.before )
if match:
# NOTE: The command will return 0.0.0.0 if the iface doesn't exist
- if IPv6 != True:
+ if IPv6 is not True:
if match.group() == '0.0.0.0':
main.log.warn( 'iface {0} has no IPv4 address'.format( ifaceName ) )
return match.group()
@@ -1006,14 +1006,14 @@
if ifaceName == "lo":
continue
ip = getIPofInterface( ifaceName )
- if ip != None:
- newip =ip
+ if ip is not None:
+ newip = ip
tmp = newip.split( "\\x" )
ip = ""
counter = 0
for i in tmp:
if i != "":
- counter = counter + 1;
+ counter = counter + 1
if counter % 2 == 0 and counter < 16:
ip = ip + i + ":"
else:
@@ -1049,7 +1049,7 @@
self.handle.sendline( 'get_if_list()' )
self.handle.expect( self.scapyPrompt )
ifList = self.handle.before.split( '\r\n' )
- ifList = ifList[ 1 ].replace( "'","" )[ 1:-1 ].split( ', ' )
+ ifList = ifList[ 1 ].replace( "'", "" )[ 1:-1 ].split( ', ' )
return ifList
except pexpect.TIMEOUT:
diff --git a/TestON/drivers/common/cli/onosclidriver.py b/TestON/drivers/common/cli/onosclidriver.py
index f6f57bb..218b1e8 100755
--- a/TestON/drivers/common/cli/onosclidriver.py
+++ b/TestON/drivers/common/cli/onosclidriver.py
@@ -61,10 +61,11 @@
self.graph = Graph()
super( OnosCliDriver, self ).__init__()
- def checkOptions(self, var, defaultVar):
+ def checkOptions( self, var, defaultVar ):
if var is None or var == "":
return defaultVar
return var
+
def connect( self, **connectargs ):
"""
Creates ssh handle for ONOS cli.
@@ -81,9 +82,9 @@
elif key == "karaf_password":
self.karafPass = self.options[ key ]
- self.home = self.checkOptions(self.home, "~/onos")
- self.karafUser = self.checkOptions(self.karafUser, self.user_name)
- self.karafPass = self.checkOptions(self.karafPass, self.pwd )
+ self.home = self.checkOptions( self.home, "~/onos" )
+ self.karafUser = self.checkOptions( self.karafUser, self.user_name )
+ self.karafPass = self.checkOptions( self.karafPass, self.pwd )
for key in self.options:
if key == 'onosIp':
@@ -227,12 +228,12 @@
# Expect the cellname in the ONOSCELL variable.
# Note that this variable name is subject to change
# and that this driver will have to change accordingly
- self.handle.expect(str(cellname))
+ self.handle.expect( str( cellname ) )
handleBefore = self.handle.before
handleAfter = self.handle.after
# Get the rest of the handle
- self.handle.sendline("")
- self.handle.expect(self.prompt)
+ self.handle.sendline( "" )
+ self.handle.expect( self.prompt )
handleMore = self.handle.before
main.log.info( "Cell call returned: " + handleBefore +
@@ -272,7 +273,7 @@
# Check if we are already in the cli
self.handle.sendline( "" )
x = self.handle.expect( [
- self.prompt, "onos>" ], commandlineTimeout)
+ self.prompt, "onos>" ], commandlineTimeout )
if x == 1:
main.log.info( "ONOS cli is already running" )
return main.TRUE
@@ -355,7 +356,7 @@
try:
self.handle.sendline( "" )
x = self.handle.expect( [
- self.prompt, "onos>" ], commandlineTimeout)
+ self.prompt, "onos>" ], commandlineTimeout )
if x == 1:
main.log.info( "ONOS cli is already running" )
@@ -478,7 +479,7 @@
self.handle.sendline( "" )
i = self.handle.expect( [ "onos>", self.prompt, pexpect.TIMEOUT ] )
if i == 1:
- main.log.error( self.name + ": onos cli session closed. ")
+ main.log.error( self.name + ": onos cli session closed. " )
if self.onosIp:
main.log.warn( "Trying to reconnect " + self.onosIp )
reconnectResult = self.startOnosCli( self.onosIp )
@@ -504,9 +505,9 @@
self.log( logStr, noExit=noExit )
self.handle.sendline( cmdStr )
if dollarSign:
- i = self.handle.expect( ["onos>"], timeout )
+ i = self.handle.expect( [ "onos>" ], timeout )
else:
- i = self.handle.expect( ["onos>", self.prompt], timeout )
+ i = self.handle.expect( [ "onos>", self.prompt ], timeout )
response = self.handle.before
# TODO: do something with i
main.log.info( "Command '" + str( cmdStr ) + "' sent to "
@@ -541,7 +542,7 @@
main.log.debug( self.name + ": split output" )
for r in output:
main.log.debug( self.name + ": " + repr( r ) )
- output = output[1].strip()
+ output = output[ 1 ].strip()
if showResponse:
main.log.info( "Response from ONOS: {}".format( output ) )
return output
@@ -647,7 +648,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def nodes( self, jsonFormat=True):
+ def nodes( self, jsonFormat=True ):
"""
List the nodes currently visible
Issues command: 'nodes'
@@ -852,7 +853,7 @@
main.log.info( "\n" + self.checkMasters( False ) )
return main.FALSE
main.log.info( "Mastership balanced between " +
- str( len(masters) ) + " masters" )
+ str( len( masters ) ) + " masters" )
return main.TRUE
except ( TypeError, ValueError ):
main.log.exception( "{}: Object not as expected: {!r}".format( self.name, mastersOutput ) )
@@ -1186,9 +1187,9 @@
else:
main.log.info( "Host intent installed between " +
str( hostIdOne ) + " and " + str( hostIdTwo ) )
- match = re.search('id=0x([\da-f]+),', handle)
+ match = re.search( 'id=0x([\da-f]+),', handle )
if match:
- return match.group()[3:-1]
+ return match.group()[ 3:-1 ]
else:
main.log.error( "Error, intent ID not found" )
main.log.debug( "Response from ONOS was: " +
@@ -1234,9 +1235,9 @@
main.log.info( "Optical intent installed between " +
str( ingressDevice ) + " and " +
str( egressDevice ) )
- match = re.search('id=0x([\da-f]+),', handle)
+ match = re.search( 'id=0x([\da-f]+),', handle )
if match:
- return match.group()[3:-1]
+ return match.group()[ 3:-1 ]
else:
main.log.error( "Error, intent ID not found" )
return None
@@ -1374,9 +1375,9 @@
main.log.info( "Point-to-point intent installed between " +
str( ingressDevice ) + " and " +
str( egressDevice ) )
- match = re.search('id=0x([\da-f]+),', handle)
+ match = re.search( 'id=0x([\da-f]+),', handle )
if match:
- return match.group()[3:-1]
+ return match.group()[ 3:-1 ]
else:
main.log.error( "Error, intent ID not found" )
return None
@@ -1532,9 +1533,9 @@
"intent" )
return None
else:
- match = re.search('id=0x([\da-f]+),', handle)
+ match = re.search( 'id=0x([\da-f]+),', handle )
if match:
- return match.group()[3:-1]
+ return match.group()[ 3:-1 ]
else:
main.log.error( "Error, intent ID not found" )
return None
@@ -1691,9 +1692,9 @@
"intent" )
return None
else:
- match = re.search('id=0x([\da-f]+),', handle)
+ match = re.search( 'id=0x([\da-f]+),', handle )
if match:
- return match.group()[3:-1]
+ return match.group()[ 3:-1 ]
else:
main.log.error( "Error, intent ID not found" )
return None
@@ -1729,7 +1730,7 @@
tcpDst="",
ingressLabel="",
egressLabel="",
- priority=""):
+ priority="" ):
"""
Required:
* ingressDevice: device id of ingress device
@@ -1824,9 +1825,9 @@
main.log.info( "MPLS intent installed between " +
str( ingressDevice ) + " and " +
str( egressDevice ) )
- match = re.search('id=0x([\da-f]+),', handle)
+ match = re.search( 'id=0x([\da-f]+),', handle )
if match:
- return match.group()[3:-1]
+ return match.group()[ 3:-1 ]
else:
main.log.error( "Error, intent ID not found" )
return None
@@ -2024,7 +2025,7 @@
assert handle is not None, "Error in sendline"
assert "Command not found:" not in handle, handle
jsonResult = json.loads( handle )
- return len(jsonResult['routes4'])
+ return len( jsonResult[ 'routes4' ] )
except AssertionError:
main.log.exception( "" )
return None
@@ -2039,7 +2040,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- #=============Function to check Bandwidth allocation========
+ # =============Function to check Bandwidth allocation========
def allocations( self, jsonFormat = True, dollarSign = True ):
"""
Description:
@@ -2067,7 +2068,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def intents( self, jsonFormat = True, summary = False, **intentargs):
+ def intents( self, jsonFormat = True, summary = False, **intentargs ):
"""
Description:
Obtain intents from the ONOS cli.
@@ -2115,7 +2116,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def getIntentState(self, intentsId, intentsJson=None):
+ def getIntentState( self, intentsId, intentsJson=None ):
"""
Description:
Gets intent state. Accepts a single intent ID (string type) or a
@@ -2193,15 +2194,15 @@
returnValue = main.TRUE
# Generating a dictionary: intent id as a key and state as value
- #intentsDict = self.getIntentState( intentsId )
+ # intentsDict = self.getIntentState( intentsId )
intentsDict = []
for intent in json.loads( self.intents() ):
- if isinstance ( intentsId, types.StringType) \
- and intent.get('id') == intentsId:
- intentsDict.append(intent)
- elif isinstance ( intentsId, types.ListType ) \
+ if isinstance( intentsId, types.StringType ) \
+ and intent.get( 'id' ) == intentsId:
+ intentsDict.append( intent )
+ elif isinstance( intentsId, types.ListType ) \
and any( intent.get( 'id' ) == ids for ids in intentsId ):
- intentsDict.append(intent)
+ intentsDict.append( intent )
if not intentsDict:
main.log.info( self.name + ": There is something wrong " +
@@ -2272,10 +2273,10 @@
expected = expected.rstrip()
main.log.debug( "Expect: {}\nactual: {}".format( expected, actual ) )
if actual != expected and 'allocated' in actual and 'allocated' in expected:
- marker1 = actual.find('allocated')
- m1 = actual[:marker1]
- marker2 = expected.find('allocated')
- m2 = expected[:marker2]
+ marker1 = actual.find( 'allocated' )
+ m1 = actual[ :marker1 ]
+ marker2 = expected.find( 'allocated' )
+ m2 = expected[ :marker2 ]
if m1 != m2:
bandwidthFailed = True
elif actual != expected and 'allocated' not in actual and 'allocated' not in expected:
@@ -2284,7 +2285,7 @@
ONOSOutput.close()
if bandwidthFailed:
- main.log.error("Bandwidth not allocated correctly using Intents!!")
+ main.log.error( "Bandwidth not allocated correctly using Intents!!" )
returnValue = main.FALSE
return returnValue
except TypeError:
@@ -2374,10 +2375,10 @@
# get total and installed number, see if they are match
allState = response.get( 'all' )
- if allState.get('total') == allState.get('installed'):
- main.log.info( 'Total Intents: {} Installed Intents: {}'.format( allState.get('total'), allState.get('installed') ) )
+ if allState.get( 'total' ) == allState.get( 'installed' ):
+ main.log.info( 'Total Intents: {} Installed Intents: {}'.format( allState.get( 'total' ), allState.get( 'installed' ) ) )
return main.TRUE
- main.log.info( 'Verified Intents failed Excepte intetnes: {} installed intents: {}'.format( allState.get('total'), allState.get('installed') ) )
+ main.log.info( 'Verified Intents failed Excepte intetnes: {} installed intents: {}'.format( allState.get( 'total' ), allState.get( 'installed' ) ) )
return main.FALSE
except ( TypeError, ValueError ):
@@ -2439,7 +2440,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def checkFlowCount(self, min=0, timeout=60 ):
+ def checkFlowCount( self, min=0, timeout=60 ):
count = self.getTotalFlowsNum( timeout=timeout )
count = int( count ) if count else 0
return count if ( count > min ) else False
@@ -2459,9 +2460,9 @@
parameter is set true, return main.FALSE otherwise.
"""
try:
- states = ["PENDING_ADD", "PENDING_REMOVE", "REMOVED", "FAILED"]
+ states = [ "PENDING_ADD", "PENDING_REMOVE", "REMOVED", "FAILED" ]
checkedStates = []
- statesCount = [0, 0, 0, 0]
+ statesCount = [ 0, 0, 0, 0 ]
for s in states:
rawFlows = self.flows( state=s, timeout = timeout )
if rawFlows:
@@ -2471,19 +2472,19 @@
else:
return main.FALSE
for i in range( len( states ) ):
- for c in checkedStates[i]:
+ for c in checkedStates[ i ]:
try:
- statesCount[i] += int( c.get( "flowCount" ) )
+ statesCount[ i ] += int( c.get( "flowCount" ) )
except TypeError:
main.log.exception( "Json object not as expected" )
- main.log.info( states[i] + " flows: " + str( statesCount[i] ) )
+ main.log.info( states[ i ] + " flows: " + str( statesCount[ i ] ) )
# We want to count PENDING_ADD if isPENDING is true
if isPENDING:
- if statesCount[1] + statesCount[2] + statesCount[3] > 0:
+ if statesCount[ 1 ] + statesCount[ 2 ] + statesCount[ 3 ] > 0:
return main.FALSE
else:
- if statesCount[0] + statesCount[1] + statesCount[2] + statesCount[3] > 0:
+ if statesCount[ 0 ] + statesCount[ 1 ] + statesCount[ 2 ] + statesCount[ 3 ] > 0:
return main.FALSE
return main.TRUE
except ( TypeError, ValueError ):
@@ -2578,12 +2579,12 @@
cmd = "flows -c added"
rawFlows = self.sendline( cmd, timeout=timeout, noExit=noExit )
if rawFlows:
- rawFlows = rawFlows.split("\n")
+ rawFlows = rawFlows.split( "\n" )
totalFlows = 0
for l in rawFlows:
- totalFlows += int(l.split("Count=")[1])
+ totalFlows += int( l.split( "Count=" )[ 1 ] )
else:
- main.log.error("Response not as expected!")
+ main.log.error( "Response not as expected!" )
return None
return totalFlows
@@ -2620,7 +2621,7 @@
if response is None:
return -1
response = json.loads( response )
- return int( response.get("intents") )
+ return int( response.get( "intents" ) )
except ( TypeError, ValueError ):
main.log.exception( "{}: Object not as expected: {!r}".format( self.name, response ) )
return None
@@ -2714,7 +2715,7 @@
"""
try:
# Obtain output of intents function
- intentsStr = self.intents(jsonFormat=True)
+ intentsStr = self.intents( jsonFormat=True )
if intentsStr is None:
raise TypeError
# Convert to a dictionary
@@ -2824,7 +2825,7 @@
main.log.info( "There are no nodes to get id from" )
return idList
nodesJson = json.loads( nodesStr )
- idList = [ node.get('id') for node in nodesJson ]
+ idList = [ node.get( 'id' ) for node in nodesJson ]
return idList
except ( TypeError, ValueError ):
main.log.exception( "{}: Object not as expected: {!r}".format( self.name, nodesStr ) )
@@ -2876,7 +2877,7 @@
import json
try:
# either onos:topology or 'topology' will work in CLI
- topology = json.loads(topologyOutput)
+ topology = json.loads( topologyOutput )
main.log.debug( topology )
return topology
except ( TypeError, ValueError ):
@@ -2890,7 +2891,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def checkStatus(self, numoswitch, numolink, numoctrl = -1, logLevel="info"):
+ def checkStatus( self, numoswitch, numolink, numoctrl = -1, logLevel="info" ):
"""
Checks the number of switches & links that ONOS sees against the
supplied values. By default this will report to main.log, but the
@@ -2990,7 +2991,7 @@
return main.TRUE
else:
main.log.error( "Invalid 'role' given to device_role(). " +
- "Value was '" + str(role) + "'." )
+ "Value was '" + str( role ) + "'." )
return main.FALSE
except AssertionError:
main.log.exception( "" )
@@ -3338,9 +3339,9 @@
output = json.loads( rawOutput )
results = []
for dict in output:
- if dict["topic"] == topic:
- leader = dict["leader"]
- candidates = re.split( ", ", dict["candidates"][1:-1] )
+ if dict[ "topic" ] == topic:
+ leader = dict[ "leader" ]
+ candidates = re.split( ", ", dict[ "candidates" ][ 1:-1 ] )
results.append( leader )
results.extend( candidates )
return results
@@ -3479,8 +3480,8 @@
appsJson = json.loads( output )
state = None
for app in appsJson:
- if appName == app.get('name'):
- state = app.get('state')
+ if appName == app.get( 'name' ):
+ state = app.get( 'state' )
break
if state == "ACTIVE" or state == "INSTALLED":
return state
@@ -3532,7 +3533,7 @@
# Invalid option
main.log.error( "The ONOS app command argument only takes " +
"the values: (activate|deactivate|uninstall)" +
- "; was given '" + option + "'")
+ "; was given '" + option + "'" )
return main.FALSE
cmdStr = "onos:app " + option + " " + appName
output = self.sendline( cmdStr )
@@ -3590,7 +3591,7 @@
if status == "INSTALLED":
response = self.app( appName, "activate" )
if check and response == main.TRUE:
- for i in range(10): # try 10 times then give up
+ for i in range( 10 ): # try 10 times then give up
status = self.appStatus( appName )
if status == "ACTIVE":
return main.TRUE
@@ -3643,7 +3644,7 @@
elif status == "ACTIVE":
response = self.app( appName, "deactivate" )
if check and response == main.TRUE:
- for i in range(10): # try 10 times then give up
+ for i in range( 10 ): # try 10 times then give up
status = self.appStatus( appName )
if status == "INSTALLED":
return main.TRUE
@@ -3692,7 +3693,7 @@
if status == "INSTALLED":
response = self.app( appName, "uninstall" )
if check and response == main.TRUE:
- for i in range(10): # try 10 times then give up
+ for i in range( 10 ): # try 10 times then give up
status = self.appStatus( appName )
if status == "UNINSTALLED":
return main.TRUE
@@ -3707,7 +3708,7 @@
"currently active." )
response = self.app( appName, "uninstall" )
if check and response == main.TRUE:
- for i in range(10): # try 10 times then give up
+ for i in range( 10 ): # try 10 times then give up
status = self.appStatus( appName )
if status == "UNINSTALLED":
return main.TRUE
@@ -3812,8 +3813,8 @@
# there is more than one app with this ID
result = main.FALSE
# We will log this later in the method
- elif not current[0][ 'name' ] == appName:
- currentName = current[0][ 'name' ]
+ elif not current[ 0 ][ 'name' ] == appName:
+ currentName = current[ 0 ][ 'name' ]
result = main.FALSE
main.log.error( "'app-ids' has " + str( currentName ) +
" registered under id:" + str( appID ) +
@@ -3828,12 +3829,12 @@
namesList.append( item[ 'name' ] )
if len( idsList ) != len( set( idsList ) ) or\
len( namesList ) != len( set( namesList ) ):
- main.log.error( "'app-ids' has some duplicate entries: \n"
- + json.dumps( ids,
- sort_keys=True,
- indent=4,
- separators=( ',', ': ' ) ) )
- result = main.FALSE
+ main.log.error( "'app-ids' has some duplicate entries: \n"
+ + json.dumps( ids,
+ sort_keys=True,
+ indent=4,
+ separators=( ',', ': ' ) ) )
+ result = main.FALSE
return result
except ( TypeError, ValueError ):
main.log.exception( "{}: Object not as expected: {!r}".format( self.name, rawJson ) )
@@ -4018,9 +4019,9 @@
output = self.distPrimitivesSend( cmdStr )
positiveMatch = "\[(.*)\] was added to the set " + str( setName )
negativeMatch = "\[(.*)\] was already in set " + str( setName )
- if re.search( positiveMatch, output):
+ if re.search( positiveMatch, output ):
return main.TRUE
- elif re.search( negativeMatch, output):
+ elif re.search( negativeMatch, output ):
return main.FALSE
else:
main.log.error( self.name + ": setTestAdd did not" +
@@ -4702,14 +4703,14 @@
cmd += " -j"
cmd += " " + uri
if isinstance( ip, str ):
- ip = [ip]
+ ip = [ ip ]
for item in ip:
if ":" in item:
sitem = item.split( ":" )
- if len(sitem) == 3:
+ if len( sitem ) == 3:
cmd += " " + item
- elif "." in sitem[1]:
- cmd += " {}:{}".format(item, port)
+ elif "." in sitem[ 1 ]:
+ cmd += " {}:{}".format( item, port )
else:
main.log.error( "Malformed entry: " + item )
raise TypeError
@@ -4749,7 +4750,7 @@
If a host cannot be removed, then this function will return main.FALSE
'''
try:
- if type( device ) is str:
+ if isinstance( device, str ):
deviceStr = device
device = []
device.append( deviceStr )
@@ -4790,7 +4791,7 @@
If a host cannot be removed, then this function will return main.FALSE
'''
try:
- if type( host ) is str:
+ if isinstance( host, str ):
host = list( host )
for h in host:
@@ -4951,7 +4952,7 @@
assert idToDevice[ nodeA ][ 'available' ] and idToDevice[ nodeB ][ 'available' ]
if nodeA not in graphDict.keys():
graphDict[ nodeA ] = { 'edges': {},
- 'dpid': idToDevice[ nodeA ][ 'id' ][3:],
+ 'dpid': idToDevice[ nodeA ][ 'id' ][ 3: ],
'type': idToDevice[ nodeA ][ 'type' ],
'available': idToDevice[ nodeA ][ 'available' ],
'role': idToDevice[ nodeA ][ 'role' ],
@@ -5002,9 +5003,9 @@
# Delete any white space in line
temp = re.sub( r'\s+', '', l )
temp = temp.split( ":" )
- respDic[ temp[0] ] = temp[ 1 ]
+ respDic[ temp[ 0 ] ] = temp[ 1 ]
- except (TypeError, ValueError):
+ except ( TypeError, ValueError ):
main.log.exception( self.name + ": Object not as expected" )
return None
except KeyError:
@@ -5046,7 +5047,7 @@
total: return how many lines in karaf log
"""
try:
- assert type( searchTerm ) is str
+ assert isinstance( searchTerm, str )
# Build the log paths string
logPath = '/opt/onos/log/karaf.log.'
logPaths = '/opt/onos/log/karaf.log'
@@ -5068,14 +5069,14 @@
return num
elif mode == 'total':
totalLines = self.sendline( "cat /opt/onos/log/karaf.log | wc -l" )
- return int(totalLines)
+ return int( totalLines )
else:
main.log.error( self.name + " unsupported mode" )
return main.ERROR
before = self.sendline( cmd )
before = before.splitlines()
# make sure the returned list only contains the search term
- returnLines = [line for line in before if searchTerm in line]
+ returnLines = [ line for line in before if searchTerm in line ]
return returnLines
except AssertionError:
main.log.error( self.name + " searchTerm is not string type" )
@@ -5121,7 +5122,7 @@
main.log.error( self.name + ": " + self.handle.before )
main.cleanAndExit()
except NotImplementedError:
- main.log.exception( self.name + ": Json output not supported")
+ main.log.exception( self.name + ": Json output not supported" )
return None
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
@@ -5143,7 +5144,7 @@
for match in mIter:
item = {}
item[ 'name' ] = match.group( 'name' )
- ifaces = match.group( 'interfaces' ).split( ', ')
+ ifaces = match.group( 'interfaces' ).split( ', ' )
if ifaces == [ "" ]:
ifaces = []
item[ 'interfaces' ] = ifaces
@@ -5183,7 +5184,7 @@
main.log.error( self.name + ": " + self.handle.before )
main.cleanAndExit()
except NotImplementedError:
- main.log.exception( self.name + ": Json output not supported")
+ main.log.exception( self.name + ": Json output not supported" )
return None
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
@@ -5415,7 +5416,7 @@
main.log.error( self.name + ": " + self.handle.before )
main.cleanAndExit()
except NotImplementedError:
- main.log.exception( self.name + ": Json output not supported")
+ main.log.exception( self.name + ": Json output not supported" )
return None
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
@@ -5437,15 +5438,15 @@
Please look at the "logsearch" Function in onosclidriver.py
'''
if logNum < 0:
- main.log.error("Get wrong log number ")
+ main.log.error( "Get wrong log number ")
return main.ERROR
lines = self.logSearch( mode=mode, searchTerm=searchTerm, startLine=startLine, logNum=logNum )
- if len(lines) == 0:
+ if len( lines ) == 0:
main.log.warn( "Captured timestamp string is empty" )
return main.ERROR
lines = lines[ 0 ]
try:
- assert type(lines) is str
+ assert isinstance( lines, str )
# get the target value
line = lines.split( splitTerm_before )
key = line[ 1 ].split( splitTerm_after )
@@ -5613,7 +5614,7 @@
return None
else:
match = re.search( pattern, output )
- return match.group(0)
+ return match.group( 0 )
except ( AttributeError, TypeError ):
main.log.exception( self.name + ": Object not as expected; " + str( output ) )
return None
@@ -5646,7 +5647,7 @@
return None
else:
match = re.search( pattern, output )
- return match.group(0)
+ return match.group( 0 )
except ( AttributeError, TypeError ):
main.log.exception( self.name + ": Object not as expected; " + str( output ) )
return None
@@ -5679,7 +5680,7 @@
return None
else:
match = re.search( pattern, output )
- return match.group(0)
+ return match.group( 0 )
except ( AttributeError, TypeError ):
main.log.exception( self.name + ": Object not as expected; " + str( output ) )
return None
@@ -5734,4 +5735,3 @@
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
diff --git a/TestON/drivers/common/cli/onosclusterdriver.py b/TestON/drivers/common/cli/onosclusterdriver.py
index 5093cfe..af59a60 100755
--- a/TestON/drivers/common/cli/onosclusterdriver.py
+++ b/TestON/drivers/common/cli/onosclusterdriver.py
@@ -34,10 +34,12 @@
# FIXME: Move this to it's own file?
class Controller():
+
def __str__( self ):
return self.name
+
def __repr__( self ):
- #TODO use repr() for components?
+ # TODO use repr() for components?
return "%s<IP=%s, CLI=%s, REST=%s, Bench=%s >" % ( self.name,
self.ipAddress,
self.CLI,
@@ -77,10 +79,8 @@
return f
raise AttributeError( "Could not find the attribute %s in %r or it's component handles" % ( name, self ) )
-
-
def __init__( self, name, ipAddress, CLI=None, REST=None, Bench=None, pos=None, userName=None, server=None ):
- #TODO: validate these arguments
+ # TODO: validate these arguments
self.name = str( name )
self.ipAddress = ipAddress
self.CLI = CLI
@@ -131,7 +131,7 @@
elif key == "cluster_name":
prefix = self.options[ key ]
- self.home = self.checkOptions(self.home, "~/onos")
+ self.home = self.checkOptions(self.home, "~/onos" )
self.karafUser = self.checkOptions(self.karafUser, self.user_name)
self.karafPass = self.checkOptions(self.karafPass, self.pwd )
prefix = self.checkOptions( prefix, "ONOS" )
@@ -366,7 +366,6 @@
main.log.error( name + " component already exists!" )
main.cleanAndExit()
-
def setServerOptions( self, name, ipAddress ):
"""
Parse the cluster options to create an ONOS "server" component with the given name
@@ -383,7 +382,6 @@
main.componentDictionary[name]['connect_order'] = str( int( main.componentDictionary[name]['connect_order'] ) + 1 )
main.log.debug( main.componentDictionary[name] )
-
def createServerComponent( self, name, ipAddress ):
"""
Creates a new onos "server" component. This will be connected to the
@@ -414,7 +412,6 @@
main.log.error( name + " component already exists!" )
main.cleanAndExit()
-
def createComponents( self, prefix='', createServer=True ):
"""
Creates a CLI and REST component for each nodes in the cluster
diff --git a/TestON/drivers/common/cli/onosdriver.py b/TestON/drivers/common/cli/onosdriver.py
index eed4057..73b1755 100755
--- a/TestON/drivers/common/cli/onosdriver.py
+++ b/TestON/drivers/common/cli/onosdriver.py
@@ -72,10 +72,9 @@
break
self.maxNodes = None
- if self.maxNodes == None or self.maxNodes == "":
+ if self.maxNodes is None or self.maxNodes == "":
self.maxNodes = 100
-
# Grabs all OC environment variables based on max number of nodes
self.onosIps = {} # Dictionary of all possible ONOS ip
@@ -110,7 +109,7 @@
main.log.error( "Uncaught exception: " + str( inst ) )
try:
- if os.getenv( str( self.ip_address ) ) != None:
+ if os.getenv( str( self.ip_address ) ) is not None:
self.ip_address = os.getenv( str( self.ip_address ) )
else:
main.log.info( self.name +
@@ -305,7 +304,7 @@
'Runtime\sEnvironment\sto\scontinue',
'BUILD\sFAILURE',
'BUILD\sSUCCESS',
- 'onos' + self.prompt, #TODO: fix this to be more generic?
+ 'onos' + self.prompt, # TODO: fix this to be more generic?
'ONOS' + self.prompt,
pexpect.TIMEOUT ], mciTimeout )
if i == 0:
@@ -417,7 +416,7 @@
self.handle.expect( self.prompt )
cmd = "git pull"
if comp1 != "":
- cmd += ' ' + comp1
+ cmd += ' ' + comp1
if fastForward:
cmd += ' ' + " --ff-only"
self.handle.sendline( cmd )
@@ -498,7 +497,7 @@
self.handle.expect( self.prompt )
return main.ERROR
except Exception:
- main.log.exception( "Couldn't exit editor prompt!")
+ main.log.exception( "Couldn't exit editor prompt!" )
main.cleanAndExit()
elif i == 10: # In the middle of a merge commit
@@ -652,11 +651,11 @@
self.handle.sendline( "git name-rev --name-only HEAD" )
self.handle.expect( "git name-rev --name-only HEAD" )
self.handle.expect( self.prompt )
- lines = self.handle.before.splitlines()
- if lines[1] == "master" or re.search( "^onos-\d+(\.\d+)+$", lines[1] ):
- return lines[1]
+ lines = self.handle.before.splitlines()
+ if lines[ 1 ] == "master" or re.search( "^onos-\d+(\.\d+)+$", lines[ 1 ] ):
+ return lines[ 1 ]
else:
- main.log.info( lines[1] )
+ main.log.info( lines[ 1 ] )
return "unexpected ONOS branch"
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -702,11 +701,11 @@
# as xml specific tags that cause errors
line = line.replace( "<", "[" )
line = line.replace( ">", "]" )
- #main.log.wiki( "\t" + line )
+ # main.log.wiki( "\t" + line )
main.log.wiki( line + "<br /> " )
main.log.summary( line )
main.log.wiki( "</blockquote>" )
- main.log.summary("\n")
+ main.log.summary( "\n" )
return lines[ 2 ]
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -837,14 +836,14 @@
handleAfter = self.handle.after
# Get the rest of the handle
self.handle.expect( self.prompt )
- time.sleep(10)
+ time.sleep( 10 )
handleMore = self.handle.before
cell_result = handleBefore + handleAfter + handleMore
- #print cell_result
+ # print cell_result
if( re.search( "No such cell", cell_result ) ):
main.log.error( "Cell call returned: " + handleBefore +
- handleAfter + handleMore )
+ handleAfter + handleMore )
main.cleanAndExit()
return main.TRUE
@@ -899,11 +898,11 @@
self.handle.sendline( "" )
self.handle.expect( ":~" )
self.handle.sendline( cfgStr )
- self.handle.expect("cfg set")
+ self.handle.expect( "cfg set" )
self.handle.expect( ":~" )
- paramValue = configParam.split(" ")[1]
- paramName = configParam.split(" ")[0]
+ paramValue = configParam.split( " " )[ 1 ]
+ paramName = configParam.split( " " )[ 0 ]
checkStr = 'onos {} cfg get " {} {} " '.format( ONOSIp, configName, paramName )
@@ -911,7 +910,7 @@
self.handle.expect( ":~" )
if "value=" + paramValue + "," in self.handle.before:
- main.log.info("cfg " + configName + " successfully set to " + configParam)
+ main.log.info( "cfg " + configName + " successfully set to " + configParam )
return main.TRUE
except pexpect.ExceptionPexpect as e:
main.log.exception( self.name + ": Pexpect exception found: " )
@@ -967,7 +966,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def onosSecureSSH( self, userName="onos", userPWD="rocks", node=""):
+ def onosSecureSSH( self, userName="onos", userPWD="rocks", node="" ):
"""
Enables secure access to ONOS console
by removing default users & keys.
@@ -985,9 +984,9 @@
# NOTE: this timeout may need to change depending on the network
# and size of ONOS
# TODO: Handle the other possible error
- i = self.handle.expect([ "Network\sis\sunreachable",
- self.prompt,
- pexpect.TIMEOUT ], timeout=180 )
+ i = self.handle.expect( [ "Network\sis\sunreachable",
+ self.prompt,
+ pexpect.TIMEOUT ], timeout=180 )
if i == 0:
# can't reach ONOS node
main.log.warn( "Network is unreachable" )
@@ -996,8 +995,8 @@
elif i == 1:
# Process started
main.log.info(
- "Secure SSH performed on " +
- node)
+ "Secure SSH performed on " +
+ node )
return main.TRUE
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
@@ -1007,7 +1006,6 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
def onosInstall( self, options="-f", node="" ):
"""
Installs ONOS bits on the designated cell machine.
@@ -1337,7 +1335,7 @@
self.handle.sendline( "onos-wait-for-start " + node )
self.handle.expect( "onos-wait-for-start" )
# NOTE: this timeout is arbitrary"
- i = self.handle.expect([self.prompt, pexpect.TIMEOUT], timeout)
+ i = self.handle.expect( [ self.prompt, pexpect.TIMEOUT ], timeout )
if i == 0:
main.log.info( self.name + ": " + node + " is up" )
return main.TRUE
@@ -1376,7 +1374,6 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
-
def pushTestIntentsShell(
self,
dpidSrc,
@@ -1518,7 +1515,7 @@
self.handle.expect( self.prompt )
self.handle.sendline( "" )
if grepOptions:
- grepStr = "grep "+str(grepOptions)
+ grepStr = "grep " + str( grepOptions )
else:
grepStr = "grep"
@@ -1527,12 +1524,12 @@
str( interface ) +
" -t e | " +
grepStr + " --line-buffered \"" +
- str(grep) +
+ str( grep ) +
"\" >" +
directory +
" &" )
- self.handle.sendline(cmd)
- main.log.info(cmd)
+ self.handle.sendline( cmd )
+ main.log.info( cmd )
self.handle.expect( "Capturing on" )
self.handle.sendline( "\n" )
self.handle.expect( self.prompt )
@@ -1600,7 +1597,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def dumpONOSCmd(self, ONOSIp, CMD, destDir, filename, options=""):
+ def dumpONOSCmd( self, ONOSIp, CMD, destDir, filename, options="" ):
"""
Dump Cmd to a desired directory.
For debugging purposes, you may want to use
@@ -1622,8 +1619,8 @@
localtime = localtime.replace( ":", "" )
if destDir[ -1: ] != "/":
destDir += "/"
- cmd=CMD + " " + options + " > " + str( destDir ) + str( filename ) + localtime
- return self.onosCli(ONOSIp, cmd)
+ cmd = CMD + " " + options + " > " + str( destDir ) + str( filename ) + localtime
+ return self.onosCli( ONOSIp, cmd )
def cpLogsToDir( self, logToCopy,
destDir, copyFileName="" ):
@@ -1678,7 +1675,7 @@
except Exception:
main.log.exception( "Copying files failed" )
- def checkLogs( self, onosIp, restart=False):
+ def checkLogs( self, onosIp, restart=False ):
"""
runs onos-check-logs on the given onos node
If restart is True, use the old version of onos-check-logs which
@@ -1804,14 +1801,14 @@
cmd = "sudo iptables " + actionFlag + " " +\
direction +\
" -s " + str( ip )
- # " -p " + str( packet_type ) +\
+ # " -p " + str( packet_type ) +\
if packet_type:
cmd += " -p " + str( packet_type )
if port:
cmd += " --dport " + str( port )
if states:
cmd += " -m state --state="
- #FIXME- Allow user to configure which states to block
+ # FIXME- Allow user to configure which states to block
cmd += "INVALID,ESTABLISHED,NEW,RELATED,UNTRACKED"
cmd += " -j " + str( rule )
@@ -1840,7 +1837,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def detailed_status(self, log_filename):
+ def detailed_status( self, log_filename ):
"""
This method is used by STS to check the status of the controller
Reports RUNNING, STARTING, STOPPED, FROZEN, ERROR (and reason)
@@ -1884,7 +1881,7 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def createLinkGraphFile( self, benchIp, ONOSIpList, deviceCount):
+ def createLinkGraphFile( self, benchIp, ONOSIpList, deviceCount ):
'''
Create/formats the LinkGraph.cfg file based on arguments
-only creates a linear topology and connects islands
@@ -1895,114 +1892,113 @@
deviceCount - number of switches to be assigned
'''
- main.log.info("Creating link graph configuration file." )
+ main.log.info( "Creating link graph configuration file." )
linkGraphPath = self.home + "/tools/package/etc/linkGraph.cfg"
tempFile = "/tmp/linkGraph.cfg"
- linkGraph = open(tempFile, 'w+')
- linkGraph.write("# NullLinkProvider topology description (config file).\n")
- linkGraph.write("# The NodeId is only added if the destination is another node's device.\n")
- linkGraph.write("# Bugs: Comments cannot be appended to a line to be read.\n")
+ linkGraph = open( tempFile, 'w+' )
+ linkGraph.write( "# NullLinkProvider topology description (config file).\n" )
+ linkGraph.write( "# The NodeId is only added if the destination is another node's device.\n" )
+ linkGraph.write( "# Bugs: Comments cannot be appended to a line to be read.\n" )
- clusterCount = len(ONOSIpList)
+ clusterCount = len( ONOSIpList )
- if type(deviceCount) is int or type(deviceCount) is str:
- deviceCount = int(deviceCount)
- switchList = [0]*(clusterCount+1)
+ if isinstance( deviceCount, int ) or isinstance( deviceCount, str ):
+ deviceCount = int( deviceCount )
+ switchList = [ 0 ]*( clusterCount+1 )
baselineSwitchCount = deviceCount/clusterCount
- for node in range(1, clusterCount + 1):
- switchList[node] = baselineSwitchCount
+ for node in range( 1, clusterCount + 1 ):
+ switchList[ node ] = baselineSwitchCount
- for node in range(1, (deviceCount%clusterCount)+1):
- switchList[node] += 1
+ for node in range( 1, ( deviceCount % clusterCount )+1 ):
+ switchList[ node ] += 1
- if type(deviceCount) is list:
- main.log.info("Using provided device distribution")
- switchList = [0]
+ if isinstance( deviceCount, list ):
+ main.log.info( "Using provided device distribution" )
+ switchList = [ 0 ]
for i in deviceCount:
- switchList.append(int(i))
+ switchList.append( int( i ) )
- tempList = ['0']
- tempList.extend(ONOSIpList)
+ tempList = [ '0' ]
+ tempList.extend( ONOSIpList )
ONOSIpList = tempList
myPort = 6
lastSwitch = 0
- for node in range(1, clusterCount+1):
- if switchList[node] == 0:
+ for node in range( 1, clusterCount+1 ):
+ if switchList[ node ] == 0:
continue
- linkGraph.write("graph " + ONOSIpList[node] + " {\n")
+ linkGraph.write( "graph " + ONOSIpList[ node ] + " {\n" )
if node > 1:
- #connect to last device on previous node
- line = ("\t0:5 -> " + str(lastSwitch) + ":6:" + lastIp + "\n") #ONOSIpList[node-1]
- linkGraph.write(line)
+ # connect to last device on previous node
+ line = ( "\t0:5 -> " + str( lastSwitch ) + ":6:" + lastIp + "\n" ) # ONOSIpList[node-1]
+ linkGraph.write( line )
lastSwitch = 0
- for switch in range (0, switchList[node]-1):
+ for switch in range( 0, switchList[ node ]-1 ):
line = ""
- line = ("\t" + str(switch) + ":" + str(myPort))
+ line = ( "\t" + str( switch ) + ":" + str( myPort ) )
line += " -- "
- line += (str(switch+1) + ":" + str(myPort-1) + "\n")
- linkGraph.write(line)
+ line += ( str( switch+1 ) + ":" + str( myPort-1 ) + "\n" )
+ linkGraph.write( line )
lastSwitch = switch+1
- lastIp = ONOSIpList[node]
+ lastIp = ONOSIpList[ node ]
- #lastSwitch += 1
- if node < (clusterCount):
- #connect to first device on the next node
- line = ("\t" + str(lastSwitch) + ":6 -> 0:5:" + ONOSIpList[node+1] + "\n")
- linkGraph.write(line)
+ # lastSwitch += 1
+ if node < ( clusterCount ):
+ # connect to first device on the next node
+ line = ( "\t" + str( lastSwitch ) + ":6 -> 0:5:" + ONOSIpList[ node+1 ] + "\n" )
+ linkGraph.write( line )
- linkGraph.write("}\n")
+ linkGraph.write( "}\n" )
linkGraph.close()
- #SCP
- os.system( "scp " + tempFile + " " + self.user_name + "@" + benchIp + ":" + linkGraphPath)
- main.log.info("linkGraph.cfg creation complete")
+ # SCP
+ os.system( "scp " + tempFile + " " + self.user_name + "@" + benchIp + ":" + linkGraphPath )
+ main.log.info( "linkGraph.cfg creation complete" )
- def configNullDev( self, ONOSIpList, deviceCount, numPorts=10):
-
+ def configNullDev( self, ONOSIpList, deviceCount, numPorts=10 ):
'''
ONOSIpList = list of Ip addresses of nodes switches will be devided amongst
deviceCount = number of switches to distribute, or list of values to use as custom distribution
numPorts = number of ports per device. Defaults to 10 both in this function and in ONOS. Optional arg
'''
- main.log.info("Configuring Null Device Provider" )
- clusterCount = len(ONOSIpList)
+ main.log.info( "Configuring Null Device Provider" )
+ clusterCount = len( ONOSIpList )
try:
- if type(deviceCount) is int or type(deviceCount) is str:
- main.log.info("Creating device distribution")
- deviceCount = int(deviceCount)
- switchList = [0]*(clusterCount+1)
+ if isinstance( deviceCount, int ) or isinstance( deviceCount, str ):
+ main.log.info( "Creating device distribution" )
+ deviceCount = int( deviceCount )
+ switchList = [ 0 ]*( clusterCount+1 )
baselineSwitchCount = deviceCount/clusterCount
- for node in range(1, clusterCount + 1):
- switchList[node] = baselineSwitchCount
+ for node in range( 1, clusterCount + 1 ):
+ switchList[ node ] = baselineSwitchCount
- for node in range(1, (deviceCount%clusterCount)+1):
- switchList[node] += 1
+ for node in range( 1, ( deviceCount % clusterCount )+1 ):
+ switchList[ node ] += 1
- if type(deviceCount) is list:
- main.log.info("Using provided device distribution")
+ if isinstance( deviceCount, list ):
+ main.log.info( "Using provided device distribution" )
- if len(deviceCount) == clusterCount:
- switchList = ['0']
- switchList.extend(deviceCount)
+ if len( deviceCount ) == clusterCount:
+ switchList = [ '0' ]
+ switchList.extend( deviceCount )
- if len(deviceCount) == (clusterCount + 1):
- if deviceCount[0] == '0' or deviceCount[0] == 0:
+ if len( deviceCount ) == ( clusterCount + 1 ):
+ if deviceCount[ 0 ] == '0' or deviceCount[ 0 ] == 0:
switchList = deviceCount
- assert len(switchList) == (clusterCount + 1)
+ assert len( switchList ) == ( clusterCount + 1 )
except AssertionError:
- main.log.error( "Bad device/Ip list match")
+ main.log.error( "Bad device/Ip list match" )
except TypeError:
main.log.exception( self.name + ": Object not as expected" )
return None
@@ -2010,73 +2006,71 @@
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
+ ONOSIp = [ 0 ]
+ ONOSIp.extend( ONOSIpList )
- ONOSIp = [0]
- ONOSIp.extend(ONOSIpList)
-
- devicesString = "devConfigs = "
- for node in range(1, len(ONOSIp)):
- devicesString += (ONOSIp[node] + ":" + str(switchList[node] ))
+ devicesString = "devConfigs = "
+ for node in range( 1, len( ONOSIp ) ):
+ devicesString += ( ONOSIp[ node ] + ":" + str( switchList[ node ] ) )
if node < clusterCount:
- devicesString += (",")
+ devicesString += ( "," )
try:
- self.handle.sendline("onos $OC1 cfg set org.onosproject.provider.nil.device.impl.NullDeviceProvider devConfigs " + devicesString )
- self.handle.expect(":~")
- self.handle.sendline("onos $OC1 cfg set org.onosproject.provider.nil.device.impl.NullDeviceProvider numPorts " + str(numPorts) )
- self.handle.expect(":~")
+ self.handle.sendline( "onos $OC1 cfg set org.onosproject.provider.nil.device.impl.NullDeviceProvider devConfigs " + devicesString )
+ self.handle.expect( ":~" )
+ self.handle.sendline( "onos $OC1 cfg set org.onosproject.provider.nil.device.impl.NullDeviceProvider numPorts " + str( numPorts ) )
+ self.handle.expect( ":~" )
- for i in range(10):
- self.handle.sendline("onos $OC1 cfg get org.onosproject.provider.nil.device.impl.NullDeviceProvider")
- self.handle.expect(":~")
+ for i in range( 10 ):
+ self.handle.sendline( "onos $OC1 cfg get org.onosproject.provider.nil.device.impl.NullDeviceProvider" )
+ self.handle.expect( ":~" )
verification = self.handle.before
- if (" value=" + str(numPorts)) in verification and (" value=" + devicesString) in verification:
+ if ( " value=" + str( numPorts ) ) in verification and ( " value=" + devicesString ) in verification:
break
else:
- time.sleep(1)
+ time.sleep( 1 )
- assert ("value=" + str(numPorts)) in verification and (" value=" + devicesString) in verification
+ assert ( "value=" + str( numPorts ) ) in verification and ( " value=" + devicesString ) in verification
except AssertionError:
- main.log.error("Incorrect Config settings: " + verification)
+ main.log.error( "Incorrect Config settings: " + verification )
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
main.cleanAndExit()
- def configNullLink( self,fileName="/opt/onos/apache-karaf-3.0.3/etc/linkGraph.cfg", eventRate=0):
+ def configNullLink( self, fileName="/opt/onos/apache-karaf-3.0.3/etc/linkGraph.cfg", eventRate=0 ):
'''
fileName default is currently the same as the default on ONOS, specify alternate file if
you want to use a different topology file than linkGraph.cfg
'''
-
try:
- self.handle.sendline("onos $OC1 cfg set org.onosproject.provider.nil.link.impl.NullLinkProvider eventRate " + str(eventRate))
- self.handle.expect(":~")
- self.handle.sendline("onos $OC1 cfg set org.onosproject.provider.nil.link.impl.NullLinkProvider cfgFile " + fileName )
- self.handle.expect(":~")
+ self.handle.sendline( "onos $OC1 cfg set org.onosproject.provider.nil.link.impl.NullLinkProvider eventRate " + str( eventRate ) )
+ self.handle.expect( ":~" )
+ self.handle.sendline( "onos $OC1 cfg set org.onosproject.provider.nil.link.impl.NullLinkProvider cfgFile " + fileName )
+ self.handle.expect( ":~" )
- for i in range(10):
- self.handle.sendline("onos $OC1 cfg get org.onosproject.provider.nil.link.impl.NullLinkProvider")
- self.handle.expect(":~")
+ for i in range( 10 ):
+ self.handle.sendline( "onos $OC1 cfg get org.onosproject.provider.nil.link.impl.NullLinkProvider" )
+ self.handle.expect( ":~" )
verification = self.handle.before
- if (" value=" + str(eventRate)) in verification and (" value=" + fileName) in verification:
+ if ( " value=" + str( eventRate ) ) in verification and ( " value=" + fileName ) in verification:
break
else:
- time.sleep(1)
+ time.sleep( 1 )
- assert ("value=" + str(eventRate)) in verification and (" value=" + fileName) in verification
+ assert ( "value=" + str( eventRate ) ) in verification and ( " value=" + fileName ) in verification
except pexpect.EOF:
main.log.error( self.name + ": EOF exception found" )
main.log.error( self.name + ": " + self.handle.before )
main.cleanAndExit()
except AssertionError:
- main.log.info("Settings did not post to ONOS")
- main.log.error(varification)
+ main.log.info( "Settings did not post to ONOS" )
+ main.log.error( varification )
except Exception:
main.log.exception( self.name + ": Uncaught exception!" )
- main.log.error(varification)
+ main.log.error( varification )
main.cleanAndExit()
def getOnosIps( self ):
@@ -2136,16 +2130,16 @@
"""
try:
main.log.info( " Log Report for {} ".format( nodeIp ).center( 70, '=' ) )
- if type( searchTerms ) is str:
- searchTerms = [searchTerms]
+ if isinstance( searchTerms, str ):
+ searchTerms = [ searchTerms ]
numTerms = len( searchTerms )
outputMode = outputMode.lower()
totalHits = 0
logLines = []
for termIndex in range( numTerms ):
- term = searchTerms[termIndex]
- logLines.append( [term] )
+ term = searchTerms[ termIndex ]
+ logLines.append( [ term ] )
if startStr and endStr:
cmd = "onos-ssh {} \"sed -n '/{}/,/{}/p' /opt/onos/log/karaf.log | grep {}\"".format( nodeIp,
startStr,
@@ -2162,7 +2156,7 @@
if term in line and "grep" not in line:
count += 1
if before.index( line ) > ( len( before ) - 7 ):
- logLines[termIndex].append( line )
+ logLines[ termIndex ].append( line )
main.log.info( "{}: {}".format( term, count ) )
totalHits += count
if termIndex == numTerms - 1:
@@ -2170,10 +2164,10 @@
if outputMode != "s":
outputString = ""
for term in logLines:
- outputString = term[0] + ": \n"
+ outputString = term[ 0 ] + ": \n"
for line in range( 1, len( term ) ):
- outputString += ( "\t" + term[line] + "\n" )
- if outputString != ( term[0] + ": \n" ):
+ outputString += ( "\t" + term[ line ] + "\n" )
+ if outputString != ( term[ 0 ] + ": \n" ):
main.log.info( outputString )
main.log.info( "=" * 70 )
return totalHits
@@ -2243,22 +2237,22 @@
main.log.error( self.name + ": " + self.handle.before )
main.cleanAndExit()
- def jvmSet(self, memory=8):
+ def jvmSet( self, memory=8 ):
import os
- homeDir = os.path.expanduser('~')
+ homeDir = os.path.expanduser( '~' )
filename = "/onos/tools/package/bin/onos-service"
- serviceConfig = open(homeDir + filename, 'w+')
- serviceConfig.write("#!/bin/bash\n ")
- serviceConfig.write("#------------------------------------- \n ")
- serviceConfig.write("# Starts ONOS Apache Karaf container\n ")
- serviceConfig.write("#------------------------------------- \n ")
- serviceConfig.write("#export JAVA_HOME=${JAVA_HOME:-/usr/lib/jvm/java-7-openjdk-amd64/}\n ")
- serviceConfig.write("""export JAVA_OPTS="${JAVA_OPTS:--Xms""" + str(memory) + "G -Xmx" + str(memory) + """G}" \n """)
- serviceConfig.write("[ -d $ONOS_HOME ] && cd $ONOS_HOME || ONOS_HOME=$(dirname $0)/..\n")
- serviceConfig.write("""${ONOS_HOME}/apache-karaf-$KARAF_VERSION/bin/karaf "$@" \n """)
+ serviceConfig = open( homeDir + filename, 'w+' )
+ serviceConfig.write( "#!/bin/bash\n " )
+ serviceConfig.write( "#------------------------------------- \n " )
+ serviceConfig.write( "# Starts ONOS Apache Karaf container\n " )
+ serviceConfig.write( "#------------------------------------- \n " )
+ serviceConfig.write( "#export JAVA_HOME=${JAVA_HOME:-/usr/lib/jvm/java-7-openjdk-amd64/}\n " )
+ serviceConfig.write( """export JAVA_OPTS="${JAVA_OPTS:--Xms""" + str( memory ) + "G -Xmx" + str( memory ) + """G}" \n """ )
+ serviceConfig.write( "[ -d $ONOS_HOME ] && cd $ONOS_HOME || ONOS_HOME=$(dirname $0)/..\n" )
+ serviceConfig.write( """${ONOS_HOME}/apache-karaf-$KARAF_VERSION/bin/karaf "$@" \n """ )
serviceConfig.close()
def createDBFile( self, testData ):
@@ -2267,7 +2261,7 @@
DBString = ""
for item in testData:
- if type( item ) is string:
+ if isinstance( item, string ):
item = "'" + item + "'"
if testData.index( item ) < len( testData - 1 ):
item += ","
@@ -2279,14 +2273,14 @@
def verifySummary( self, ONOSIp, *deviceCount ):
- self.handle.sendline( "onos " + ONOSIp + " summary" )
+ self.handle.sendline( "onos " + ONOSIp + " summary" )
self.handle.expect( ":~" )
summaryStr = self.handle.before
print "\nSummary\n==============\n" + summaryStr + "\n\n"
- #passed = "SCC(s)=1" in summaryStr
- #if deviceCount:
+ # passed = "SCC(s)=1" in summaryStr
+ # if deviceCount:
# passed = "devices=" + str(deviceCount) + "," not in summaryStr
passed = False
@@ -2298,7 +2292,7 @@
if deviceCount:
print" ============================="
- checkStr = "devices=" + str( deviceCount[0] ) + ","
+ checkStr = "devices=" + str( deviceCount[ 0 ] ) + ","
print "Checkstr: " + checkStr
if checkStr not in summaryStr:
passed = False
@@ -2330,7 +2324,7 @@
# IF self.ip_address is an ip address and matches
# self.nicAddr: return self.ip_address
if match:
- curIp = match.group(0)
+ curIp = match.group( 0 )
if nicPat:
nicMatch = re.search( nicPat, curIp )
if nicMatch:
@@ -2345,7 +2339,7 @@
ips = re.findall( ifPat, raw )
if iface:
if ips:
- ip = ips[0]
+ ip = ips[ 0 ]
self.ip_address = ip
return ip
else:
@@ -2359,8 +2353,8 @@
return ip
else: # If only one non-localhost ip, return that
tmpList = [ ip for ip in ips if ip is not LOCALHOST ]
- if len(tmpList) == 1:
- curIp = tmpList[0]
+ if len( tmpList ) == 1:
+ curIp = tmpList[ 0 ]
self.ip_address = curIp
return curIp
# Either no non-localhost IPs, or more than 1
@@ -2410,7 +2404,7 @@
onosStatus = True
for nd in nodeList:
onosStatus = onosStatus & self.isup( node = nd )
- #print "onosStatus is: " + str( onosStatus )
+ # print "onosStatus is: " + str( onosStatus )
return main.TRUE if onosStatus else main.FALSE
diff --git a/TestON/drivers/common/cli/ovsdbdriver.py b/TestON/drivers/common/cli/ovsdbdriver.py
index 636a7b2..fc029ce 100644
--- a/TestON/drivers/common/cli/ovsdbdriver.py
+++ b/TestON/drivers/common/cli/ovsdbdriver.py
@@ -51,11 +51,11 @@
def connect( self, **connectargs ):
try:
for key in connectargs:
- vars( self)[ key ] = connectargs[ key ]
+ vars( self )[ key ] = connectargs[ key ]
self.name = self.options[ 'name' ]
- if os.getenv( str( self.ip_address ) ) != None:
- self.ip_address = os.getenv(str ( self.ip_address ) )
+ if os.getenv( str( self.ip_address ) ) is not None:
+ self.ip_address = os.getenv( str( self.ip_address ) )
else:
main.log.info( self.name + ": Trying to connect to " +
self.ip_address )
@@ -63,7 +63,7 @@
user_name=self.user_name,
ip_address=self.ip_address,
port=self.port,
- pwd=self.pwd)
+ pwd=self.pwd )
if self.handle:
main.log.info( "Connection successful to the ovsdb node " +
@@ -91,7 +91,7 @@
return response
def setManager( self, ip, port, delaytime="5" ):
- command= "sudo ovs-vsctl set-manager tcp:" + str( ip ) + ":" + str( port )
+ command = "sudo ovs-vsctl set-manager tcp:" + str( ip ) + ":" + str( port )
try:
handle = self.execute(
cmd=command,
@@ -102,7 +102,7 @@
return main.FALSE
else:
main.log.info( "Ovsdb manager " + str( ip ) + " set" )
- #delay time for ovsdb connection create
+ # delay time for ovsdb connection create
main.log.info( "Wait " + str( delaytime ) + " seconds for ovsdb connection create" )
time.sleep( int( delaytime ) )
return main.TRUE
@@ -112,7 +112,7 @@
main.cleanAndExit()
def delManager( self, delaytime="5" ):
- command= "sudo ovs-vsctl del-manager"
+ command = "sudo ovs-vsctl del-manager"
try:
handle = self.execute(
cmd=command,
@@ -123,7 +123,7 @@
return main.FALSE
else:
main.log.info( "Ovsdb manager delete" )
- #delay time for ovsdb connection delete
+ # delay time for ovsdb connection delete
main.log.info( "Wait " + str( delaytime ) + " seconds for ovsdb connection delete" )
time.sleep( int( delaytime ) )
return main.TRUE
@@ -133,7 +133,7 @@
main.cleanAndExit()
def getManager( self ):
- command= "sudo ovs-vsctl get-manager"
+ command = "sudo ovs-vsctl get-manager"
try:
response = self.execute(
cmd=command,
@@ -152,7 +152,7 @@
The output of the command from the linux
or main.FALSE on timeout
"""
- command= "sudo ovs-vsctl list-br"
+ command = "sudo ovs-vsctl list-br"
try:
response = self.execute(
cmd=command,
@@ -174,7 +174,7 @@
The output of the command from the linux
or main.FALSE on timeout
"""
- command= "sudo ovs-vsctl list-ports " + str( sw )
+ command = "sudo ovs-vsctl list-ports " + str( sw )
try:
response = self.execute(
cmd=command,
@@ -199,7 +199,7 @@
try:
response = self.execute(
cmd=command,
- timeout=10)
+ timeout=10 )
if response:
return response
else:
@@ -220,7 +220,7 @@
try:
response = self.execute(
cmd=command,
- timeout=10)
+ timeout=10 )
if response:
return response
else:
@@ -251,8 +251,8 @@
else:
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.cleanAndExit()
def createHost( self, hostname ):
@@ -260,7 +260,7 @@
try:
handle = self.execute(
cmd=command,
- timeout=10)
+ timeout=10 )
if re.search( "Error", handle ):
main.log.error( "Error in create host" + str( hostname ) )
main.log.error( handle )
@@ -269,20 +269,20 @@
main.log.info( "Create " + str( hostname ) + " sucess" )
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.cleanAndExit()
- def createHostport(self, hostname="host1", hostport="host1-eth0", ovsport="port1", hostportmac="000000000001" ):
- command = "sudo ip link add " + str(hostport) +" type veth peer name " + str(ovsport)
- command += ";" + "sudo ip link set " + str(hostport) + " up"
- command += ";" + "sudo ip link set " + str(ovsport) + " up"
- command += ";" +" sudo ifconfig " + str(hostport) + " hw ether " + str(hostportmac)
- command += ";" +" sudo ip link set " + str(hostport) + " netns " + str(hostname)
+ def createHostport( self, hostname="host1", hostport="host1-eth0", ovsport="port1", hostportmac="000000000001" ):
+ command = "sudo ip link add " + str( hostport ) + " type veth peer name " + str( ovsport )
+ command += ";" + "sudo ip link set " + str( hostport ) + " up"
+ command += ";" + "sudo ip link set " + str( ovsport ) + " up"
+ command += ";" + " sudo ifconfig " + str( hostport ) + " hw ether " + str( hostportmac )
+ command += ";" + " sudo ip link set " + str( hostport ) + " netns " + str( hostname )
try:
handle = self.execute(
cmd=command,
- timeout=10)
+ timeout=10 )
if re.search( "Error", handle ):
main.log.error( "Error in create host port " + str( hostport ) + " on " + str( hostname ) )
main.log.error( handle )
@@ -291,40 +291,40 @@
main.log.info( "Create host port " + str( hostport ) + " on " + str( hostname ) + " sucess" )
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.cleanAndExit()
- def addPortToOvs(self, ifaceId, attachedMac, vmuuid, port="port1", ovsname="br-int" ):
- command = "sudo ovs-vsctl add-port " + str(ovsname) +" " + str(port)
+ def addPortToOvs( self, ifaceId, attachedMac, vmuuid, port="port1", ovsname="br-int" ):
+ command = "sudo ovs-vsctl add-port " + str( ovsname ) + " " + str( port )
if ifaceId:
- command += " -- set Interface " + str(port) + " external-ids:iface-id=" + str(ifaceId) + " external-ids:iface-status=active"
+ command += " -- set Interface " + str( port ) + " external-ids:iface-id=" + str( ifaceId ) + " external-ids:iface-status=active"
if attachedMac:
- command += " external-ids:attached-mac=" + str(attachedMac)
+ command += " external-ids:attached-mac=" + str( attachedMac )
if vmuuid:
- command += " external-ids:vm-uuid=" + str(vmuuid)
+ command += " external-ids:vm-uuid=" + str( vmuuid )
try:
handle = self.execute(
cmd=command,
- timeout=10)
+ timeout=10 )
if re.search( "Error", handle ):
- main.log.error( "Error in add port " + str(port) + " to ovs " + str( ovsname ) )
+ main.log.error( "Error in add port " + str( port ) + " to ovs " + str( ovsname ) )
main.log.error( handle )
return main.FALSE
else:
- main.log.info( "Add port " + str(port) + " to ovs " + str( ovsname ) + " sucess" )
+ main.log.info( "Add port " + str( port ) + " to ovs " + str( ovsname ) + " sucess" )
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.cleanAndExit()
- def setHostportIp(self, ip, hostname="host1", hostport1="host1-eth0" ):
- command = "sudo ip netns exec " + str(hostname) +" ifconfig " + str(hostport1) + " " + str(ip)
+ def setHostportIp( self, ip, hostname="host1", hostport1="host1-eth0" ):
+ command = "sudo ip netns exec " + str( hostname ) + " ifconfig " + str( hostport1 ) + " " + str( ip )
try:
handle = self.execute(
cmd=command,
- timeout=10)
+ timeout=10 )
if re.search( "Error", handle ):
main.log.error( "Error in set host ip for " + str( hostport1 ) + " on host " + str( hostname ) )
main.log.error( handle )
@@ -333,32 +333,32 @@
main.log.info( "Set host ip for " + str( hostport1 ) + " on host " + str( hostname ) + " sucess" )
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.cleanAndExit()
- def hostPing(self, src, target, hostname="host1" ):
+ def hostPing( self, src, target, hostname="host1" ):
if src:
- command = "sudo ip netns exec " + str( hostname ) +" ping -c 1 -S " +\
- str( src ) + " " + str( target )
+ command = "sudo ip netns exec " + str( hostname ) + " ping -c 1 -S " +\
+ str( src ) + " " + str( target )
else:
- command = "sudo ip netns exec " + str( hostname ) +" ping -c 1 " + str( target )
+ command = "sudo ip netns exec " + str( hostname ) + " ping -c 1 " + str( target )
try:
- for i in range(1,5):
+ for i in range( 1, 5 ):
handle = self.execute(
cmd=command,
- timeout=10)
- if re.search(',\s0\%\spacket\sloss', handle):
- main.log.info(self.name + ": no packets lost, host is reachable")
+ timeout=10 )
+ if re.search( ',\s0\%\spacket\sloss', handle ):
+ main.log.info( self.name + ": no packets lost, host is reachable" )
return main.TRUE
break
- time.sleep(5)
+ time.sleep( 5 )
else:
- main.log.info(self.name + ": packets lost, host is unreachable")
+ main.log.info( self.name + ": packets lost, host is unreachable" )
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.cleanAndExit()
def delBr( self, sw ):
@@ -368,7 +368,7 @@
Return:
Delete sucess return main.TRUE or main.FALSE on delete failed
"""
- command= "sudo ovs-vsctl del-br " + str( sw )
+ command = "sudo ovs-vsctl del-br " + str( sw )
try:
response = self.execute(
cmd=command,
@@ -389,7 +389,7 @@
Return:
Delete sucess return main.TRUE or main.FALSE on delete failed
"""
- command= "sudo ip netns delete " + str( hostname )
+ command = "sudo ip netns delete " + str( hostname )
try:
response = self.execute(
cmd=command,
diff --git a/TestON/drivers/common/cli/quaggaclidriver.py b/TestON/drivers/common/cli/quaggaclidriver.py
index e1cbeef..01905c2 100644
--- a/TestON/drivers/common/cli/quaggaclidriver.py
+++ b/TestON/drivers/common/cli/quaggaclidriver.py
@@ -58,7 +58,7 @@
ip_address="1.1.1.1",
port=self.port,
pwd=self.pwd )
- #main.log.info( "connect parameters:" + str( self.user_name ) + ";"
+ # main.log.info( "connect parameters:" + str( self.user_name ) + ";"
# + str( self.ip_address ) + ";" + str( self.port )
# + ";" + str(self.pwd ) )
@@ -208,7 +208,7 @@
routesJsonObj = json.loads( getRoutesResult )
allRoutesActual = []
- for route in routesJsonObj['routes4']:
+ for route in routesJsonObj[ 'routes4' ]:
if 'prefix' in route:
if route[ 'prefix' ] == '172.16.10.0/24':
continue
@@ -221,7 +221,7 @@
routesJsonObj = json.loads( getRoutesResult )
allRoutesActual = []
- for route in routesJsonObj['routes4']:
+ for route in routesJsonObj[ 'routes4' ]:
if route[ 'prefix' ] == '172.16.10.0/24':
continue
allRoutesActual.append(
@@ -237,10 +237,10 @@
intentsJsonObj = json.loads( getIntentsResult )
for intent in intentsJsonObj:
- #if intent[ 'appId' ] != "org.onosproject.sdnip":
+ # if intent[ 'appId' ] != "org.onosproject.sdnip":
# continue
if intent[ 'type' ] == "MultiPointToSinglePointIntent" \
- and intent[ 'state' ] == 'INSTALLED':
+ and intent[ 'state' ] == 'INSTALLED':
egress = str( intent[ 'egress' ][ 'device' ] ) + ":" \
+ str( intent[ 'egress' ][ 'port' ] )
ingress = []
@@ -266,7 +266,7 @@
num = 0
for intent in intentsJsonObj:
if intent[ 'type' ] == "MultiPointToSinglePointIntent" \
- and intent[ 'state' ] == 'INSTALLED':
+ and intent[ 'state' ] == 'INSTALLED':
num = num + 1
return num
@@ -276,7 +276,7 @@
num = 0
for intent in intentsJsonObj:
if intent[ 'type' ] == "PointToPointIntent" \
- and intent[ 'state' ] == 'INSTALLED':
+ and intent[ 'state' ] == 'INSTALLED':
num = num + 1
return num
@@ -288,10 +288,10 @@
intentsJsonObj = json.loads( getIntentsResult )
for intent in intentsJsonObj:
- #if intent[ 'appId' ] != "org.onosproject.sdnip":
+ # if intent[ 'appId' ] != "org.onosproject.sdnip":
# continue
if intent[ 'type' ] == "PointToPointIntent" \
- and "protocol=6" in str( intent[ 'selector' ] ):
+ and "protocol=6" in str( intent[ 'selector' ] ):
ingress = str( intent[ 'ingress' ][ 'device' ] ) + ":" \
+ str( intent[ 'ingress' ][ 'port' ] )
egress = str( intent[ 'egress' ][ 'device' ] ) + ":" + \
@@ -325,15 +325,15 @@
# find out the BGP speaker IP address for this BGP peer
bgpSpeakerIpAddress = ""
for interfaceAddress in \
- sdnipData[ 'bgpSpeakers' ][ 0 ][ 'interfaceAddresses' ]:
+ sdnipData[ 'bgpSpeakers' ][ 0 ][ 'interfaceAddresses' ]:
# if eq( interfaceAddress[ 'interfaceDpid' ],sdnipData[
# 'bgpSpeakers' ][ 0 ][ 'attachmentDpid' ] ) and eq(
# interfaceAddress[ 'interfacePort' ], sdnipData[ 'bgpSpeakers'
# ][ 0 ][ 'attachmentPort' ] ):
if eq( interfaceAddress[ 'interfaceDpid' ],
peer[ 'attachmentDpid' ] ) \
- and eq( interfaceAddress[ 'interfacePort' ],
- peer[ 'attachmentPort' ] ):
+ and eq( interfaceAddress[ 'interfacePort' ],
+ peer[ 'attachmentPort' ] ):
bgpSpeakerIpAddress = interfaceAddress[ 'ipAddress' ]
break
else:
@@ -345,7 +345,7 @@
+ "IPV4_DST{ip=" + peer[ 'ipAddress' ] + "/32}," \
+ "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, \
TCP_DST{tcpPort=179}"
- selector = selectorStr.replace( " ", "" ).replace("[", "" )\
+ selector = selectorStr.replace( " ", "" ).replace( "[", "" )\
.replace( "]", "" ).split( "," )
intent = bgpSpeakerAttachmentPoint + "/" + \
bgpPeerAttachmentPoint + "/" + str( sorted( selector ) )
@@ -355,7 +355,7 @@
+ "IPV4_DST{ip=" + peer[ 'ipAddress' ] + "/32}," \
+ "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, \
TCP_SRC{tcpPort=179}"
- selector = selectorStr.replace( " ", "" ).replace("[", "" )\
+ selector = selectorStr.replace( " ", "" ).replace( "[", "" )\
.replace( "]", "" ).split( "," )
intent = bgpSpeakerAttachmentPoint + "/" \
+ bgpPeerAttachmentPoint + "/" + str( sorted( selector ) )
@@ -367,7 +367,7 @@
+ "IPV4_DST{ip=" + bgpSpeakerIpAddress + "/32}," \
+ "IP_PROTO{protocol=6}, ETH_TYPE{ethType=800}, \
TCP_DST{tcpPort=179}"
- selector = selectorStr.replace( " ", "" ).replace("[", "" )\
+ selector = selectorStr.replace( " ", "" ).replace( "[", "" )\
.replace( "]", "" ).split( "," )
intent = bgpPeerAttachmentPoint + "/" \
+ bgpSpeakerAttachmentPoint + "/" + str( sorted( selector ) )
@@ -400,23 +400,23 @@
chunk_size = 20
- if len(routes) > chunk_size:
- num_iter = (int) (len(routes) / chunk_size)
+ if len( routes ) > chunk_size:
+ num_iter = ( int )( len( routes ) / chunk_size )
else:
- num_iter = 1;
+ num_iter = 1
total = 0
- for n in range( 0, num_iter + 1):
+ for n in range( 0, num_iter + 1 ):
routeCmd = ""
- if (len( routes ) - (n * chunk_size)) >= chunk_size:
- m = (n + 1) * chunk_size
+ if ( len( routes ) - ( n * chunk_size ) ) >= chunk_size:
+ m = ( n + 1 ) * chunk_size
else:
m = len( routes )
for i in range( n * chunk_size, m ):
routeCmd = routeCmd + "network " + routes[ i ] + "\n"
total = total + 1
- main.log.info(routeCmd)
+ main.log.info( routeCmd )
try:
self.handle.sendline( routeCmd )
self.handle.expect( "bgpd", timeout=5 )
@@ -425,8 +425,8 @@
self.disconnect()
# waitTimer = 1.00 / routeRate
- main.log.info("Total routes so far " + ((str) (total)) + " wait for 0 sec")
- #time.sleep( 1 )
+ main.log.info( "Total routes so far " + ( str( total ) ) + " wait for 0 sec" )
+ # time.sleep( 1 )
if routesAdded == len( routes ):
main.log.info( "Finished adding routes" )
return main.TRUE
@@ -489,7 +489,6 @@
main.log.info( "NO HANDLE" )
return main.FALSE
-
# Please use the generateRoutes plus addRoutes instead of this one!
def addRoute( self, net, numRoutes, routeRate ):
try:
@@ -613,7 +612,7 @@
count = 0
while True:
i = child.expect( [ '17\d\.\d{1,3}\.\d{1,3}\.\d{1,3}',
- 'CLI#', pexpect.TIMEOUT ] )
+ 'CLI#', pexpect.TIMEOUT ] )
if i == 0:
count = count + 1
elif i == 1:
@@ -700,4 +699,3 @@
main.log.error( "Connection failed to the host" )
response = main.FALSE
return response
-
diff --git a/TestON/drivers/common/cli/tool/dpctlclidriver.py b/TestON/drivers/common/cli/tool/dpctlclidriver.py
index 0dd15ee..6375c0f 100644
--- a/TestON/drivers/common/cli/tool/dpctlclidriver.py
+++ b/TestON/drivers/common/cli/tool/dpctlclidriver.py
@@ -1,4 +1,4 @@
-#/usr/bin/env python
+# /usr/bin/env python
"""
Created on 26-Nov-2012
Copyright 2012 Open Networking Foundation (ONF)
@@ -50,9 +50,9 @@
self.handle = super(
DpctlCliDriver, self ).connect( user_name=self.user_name,
- ip_address=self.ip_address,
- port=None,
- pwd=self.pwd )
+ ip_address=self.ip_address,
+ port=None,
+ pwd=self.pwd )
if self.handle:
main.log.info( "Connected to the host" )
return main.TRUE
@@ -74,7 +74,7 @@
"INPORT",
"ACTION",
"TIMEOUT" ],
- **flowParameters )
+ **flowParameters )
cmd = "dpctl add-flow tcp:"
tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
@@ -258,7 +258,7 @@
"TCPIP",
"TCPPORT",
"STRING" ],
- **flowParameters )
+ **flowParameters )
tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
tcpPort = args[ "TCPPORT" ] if args[
@@ -286,7 +286,7 @@
"TCPIP",
"TCPPORT",
"STRING" ],
- **flowParameters )
+ **flowParameters )
tcpIP = args[ "TCPIP" ] if args[ "TCPIP" ] is not None else "127.0.0.1"
tcpPort = args[ "TCPPORT" ] if args[
@@ -306,4 +306,3 @@
if __name__ != "__main__":
import sys
sys.modules[ __name__ ] = DpctlCliDriver()
-
diff --git a/TestON/drivers/common/clidriver.py b/TestON/drivers/common/clidriver.py
index 086ae0a..0f3140a 100644
--- a/TestON/drivers/common/clidriver.py
+++ b/TestON/drivers/common/clidriver.py
@@ -10,7 +10,7 @@
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
@@ -34,10 +34,10 @@
def __init__( self ):
super( CLI, self ).__init__()
- def checkPrompt(self):
+ def checkPrompt( self ):
for key in self.options:
- if key == "prompt" and self.options['prompt'] is not None:
- self.prompt = self.options['prompt']
+ if key == "prompt" and self.options[ 'prompt' ] is not None:
+ self.prompt = self.options[ 'prompt' ]
break
def connect( self, **connectargs ):
@@ -100,7 +100,7 @@
else:
main.log.info( "Server asked for password, but none was "
"given in the .topo file. Trying "
- "no password.")
+ "no password." )
self.pwd = ""
self.handle.sendline( self.pwd )
j = self.handle.expect( [
@@ -181,8 +181,8 @@
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) +
+ main.log.info( "Executed :" + str( cmd ) +
+ " \t\t Expected Prompt '" + str( expectPrompt ) +
"' Found" )
elif index == 1:
self.LASTRSP = self.LASTRSP + self.handle.before
@@ -397,7 +397,7 @@
else:
main.log.info( "Server asked for password, but none was "
"given in the .topo file. Trying "
- "no password.")
+ "no password." )
pwd = ""
handle.sendline( pwd )
j = handle.expect( [ self.prompt,
@@ -479,16 +479,16 @@
assert "cannot access" not in output
assert "command not found" not in output
main.log.debug( output )
- lines = [ line for line in output.split('\r\n') ]
+ lines = [ line for line in output.split( '\r\n' ) ]
retValue = True
if ignoreRoot:
lastIndex = -2
else:
lastIndex = -1
- for line in lines[1:lastIndex]:
+ for line in lines[ 1:lastIndex ]:
parsed = line.split()
- sizeMatch = parsed[0]
- folder = parsed[1]
+ sizeMatch = parsed[ 0 ]
+ folder = parsed[ 1 ]
match = re.search( sizeRe, sizeMatch )
num = match.group( 'number' )
unitMatch = match.group( 'unit' )
diff --git a/TestON/drivers/component.py b/TestON/drivers/component.py
index 968306e..c3d3297 100644
--- a/TestON/drivers/component.py
+++ b/TestON/drivers/component.py
@@ -117,4 +117,3 @@
if __name__ != "__main__":
import sys
sys.modules[ __name__ ] = Component()
-