blob: 3923e66b5c8181d8140acd4dc3926fc9135bc6a1 [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 -070058
Bob Lantz087b5d92016-05-06 11:39:04 -070059
60### ONOS Environment
61
Bob Lantzbb37d872016-05-16 16:26:13 -070062KarafPort = 8101 # ssh port indicating karaf is running
63GUIPort = 8181 # GUI/REST port
64OpenFlowPort = 6653 # OpenFlow port
Jon Halla43d0332016-08-04 15:02:23 -070065CopycatPort = 9876 # Copycat 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
Lyndon Fawcettfbad2e72017-09-20 11:46:17 +000079ONOS_APPS = ONOS_WEB_USER = ONOS_WEB_PASS = ONOS_TAR = JAVA_OPTS = None
Bob Lantz087b5d92016-05-06 11:39:04 -070080
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' )
Lyndon Fawcettfbad2e72017-09-20 11:46:17 +0000102 JAVA_OPTS = sd( 'JAVA_OPTS', '-Xms128m -Xmx512m' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700103 # ONOS_WEB_{USER,PASS} isn't respected by onos-karaf:
104 environ.update( ONOS_WEB_USER='karaf', ONOS_WEB_PASS='karaf' )
105 ONOS_WEB_USER = sd( 'ONOS_WEB_USER', 'karaf' )
106 ONOS_WEB_PASS = sd( 'ONOS_WEB_PASS', 'karaf' )
107 return env
108
109
110def updateNodeIPs( env, nodes ):
111 "Update env dict and environ with node IPs"
112 # Get rid of stale junk
113 for var in 'ONOS_NIC', 'ONOS_CELL', 'ONOS_INSTANCES':
114 env[ var ] = ''
115 for var in environ.keys():
116 if var.startswith( 'OC' ):
117 env[ var ] = ''
118 for index, node in enumerate( nodes, 1 ):
119 var = 'OC%d' % index
120 env[ var ] = node.IP()
Jon Hall25485592016-08-19 13:56:14 -0700121 if nodes:
122 env[ 'OCI' ] = env[ 'OCN' ] = env[ 'OC1' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700123 env[ 'ONOS_INSTANCES' ] = '\n'.join(
124 node.IP() for node in nodes )
125 environ.update( env )
126 return env
127
128
129tarDefaultPath = 'buck-out/gen/tools/package/onos-package/onos.tar.gz'
130
Bob Lantz1451d722016-05-17 14:40:07 -0700131def unpackONOS( destDir='/tmp', run=quietRun ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700132 "Unpack ONOS and return its location"
133 global ONOS_TAR
134 environ.setdefault( 'ONOS_TAR', join( ONOS_ROOT, tarDefaultPath ) )
135 ONOS_TAR = environ[ 'ONOS_TAR' ]
136 tarPath = ONOS_TAR
137 if not isfile( tarPath ):
138 raise Exception( 'Missing ONOS tarball %s - run buck build onos?'
139 % tarPath )
140 info( '(unpacking %s)' % destDir)
Bob Lantza2ccaa52016-06-29 18:26:06 -0700141 success = '*** SUCCESS ***'
142 cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s" && echo "%s"'
143 % ( destDir, destDir, tarPath, success ) )
144 result = run( cmds, shell=True, verbose=True )
145 if success not in result:
146 raise Exception( 'Failed to unpack ONOS archive %s in %s:\n%s\n' %
147 ( tarPath, destDir, result ) )
Bob Lantz1451d722016-05-17 14:40:07 -0700148 # We can use quietRun for this usually
149 tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True)
150 tarOutput = tarOutput.split()[ 0 ].strip()
151 assert '/' in tarOutput
152 onosDir = join( destDir, dirname( tarOutput ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700153 # Add symlink to log file
Bob Lantz1451d722016-05-17 14:40:07 -0700154 run( 'cd %s; ln -s onos*/apache* karaf;'
155 'ln -s karaf/data/log/karaf.log log' % destDir,
156 shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700157 return onosDir
158
159
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700160def waitListening( server, port=80, callback=None, sleepSecs=.5,
161 proc='java' ):
162 "Simplified netstat version of waitListening"
163 while True:
164 lines = server.cmd( 'netstat -natp' ).strip().split( '\n' )
165 entries = [ line.split() for line in lines ]
166 portstr = ':%s' % port
167 listening = [ entry for entry in entries
168 if len( entry ) > 6 and portstr in entry[ 3 ]
169 and proc in entry[ 6 ] ]
170 if listening:
171 break
Bob Lantz64382422016-06-03 22:51:39 -0700172 info( '.' )
173 if callback:
174 callback()
175 time.sleep( sleepSecs )
Bob Lantz64382422016-06-03 22:51:39 -0700176
177
Bob Lantz087b5d92016-05-06 11:39:04 -0700178### Mininet classes
179
180def RenamedTopo( topo, *args, **kwargs ):
181 """Return specialized topo with renamed hosts
182 topo: topo class/class name to specialize
183 args, kwargs: topo args
184 sold: old switch name prefix (default 's')
185 snew: new switch name prefix
186 hold: old host name prefix (default 'h')
187 hnew: new host name prefix
188 This may be used from the mn command, e.g.
189 mn --topo renamed,single,spref=sw,hpref=host"""
190 sold = kwargs.pop( 'sold', 's' )
191 hold = kwargs.pop( 'hold', 'h' )
192 snew = kwargs.pop( 'snew', 'cs' )
193 hnew = kwargs.pop( 'hnew' ,'ch' )
194 topos = {} # TODO: use global TOPOS dict
195 if isinstance( topo, str ):
196 # Look up in topo directory - this allows us to
197 # use RenamedTopo from the command line!
198 if topo in topos:
199 topo = topos.get( topo )
200 else:
201 raise Exception( 'Unknown topo name: %s' % topo )
202 # pylint: disable=no-init
203 class RenamedTopoCls( topo ):
204 "Topo subclass with renamed nodes"
205 def addNode( self, name, *args, **kwargs ):
206 "Add a node, renaming if necessary"
207 if name.startswith( sold ):
208 name = snew + name[ len( sold ): ]
209 elif name.startswith( hold ):
210 name = hnew + name[ len( hold ): ]
211 return topo.addNode( self, name, *args, **kwargs )
212 return RenamedTopoCls( *args, **kwargs )
213
214
Bob Lantz8e576252016-08-29 14:05:59 -0700215# We accept objects that "claim" to be a particular class,
216# since the class definitions can be both execed (--custom) and
217# imported (in another custom file), which breaks isinstance().
218# In order for this to work properly, a class should not be
219# renamed so as to inappropriately omit or include the class
220# name text. Note that mininet.util.specialClass renames classes
221# by adding the specialized parameter names and values.
222
223def isONOSNode( obj ):
224 "Does obj claim to be some kind of ONOSNode?"
225 return ( isinstance( obj, ONOSNode) or
226 'ONOSNode' in type( obj ).__name__ )
227
228def isONOSCluster( obj ):
229 "Does obj claim to be some kind of ONOSCluster?"
230 return ( isinstance( obj, ONOSCluster ) or
231 'ONOSCluster' in type( obj ).__name__ )
232
233
Bob Lantz087b5d92016-05-06 11:39:04 -0700234class ONOSNode( Controller ):
235 "ONOS cluster node"
236
Bob Lantz087b5d92016-05-06 11:39:04 -0700237 def __init__( self, name, **kwargs ):
Bob Lantz64382422016-06-03 22:51:39 -0700238 "alertAction: exception|ignore|warn|exit (exception)"
Bob Lantz087b5d92016-05-06 11:39:04 -0700239 kwargs.update( inNamespace=True )
Bob Lantz64382422016-06-03 22:51:39 -0700240 self.alertAction = kwargs.pop( 'alertAction', 'exception' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700241 Controller.__init__( self, name, **kwargs )
242 self.dir = '/tmp/%s' % self.name
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700243 self.client = self.dir + '/karaf/bin/client'
Bob Lantz087b5d92016-05-06 11:39:04 -0700244 self.ONOS_HOME = '/tmp'
Bob Lantz55562ea2016-06-17 18:19:03 -0700245 self.cmd( 'rm -rf', self.dir )
246 self.ONOS_HOME = unpackONOS( self.dir, run=self.ucmd )
Jon Hall25485592016-08-19 13:56:14 -0700247 self.ONOS_ROOT = ONOS_ROOT
Bob Lantz087b5d92016-05-06 11:39:04 -0700248
249 # pylint: disable=arguments-differ
250
jaegonkim4e360492018-02-17 08:44:35 +0900251
jaegonkima1988f32018-04-09 22:52:26 +0900252 def start( self, env=None, nodes=(), debug=False ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700253 """Start ONOS on node
Bob Lantz569bbec2016-06-03 18:51:16 -0700254 env: environment var dict
255 nodes: all nodes in cluster"""
jaegonkim4e360492018-02-17 08:44:35 +0900256 if env is not None:
257 self.genStartConfig(env, nodes)
258 self.cmd( 'cd', self.ONOS_HOME )
jaegonkima1988f32018-04-09 22:52:26 +0900259 info( '(starting %s debug: %s)' % ( self, debug ) )
jaegonkim4e360492018-02-17 08:44:35 +0900260 service = join( self.ONOS_HOME, 'bin/onos-service' )
jaegonkima1988f32018-04-09 22:52:26 +0900261 if debug:
262 self.ucmd( service, 'server debug 1>../onos.log 2>../onos.log'
jaegonkim4e360492018-02-17 08:44:35 +0900263 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
jaegonkima1988f32018-04-09 22:52:26 +0900264 else:
265 self.ucmd( service, 'server 1>../onos.log 2>../onos.log'
266 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
jaegonkim4e360492018-02-17 08:44:35 +0900267 self.onosPid = int( self.cmd( 'cat onos.pid' ).strip() )
268 self.warningCount = 0
269
270 # pylint: disable=arguments-differ
271
272 def genStartConfig( self, env, nodes=() ):
273 """generate a start config"""
Bob Lantz087b5d92016-05-06 11:39:04 -0700274 env = dict( env )
Bob Lantz087b5d92016-05-06 11:39:04 -0700275 env.update( ONOS_HOME=self.ONOS_HOME )
276 self.updateEnv( env )
277 karafbin = glob( '%s/apache*/bin' % self.ONOS_HOME )[ 0 ]
278 onosbin = join( ONOS_ROOT, 'tools/test/bin' )
279 self.cmd( 'export PATH=%s:%s:$PATH' % ( onosbin, karafbin ) )
280 self.cmd( 'cd', self.ONOS_HOME )
Bob Lantz1451d722016-05-17 14:40:07 -0700281 self.ucmd( 'mkdir -p config && '
Bob Lantz569bbec2016-06-03 18:51:16 -0700282 'onos-gen-partitions config/cluster.json',
283 ' '.join( node.IP() for node in nodes ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700284
Carmelo Casconec52a4b12016-10-24 16:47:17 +0200285 def intfsDown( self ):
286 """Bring all interfaces down"""
287 for intf in self.intfs.values():
288 cmdOutput = intf.ifconfig( 'down' )
289 # no output indicates success
290 if cmdOutput:
291 error( "Error setting %s down: %s " % ( intf.name, cmdOutput ) )
292
293 def intfsUp( self ):
294 """Bring all interfaces up"""
295 for intf in self.intfs.values():
296 cmdOutput = intf.ifconfig( 'up' )
297 if cmdOutput:
298 error( "Error setting %s up: %s " % ( intf.name, cmdOutput ) )
299
jaegonkim4e360492018-02-17 08:44:35 +0900300 def kill( self ):
301 """Kill ONOS process"""
302 self.cmd( 'kill %d && wait' % ( self.onosPid ) )
303
Bob Lantz087b5d92016-05-06 11:39:04 -0700304 def stop( self ):
305 # XXX This will kill all karafs - too bad!
306 self.cmd( 'pkill -HUP -f karaf.jar && wait' )
307 self.cmd( 'rm -rf', self.dir )
308
Bob Lantz64382422016-06-03 22:51:39 -0700309 def sanityAlert( self, *args ):
310 "Alert to raise on sanityCheck failure"
311 info( '\n' )
312 if self.alertAction == 'exception':
313 raise Exception( *args )
314 if self.alertAction == 'warn':
315 warn( *args + ( '\n', ) )
316 elif self.alertAction == 'exit':
317 error( '***', *args +
318 ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) )
319 exit( 1 )
320
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700321 def isRunning( self ):
322 "Is our ONOS process still running?"
Bob Lantz64382422016-06-03 22:51:39 -0700323 cmd = ( 'ps -p %d >/dev/null 2>&1 && echo "running" ||'
324 'echo "not running"' )
325 return self.cmd( cmd % self.onosPid ).strip() == 'running'
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700326
Bob Lantz64382422016-06-03 22:51:39 -0700327 def checkLog( self ):
328 "Return log file errors and warnings"
329 log = join( self.dir, 'log' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700330 errors, warnings = [], []
Bob Lantz64382422016-06-03 22:51:39 -0700331 if isfile( log ):
332 lines = open( log ).read().split( '\n' )
333 errors = [ line for line in lines if 'ERROR' in line ]
334 warnings = [ line for line in lines if 'WARN'in line ]
335 return errors, warnings
336
337 def memAvailable( self ):
338 "Return available memory in KB (or -1 if we can't tell)"
339 lines = open( '/proc/meminfo' ).read().strip().split( '\n' )
340 entries = map( str.split, lines )
341 index = { entry[ 0 ]: entry for entry in entries }
342 # Check MemAvailable if present
343 default = ( None, '-1', 'kB' )
344 _name, count, unit = index.get( 'MemAvailable:', default )
345 if unit.lower() == 'kb':
346 return int( count )
347 return -1
348
349 def sanityCheck( self, lowMem=100000 ):
350 """Check whether we've quit or are running out of memory
351 lowMem: low memory threshold in KB (100000)"""
352 # Are we still running?
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700353 if not self.isRunning():
Bob Lantz64382422016-06-03 22:51:39 -0700354 self.sanityAlert( 'ONOS node %s has died' % self.name )
355 # Are there errors in the log file?
356 errors, warnings = self.checkLog()
357 if errors:
358 self.sanityAlert( 'ONOS startup errors:\n<<%s>>' %
359 '\n'.join( errors ) )
360 warningCount = len( warnings )
361 if warnings and warningCount > self.warningCount:
362 warn( '(%d warnings)' % len( warnings ) )
363 self.warningCount = warningCount
364 # Are we running out of memory?
365 mem = self.memAvailable()
366 if mem > 0 and mem < lowMem:
367 self.sanityAlert( 'Running out of memory (only %d KB available)'
368 % mem )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700369
Bob Lantz087b5d92016-05-06 11:39:04 -0700370 def waitStarted( self ):
371 "Wait until we've really started"
372 info( '(checking: karaf' )
373 while True:
Bob Lantz1451d722016-05-17 14:40:07 -0700374 status = self.ucmd( 'karaf status' ).lower()
Bob Lantz087b5d92016-05-06 11:39:04 -0700375 if 'running' in status and 'not running' not in status:
376 break
377 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700378 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700379 time.sleep( 1 )
380 info( ' ssh-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700381 waitListening( server=self, port=KarafPort, callback=self.sanityCheck )
Carmelo Casconec3baa4c2017-11-21 00:06:11 -0800382 info( ' protocol' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700383 while True:
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700384 result = quietRun( '%s -h %s "apps -a"' %
Bob Lantzbb37d872016-05-16 16:26:13 -0700385 ( self.client, self.IP() ), shell=True )
Carmelo Casconec3baa4c2017-11-21 00:06:11 -0800386 if 'openflow' in result or 'p4runtime' in result:
Bob Lantz087b5d92016-05-06 11:39:04 -0700387 break
388 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700389 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700390 time.sleep( 1 )
Jon Halla43d0332016-08-04 15:02:23 -0700391 info( ' node-status' )
392 while True:
393 result = quietRun( '%s -h %s "nodes"' %
394 ( self.client, self.IP() ), shell=True )
Carmelo Casconec3baa4c2017-11-21 00:06:11 -0800395 nodeStr = 'id=%s, address=%s:%s, state=READY' %\
Jon Halla43d0332016-08-04 15:02:23 -0700396 ( self.IP(), self.IP(), CopycatPort )
397 if nodeStr in result:
398 break
399 info( '.' )
400 self.sanityCheck()
401 time.sleep( 1 )
Bob Lantz087b5d92016-05-06 11:39:04 -0700402 info( ')\n' )
403
404 def updateEnv( self, envDict ):
405 "Update environment variables"
Bob Lantz569bbec2016-06-03 18:51:16 -0700406 cmd = ';'.join( ( 'export %s="%s"' % ( var, val )
407 if val else 'unset %s' % var )
Bob Lantz087b5d92016-05-06 11:39:04 -0700408 for var, val in envDict.iteritems() )
409 self.cmd( cmd )
410
Bob Lantz1451d722016-05-17 14:40:07 -0700411 def ucmd( self, *args, **_kwargs ):
412 "Run command as $ONOS_USER using sudo -E -u"
413 if ONOS_USER != 'root': # don't bother with sudo
414 args = [ "sudo -E -u $ONOS_USER PATH=$PATH "
415 "bash -c '%s'" % ' '.join( args ) ]
416 return self.cmd( *args )
417
Bob Lantz087b5d92016-05-06 11:39:04 -0700418
419class ONOSCluster( Controller ):
420 "ONOS Cluster"
Bob Lantz57635162016-08-29 15:13:54 -0700421 # Offset for port forwarding
422 portOffset = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700423 def __init__( self, *args, **kwargs ):
424 """name: (first parameter)
425 *args: topology class parameters
426 ipBase: IP range for ONOS nodes
Bob Lantz57635162016-08-29 15:13:54 -0700427 forward: default port forwarding list
428 portOffset: offset to port base (optional)
Bob Lantz087b5d92016-05-06 11:39:04 -0700429 topo: topology class or instance
Bob Lantz64382422016-06-03 22:51:39 -0700430 nodeOpts: ONOSNode options
jaegonkima1988f32018-04-09 22:52:26 +0900431 debug: enabling debug mode or not
Bob Lantz57635162016-08-29 15:13:54 -0700432 **kwargs: additional topology parameters
433 By default, multiple ONOSClusters will increment
434 the portOffset automatically; alternately, it can
435 be specified explicitly.
436 """
Bob Lantz087b5d92016-05-06 11:39:04 -0700437 args = list( args )
438 name = args.pop( 0 )
439 topo = kwargs.pop( 'topo', None )
Bob Lantz930138e2016-06-23 18:53:19 -0700440 self.nat = kwargs.pop( 'nat', 'nat0' )
Bob Lantz64382422016-06-03 22:51:39 -0700441 nodeOpts = kwargs.pop( 'nodeOpts', {} )
Bob Lantz57635162016-08-29 15:13:54 -0700442 self.portOffset = kwargs.pop( 'portOffset', ONOSCluster.portOffset )
Jon Hall9b238ae2016-08-09 13:47:43 -0700443 # Pass in kwargs to the ONOSNodes instead of the cluster
444 "alertAction: exception|ignore|warn|exit (exception)"
445 alertAction = kwargs.pop( 'alertAction', None )
446 if alertAction:
447 nodeOpts[ 'alertAction'] = alertAction
Bob Lantz087b5d92016-05-06 11:39:04 -0700448 # Default: single switch with 1 ONOS node
449 if not topo:
450 topo = SingleSwitchTopo
451 if not args:
452 args = ( 1, )
453 if not isinstance( topo, Topo ):
454 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700455 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
456 self.forward = kwargs.pop( 'forward',
457 [ KarafPort, GUIPort, OpenFlowPort ] )
jaegonkima1988f32018-04-09 22:52:26 +0900458 self.debug = kwargs.pop('debug', 'False') == 'True'
459
Bob Lantz087b5d92016-05-06 11:39:04 -0700460 super( ONOSCluster, self ).__init__( name, inNamespace=False )
461 fixIPTables()
462 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700463 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700464 host=partial( ONOSNode, **nodeOpts ),
465 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700466 controller=None )
Bob Lantz930138e2016-06-23 18:53:19 -0700467 if self.nat:
468 self.net.addNAT( self.nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700469 updateNodeIPs( self.env, self.nodes() )
470 self._remoteControllers = []
Bob Lantz57635162016-08-29 15:13:54 -0700471 # Update port offset for more ONOS clusters
472 ONOSCluster.portOffset += len( self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700473
474 def start( self ):
475 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700476 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
477 self.net.start()
478 for node in self.nodes():
jaegonkima1988f32018-04-09 22:52:26 +0900479 node.start( self.env, self.nodes(), self.debug )
Bob Lantz087b5d92016-05-06 11:39:04 -0700480 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700481 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700482 self.waitStarted()
483 return
484
485 def waitStarted( self ):
486 "Wait until all nodes have started"
487 startTime = time.time()
488 for node in self.nodes():
489 info( node )
490 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700491 info( '*** Waited %.2f seconds for ONOS startup' %
492 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700493
494 def stop( self ):
495 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700496 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700497 for node in self.nodes():
498 node.stop()
499 self.net.stop()
500
501 def nodes( self ):
502 "Return list of ONOS nodes"
Bob Lantz8e576252016-08-29 14:05:59 -0700503 return [ h for h in self.net.hosts if isONOSNode( h ) ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700504
Bob Lantz930138e2016-06-23 18:53:19 -0700505 def configPortForwarding( self, ports=[], action='A' ):
506 """Start or stop port forwarding (any intf) for all nodes
507 ports: list of ports to forward
Bob Lantzbb37d872016-05-16 16:26:13 -0700508 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz930138e2016-06-23 18:53:19 -0700509 self.cmd( 'iptables -' + action, 'FORWARD -d', self.ipBase,
510 '-j ACCEPT' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700511 for port in ports:
512 for index, node in enumerate( self.nodes() ):
Bob Lantz57635162016-08-29 15:13:54 -0700513 ip, inport = node.IP(), port + self.portOffset + index
Bob Lantzbb37d872016-05-16 16:26:13 -0700514 # Configure a destination NAT rule
Bob Lantz930138e2016-06-23 18:53:19 -0700515 self.cmd( 'iptables -t nat -' + action,
516 'PREROUTING -t nat -p tcp --dport', inport,
517 '-j DNAT --to-destination %s:%s' % ( ip, port ) )
Bob Lantzbb37d872016-05-16 16:26:13 -0700518
jaegonkim4e360492018-02-17 08:44:35 +0900519 def getONOSNode( self, instance ):
520 """Return ONOS node which name is 'instance'
521 instance: ONOS instance name"""
522 try:
523 onos = self.net.getNodeByName( instance )
524 if isONOSNode( onos ):
525 return onos
526 else:
527 info( 'instance %s is not ONOS.\n' % instance )
528 except KeyError:
529 info( 'No such ONOS instance %s.\n' % instance )
Bob Lantz57635162016-08-29 15:13:54 -0700530
Bob Lantz087b5d92016-05-06 11:39:04 -0700531class ONOSSwitchMixin( object ):
532 "Mixin for switches that connect to an ONOSCluster"
533 def start( self, controllers ):
534 "Connect to ONOSCluster"
535 self.controllers = controllers
536 assert ( len( controllers ) is 1 and
Bob Lantz8e576252016-08-29 14:05:59 -0700537 isONOSCluster( controllers[ 0 ] ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700538 clist = controllers[ 0 ].nodes()
539 return super( ONOSSwitchMixin, self ).start( clist )
540
541class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
542 "OVSSwitch that can connect to an ONOSCluster"
543 pass
544
545class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
546 "UserSwitch that can connect to an ONOSCluster"
547 pass
548
549
550### Ugly utility routines
551
552def fixIPTables():
553 "Fix LinuxBridge warning"
554 for s in 'arp', 'ip', 'ip6':
555 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
556
557
558### Test code
559
560def test( serverCount ):
561 "Test this setup"
562 setLogLevel( 'info' )
563 net = Mininet( topo=SingleSwitchTopo( 3 ),
564 controller=[ ONOSCluster( 'c0', serverCount ) ],
565 switch=ONOSOVSSwitch )
566 net.start()
567 net.waitConnected()
568 CLI( net )
569 net.stop()
570
571
572### CLI Extensions
573
574OldCLI = CLI
575
576class ONOSCLI( OldCLI ):
577 "CLI Extensions for ONOS"
578
579 prompt = 'mininet-onos> '
580
581 def __init__( self, net, **kwargs ):
Bob Lantz503a4022016-08-29 18:08:37 -0700582 clusters = [ c.net for c in net.controllers
583 if isONOSCluster( c ) ]
584 net = MininetFacade( net, *clusters )
Bob Lantz087b5d92016-05-06 11:39:04 -0700585 OldCLI.__init__( self, net, **kwargs )
586
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700587 def onos1( self ):
588 "Helper function: return default ONOS node"
589 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
590
Bob Lantz087b5d92016-05-06 11:39:04 -0700591 def do_onos( self, line ):
592 "Send command to ONOS CLI"
593 c0 = self.mn.controllers[ 0 ]
Bob Lantz8e576252016-08-29 14:05:59 -0700594 if isONOSCluster( c0 ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700595 # cmdLoop strips off command name 'onos'
596 if line.startswith( ':' ):
597 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700598 onos1 = self.onos1().name
599 if line:
600 line = '"%s"' % line
601 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700602 quietRun( 'stty -echo' )
603 self.default( cmd )
604 quietRun( 'stty echo' )
605
606 def do_wait( self, line ):
607 "Wait for switches to connect"
608 self.mn.waitConnected()
609
610 def do_balance( self, line ):
611 "Balance switch mastership"
612 self.do_onos( ':balance-masters' )
613
614 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700615 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700616 self.default( '%s tail -f /tmp/%s/log' %
617 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700618
Bob Lantz64382422016-06-03 22:51:39 -0700619 def do_status( self, line ):
620 "Return status of ONOS cluster(s)"
621 for c in self.mn.controllers:
Bob Lantz8e576252016-08-29 14:05:59 -0700622 if isONOSCluster( c ):
Bob Lantz64382422016-06-03 22:51:39 -0700623 for node in c.net.hosts:
Bob Lantz8e576252016-08-29 14:05:59 -0700624 if isONOSNode( node ):
Bob Lantz64382422016-06-03 22:51:39 -0700625 errors, warnings = node.checkLog()
626 running = ( 'Running' if node.isRunning()
627 else 'Exited' )
628 status = ''
629 if errors:
630 status += '%d ERRORS ' % len( errors )
631 if warnings:
632 status += '%d warnings' % len( warnings )
633 status = status if status else 'OK'
634 info( node, '\t', running, '\t', status, '\n' )
635
Bob Lantzc96e2582016-06-13 18:57:04 -0700636 def do_arp( self, line ):
637 "Send gratuitous arps from all data network hosts"
638 startTime = time.time()
639 try:
640 count = int( line )
641 except:
642 count = 1
643 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700644 if '-U' not in quietRun( 'arping -h', shell=True ):
645 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700646 return
647 # This is much faster if we do it in parallel
648 for host in self.mn.net.hosts:
649 intf = host.defaultIntf()
650 # -b: keep using broadcasts; -f: quit after 1 reply
651 # -U: gratuitous ARP update
652 host.sendCmd( 'arping -bf -c', count, '-U -I',
653 intf.name, intf.IP() )
654 for host in self.mn.net.hosts:
655 # We could check the output here if desired
656 host.waitOutput()
657 info( '.' )
658 info( '\n' )
659 elapsed = time.time() - startTime
660 debug( 'Completed in %.2f seconds\n' % elapsed )
661
Carmelo Casconec52a4b12016-10-24 16:47:17 +0200662 def onosupdown( self, cmd, instance ):
663 if not instance:
664 info( 'Provide the name of an ONOS instance.\n' )
665 return
666 c0 = self.mn.controllers[ 0 ]
667 if isONOSCluster( c0 ):
jaegonkim4e360492018-02-17 08:44:35 +0900668 onos = c0.getONOSNode( instance )
669 if onos:
670 info('Bringing %s %s...\n' % ( instance, cmd ) )
671 if cmd == 'up':
672 onos.intfsUp()
673 else:
674 onos.intfsDown()
Carmelo Casconec52a4b12016-10-24 16:47:17 +0200675
676 def do_onosdown( self, instance=None ):
677 """Disconnects an ONOS instance from the network"""
678 self.onosupdown( 'down', instance )
679
680 def do_onosup( self, instance=None ):
681 """"Connects an ONOS instance to the network"""
682 self.onosupdown( 'up', instance )
683
jaegonkim4e360492018-02-17 08:44:35 +0900684 def do_start( self, instance=None ):
685 """Start ONOS instance"""
686 if not instance:
687 info( 'Provide the name of an ONOS instance.\n' )
688 return
689 c0 = self.mn.controllers[ 0 ]
690 if isONOSCluster( c0 ):
691 onos = c0.getONOSNode( instance )
692 if onos:
693 info('Starting %s...\n' % ( instance ) )
jaegonkima1988f32018-04-09 22:52:26 +0900694 onos.start( debug=c0.debug )
jaegonkim4e360492018-02-17 08:44:35 +0900695
696 def do_kill( self, instance=None ):
697 """Kill ONOS instance"""
698 if not instance:
699 info( 'Provide the name of an ONOS instance.\n' )
700 return
701 c0 = self.mn.controllers[ 0 ]
702 if isONOSCluster( c0 ):
703 onos = c0.getONOSNode( instance )
704 if onos:
705 info('Killing %s...\n' % ( instance ) )
706 onos.kill()
Bob Lantz64382422016-06-03 22:51:39 -0700707
708# For interactive use, exit on error
709exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
710ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
711
Bob Lantz087b5d92016-05-06 11:39:04 -0700712
713### Exports for bin/mn
714
715CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700716controllers = { 'onos': ONOSClusterInteractive,
717 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700718
719# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700720findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700721
722switches = { 'onos': ONOSOVSSwitch,
723 'onosovs': ONOSOVSSwitch,
724 'onosuser': ONOSUserSwitch,
725 'default': ONOSOVSSwitch }
726
Bob Lantzbb37d872016-05-16 16:26:13 -0700727# Null topology so we can control an external/hardware network
728topos = { 'none': Topo }
729
Bob Lantz087b5d92016-05-06 11:39:04 -0700730if __name__ == '__main__':
731 if len( argv ) != 2:
732 test( 3 )
733 else:
734 test( int( argv[ 1 ] ) )