blob: c656a05717674459eeb610c6acb0e1f9ce0c578f [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
Carmelo Cascone3c8d3d02018-08-15 10:12:51 -070066DebugPort = 5005 # JVM debug port
Bob Lantz087b5d92016-05-06 11:39:04 -070067
68def defaultUser():
69 "Return a reasonable default user"
70 if 'SUDO_USER' in environ:
71 return environ[ 'SUDO_USER' ]
72 try:
73 user = quietRun( 'who am i' ).split()[ 0 ]
74 except:
75 user = 'nobody'
76 return user
77
Bob Lantz087b5d92016-05-06 11:39:04 -070078# Module vars, initialized below
Bob Lantz4b51d5c2016-05-27 14:47:38 -070079HOME = ONOS_ROOT = ONOS_USER = None
Lyndon Fawcettfbad2e72017-09-20 11:46:17 +000080ONOS_APPS = ONOS_WEB_USER = ONOS_WEB_PASS = ONOS_TAR = JAVA_OPTS = None
Bob Lantz087b5d92016-05-06 11:39:04 -070081
82def initONOSEnv():
83 """Initialize ONOS environment (and module) variables
84 This is ugly and painful, but they have to be set correctly
85 in order for the onos-setup-karaf script to work.
86 nodes: list of ONOS nodes
87 returns: ONOS environment variable dict"""
88 # pylint: disable=global-statement
Bob Lantz4b51d5c2016-05-27 14:47:38 -070089 global HOME, ONOS_ROOT, ONOS_USER
Bob Lantz087b5d92016-05-06 11:39:04 -070090 global ONOS_APPS, ONOS_WEB_USER, ONOS_WEB_PASS
91 env = {}
92 def sd( var, val ):
93 "Set default value for environment variable"
94 env[ var ] = environ.setdefault( var, val )
95 return env[ var ]
Bob Lantz4b51d5c2016-05-27 14:47:38 -070096 assert environ[ 'HOME' ]
Bob Lantz087b5d92016-05-06 11:39:04 -070097 HOME = sd( 'HOME', environ[ 'HOME' ] )
Bob Lantz087b5d92016-05-06 11:39:04 -070098 ONOS_ROOT = sd( 'ONOS_ROOT', join( HOME, 'onos' ) )
Bob Lantz087b5d92016-05-06 11:39:04 -070099 environ[ 'ONOS_USER' ] = defaultUser()
100 ONOS_USER = sd( 'ONOS_USER', defaultUser() )
101 ONOS_APPS = sd( 'ONOS_APPS',
102 'drivers,openflow,fwd,proxyarp,mobility' )
Lyndon Fawcettfbad2e72017-09-20 11:46:17 +0000103 JAVA_OPTS = sd( 'JAVA_OPTS', '-Xms128m -Xmx512m' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700104 # ONOS_WEB_{USER,PASS} isn't respected by onos-karaf:
105 environ.update( ONOS_WEB_USER='karaf', ONOS_WEB_PASS='karaf' )
106 ONOS_WEB_USER = sd( 'ONOS_WEB_USER', 'karaf' )
107 ONOS_WEB_PASS = sd( 'ONOS_WEB_PASS', 'karaf' )
108 return env
109
110
111def updateNodeIPs( env, nodes ):
112 "Update env dict and environ with node IPs"
113 # Get rid of stale junk
114 for var in 'ONOS_NIC', 'ONOS_CELL', 'ONOS_INSTANCES':
115 env[ var ] = ''
116 for var in environ.keys():
117 if var.startswith( 'OC' ):
118 env[ var ] = ''
119 for index, node in enumerate( nodes, 1 ):
120 var = 'OC%d' % index
121 env[ var ] = node.IP()
Jon Hall25485592016-08-19 13:56:14 -0700122 if nodes:
123 env[ 'OCI' ] = env[ 'OCN' ] = env[ 'OC1' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700124 env[ 'ONOS_INSTANCES' ] = '\n'.join(
125 node.IP() for node in nodes )
126 environ.update( env )
127 return env
128
129
130tarDefaultPath = 'buck-out/gen/tools/package/onos-package/onos.tar.gz'
131
Bob Lantz1451d722016-05-17 14:40:07 -0700132def unpackONOS( destDir='/tmp', run=quietRun ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700133 "Unpack ONOS and return its location"
134 global ONOS_TAR
135 environ.setdefault( 'ONOS_TAR', join( ONOS_ROOT, tarDefaultPath ) )
136 ONOS_TAR = environ[ 'ONOS_TAR' ]
137 tarPath = ONOS_TAR
138 if not isfile( tarPath ):
139 raise Exception( 'Missing ONOS tarball %s - run buck build onos?'
140 % tarPath )
141 info( '(unpacking %s)' % destDir)
Bob Lantza2ccaa52016-06-29 18:26:06 -0700142 success = '*** SUCCESS ***'
143 cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s" && echo "%s"'
144 % ( destDir, destDir, tarPath, success ) )
145 result = run( cmds, shell=True, verbose=True )
146 if success not in result:
147 raise Exception( 'Failed to unpack ONOS archive %s in %s:\n%s\n' %
148 ( tarPath, destDir, result ) )
Bob Lantz1451d722016-05-17 14:40:07 -0700149 # We can use quietRun for this usually
150 tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True)
151 tarOutput = tarOutput.split()[ 0 ].strip()
152 assert '/' in tarOutput
153 onosDir = join( destDir, dirname( tarOutput ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700154 # Add symlink to log file
Bob Lantz1451d722016-05-17 14:40:07 -0700155 run( 'cd %s; ln -s onos*/apache* karaf;'
156 'ln -s karaf/data/log/karaf.log log' % destDir,
157 shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700158 return onosDir
159
160
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700161def waitListening( server, port=80, callback=None, sleepSecs=.5,
162 proc='java' ):
163 "Simplified netstat version of waitListening"
164 while True:
165 lines = server.cmd( 'netstat -natp' ).strip().split( '\n' )
166 entries = [ line.split() for line in lines ]
167 portstr = ':%s' % port
168 listening = [ entry for entry in entries
169 if len( entry ) > 6 and portstr in entry[ 3 ]
170 and proc in entry[ 6 ] ]
171 if listening:
172 break
Bob Lantz64382422016-06-03 22:51:39 -0700173 info( '.' )
174 if callback:
175 callback()
176 time.sleep( sleepSecs )
Bob Lantz64382422016-06-03 22:51:39 -0700177
178
Bob Lantz087b5d92016-05-06 11:39:04 -0700179### Mininet classes
180
181def RenamedTopo( topo, *args, **kwargs ):
182 """Return specialized topo with renamed hosts
183 topo: topo class/class name to specialize
184 args, kwargs: topo args
185 sold: old switch name prefix (default 's')
186 snew: new switch name prefix
187 hold: old host name prefix (default 'h')
188 hnew: new host name prefix
189 This may be used from the mn command, e.g.
190 mn --topo renamed,single,spref=sw,hpref=host"""
191 sold = kwargs.pop( 'sold', 's' )
192 hold = kwargs.pop( 'hold', 'h' )
193 snew = kwargs.pop( 'snew', 'cs' )
194 hnew = kwargs.pop( 'hnew' ,'ch' )
195 topos = {} # TODO: use global TOPOS dict
196 if isinstance( topo, str ):
197 # Look up in topo directory - this allows us to
198 # use RenamedTopo from the command line!
199 if topo in topos:
200 topo = topos.get( topo )
201 else:
202 raise Exception( 'Unknown topo name: %s' % topo )
203 # pylint: disable=no-init
204 class RenamedTopoCls( topo ):
205 "Topo subclass with renamed nodes"
206 def addNode( self, name, *args, **kwargs ):
207 "Add a node, renaming if necessary"
208 if name.startswith( sold ):
209 name = snew + name[ len( sold ): ]
210 elif name.startswith( hold ):
211 name = hnew + name[ len( hold ): ]
212 return topo.addNode( self, name, *args, **kwargs )
213 return RenamedTopoCls( *args, **kwargs )
214
215
Bob Lantz8e576252016-08-29 14:05:59 -0700216# We accept objects that "claim" to be a particular class,
217# since the class definitions can be both execed (--custom) and
218# imported (in another custom file), which breaks isinstance().
219# In order for this to work properly, a class should not be
220# renamed so as to inappropriately omit or include the class
221# name text. Note that mininet.util.specialClass renames classes
222# by adding the specialized parameter names and values.
223
224def isONOSNode( obj ):
225 "Does obj claim to be some kind of ONOSNode?"
226 return ( isinstance( obj, ONOSNode) or
227 'ONOSNode' in type( obj ).__name__ )
228
229def isONOSCluster( obj ):
230 "Does obj claim to be some kind of ONOSCluster?"
231 return ( isinstance( obj, ONOSCluster ) or
232 'ONOSCluster' in type( obj ).__name__ )
233
234
Bob Lantz087b5d92016-05-06 11:39:04 -0700235class ONOSNode( Controller ):
236 "ONOS cluster node"
237
Bob Lantz087b5d92016-05-06 11:39:04 -0700238 def __init__( self, name, **kwargs ):
Bob Lantz64382422016-06-03 22:51:39 -0700239 "alertAction: exception|ignore|warn|exit (exception)"
Bob Lantz087b5d92016-05-06 11:39:04 -0700240 kwargs.update( inNamespace=True )
Bob Lantz64382422016-06-03 22:51:39 -0700241 self.alertAction = kwargs.pop( 'alertAction', 'exception' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700242 Controller.__init__( self, name, **kwargs )
243 self.dir = '/tmp/%s' % self.name
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700244 self.client = self.dir + '/karaf/bin/client'
Bob Lantz087b5d92016-05-06 11:39:04 -0700245 self.ONOS_HOME = '/tmp'
Bob Lantz55562ea2016-06-17 18:19:03 -0700246 self.cmd( 'rm -rf', self.dir )
247 self.ONOS_HOME = unpackONOS( self.dir, run=self.ucmd )
Jon Hall25485592016-08-19 13:56:14 -0700248 self.ONOS_ROOT = ONOS_ROOT
Bob Lantz087b5d92016-05-06 11:39:04 -0700249
250 # pylint: disable=arguments-differ
251
jaegonkim4e360492018-02-17 08:44:35 +0900252
jaegonkima1988f32018-04-09 22:52:26 +0900253 def start( self, env=None, nodes=(), debug=False ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700254 """Start ONOS on node
Bob Lantz569bbec2016-06-03 18:51:16 -0700255 env: environment var dict
256 nodes: all nodes in cluster"""
jaegonkim4e360492018-02-17 08:44:35 +0900257 if env is not None:
258 self.genStartConfig(env, nodes)
259 self.cmd( 'cd', self.ONOS_HOME )
jaegonkima1988f32018-04-09 22:52:26 +0900260 info( '(starting %s debug: %s)' % ( self, debug ) )
jaegonkim4e360492018-02-17 08:44:35 +0900261 service = join( self.ONOS_HOME, 'bin/onos-service' )
jaegonkima1988f32018-04-09 22:52:26 +0900262 if debug:
263 self.ucmd( service, 'server debug 1>../onos.log 2>../onos.log'
jaegonkim4e360492018-02-17 08:44:35 +0900264 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
jaegonkima1988f32018-04-09 22:52:26 +0900265 else:
266 self.ucmd( service, 'server 1>../onos.log 2>../onos.log'
267 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
jaegonkim4e360492018-02-17 08:44:35 +0900268 self.onosPid = int( self.cmd( 'cat onos.pid' ).strip() )
269 self.warningCount = 0
270
271 # pylint: disable=arguments-differ
272
273 def genStartConfig( self, env, nodes=() ):
274 """generate a start config"""
Bob Lantz087b5d92016-05-06 11:39:04 -0700275 env = dict( env )
Bob Lantz087b5d92016-05-06 11:39:04 -0700276 env.update( ONOS_HOME=self.ONOS_HOME )
277 self.updateEnv( env )
278 karafbin = glob( '%s/apache*/bin' % self.ONOS_HOME )[ 0 ]
279 onosbin = join( ONOS_ROOT, 'tools/test/bin' )
280 self.cmd( 'export PATH=%s:%s:$PATH' % ( onosbin, karafbin ) )
281 self.cmd( 'cd', self.ONOS_HOME )
Bob Lantz1451d722016-05-17 14:40:07 -0700282 self.ucmd( 'mkdir -p config && '
Bob Lantz569bbec2016-06-03 18:51:16 -0700283 'onos-gen-partitions config/cluster.json',
284 ' '.join( node.IP() for node in nodes ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700285
Carmelo Casconec52a4b12016-10-24 16:47:17 +0200286 def intfsDown( self ):
287 """Bring all interfaces down"""
288 for intf in self.intfs.values():
289 cmdOutput = intf.ifconfig( 'down' )
290 # no output indicates success
291 if cmdOutput:
292 error( "Error setting %s down: %s " % ( intf.name, cmdOutput ) )
293
294 def intfsUp( self ):
295 """Bring all interfaces up"""
296 for intf in self.intfs.values():
297 cmdOutput = intf.ifconfig( 'up' )
298 if cmdOutput:
299 error( "Error setting %s up: %s " % ( intf.name, cmdOutput ) )
300
jaegonkim4e360492018-02-17 08:44:35 +0900301 def kill( self ):
302 """Kill ONOS process"""
303 self.cmd( 'kill %d && wait' % ( self.onosPid ) )
304
Bob Lantz087b5d92016-05-06 11:39:04 -0700305 def stop( self ):
306 # XXX This will kill all karafs - too bad!
307 self.cmd( 'pkill -HUP -f karaf.jar && wait' )
308 self.cmd( 'rm -rf', self.dir )
309
Bob Lantz64382422016-06-03 22:51:39 -0700310 def sanityAlert( self, *args ):
311 "Alert to raise on sanityCheck failure"
312 info( '\n' )
313 if self.alertAction == 'exception':
314 raise Exception( *args )
315 if self.alertAction == 'warn':
316 warn( *args + ( '\n', ) )
317 elif self.alertAction == 'exit':
318 error( '***', *args +
319 ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) )
320 exit( 1 )
321
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700322 def isRunning( self ):
323 "Is our ONOS process still running?"
Bob Lantz64382422016-06-03 22:51:39 -0700324 cmd = ( 'ps -p %d >/dev/null 2>&1 && echo "running" ||'
325 'echo "not running"' )
326 return self.cmd( cmd % self.onosPid ).strip() == 'running'
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700327
Bob Lantz64382422016-06-03 22:51:39 -0700328 def checkLog( self ):
329 "Return log file errors and warnings"
330 log = join( self.dir, 'log' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700331 errors, warnings = [], []
Bob Lantz64382422016-06-03 22:51:39 -0700332 if isfile( log ):
333 lines = open( log ).read().split( '\n' )
334 errors = [ line for line in lines if 'ERROR' in line ]
335 warnings = [ line for line in lines if 'WARN'in line ]
336 return errors, warnings
337
338 def memAvailable( self ):
339 "Return available memory in KB (or -1 if we can't tell)"
340 lines = open( '/proc/meminfo' ).read().strip().split( '\n' )
341 entries = map( str.split, lines )
342 index = { entry[ 0 ]: entry for entry in entries }
343 # Check MemAvailable if present
344 default = ( None, '-1', 'kB' )
345 _name, count, unit = index.get( 'MemAvailable:', default )
346 if unit.lower() == 'kb':
347 return int( count )
348 return -1
349
350 def sanityCheck( self, lowMem=100000 ):
351 """Check whether we've quit or are running out of memory
352 lowMem: low memory threshold in KB (100000)"""
353 # Are we still running?
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700354 if not self.isRunning():
Bob Lantz64382422016-06-03 22:51:39 -0700355 self.sanityAlert( 'ONOS node %s has died' % self.name )
356 # Are there errors in the log file?
357 errors, warnings = self.checkLog()
358 if errors:
359 self.sanityAlert( 'ONOS startup errors:\n<<%s>>' %
360 '\n'.join( errors ) )
361 warningCount = len( warnings )
362 if warnings and warningCount > self.warningCount:
363 warn( '(%d warnings)' % len( warnings ) )
364 self.warningCount = warningCount
365 # Are we running out of memory?
366 mem = self.memAvailable()
367 if mem > 0 and mem < lowMem:
368 self.sanityAlert( 'Running out of memory (only %d KB available)'
369 % mem )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700370
Bob Lantz087b5d92016-05-06 11:39:04 -0700371 def waitStarted( self ):
372 "Wait until we've really started"
373 info( '(checking: karaf' )
374 while True:
Bob Lantz1451d722016-05-17 14:40:07 -0700375 status = self.ucmd( 'karaf status' ).lower()
Bob Lantz087b5d92016-05-06 11:39:04 -0700376 if 'running' in status and 'not running' not in status:
377 break
378 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700379 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700380 time.sleep( 1 )
381 info( ' ssh-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700382 waitListening( server=self, port=KarafPort, callback=self.sanityCheck )
Carmelo Casconec3baa4c2017-11-21 00:06:11 -0800383 info( ' protocol' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700384 while True:
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700385 result = quietRun( '%s -h %s "apps -a"' %
Bob Lantzbb37d872016-05-16 16:26:13 -0700386 ( self.client, self.IP() ), shell=True )
Carmelo Casconec3baa4c2017-11-21 00:06:11 -0800387 if 'openflow' in result or 'p4runtime' in result:
Bob Lantz087b5d92016-05-06 11:39:04 -0700388 break
389 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700390 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700391 time.sleep( 1 )
Jon Halla43d0332016-08-04 15:02:23 -0700392 info( ' node-status' )
393 while True:
394 result = quietRun( '%s -h %s "nodes"' %
395 ( self.client, self.IP() ), shell=True )
Carmelo Casconec3baa4c2017-11-21 00:06:11 -0800396 nodeStr = 'id=%s, address=%s:%s, state=READY' %\
Jon Halla43d0332016-08-04 15:02:23 -0700397 ( self.IP(), self.IP(), CopycatPort )
398 if nodeStr in result:
399 break
400 info( '.' )
401 self.sanityCheck()
402 time.sleep( 1 )
Bob Lantz087b5d92016-05-06 11:39:04 -0700403 info( ')\n' )
404
405 def updateEnv( self, envDict ):
406 "Update environment variables"
Bob Lantz569bbec2016-06-03 18:51:16 -0700407 cmd = ';'.join( ( 'export %s="%s"' % ( var, val )
408 if val else 'unset %s' % var )
Bob Lantz087b5d92016-05-06 11:39:04 -0700409 for var, val in envDict.iteritems() )
410 self.cmd( cmd )
411
Bob Lantz1451d722016-05-17 14:40:07 -0700412 def ucmd( self, *args, **_kwargs ):
413 "Run command as $ONOS_USER using sudo -E -u"
414 if ONOS_USER != 'root': # don't bother with sudo
415 args = [ "sudo -E -u $ONOS_USER PATH=$PATH "
416 "bash -c '%s'" % ' '.join( args ) ]
417 return self.cmd( *args )
418
Bob Lantz087b5d92016-05-06 11:39:04 -0700419
420class ONOSCluster( Controller ):
421 "ONOS Cluster"
Bob Lantz57635162016-08-29 15:13:54 -0700422 # Offset for port forwarding
423 portOffset = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700424 def __init__( self, *args, **kwargs ):
425 """name: (first parameter)
426 *args: topology class parameters
427 ipBase: IP range for ONOS nodes
Bob Lantz57635162016-08-29 15:13:54 -0700428 forward: default port forwarding list
429 portOffset: offset to port base (optional)
Bob Lantz087b5d92016-05-06 11:39:04 -0700430 topo: topology class or instance
Bob Lantz64382422016-06-03 22:51:39 -0700431 nodeOpts: ONOSNode options
jaegonkima1988f32018-04-09 22:52:26 +0900432 debug: enabling debug mode or not
Bob Lantz57635162016-08-29 15:13:54 -0700433 **kwargs: additional topology parameters
434 By default, multiple ONOSClusters will increment
435 the portOffset automatically; alternately, it can
436 be specified explicitly.
437 """
Bob Lantz087b5d92016-05-06 11:39:04 -0700438 args = list( args )
439 name = args.pop( 0 )
440 topo = kwargs.pop( 'topo', None )
Bob Lantz930138e2016-06-23 18:53:19 -0700441 self.nat = kwargs.pop( 'nat', 'nat0' )
Bob Lantz64382422016-06-03 22:51:39 -0700442 nodeOpts = kwargs.pop( 'nodeOpts', {} )
Bob Lantz57635162016-08-29 15:13:54 -0700443 self.portOffset = kwargs.pop( 'portOffset', ONOSCluster.portOffset )
Jon Hall9b238ae2016-08-09 13:47:43 -0700444 # Pass in kwargs to the ONOSNodes instead of the cluster
445 "alertAction: exception|ignore|warn|exit (exception)"
446 alertAction = kwargs.pop( 'alertAction', None )
447 if alertAction:
448 nodeOpts[ 'alertAction'] = alertAction
Bob Lantz087b5d92016-05-06 11:39:04 -0700449 # Default: single switch with 1 ONOS node
450 if not topo:
451 topo = SingleSwitchTopo
452 if not args:
453 args = ( 1, )
454 if not isinstance( topo, Topo ):
455 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700456 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
457 self.forward = kwargs.pop( 'forward',
Carmelo Cascone3c8d3d02018-08-15 10:12:51 -0700458 [ KarafPort, GUIPort, OpenFlowPort, DebugPort ] )
jaegonkima1988f32018-04-09 22:52:26 +0900459 self.debug = kwargs.pop('debug', 'False') == 'True'
460
Bob Lantz087b5d92016-05-06 11:39:04 -0700461 super( ONOSCluster, self ).__init__( name, inNamespace=False )
462 fixIPTables()
463 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700464 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700465 host=partial( ONOSNode, **nodeOpts ),
466 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700467 controller=None )
Bob Lantz930138e2016-06-23 18:53:19 -0700468 if self.nat:
469 self.net.addNAT( self.nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700470 updateNodeIPs( self.env, self.nodes() )
471 self._remoteControllers = []
Bob Lantz57635162016-08-29 15:13:54 -0700472 # Update port offset for more ONOS clusters
473 ONOSCluster.portOffset += len( self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700474
475 def start( self ):
476 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700477 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
478 self.net.start()
479 for node in self.nodes():
jaegonkima1988f32018-04-09 22:52:26 +0900480 node.start( self.env, self.nodes(), self.debug )
Bob Lantz087b5d92016-05-06 11:39:04 -0700481 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700482 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700483 self.waitStarted()
484 return
485
486 def waitStarted( self ):
487 "Wait until all nodes have started"
488 startTime = time.time()
489 for node in self.nodes():
490 info( node )
491 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700492 info( '*** Waited %.2f seconds for ONOS startup' %
493 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700494
495 def stop( self ):
496 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700497 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700498 for node in self.nodes():
499 node.stop()
500 self.net.stop()
501
502 def nodes( self ):
503 "Return list of ONOS nodes"
Bob Lantz8e576252016-08-29 14:05:59 -0700504 return [ h for h in self.net.hosts if isONOSNode( h ) ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700505
Bob Lantz930138e2016-06-23 18:53:19 -0700506 def configPortForwarding( self, ports=[], action='A' ):
507 """Start or stop port forwarding (any intf) for all nodes
508 ports: list of ports to forward
Bob Lantzbb37d872016-05-16 16:26:13 -0700509 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz930138e2016-06-23 18:53:19 -0700510 self.cmd( 'iptables -' + action, 'FORWARD -d', self.ipBase,
511 '-j ACCEPT' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700512 for port in ports:
513 for index, node in enumerate( self.nodes() ):
Bob Lantz57635162016-08-29 15:13:54 -0700514 ip, inport = node.IP(), port + self.portOffset + index
Bob Lantzbb37d872016-05-16 16:26:13 -0700515 # Configure a destination NAT rule
Bob Lantz930138e2016-06-23 18:53:19 -0700516 self.cmd( 'iptables -t nat -' + action,
517 'PREROUTING -t nat -p tcp --dport', inport,
518 '-j DNAT --to-destination %s:%s' % ( ip, port ) )
Bob Lantzbb37d872016-05-16 16:26:13 -0700519
jaegonkim4e360492018-02-17 08:44:35 +0900520 def getONOSNode( self, instance ):
521 """Return ONOS node which name is 'instance'
522 instance: ONOS instance name"""
523 try:
524 onos = self.net.getNodeByName( instance )
525 if isONOSNode( onos ):
526 return onos
527 else:
528 info( 'instance %s is not ONOS.\n' % instance )
529 except KeyError:
530 info( 'No such ONOS instance %s.\n' % instance )
Bob Lantz57635162016-08-29 15:13:54 -0700531
Bob Lantz087b5d92016-05-06 11:39:04 -0700532class ONOSSwitchMixin( object ):
533 "Mixin for switches that connect to an ONOSCluster"
534 def start( self, controllers ):
535 "Connect to ONOSCluster"
536 self.controllers = controllers
537 assert ( len( controllers ) is 1 and
Bob Lantz8e576252016-08-29 14:05:59 -0700538 isONOSCluster( controllers[ 0 ] ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700539 clist = controllers[ 0 ].nodes()
540 return super( ONOSSwitchMixin, self ).start( clist )
541
542class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
543 "OVSSwitch that can connect to an ONOSCluster"
544 pass
545
546class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
547 "UserSwitch that can connect to an ONOSCluster"
548 pass
549
550
551### Ugly utility routines
552
553def fixIPTables():
554 "Fix LinuxBridge warning"
555 for s in 'arp', 'ip', 'ip6':
556 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
557
558
559### Test code
560
561def test( serverCount ):
562 "Test this setup"
563 setLogLevel( 'info' )
564 net = Mininet( topo=SingleSwitchTopo( 3 ),
565 controller=[ ONOSCluster( 'c0', serverCount ) ],
566 switch=ONOSOVSSwitch )
567 net.start()
568 net.waitConnected()
569 CLI( net )
570 net.stop()
571
572
573### CLI Extensions
574
575OldCLI = CLI
576
577class ONOSCLI( OldCLI ):
578 "CLI Extensions for ONOS"
579
580 prompt = 'mininet-onos> '
581
582 def __init__( self, net, **kwargs ):
Bob Lantz503a4022016-08-29 18:08:37 -0700583 clusters = [ c.net for c in net.controllers
584 if isONOSCluster( c ) ]
585 net = MininetFacade( net, *clusters )
Bob Lantz087b5d92016-05-06 11:39:04 -0700586 OldCLI.__init__( self, net, **kwargs )
587
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700588 def onos1( self ):
589 "Helper function: return default ONOS node"
590 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
591
Bob Lantz087b5d92016-05-06 11:39:04 -0700592 def do_onos( self, line ):
593 "Send command to ONOS CLI"
594 c0 = self.mn.controllers[ 0 ]
Bob Lantz8e576252016-08-29 14:05:59 -0700595 if isONOSCluster( c0 ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700596 # cmdLoop strips off command name 'onos'
597 if line.startswith( ':' ):
598 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700599 onos1 = self.onos1().name
600 if line:
601 line = '"%s"' % line
602 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700603 quietRun( 'stty -echo' )
604 self.default( cmd )
605 quietRun( 'stty echo' )
606
607 def do_wait( self, line ):
608 "Wait for switches to connect"
609 self.mn.waitConnected()
610
611 def do_balance( self, line ):
612 "Balance switch mastership"
613 self.do_onos( ':balance-masters' )
614
615 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700616 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700617 self.default( '%s tail -f /tmp/%s/log' %
618 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700619
Bob Lantz64382422016-06-03 22:51:39 -0700620 def do_status( self, line ):
621 "Return status of ONOS cluster(s)"
622 for c in self.mn.controllers:
Bob Lantz8e576252016-08-29 14:05:59 -0700623 if isONOSCluster( c ):
Bob Lantz64382422016-06-03 22:51:39 -0700624 for node in c.net.hosts:
Bob Lantz8e576252016-08-29 14:05:59 -0700625 if isONOSNode( node ):
Bob Lantz64382422016-06-03 22:51:39 -0700626 errors, warnings = node.checkLog()
627 running = ( 'Running' if node.isRunning()
628 else 'Exited' )
629 status = ''
630 if errors:
631 status += '%d ERRORS ' % len( errors )
632 if warnings:
633 status += '%d warnings' % len( warnings )
634 status = status if status else 'OK'
635 info( node, '\t', running, '\t', status, '\n' )
636
Bob Lantzc96e2582016-06-13 18:57:04 -0700637 def do_arp( self, line ):
638 "Send gratuitous arps from all data network hosts"
639 startTime = time.time()
640 try:
641 count = int( line )
642 except:
643 count = 1
644 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700645 if '-U' not in quietRun( 'arping -h', shell=True ):
646 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700647 return
648 # This is much faster if we do it in parallel
649 for host in self.mn.net.hosts:
650 intf = host.defaultIntf()
651 # -b: keep using broadcasts; -f: quit after 1 reply
652 # -U: gratuitous ARP update
653 host.sendCmd( 'arping -bf -c', count, '-U -I',
654 intf.name, intf.IP() )
655 for host in self.mn.net.hosts:
656 # We could check the output here if desired
657 host.waitOutput()
658 info( '.' )
659 info( '\n' )
660 elapsed = time.time() - startTime
661 debug( 'Completed in %.2f seconds\n' % elapsed )
662
Carmelo Casconec52a4b12016-10-24 16:47:17 +0200663 def onosupdown( self, cmd, instance ):
664 if not instance:
665 info( 'Provide the name of an ONOS instance.\n' )
666 return
667 c0 = self.mn.controllers[ 0 ]
668 if isONOSCluster( c0 ):
jaegonkim4e360492018-02-17 08:44:35 +0900669 onos = c0.getONOSNode( instance )
670 if onos:
671 info('Bringing %s %s...\n' % ( instance, cmd ) )
672 if cmd == 'up':
673 onos.intfsUp()
674 else:
675 onos.intfsDown()
Carmelo Casconec52a4b12016-10-24 16:47:17 +0200676
677 def do_onosdown( self, instance=None ):
678 """Disconnects an ONOS instance from the network"""
679 self.onosupdown( 'down', instance )
680
681 def do_onosup( self, instance=None ):
682 """"Connects an ONOS instance to the network"""
683 self.onosupdown( 'up', instance )
684
jaegonkim4e360492018-02-17 08:44:35 +0900685 def do_start( self, instance=None ):
686 """Start ONOS instance"""
687 if not instance:
688 info( 'Provide the name of an ONOS instance.\n' )
689 return
690 c0 = self.mn.controllers[ 0 ]
691 if isONOSCluster( c0 ):
692 onos = c0.getONOSNode( instance )
693 if onos:
694 info('Starting %s...\n' % ( instance ) )
jaegonkima1988f32018-04-09 22:52:26 +0900695 onos.start( debug=c0.debug )
jaegonkim4e360492018-02-17 08:44:35 +0900696
697 def do_kill( self, instance=None ):
698 """Kill ONOS instance"""
699 if not instance:
700 info( 'Provide the name of an ONOS instance.\n' )
701 return
702 c0 = self.mn.controllers[ 0 ]
703 if isONOSCluster( c0 ):
704 onos = c0.getONOSNode( instance )
705 if onos:
706 info('Killing %s...\n' % ( instance ) )
707 onos.kill()
Bob Lantz64382422016-06-03 22:51:39 -0700708
709# For interactive use, exit on error
710exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
711ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
712
Bob Lantz087b5d92016-05-06 11:39:04 -0700713
714### Exports for bin/mn
715
716CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700717controllers = { 'onos': ONOSClusterInteractive,
718 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700719
720# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700721findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700722
723switches = { 'onos': ONOSOVSSwitch,
724 'onosovs': ONOSOVSSwitch,
725 'onosuser': ONOSUserSwitch,
726 'default': ONOSOVSSwitch }
727
Bob Lantzbb37d872016-05-16 16:26:13 -0700728# Null topology so we can control an external/hardware network
729topos = { 'none': Topo }
730
Bob Lantz087b5d92016-05-06 11:39:04 -0700731if __name__ == '__main__':
732 if len( argv ) != 2:
733 test( 3 )
734 else:
735 test( int( argv[ 1 ] ) )