blob: 0a1d25f5e18a4de38a05c289495386647a8ea779 [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001#!/usr/bin/env python
Jon Hall7eb38402015-01-08 17:19:54 -08002"""
adminbae64d82013-08-01 10:50:15 -07003Created on 26-Oct-2012
4
Jon Hallbe6dfc42015-01-12 17:37:25 -08005author: Anil Kumar ( anilkumar.s@paxterrasolutions.com )
adminbae64d82013-08-01 10:50:15 -07006
7
Jon Hall7eb38402015-01-08 17:19:54 -08008TestON is free software: you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation, either version 2 of the License, or
11( at your option ) any later version.
adminbae64d82013-08-01 10:50:15 -070012
Jon Hall7eb38402015-01-08 17:19:54 -080013TestON is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
adminbae64d82013-08-01 10:50:15 -070017
Jon Hall7eb38402015-01-08 17:19:54 -080018You should have received a copy of the GNU General Public License
19along with TestON. If not, see <http://www.gnu.org/licenses/>.
adminbae64d82013-08-01 10:50:15 -070020
Jon Hallbe6dfc42015-01-12 17:37:25 -080021MininetCliDriver is the basic driver which will handle the Mininet functions
22
23Some functions rely on a modified version of Mininet. These functions
24should all be noted in the comments. To get this MN version run these commands
25from within your Mininet folder:
Jon Hall272a4db2015-01-12 17:43:48 -080026 git remote add jhall11 https://github.com/jhall11/mininet.git
Jon Hallbe6dfc42015-01-12 17:37:25 -080027 git fetch jhall11
Jon Hall272a4db2015-01-12 17:43:48 -080028 git checkout -b dynamic_topo remotes/jhall11/dynamic_topo
Jon Hallbe6dfc42015-01-12 17:37:25 -080029 git pull
30
Jon Hall272a4db2015-01-12 17:43:48 -080031
32 Note that you may need to run 'sudo make develop' if your mnexec.c file
Jon Hallbe6dfc42015-01-12 17:37:25 -080033changed when switching branches."""
adminbae64d82013-08-01 10:50:15 -070034import pexpect
adminbae64d82013-08-01 10:50:15 -070035import re
36import sys
kelvin-onlabfa6ada82015-06-11 13:06:24 -070037import types
kelvin-onlaba4074292015-07-09 15:19:49 -070038import os
Jon Hall1ccf82c2014-10-15 14:55:16 -040039from math import pow
adminbae64d82013-08-01 10:50:15 -070040from drivers.common.cli.emulatordriver import Emulator
adminbae64d82013-08-01 10:50:15 -070041
Jon Hall7eb38402015-01-08 17:19:54 -080042
kelvin-onlab50907142015-04-01 13:37:45 -070043class MininetCliDriver( Emulator ):
Jon Hall7eb38402015-01-08 17:19:54 -080044
45 """
46 MininetCliDriver is the basic driver which will handle
47 the Mininet functions"""
48 def __init__( self ):
49 super( Emulator, self ).__init__()
adminbae64d82013-08-01 10:50:15 -070050 self.handle = self
Jon Hallefbd9792015-03-05 16:11:36 -080051 self.name = None
kelvin-onlabd9e23de2015-08-06 10:34:44 -070052 self.home = None
Jon Hall7eb38402015-01-08 17:19:54 -080053 self.wrapped = sys.modules[ __name__ ]
adminbae64d82013-08-01 10:50:15 -070054 self.flag = 0
Jon Hall892818c2015-10-20 17:58:34 -070055 # TODO: Refactor driver to use these everywhere
56 self.mnPrompt = "mininet>"
57 self.hostPrompt = "~#"
58 self.bashPrompt = "\$"
59 self.scapyPrompt = ">>>"
adminbae64d82013-08-01 10:50:15 -070060
Jon Hall7eb38402015-01-08 17:19:54 -080061 def connect( self, **connectargs ):
62 """
63 Here the main is the TestON instance after creating
64 all the log handles."""
kelvin-onlaba1484582015-02-02 15:46:20 -080065 try:
66 for key in connectargs:
67 vars( self )[ key ] = connectargs[ key ]
kelvin-onlabd9e23de2015-08-06 10:34:44 -070068 self.home = "~/mininet"
kelvin-onlaba1484582015-02-02 15:46:20 -080069 self.name = self.options[ 'name' ]
kelvin-onlabd9e23de2015-08-06 10:34:44 -070070 for key in self.options:
71 if key == "home":
72 self.home = self.options[ 'home' ]
73 break
74 if self.home is None or self.home == "":
75 self.home = "~/mininet"
kelvin-onlaba4074292015-07-09 15:19:49 -070076
77 try:
Jon Hall892818c2015-10-20 17:58:34 -070078 if os.getenv( str( self.ip_address ) ) is not None:
kelvin-onlaba4074292015-07-09 15:19:49 -070079 self.ip_address = os.getenv( str( self.ip_address ) )
80 else:
81 main.log.info( self.name +
82 ": Trying to connect to " +
83 self.ip_address )
84
85 except KeyError:
86 main.log.info( "Invalid host name," +
87 " connecting to local host instead" )
88 self.ip_address = 'localhost'
89 except Exception as inst:
90 main.log.error( "Uncaught exception: " + str( inst ) )
91
kelvin-onlaba1484582015-02-02 15:46:20 -080092 self.handle = super(
kelvin-onlab50907142015-04-01 13:37:45 -070093 MininetCliDriver,
kelvin-onlaba1484582015-02-02 15:46:20 -080094 self ).connect(
95 user_name=self.user_name,
96 ip_address=self.ip_address,
97 port=None,
98 pwd=self.pwd )
Jon Hallfbc828e2015-01-06 17:30:19 -080099
kelvin-onlaba1484582015-02-02 15:46:20 -0800100 if self.handle:
Jon Hallefbd9792015-03-05 16:11:36 -0800101 main.log.info( "Connection successful to the host " +
102 self.user_name +
103 "@" +
104 self.ip_address )
kelvin-onlaba1484582015-02-02 15:46:20 -0800105 return main.TRUE
106 else:
107 main.log.error( "Connection failed to the host " +
Jon Hallefbd9792015-03-05 16:11:36 -0800108 self.user_name +
109 "@" +
110 self.ip_address )
Jon Hallfebb1c72015-03-05 13:30:09 -0800111 main.log.error( "Failed to connect to the Mininet CLI" )
kelvin-onlaba1484582015-02-02 15:46:20 -0800112 return main.FALSE
113 except pexpect.EOF:
114 main.log.error( self.name + ": EOF exception found" )
115 main.log.error( self.name + ": " + self.handle.before )
116 main.cleanup()
117 main.exit()
Jon Hallfebb1c72015-03-05 13:30:09 -0800118 except Exception:
119 main.log.exception( self.name + ": Uncaught exception!" )
kelvin-onlaba1484582015-02-02 15:46:20 -0800120 main.cleanup()
121 main.exit()
122
kelvin-onlab10e8d392015-06-03 13:53:45 -0700123 def startNet( self, topoFile='', args='', mnCmd='', timeout=120 ):
kelvin-onlab00ac67b2015-02-04 09:52:02 -0800124 """
kelvin-onlabf512e942015-06-08 19:42:59 -0700125 Description:
126 Starts Mininet accepts a topology(.py) file and/or an optional
127 argument, to start the mininet, as a parameter.
128 Can also send regular mininet command to load up desired topology.
129 Eg. Pass in a string 'sudo mn --topo=tree,3,3' to mnCmd
130 Options:
131 topoFile = file path for topology file (.py)
132 args = extra option added when starting the topology from the file
133 mnCmd = Mininet command use to start topology
134 Returns:
135 main.TRUE if the mininet starts successfully, main.FALSE
136 otherwise
kelvin-onlab00ac67b2015-02-04 09:52:02 -0800137 """
Jon Hall7eb38402015-01-08 17:19:54 -0800138 if self.handle:
Jon Hall689d8e42015-04-03 13:59:24 -0700139 # make sure old networks are cleaned up
140 main.log.info( self.name +
141 ": Clearing any residual state or processes" )
Jon Hall7eb38402015-01-08 17:19:54 -0800142 self.handle.sendline( "sudo mn -c" )
143 i = self.handle.expect( [ 'password\sfor\s',
144 'Cleanup\scomplete',
145 pexpect.EOF,
146 pexpect.TIMEOUT ],
kelvin-onlaba1484582015-02-02 15:46:20 -0800147 timeout )
Jon Hall7eb38402015-01-08 17:19:54 -0800148 if i == 0:
Jon Hall689d8e42015-04-03 13:59:24 -0700149 # Sudo asking for password
Jon Hall7eb38402015-01-08 17:19:54 -0800150 main.log.info( self.name + ": Sending sudo password" )
151 self.handle.sendline( self.pwd )
Jon Hallefbd9792015-03-05 16:11:36 -0800152 i = self.handle.expect( [ '%s:' % self.user,
Jon Hall7eb38402015-01-08 17:19:54 -0800153 '\$',
154 pexpect.EOF,
155 pexpect.TIMEOUT ],
kelvin-onlaba1484582015-02-02 15:46:20 -0800156 timeout )
Jon Hall7eb38402015-01-08 17:19:54 -0800157 if i == 1:
158 main.log.info( self.name + ": Clean" )
159 elif i == 2:
160 main.log.error( self.name + ": Connection terminated" )
161 elif i == 3: # timeout
Jon Hall689d8e42015-04-03 13:59:24 -0700162 main.log.error( self.name + ": Something while cleaning " +
163 "Mininet took too long... " )
164 # Craft the string to start mininet
165 cmdString = "sudo "
kelvin-onlab10e8d392015-06-03 13:53:45 -0700166 if not mnCmd:
167 if topoFile is None or topoFile == '': # If no file is given
168 main.log.info( self.name + ": building fresh Mininet" )
169 cmdString += "mn "
170 if args is None or args == '':
171 # If no args given, use args from .topo file
172 args = self.options[ 'arg1' ] +\
Jon Halld80cc142015-07-06 13:36:05 -0700173 " " + self.options[ 'arg2' ] +\
174 " --mac --controller " +\
175 self.options[ 'controller' ] + " " +\
176 self.options[ 'arg3' ]
kelvin-onlab10e8d392015-06-03 13:53:45 -0700177 else: # else only use given args
178 pass
179 # TODO: allow use of topo args and method args?
180 else: # Use given topology file
Jon Halld80cc142015-07-06 13:36:05 -0700181 main.log.info(
182 "Starting Mininet from topo file " +
183 topoFile )
Flavio Castrocc38a542016-03-03 13:15:46 -0800184 cmdString += "-E python " + topoFile + " "
kelvin-onlab10e8d392015-06-03 13:53:45 -0700185 if args is None:
186 args = ''
187 # TODO: allow use of args from .topo file?
188 cmdString += args
189 else:
190 main.log.info( "Starting Mininet topology using '" + mnCmd +
191 "' command" )
192 cmdString += mnCmd
Jon Hall689d8e42015-04-03 13:59:24 -0700193 # Send the command and check if network started
194 self.handle.sendline( "" )
195 self.handle.expect( '\$' )
196 main.log.info( "Sending '" + cmdString + "' to " + self.name )
197 self.handle.sendline( cmdString )
198 while True:
Jon Hall7eb38402015-01-08 17:19:54 -0800199 i = self.handle.expect( [ 'mininet>',
Jon Hall689d8e42015-04-03 13:59:24 -0700200 'Exception',
201 '\*\*\*',
Jon Hallefbd9792015-03-05 16:11:36 -0800202 pexpect.EOF,
203 pexpect.TIMEOUT ],
Jon Hall689d8e42015-04-03 13:59:24 -0700204 timeout )
kelvin-onlabef0cc1c2015-02-09 15:20:26 -0800205 if i == 0:
Jon Hall689d8e42015-04-03 13:59:24 -0700206 main.log.info( self.name + ": Mininet built" )
kelvin-onlabef0cc1c2015-02-09 15:20:26 -0800207 return main.TRUE
kelvin-onlabec228b82015-02-09 15:45:55 -0800208 elif i == 1:
Jon Hall689d8e42015-04-03 13:59:24 -0700209 response = str( self.handle.before +
210 self.handle.after )
211 self.handle.expect( '\$' )
212 response += str( self.handle.before +
Jon Halld80cc142015-07-06 13:36:05 -0700213 self.handle.after )
Jon Hall689d8e42015-04-03 13:59:24 -0700214 main.log.error(
215 self.name +
216 ": Launching Mininet failed: " + response )
217 return main.FALSE
218 elif i == 2:
219 self.handle.expect( [ "\n",
220 pexpect.EOF,
221 pexpect.TIMEOUT ],
222 timeout )
223 main.log.info( self.handle.before )
224 elif i == 3:
kelvin-onlabef0cc1c2015-02-09 15:20:26 -0800225 main.log.error( self.name + ": Connection timeout" )
226 return main.FALSE
Jon Hall689d8e42015-04-03 13:59:24 -0700227 elif i == 4: # timeout
kelvin-onlabef0cc1c2015-02-09 15:20:26 -0800228 main.log.error(
229 self.name +
230 ": Something took too long... " )
231 return main.FALSE
Jon Hall689d8e42015-04-03 13:59:24 -0700232 # Why did we hit this part?
233 main.log.error( "startNet did not return correctly" )
234 return main.FASLE
Jon Hall7eb38402015-01-08 17:19:54 -0800235 else: # if no handle
Jon Hall689d8e42015-04-03 13:59:24 -0700236 main.log.error( self.name + ": Connection failed to the host " +
237 self.user_name + "@" + self.ip_address )
Jon Hall7eb38402015-01-08 17:19:54 -0800238 main.log.error( self.name + ": Failed to connect to the Mininet" )
adminbae64d82013-08-01 10:50:15 -0700239 return main.FALSE
Jon Hallfbc828e2015-01-06 17:30:19 -0800240
kelvin-onlabfccaafa2015-01-20 13:50:44 -0800241 def numSwitchesNlinks( self, topoType, depth, fanout ):
Jon Hall1ccf82c2014-10-15 14:55:16 -0400242 if topoType == 'tree':
Jon Hall7eb38402015-01-08 17:19:54 -0800243 # In tree topology, if fanout arg is not given, by default it is 2
244 if fanout is None:
Jon Hall1ccf82c2014-10-15 14:55:16 -0400245 fanout = 2
246 k = 0
Jon Hall38481722014-11-04 16:50:05 -0500247 count = 0
Jon Hall7eb38402015-01-08 17:19:54 -0800248 while( k <= depth - 1 ):
249 count = count + pow( fanout, k )
250 k = k + 1
kelvin-onlabd3b64892015-01-20 13:26:24 -0800251 numSwitches = count
Jon Hall7eb38402015-01-08 17:19:54 -0800252 while( k <= depth - 2 ):
253 # depth-2 gives you only core links and not considering
254 # edge links as seen by ONOS. If all the links including
255 # edge links are required, do depth-1
256 count = count + pow( fanout, k )
257 k = k + 1
kelvin-onlabd3b64892015-01-20 13:26:24 -0800258 numLinks = count * fanout
Jon Hall7eb38402015-01-08 17:19:54 -0800259 # print "num_switches for %s(%d,%d) = %d and links=%d" %(
kelvin-onlabd3b64892015-01-20 13:26:24 -0800260 # topoType,depth,fanout,numSwitches,numLinks )
Jon Hallfbc828e2015-01-06 17:30:19 -0800261
Jon Hall7eb38402015-01-08 17:19:54 -0800262 elif topoType == 'linear':
kelvin-onlabd3b64892015-01-20 13:26:24 -0800263 # In linear topology, if fanout or numHostsPerSw is not given,
Jon Hall7eb38402015-01-08 17:19:54 -0800264 # by default it is 1
265 if fanout is None:
Jon Hall1ccf82c2014-10-15 14:55:16 -0400266 fanout = 1
kelvin-onlabd3b64892015-01-20 13:26:24 -0800267 numSwitches = depth
268 numHostsPerSw = fanout
269 totalNumHosts = numSwitches * numHostsPerSw
270 numLinks = totalNumHosts + ( numSwitches - 1 )
Jon Hall7eb38402015-01-08 17:19:54 -0800271 print "num_switches for %s(%d,%d) = %d and links=%d" %\
kelvin-onlabd3b64892015-01-20 13:26:24 -0800272 ( topoType, depth, fanout, numSwitches, numLinks )
Jon Hallefbd9792015-03-05 16:11:36 -0800273 topoDict = { "num_switches": int( numSwitches ),
274 "num_corelinks": int( numLinks ) }
Jon Hall1ccf82c2014-10-15 14:55:16 -0400275 return topoDict
276
kelvin-onlabd3b64892015-01-20 13:26:24 -0800277 def calculateSwAndLinks( self ):
Jon Hall689d8e42015-04-03 13:59:24 -0700278 """
279 Calculate the number of switches and links in a topo."""
280 # TODO: combine this function and numSwitchesNlinks
281 argList = self.options[ 'arg1' ].split( "," )
282 topoArgList = argList[ 0 ].split( " " )
283 argList = map( int, argList[ 1: ] )
284 topoArgList = topoArgList[ 1: ] + argList
285
286 topoDict = self.numSwitchesNlinks( *topoArgList )
Jon Hall1ccf82c2014-10-15 14:55:16 -0400287 return topoDict
288
GlennRCf07c44a2015-09-18 13:33:46 -0700289 def pingall( self, protocol="IPv4", timeout=300, shortCircuit=False, acceptableFailed=0 ):
Jon Hall7eb38402015-01-08 17:19:54 -0800290 """
291 Verifies the reachability of the hosts using pingall command.
292 Optional parameter timeout allows you to specify how long to
293 wait for pingall to complete
kelvin-onlabfbcd82f2015-04-02 12:06:00 -0700294 Optional:
Jon Halld80cc142015-07-06 13:36:05 -0700295 timeout( seconds ) - How long to wait before breaking the pingall
kelvin-onlabfbcd82f2015-04-02 12:06:00 -0700296 shortCircuit - Break the pingall based on the number of failed hosts
kelvin-onlabc44f0192015-04-02 22:08:41 -0700297 ping
298 acceptableFailed - Set the number of acceptable failed pings for the
299 function to still return main.TRUE
Jon Hall7eb38402015-01-08 17:19:54 -0800300 Returns:
301 main.TRUE if pingall completes with no pings dropped
Jon Hall390696c2015-05-05 17:13:41 -0700302 otherwise main.FALSE
303 """
304 import time
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700305 try:
Jon Hallfb760a02015-04-13 15:35:03 -0700306 timeout = int( timeout )
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700307 if self.handle:
308 main.log.info(
309 self.name +
310 ": Checking reachabilty to the hosts using pingall" )
311 response = ""
312 failedPings = 0
313 returnValue = main.TRUE
GlennRCf07c44a2015-09-18 13:33:46 -0700314 cmd = "pingall"
315 if protocol == "IPv6":
316 cmd = "py net.pingAll6()"
317 self.handle.sendline( cmd )
Jon Hall390696c2015-05-05 17:13:41 -0700318 startTime = time.time()
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700319 while True:
Jon Halld80cc142015-07-06 13:36:05 -0700320 i = self.handle.expect( [ "mininet>", "X",
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700321 pexpect.EOF,
322 pexpect.TIMEOUT ],
Jon Halld80cc142015-07-06 13:36:05 -0700323 timeout )
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700324 if i == 0:
Jon Halld80cc142015-07-06 13:36:05 -0700325 main.log.info( self.name + ": pingall finished" )
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700326 response += self.handle.before
327 break
328 elif i == 1:
329 response += self.handle.before + self.handle.after
330 failedPings = failedPings + 1
kelvin-onlabd26a3742015-04-06 15:31:16 -0700331 if failedPings > acceptableFailed:
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700332 returnValue = main.FALSE
333 if shortCircuit:
334 main.log.error( self.name +
335 ": Aborting pingall - "
336 + str( failedPings ) +
337 " pings failed" )
338 break
Jon Hall390696c2015-05-05 17:13:41 -0700339 if ( time.time() - startTime ) > timeout:
340 returnValue = main.FALSE
341 main.log.error( self.name +
342 ": Aborting pingall - " +
343 "Function took too long " )
344 break
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700345 elif i == 2:
346 main.log.error( self.name +
347 ": EOF exception found" )
348 main.log.error( self.name + ": " +
349 self.handle.before )
350 main.cleanup()
351 main.exit()
352 elif i == 3:
353 response += self.handle.before
354 main.log.error( self.name +
355 ": TIMEOUT exception found" )
356 main.log.error( self.name +
357 ": " +
358 str( response ) )
359 # NOTE: Send ctrl-c to make sure pingall is done
You Wangaf684312016-01-27 14:44:38 -0800360 self.handle.send( "\x03" )
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700361 self.handle.expect( "Interrupt" )
362 self.handle.expect( "mininet>" )
363 break
364 pattern = "Results\:"
365 main.log.info( "Pingall output: " + str( response ) )
366 if re.search( pattern, response ):
367 main.log.info( self.name + ": Pingall finished with "
368 + str( failedPings ) + " failed pings" )
369 return returnValue
370 else:
kelvin-onlabc44f0192015-04-02 22:08:41 -0700371 # NOTE: Send ctrl-c to make sure pingall is done
You Wangaf684312016-01-27 14:44:38 -0800372 self.handle.send( "\x03" )
kelvin-onlabc44f0192015-04-02 22:08:41 -0700373 self.handle.expect( "Interrupt" )
kelvin-onlabc44f0192015-04-02 22:08:41 -0700374 self.handle.expect( "mininet>" )
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700375 return main.FALSE
adminbae64d82013-08-01 10:50:15 -0700376 else:
kelvin-onlabd9a8ed32015-04-03 13:55:28 -0700377 main.log.error( self.name + ": Connection failed to the host" )
378 main.cleanup()
379 main.exit()
380 except pexpect.TIMEOUT:
381 if response:
382 main.log.info( "Pingall output: " + str( response ) )
383 main.log.error( self.name + ": pexpect.TIMEOUT found" )
384 return main.FALSE
385 except pexpect.EOF:
386 main.log.error( self.name + ": EOF exception found" )
387 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -0500388 main.cleanup()
389 main.exit()
adminaeedddd2013-08-02 15:14:15 -0700390
Jon Hall7eb38402015-01-08 17:19:54 -0800391 def fpingHost( self, **pingParams ):
392 """
393 Uses the fping package for faster pinging...
394 *requires fping to be installed on machine running mininet"""
kelvin-onlab7d0c9672015-01-20 15:56:22 -0800395 args = utilities.parse_args( [ "SRC", "TARGET" ], **pingParams )
Jon Hall7eb38402015-01-08 17:19:54 -0800396 command = args[ "SRC" ] + \
397 " fping -i 100 -t 20 -C 1 -q " + args[ "TARGET" ]
398 self.handle.sendline( command )
399 self.handle.expect(
400 [ args[ "TARGET" ], pexpect.EOF, pexpect.TIMEOUT ] )
401 self.handle.expect( [ "mininet", pexpect.EOF, pexpect.TIMEOUT ] )
402 response = self.handle.before
403 if re.search( ":\s-", response ):
404 main.log.info( self.name + ": Ping fail" )
adminaeedddd2013-08-02 15:14:15 -0700405 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -0800406 elif re.search( ":\s\d{1,2}\.\d\d", response ):
407 main.log.info( self.name + ": Ping good!" )
adminaeedddd2013-08-02 15:14:15 -0700408 return main.TRUE
Jon Hall7eb38402015-01-08 17:19:54 -0800409 main.log.info( self.name + ": Install fping on mininet machine... " )
410 main.log.info( self.name + ": \n---\n" + response )
adminaeedddd2013-08-02 15:14:15 -0700411 return main.FALSE
Jon Hallfbc828e2015-01-06 17:30:19 -0800412
Jon Hall3b489db2015-10-05 14:38:37 -0700413 def pingallHosts( self, hostList, wait=1 ):
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400414 """
Hari Krishna9592fc82015-07-31 15:11:15 -0700415 Ping all specified IPv4 hosts
kelvin-onlab2ff57022015-05-29 10:48:51 -0700416
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400417 Acceptable hostList:
Jon Halld80cc142015-07-06 13:36:05 -0700418 - [ 'h1','h2','h3','h4' ]
kelvin-onlab2ff57022015-05-29 10:48:51 -0700419
420 Returns main.TRUE if all hosts specified can reach
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400421 each other
kelvin-onlab2ff57022015-05-29 10:48:51 -0700422
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400423 Returns main.FALSE if one or more of hosts specified
424 cannot reach each other"""
Jon Hall3b489db2015-10-05 14:38:37 -0700425 wait = int( wait )
426 cmd = " ping -c 1 -i 1 -W " + str( wait ) + " "
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400427
428 try:
429 main.log.info( "Testing reachability between specified hosts" )
kelvin-onlab2ff57022015-05-29 10:48:51 -0700430
andrew@onlab.usdefe38c2015-05-14 19:18:18 -0400431 isReachable = main.TRUE
GlennRC6d506272015-09-25 11:36:07 -0700432 pingResponse = "IPv4 ping across specified hosts\n"
433 failedPings = 0
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400434 for host in hostList:
Jon Halld80cc142015-07-06 13:36:05 -0700435 listIndex = hostList.index( host )
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400436 # List of hosts to ping other than itself
Jon Halld80cc142015-07-06 13:36:05 -0700437 pingList = hostList[ :listIndex ] + \
438 hostList[ ( listIndex + 1 ): ]
GlennRCd10d3cc2015-09-24 12:47:16 -0700439
440 pingResponse += str(str(host) + " -> ")
441
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400442 for temp in pingList:
443 # Current host pings all other hosts specified
Jon Halld80cc142015-07-06 13:36:05 -0700444 pingCmd = str( host ) + cmd + str( temp )
Jon Hall934576d2015-10-09 10:12:22 -0700445 self.handle.sendline( pingCmd )
446 self.handle.expect( "mininet>", timeout=wait + 1 )
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400447 response = self.handle.before
448 if re.search( ',\s0\%\spacket\sloss', response ):
GlennRCd10d3cc2015-09-24 12:47:16 -0700449 pingResponse += str(" h" + str( temp[1:] ))
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400450 else:
GlennRCd10d3cc2015-09-24 12:47:16 -0700451 pingResponse += " X"
andrew@onlab.usdefe38c2015-05-14 19:18:18 -0400452 # One of the host to host pair is unreachable
453 isReachable = main.FALSE
GlennRC6d506272015-09-25 11:36:07 -0700454 failedPings += 1
GlennRCd10d3cc2015-09-24 12:47:16 -0700455 pingResponse += "\n"
GlennRC6d506272015-09-25 11:36:07 -0700456 main.log.info( pingResponse + "Failed pings: " + str(failedPings) )
kelvin-onlab2ff57022015-05-29 10:48:51 -0700457 return isReachable
Hari Krishna3bf8ea82015-08-11 09:02:02 -0700458 except pexpect.TIMEOUT:
459 main.log.exception( self.name + ": TIMEOUT exception" )
Hari Krishna4223dbd2015-08-13 16:29:53 -0700460 return main.FALSE
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400461 except pexpect.EOF:
462 main.log.error( self.name + ": EOF exception found" )
463 main.log.error( self.name + ": " + self.handle.before )
464 main.cleanup()
465 main.exit()
Hari Krishna3bf8ea82015-08-11 09:02:02 -0700466 except Exception:
467 main.log.exception( self.name + ": Uncaught exception!" )
468 main.cleanup()
469 main.exit()
andrew@onlab.us9fdee812015-05-14 17:23:26 -0400470
Jon Hall3b489db2015-10-05 14:38:37 -0700471 def pingIpv6Hosts( self, hostList, prefix='1000::', wait=1 ):
Hari Krishna9592fc82015-07-31 15:11:15 -0700472 """
Jon Hall3b489db2015-10-05 14:38:37 -0700473 IPv6 ping all hosts in hostList. If no prefix passed this will use
474 default prefix of 1000::
Hari Krishna9592fc82015-07-31 15:11:15 -0700475
Jon Hall3b489db2015-10-05 14:38:37 -0700476 Returns main.TRUE if all hosts specified can reach each other
Hari Krishna9592fc82015-07-31 15:11:15 -0700477
Jon Hall3b489db2015-10-05 14:38:37 -0700478 Returns main.FALSE if one or more of hosts specified cannot reach each other
Hari Krishna9592fc82015-07-31 15:11:15 -0700479 """
480 try:
481 main.log.info( "Testing reachability between specified IPv6 hosts" )
482 isReachable = main.TRUE
Jon Hall3b489db2015-10-05 14:38:37 -0700483 wait = int( wait )
484 cmd = " ping6 -c 1 -i 1 -W " + str( wait ) + " "
GlennRC6d506272015-09-25 11:36:07 -0700485 pingResponse = "IPv6 Pingall output:\n"
486 failedPings = 0
Hari Krishna9592fc82015-07-31 15:11:15 -0700487 for host in hostList:
488 listIndex = hostList.index( host )
489 # List of hosts to ping other than itself
490 pingList = hostList[ :listIndex ] + \
491 hostList[ ( listIndex + 1 ): ]
492
GlennRC2cf7d952015-09-11 16:32:13 -0700493 pingResponse += str(str(host) + " -> ")
494
Hari Krishna9592fc82015-07-31 15:11:15 -0700495 for temp in pingList:
496 # Current host pings all other hosts specified
Jon Hall439c8912016-04-15 02:22:03 -0700497 pingCmd = str( host ) + cmd + str( self.getIPAddress(temp,proto='IPv6') )
Jon Hall934576d2015-10-09 10:12:22 -0700498 self.handle.sendline( pingCmd )
499 self.handle.expect( "mininet>", timeout=wait + 1 )
Hari Krishna9592fc82015-07-31 15:11:15 -0700500 response = self.handle.before
501 if re.search( ',\s0\%\spacket\sloss', response ):
GlennRC2cf7d952015-09-11 16:32:13 -0700502 pingResponse += str(" h" + str( temp[1:] ))
Hari Krishna9592fc82015-07-31 15:11:15 -0700503 else:
GlennRC2cf7d952015-09-11 16:32:13 -0700504 pingResponse += " X"
Hari Krishna9592fc82015-07-31 15:11:15 -0700505 # One of the host to host pair is unreachable
506 isReachable = main.FALSE
GlennRC6d506272015-09-25 11:36:07 -0700507 failedPings += 1
GlennRCd10d3cc2015-09-24 12:47:16 -0700508 pingResponse += "\n"
GlennRC6d506272015-09-25 11:36:07 -0700509 main.log.info( pingResponse + "Failed pings: " + str(failedPings) )
Hari Krishna9592fc82015-07-31 15:11:15 -0700510 return isReachable
511
Hari Krishna3bf8ea82015-08-11 09:02:02 -0700512 except pexpect.TIMEOUT:
513 main.log.exception( self.name + ": TIMEOUT exception" )
514 return main.FALSE
Hari Krishna9592fc82015-07-31 15:11:15 -0700515 except pexpect.EOF:
516 main.log.error( self.name + ": EOF exception found" )
517 main.log.error( self.name + ": " + self.handle.before )
518 main.cleanup()
519 main.exit()
Hari Krishna3bf8ea82015-08-11 09:02:02 -0700520 except Exception:
521 main.log.exception( self.name + ": Uncaught exception!" )
522 main.cleanup()
523 main.exit()
Hari Krishna9592fc82015-07-31 15:11:15 -0700524
Jon Hall7eb38402015-01-08 17:19:54 -0800525 def pingHost( self, **pingParams ):
526 """
Jon Hall3b489db2015-10-05 14:38:37 -0700527 Ping from one mininet host to another
528 Currently the only supported Params: SRC, TARGET, and WAIT
529 """
530 args = utilities.parse_args( [ "SRC", "TARGET", 'WAIT' ], **pingParams )
531 wait = args['WAIT']
532 wait = int( wait if wait else 1 )
Jon Hall7eb38402015-01-08 17:19:54 -0800533 command = args[ "SRC" ] + " ping " + \
Jon Hall3b489db2015-10-05 14:38:37 -0700534 args[ "TARGET" ] + " -c 1 -i 1 -W " + str( wait ) + " "
Jon Hall6094a362014-04-11 14:46:56 -0700535 try:
Jon Hall61282e32015-03-19 11:34:11 -0700536 main.log.info( "Sending: " + command )
Jon Hall7eb38402015-01-08 17:19:54 -0800537 self.handle.sendline( command )
Jon Hall3b489db2015-10-05 14:38:37 -0700538 i = self.handle.expect( [ command, pexpect.TIMEOUT ],
539 timeout=wait + 1 )
Jon Hall6e18c7b2014-04-23 16:26:33 -0700540 if i == 1:
Jon Hall7eb38402015-01-08 17:19:54 -0800541 main.log.error(
542 self.name +
543 ": timeout when waiting for response from mininet" )
544 main.log.error( "response: " + str( self.handle.before ) )
545 i = self.handle.expect( [ "mininet>", pexpect.TIMEOUT ] )
Jon Hall6e18c7b2014-04-23 16:26:33 -0700546 if i == 1:
Jon Hall7eb38402015-01-08 17:19:54 -0800547 main.log.error(
548 self.name +
549 ": timeout when waiting for response from mininet" )
550 main.log.error( "response: " + str( self.handle.before ) )
Jon Hall6e18c7b2014-04-23 16:26:33 -0700551 response = self.handle.before
Hari Krishna012a1c12015-08-25 14:23:58 -0700552 if re.search( ',\s0\%\spacket\sloss', response ):
553 main.log.info( self.name + ": no packets lost, host is reachable" )
554 return main.TRUE
555 else:
556 main.log.error(
557 self.name +
558 ": PACKET LOST, HOST IS NOT REACHABLE" )
559 return main.FALSE
560
Jon Hallfbc828e2015-01-06 17:30:19 -0800561 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800562 main.log.error( self.name + ": EOF exception found" )
563 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -0700564 main.cleanup()
565 main.exit()
Hari Krishna012a1c12015-08-25 14:23:58 -0700566 except Exception:
567 main.log.exception( self.name + ": Uncaught exception!" )
568 main.cleanup()
569 main.exit()
570
571 def ping6pair( self, **pingParams ):
572 """
GlennRC2cf7d952015-09-11 16:32:13 -0700573 IPv6 Ping between a pair of mininet hosts
Jon Hall3b489db2015-10-05 14:38:37 -0700574 Currently the only supported Params are: SRC, TARGET, and WAIT
Hari Krishna012a1c12015-08-25 14:23:58 -0700575 FLOWLABEL and -I (src interface) will be added later after running some tests.
576 Example: main.Mininet1.ping6pair( src="h1", target="1000::2" )
577 """
Jon Hall3b489db2015-10-05 14:38:37 -0700578 args = utilities.parse_args( [ "SRC", "TARGET", 'WAIT' ], **pingParams )
579 wait = args['WAIT']
580 wait = int( wait if wait else 1 )
Subhash Kumar Singhbcc1c792015-11-07 04:52:11 +0530581 command = args[ "SRC" ] + " ping6 " + \
Jon Hall3b489db2015-10-05 14:38:37 -0700582 args[ "TARGET" ] + " -c 1 -i 1 -W " + str( wait ) + " "
Hari Krishna012a1c12015-08-25 14:23:58 -0700583 try:
584 main.log.info( "Sending: " + command )
585 self.handle.sendline( command )
Jon Hall3b489db2015-10-05 14:38:37 -0700586 i = self.handle.expect( [ command, pexpect.TIMEOUT ],
587 timeout=wait + 1 )
Hari Krishna012a1c12015-08-25 14:23:58 -0700588 if i == 1:
589 main.log.error(
590 self.name +
591 ": timeout when waiting for response from mininet" )
592 main.log.error( "response: " + str( self.handle.before ) )
593 i = self.handle.expect( [ "mininet>", pexpect.TIMEOUT ] )
594 if i == 1:
595 main.log.error(
596 self.name +
597 ": timeout when waiting for response from mininet" )
598 main.log.error( "response: " + str( self.handle.before ) )
599 response = self.handle.before
600 main.log.info( self.name + ": Ping Response: " + response )
601 if re.search( ',\s0\%\spacket\sloss', response ):
602 main.log.info( self.name + ": no packets lost, host is reachable" )
GlennRC2cf7d952015-09-11 16:32:13 -0700603 return main.TRUE
Hari Krishna012a1c12015-08-25 14:23:58 -0700604 else:
605 main.log.error(
606 self.name +
607 ": PACKET LOST, HOST IS NOT REACHABLE" )
608 return main.FALSE
609
610 except pexpect.EOF:
611 main.log.error( self.name + ": EOF exception found" )
612 main.log.error( self.name + ": " + self.handle.before )
613 main.cleanup()
614 main.exit()
615 except Exception:
616 main.log.exception( self.name + ": Uncaught exception!" )
617 main.cleanup()
618 main.exit()
Jon Hallfbc828e2015-01-06 17:30:19 -0800619
Jon Hall7eb38402015-01-08 17:19:54 -0800620 def checkIP( self, host ):
621 """
622 Verifies the host's ip configured or not."""
623 if self.handle:
Jon Hall6094a362014-04-11 14:46:56 -0700624 try:
Jon Hall7eb38402015-01-08 17:19:54 -0800625 response = self.execute(
626 cmd=host +
627 " ifconfig",
628 prompt="mininet>",
629 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -0800630 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800631 main.log.error( self.name + ": EOF exception found" )
632 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -0700633 main.cleanup()
634 main.exit()
adminbae64d82013-08-01 10:50:15 -0700635
Jon Hall7eb38402015-01-08 17:19:54 -0800636 pattern = "inet\s(addr|Mask):([0-1]{1}[0-9]{1,2}|" +\
kelvin-onlabedcff052015-01-16 12:53:55 -0800637 "2[0-4][0-9]|25[0-5]|[0-9]{1,2}).([0-1]{1}" +\
638 "[0-9]{1,2}|2[0-4][0-9]|25[0-5]|[0-9]{1,2})." +\
639 "([0-1]{1}[0-9]{1,2}|2[0-4][0-9]|25[0-5]|" +\
640 "[0-9]{1,2}).([0-1]{1}[0-9]{1,2}|2[0-4]" +\
641 "[0-9]|25[0-5]|[0-9]{1,2})"
Jon Hall7eb38402015-01-08 17:19:54 -0800642 # pattern = "inet addr:10.0.0.6"
643 if re.search( pattern, response ):
644 main.log.info( self.name + ": Host Ip configured properly" )
adminbae64d82013-08-01 10:50:15 -0700645 return main.TRUE
646 else:
Jon Hall7eb38402015-01-08 17:19:54 -0800647 main.log.error( self.name + ": Host IP not found" )
adminbae64d82013-08-01 10:50:15 -0700648 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -0800649 else:
650 main.log.error( self.name + ": Connection failed to the host" )
Jon Hallfbc828e2015-01-06 17:30:19 -0800651
Jon Hall7eb38402015-01-08 17:19:54 -0800652 def verifySSH( self, **connectargs ):
Jon Hallefbd9792015-03-05 16:11:36 -0800653 # FIXME: Who uses this and what is the purpose? seems very specific
Jon Hall6094a362014-04-11 14:46:56 -0700654 try:
Jon Hall7eb38402015-01-08 17:19:54 -0800655 response = self.execute(
656 cmd="h1 /usr/sbin/sshd -D&",
657 prompt="mininet>",
658 timeout=10 )
659 response = self.execute(
660 cmd="h4 /usr/sbin/sshd -D&",
661 prompt="mininet>",
662 timeout=10 )
Jon Hall6094a362014-04-11 14:46:56 -0700663 for key in connectargs:
Jon Hall7eb38402015-01-08 17:19:54 -0800664 vars( self )[ key ] = connectargs[ key ]
665 response = self.execute(
666 cmd="xterm h1 h4 ",
667 prompt="mininet>",
668 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -0800669 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800670 main.log.error( self.name + ": EOF exception found" )
671 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -0700672 main.cleanup()
673 main.exit()
adminbae64d82013-08-01 10:50:15 -0700674 import time
Jon Hall7eb38402015-01-08 17:19:54 -0800675 time.sleep( 20 )
adminbae64d82013-08-01 10:50:15 -0700676 if self.flag == 0:
677 self.flag = 1
678 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -0800679 else:
adminbae64d82013-08-01 10:50:15 -0700680 return main.TRUE
shahshreyae6c7cf42014-11-26 16:39:01 -0800681
Jon Hall53c5e662016-04-13 16:06:56 -0700682 def moveHost( self, host, oldSw, newSw, ):
683 """
684 Moves a host from one switch to another on the fly
685 Note: The intf between host and oldSw when detached
686 using detach(), will still show up in the 'net'
687 cmd, because switch.detach() doesn't affect switch.intfs[]
688 ( which is correct behavior since the interfaces
689 haven't moved ).
690 """
691 if self.handle:
692 try:
693 # Bring link between oldSw-host down
694 cmd = "py net.configLinkStatus('" + oldSw + "'," + "'" + host +\
695 "'," + "'down')"
696 print "cmd1= ", cmd
697 response = self.execute( cmd=cmd,
698 prompt="mininet>",
699 timeout=10 )
700
701 # Determine hostintf and Oldswitchintf
702 cmd = "px hintf,sintf = " + host + ".connectionsTo(" + oldSw +\
703 ")[0]"
704 print "cmd2= ", cmd
705 self.handle.sendline( cmd )
706 self.handle.expect( "mininet>" )
707
708 # Determine ip and mac address of the host-oldSw interface
709 cmd = "px ipaddr = hintf.IP()"
710 print "cmd3= ", cmd
711 self.handle.sendline( cmd )
712 self.handle.expect( "mininet>" )
713
714 cmd = "px macaddr = hintf.MAC()"
715 print "cmd3= ", cmd
716 self.handle.sendline( cmd )
717 self.handle.expect( "mininet>" )
718
719 # Detach interface between oldSw-host
720 cmd = "px " + oldSw + ".detach( sintf )"
721 print "cmd4= ", cmd
722 self.handle.sendline( cmd )
723 self.handle.expect( "mininet>" )
724
725 # Add link between host-newSw
726 cmd = "py net.addLink(" + host + "," + newSw + ")"
727 print "cmd5= ", cmd
728 self.handle.sendline( cmd )
729 self.handle.expect( "mininet>" )
730
731 # Determine hostintf and Newswitchintf
732 cmd = "px hintf,sintf = " + host + ".connectionsTo(" + newSw +\
733 ")[0]"
734 print "cmd6= ", cmd
735 self.handle.sendline( cmd )
736 self.handle.expect( "mininet>" )
737
738 # Attach interface between newSw-host
739 cmd = "px " + newSw + ".attach( sintf )"
740 print "cmd3= ", cmd
741 self.handle.sendline( cmd )
742 self.handle.expect( "mininet>" )
743
744 # Set ipaddress of the host-newSw interface
745 cmd = "px " + host + ".setIP( ip = ipaddr, intf = hintf)"
746 print "cmd7 = ", cmd
747 self.handle.sendline( cmd )
748 self.handle.expect( "mininet>" )
749
750 # Set macaddress of the host-newSw interface
751 cmd = "px " + host + ".setMAC( mac = macaddr, intf = hintf)"
752 print "cmd8 = ", cmd
753 self.handle.sendline( cmd )
754 self.handle.expect( "mininet>" )
755
756 cmd = "net"
757 print "cmd9 = ", cmd
758 self.handle.sendline( cmd )
759 self.handle.expect( "mininet>" )
760 print "output = ", self.handle.before
761
762 # Determine ipaddress of the host-newSw interface
763 cmd = host + " ifconfig"
764 print "cmd10= ", cmd
765 self.handle.sendline( cmd )
766 self.handle.expect( "mininet>" )
767 print "ifconfig o/p = ", self.handle.before
768
769 return main.TRUE
770 except pexpect.EOF:
771 main.log.error( self.name + ": EOF exception found" )
772 main.log.error( self.name + ": " + self.handle.before )
773 return main.FALSE
774
Jon Hall439c8912016-04-15 02:22:03 -0700775 def moveHostv6( self, host, oldSw, newSw, ):
kelvin-onlaba1484582015-02-02 15:46:20 -0800776 """
777 Moves a host from one switch to another on the fly
778 Note: The intf between host and oldSw when detached
779 using detach(), will still show up in the 'net'
780 cmd, because switch.detach() doesn't affect switch.intfs[]
Jon Halld80cc142015-07-06 13:36:05 -0700781 ( which is correct behavior since the interfaces
782 haven't moved ).
kelvin-onlaba1484582015-02-02 15:46:20 -0800783 """
784 if self.handle:
785 try:
Jon Hall439c8912016-04-15 02:22:03 -0700786 IP = str( self.getIPAddress( host, proto='IPV6' ) ) + "/64"
kelvin-onlaba1484582015-02-02 15:46:20 -0800787 # Bring link between oldSw-host down
Jon Halld80cc142015-07-06 13:36:05 -0700788 cmd = "py net.configLinkStatus('" + oldSw + "'," + "'" + host +\
Jon Hallefbd9792015-03-05 16:11:36 -0800789 "'," + "'down')"
kelvin-onlaba1484582015-02-02 15:46:20 -0800790 print "cmd1= ", cmd
Jon Hallefbd9792015-03-05 16:11:36 -0800791 response = self.execute( cmd=cmd,
792 prompt="mininet>",
793 timeout=10 )
Jon Hallafa8a472015-06-12 14:02:42 -0700794
kelvin-onlaba1484582015-02-02 15:46:20 -0800795 # Determine hostintf and Oldswitchintf
796 cmd = "px hintf,sintf = " + host + ".connectionsTo(" + oldSw +\
Jon Hallefbd9792015-03-05 16:11:36 -0800797 ")[0]"
kelvin-onlaba1484582015-02-02 15:46:20 -0800798 print "cmd2= ", cmd
799 self.handle.sendline( cmd )
800 self.handle.expect( "mininet>" )
801
shahshreya73537862015-02-11 15:15:24 -0800802 # Determine ip and mac address of the host-oldSw interface
Jon Hall439c8912016-04-15 02:22:03 -0700803 cmd = "px ipaddr = " + str(IP)
kelvin-onlaba1484582015-02-02 15:46:20 -0800804 print "cmd3= ", cmd
805 self.handle.sendline( cmd )
806 self.handle.expect( "mininet>" )
shahshreya73537862015-02-11 15:15:24 -0800807
808 cmd = "px macaddr = hintf.MAC()"
809 print "cmd3= ", cmd
810 self.handle.sendline( cmd )
811 self.handle.expect( "mininet>" )
Jon Hallafa8a472015-06-12 14:02:42 -0700812
kelvin-onlaba1484582015-02-02 15:46:20 -0800813 # Detach interface between oldSw-host
814 cmd = "px " + oldSw + ".detach( sintf )"
815 print "cmd4= ", cmd
816 self.handle.sendline( cmd )
817 self.handle.expect( "mininet>" )
818
819 # Add link between host-newSw
820 cmd = "py net.addLink(" + host + "," + newSw + ")"
821 print "cmd5= ", cmd
822 self.handle.sendline( cmd )
823 self.handle.expect( "mininet>" )
Jon Hallafa8a472015-06-12 14:02:42 -0700824
kelvin-onlaba1484582015-02-02 15:46:20 -0800825 # Determine hostintf and Newswitchintf
826 cmd = "px hintf,sintf = " + host + ".connectionsTo(" + newSw +\
Jon Hallefbd9792015-03-05 16:11:36 -0800827 ")[0]"
kelvin-onlaba1484582015-02-02 15:46:20 -0800828 print "cmd6= ", cmd
829 self.handle.sendline( cmd )
Jon Hallafa8a472015-06-12 14:02:42 -0700830 self.handle.expect( "mininet>" )
kelvin-onlaba1484582015-02-02 15:46:20 -0800831
832 # Attach interface between newSw-host
833 cmd = "px " + newSw + ".attach( sintf )"
Jon Hall439c8912016-04-15 02:22:03 -0700834 print "cmd6= ", cmd
kelvin-onlaba1484582015-02-02 15:46:20 -0800835 self.handle.sendline( cmd )
836 self.handle.expect( "mininet>" )
shahshreya73537862015-02-11 15:15:24 -0800837
838 # Set macaddress of the host-newSw interface
839 cmd = "px " + host + ".setMAC( mac = macaddr, intf = hintf)"
Jon Hall439c8912016-04-15 02:22:03 -0700840 print "cmd7 = ", cmd
841 self.handle.sendline( cmd )
842 self.handle.expect( "mininet>" )
843
844 # Set ipaddress of the host-newSw interface
845 cmd = "px " + host + ".setIP( ip = ipaddr, intf = hintf)"
shahshreya73537862015-02-11 15:15:24 -0800846 print "cmd8 = ", cmd
847 self.handle.sendline( cmd )
848 self.handle.expect( "mininet>" )
Jon Hallafa8a472015-06-12 14:02:42 -0700849
Jon Hall439c8912016-04-15 02:22:03 -0700850 cmd = host + " ifconfig"
851 print "cmd9 =",cmd
852 response = self.execute( cmd = cmd, prompt="mininet>" ,timeout=10 )
853 print response
854 pattern = "h\d-eth([\w])"
Jeremyd9e4eb12016-04-13 12:09:06 -0700855 ipAddressSearch = re.search( pattern, response )
Jon Hall439c8912016-04-15 02:22:03 -0700856 print ipAddressSearch.group(1)
857 intf= host + "-eth" + str(ipAddressSearch.group(1))
858 cmd = host + " ip -6 addr add %s dev %s" % ( IP, intf )
859 print "cmd10 = ", cmd
860 self.handle.sendline( cmd )
861 self.handle.expect( "mininet>" )
862
kelvin-onlaba1484582015-02-02 15:46:20 -0800863 cmd = "net"
Jon Hall439c8912016-04-15 02:22:03 -0700864 print "cmd11 = ", cmd
kelvin-onlaba1484582015-02-02 15:46:20 -0800865 self.handle.sendline( cmd )
866 self.handle.expect( "mininet>" )
867 print "output = ", self.handle.before
868
869 # Determine ipaddress of the host-newSw interface
shahshreya73537862015-02-11 15:15:24 -0800870 cmd = host + " ifconfig"
Jon Hall439c8912016-04-15 02:22:03 -0700871 print "cmd12= ", cmd
kelvin-onlaba1484582015-02-02 15:46:20 -0800872 self.handle.sendline( cmd )
873 self.handle.expect( "mininet>" )
874 print "ifconfig o/p = ", self.handle.before
Jon Hallafa8a472015-06-12 14:02:42 -0700875
kelvin-onlaba1484582015-02-02 15:46:20 -0800876 return main.TRUE
877 except pexpect.EOF:
878 main.log.error( self.name + ": EOF exception found" )
879 main.log.error( self.name + ": " + self.handle.before )
880 return main.FALSE
881
Jon Hall7eb38402015-01-08 17:19:54 -0800882 def changeIP( self, host, intf, newIP, newNetmask ):
883 """
884 Changes the ip address of a host on the fly
885 Ex: h2 ifconfig h2-eth0 10.0.1.2 netmask 255.255.255.0"""
shahshreyae6c7cf42014-11-26 16:39:01 -0800886 if self.handle:
887 try:
Jon Hall7eb38402015-01-08 17:19:54 -0800888 cmd = host + " ifconfig " + intf + " " + \
889 newIP + " " + 'netmask' + " " + newNetmask
890 self.handle.sendline( cmd )
891 self.handle.expect( "mininet>" )
shahshreyae6c7cf42014-11-26 16:39:01 -0800892 response = self.handle.before
Jon Hall7eb38402015-01-08 17:19:54 -0800893 main.log.info( "response = " + response )
894 main.log.info(
895 "Ip of host " +
896 host +
897 " changed to new IP " +
898 newIP )
shahshreyae6c7cf42014-11-26 16:39:01 -0800899 return main.TRUE
900 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800901 main.log.error( self.name + ": EOF exception found" )
902 main.log.error( self.name + ": " + self.handle.before )
shahshreyae6c7cf42014-11-26 16:39:01 -0800903 return main.FALSE
904
Jon Hall7eb38402015-01-08 17:19:54 -0800905 def changeDefaultGateway( self, host, newGW ):
906 """
907 Changes the default gateway of a host
908 Ex: h1 route add default gw 10.0.1.2"""
shahshreyae6c7cf42014-11-26 16:39:01 -0800909 if self.handle:
910 try:
Jon Hall7eb38402015-01-08 17:19:54 -0800911 cmd = host + " route add default gw " + newGW
912 self.handle.sendline( cmd )
913 self.handle.expect( "mininet>" )
shahshreyae6c7cf42014-11-26 16:39:01 -0800914 response = self.handle.before
Jon Hall7eb38402015-01-08 17:19:54 -0800915 main.log.info( "response = " + response )
916 main.log.info(
917 "Default gateway of host " +
918 host +
919 " changed to " +
920 newGW )
shahshreyae6c7cf42014-11-26 16:39:01 -0800921 return main.TRUE
922 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800923 main.log.error( self.name + ": EOF exception found" )
924 main.log.error( self.name + ": " + self.handle.before )
shahshreyae6c7cf42014-11-26 16:39:01 -0800925 return main.FALSE
Jon Hallfbc828e2015-01-06 17:30:19 -0800926
Jon Hall7eb38402015-01-08 17:19:54 -0800927 def addStaticMACAddress( self, host, GW, macaddr ):
928 """
Jon Hallefbd9792015-03-05 16:11:36 -0800929 Changes the mac address of a gateway host"""
shahshreyad0c80432014-12-04 16:56:05 -0800930 if self.handle:
931 try:
Jon Hall7eb38402015-01-08 17:19:54 -0800932 # h1 arp -s 10.0.1.254 00:00:00:00:11:11
933 cmd = host + " arp -s " + GW + " " + macaddr
934 self.handle.sendline( cmd )
935 self.handle.expect( "mininet>" )
shahshreyad0c80432014-12-04 16:56:05 -0800936 response = self.handle.before
Jon Hall7eb38402015-01-08 17:19:54 -0800937 main.log.info( "response = " + response )
938 main.log.info(
Jon Hallefbd9792015-03-05 16:11:36 -0800939 "Mac address of gateway " +
Jon Hall7eb38402015-01-08 17:19:54 -0800940 GW +
941 " changed to " +
942 macaddr )
shahshreyad0c80432014-12-04 16:56:05 -0800943 return main.TRUE
944 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800945 main.log.error( self.name + ": EOF exception found" )
946 main.log.error( self.name + ": " + self.handle.before )
shahshreyad0c80432014-12-04 16:56:05 -0800947 return main.FALSE
948
Jon Hall7eb38402015-01-08 17:19:54 -0800949 def verifyStaticGWandMAC( self, host ):
950 """
951 Verify if the static gateway and mac address assignment"""
shahshreyad0c80432014-12-04 16:56:05 -0800952 if self.handle:
953 try:
Jon Hall7eb38402015-01-08 17:19:54 -0800954 # h1 arp -an
955 cmd = host + " arp -an "
956 self.handle.sendline( cmd )
957 self.handle.expect( "mininet>" )
shahshreyad0c80432014-12-04 16:56:05 -0800958 response = self.handle.before
Jon Hall7eb38402015-01-08 17:19:54 -0800959 main.log.info( host + " arp -an = " + response )
shahshreyad0c80432014-12-04 16:56:05 -0800960 return main.TRUE
961 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800962 main.log.error( self.name + ": EOF exception found" )
963 main.log.error( self.name + ": " + self.handle.before )
shahshreyad0c80432014-12-04 16:56:05 -0800964 return main.FALSE
965
Jon Hall7eb38402015-01-08 17:19:54 -0800966 def getMacAddress( self, host ):
967 """
968 Verifies the host's ip configured or not."""
969 if self.handle:
Jon Hall6094a362014-04-11 14:46:56 -0700970 try:
Jon Hall7eb38402015-01-08 17:19:54 -0800971 response = self.execute(
972 cmd=host +
973 " ifconfig",
974 prompt="mininet>",
975 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -0800976 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -0800977 main.log.error( self.name + ": EOF exception found" )
978 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -0700979 main.cleanup()
980 main.exit()
adminbae64d82013-08-01 10:50:15 -0700981
Ahmed El-Hassanyf720e202014-04-04 16:11:36 -0700982 pattern = r'HWaddr\s([0-9A-F]{2}[:-]){5}([0-9A-F]{2})'
kelvin-onlabd3b64892015-01-20 13:26:24 -0800983 macAddressSearch = re.search( pattern, response, re.I )
984 macAddress = macAddressSearch.group().split( " " )[ 1 ]
Jon Hall7eb38402015-01-08 17:19:54 -0800985 main.log.info(
986 self.name +
987 ": Mac-Address of Host " +
988 host +
989 " is " +
kelvin-onlabd3b64892015-01-20 13:26:24 -0800990 macAddress )
991 return macAddress
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -0700992 else:
Jon Hall7eb38402015-01-08 17:19:54 -0800993 main.log.error( self.name + ": Connection failed to the host" )
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -0700994
Jon Hall7eb38402015-01-08 17:19:54 -0800995 def getInterfaceMACAddress( self, host, interface ):
996 """
997 Return the IP address of the interface on the given host"""
998 if self.handle:
Jon Hall6094a362014-04-11 14:46:56 -0700999 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001000 response = self.execute( cmd=host + " ifconfig " + interface,
1001 prompt="mininet>", timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001002 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001003 main.log.error( self.name + ": EOF exception found" )
1004 main.log.error( self.name + ": " + self.handle.before )
1005 main.cleanup()
1006 main.exit()
1007
1008 pattern = r'HWaddr\s([0-9A-F]{2}[:-]){5}([0-9A-F]{2})'
kelvin-onlabd3b64892015-01-20 13:26:24 -08001009 macAddressSearch = re.search( pattern, response, re.I )
1010 if macAddressSearch is None:
Jon Hall7eb38402015-01-08 17:19:54 -08001011 main.log.info( "No mac address found in %s" % response )
1012 return main.FALSE
kelvin-onlabd3b64892015-01-20 13:26:24 -08001013 macAddress = macAddressSearch.group().split( " " )[ 1 ]
Jon Hall7eb38402015-01-08 17:19:54 -08001014 main.log.info(
1015 "Mac-Address of " +
1016 host +
1017 ":" +
1018 interface +
1019 " is " +
kelvin-onlabd3b64892015-01-20 13:26:24 -08001020 macAddress )
1021 return macAddress
Jon Hall7eb38402015-01-08 17:19:54 -08001022 else:
1023 main.log.error( "Connection failed to the host" )
1024
sathishmad953462015-12-03 17:42:07 +05301025 def getIPAddress( self, host , proto='IPV4'):
Jon Hall7eb38402015-01-08 17:19:54 -08001026 """
1027 Verifies the host's ip configured or not."""
1028 if self.handle:
1029 try:
1030 response = self.execute(
1031 cmd=host +
1032 " ifconfig",
1033 prompt="mininet>",
1034 timeout=10 )
1035 except pexpect.EOF:
1036 main.log.error( self.name + ": EOF exception found" )
1037 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001038 main.cleanup()
1039 main.exit()
adminbae64d82013-08-01 10:50:15 -07001040
sathishmad953462015-12-03 17:42:07 +05301041 pattern = ''
1042 if proto == 'IPV4':
1043 pattern = "inet\saddr:(\d+\.\d+\.\d+\.\d+)"
1044 else:
Jon Hall439c8912016-04-15 02:22:03 -07001045 pattern = "inet6\saddr:\s([\w,:]*)/\d+\sScope:Global"
kelvin-onlabd3b64892015-01-20 13:26:24 -08001046 ipAddressSearch = re.search( pattern, response )
Jon Hall7eb38402015-01-08 17:19:54 -08001047 main.log.info(
1048 self.name +
1049 ": IP-Address of Host " +
1050 host +
1051 " is " +
kelvin-onlabd3b64892015-01-20 13:26:24 -08001052 ipAddressSearch.group( 1 ) )
1053 return ipAddressSearch.group( 1 )
Jon Hall7eb38402015-01-08 17:19:54 -08001054 else:
1055 main.log.error( self.name + ": Connection failed to the host" )
Jon Hallfbc828e2015-01-06 17:30:19 -08001056
Jon Hall7eb38402015-01-08 17:19:54 -08001057 def getSwitchDPID( self, switch ):
1058 """
1059 return the datapath ID of the switch"""
1060 if self.handle:
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001061 cmd = "py %s.dpid" % switch
Jon Hall6094a362014-04-11 14:46:56 -07001062 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001063 response = self.execute(
1064 cmd=cmd,
1065 prompt="mininet>",
1066 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001067 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001068 main.log.error( self.name + ": EOF exception found" )
1069 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001070 main.cleanup()
1071 main.exit()
Jon Hall28bf54b2014-12-17 16:25:44 -08001072 pattern = r'^(?P<dpid>\w)+'
Jon Hall7eb38402015-01-08 17:19:54 -08001073 result = re.search( pattern, response, re.MULTILINE )
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001074 if result is None:
Jon Hall7eb38402015-01-08 17:19:54 -08001075 main.log.info(
1076 "Couldn't find DPID for switch %s, found: %s" %
1077 ( switch, response ) )
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001078 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001079 return str( result.group( 0 ) ).lower()
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001080 else:
Jon Hall7eb38402015-01-08 17:19:54 -08001081 main.log.error( "Connection failed to the host" )
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001082
Jon Hall7eb38402015-01-08 17:19:54 -08001083 def getDPID( self, switch ):
admin2580a0e2014-07-29 11:24:34 -07001084 if self.handle:
Jon Hall7eb38402015-01-08 17:19:54 -08001085 self.handle.sendline( "" )
1086 self.expect( "mininet>" )
1087 cmd = "py %s.dpid" % switch
admin2580a0e2014-07-29 11:24:34 -07001088 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001089 response = self.execute(
1090 cmd=cmd,
1091 prompt="mininet>",
1092 timeout=10 )
1093 self.handle.expect( "mininet>" )
admin2580a0e2014-07-29 11:24:34 -07001094 response = self.handle.before
1095 return response
1096 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001097 main.log.error( self.name + ": EOF exception found" )
1098 main.log.error( self.name + ": " + self.handle.before )
admin2580a0e2014-07-29 11:24:34 -07001099 main.cleanup()
1100 main.exit()
1101
Jon Hall7eb38402015-01-08 17:19:54 -08001102 def getInterfaces( self, node ):
1103 """
1104 return information dict about interfaces connected to the node"""
1105 if self.handle:
1106 cmd = 'py "\\n".join(["name=%s,mac=%s,ip=%s,enabled=%s"' +\
kelvin-onlabedcff052015-01-16 12:53:55 -08001107 ' % (i.name, i.MAC(), i.IP(), i.isUp())'
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001108 cmd += ' for i in %s.intfs.values()])' % node
Jon Hall6094a362014-04-11 14:46:56 -07001109 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001110 response = self.execute(
1111 cmd=cmd,
1112 prompt="mininet>",
1113 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001114 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001115 main.log.error( self.name + ": EOF exception found" )
1116 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001117 main.cleanup()
1118 main.exit()
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001119 return response
1120 else:
Jon Hall7eb38402015-01-08 17:19:54 -08001121 main.log.error( "Connection failed to the node" )
Ahmed El-Hassanyfd329182014-04-10 11:38:16 -07001122
Jon Hall7eb38402015-01-08 17:19:54 -08001123 def dump( self ):
1124 main.log.info( self.name + ": Dump node info" )
Jon Hall6094a362014-04-11 14:46:56 -07001125 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001126 response = self.execute(
1127 cmd='dump',
1128 prompt='mininet>',
1129 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001130 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001131 main.log.error( self.name + ": EOF exception found" )
1132 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001133 main.cleanup()
1134 main.exit()
Ahmed El-Hassanyd1f71702014-04-04 16:12:45 -07001135 return response
Jon Hallfbc828e2015-01-06 17:30:19 -08001136
Jon Hall7eb38402015-01-08 17:19:54 -08001137 def intfs( self ):
1138 main.log.info( self.name + ": List interfaces" )
Jon Hall6094a362014-04-11 14:46:56 -07001139 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001140 response = self.execute(
1141 cmd='intfs',
1142 prompt='mininet>',
1143 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001144 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001145 main.log.error( self.name + ": EOF exception found" )
1146 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001147 main.cleanup()
1148 main.exit()
Jon Hall668ed802014-04-08 17:17:59 -07001149 return response
Jon Hallfbc828e2015-01-06 17:30:19 -08001150
Jon Hall7eb38402015-01-08 17:19:54 -08001151 def net( self ):
1152 main.log.info( self.name + ": List network connections" )
Jon Hall6094a362014-04-11 14:46:56 -07001153 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001154 response = self.execute( cmd='net', prompt='mininet>', timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001155 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001156 main.log.error( self.name + ": EOF exception found" )
1157 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001158 main.cleanup()
1159 main.exit()
Jon Hall668ed802014-04-08 17:17:59 -07001160 return response
Jon Hall7eb38402015-01-08 17:19:54 -08001161
Jon Hallafa8a472015-06-12 14:02:42 -07001162 def links( self ):
1163 main.log.info( self.name + ": List network links" )
1164 try:
1165 response = self.execute( cmd='links', prompt='mininet>',
Jon Hall3b489db2015-10-05 14:38:37 -07001166 timeout=20 )
Jon Hallafa8a472015-06-12 14:02:42 -07001167 except pexpect.EOF:
1168 main.log.error( self.name + ": EOF exception found" )
1169 main.log.error( self.name + ": " + self.handle.before )
1170 main.cleanup()
1171 main.exit()
1172 return response
1173
GlennRC61321f22015-07-16 13:36:54 -07001174 def iperftcpAll(self, hosts, timeout=6):
kelvin-onlab7cce9382015-07-17 10:21:03 -07001175 '''
1176 Runs the iperftcp function with a given set of hosts and specified timeout.
GlennRC61321f22015-07-16 13:36:54 -07001177
kelvin-onlab7cce9382015-07-17 10:21:03 -07001178 @parm:
1179 timeout: The defualt timeout is 6 sec to allow enough time for a successful test to complete,
1180 and short enough to stop an unsuccessful test from quiting and cleaning up mininet.
1181 '''
1182 for host1 in hosts:
1183 for host2 in hosts:
1184 if host1 != host2:
1185 if self.iperftcp(host1, host2, timeout) == main.FALSE:
1186 main.log.error(self.name + ": iperftcp test failed for " + host1 + " and " + host2)
GlennRC61321f22015-07-16 13:36:54 -07001187
1188 def iperftcp(self, host1="h1", host2="h2", timeout=6):
kelvin-onlab7cce9382015-07-17 10:21:03 -07001189 '''
1190 Creates an iperf TCP test between two hosts. Returns main.TRUE if test results
1191 are valid.
GlennRC61321f22015-07-16 13:36:54 -07001192
kelvin-onlab7cce9382015-07-17 10:21:03 -07001193 @parm:
1194 timeout: The defualt timeout is 6 sec to allow enough time for a successful test to complete,
1195 and short enough to stop an unsuccessful test from quiting and cleaning up mininet.
1196 '''
1197 main.log.info( self.name + ": Simple iperf TCP test between two hosts" )
1198 try:
1199 # Setup the mininet command
1200 cmd1 = 'iperf ' + host1 + " " + host2
1201 self.handle.sendline( cmd1 )
1202 outcome = self.handle.expect( "mininet>", timeout )
1203 response = self.handle.before
GlennRC61321f22015-07-16 13:36:54 -07001204
kelvin-onlab7cce9382015-07-17 10:21:03 -07001205 # checks if there are results in the mininet response
1206 if "Results:" in response:
Jon Hall892818c2015-10-20 17:58:34 -07001207 main.log.report(self.name + ": iperf test completed")
kelvin-onlab7cce9382015-07-17 10:21:03 -07001208 # parse the mn results
1209 response = response.split("\r\n")
1210 response = response[len(response)-2]
1211 response = response.split(": ")
1212 response = response[len(response)-1]
1213 response = response.replace("[", "")
1214 response = response.replace("]", "")
1215 response = response.replace("\'", "")
GlennRC61321f22015-07-16 13:36:54 -07001216
kelvin-onlab7cce9382015-07-17 10:21:03 -07001217 # this is the bandwith two and from the two hosts
1218 bandwidth = response.split(", ")
GlennRC61321f22015-07-16 13:36:54 -07001219
kelvin-onlab7cce9382015-07-17 10:21:03 -07001220 # there should be two elements in the bandwidth list
1221 # ['host1 to host2', 'host2 to host1"]
1222 if len(bandwidth) == 2:
1223 main.log.report(self.name + ": iperf test successful")
1224 return main.TRUE
1225 else:
1226 main.log.error(self.name + ": invalid iperf results")
1227 return main.FALSE
shahshreyae6c7cf42014-11-26 16:39:01 -08001228 else:
kelvin-onlab7cce9382015-07-17 10:21:03 -07001229 main.log.error( self.name + ": iperf test failed" )
Jon Hall7eb38402015-01-08 17:19:54 -08001230 return main.FALSE
GlennRC61321f22015-07-16 13:36:54 -07001231 except pexpect.TIMEOUT:
Jon Hall3b489db2015-10-05 14:38:37 -07001232 main.log.error( self.name + ": TIMEOUT exception found" )
1233 main.log.error( self.name + " response: " +
Jon Hall892818c2015-10-20 17:58:34 -07001234 repr( self.handle.before ) )
Jon Hall3b489db2015-10-05 14:38:37 -07001235 # NOTE: Send ctrl-c to make sure iperf is done
1236 self.handle.sendline( "\x03" )
1237 self.handle.expect( "Interrupt" )
1238 self.handle.expect( "mininet>" )
GlennRC61321f22015-07-16 13:36:54 -07001239 return main.FALSE
Jon Hallfbc828e2015-01-06 17:30:19 -08001240 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001241 main.log.error( self.name + ": EOF exception found" )
1242 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001243 main.cleanup()
kelvin-onlab7cce9382015-07-17 10:21:03 -07001244 main.exit()
GlennRC61321f22015-07-16 13:36:54 -07001245
Jon Hall439c8912016-04-15 02:22:03 -07001246 def iperftcpipv6(self, host1="h1", host2="h2", timeout=50):
1247 main.log.info( self.name + ": Simple iperf TCP test between two hosts" )
1248 try:
1249 IP1 = self.getIPAddress( host1, proto='IPV6' )
1250 cmd1 = host1 +' iperf -V -sD -B '+ str(IP1)
1251 self.handle.sendline( cmd1 )
1252 outcome1 = self.handle.expect( "mininet>")
1253 cmd2 = host2 +' iperf -V -c '+ str(IP1) +' -t 5'
1254 self.handle.sendline( cmd2 )
1255 outcome2 = self.handle.expect( "mininet>")
1256 response1 = self.handle.before
1257 response2 = self.handle.after
1258 print response1,response2
1259 pattern = "connected with "+ str(IP1)
1260 if pattern in response1:
1261 main.log.report(self.name + ": iperf test completed")
1262 return main.TRUE
1263 else:
1264 main.log.error( self.name + ": iperf test failed" )
1265 return main.FALSE
1266 except pexpect.TIMEOUT:
1267 main.log.error( self.name + ": TIMEOUT exception found" )
1268 main.log.error( self.name + " response: " + repr( self.handle.before ) )
1269 self.handle.sendline( "\x03" )
1270 self.handle.expect( "Interrupt" )
1271 self.handle.expect( "mininet>" )
1272 return main.FALSE
1273 except pexpect.EOF:
1274 main.log.error( self.name + ": EOF exception found" )
1275 main.log.error( self.name + ": " + self.handle.before )
1276 main.cleanup()
1277 main.exit()
1278
GlennRC61321f22015-07-16 13:36:54 -07001279 def iperfudpAll(self, hosts, bandwidth="10M"):
1280 '''
1281 Runs the iperfudp function with a given set of hosts and specified
1282 bandwidth
kelvin-onlab7cce9382015-07-17 10:21:03 -07001283
GlennRC61321f22015-07-16 13:36:54 -07001284 @param:
1285 bandwidth: the targeted bandwidth, in megabits ('M')
1286 '''
1287 for host1 in hosts:
1288 for host2 in hosts:
1289 if host1 != host2:
1290 if self.iperfudp(host1, host2, bandwidth) == main.FALSE:
1291 main.log.error(self.name + ": iperfudp test failed for " + host1 + " and " + host2)
1292
1293 def iperfudp( self, bandwidth="10M", host1="h1", host2="h2"):
1294
kelvin-onlab7cce9382015-07-17 10:21:03 -07001295 '''
1296 Creates an iperf UDP test with a specific bandwidth.
1297 Returns true if results are valid.
GlennRC61321f22015-07-16 13:36:54 -07001298
kelvin-onlab7cce9382015-07-17 10:21:03 -07001299 @param:
1300 bandwidth: the targeted bandwidth, in megabits ('M'), to run the test
1301 '''
1302 main.log.info(self.name + ": Simple iperf UDP test between two hosts")
1303 try:
1304 # setup the mininet command
1305 cmd = 'iperfudp ' + bandwidth + " " + host1 + " " + host2
1306 self.handle.sendline(cmd)
1307 self.handle.expect("mininet>")
1308 response = self.handle.before
GlennRC61321f22015-07-16 13:36:54 -07001309
kelvin-onlab7cce9382015-07-17 10:21:03 -07001310 # check if there are in results in the mininet response
1311 if "Results:" in response:
Jon Hall892818c2015-10-20 17:58:34 -07001312 main.log.report(self.name + ": iperfudp test completed")
kelvin-onlab7cce9382015-07-17 10:21:03 -07001313 # parse the results
1314 response = response.split("\r\n")
1315 response = response[len(response)-2]
1316 response = response.split(": ")
1317 response = response[len(response)-1]
1318 response = response.replace("[", "")
1319 response = response.replace("]", "")
1320 response = response.replace("\'", "")
GlennRC61321f22015-07-16 13:36:54 -07001321
kelvin-onlab7cce9382015-07-17 10:21:03 -07001322 mnBandwidth = response.split(", ")
GlennRC61321f22015-07-16 13:36:54 -07001323
kelvin-onlab7cce9382015-07-17 10:21:03 -07001324 # check to see if there are at least three entries
1325 # ['bandwidth', 'host1 to host2', 'host2 to host1']
1326 if len(mnBandwidth) == 3:
1327 # if one entry is blank then something is wrong
1328 for item in mnBandwidth:
1329 if item == "":
1330 main.log.error(self.name + ": Could not parse iperf output")
1331 main.log.error(self.name + ": invalid iperfudp results")
1332 return main.FALSE
1333 # otherwise results are vaild
1334 main.log.report(self.name + ": iperfudp test successful")
1335 return main.TRUE
1336 else:
1337 main.log.error(self.name + ": invalid iperfudp results")
1338 return main.FALSE
GlennRC61321f22015-07-16 13:36:54 -07001339
kelvin-onlab7cce9382015-07-17 10:21:03 -07001340 except pexpect.EOF:
1341 main.log.error( self.name + ": EOF exception found" )
1342 main.log.error( self.name + ": " + self.handle.before )
1343 main.cleanup()
1344 main.exit()
Jon Hallfbc828e2015-01-06 17:30:19 -08001345
Jon Hall7eb38402015-01-08 17:19:54 -08001346 def nodes( self ):
1347 main.log.info( self.name + ": List all nodes." )
Jon Hall6094a362014-04-11 14:46:56 -07001348 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001349 response = self.execute(
1350 cmd='nodes',
1351 prompt='mininet>',
1352 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001353 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001354 main.log.error( self.name + ": EOF exception found" )
1355 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001356 main.cleanup()
1357 main.exit()
Jon Hall668ed802014-04-08 17:17:59 -07001358 return response
Jon Hallfbc828e2015-01-06 17:30:19 -08001359
Jon Hall7eb38402015-01-08 17:19:54 -08001360 def pingpair( self ):
1361 main.log.info( self.name + ": Ping between first two hosts" )
Jon Hall6094a362014-04-11 14:46:56 -07001362 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001363 response = self.execute(
1364 cmd='pingpair',
1365 prompt='mininet>',
1366 timeout=20 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001367 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001368 main.log.error( self.name + ": EOF exception found" )
1369 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001370 main.cleanup()
1371 main.exit()
Jon Hallfbc828e2015-01-06 17:30:19 -08001372
Jon Hall7eb38402015-01-08 17:19:54 -08001373 if re.search( ',\s0\%\spacket\sloss', response ):
1374 main.log.info( self.name + ": Ping between two hosts SUCCESSFUL" )
adminbae64d82013-08-01 10:50:15 -07001375 return main.TRUE
Jon Hall7eb38402015-01-08 17:19:54 -08001376 else:
1377 main.log.error( self.name + ": PACKET LOST, HOSTS NOT REACHABLE" )
adminbae64d82013-08-01 10:50:15 -07001378 return main.FALSE
Jon Hallfbc828e2015-01-06 17:30:19 -08001379
Jon Hall7eb38402015-01-08 17:19:54 -08001380 def link( self, **linkargs ):
1381 """
GlennRCed771242016-01-13 17:02:47 -08001382 Bring link( s ) between two nodes up or down
1383 """
Jon Hall6094a362014-04-11 14:46:56 -07001384 try:
GlennRCed771242016-01-13 17:02:47 -08001385 args = utilities.parse_args( [ "END1", "END2", "OPTION" ], **linkargs )
1386 end1 = args[ "END1" ] if args[ "END1" ] is not None else ""
1387 end2 = args[ "END2" ] if args[ "END2" ] is not None else ""
1388 option = args[ "OPTION" ] if args[ "OPTION" ] is not None else ""
1389
1390 main.log.info( "Bring link between " + str( end1 ) + " and " + str( end2 ) + " " + str( option ) )
1391 cmd = "link {} {} {}".format( end1, end2, option )
1392 self.handle.sendline( cmd )
Jon Hall7eb38402015-01-08 17:19:54 -08001393 self.handle.expect( "mininet>" )
GlennRCed771242016-01-13 17:02:47 -08001394 response = self.handle.before
1395 main.log.info( response )
1396
1397 return main.TRUE
1398 except pexpect.TIMEOUT:
1399 main.log.exception( self.name + ": Command timed out" )
1400 return None
Jon Hallfbc828e2015-01-06 17:30:19 -08001401 except pexpect.EOF:
GlennRCed771242016-01-13 17:02:47 -08001402 main.log.exception( self.name + ": connection closed." )
Jon Hall6094a362014-04-11 14:46:56 -07001403 main.cleanup()
1404 main.exit()
GlennRCed771242016-01-13 17:02:47 -08001405 except Exception:
1406 main.log.exception( self.name + ": Uncaught exception!" )
1407 main.cleanup()
1408 main.exit()
Jon Hallfbc828e2015-01-06 17:30:19 -08001409
pingping-lin8244a3b2015-09-16 13:36:56 -07001410 def switch( self, **switchargs ):
1411 """
1412 start/stop a switch
1413 """
1414 args = utilities.parse_args( [ "SW", "OPTION" ], **switchargs )
1415 sw = args[ "SW" ] if args[ "SW" ] is not None else ""
1416 option = args[ "OPTION" ] if args[ "OPTION" ] is not None else ""
1417 command = "switch " + str( sw ) + " " + str( option )
1418 main.log.info( command )
1419 try:
1420 self.handle.sendline( command )
1421 self.handle.expect( "mininet>" )
1422 except pexpect.TIMEOUT:
1423 main.log.error( self.name + ": pexpect.TIMEOUT found" )
1424 main.cleanup()
1425 main.exit()
1426 except pexpect.EOF:
1427 main.log.error( self.name + ": EOF exception found" )
1428 main.log.error( self.name + ": " + self.handle.before )
1429 main.cleanup()
1430 main.exit()
1431 return main.TRUE
1432
pingping-lin5bb663b2015-09-24 11:47:50 -07001433 def node( self, nodeName, commandStr ):
1434 """
1435 Carry out a command line on a given node
1436 @parm:
1437 nodeName: the node name in Mininet testbed
1438 commandStr: the command line will be carried out on the node
1439 Example: main.Mininet.node( nodeName="h1", commandStr="ls" )
1440 """
1441 command = str( nodeName ) + " " + str( commandStr )
1442 main.log.info( command )
1443
1444 try:
1445 response = self.execute( cmd = command, prompt = "mininet>" )
1446 if re.search( "Unknown command", response ):
1447 main.log.warn( response )
1448 return main.FALSE
Jon Hall9ed8f372016-02-24 17:34:07 -08001449 if re.search( "Permission denied", response ):
1450 main.log.warn( response )
1451 return main.FALSE
pingping-lin5bb663b2015-09-24 11:47:50 -07001452 except pexpect.TIMEOUT:
1453 main.log.error( self.name + ": pexpect.TIMEOUT found" )
1454 main.cleanup()
1455 main.exit()
1456 except pexpect.EOF:
1457 main.log.error( self.name + ": EOF exception found" )
1458 main.log.error( self.name + ": " + self.handle.before )
1459 main.cleanup()
1460 main.exit()
1461 main.log.info( " response is :" )
1462 main.log.info( response )
1463 return response
1464
Jon Hall7eb38402015-01-08 17:19:54 -08001465 def yank( self, **yankargs ):
1466 """
1467 yank a mininet switch interface to a host"""
1468 main.log.info( 'Yank the switch interface attached to a host' )
kelvin-onlab7d0c9672015-01-20 15:56:22 -08001469 args = utilities.parse_args( [ "SW", "INTF" ], **yankargs )
Jon Hall7eb38402015-01-08 17:19:54 -08001470 sw = args[ "SW" ] if args[ "SW" ] is not None else ""
1471 intf = args[ "INTF" ] if args[ "INTF" ] is not None else ""
1472 command = "py " + str( sw ) + '.detach("' + str(intf) + '")'
Jon Hall6094a362014-04-11 14:46:56 -07001473 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001474 response = self.execute(
1475 cmd=command,
1476 prompt="mininet>",
1477 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001478 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001479 main.log.error( self.name + ": EOF exception found" )
1480 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001481 main.cleanup()
1482 main.exit()
adminaeedddd2013-08-02 15:14:15 -07001483 return main.TRUE
1484
Jon Hall7eb38402015-01-08 17:19:54 -08001485 def plug( self, **plugargs ):
1486 """
1487 plug the yanked mininet switch interface to a switch"""
1488 main.log.info( 'Plug the switch interface attached to a switch' )
kelvin-onlab7d0c9672015-01-20 15:56:22 -08001489 args = utilities.parse_args( [ "SW", "INTF" ], **plugargs )
Jon Hall7eb38402015-01-08 17:19:54 -08001490 sw = args[ "SW" ] if args[ "SW" ] is not None else ""
1491 intf = args[ "INTF" ] if args[ "INTF" ] is not None else ""
1492 command = "py " + str( sw ) + '.attach("' + str(intf) + '")'
Jon Hall6094a362014-04-11 14:46:56 -07001493 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001494 response = self.execute(
1495 cmd=command,
1496 prompt="mininet>",
1497 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001498 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001499 main.log.error( self.name + ": EOF exception found" )
1500 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001501 main.cleanup()
1502 main.exit()
adminbae64d82013-08-01 10:50:15 -07001503 return main.TRUE
Jon Hallfbc828e2015-01-06 17:30:19 -08001504
Jon Hall7eb38402015-01-08 17:19:54 -08001505 def dpctl( self, **dpctlargs ):
1506 """
1507 Run dpctl command on all switches."""
1508 main.log.info( 'Run dpctl command on all switches' )
kelvin-onlab7d0c9672015-01-20 15:56:22 -08001509 args = utilities.parse_args( [ "CMD", "ARGS" ], **dpctlargs )
Jon Hall7eb38402015-01-08 17:19:54 -08001510 cmd = args[ "CMD" ] if args[ "CMD" ] is not None else ""
1511 cmdargs = args[ "ARGS" ] if args[ "ARGS" ] is not None else ""
1512 command = "dpctl " + cmd + " " + str( cmdargs )
1513 try:
1514 response = self.execute(
1515 cmd=command,
1516 prompt="mininet>",
1517 timeout=10 )
1518 except pexpect.EOF:
1519 main.log.error( self.name + ": EOF exception found" )
1520 main.log.error( self.name + ": " + self.handle.before )
1521 main.cleanup()
1522 main.exit()
1523 return main.TRUE
Jon Hallfbc828e2015-01-06 17:30:19 -08001524
kelvin-onlabd3b64892015-01-20 13:26:24 -08001525 def getVersion( self ):
Jon Halld80cc142015-07-06 13:36:05 -07001526 # FIXME: What uses this? This should be refactored to get
Jon Hallff6b4b22015-02-23 09:25:15 -08001527 # version from MN and not some other file
kelvin-onlabd3b64892015-01-20 13:26:24 -08001528 fileInput = path + '/lib/Mininet/INSTALL'
1529 version = super( Mininet, self ).getVersion()
adminbae64d82013-08-01 10:50:15 -07001530 pattern = 'Mininet\s\w\.\w\.\w\w*'
kelvin-onlabd3b64892015-01-20 13:26:24 -08001531 for line in open( fileInput, 'r' ).readlines():
Jon Hall7eb38402015-01-08 17:19:54 -08001532 result = re.match( pattern, line )
adminbae64d82013-08-01 10:50:15 -07001533 if result:
Jon Hall7eb38402015-01-08 17:19:54 -08001534 version = result.group( 0 )
Jon Hallec3c21e2014-11-10 22:22:37 -05001535 return version
adminbae64d82013-08-01 10:50:15 -07001536
kelvin-onlabd3b64892015-01-20 13:26:24 -08001537 def getSwController( self, sw ):
Jon Hall7eb38402015-01-08 17:19:54 -08001538 """
Jon Hallec3c21e2014-11-10 22:22:37 -05001539 Parameters:
1540 sw: The name of an OVS switch. Example "s1"
1541 Return:
Jon Hall7eb38402015-01-08 17:19:54 -08001542 The output of the command from the mininet cli
1543 or main.FALSE on timeout"""
1544 command = "sh ovs-vsctl get-controller " + str( sw )
admin2a9548d2014-06-17 14:08:07 -07001545 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001546 response = self.execute(
1547 cmd=command,
1548 prompt="mininet>",
1549 timeout=10 )
admin2a9548d2014-06-17 14:08:07 -07001550 if response:
Jon Hallec3c21e2014-11-10 22:22:37 -05001551 return response
admin2a9548d2014-06-17 14:08:07 -07001552 else:
1553 return main.FALSE
1554 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001555 main.log.error( self.name + ": EOF exception found" )
1556 main.log.error( self.name + ": " + self.handle.before )
admin2a9548d2014-06-17 14:08:07 -07001557 main.cleanup()
1558 main.exit()
adminbae64d82013-08-01 10:50:15 -07001559
Charles Chan029be652015-08-24 01:46:10 +08001560 def assignSwController( self, sw, ip, port="6653", ptcp="" ):
Jon Hall7eb38402015-01-08 17:19:54 -08001561 """
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001562 Description:
1563 Assign switches to the controllers ( for ovs use only )
1564 Required:
1565 sw - Name of the switch. This can be a list or a string.
1566 ip - Ip addresses of controllers. This can be a list or a string.
1567 Optional:
Charles Chan029be652015-08-24 01:46:10 +08001568 port - ONOS use port 6653, if no list of ports is passed, then
1569 the all the controller will use 6653 as their port number
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001570 ptcp - ptcp number, This can be a string or a list that has
1571 the same length as switch. This is optional and not required
1572 when using ovs switches.
1573 NOTE: If switches and ptcp are given in a list type they should have the
1574 same length and should be in the same order, Eg. sw=[ 's1' ... n ]
1575 ptcp=[ '6637' ... n ], s1 has ptcp number 6637 and so on.
Jon Hallf89c8552014-04-02 13:14:06 -07001576
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001577 Return:
1578 Returns main.TRUE if mininet correctly assigned switches to
1579 controllers, otherwise it will return main.FALSE or an appropriate
1580 exception(s)
1581 """
1582 assignResult = main.TRUE
1583 # Initial ovs command
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001584 commandList = []
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001585 command = "sh ovs-vsctl set-controller "
1586 onosIp = ""
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001587 try:
1588 if isinstance( ip, types.StringType ):
kelvin-onlabf713d7c2015-06-11 14:29:05 -07001589 onosIp = "tcp:" + str( ip ) + ":"
kelvin-onlab5c2df432015-06-11 17:29:56 -07001590 if isinstance( port, types.StringType ) or \
1591 isinstance( port, types.IntType ):
kelvin-onlabf713d7c2015-06-11 14:29:05 -07001592 onosIp += str( port )
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001593 elif isinstance( port, types.ListType ):
1594 main.log.error( self.name + ": Only one controller " +
1595 "assigned and a list of ports has" +
1596 " been passed" )
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001597 return main.FALSE
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001598 else:
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001599 main.log.error( self.name + ": Invalid controller port " +
1600 "number. Please specify correct " +
1601 "controller port" )
1602 return main.FALSE
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001603
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001604 elif isinstance( ip, types.ListType ):
kelvin-onlab5c2df432015-06-11 17:29:56 -07001605 if isinstance( port, types.StringType ) or \
1606 isinstance( port, types.IntType ):
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001607 for ipAddress in ip:
kelvin-onlabf713d7c2015-06-11 14:29:05 -07001608 onosIp += "tcp:" + str( ipAddress ) + ":" + \
1609 str( port ) + " "
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001610 elif isinstance( port, types.ListType ):
1611 if ( len( ip ) != len( port ) ):
1612 main.log.error( self.name + ": Port list = " +
1613 str( len( port ) ) +
1614 "should be the same as controller" +
1615 " ip list = " + str( len( ip ) ) )
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001616 return main.FALSE
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001617 else:
1618 onosIp = ""
1619 for ipAddress, portNum in zip( ip, port ):
kelvin-onlabf713d7c2015-06-11 14:29:05 -07001620 onosIp += "tcp:" + str( ipAddress ) + ":" + \
1621 str( portNum ) + " "
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001622 else:
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001623 main.log.error( self.name + ": Invalid controller port " +
1624 "number. Please specify correct " +
1625 "controller port" )
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001626 return main.FALSE
kelvin-onlabe5edb9e2015-06-12 09:38:47 -07001627 else:
1628 main.log.error( self.name + ": Invalid ip address" )
1629 return main.FALSE
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001630
1631 if isinstance( sw, types.StringType ):
1632 command += sw + " "
1633 if ptcp:
1634 if isinstance( ptcp, types.StringType ):
kelvin-onlabf713d7c2015-06-11 14:29:05 -07001635 command += "ptcp:" + str( ptcp ) + " "
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001636 elif isinstance( ptcp, types.ListType ):
1637 main.log.error( self.name + ": Only one switch is " +
1638 "being set and multiple PTCP is " +
1639 "being passed " )
1640 else:
1641 main.log.error( self.name + ": Invalid PTCP" )
1642 ptcp = ""
1643 command += onosIp
1644 commandList.append( command )
1645
1646 elif isinstance( sw, types.ListType ):
1647 if ptcp:
1648 if isinstance( ptcp, types.ListType ):
1649 if len( ptcp ) != len( sw ):
1650 main.log.error( self.name + ": PTCP length = " +
1651 str( len( ptcp ) ) +
1652 " is not the same as switch" +
1653 " length = " +
1654 str( len( sw ) ) )
1655 return main.FALSE
1656 else:
1657 for switch, ptcpNum in zip( sw, ptcp ):
1658 tempCmd = "sh ovs-vsctl set-controller "
kelvin-onlabf713d7c2015-06-11 14:29:05 -07001659 tempCmd += switch + " ptcp:" + \
Jon Halld80cc142015-07-06 13:36:05 -07001660 str( ptcpNum ) + " "
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001661 tempCmd += onosIp
1662 commandList.append( tempCmd )
1663 else:
1664 main.log.error( self.name + ": Invalid PTCP" )
1665 return main.FALSE
1666 else:
1667 for switch in sw:
1668 tempCmd = "sh ovs-vsctl set-controller "
1669 tempCmd += switch + " " + onosIp
1670 commandList.append( tempCmd )
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001671 else:
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001672 main.log.error( self.name + ": Invalid switch type " )
1673 return main.FALSE
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001674
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001675 for cmd in commandList:
1676 try:
kelvin-onlabfa6ada82015-06-11 13:06:24 -07001677 self.execute( cmd=cmd, prompt="mininet>", timeout=5 )
kelvin-onlab4f9f7e02015-06-11 14:07:20 -07001678 except pexpect.TIMEOUT:
1679 main.log.error( self.name + ": pexpect.TIMEOUT found" )
1680 return main.FALSE
1681 except pexpect.EOF:
1682 main.log.error( self.name + ": EOF exception found" )
1683 main.log.error( self.name + ": " + self.handle.before )
1684 main.cleanup()
1685 main.exit()
1686 return main.TRUE
1687 except Exception:
1688 main.log.exception( self.name + ": Uncaught exception!" )
1689 main.cleanup()
1690 main.exit()
adminbae64d82013-08-01 10:50:15 -07001691
kelvin-onlabd3b64892015-01-20 13:26:24 -08001692 def deleteSwController( self, sw ):
Jon Hall7eb38402015-01-08 17:19:54 -08001693 """
1694 Removes the controller target from sw"""
1695 command = "sh ovs-vsctl del-controller " + str( sw )
Jon Hall0819fd92014-05-23 12:08:13 -07001696 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001697 response = self.execute(
1698 cmd=command,
1699 prompt="mininet>",
1700 timeout=10 )
Jon Hallfbc828e2015-01-06 17:30:19 -08001701 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001702 main.log.error( self.name + ": EOF exception found" )
1703 main.log.error( self.name + ": " + self.handle.before )
Jon Hall0819fd92014-05-23 12:08:13 -07001704 main.cleanup()
1705 main.exit()
1706 else:
Jon Hall7eb38402015-01-08 17:19:54 -08001707 main.log.info( response )
Jon Hall0819fd92014-05-23 12:08:13 -07001708
kelvin-onlabd3b64892015-01-20 13:26:24 -08001709 def addSwitch( self, sw, **kwargs ):
Jon Hall7eb38402015-01-08 17:19:54 -08001710 """
Jon Hallb1290e82014-11-18 16:17:48 -05001711 adds a switch to the mininet topology
Jon Hallbe6dfc42015-01-12 17:37:25 -08001712 NOTE: This uses a custom mn function. MN repo should be on
Jon Hall272a4db2015-01-12 17:43:48 -08001713 dynamic_topo branch
Jon Hallb1290e82014-11-18 16:17:48 -05001714 NOTE: cannot currently specify what type of switch
1715 required params:
Jon Hallefbd9792015-03-05 16:11:36 -08001716 sw = name of the new switch as a string
1717 optional keywords:
Jon Hallb1290e82014-11-18 16:17:48 -05001718 dpid = "dpid"
Jon Hallefbd9792015-03-05 16:11:36 -08001719 returns: main.FALSE on an error, else main.TRUE
Jon Hall7eb38402015-01-08 17:19:54 -08001720 """
1721 dpid = kwargs.get( 'dpid', '' )
Jon Hallffb386d2014-11-21 13:43:38 -08001722 command = "addswitch " + str( sw ) + " " + str( dpid )
Jon Hallb1290e82014-11-18 16:17:48 -05001723 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001724 response = self.execute(
1725 cmd=command,
1726 prompt="mininet>",
1727 timeout=10 )
1728 if re.search( "already exists!", response ):
1729 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001730 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001731 elif re.search( "Error", response ):
1732 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001733 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001734 elif re.search( "usage:", response ):
1735 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001736 return main.FALSE
1737 else:
1738 return main.TRUE
1739 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001740 main.log.error( self.name + ": EOF exception found" )
Jon Halld80cc142015-07-06 13:36:05 -07001741 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -05001742 main.cleanup()
1743 main.exit()
1744
kelvin-onlabd3b64892015-01-20 13:26:24 -08001745 def delSwitch( self, sw ):
Jon Hall7eb38402015-01-08 17:19:54 -08001746 """
Jon Hallbe6dfc42015-01-12 17:37:25 -08001747 delete a switch from the mininet topology
1748 NOTE: This uses a custom mn function. MN repo should be on
Jon Hall272a4db2015-01-12 17:43:48 -08001749 dynamic_topo branch
Jon Hallbe6dfc42015-01-12 17:37:25 -08001750 required params:
Jon Hallefbd9792015-03-05 16:11:36 -08001751 sw = name of the switch as a string
1752 returns: main.FALSE on an error, else main.TRUE"""
Jon Hallffb386d2014-11-21 13:43:38 -08001753 command = "delswitch " + str( sw )
Jon Hallb1290e82014-11-18 16:17:48 -05001754 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001755 response = self.execute(
1756 cmd=command,
1757 prompt="mininet>",
1758 timeout=10 )
1759 if re.search( "no switch named", response ):
1760 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001761 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001762 elif re.search( "Error", response ):
1763 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001764 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001765 elif re.search( "usage:", response ):
1766 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001767 return main.FALSE
1768 else:
1769 return main.TRUE
1770 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001771 main.log.error( self.name + ": EOF exception found" )
1772 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -05001773 main.cleanup()
1774 main.exit()
1775
kelvin-onlabd3b64892015-01-20 13:26:24 -08001776 def addLink( self, node1, node2 ):
Jon Hall7eb38402015-01-08 17:19:54 -08001777 """
1778 add a link to the mininet topology
Jon Hallbe6dfc42015-01-12 17:37:25 -08001779 NOTE: This uses a custom mn function. MN repo should be on
Jon Hall272a4db2015-01-12 17:43:48 -08001780 dynamic_topo branch
Jon Hall7eb38402015-01-08 17:19:54 -08001781 NOTE: cannot currently specify what type of link
1782 required params:
1783 node1 = the string node name of the first endpoint of the link
1784 node2 = the string node name of the second endpoint of the link
Jon Hallefbd9792015-03-05 16:11:36 -08001785 returns: main.FALSE on an error, else main.TRUE"""
Jon Hallffb386d2014-11-21 13:43:38 -08001786 command = "addlink " + str( node1 ) + " " + str( node2 )
Jon Hallb1290e82014-11-18 16:17:48 -05001787 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001788 response = self.execute(
1789 cmd=command,
1790 prompt="mininet>",
1791 timeout=10 )
1792 if re.search( "doesnt exist!", response ):
1793 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001794 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001795 elif re.search( "Error", response ):
1796 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001797 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001798 elif re.search( "usage:", response ):
1799 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001800 return main.FALSE
1801 else:
1802 return main.TRUE
1803 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001804 main.log.error( self.name + ": EOF exception found" )
1805 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -05001806 main.cleanup()
1807 main.exit()
1808
kelvin-onlabd3b64892015-01-20 13:26:24 -08001809 def delLink( self, node1, node2 ):
Jon Hall7eb38402015-01-08 17:19:54 -08001810 """
1811 delete a link from the mininet topology
Jon Hallbe6dfc42015-01-12 17:37:25 -08001812 NOTE: This uses a custom mn function. MN repo should be on
Jon Hall272a4db2015-01-12 17:43:48 -08001813 dynamic_topo branch
Jon Hall7eb38402015-01-08 17:19:54 -08001814 required params:
1815 node1 = the string node name of the first endpoint of the link
1816 node2 = the string node name of the second endpoint of the link
Jon Hallefbd9792015-03-05 16:11:36 -08001817 returns: main.FALSE on an error, else main.TRUE"""
Jon Hallffb386d2014-11-21 13:43:38 -08001818 command = "dellink " + str( node1 ) + " " + str( node2 )
Jon Hallb1290e82014-11-18 16:17:48 -05001819 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001820 response = self.execute(
1821 cmd=command,
1822 prompt="mininet>",
1823 timeout=10 )
1824 if re.search( "no node named", response ):
1825 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001826 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001827 elif re.search( "Error", response ):
1828 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001829 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001830 elif re.search( "usage:", response ):
1831 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001832 return main.FALSE
1833 else:
1834 return main.TRUE
1835 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001836 main.log.error( self.name + ": EOF exception found" )
1837 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -05001838 main.cleanup()
1839 main.exit()
1840
kelvin-onlabd3b64892015-01-20 13:26:24 -08001841 def addHost( self, hostname, **kwargs ):
Jon Hall7eb38402015-01-08 17:19:54 -08001842 """
Jon Hallb1290e82014-11-18 16:17:48 -05001843 Add a host to the mininet topology
Jon Hallbe6dfc42015-01-12 17:37:25 -08001844 NOTE: This uses a custom mn function. MN repo should be on
Jon Hall272a4db2015-01-12 17:43:48 -08001845 dynamic_topo branch
Jon Hallb1290e82014-11-18 16:17:48 -05001846 NOTE: cannot currently specify what type of host
1847 required params:
1848 hostname = the string hostname
1849 optional key-value params
1850 switch = "switch name"
Jon Hallefbd9792015-03-05 16:11:36 -08001851 returns: main.FALSE on an error, else main.TRUE
Jon Hall7eb38402015-01-08 17:19:54 -08001852 """
1853 switch = kwargs.get( 'switch', '' )
Jon Hallffb386d2014-11-21 13:43:38 -08001854 command = "addhost " + str( hostname ) + " " + str( switch )
Jon Hallb1290e82014-11-18 16:17:48 -05001855 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001856 response = self.execute(
1857 cmd=command,
1858 prompt="mininet>",
1859 timeout=10 )
1860 if re.search( "already exists!", response ):
1861 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001862 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001863 elif re.search( "doesnt exists!", response ):
1864 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001865 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001866 elif re.search( "Error", response ):
1867 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001868 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001869 elif re.search( "usage:", response ):
1870 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001871 return main.FALSE
1872 else:
1873 return main.TRUE
1874 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001875 main.log.error( self.name + ": EOF exception found" )
1876 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -05001877 main.cleanup()
1878 main.exit()
1879
kelvin-onlabd3b64892015-01-20 13:26:24 -08001880 def delHost( self, hostname ):
Jon Hall7eb38402015-01-08 17:19:54 -08001881 """
1882 delete a host from the mininet topology
Jon Hallbe6dfc42015-01-12 17:37:25 -08001883 NOTE: This uses a custom mn function. MN repo should be on
Jon Hall272a4db2015-01-12 17:43:48 -08001884 dynamic_topo branch
Jon Hall7eb38402015-01-08 17:19:54 -08001885 NOTE: this uses a custom mn function
1886 required params:
1887 hostname = the string hostname
Jon Hallefbd9792015-03-05 16:11:36 -08001888 returns: main.FALSE on an error, else main.TRUE"""
Jon Hallffb386d2014-11-21 13:43:38 -08001889 command = "delhost " + str( hostname )
Jon Hallb1290e82014-11-18 16:17:48 -05001890 try:
Jon Hall7eb38402015-01-08 17:19:54 -08001891 response = self.execute(
1892 cmd=command,
1893 prompt="mininet>",
1894 timeout=10 )
1895 if re.search( "no host named", response ):
1896 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001897 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001898 elif re.search( "Error", response ):
1899 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001900 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08001901 elif re.search( "usage:", response ):
1902 main.log.warn( response )
Jon Hallb1290e82014-11-18 16:17:48 -05001903 return main.FALSE
1904 else:
1905 return main.TRUE
1906 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001907 main.log.error( self.name + ": EOF exception found" )
1908 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -05001909 main.cleanup()
1910 main.exit()
Jon Hall0819fd92014-05-23 12:08:13 -07001911
Jon Hall7eb38402015-01-08 17:19:54 -08001912 def disconnect( self ):
kelvin-onlaba1484582015-02-02 15:46:20 -08001913 """
kelvin-onlab00ac67b2015-02-04 09:52:02 -08001914 Called at the end of the test to stop the mininet and
1915 disconnect the handle.
kelvin-onlaba1484582015-02-02 15:46:20 -08001916 """
Jon Halld80cc142015-07-06 13:36:05 -07001917 self.handle.sendline( '' )
Jon Halld61331b2015-02-17 16:35:47 -08001918 i = self.handle.expect( [ 'mininet>', pexpect.EOF, pexpect.TIMEOUT ],
Jon Halld80cc142015-07-06 13:36:05 -07001919 timeout=2 )
Jon Hall390696c2015-05-05 17:13:41 -07001920 response = main.TRUE
kelvin-onlaba1484582015-02-02 15:46:20 -08001921 if i == 0:
Jon Hall390696c2015-05-05 17:13:41 -07001922 response = self.stopNet()
Jon Halld61331b2015-02-17 16:35:47 -08001923 elif i == 1:
1924 return main.TRUE
kelvin-onlaba1484582015-02-02 15:46:20 -08001925 # print "Disconnecting Mininet"
1926 if self.handle:
1927 self.handle.sendline( "exit" )
1928 self.handle.expect( "exit" )
1929 self.handle.expect( "(.*)" )
kelvin-onlaba1484582015-02-02 15:46:20 -08001930 else:
1931 main.log.error( "Connection failed to the host" )
kelvin-onlaba1484582015-02-02 15:46:20 -08001932 return response
1933
Jon Halld80cc142015-07-06 13:36:05 -07001934 def stopNet( self, fileName="", timeout=5 ):
kelvin-onlab00ac67b2015-02-04 09:52:02 -08001935 """
Jon Hall21270ac2015-02-16 17:59:55 -08001936 Stops mininet.
Jon Hallefbd9792015-03-05 16:11:36 -08001937 Returns main.TRUE if the mininet successfully stops and
Jon Hall21270ac2015-02-16 17:59:55 -08001938 main.FALSE if the pexpect handle does not exist.
1939
Jon Halld61331b2015-02-17 16:35:47 -08001940 Will cleanup and exit the test if mininet fails to stop
kelvin-onlab00ac67b2015-02-04 09:52:02 -08001941 """
Jon Halld61331b2015-02-17 16:35:47 -08001942 main.log.info( self.name + ": Stopping mininet..." )
adminbae64d82013-08-01 10:50:15 -07001943 response = ''
1944 if self.handle:
Jon Hall6094a362014-04-11 14:46:56 -07001945 try:
Jon Halld80cc142015-07-06 13:36:05 -07001946 self.handle.sendline( "" )
kelvin-onlab56a3f462015-02-06 14:04:43 -08001947 i = self.handle.expect( [ 'mininet>',
1948 '\$',
1949 pexpect.EOF,
1950 pexpect.TIMEOUT ],
1951 timeout )
1952 if i == 0:
1953 main.log.info( "Exiting mininet..." )
Jeremyd9e4eb12016-04-13 12:09:06 -07001954 response = self.execute( cmd="exit",
1955 prompt="(.*)",
1956 timeout=120 )
1957 main.log.info( self.name + ": Stopped" )
1958 self.handle.sendline( "sudo mn -c" )
1959 response = main.TRUE
Jon Hallafa8a472015-06-12 14:02:42 -07001960
Jeremyd9e4eb12016-04-13 12:09:06 -07001961 elif i == 1:
kelvin-onlab56a3f462015-02-06 14:04:43 -08001962 main.log.info( " Mininet trying to exit while not " +
1963 "in the mininet prompt" )
1964 elif i == 2:
1965 main.log.error( "Something went wrong exiting mininet" )
1966 elif i == 3: # timeout
1967 main.log.error( "Something went wrong exiting mininet " +
1968 "TIMEOUT" )
Jon Hallafa8a472015-06-12 14:02:42 -07001969
Hari Krishnab35c6d02015-03-18 11:13:51 -07001970 if fileName:
Jon Halld80cc142015-07-06 13:36:05 -07001971 self.handle.sendline( "" )
1972 self.handle.expect( '\$' )
1973 self.handle.sendline(
1974 "sudo kill -9 \`ps -ef | grep \"" +
1975 fileName +
1976 "\" | grep -v grep | awk '{print $2}'\`" )
Jon Hallfbc828e2015-01-06 17:30:19 -08001977 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08001978 main.log.error( self.name + ": EOF exception found" )
1979 main.log.error( self.name + ": " + self.handle.before )
Jon Hall6094a362014-04-11 14:46:56 -07001980 main.cleanup()
1981 main.exit()
Jon Hall7eb38402015-01-08 17:19:54 -08001982 else:
1983 main.log.error( self.name + ": Connection failed to the host" )
adminbae64d82013-08-01 10:50:15 -07001984 response = main.FALSE
Jon Hallfbc828e2015-01-06 17:30:19 -08001985 return response
1986
Jon Halla5cb3412015-08-18 14:08:22 -07001987 def arping( self, srcHost="", dstHost="10.128.20.211", ethDevice="" ):
kelvin-onlab65782a82015-05-07 14:12:13 -07001988 """
1989 Description:
1990 Sends arp message from mininet host for hosts discovery
1991 Required:
1992 host - hosts name
1993 Optional:
1994 ip - ip address that does not exist in the network so there would
1995 be no reply.
1996 """
kelvin-onlabf0594d72015-05-19 17:25:12 -07001997 if ethDevice:
1998 ethDevice = '-I ' + ethDevice + ' '
Jon Halla5cb3412015-08-18 14:08:22 -07001999 cmd = srcHost + " arping -c1 " + ethDevice + dstHost
admin07529932013-11-22 14:58:28 -08002000 try:
Jon Halla5cb3412015-08-18 14:08:22 -07002001 main.log.info( "Sending: " + cmd )
kelvin-onlab65782a82015-05-07 14:12:13 -07002002 self.handle.sendline( cmd )
Jon Halla5cb3412015-08-18 14:08:22 -07002003 i = self.handle.expect( [ "mininet>", "arping: " ] )
2004 if i == 0:
2005 return main.TRUE
2006 elif i == 1:
2007 response = self.handle.before + self.handle.after
2008 self.handle.expect( "mininet>" )
2009 response += self.handle.before + self.handle.after
2010 main.log.warn( "Error sending arping, output was: " +
2011 response )
2012 return main.FALSE
2013 except pexpect.TIMEOUT:
2014 main.log.error( self.name + ": TIMEOUT exception found" )
2015 main.log.warn( self.handle.before )
2016 return main.FALSE
kelvin-onlab65782a82015-05-07 14:12:13 -07002017 except pexpect.EOF:
2018 main.log.error( self.name + ": EOF exception found" )
2019 main.log.error( self.name + ": " + self.handle.before )
2020 main.cleanup()
2021 main.exit()
admin07529932013-11-22 14:58:28 -08002022
Jon Hall7eb38402015-01-08 17:19:54 -08002023 def decToHex( self, num ):
2024 return hex( num ).split( 'x' )[ 1 ]
Jon Hallfbc828e2015-01-06 17:30:19 -08002025
Jon Hall7eb38402015-01-08 17:19:54 -08002026 def getSwitchFlowCount( self, switch ):
2027 """
2028 return the Flow Count of the switch"""
admin2a9548d2014-06-17 14:08:07 -07002029 if self.handle:
2030 cmd = "sh ovs-ofctl dump-aggregate %s" % switch
2031 try:
Jon Hall7eb38402015-01-08 17:19:54 -08002032 response = self.execute(
2033 cmd=cmd,
2034 prompt="mininet>",
2035 timeout=10 )
admin2a9548d2014-06-17 14:08:07 -07002036 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08002037 main.log.error( self.name + ": EOF exception found" )
2038 main.log.error( self.name + " " + self.handle.before )
admin2a9548d2014-06-17 14:08:07 -07002039 main.cleanup()
2040 main.exit()
2041 pattern = "flow_count=(\d+)"
Jon Hall7eb38402015-01-08 17:19:54 -08002042 result = re.search( pattern, response, re.MULTILINE )
admin2a9548d2014-06-17 14:08:07 -07002043 if result is None:
Jon Hall7eb38402015-01-08 17:19:54 -08002044 main.log.info(
2045 "Couldn't find flows on switch %s, found: %s" %
2046 ( switch, response ) )
admin2a9548d2014-06-17 14:08:07 -07002047 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08002048 return result.group( 1 )
admin2a9548d2014-06-17 14:08:07 -07002049 else:
Jon Hall7eb38402015-01-08 17:19:54 -08002050 main.log.error( "Connection failed to the Mininet host" )
Jon Hallfbc828e2015-01-06 17:30:19 -08002051
Jon Hall9ed8f372016-02-24 17:34:07 -08002052 def checkFlows( self, sw, dumpFormat=None ):
2053 if dumpFormat:
2054 command = "sh ovs-ofctl -F " + \
2055 dumpFormat + " dump-flows " + str( sw )
2056 else:
2057 command = "sh ovs-ofctl dump-flows " + str( sw )
2058 try:
2059 response = self.execute(
2060 cmd=command,
2061 prompt="mininet>",
2062 timeout=10 )
2063 return response
2064 except pexpect.EOF:
2065 main.log.error( self.name + ": EOF exception found" )
2066 main.log.error( self.name + ": " + self.handle.before )
2067 main.cleanup()
2068 main.exit()
2069
GlennRC68467eb2015-11-16 18:01:01 -08002070 def flowTableComp( self, flowTable1, flowTable2 ):
2071 # This function compares the selctors and treatments of each flow
2072 try:
Jon Hall41d39f12016-04-11 22:54:35 -07002073 returnValue = main.TRUE
GlennRC68467eb2015-11-16 18:01:01 -08002074 if len(flowTable1) != len(flowTable2):
2075 main.log.warn( "Flow table lengths do not match" )
Jon Hall41d39f12016-04-11 22:54:35 -07002076 returnValue = main.FALSE
GlennRCfa65fce2015-12-16 13:16:08 -08002077 dFields = ["n_bytes", "cookie", "n_packets", "duration"]
2078 for flow1, flow2 in zip(flowTable1, flowTable2):
Jon Hallacd1b182015-12-17 11:43:20 -08002079 for field in dFields:
2080 try:
2081 flow1.pop( field )
Jon Hall41d39f12016-04-11 22:54:35 -07002082 except KeyError:
2083 pass
Jon Hallacd1b182015-12-17 11:43:20 -08002084 try:
2085 flow2.pop( field )
Jon Hall41d39f12016-04-11 22:54:35 -07002086 except KeyError:
2087 pass
GlennRC68467eb2015-11-16 18:01:01 -08002088 for i in range( len(flowTable1) ):
GlennRC17bbcf52015-12-14 17:31:50 -08002089 if flowTable1[i] not in flowTable2:
2090 main.log.warn( "Flow tables do not match:" )
2091 main.log.warn( "Old flow:\n{}\n not in new flow table".format( flowTable1[i] ) )
Jon Hall41d39f12016-04-11 22:54:35 -07002092 returnValue = main.FALSE
2093 break
2094 return returnValue
GlennRC68467eb2015-11-16 18:01:01 -08002095 except Exception:
2096 main.log.exception( "Uncaught exception!" )
2097 main.cleanup()
2098 main.exit()
Jon Hall9043c902015-07-30 14:23:44 -07002099
GlennRC528ad292015-11-12 10:38:18 -08002100 def parseFlowTable( self, flowTable, version="", debug=True ):
GlennRC956ea742015-11-05 16:14:15 -08002101 '''
2102 Discription: Parses flows into json format.
2103 NOTE: this can parse any string thats separated with commas
2104 Arguments:
2105 Required:
2106 flows: a list of strings that represnt flows
2107 Optional:
2108 version: The version of OpenFlow. Currently, 1.3 and 1.0 are supported.
2109 debug: prints out the final result
2110 returns: A list of flows in json format
2111 '''
GlennRC528ad292015-11-12 10:38:18 -08002112 jsonFlowTable = []
2113 for flow in flowTable:
GlennRC956ea742015-11-05 16:14:15 -08002114 jsonFlow = {}
GlennRC528ad292015-11-12 10:38:18 -08002115 # split up the fields of the flow
2116 parsedFlow = flow.split(", ")
2117 # get rid of any spaces in front of the field
2118 for i in range( len(parsedFlow) ):
2119 item = parsedFlow[i]
2120 if item[0] == " ":
2121 parsedFlow[i] = item[1:]
2122 # grab the selector and treatment from the parsed flow
2123 # the last element is the selector and the treatment
2124 temp = parsedFlow.pop(-1)
2125 # split up the selector and the treatment
2126 temp = temp.split(" ")
2127 index = 0
2128 # parse the flags
2129 # NOTE: This only parses one flag
2130 flag = {}
2131 if version == "1.3":
2132 flag = {"flag":[temp[index]]}
2133 index += 1
2134 # the first element is the selector and split it up
2135 sel = temp[index]
2136 index += 1
2137 sel = sel.split(",")
2138 # the priority is stuck in the selecter so put it back
2139 # in the flow
2140 parsedFlow.append(sel.pop(0))
2141 # parse selector
2142 criteria = []
2143 for item in sel:
2144 # this is the type of the packet e.g. "arp"
2145 if "=" not in item:
2146 criteria.append( {"type":item} )
2147 else:
2148 field = item.split("=")
2149 criteria.append( {field[0]:field[1]} )
GlennRC68467eb2015-11-16 18:01:01 -08002150 selector = {"selector": {"criteria":sorted(criteria)} }
GlennRC528ad292015-11-12 10:38:18 -08002151 treat = temp[index]
2152 # get rid of the action part e.g. "action=output:2"
2153 # we will add it back later
2154 treat = treat.split("=")
2155 treat.pop(0)
2156 # parse treatment
2157 action = []
2158 for item in treat:
2159 field = item.split(":")
2160 action.append( {field[0]:field[1]} )
2161 # create the treatment field and add the actions
GlennRC68467eb2015-11-16 18:01:01 -08002162 treatment = {"treatment": {"action":sorted(action)} }
GlennRC528ad292015-11-12 10:38:18 -08002163 # parse the rest of the flow
2164 for item in parsedFlow:
2165 field = item.split("=")
2166 jsonFlow.update( {field[0]:field[1]} )
2167 # add the treatment and the selector to the json flow
2168 jsonFlow.update( selector )
2169 jsonFlow.update( treatment )
2170 jsonFlow.update( flag )
GlennRC956ea742015-11-05 16:14:15 -08002171
GlennRC528ad292015-11-12 10:38:18 -08002172 if debug: main.log.debug( "\033[94mJson flow:\033[0m\n{}\n".format(jsonFlow) )
GlennRC956ea742015-11-05 16:14:15 -08002173
GlennRC528ad292015-11-12 10:38:18 -08002174 # add the json flow to the json flow table
2175 jsonFlowTable.append( jsonFlow )
GlennRC956ea742015-11-05 16:14:15 -08002176
GlennRC528ad292015-11-12 10:38:18 -08002177 return jsonFlowTable
2178
Jon Hall0a543792015-12-14 11:00:26 -08002179 def getFlowTable( self, sw, version="", debug=False):
GlennRC956ea742015-11-05 16:14:15 -08002180 '''
2181 Discription: Returns the flow table(s) on a switch or switches in a list.
2182 Each element is a flow.
2183 Arguments:
2184 Required:
2185 sw: The switch name ("s1") to retrive the flow table. Can also be
2186 a list of switches.
2187 Optional:
2188 version: The version of OpenFlow. Currently, 1.3 and 1.0 are supported.
2189 debug: prints out the final result
2190 '''
2191 try:
2192 switches = []
2193 if type(sw) is list:
Jon Hallca7ac292015-11-11 09:28:12 -08002194 switches.extend(sw)
GlennRC956ea742015-11-05 16:14:15 -08002195 else: switches.append(sw)
2196
2197 flows = []
2198 for s in switches:
2199 cmd = "sh ovs-ofctl dump-flows " + s
2200
GlennRC528ad292015-11-12 10:38:18 -08002201 if "1.0" == version:
2202 cmd += " -F OpenFlow10-table_id"
2203 elif "1.3" == version:
GlennRC956ea742015-11-05 16:14:15 -08002204 cmd += " -O OpenFlow13"
GlennRC956ea742015-11-05 16:14:15 -08002205
2206 main.log.info( "Sending: " + cmd )
2207 self.handle.sendline( cmd )
2208 self.handle.expect( "mininet>" )
2209 response = self.handle.before
2210 response = response.split( "\r\n" )
2211 # dump the first two elements and the last
2212 # the first element is the command that was sent
2213 # the second is the table header
2214 # the last element is empty
2215 response = response[2:-1]
2216 flows.extend( response )
2217
2218 if debug: print "Flows:\n{}\n\n".format(flows)
2219
GlennRC528ad292015-11-12 10:38:18 -08002220 return self.parseFlowTable( flows, version, debug )
GlennRC956ea742015-11-05 16:14:15 -08002221
2222 except pexpect.TIMEOUT:
2223 main.log.exception( self.name + ": Command timed out" )
2224 return None
2225 except pexpect.EOF:
2226 main.log.exception( self.name + ": connection closed." )
2227 main.cleanup()
2228 main.exit()
2229 except Exception:
2230 main.log.exception( self.name + ": Uncaught exception!" )
2231 main.cleanup()
2232 main.exit()
2233
2234 def checkFlowId( self, sw, flowId, version="1.3", debug=True ):
2235 '''
2236 Discription: Checks whether the ID provided matches a flow ID in Mininet
2237 Arguments:
2238 Required:
2239 sw: The switch name ("s1") to retrive the flow table. Can also be
2240 a list of switches.
2241 flowId: the flow ID in hex format. Can also be a list of IDs
2242 Optional:
2243 version: The version of OpenFlow. Currently, 1.3 and 1.0 are supported.
2244 debug: prints out the final result
2245 returns: main.TRUE if all IDs are present, otherwise returns main.FALSE
2246 NOTE: prints out IDs that are not present
2247 '''
2248 try:
2249 main.log.info( "Getting flows from Mininet" )
2250 flows = self.getFlowTable( sw, version, debug )
2251
2252 if debug: print "flow ids:\n{}\n\n".format(flowId)
2253
2254 # Check flowId is a list or a string
2255 if type( flowId ) is str:
2256 result = False
2257 for f in flows:
2258 if flowId in f.get( 'cookie' ):
2259 result = True
2260 break
2261 # flowId is a list
2262 else:
2263 result = True
2264 # Get flow IDs from Mininet
2265 mnFlowIds = [ f.get( 'cookie' ) for f in flows ]
2266 # Save the IDs that are not in Mininet
2267 absentIds = [ x for x in flowId if x not in mnFlowIds ]
2268
2269 if debug: print "mn flow ids:\n{}\n\n".format(mnFlowIds)
2270
2271 # Print out the IDs that are not in Mininet
2272 if absentIds:
2273 main.log.warn( "Absent ids: {}".format( absentIds ) )
2274 result = False
2275
2276 return main.TRUE if result else main.FALSE
2277
2278 except Exception:
2279 main.log.exception( self.name + ": Uncaught exception!" )
2280 main.cleanup()
2281 main.exit()
2282
2283
Charles Chan029be652015-08-24 01:46:10 +08002284 def startTcpdump( self, filename, intf="eth0", port="port 6653" ):
Jon Hall7eb38402015-01-08 17:19:54 -08002285 """
Jon Hallefbd9792015-03-05 16:11:36 -08002286 Runs tpdump on an interface and saves the file
Jon Hall7eb38402015-01-08 17:19:54 -08002287 intf can be specified, or the default eth0 is used"""
admin2a9548d2014-06-17 14:08:07 -07002288 try:
Jon Hall7eb38402015-01-08 17:19:54 -08002289 self.handle.sendline( "" )
2290 self.handle.expect( "mininet>" )
2291 self.handle.sendline(
2292 "sh sudo tcpdump -n -i " +
2293 intf +
2294 " " +
2295 port +
2296 " -w " +
2297 filename.strip() +
2298 " &" )
2299 self.handle.sendline( "" )
2300 i = self.handle.expect( [ 'No\ssuch\device',
2301 'listening\son',
2302 pexpect.TIMEOUT,
2303 "mininet>" ],
2304 timeout=10 )
2305 main.log.warn( self.handle.before + self.handle.after )
2306 self.handle.sendline( "" )
2307 self.handle.expect( "mininet>" )
admin2a9548d2014-06-17 14:08:07 -07002308 if i == 0:
Jon Hall7eb38402015-01-08 17:19:54 -08002309 main.log.error(
2310 self.name +
2311 ": tcpdump - No such device exists. " +
2312 "tcpdump attempted on: " +
2313 intf )
admin2a9548d2014-06-17 14:08:07 -07002314 return main.FALSE
2315 elif i == 1:
Jon Hall7eb38402015-01-08 17:19:54 -08002316 main.log.info( self.name + ": tcpdump started on " + intf )
admin2a9548d2014-06-17 14:08:07 -07002317 return main.TRUE
2318 elif i == 2:
Jon Hall7eb38402015-01-08 17:19:54 -08002319 main.log.error(
2320 self.name +
2321 ": tcpdump command timed out! Check interface name," +
2322 " given interface was: " +
2323 intf )
admin2a9548d2014-06-17 14:08:07 -07002324 return main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08002325 elif i == 3:
2326 main.log.info( self.name + ": " + self.handle.before )
admin2a9548d2014-06-17 14:08:07 -07002327 return main.TRUE
2328 else:
Jon Hall7eb38402015-01-08 17:19:54 -08002329 main.log.error( self.name + ": tcpdump - unexpected response" )
admin2a9548d2014-06-17 14:08:07 -07002330 return main.FALSE
2331 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08002332 main.log.error( self.name + ": EOF exception found" )
2333 main.log.error( self.name + ": " + self.handle.before )
admin2a9548d2014-06-17 14:08:07 -07002334 main.cleanup()
2335 main.exit()
Jon Hallfebb1c72015-03-05 13:30:09 -08002336 except Exception:
2337 main.log.exception( self.name + ": Uncaught exception!" )
admin2a9548d2014-06-17 14:08:07 -07002338 main.cleanup()
2339 main.exit()
2340
kelvin-onlabd3b64892015-01-20 13:26:24 -08002341 def stopTcpdump( self ):
Jon Hallefbd9792015-03-05 16:11:36 -08002342 """
2343 pkills tcpdump"""
admin2a9548d2014-06-17 14:08:07 -07002344 try:
Jon Hall7eb38402015-01-08 17:19:54 -08002345 self.handle.sendline( "sh sudo pkill tcpdump" )
2346 self.handle.expect( "mininet>" )
2347 self.handle.sendline( "" )
2348 self.handle.expect( "mininet>" )
admin2a9548d2014-06-17 14:08:07 -07002349 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08002350 main.log.error( self.name + ": EOF exception found" )
2351 main.log.error( self.name + ": " + self.handle.before )
admin2a9548d2014-06-17 14:08:07 -07002352 main.cleanup()
2353 main.exit()
Jon Hallfebb1c72015-03-05 13:30:09 -08002354 except Exception:
2355 main.log.exception( self.name + ": Uncaught exception!" )
admin2a9548d2014-06-17 14:08:07 -07002356 main.cleanup()
2357 main.exit()
2358
Jon Halld80cc142015-07-06 13:36:05 -07002359 def getPorts( self, nodeName, verbose=False ):
Jon Hallafa8a472015-06-12 14:02:42 -07002360 """
2361 Read ports from a Mininet switch.
2362
2363 Returns a json structure containing information about the
2364 ports of the given switch.
2365 """
2366 response = self.getInterfaces( nodeName )
2367 # TODO: Sanity check on response. log if no such switch exists
2368 ports = []
2369 for line in response.split( "\n" ):
2370 if not line.startswith( "name=" ):
2371 continue
2372 portVars = {}
2373 for var in line.split( "," ):
2374 key, value = var.split( "=" )
2375 portVars[ key ] = value
2376 isUp = portVars.pop( 'enabled', "True" )
2377 isUp = "True" in isUp
2378 if verbose:
2379 main.log.info( "Reading switch port %s(%s)" %
2380 ( portVars[ 'name' ], portVars[ 'mac' ] ) )
2381 mac = portVars[ 'mac' ]
Jon Halld80cc142015-07-06 13:36:05 -07002382 if mac == 'None':
Jon Hallafa8a472015-06-12 14:02:42 -07002383 mac = None
2384 ips = []
2385 ip = portVars[ 'ip' ]
2386 if ip == 'None':
2387 ip = None
2388 ips.append( ip )
2389 name = portVars[ 'name' ]
2390 if name == 'None':
2391 name = None
2392 portRe = r'[^\-]\d\-eth(?P<port>\d+)'
2393 if name == 'lo':
2394 portNo = 0xfffe # TODO: 1.0 value - Should we just return lo?
2395 else:
2396 portNo = re.search( portRe, name ).group( 'port' )
2397 ports.append( { 'of_port': portNo,
2398 'mac': str( mac ).replace( '\'', '' ),
2399 'name': name,
2400 'ips': ips,
2401 'enabled': isUp } )
2402 return ports
2403
Jon Halld80cc142015-07-06 13:36:05 -07002404 def getSwitches( self, verbose=False ):
Jon Hallafa8a472015-06-12 14:02:42 -07002405 """
2406 Read switches from Mininet.
2407
2408 Returns a dictionary whose keys are the switch names and the value is
2409 a dictionary containing information about the switch.
2410 """
Jon Halla22481b2015-07-28 17:46:01 -07002411 # NOTE: To support new Mininet switch classes, just append the new
2412 # class to the switchClasses variable
Jon Hallafa8a472015-06-12 14:02:42 -07002413
Jon Halla22481b2015-07-28 17:46:01 -07002414 # Regex patterns to parse 'dump' output
2415 # Example Switches:
Jon Hallafa8a472015-06-12 14:02:42 -07002416 # <OVSSwitch s1: lo:127.0.0.1,s1-eth1:None,s1-eth2:None,s1-eth3:None pid=5238>
Jon Halld80cc142015-07-06 13:36:05 -07002417 # <OVSSwitch{ 'protocols': 'OpenFlow10' } s1: lo:127.0.0.1,s1-eth1:None,s1-eth2:None pid=25974>
Jon Halla22481b2015-07-28 17:46:01 -07002418 # <OVSSwitchNS s1: lo:127.0.0.1,s1-eth1:None,s1-eth2:None,s1-eth3:None pid=22550>
2419 # <OVSBridge s1: lo:127.0.0.1,s1-eth1:None,s1-eth2:None pid=26830>
2420 # <UserSwitch s1: lo:127.0.0.1,s1-eth1:None,s1-eth2:None pid=14737>
2421 switchClasses = r"(OVSSwitch)|(OVSBridge)|(OVSSwitchNS)|(IVSSwitch)|(LinuxBridge)|(UserSwitch)"
2422 swRE = r"<(?P<class>" + switchClasses + r")" +\
2423 r"(?P<options>\{.*\})?\s" +\
2424 r"(?P<name>[^:]+)\:\s" +\
2425 r"(?P<ports>([^,]+,)*[^,\s]+)" +\
2426 r"\spid=(?P<pid>(\d)+)"
Jon Hallafa8a472015-06-12 14:02:42 -07002427 # Update mn port info
2428 self.update()
Jon Halld80cc142015-07-06 13:36:05 -07002429 output = {}
Jon Hallafa8a472015-06-12 14:02:42 -07002430 dump = self.dump().split( "\n" )
2431 for line in dump:
Jon Halla22481b2015-07-28 17:46:01 -07002432 result = re.search( swRE, line, re.I )
2433 if result:
Jon Hallafa8a472015-06-12 14:02:42 -07002434 name = result.group( 'name' )
2435 dpid = str( self.getSwitchDPID( name ) ).zfill( 16 )
Jon Halla22481b2015-07-28 17:46:01 -07002436 pid = result.group( 'pid' )
2437 swClass = result.group( 'class' )
2438 options = result.group( 'options' )
Jon Hallafa8a472015-06-12 14:02:42 -07002439 if verbose:
2440 main.log.info( "Reading switch %s(%s)" % ( name, dpid ) )
2441 ports = self.getPorts( name )
Jon Halla22481b2015-07-28 17:46:01 -07002442 output[ name ] = { "dpid": dpid,
2443 "ports": ports,
2444 "swClass": swClass,
2445 "pid": pid,
2446 "options": options }
Jon Hallafa8a472015-06-12 14:02:42 -07002447 return output
2448
Jon Halld80cc142015-07-06 13:36:05 -07002449 def getHosts( self, verbose=False ):
Jon Hallafa8a472015-06-12 14:02:42 -07002450 """
2451 Read hosts from Mininet.
2452
2453 Returns a dictionary whose keys are the host names and the value is
2454 a dictionary containing information about the host.
2455 """
2456 # Regex patterns to parse dump output
2457 # Example host: <Host h1: h1-eth0:10.0.0.1 pid=5227>
kelvin-onlab299ab062015-07-15 10:58:27 -07002458 # <Host h1: pid=12725>
2459 # <VLANHost h12: h12-eth0.100.100.100:100.1.0.3 pid=30186>
2460 # <dualStackHost h19: h19-eth0:10.1.0.9 pid=30200>
2461 # <IPv6Host h18: h18-eth0:10.0.0.18 pid=30198>
Jon Hallafa8a472015-06-12 14:02:42 -07002462 # NOTE: Does not correctly match hosts with multi-links
2463 # <Host h2: h2-eth0:10.0.0.2,h2-eth1:10.0.1.2 pid=14386>
2464 # FIXME: Fix that
kelvin-onlabd48a68c2015-07-13 16:01:36 -07002465 hostRE = r"Host\s(?P<name>[^:]+)\:((\s(?P<ifname>[^:]+)\:" +\
Jon Halld80cc142015-07-06 13:36:05 -07002466 "(?P<ip>[^\s]+))|(\s)\spid=(?P<pid>[^>]+))"
Jon Hallafa8a472015-06-12 14:02:42 -07002467 # update mn port info
2468 self.update()
2469 # Get mininet dump
2470 dump = self.dump().split( "\n" )
Jon Hall5b0120a2015-06-12 17:35:53 -07002471 hosts = {}
Jon Hallafa8a472015-06-12 14:02:42 -07002472 for line in dump:
kelvin-onlabd48a68c2015-07-13 16:01:36 -07002473 if "Host" in line :
Jon Hallafa8a472015-06-12 14:02:42 -07002474 result = re.search( hostRE, line )
2475 name = result.group( 'name' )
2476 interfaces = []
2477 response = self.getInterfaces( name )
2478 # Populate interface info
2479 for line in response.split( "\n" ):
2480 if line.startswith( "name=" ):
2481 portVars = {}
2482 for var in line.split( "," ):
2483 key, value = var.split( "=" )
2484 portVars[ key ] = value
2485 isUp = portVars.pop( 'enabled', "True" )
2486 isUp = "True" in isUp
2487 if verbose:
2488 main.log.info( "Reading host port %s(%s)" %
2489 ( portVars[ 'name' ],
2490 portVars[ 'mac' ] ) )
2491 mac = portVars[ 'mac' ]
Jon Halld80cc142015-07-06 13:36:05 -07002492 if mac == 'None':
Jon Hallafa8a472015-06-12 14:02:42 -07002493 mac = None
2494 ips = []
2495 ip = portVars[ 'ip' ]
2496 if ip == 'None':
2497 ip = None
2498 ips.append( ip )
2499 intfName = portVars[ 'name' ]
2500 if name == 'None':
2501 name = None
2502 interfaces.append( {
2503 "name": intfName,
2504 "ips": ips,
2505 "mac": str( mac ),
2506 "isUp": isUp } )
Jon Hall5b0120a2015-06-12 17:35:53 -07002507 hosts[ name ] = { "interfaces": interfaces }
Jon Hallafa8a472015-06-12 14:02:42 -07002508 return hosts
2509
2510 def getLinks( self ):
2511 """
2512 Gathers information about current Mininet links. These links may not
2513 be up if one of the ports is down.
2514
2515 Returns a list of dictionaries with link endpoints.
2516
2517 The dictionary structure is:
Jon Halld80cc142015-07-06 13:36:05 -07002518 { 'node1': str( node1 name )
2519 'node2': str( node2 name )
2520 'port1': str( port1 of_port )
2521 'port2': str( port2 of_port ) }
Jon Hallafa8a472015-06-12 14:02:42 -07002522 Note: The port number returned is the eth#, not necessarily the of_port
2523 number. In Mininet, for OVS switch, these should be the same. For
2524 hosts, this is just the eth#.
2525 """
2526 self.update()
2527 response = self.links().split( '\n' )
2528
2529 # Examples:
2530 # s1-eth3<->s2-eth1 (OK OK)
2531 # s13-eth3<->h27-eth0 (OK OK)
2532 linkRE = "(?P<node1>[\w]+)\-eth(?P<port1>[\d]+)\<\-\>" +\
2533 "(?P<node2>[\w]+)\-eth(?P<port2>[\d]+)"
2534 links = []
2535 for line in response:
2536 match = re.search( linkRE, line )
2537 if match:
2538 node1 = match.group( 'node1' )
2539 node2 = match.group( 'node2' )
2540 port1 = match.group( 'port1' )
2541 port2 = match.group( 'port2' )
2542 links.append( { 'node1': node1,
2543 'node2': node2,
2544 'port1': port1,
2545 'port2': port2 } )
2546 return links
2547
2548 def compareSwitches( self, switches, switchesJson, portsJson ):
Jon Hall7eb38402015-01-08 17:19:54 -08002549 """
2550 Compare mn and onos switches
Jon Hallafa8a472015-06-12 14:02:42 -07002551 switchesJson: parsed json object from the onos devices api
Jon Hall3d87d502014-10-17 18:37:42 -04002552
Jon Hallafa8a472015-06-12 14:02:42 -07002553 Dependencies:
2554 1. numpy - "sudo pip install numpy"
2555 """
2556 from numpy import uint64
Jon Hall3d87d502014-10-17 18:37:42 -04002557 # created sorted list of dpid's in MN and ONOS for comparison
Jon Hall7eb38402015-01-08 17:19:54 -08002558 mnDPIDs = []
Jon Hallafa8a472015-06-12 14:02:42 -07002559 for swName, switch in switches.iteritems():
Jon Hall7eb38402015-01-08 17:19:54 -08002560 mnDPIDs.append( switch[ 'dpid' ].lower() )
Jon Hall3d87d502014-10-17 18:37:42 -04002561 mnDPIDs.sort()
kelvin-onlabd3b64892015-01-20 13:26:24 -08002562 if switchesJson == "": # if rest call fails
Jon Hall7eb38402015-01-08 17:19:54 -08002563 main.log.error(
2564 self.name +
Jon Hallfeff3082015-05-19 10:23:26 -07002565 ".compareSwitches(): Empty JSON object given from ONOS" )
Jon Hall3d87d502014-10-17 18:37:42 -04002566 return main.FALSE
kelvin-onlabd3b64892015-01-20 13:26:24 -08002567 onos = switchesJson
Jon Hall7eb38402015-01-08 17:19:54 -08002568 onosDPIDs = []
Jon Hall3d87d502014-10-17 18:37:42 -04002569 for switch in onos:
Jon Hall7eb38402015-01-08 17:19:54 -08002570 if switch[ 'available' ]:
Jon Halld80cc142015-07-06 13:36:05 -07002571 onosDPIDs.append(
2572 switch[ 'id' ].replace(
2573 ":",
2574 '' ).replace(
2575 "of",
2576 '' ).lower() )
Jon Hall3d87d502014-10-17 18:37:42 -04002577 onosDPIDs.sort()
Jon Hall3d87d502014-10-17 18:37:42 -04002578
Jon Hall7eb38402015-01-08 17:19:54 -08002579 if mnDPIDs != onosDPIDs:
kelvin-onlabd3b64892015-01-20 13:26:24 -08002580 switchResults = main.FALSE
Jon Hallafa8a472015-06-12 14:02:42 -07002581 main.log.error( "Switches in MN but not in ONOS:" )
Jon Hall7eb38402015-01-08 17:19:54 -08002582 list1 = [ switch for switch in mnDPIDs if switch not in onosDPIDs ]
Jon Hallafa8a472015-06-12 14:02:42 -07002583 main.log.error( str( list1 ) )
2584 main.log.error( "Switches in ONOS but not in MN:" )
Jon Hall7eb38402015-01-08 17:19:54 -08002585 list2 = [ switch for switch in onosDPIDs if switch not in mnDPIDs ]
Jon Hallafa8a472015-06-12 14:02:42 -07002586 main.log.error( str( list2 ) )
Jon Hall7eb38402015-01-08 17:19:54 -08002587 else: # list of dpid's match in onos and mn
kelvin-onlabd3b64892015-01-20 13:26:24 -08002588 switchResults = main.TRUE
Jon Hallafa8a472015-06-12 14:02:42 -07002589 finalResults = switchResults
Jon Hall3d87d502014-10-17 18:37:42 -04002590
Jon Hall7eb38402015-01-08 17:19:54 -08002591 # FIXME: this does not look for extra ports in ONOS, only checks that
2592 # ONOS has what is in MN
kelvin-onlabd3b64892015-01-20 13:26:24 -08002593 portsResults = main.TRUE
Jon Hall72cf1dc2014-10-20 21:04:50 -04002594
Jon Hall7eb38402015-01-08 17:19:54 -08002595 # PORTS
Jon Hallafa8a472015-06-12 14:02:42 -07002596 for name, mnSwitch in switches.iteritems():
kelvin-onlabd3b64892015-01-20 13:26:24 -08002597 mnPorts = []
2598 onosPorts = []
2599 switchResult = main.TRUE
2600 for port in mnSwitch[ 'ports' ]:
Jon Hall7eb38402015-01-08 17:19:54 -08002601 if port[ 'enabled' ]:
Jon Hallafa8a472015-06-12 14:02:42 -07002602 mnPorts.append( int( port[ 'of_port' ] ) )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002603 for onosSwitch in portsJson:
kelvin-onlabd3b64892015-01-20 13:26:24 -08002604 if onosSwitch[ 'device' ][ 'available' ]:
Jon Halld80cc142015-07-06 13:36:05 -07002605 if onosSwitch[ 'device' ][ 'id' ].replace(
2606 ':',
2607 '' ).replace(
2608 "of",
2609 '' ) == mnSwitch[ 'dpid' ]:
kelvin-onlabd3b64892015-01-20 13:26:24 -08002610 for port in onosSwitch[ 'ports' ]:
Jon Hall7eb38402015-01-08 17:19:54 -08002611 if port[ 'isEnabled' ]:
2612 if port[ 'port' ] == 'local':
kelvin-onlabd3b64892015-01-20 13:26:24 -08002613 # onosPorts.append( 'local' )
2614 onosPorts.append( long( uint64( -2 ) ) )
Jon Hallb1290e82014-11-18 16:17:48 -05002615 else:
kelvin-onlabd3b64892015-01-20 13:26:24 -08002616 onosPorts.append( int( port[ 'port' ] ) )
Jon Hallb1290e82014-11-18 16:17:48 -05002617 break
kelvin-onlabd3b64892015-01-20 13:26:24 -08002618 mnPorts.sort( key=float )
2619 onosPorts.sort( key=float )
Jon Hallafa8a472015-06-12 14:02:42 -07002620
kelvin-onlabd3b64892015-01-20 13:26:24 -08002621 mnPortsLog = mnPorts
2622 onosPortsLog = onosPorts
2623 mnPorts = [ x for x in mnPorts ]
2624 onosPorts = [ x for x in onosPorts ]
Jon Hall38481722014-11-04 16:50:05 -05002625
Jon Hall7eb38402015-01-08 17:19:54 -08002626 # TODO: handle other reserved port numbers besides LOCAL
2627 # NOTE: Reserved ports
2628 # Local port: -2 in Openflow, ONOS shows 'local', we store as
2629 # long( uint64( -2 ) )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002630 for mnPort in mnPortsLog:
2631 if mnPort in onosPorts:
Jon Hall7eb38402015-01-08 17:19:54 -08002632 # don't set results to true here as this is just one of
2633 # many checks and it might override a failure
kelvin-onlabd3b64892015-01-20 13:26:24 -08002634 mnPorts.remove( mnPort )
2635 onosPorts.remove( mnPort )
Jon Hallafa8a472015-06-12 14:02:42 -07002636
Jon Hall7eb38402015-01-08 17:19:54 -08002637 # NOTE: OVS reports this as down since there is no link
Jon Hallb1290e82014-11-18 16:17:48 -05002638 # So ignoring these for now
Jon Hall7eb38402015-01-08 17:19:54 -08002639 # TODO: Come up with a better way of handling these
kelvin-onlabd3b64892015-01-20 13:26:24 -08002640 if 65534 in mnPorts:
2641 mnPorts.remove( 65534 )
2642 if long( uint64( -2 ) ) in onosPorts:
2643 onosPorts.remove( long( uint64( -2 ) ) )
2644 if len( mnPorts ): # the ports of this switch don't match
2645 switchResult = main.FALSE
2646 main.log.warn( "Ports in MN but not ONOS: " + str( mnPorts ) )
2647 if len( onosPorts ): # the ports of this switch don't match
2648 switchResult = main.FALSE
Jon Hall7eb38402015-01-08 17:19:54 -08002649 main.log.warn(
2650 "Ports in ONOS but not MN: " +
kelvin-onlabd3b64892015-01-20 13:26:24 -08002651 str( onosPorts ) )
2652 if switchResult == main.FALSE:
Jon Hallafa8a472015-06-12 14:02:42 -07002653 main.log.error(
Jon Hall7eb38402015-01-08 17:19:54 -08002654 "The list of ports for switch %s(%s) does not match:" %
Jon Hallafa8a472015-06-12 14:02:42 -07002655 ( name, mnSwitch[ 'dpid' ] ) )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002656 main.log.warn( "mn_ports[] = " + str( mnPortsLog ) )
2657 main.log.warn( "onos_ports[] = " + str( onosPortsLog ) )
2658 portsResults = portsResults and switchResult
Jon Hallafa8a472015-06-12 14:02:42 -07002659 finalResults = finalResults and portsResults
2660 return finalResults
Jon Hall72cf1dc2014-10-20 21:04:50 -04002661
Jon Hallafa8a472015-06-12 14:02:42 -07002662 def compareLinks( self, switches, links, linksJson ):
Jon Hall7eb38402015-01-08 17:19:54 -08002663 """
2664 Compare mn and onos links
kelvin-onlabd3b64892015-01-20 13:26:24 -08002665 linksJson: parsed json object from the onos links api
Jon Hall72cf1dc2014-10-20 21:04:50 -04002666
Jon Hallafa8a472015-06-12 14:02:42 -07002667 """
Jon Hall7eb38402015-01-08 17:19:54 -08002668 # FIXME: this does not look for extra links in ONOS, only checks that
Jon Hallefbd9792015-03-05 16:11:36 -08002669 # ONOS has what is in MN
kelvin-onlabd3b64892015-01-20 13:26:24 -08002670 onos = linksJson
Jon Hall72cf1dc2014-10-20 21:04:50 -04002671
Jon Halld80cc142015-07-06 13:36:05 -07002672 mnLinks = []
Jon Hallafa8a472015-06-12 14:02:42 -07002673 for l in links:
2674 try:
2675 node1 = switches[ l[ 'node1' ] ]
2676 node2 = switches[ l[ 'node2' ] ]
2677 enabled = True
2678 for port in node1[ 'ports' ]:
2679 if port[ 'of_port' ] == l[ 'port1' ]:
2680 enabled = enabled and port[ 'enabled' ]
2681 for port in node2[ 'ports' ]:
Jon Halld80cc142015-07-06 13:36:05 -07002682 if port[ 'of_port' ] == l[ 'port2' ]:
Jon Hallafa8a472015-06-12 14:02:42 -07002683 enabled = enabled and port[ 'enabled' ]
2684 if enabled:
2685 mnLinks.append( l )
2686 except KeyError:
2687 pass
kelvin-onlabd3b64892015-01-20 13:26:24 -08002688 if 2 * len( mnLinks ) == len( onos ):
2689 linkResults = main.TRUE
Jon Hall72cf1dc2014-10-20 21:04:50 -04002690 else:
kelvin-onlabd3b64892015-01-20 13:26:24 -08002691 linkResults = main.FALSE
Jon Hallafa8a472015-06-12 14:02:42 -07002692 main.log.error(
Jon Hall328ddca2015-01-28 15:57:15 -08002693 "Mininet has " + str( len( mnLinks ) ) +
2694 " bidirectional links and ONOS has " +
2695 str( len( onos ) ) + " unidirectional links" )
Jon Hall72cf1dc2014-10-20 21:04:50 -04002696
Jon Hall7eb38402015-01-08 17:19:54 -08002697 # iterate through MN links and check if an ONOS link exists in
2698 # both directions
kelvin-onlabd3b64892015-01-20 13:26:24 -08002699 for link in mnLinks:
Jon Hall7eb38402015-01-08 17:19:54 -08002700 # TODO: Find a more efficient search method
Jon Hall72cf1dc2014-10-20 21:04:50 -04002701 node1 = None
2702 port1 = None
2703 node2 = None
2704 port2 = None
kelvin-onlabd3b64892015-01-20 13:26:24 -08002705 firstDir = main.FALSE
2706 secondDir = main.FALSE
Jon Hallafa8a472015-06-12 14:02:42 -07002707 for swName, switch in switches.iteritems():
2708 if swName == link[ 'node1' ]:
Jon Hall7eb38402015-01-08 17:19:54 -08002709 node1 = switch[ 'dpid' ]
2710 for port in switch[ 'ports' ]:
Jon Hallafa8a472015-06-12 14:02:42 -07002711 if str( port[ 'of_port' ] ) == str( link[ 'port1' ] ):
Jon Hall7eb38402015-01-08 17:19:54 -08002712 port1 = port[ 'of_port' ]
Jon Hall72cf1dc2014-10-20 21:04:50 -04002713 if node1 is not None and node2 is not None:
2714 break
Jon Hallafa8a472015-06-12 14:02:42 -07002715 if swName == link[ 'node2' ]:
Jon Hall7eb38402015-01-08 17:19:54 -08002716 node2 = switch[ 'dpid' ]
2717 for port in switch[ 'ports' ]:
Jon Hallafa8a472015-06-12 14:02:42 -07002718 if str( port[ 'of_port' ] ) == str( link[ 'port2' ] ):
Jon Hall7eb38402015-01-08 17:19:54 -08002719 port2 = port[ 'of_port' ]
Jon Hall72cf1dc2014-10-20 21:04:50 -04002720 if node1 is not None and node2 is not None:
2721 break
2722
kelvin-onlabd3b64892015-01-20 13:26:24 -08002723 for onosLink in onos:
2724 onosNode1 = onosLink[ 'src' ][ 'device' ].replace(
Jon Hallafa8a472015-06-12 14:02:42 -07002725 ":", '' ).replace( "of", '' )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002726 onosNode2 = onosLink[ 'dst' ][ 'device' ].replace(
Jon Hallafa8a472015-06-12 14:02:42 -07002727 ":", '' ).replace( "of", '' )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002728 onosPort1 = onosLink[ 'src' ][ 'port' ]
2729 onosPort2 = onosLink[ 'dst' ][ 'port' ]
Jon Hall72cf1dc2014-10-20 21:04:50 -04002730
Jon Hall72cf1dc2014-10-20 21:04:50 -04002731 # check onos link from node1 to node2
kelvin-onlabd3b64892015-01-20 13:26:24 -08002732 if str( onosNode1 ) == str( node1 ) and str(
2733 onosNode2 ) == str( node2 ):
2734 if int( onosPort1 ) == int( port1 ) and int(
2735 onosPort2 ) == int( port2 ):
2736 firstDir = main.TRUE
Jon Hall72cf1dc2014-10-20 21:04:50 -04002737 else:
Jon Hall7eb38402015-01-08 17:19:54 -08002738 main.log.warn(
2739 'The port numbers do not match for ' +
2740 str( link ) +
Jon Hallefbd9792015-03-05 16:11:36 -08002741 ' between ONOS and MN. When checking ONOS for ' +
Jon Hall7eb38402015-01-08 17:19:54 -08002742 'link %s/%s -> %s/%s' %
Jon Hallafa8a472015-06-12 14:02:42 -07002743 ( node1, port1, node2, port2 ) +
Jon Hall7eb38402015-01-08 17:19:54 -08002744 ' ONOS has the values %s/%s -> %s/%s' %
Jon Hallafa8a472015-06-12 14:02:42 -07002745 ( onosNode1, onosPort1, onosNode2, onosPort2 ) )
Jon Hall72cf1dc2014-10-20 21:04:50 -04002746
2747 # check onos link from node2 to node1
kelvin-onlabd3b64892015-01-20 13:26:24 -08002748 elif ( str( onosNode1 ) == str( node2 ) and
2749 str( onosNode2 ) == str( node1 ) ):
2750 if ( int( onosPort1 ) == int( port2 )
2751 and int( onosPort2 ) == int( port1 ) ):
2752 secondDir = main.TRUE
Jon Hall72cf1dc2014-10-20 21:04:50 -04002753 else:
Jon Hall7eb38402015-01-08 17:19:54 -08002754 main.log.warn(
2755 'The port numbers do not match for ' +
2756 str( link ) +
Jon Hallefbd9792015-03-05 16:11:36 -08002757 ' between ONOS and MN. When checking ONOS for ' +
Jon Hall7eb38402015-01-08 17:19:54 -08002758 'link %s/%s -> %s/%s' %
Jon Hallafa8a472015-06-12 14:02:42 -07002759 ( node1, port1, node2, port2 ) +
Jon Hall7eb38402015-01-08 17:19:54 -08002760 ' ONOS has the values %s/%s -> %s/%s' %
Jon Hallafa8a472015-06-12 14:02:42 -07002761 ( onosNode2, onosPort2, onosNode1, onosPort1 ) )
Jon Hall7eb38402015-01-08 17:19:54 -08002762 else: # this is not the link you're looking for
Jon Hall72cf1dc2014-10-20 21:04:50 -04002763 pass
kelvin-onlabd3b64892015-01-20 13:26:24 -08002764 if not firstDir:
Jon Hallafa8a472015-06-12 14:02:42 -07002765 main.log.error(
Jon Hall7eb38402015-01-08 17:19:54 -08002766 'ONOS does not have the link %s/%s -> %s/%s' %
2767 ( node1, port1, node2, port2 ) )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002768 if not secondDir:
Jon Hallafa8a472015-06-12 14:02:42 -07002769 main.log.error(
Jon Hall7eb38402015-01-08 17:19:54 -08002770 'ONOS does not have the link %s/%s -> %s/%s' %
2771 ( node2, port2, node1, port1 ) )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002772 linkResults = linkResults and firstDir and secondDir
2773 return linkResults
Jon Hall72cf1dc2014-10-20 21:04:50 -04002774
Jon Hallafa8a472015-06-12 14:02:42 -07002775 def compareHosts( self, hosts, hostsJson ):
Jon Hallff6b4b22015-02-23 09:25:15 -08002776 """
Jon Hallafa8a472015-06-12 14:02:42 -07002777 Compare mn and onos Hosts.
2778 Since Mininet hosts are quiet, ONOS will only know of them when they
2779 speak. For this reason, we will only check that the hosts in ONOS
2780 stores are in Mininet, and not vice versa.
Jon Hallff6b4b22015-02-23 09:25:15 -08002781
Jon Hallafa8a472015-06-12 14:02:42 -07002782 Arguments:
2783 hostsJson: parsed json object from the onos hosts api
2784 Returns:
2785 """
Jon Hallff6b4b22015-02-23 09:25:15 -08002786 import json
2787 hostResults = main.TRUE
Jon Hallff6b4b22015-02-23 09:25:15 -08002788 for onosHost in hostsJson:
2789 onosMAC = onosHost[ 'mac' ].lower()
2790 match = False
Jon Halld80cc142015-07-06 13:36:05 -07002791 for mnHost, info in hosts.iteritems():
2792 for mnIntf in info[ 'interfaces' ]:
2793 if onosMAC == mnIntf[ 'mac' ].lower():
Jon Hallff6b4b22015-02-23 09:25:15 -08002794 match = True
2795 for ip in mnIntf[ 'ips' ]:
Jon Hallfeff3082015-05-19 10:23:26 -07002796 if ip in onosHost[ 'ipAddresses' ]:
Jon Hallff6b4b22015-02-23 09:25:15 -08002797 pass # all is well
2798 else:
2799 # misssing ip
Jon Halld80cc142015-07-06 13:36:05 -07002800 main.log.error( "ONOS host " +
2801 onosHost[ 'id' ] +
2802 " has a different IP(" +
Jon Hallafa8a472015-06-12 14:02:42 -07002803 str( onosHost[ 'ipAddresses' ] ) +
2804 ") than the Mininet host(" +
Jon Halld80cc142015-07-06 13:36:05 -07002805 str( ip ) +
2806 ")." )
Jon Hallff6b4b22015-02-23 09:25:15 -08002807 output = json.dumps(
Jon Halld80cc142015-07-06 13:36:05 -07002808 onosHost,
2809 sort_keys=True,
2810 indent=4,
2811 separators=( ',', ': ' ) )
Jon Hallff6b4b22015-02-23 09:25:15 -08002812 main.log.info( output )
2813 hostResults = main.FALSE
2814 if not match:
2815 hostResults = main.FALSE
2816 main.log.error( "ONOS host " + onosHost[ 'id' ] + " has no " +
2817 "corresponding Mininet host." )
2818 output = json.dumps( onosHost,
2819 sort_keys=True,
2820 indent=4,
2821 separators=( ',', ': ' ) )
2822 main.log.info( output )
Jon Hallff6b4b22015-02-23 09:25:15 -08002823 return hostResults
2824
Jon Hallafa8a472015-06-12 14:02:42 -07002825 def getHostsOld( self ):
Jon Hall7eb38402015-01-08 17:19:54 -08002826 """
2827 Returns a list of all hosts
2828 Don't ask questions just use it"""
2829 self.handle.sendline( "" )
2830 self.handle.expect( "mininet>" )
Jon Hall72cf1dc2014-10-20 21:04:50 -04002831
Jon Hall7eb38402015-01-08 17:19:54 -08002832 self.handle.sendline( "py [ host.name for host in net.hosts ]" )
2833 self.handle.expect( "mininet>" )
admin2a9548d2014-06-17 14:08:07 -07002834
kelvin-onlabd3b64892015-01-20 13:26:24 -08002835 handlePy = self.handle.before
2836 handlePy = handlePy.split( "]\r\n", 1 )[ 1 ]
2837 handlePy = handlePy.rstrip()
admin2a9548d2014-06-17 14:08:07 -07002838
Jon Hall7eb38402015-01-08 17:19:54 -08002839 self.handle.sendline( "" )
2840 self.handle.expect( "mininet>" )
admin2a9548d2014-06-17 14:08:07 -07002841
kelvin-onlabd3b64892015-01-20 13:26:24 -08002842 hostStr = handlePy.replace( "]", "" )
2843 hostStr = hostStr.replace( "'", "" )
2844 hostStr = hostStr.replace( "[", "" )
kelvin-onlab2ccad6e2015-05-18 10:36:54 -07002845 hostStr = hostStr.replace( " ", "" )
kelvin-onlabd3b64892015-01-20 13:26:24 -08002846 hostList = hostStr.split( "," )
andrewonlab3f0a4af2014-10-17 12:25:14 -04002847
kelvin-onlabd3b64892015-01-20 13:26:24 -08002848 return hostList
adminbae64d82013-08-01 10:50:15 -07002849
kelvin-onlabfa6ada82015-06-11 13:06:24 -07002850 def getSwitch( self ):
2851 """
2852 Returns a list of all switches
2853 Again, don't ask question just use it...
2854 """
2855 # get host list...
2856 hostList = self.getHosts()
2857 # Make host set
2858 hostSet = set( hostList )
2859
2860 # Getting all the nodes in mininet
2861 self.handle.sendline( "" )
2862 self.handle.expect( "mininet>" )
2863
2864 self.handle.sendline( "py [ node.name for node in net.values() ]" )
2865 self.handle.expect( "mininet>" )
2866
2867 handlePy = self.handle.before
2868 handlePy = handlePy.split( "]\r\n", 1 )[ 1 ]
2869 handlePy = handlePy.rstrip()
2870
2871 self.handle.sendline( "" )
2872 self.handle.expect( "mininet>" )
2873
2874 nodesStr = handlePy.replace( "]", "" )
2875 nodesStr = nodesStr.replace( "'", "" )
2876 nodesStr = nodesStr.replace( "[", "" )
2877 nodesStr = nodesStr.replace( " ", "" )
2878 nodesList = nodesStr.split( "," )
2879
2880 nodesSet = set( nodesList )
2881 # discarding default controller(s) node
2882 nodesSet.discard( 'c0' )
2883 nodesSet.discard( 'c1' )
2884 nodesSet.discard( 'c2' )
2885
2886 switchSet = nodesSet - hostSet
2887 switchList = list( switchSet )
2888
2889 return switchList
2890
Jon Hall7eb38402015-01-08 17:19:54 -08002891 def update( self ):
2892 """
2893 updates the port address and status information for
2894 each port in mn"""
2895 # TODO: Add error checking. currently the mininet command has no output
Jon Hallefbd9792015-03-05 16:11:36 -08002896 main.log.info( "Updating MN port information" )
Jon Hallb1290e82014-11-18 16:17:48 -05002897 try:
Jon Hall7eb38402015-01-08 17:19:54 -08002898 self.handle.sendline( "" )
2899 self.handle.expect( "mininet>" )
Jon Hall38481722014-11-04 16:50:05 -05002900
Jon Hall7eb38402015-01-08 17:19:54 -08002901 self.handle.sendline( "update" )
2902 self.handle.expect( "update" )
2903 self.handle.expect( "mininet>" )
Jon Hall38481722014-11-04 16:50:05 -05002904
Jon Hall7eb38402015-01-08 17:19:54 -08002905 self.handle.sendline( "" )
2906 self.handle.expect( "mininet>" )
Jon Hall38481722014-11-04 16:50:05 -05002907
Jon Hallb1290e82014-11-18 16:17:48 -05002908 return main.TRUE
2909 except pexpect.EOF:
Jon Hall7eb38402015-01-08 17:19:54 -08002910 main.log.error( self.name + ": EOF exception found" )
2911 main.log.error( self.name + ": " + self.handle.before )
Jon Hallb1290e82014-11-18 16:17:48 -05002912 main.cleanup()
2913 main.exit()
2914
Jon Halld80cc142015-07-06 13:36:05 -07002915 def assignVLAN( self, host, intf, vlan ):
kaouthera3f13ca22015-05-05 15:01:41 -07002916 """
2917 Add vlan tag to a host.
2918 Dependencies:
2919 This class depends on the "vlan" package
2920 $ sudo apt-get install vlan
2921 Configuration:
2922 Load the 8021q module into the kernel
2923 $sudo modprobe 8021q
2924
2925 To make this setup permanent:
2926 $ sudo su -c 'echo "8021q" >> /etc/modules'
2927 """
2928 if self.handle:
2929 try:
Jon Halld80cc142015-07-06 13:36:05 -07002930 # get the ip address of the host
2931 main.log.info( "Get the ip address of the host" )
2932 ipaddr = self.getIPAddress( host )
2933 print repr( ipaddr )
kaouthera3f13ca22015-05-05 15:01:41 -07002934
Jon Halld80cc142015-07-06 13:36:05 -07002935 # remove IP from interface intf
2936 # Ex: h1 ifconfig h1-eth0 inet 0
2937 main.log.info( "Remove IP from interface " )
2938 cmd2 = host + " ifconfig " + intf + " " + " inet 0 "
2939 self.handle.sendline( cmd2 )
2940 self.handle.expect( "mininet>" )
2941 response = self.handle.before
2942 main.log.info( "====> %s ", response )
kaouthera3f13ca22015-05-05 15:01:41 -07002943
Jon Halld80cc142015-07-06 13:36:05 -07002944 # create VLAN interface
2945 # Ex: h1 vconfig add h1-eth0 100
2946 main.log.info( "Create Vlan" )
2947 cmd3 = host + " vconfig add " + intf + " " + vlan
2948 self.handle.sendline( cmd3 )
2949 self.handle.expect( "mininet>" )
2950 response = self.handle.before
2951 main.log.info( "====> %s ", response )
kaouthera3f13ca22015-05-05 15:01:41 -07002952
Jon Halld80cc142015-07-06 13:36:05 -07002953 # assign the host's IP to the VLAN interface
2954 # Ex: h1 ifconfig h1-eth0.100 inet 10.0.0.1
2955 main.log.info( "Assign the host IP to the vlan interface" )
2956 vintf = intf + "." + vlan
2957 cmd4 = host + " ifconfig " + vintf + " " + " inet " + ipaddr
2958 self.handle.sendline( cmd4 )
2959 self.handle.expect( "mininet>" )
2960 response = self.handle.before
2961 main.log.info( "====> %s ", response )
kaouthera3f13ca22015-05-05 15:01:41 -07002962
2963 return main.TRUE
2964 except pexpect.EOF:
2965 main.log.error( self.name + ": EOF exception found" )
2966 main.log.error( self.name + ": " + self.handle.before )
2967 return main.FALSE
2968
Jon Hall892818c2015-10-20 17:58:34 -07002969 def createHostComponent( self, name ):
2970 """
2971 Creates a new mininet cli component with the same parameters as self.
2972 This new component is intended to be used to login to the hosts created
2973 by mininet.
2974
2975 Arguments:
2976 name - The string of the name of this component. The new component
2977 will be assigned to main.<name> .
2978 In addition, main.<name>.name = str( name )
2979 """
2980 try:
2981 # look to see if this component already exists
2982 getattr( main, name )
2983 except AttributeError:
2984 # namespace is clear, creating component
2985 main.componentDictionary[name] = main.componentDictionary[self.name].copy()
2986 main.componentDictionary[name]['connect_order'] = str( int( main.componentDictionary[name]['connect_order'] ) + 1 )
2987 main.componentInit( name )
2988 except Exception:
2989 main.log.exception( self.name + ": Uncaught exception!" )
2990 main.cleanup()
2991 main.exit()
2992 else:
2993 # namespace is not clear!
2994 main.log.error( name + " component already exists!" )
2995 # FIXME: Should we exit here?
2996 main.cleanup()
2997 main.exit()
2998
2999 def removeHostComponent( self, name ):
3000 """
3001 Remove host component
3002 Arguments:
3003 name - The string of the name of the component to delete.
3004 """
3005 try:
3006 # Get host component
3007 component = getattr( main, name )
3008 except AttributeError:
3009 main.log.error( "Component " + name + " does not exist." )
3010 return
3011 try:
3012 # Disconnect from component
3013 component.disconnect()
3014 # Delete component
3015 delattr( main, name )
3016 # Delete component from ComponentDictionary
3017 del( main.componentDictionary[name] )
3018 except Exception:
3019 main.log.exception( self.name + ": Uncaught exception!" )
3020 main.cleanup()
3021 main.exit()
3022
3023 def startHostCli( self, host=None ):
3024 """
3025 Use the mininet m utility to connect to the host's cli
3026 """
3027 # These are fields that can be used by scapy packets. Initialized to None
3028 self.hostIp = None
3029 self.hostMac = None
3030 try:
3031 if not host:
3032 host = self.name
3033 self.handle.sendline( self.home + "/util/m " + host )
3034 self.handle.expect( self.hostPrompt )
3035 return main.TRUE
3036 except pexpect.TIMEOUT:
3037 main.log.exception( self.name + ": Command timed out" )
3038 return main.FALSE
3039 except pexpect.EOF:
3040 main.log.exception( self.name + ": connection closed." )
3041 main.cleanup()
3042 main.exit()
3043 except Exception:
3044 main.log.exception( self.name + ": Uncaught exception!" )
3045 main.cleanup()
3046 main.exit()
3047
GlennRC956ea742015-11-05 16:14:15 -08003048 def startScapy( self, mplsPath="" ):
Jon Hall892818c2015-10-20 17:58:34 -07003049 """
3050 Start the Scapy cli
GlennRC956ea742015-11-05 16:14:15 -08003051 optional:
3052 mplsPath - The path where the MPLS class is located
3053 NOTE: This can be a relative path from the user's home dir
Jon Hall892818c2015-10-20 17:58:34 -07003054 """
GlennRC956ea742015-11-05 16:14:15 -08003055 mplsLines = ['import imp',
3056 'imp.load_source( "mplsClass", "{}mplsClass.py" )'.format(mplsPath),
3057 'from mplsClass import MPLS',
3058 'bind_layers(Ether, MPLS, type = 0x8847)',
3059 'bind_layers(MPLS, MPLS, bottom_of_label_stack = 0)',
3060 'bind_layers(MPLS, IP)']
3061
Jon Hall892818c2015-10-20 17:58:34 -07003062 try:
3063 self.handle.sendline( "scapy" )
3064 self.handle.expect( self.scapyPrompt )
3065 self.handle.sendline( "conf.color_theme = NoTheme()" )
3066 self.handle.expect( self.scapyPrompt )
GlennRC956ea742015-11-05 16:14:15 -08003067 if mplsPath:
3068 main.log.info( "Adding MPLS class" )
3069 main.log.info( "MPLS class path: " + mplsPath )
3070 for line in mplsLines:
3071 main.log.info( "sending line: " + line )
3072 self.handle.sendline( line )
3073 self.handle.expect( self.scapyPrompt )
Jon Hall892818c2015-10-20 17:58:34 -07003074 return main.TRUE
3075 except pexpect.TIMEOUT:
3076 main.log.exception( self.name + ": Command timed out" )
3077 return main.FALSE
3078 except pexpect.EOF:
3079 main.log.exception( self.name + ": connection closed." )
3080 main.cleanup()
3081 main.exit()
3082 except Exception:
3083 main.log.exception( self.name + ": Uncaught exception!" )
3084 main.cleanup()
3085 main.exit()
3086
3087 def stopScapy( self ):
3088 """
3089 Exit the Scapy cli
3090 """
3091 try:
3092 self.handle.sendline( "exit()" )
3093 self.handle.expect( self.hostPrompt )
3094 return main.TRUE
3095 except pexpect.TIMEOUT:
3096 main.log.exception( self.name + ": Command timed out" )
3097 return main.FALSE
3098 except pexpect.EOF:
3099 main.log.exception( self.name + ": connection closed." )
3100 main.cleanup()
3101 main.exit()
3102 except Exception:
3103 main.log.exception( self.name + ": Uncaught exception!" )
3104 main.cleanup()
3105 main.exit()
3106
3107 def buildEther( self, **kwargs ):
3108 """
3109 Build an Ethernet frame
3110
3111 Will create a frame class with the given options. If a field is
3112 left blank it will default to the below value unless it is
3113 overwritten by the next frame.
3114 Default frame:
3115 ###[ Ethernet ]###
3116 dst= ff:ff:ff:ff:ff:ff
3117 src= 00:00:00:00:00:00
3118 type= 0x800
3119
3120 Returns main.TRUE or main.FALSE on error
3121 """
3122 try:
3123 # Set the Ethernet frame
3124 cmd = 'ether = Ether( '
3125 options = []
3126 for key, value in kwargs.iteritems():
3127 if isinstance( value, str ):
3128 value = '"' + value + '"'
3129 options.append( str( key ) + "=" + str( value ) )
3130 cmd += ", ".join( options )
3131 cmd += ' )'
3132 self.handle.sendline( cmd )
3133 self.handle.expect( self.scapyPrompt )
3134 if "Traceback" in self.handle.before:
3135 # KeyError, SyntaxError, ...
3136 main.log.error( "Error in sending command: " + self.handle.before )
3137 return main.FALSE
3138 self.handle.sendline( "packet = ether" )
3139 self.handle.expect( self.scapyPrompt )
3140 if "Traceback" in self.handle.before:
3141 # KeyError, SyntaxError, ...
3142 main.log.error( "Error in sending command: " + self.handle.before )
3143 return main.FALSE
3144 return main.TRUE
3145 except pexpect.TIMEOUT:
3146 main.log.exception( self.name + ": Command timed out" )
3147 return main.FALSE
3148 except pexpect.EOF:
3149 main.log.exception( self.name + ": connection closed." )
3150 main.cleanup()
3151 main.exit()
3152 except Exception:
3153 main.log.exception( self.name + ": Uncaught exception!" )
3154 main.cleanup()
3155 main.exit()
3156
3157 def buildIP( self, **kwargs ):
3158 """
3159 Build an IP frame
3160
3161 Will create a frame class with the given options. If a field is
3162 left blank it will default to the below value unless it is
3163 overwritten by the next frame.
3164 Default frame:
3165 ###[ IP ]###
3166 version= 4
3167 ihl= None
3168 tos= 0x0
3169 len= None
3170 id= 1
3171 flags=
3172 frag= 0
3173 ttl= 64
3174 proto= hopopt
3175 chksum= None
3176 src= 127.0.0.1
3177 dst= 127.0.0.1
3178 \options\
3179
3180 Returns main.TRUE or main.FALSE on error
3181 """
3182 try:
3183 # Set the IP frame
3184 cmd = 'ip = IP( '
3185 options = []
3186 for key, value in kwargs.iteritems():
3187 if isinstance( value, str ):
3188 value = '"' + value + '"'
3189 options.append( str( key ) + "=" + str( value ) )
3190 cmd += ", ".join( options )
3191 cmd += ' )'
3192 self.handle.sendline( cmd )
3193 self.handle.expect( self.scapyPrompt )
3194 if "Traceback" in self.handle.before:
3195 # KeyError, SyntaxError, ...
3196 main.log.error( "Error in sending command: " + self.handle.before )
3197 return main.FALSE
3198 self.handle.sendline( "packet = ether/ip" )
3199 self.handle.expect( self.scapyPrompt )
3200 if "Traceback" in self.handle.before:
3201 # KeyError, SyntaxError, ...
3202 main.log.error( "Error in sending command: " + self.handle.before )
3203 return main.FALSE
3204 return main.TRUE
3205 except pexpect.TIMEOUT:
3206 main.log.exception( self.name + ": Command timed out" )
3207 return main.FALSE
3208 except pexpect.EOF:
3209 main.log.exception( self.name + ": connection closed." )
3210 main.cleanup()
3211 main.exit()
3212 except Exception:
3213 main.log.exception( self.name + ": Uncaught exception!" )
3214 main.cleanup()
3215 main.exit()
3216
3217 def buildIPv6( self, **kwargs ):
3218 """
3219 Build an IPv6 frame
3220
3221 Will create a frame class with the given options. If a field is
3222 left blank it will default to the below value unless it is
3223 overwritten by the next frame.
3224 Default frame:
3225 ###[ IPv6 ]###
3226 version= 6
3227 tc= 0
3228 fl= 0
3229 plen= None
3230 nh= No Next Header
3231 hlim= 64
3232 src= ::1
3233 dst= ::1
3234
3235 Returns main.TRUE or main.FALSE on error
3236 """
3237 try:
3238 # Set the IPv6 frame
3239 cmd = 'ipv6 = IPv6( '
3240 options = []
3241 for key, value in kwargs.iteritems():
3242 if isinstance( value, str ):
3243 value = '"' + value + '"'
3244 options.append( str( key ) + "=" + str( value ) )
3245 cmd += ", ".join( options )
3246 cmd += ' )'
3247 self.handle.sendline( cmd )
3248 self.handle.expect( self.scapyPrompt )
3249 if "Traceback" in self.handle.before:
3250 # KeyError, SyntaxError, ...
3251 main.log.error( "Error in sending command: " + self.handle.before )
3252 return main.FALSE
3253 self.handle.sendline( "packet = ether/ipv6" )
3254 self.handle.expect( self.scapyPrompt )
3255 if "Traceback" in self.handle.before:
3256 # KeyError, SyntaxError, ...
3257 main.log.error( "Error in sending command: " + self.handle.before )
3258 return main.FALSE
3259 return main.TRUE
3260 except pexpect.TIMEOUT:
3261 main.log.exception( self.name + ": Command timed out" )
3262 return main.FALSE
3263 except pexpect.EOF:
3264 main.log.exception( self.name + ": connection closed." )
3265 main.cleanup()
3266 main.exit()
3267 except Exception:
3268 main.log.exception( self.name + ": Uncaught exception!" )
3269 main.cleanup()
3270 main.exit()
3271
3272 def buildTCP( self, ipVersion=4, **kwargs ):
3273 """
3274 Build an TCP frame
3275
3276 Will create a frame class with the given options. If a field is
3277 left blank it will default to the below value unless it is
3278 overwritten by the next frame.
3279
GlennRC956ea742015-11-05 16:14:15 -08003280 NOTE: Some arguments require quotes around them. It's up to you to
3281 know which ones and to add them yourself. Arguments with an asterisk
3282 do not need quotes.
3283
Jon Hall892818c2015-10-20 17:58:34 -07003284 Options:
3285 ipVersion - Either 4 (default) or 6, indicates what Internet Protocol
3286 frame to use to encapsulate into
3287 Default frame:
3288 ###[ TCP ]###
GlennRC956ea742015-11-05 16:14:15 -08003289 sport= ftp_data *
3290 dport= http *
Jon Hall892818c2015-10-20 17:58:34 -07003291 seq= 0
3292 ack= 0
3293 dataofs= None
3294 reserved= 0
3295 flags= S
3296 window= 8192
3297 chksum= None
3298 urgptr= 0
3299 options= {}
3300
3301 Returns main.TRUE or main.FALSE on error
3302 """
3303 try:
3304 # Set the TCP frame
3305 cmd = 'tcp = TCP( '
3306 options = []
3307 for key, value in kwargs.iteritems():
Jon Hall892818c2015-10-20 17:58:34 -07003308 options.append( str( key ) + "=" + str( value ) )
3309 cmd += ", ".join( options )
3310 cmd += ' )'
3311 self.handle.sendline( cmd )
3312 self.handle.expect( self.scapyPrompt )
3313 if "Traceback" in self.handle.before:
3314 # KeyError, SyntaxError, ...
3315 main.log.error( "Error in sending command: " + self.handle.before )
3316 return main.FALSE
3317 if str( ipVersion ) is '4':
3318 self.handle.sendline( "packet = ether/ip/tcp" )
3319 elif str( ipVersion ) is '6':
3320 self.handle.sendline( "packet = ether/ipv6/tcp" )
3321 else:
3322 main.log.error( "Unrecognized option for ipVersion, given " +
3323 repr( ipVersion ) )
3324 return main.FALSE
3325 self.handle.expect( self.scapyPrompt )
3326 if "Traceback" in self.handle.before:
3327 # KeyError, SyntaxError, ...
3328 main.log.error( "Error in sending command: " + self.handle.before )
3329 return main.FALSE
3330 return main.TRUE
3331 except pexpect.TIMEOUT:
3332 main.log.exception( self.name + ": Command timed out" )
3333 return main.FALSE
3334 except pexpect.EOF:
3335 main.log.exception( self.name + ": connection closed." )
3336 main.cleanup()
3337 main.exit()
3338 except Exception:
3339 main.log.exception( self.name + ": Uncaught exception!" )
3340 main.cleanup()
3341 main.exit()
3342
3343 def buildUDP( self, ipVersion=4, **kwargs ):
3344 """
3345 Build an UDP frame
3346
3347 Will create a frame class with the given options. If a field is
3348 left blank it will default to the below value unless it is
3349 overwritten by the next frame.
3350
GlennRC956ea742015-11-05 16:14:15 -08003351 NOTE: Some arguments require quotes around them. It's up to you to
3352 know which ones and to add them yourself. Arguments with an asterisk
3353 do not need quotes.
3354
Jon Hall892818c2015-10-20 17:58:34 -07003355 Options:
3356 ipVersion - Either 4 (default) or 6, indicates what Internet Protocol
3357 frame to use to encapsulate into
3358 Default frame:
3359 ###[ UDP ]###
GlennRC956ea742015-11-05 16:14:15 -08003360 sport= domain *
3361 dport= domain *
Jon Hall892818c2015-10-20 17:58:34 -07003362 len= None
3363 chksum= None
3364
3365 Returns main.TRUE or main.FALSE on error
3366 """
3367 try:
3368 # Set the UDP frame
3369 cmd = 'udp = UDP( '
3370 options = []
3371 for key, value in kwargs.iteritems():
Jon Hall892818c2015-10-20 17:58:34 -07003372 options.append( str( key ) + "=" + str( value ) )
3373 cmd += ", ".join( options )
3374 cmd += ' )'
3375 self.handle.sendline( cmd )
3376 self.handle.expect( self.scapyPrompt )
3377 if "Traceback" in self.handle.before:
3378 # KeyError, SyntaxError, ...
3379 main.log.error( "Error in sending command: " + self.handle.before )
3380 return main.FALSE
3381 if str( ipVersion ) is '4':
3382 self.handle.sendline( "packet = ether/ip/udp" )
3383 elif str( ipVersion ) is '6':
3384 self.handle.sendline( "packet = ether/ipv6/udp" )
3385 else:
3386 main.log.error( "Unrecognized option for ipVersion, given " +
3387 repr( ipVersion ) )
3388 return main.FALSE
3389 self.handle.expect( self.scapyPrompt )
3390 if "Traceback" in self.handle.before:
3391 # KeyError, SyntaxError, ...
3392 main.log.error( "Error in sending command: " + self.handle.before )
3393 return main.FALSE
3394 return main.TRUE
3395 except pexpect.TIMEOUT:
3396 main.log.exception( self.name + ": Command timed out" )
3397 return main.FALSE
3398 except pexpect.EOF:
3399 main.log.exception( self.name + ": connection closed." )
3400 main.cleanup()
3401 main.exit()
3402 except Exception:
3403 main.log.exception( self.name + ": Uncaught exception!" )
3404 main.cleanup()
3405 main.exit()
3406
3407 def buildICMP( self, **kwargs ):
3408 """
3409 Build an ICMP frame
3410
3411 Will create a frame class with the given options. If a field is
3412 left blank it will default to the below value unless it is
3413 overwritten by the next frame.
3414 Default frame:
3415 ###[ ICMP ]###
3416 type= echo-request
3417 code= 0
3418 chksum= None
3419 id= 0x0
3420 seq= 0x0
3421
3422 Returns main.TRUE or main.FALSE on error
3423 """
3424 try:
3425 # Set the ICMP frame
3426 cmd = 'icmp = ICMP( '
3427 options = []
3428 for key, value in kwargs.iteritems():
3429 if isinstance( value, str ):
3430 value = '"' + value + '"'
3431 options.append( str( key ) + "=" + str( value ) )
3432 cmd += ", ".join( options )
3433 cmd += ' )'
3434 self.handle.sendline( cmd )
3435 self.handle.expect( self.scapyPrompt )
3436 if "Traceback" in self.handle.before:
3437 # KeyError, SyntaxError, ...
3438 main.log.error( "Error in sending command: " + self.handle.before )
3439 return main.FALSE
3440 self.handle.sendline( "packet = ether/ip/icmp" )
3441 self.handle.expect( self.scapyPrompt )
3442 if "Traceback" in self.handle.before:
3443 # KeyError, SyntaxError, ...
3444 main.log.error( "Error in sending command: " + self.handle.before )
3445 return main.FALSE
3446 return main.TRUE
3447 except pexpect.TIMEOUT:
3448 main.log.exception( self.name + ": Command timed out" )
3449 return main.FALSE
3450 except pexpect.EOF:
3451 main.log.exception( self.name + ": connection closed." )
3452 main.cleanup()
3453 main.exit()
3454 except Exception:
3455 main.log.exception( self.name + ": Uncaught exception!" )
3456 main.cleanup()
3457 main.exit()
3458
GlennRC073e8bc2015-10-27 17:11:28 -07003459 def sendPacket( self, iface=None, packet=None, timeout=1 ):
Jon Hall892818c2015-10-20 17:58:34 -07003460 """
3461 Send a packet with either the given scapy packet command, or use the
3462 packet saved in the variable 'packet'.
3463
3464 Examples of a valid string for packet:
3465
3466 Simple IP packet
3467 packet='Ether(dst="a6:d9:26:df:1d:4b")/IP(dst="10.0.0.2")'
3468
3469 A Ping with two vlan tags
3470 packet='Ether(dst='ff:ff:ff:ff:ff:ff')/Dot1Q(vlan=1)/Dot1Q(vlan=10)/
3471 IP(dst='255.255.255.255', src='192.168.0.1')/ICMP()'
3472
3473 Returns main.TRUE or main.FALSE on error
3474 """
3475 try:
3476 # TODO: add all params, or use kwargs
3477 sendCmd = 'srp( '
3478 if packet:
3479 sendCmd += packet
3480 else:
3481 sendCmd += "packet"
GlennRC073e8bc2015-10-27 17:11:28 -07003482 if iface:
3483 sendCmd += ", iface='{}'".format( iface )
3484
Jon Hall892818c2015-10-20 17:58:34 -07003485 sendCmd += ', timeout=' + str( timeout ) + ')'
3486 self.handle.sendline( sendCmd )
3487 self.handle.expect( self.scapyPrompt )
3488 if "Traceback" in self.handle.before:
3489 # KeyError, SyntaxError, ...
3490 main.log.error( "Error in sending command: " + self.handle.before )
3491 return main.FALSE
3492 # TODO: Check # of packets sent?
3493 return main.TRUE
3494 except pexpect.TIMEOUT:
3495 main.log.exception( self.name + ": Command timed out" )
3496 return main.FALSE
3497 except pexpect.EOF:
3498 main.log.exception( self.name + ": connection closed." )
3499 main.cleanup()
3500 main.exit()
3501 except Exception:
3502 main.log.exception( self.name + ": Uncaught exception!" )
3503 main.cleanup()
3504 main.exit()
3505
3506 def startFilter( self, ifaceName=None, sniffCount=1, pktFilter="ip" ):
3507 """
3508 Listen for packets using the given filters
3509
3510 Options:
3511 ifaceName - the name of the interface to listen on. If none is given,
3512 defaults to <host name>-eth0
3513 pktFilter - A string in Berkeley Packet Filter (BPF) format which
3514 specifies which packets to sniff
3515 sniffCount - The number of matching packets to capture before returning
3516
3517 Returns main.TRUE or main.FALSE on error
3518 """
3519 try:
3520 # TODO: add all params, or use kwargs
3521 ifaceName = str( ifaceName ) if ifaceName else self.name + "-eth0"
3522 # Set interface
3523 self.handle.sendline( ' conf.iface = "' + ifaceName + '"' )
3524 self.handle.expect( self.scapyPrompt )
3525 cmd = 'pkt = sniff(count = ' + str( sniffCount ) +\
3526 ', filter = "' + str( pktFilter ) + '")'
3527 self.handle.sendline( cmd )
3528 self.handle.expect( '"\)\r\n' )
3529 # TODO: parse this?
3530 return main.TRUE
3531 except pexpect.TIMEOUT:
3532 main.log.exception( self.name + ": Command timed out" )
3533 return main.FALSE
3534 except pexpect.EOF:
3535 main.log.exception( self.name + ": connection closed." )
3536 main.cleanup()
3537 main.exit()
3538 except Exception:
3539 main.log.exception( self.name + ": Uncaught exception!" )
3540 main.cleanup()
3541 main.exit()
3542
3543 def checkFilter( self ):
3544 """
3545 Check that a filter returned and returns the reponse
3546 """
3547 try:
3548 i = self.handle.expect( [ self.scapyPrompt, pexpect.TIMEOUT ] )
3549 if i == 0:
3550 return main.TRUE
3551 else:
3552 return main.FALSE
3553 except pexpect.EOF:
3554 main.log.exception( self.name + ": connection closed." )
3555 main.cleanup()
3556 main.exit()
3557 except Exception:
3558 main.log.exception( self.name + ": Uncaught exception!" )
3559 main.cleanup()
3560 main.exit()
3561
3562 def killFilter( self ):
3563 """
3564 Kill a scapy filter
3565 """
3566 try:
3567 self.handle.send( "\x03" ) # Send a ctrl-c to kill the filter
3568 self.handle.expect( self.scapyPrompt )
3569 return self.handle.before
3570 except pexpect.TIMEOUT:
3571 main.log.exception( self.name + ": Command timed out" )
3572 return None
3573 except pexpect.EOF:
3574 main.log.exception( self.name + ": connection closed." )
3575 main.cleanup()
3576 main.exit()
3577 except Exception:
3578 main.log.exception( self.name + ": Uncaught exception!" )
3579 main.cleanup()
3580 main.exit()
3581
3582 def readPackets( self ):
3583 """
3584 Read all the packets captured by the previous filter
3585 """
3586 try:
3587 self.handle.sendline( "for p in pkt: p \n")
3588 self.handle.expect( "for p in pkt: p \r\n... \r\n" )
3589 self.handle.expect( self.scapyPrompt )
3590 except pexpect.TIMEOUT:
3591 main.log.exception( self.name + ": Command timed out" )
3592 return None
3593 except pexpect.EOF:
3594 main.log.exception( self.name + ": connection closed." )
3595 main.cleanup()
3596 main.exit()
3597 except Exception:
3598 main.log.exception( self.name + ": Uncaught exception!" )
3599 main.cleanup()
3600 main.exit()
3601 return self.handle.before
3602
3603 def updateSelf( self ):
3604 """
3605 Updates local MAC and IP fields
3606 """
3607 self.hostMac = self.getMac()
3608 self.hostIp = self.getIp()
3609
3610 def getMac( self, ifaceName=None ):
3611 """
3612 Save host's MAC address
3613 """
3614 try:
3615 ifaceName = str( ifaceName ) if ifaceName else self.name + "-eth0"
3616 cmd = 'get_if_hwaddr("' + str( ifaceName ) + '")'
3617 self.handle.sendline( cmd )
3618 self.handle.expect( self.scapyPrompt )
3619 pattern = r'(([0-9a-f]{2}[:-]){5}([0-9a-f]{2}))'
3620 match = re.search( pattern, self.handle.before )
3621 if match:
3622 return match.group()
3623 else:
3624 # the command will have an exception if iface doesn't exist
3625 return None
3626 except pexpect.TIMEOUT:
3627 main.log.exception( self.name + ": Command timed out" )
3628 return None
3629 except pexpect.EOF:
3630 main.log.exception( self.name + ": connection closed." )
3631 main.cleanup()
3632 main.exit()
3633 except Exception:
3634 main.log.exception( self.name + ": Uncaught exception!" )
3635 main.cleanup()
3636 main.exit()
3637
3638 def getIp( self, ifaceName=None ):
3639 """
3640 Save host's IP address
3641 """
3642 try:
3643 ifaceName = ifaceName if ifaceName else self.name + "-eth0"
3644 cmd = 'get_if_addr("' + str( ifaceName ) + '")'
3645 self.handle.sendline( cmd )
3646 self.handle.expect( self.scapyPrompt )
3647
3648 pattern = r'(((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9]))'
3649 match = re.search( pattern, self.handle.before )
3650 if match:
3651 # NOTE: The command will return 0.0.0.0 if the iface doesn't exist
3652 return match.group()
3653 else:
3654 return None
3655 except pexpect.TIMEOUT:
3656 main.log.exception( self.name + ": Command timed out" )
3657 return None
3658 except pexpect.EOF:
3659 main.log.exception( self.name + ": connection closed." )
3660 main.cleanup()
3661 main.exit()
3662 except Exception:
3663 main.log.exception( self.name + ": Uncaught exception!" )
3664 main.cleanup()
3665 main.exit()
3666
adminbae64d82013-08-01 10:50:15 -07003667if __name__ != "__main__":
kelvin-onlab50907142015-04-01 13:37:45 -07003668 sys.modules[ __name__ ] = MininetCliDriver()