blob: 00e4a40f2084938a066911dc207c5c25fa92d2f3 [file] [log] [blame]
Bob Lantz087b5d92016-05-06 11:39:04 -07001#!/usr/bin/python
2
3"""
4onos.py: ONOS cluster and control network in Mininet
5
6With onos.py, you can use Mininet to create a complete
7ONOS network, including an ONOS cluster with a modeled
8control network as well as the usual data nework.
9
10This is intended to be useful for distributed ONOS
11development and testing in the case that you require
12a modeled control network.
13
14Invocation (using OVS as default switch):
15
16mn --custom onos.py --controller onos,3 --topo torus,4,4
17
18Or with the user switch (or CPqD if installed):
19
20mn --custom onos.py --controller onos,3 \
21 --switch onosuser --topo torus,4,4
22
Bob Lantzbb37d872016-05-16 16:26:13 -070023Currently you meed to use a custom switch class
Bob Lantz087b5d92016-05-06 11:39:04 -070024because Mininet's Switch() class does't (yet?) handle
25controllers with multiple IP addresses directly.
26
27The classes may also be imported and used via Mininet's
28python API.
29
30Bugs/Gripes:
31- We need --switch onosuser for the user switch because
32 Switch() doesn't currently handle Controller objects
33 with multiple IP addresses.
34- ONOS startup and configuration is painful/undocumented.
35- Too many ONOS environment vars - do we need them all?
36- ONOS cluster startup is very, very slow. If Linux can
37 boot in 4 seconds, why can't ONOS?
38- It's a pain to mess with the control network from the
39 CLI
40- Setting a default controller for Mininet should be easier
41"""
42
43from mininet.node import Controller, OVSSwitch, UserSwitch
44from mininet.nodelib import LinuxBridge
45from mininet.net import Mininet
46from mininet.topo import SingleSwitchTopo, Topo
Bob Lantz64382422016-06-03 22:51:39 -070047from mininet.log import setLogLevel, info, warn, error, debug
Bob Lantz087b5d92016-05-06 11:39:04 -070048from mininet.cli import CLI
Bob Lantz64382422016-06-03 22:51:39 -070049from mininet.util import quietRun, specialClass
Bob Lantz087b5d92016-05-06 11:39:04 -070050from mininet.examples.controlnet import MininetFacade
51
52from os import environ
53from os.path import dirname, join, isfile
54from sys import argv
55from glob import glob
56import time
Bob Lantz64382422016-06-03 22:51:39 -070057from functools import partial
Bob Lantz92d8e052016-06-17 16:03:58 -070058from re import search
59
Bob Lantz087b5d92016-05-06 11:39:04 -070060
61### ONOS Environment
62
Bob Lantzbb37d872016-05-16 16:26:13 -070063KarafPort = 8101 # ssh port indicating karaf is running
64GUIPort = 8181 # GUI/REST port
65OpenFlowPort = 6653 # OpenFlow port
Bob Lantz087b5d92016-05-06 11:39:04 -070066
67def defaultUser():
68 "Return a reasonable default user"
69 if 'SUDO_USER' in environ:
70 return environ[ 'SUDO_USER' ]
71 try:
72 user = quietRun( 'who am i' ).split()[ 0 ]
73 except:
74 user = 'nobody'
75 return user
76
Bob Lantz087b5d92016-05-06 11:39:04 -070077# Module vars, initialized below
Bob Lantz4b51d5c2016-05-27 14:47:38 -070078HOME = ONOS_ROOT = ONOS_USER = None
Bob Lantz087b5d92016-05-06 11:39:04 -070079ONOS_APPS = ONOS_WEB_USER = ONOS_WEB_PASS = ONOS_TAR = None
80
81def initONOSEnv():
82 """Initialize ONOS environment (and module) variables
83 This is ugly and painful, but they have to be set correctly
84 in order for the onos-setup-karaf script to work.
85 nodes: list of ONOS nodes
86 returns: ONOS environment variable dict"""
87 # pylint: disable=global-statement
Bob Lantz4b51d5c2016-05-27 14:47:38 -070088 global HOME, ONOS_ROOT, ONOS_USER
Bob Lantz087b5d92016-05-06 11:39:04 -070089 global ONOS_APPS, ONOS_WEB_USER, ONOS_WEB_PASS
90 env = {}
91 def sd( var, val ):
92 "Set default value for environment variable"
93 env[ var ] = environ.setdefault( var, val )
94 return env[ var ]
Bob Lantz4b51d5c2016-05-27 14:47:38 -070095 assert environ[ 'HOME' ]
Bob Lantz087b5d92016-05-06 11:39:04 -070096 HOME = sd( 'HOME', environ[ 'HOME' ] )
Bob Lantz087b5d92016-05-06 11:39:04 -070097 ONOS_ROOT = sd( 'ONOS_ROOT', join( HOME, 'onos' ) )
Bob Lantz087b5d92016-05-06 11:39:04 -070098 environ[ 'ONOS_USER' ] = defaultUser()
99 ONOS_USER = sd( 'ONOS_USER', defaultUser() )
100 ONOS_APPS = sd( 'ONOS_APPS',
101 'drivers,openflow,fwd,proxyarp,mobility' )
102 # ONOS_WEB_{USER,PASS} isn't respected by onos-karaf:
103 environ.update( ONOS_WEB_USER='karaf', ONOS_WEB_PASS='karaf' )
104 ONOS_WEB_USER = sd( 'ONOS_WEB_USER', 'karaf' )
105 ONOS_WEB_PASS = sd( 'ONOS_WEB_PASS', 'karaf' )
106 return env
107
108
109def updateNodeIPs( env, nodes ):
110 "Update env dict and environ with node IPs"
111 # Get rid of stale junk
112 for var in 'ONOS_NIC', 'ONOS_CELL', 'ONOS_INSTANCES':
113 env[ var ] = ''
114 for var in environ.keys():
115 if var.startswith( 'OC' ):
116 env[ var ] = ''
117 for index, node in enumerate( nodes, 1 ):
118 var = 'OC%d' % index
119 env[ var ] = node.IP()
120 env[ 'OCI' ] = env[ 'OCN' ] = env[ 'OC1' ]
121 env[ 'ONOS_INSTANCES' ] = '\n'.join(
122 node.IP() for node in nodes )
123 environ.update( env )
124 return env
125
126
127tarDefaultPath = 'buck-out/gen/tools/package/onos-package/onos.tar.gz'
128
Bob Lantz1451d722016-05-17 14:40:07 -0700129def unpackONOS( destDir='/tmp', run=quietRun ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700130 "Unpack ONOS and return its location"
131 global ONOS_TAR
132 environ.setdefault( 'ONOS_TAR', join( ONOS_ROOT, tarDefaultPath ) )
133 ONOS_TAR = environ[ 'ONOS_TAR' ]
134 tarPath = ONOS_TAR
135 if not isfile( tarPath ):
136 raise Exception( 'Missing ONOS tarball %s - run buck build onos?'
137 % tarPath )
138 info( '(unpacking %s)' % destDir)
Bob Lantz1451d722016-05-17 14:40:07 -0700139 cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s"'
Bob Lantz087b5d92016-05-06 11:39:04 -0700140 % ( destDir, destDir, tarPath) )
Bob Lantz1451d722016-05-17 14:40:07 -0700141 run( cmds, shell=True, verbose=True )
142 # We can use quietRun for this usually
143 tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True)
144 tarOutput = tarOutput.split()[ 0 ].strip()
145 assert '/' in tarOutput
146 onosDir = join( destDir, dirname( tarOutput ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700147 # Add symlink to log file
Bob Lantz1451d722016-05-17 14:40:07 -0700148 run( 'cd %s; ln -s onos*/apache* karaf;'
149 'ln -s karaf/data/log/karaf.log log' % destDir,
150 shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700151 return onosDir
152
153
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700154def waitListening( server, port=80, callback=None, sleepSecs=.5,
155 proc='java' ):
156 "Simplified netstat version of waitListening"
157 while True:
158 lines = server.cmd( 'netstat -natp' ).strip().split( '\n' )
159 entries = [ line.split() for line in lines ]
160 portstr = ':%s' % port
161 listening = [ entry for entry in entries
162 if len( entry ) > 6 and portstr in entry[ 3 ]
163 and proc in entry[ 6 ] ]
164 if listening:
165 break
Bob Lantz64382422016-06-03 22:51:39 -0700166 info( '.' )
167 if callback:
168 callback()
169 time.sleep( sleepSecs )
Bob Lantz64382422016-06-03 22:51:39 -0700170
171
Bob Lantz087b5d92016-05-06 11:39:04 -0700172### Mininet classes
173
174def RenamedTopo( topo, *args, **kwargs ):
175 """Return specialized topo with renamed hosts
176 topo: topo class/class name to specialize
177 args, kwargs: topo args
178 sold: old switch name prefix (default 's')
179 snew: new switch name prefix
180 hold: old host name prefix (default 'h')
181 hnew: new host name prefix
182 This may be used from the mn command, e.g.
183 mn --topo renamed,single,spref=sw,hpref=host"""
184 sold = kwargs.pop( 'sold', 's' )
185 hold = kwargs.pop( 'hold', 'h' )
186 snew = kwargs.pop( 'snew', 'cs' )
187 hnew = kwargs.pop( 'hnew' ,'ch' )
188 topos = {} # TODO: use global TOPOS dict
189 if isinstance( topo, str ):
190 # Look up in topo directory - this allows us to
191 # use RenamedTopo from the command line!
192 if topo in topos:
193 topo = topos.get( topo )
194 else:
195 raise Exception( 'Unknown topo name: %s' % topo )
196 # pylint: disable=no-init
197 class RenamedTopoCls( topo ):
198 "Topo subclass with renamed nodes"
199 def addNode( self, name, *args, **kwargs ):
200 "Add a node, renaming if necessary"
201 if name.startswith( sold ):
202 name = snew + name[ len( sold ): ]
203 elif name.startswith( hold ):
204 name = hnew + name[ len( hold ): ]
205 return topo.addNode( self, name, *args, **kwargs )
206 return RenamedTopoCls( *args, **kwargs )
207
208
209class ONOSNode( Controller ):
210 "ONOS cluster node"
211
Bob Lantz087b5d92016-05-06 11:39:04 -0700212 def __init__( self, name, **kwargs ):
Bob Lantz64382422016-06-03 22:51:39 -0700213 "alertAction: exception|ignore|warn|exit (exception)"
Bob Lantz087b5d92016-05-06 11:39:04 -0700214 kwargs.update( inNamespace=True )
Bob Lantz64382422016-06-03 22:51:39 -0700215 self.alertAction = kwargs.pop( 'alertAction', 'exception' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700216 Controller.__init__( self, name, **kwargs )
217 self.dir = '/tmp/%s' % self.name
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700218 self.client = self.dir + '/karaf/bin/client'
Bob Lantz087b5d92016-05-06 11:39:04 -0700219 self.ONOS_HOME = '/tmp'
Bob Lantz55562ea2016-06-17 18:19:03 -0700220 self.cmd( 'rm -rf', self.dir )
221 self.ONOS_HOME = unpackONOS( self.dir, run=self.ucmd )
Bob Lantz087b5d92016-05-06 11:39:04 -0700222
223 # pylint: disable=arguments-differ
224
Bob Lantz569bbec2016-06-03 18:51:16 -0700225 def start( self, env, nodes=() ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700226 """Start ONOS on node
Bob Lantz569bbec2016-06-03 18:51:16 -0700227 env: environment var dict
228 nodes: all nodes in cluster"""
Bob Lantz087b5d92016-05-06 11:39:04 -0700229 env = dict( env )
Bob Lantz087b5d92016-05-06 11:39:04 -0700230 env.update( ONOS_HOME=self.ONOS_HOME )
231 self.updateEnv( env )
232 karafbin = glob( '%s/apache*/bin' % self.ONOS_HOME )[ 0 ]
233 onosbin = join( ONOS_ROOT, 'tools/test/bin' )
234 self.cmd( 'export PATH=%s:%s:$PATH' % ( onosbin, karafbin ) )
235 self.cmd( 'cd', self.ONOS_HOME )
Bob Lantz1451d722016-05-17 14:40:07 -0700236 self.ucmd( 'mkdir -p config && '
Bob Lantz569bbec2016-06-03 18:51:16 -0700237 'onos-gen-partitions config/cluster.json',
238 ' '.join( node.IP() for node in nodes ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700239 info( '(starting %s)' % self )
240 service = join( self.ONOS_HOME, 'bin/onos-service' )
Bob Lantz1451d722016-05-17 14:40:07 -0700241 self.ucmd( service, 'server 1>../onos.log 2>../onos.log'
242 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700243 self.onosPid = int( self.cmd( 'cat onos.pid' ).strip() )
Bob Lantz64382422016-06-03 22:51:39 -0700244 self.warningCount = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700245
246 # pylint: enable=arguments-differ
247
248 def stop( self ):
249 # XXX This will kill all karafs - too bad!
250 self.cmd( 'pkill -HUP -f karaf.jar && wait' )
251 self.cmd( 'rm -rf', self.dir )
252
Bob Lantz64382422016-06-03 22:51:39 -0700253 def sanityAlert( self, *args ):
254 "Alert to raise on sanityCheck failure"
255 info( '\n' )
256 if self.alertAction == 'exception':
257 raise Exception( *args )
258 if self.alertAction == 'warn':
259 warn( *args + ( '\n', ) )
260 elif self.alertAction == 'exit':
261 error( '***', *args +
262 ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) )
263 exit( 1 )
264
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700265 def isRunning( self ):
266 "Is our ONOS process still running?"
Bob Lantz64382422016-06-03 22:51:39 -0700267 cmd = ( 'ps -p %d >/dev/null 2>&1 && echo "running" ||'
268 'echo "not running"' )
269 return self.cmd( cmd % self.onosPid ).strip() == 'running'
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700270
Bob Lantz64382422016-06-03 22:51:39 -0700271 def checkLog( self ):
272 "Return log file errors and warnings"
273 log = join( self.dir, 'log' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700274 errors, warnings = [], []
Bob Lantz64382422016-06-03 22:51:39 -0700275 if isfile( log ):
276 lines = open( log ).read().split( '\n' )
277 errors = [ line for line in lines if 'ERROR' in line ]
278 warnings = [ line for line in lines if 'WARN'in line ]
279 return errors, warnings
280
281 def memAvailable( self ):
282 "Return available memory in KB (or -1 if we can't tell)"
283 lines = open( '/proc/meminfo' ).read().strip().split( '\n' )
284 entries = map( str.split, lines )
285 index = { entry[ 0 ]: entry for entry in entries }
286 # Check MemAvailable if present
287 default = ( None, '-1', 'kB' )
288 _name, count, unit = index.get( 'MemAvailable:', default )
289 if unit.lower() == 'kb':
290 return int( count )
291 return -1
292
293 def sanityCheck( self, lowMem=100000 ):
294 """Check whether we've quit or are running out of memory
295 lowMem: low memory threshold in KB (100000)"""
296 # Are we still running?
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700297 if not self.isRunning():
Bob Lantz64382422016-06-03 22:51:39 -0700298 self.sanityAlert( 'ONOS node %s has died' % self.name )
299 # Are there errors in the log file?
300 errors, warnings = self.checkLog()
301 if errors:
302 self.sanityAlert( 'ONOS startup errors:\n<<%s>>' %
303 '\n'.join( errors ) )
304 warningCount = len( warnings )
305 if warnings and warningCount > self.warningCount:
306 warn( '(%d warnings)' % len( warnings ) )
307 self.warningCount = warningCount
308 # Are we running out of memory?
309 mem = self.memAvailable()
310 if mem > 0 and mem < lowMem:
311 self.sanityAlert( 'Running out of memory (only %d KB available)'
312 % mem )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700313
Bob Lantz087b5d92016-05-06 11:39:04 -0700314 def waitStarted( self ):
315 "Wait until we've really started"
316 info( '(checking: karaf' )
317 while True:
Bob Lantz1451d722016-05-17 14:40:07 -0700318 status = self.ucmd( 'karaf status' ).lower()
Bob Lantz087b5d92016-05-06 11:39:04 -0700319 if 'running' in status and 'not running' not in status:
320 break
321 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700322 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700323 time.sleep( 1 )
324 info( ' ssh-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700325 waitListening( server=self, port=KarafPort, callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700326 info( ' openflow-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700327 waitListening( server=self, port=OpenFlowPort,
328 callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700329 info( ' client' )
330 while True:
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700331 result = quietRun( '%s -h %s "apps -a"' %
Bob Lantzbb37d872016-05-16 16:26:13 -0700332 ( self.client, self.IP() ), shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700333 if 'openflow' in result:
334 break
335 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700336 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700337 time.sleep( 1 )
338 info( ')\n' )
339
340 def updateEnv( self, envDict ):
341 "Update environment variables"
Bob Lantz569bbec2016-06-03 18:51:16 -0700342 cmd = ';'.join( ( 'export %s="%s"' % ( var, val )
343 if val else 'unset %s' % var )
Bob Lantz087b5d92016-05-06 11:39:04 -0700344 for var, val in envDict.iteritems() )
345 self.cmd( cmd )
346
Bob Lantz1451d722016-05-17 14:40:07 -0700347 def ucmd( self, *args, **_kwargs ):
348 "Run command as $ONOS_USER using sudo -E -u"
349 if ONOS_USER != 'root': # don't bother with sudo
350 args = [ "sudo -E -u $ONOS_USER PATH=$PATH "
351 "bash -c '%s'" % ' '.join( args ) ]
352 return self.cmd( *args )
353
Bob Lantz087b5d92016-05-06 11:39:04 -0700354
355class ONOSCluster( Controller ):
356 "ONOS Cluster"
357 def __init__( self, *args, **kwargs ):
358 """name: (first parameter)
359 *args: topology class parameters
360 ipBase: IP range for ONOS nodes
Bob Lantzbb37d872016-05-16 16:26:13 -0700361 forward: default port forwarding list,
Bob Lantz087b5d92016-05-06 11:39:04 -0700362 topo: topology class or instance
Bob Lantz64382422016-06-03 22:51:39 -0700363 nodeOpts: ONOSNode options
Bob Lantz087b5d92016-05-06 11:39:04 -0700364 **kwargs: additional topology parameters"""
365 args = list( args )
366 name = args.pop( 0 )
367 topo = kwargs.pop( 'topo', None )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700368 nat = kwargs.pop( 'nat', 'nat0' )
Bob Lantz64382422016-06-03 22:51:39 -0700369 nodeOpts = kwargs.pop( 'nodeOpts', {} )
Bob Lantz087b5d92016-05-06 11:39:04 -0700370 # Default: single switch with 1 ONOS node
371 if not topo:
372 topo = SingleSwitchTopo
373 if not args:
374 args = ( 1, )
375 if not isinstance( topo, Topo ):
376 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700377 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
378 self.forward = kwargs.pop( 'forward',
379 [ KarafPort, GUIPort, OpenFlowPort ] )
Bob Lantz087b5d92016-05-06 11:39:04 -0700380 super( ONOSCluster, self ).__init__( name, inNamespace=False )
381 fixIPTables()
382 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700383 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700384 host=partial( ONOSNode, **nodeOpts ),
385 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700386 controller=None )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700387 if nat:
388 self.net.addNAT( nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700389 updateNodeIPs( self.env, self.nodes() )
390 self._remoteControllers = []
391
392 def start( self ):
393 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700394 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
395 self.net.start()
396 for node in self.nodes():
Bob Lantz569bbec2016-06-03 18:51:16 -0700397 node.start( self.env, self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700398 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700399 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700400 self.waitStarted()
401 return
402
403 def waitStarted( self ):
404 "Wait until all nodes have started"
405 startTime = time.time()
406 for node in self.nodes():
407 info( node )
408 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700409 info( '*** Waited %.2f seconds for ONOS startup' %
410 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700411
412 def stop( self ):
413 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700414 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700415 for node in self.nodes():
416 node.stop()
417 self.net.stop()
418
419 def nodes( self ):
420 "Return list of ONOS nodes"
421 return [ h for h in self.net.hosts if isinstance( h, ONOSNode ) ]
422
Bob Lantz92d8e052016-06-17 16:03:58 -0700423 def defaultIntf( self ):
424 "Call ip route to determine default interface"
425 result = quietRun( 'ip route | grep default', shell=True ).strip()
426 match = search( r'dev\s+([^\s]+)', result )
427 if match:
428 intf = match.group( 1 )
429 else:
430 warn( "Can't find default network interface - using eth0\n" )
431 intf = 'eth0'
432 return intf
433
434 def configPortForwarding( self, ports=[], intf='', action='A' ):
435 """Start or stop forwarding on intf to all nodes
Bob Lantzbb37d872016-05-16 16:26:13 -0700436 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz92d8e052016-06-17 16:03:58 -0700437 if not intf:
438 intf = self.defaultIntf()
Bob Lantzbb37d872016-05-16 16:26:13 -0700439 for port in ports:
440 for index, node in enumerate( self.nodes() ):
441 ip, inport = node.IP(), port + index
442 # Configure a destination NAT rule
443 cmd = ( 'iptables -t nat -{action} PREROUTING -t nat '
444 '-i {intf} -p tcp --dport {inport} '
445 '-j DNAT --to-destination {ip}:{port}' )
446 self.cmd( cmd.format( **locals() ) )
447
Bob Lantz087b5d92016-05-06 11:39:04 -0700448
449class ONOSSwitchMixin( object ):
450 "Mixin for switches that connect to an ONOSCluster"
451 def start( self, controllers ):
452 "Connect to ONOSCluster"
453 self.controllers = controllers
454 assert ( len( controllers ) is 1 and
455 isinstance( controllers[ 0 ], ONOSCluster ) )
456 clist = controllers[ 0 ].nodes()
457 return super( ONOSSwitchMixin, self ).start( clist )
458
459class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
460 "OVSSwitch that can connect to an ONOSCluster"
461 pass
462
463class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
464 "UserSwitch that can connect to an ONOSCluster"
465 pass
466
467
468### Ugly utility routines
469
470def fixIPTables():
471 "Fix LinuxBridge warning"
472 for s in 'arp', 'ip', 'ip6':
473 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
474
475
476### Test code
477
478def test( serverCount ):
479 "Test this setup"
480 setLogLevel( 'info' )
481 net = Mininet( topo=SingleSwitchTopo( 3 ),
482 controller=[ ONOSCluster( 'c0', serverCount ) ],
483 switch=ONOSOVSSwitch )
484 net.start()
485 net.waitConnected()
486 CLI( net )
487 net.stop()
488
489
490### CLI Extensions
491
492OldCLI = CLI
493
494class ONOSCLI( OldCLI ):
495 "CLI Extensions for ONOS"
496
497 prompt = 'mininet-onos> '
498
499 def __init__( self, net, **kwargs ):
500 c0 = net.controllers[ 0 ]
501 if isinstance( c0, ONOSCluster ):
502 net = MininetFacade( net, cnet=c0.net )
503 OldCLI.__init__( self, net, **kwargs )
504
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700505 def onos1( self ):
506 "Helper function: return default ONOS node"
507 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
508
Bob Lantz087b5d92016-05-06 11:39:04 -0700509 def do_onos( self, line ):
510 "Send command to ONOS CLI"
511 c0 = self.mn.controllers[ 0 ]
512 if isinstance( c0, ONOSCluster ):
513 # cmdLoop strips off command name 'onos'
514 if line.startswith( ':' ):
515 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700516 onos1 = self.onos1().name
517 if line:
518 line = '"%s"' % line
519 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700520 quietRun( 'stty -echo' )
521 self.default( cmd )
522 quietRun( 'stty echo' )
523
524 def do_wait( self, line ):
525 "Wait for switches to connect"
526 self.mn.waitConnected()
527
528 def do_balance( self, line ):
529 "Balance switch mastership"
530 self.do_onos( ':balance-masters' )
531
532 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700533 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700534 self.default( '%s tail -f /tmp/%s/log' %
535 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700536
Bob Lantz64382422016-06-03 22:51:39 -0700537 def do_status( self, line ):
538 "Return status of ONOS cluster(s)"
539 for c in self.mn.controllers:
540 if isinstance( c, ONOSCluster ):
541 for node in c.net.hosts:
542 if isinstance( node, ONOSNode ):
543 errors, warnings = node.checkLog()
544 running = ( 'Running' if node.isRunning()
545 else 'Exited' )
546 status = ''
547 if errors:
548 status += '%d ERRORS ' % len( errors )
549 if warnings:
550 status += '%d warnings' % len( warnings )
551 status = status if status else 'OK'
552 info( node, '\t', running, '\t', status, '\n' )
553
Bob Lantzc96e2582016-06-13 18:57:04 -0700554 def do_arp( self, line ):
555 "Send gratuitous arps from all data network hosts"
556 startTime = time.time()
557 try:
558 count = int( line )
559 except:
560 count = 1
561 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700562 if '-U' not in quietRun( 'arping -h', shell=True ):
563 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700564 return
565 # This is much faster if we do it in parallel
566 for host in self.mn.net.hosts:
567 intf = host.defaultIntf()
568 # -b: keep using broadcasts; -f: quit after 1 reply
569 # -U: gratuitous ARP update
570 host.sendCmd( 'arping -bf -c', count, '-U -I',
571 intf.name, intf.IP() )
572 for host in self.mn.net.hosts:
573 # We could check the output here if desired
574 host.waitOutput()
575 info( '.' )
576 info( '\n' )
577 elapsed = time.time() - startTime
578 debug( 'Completed in %.2f seconds\n' % elapsed )
579
Bob Lantz64382422016-06-03 22:51:39 -0700580
581# For interactive use, exit on error
582exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
583ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
584
Bob Lantz087b5d92016-05-06 11:39:04 -0700585
586### Exports for bin/mn
587
588CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700589controllers = { 'onos': ONOSClusterInteractive,
590 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700591
592# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700593findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700594
595switches = { 'onos': ONOSOVSSwitch,
596 'onosovs': ONOSOVSSwitch,
597 'onosuser': ONOSUserSwitch,
598 'default': ONOSOVSSwitch }
599
Bob Lantzbb37d872016-05-16 16:26:13 -0700600# Null topology so we can control an external/hardware network
601topos = { 'none': Topo }
602
Bob Lantz087b5d92016-05-06 11:39:04 -0700603if __name__ == '__main__':
604 if len( argv ) != 2:
605 test( 3 )
606 else:
607 test( int( argv[ 1 ] ) )