blob: 1f69e0f44b186499aa53e6c87e5b70d20b2c03bb [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
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 Lantza2ccaa52016-06-29 18:26:06 -0700139 success = '*** SUCCESS ***'
140 cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s" && echo "%s"'
141 % ( destDir, destDir, tarPath, success ) )
142 result = run( cmds, shell=True, verbose=True )
143 if success not in result:
144 raise Exception( 'Failed to unpack ONOS archive %s in %s:\n%s\n' %
145 ( tarPath, destDir, result ) )
Bob Lantz1451d722016-05-17 14:40:07 -0700146 # We can use quietRun for this usually
147 tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True)
148 tarOutput = tarOutput.split()[ 0 ].strip()
149 assert '/' in tarOutput
150 onosDir = join( destDir, dirname( tarOutput ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700151 # Add symlink to log file
Bob Lantz1451d722016-05-17 14:40:07 -0700152 run( 'cd %s; ln -s onos*/apache* karaf;'
153 'ln -s karaf/data/log/karaf.log log' % destDir,
154 shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700155 return onosDir
156
157
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700158def waitListening( server, port=80, callback=None, sleepSecs=.5,
159 proc='java' ):
160 "Simplified netstat version of waitListening"
161 while True:
162 lines = server.cmd( 'netstat -natp' ).strip().split( '\n' )
163 entries = [ line.split() for line in lines ]
164 portstr = ':%s' % port
165 listening = [ entry for entry in entries
166 if len( entry ) > 6 and portstr in entry[ 3 ]
167 and proc in entry[ 6 ] ]
168 if listening:
169 break
Bob Lantz64382422016-06-03 22:51:39 -0700170 info( '.' )
171 if callback:
172 callback()
173 time.sleep( sleepSecs )
Bob Lantz64382422016-06-03 22:51:39 -0700174
175
Bob Lantz087b5d92016-05-06 11:39:04 -0700176### Mininet classes
177
178def RenamedTopo( topo, *args, **kwargs ):
179 """Return specialized topo with renamed hosts
180 topo: topo class/class name to specialize
181 args, kwargs: topo args
182 sold: old switch name prefix (default 's')
183 snew: new switch name prefix
184 hold: old host name prefix (default 'h')
185 hnew: new host name prefix
186 This may be used from the mn command, e.g.
187 mn --topo renamed,single,spref=sw,hpref=host"""
188 sold = kwargs.pop( 'sold', 's' )
189 hold = kwargs.pop( 'hold', 'h' )
190 snew = kwargs.pop( 'snew', 'cs' )
191 hnew = kwargs.pop( 'hnew' ,'ch' )
192 topos = {} # TODO: use global TOPOS dict
193 if isinstance( topo, str ):
194 # Look up in topo directory - this allows us to
195 # use RenamedTopo from the command line!
196 if topo in topos:
197 topo = topos.get( topo )
198 else:
199 raise Exception( 'Unknown topo name: %s' % topo )
200 # pylint: disable=no-init
201 class RenamedTopoCls( topo ):
202 "Topo subclass with renamed nodes"
203 def addNode( self, name, *args, **kwargs ):
204 "Add a node, renaming if necessary"
205 if name.startswith( sold ):
206 name = snew + name[ len( sold ): ]
207 elif name.startswith( hold ):
208 name = hnew + name[ len( hold ): ]
209 return topo.addNode( self, name, *args, **kwargs )
210 return RenamedTopoCls( *args, **kwargs )
211
212
Bob Lantz8e576252016-08-29 14:05:59 -0700213# We accept objects that "claim" to be a particular class,
214# since the class definitions can be both execed (--custom) and
215# imported (in another custom file), which breaks isinstance().
216# In order for this to work properly, a class should not be
217# renamed so as to inappropriately omit or include the class
218# name text. Note that mininet.util.specialClass renames classes
219# by adding the specialized parameter names and values.
220
221def isONOSNode( obj ):
222 "Does obj claim to be some kind of ONOSNode?"
223 return ( isinstance( obj, ONOSNode) or
224 'ONOSNode' in type( obj ).__name__ )
225
226def isONOSCluster( obj ):
227 "Does obj claim to be some kind of ONOSCluster?"
228 return ( isinstance( obj, ONOSCluster ) or
229 'ONOSCluster' in type( obj ).__name__ )
230
231
Bob Lantz087b5d92016-05-06 11:39:04 -0700232class ONOSNode( Controller ):
233 "ONOS cluster node"
234
Bob Lantz087b5d92016-05-06 11:39:04 -0700235 def __init__( self, name, **kwargs ):
Bob Lantz64382422016-06-03 22:51:39 -0700236 "alertAction: exception|ignore|warn|exit (exception)"
Bob Lantz087b5d92016-05-06 11:39:04 -0700237 kwargs.update( inNamespace=True )
Bob Lantz64382422016-06-03 22:51:39 -0700238 self.alertAction = kwargs.pop( 'alertAction', 'exception' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700239 Controller.__init__( self, name, **kwargs )
240 self.dir = '/tmp/%s' % self.name
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700241 self.client = self.dir + '/karaf/bin/client'
Bob Lantz087b5d92016-05-06 11:39:04 -0700242 self.ONOS_HOME = '/tmp'
Bob Lantz55562ea2016-06-17 18:19:03 -0700243 self.cmd( 'rm -rf', self.dir )
244 self.ONOS_HOME = unpackONOS( self.dir, run=self.ucmd )
Bob Lantz087b5d92016-05-06 11:39:04 -0700245
246 # pylint: disable=arguments-differ
247
Bob Lantz569bbec2016-06-03 18:51:16 -0700248 def start( self, env, nodes=() ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700249 """Start ONOS on node
Bob Lantz569bbec2016-06-03 18:51:16 -0700250 env: environment var dict
251 nodes: all nodes in cluster"""
Bob Lantz087b5d92016-05-06 11:39:04 -0700252 env = dict( env )
Bob Lantz087b5d92016-05-06 11:39:04 -0700253 env.update( ONOS_HOME=self.ONOS_HOME )
254 self.updateEnv( env )
255 karafbin = glob( '%s/apache*/bin' % self.ONOS_HOME )[ 0 ]
256 onosbin = join( ONOS_ROOT, 'tools/test/bin' )
257 self.cmd( 'export PATH=%s:%s:$PATH' % ( onosbin, karafbin ) )
258 self.cmd( 'cd', self.ONOS_HOME )
Bob Lantz1451d722016-05-17 14:40:07 -0700259 self.ucmd( 'mkdir -p config && '
Bob Lantz569bbec2016-06-03 18:51:16 -0700260 'onos-gen-partitions config/cluster.json',
261 ' '.join( node.IP() for node in nodes ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700262 info( '(starting %s)' % self )
263 service = join( self.ONOS_HOME, 'bin/onos-service' )
Bob Lantz1451d722016-05-17 14:40:07 -0700264 self.ucmd( service, 'server 1>../onos.log 2>../onos.log'
265 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700266 self.onosPid = int( self.cmd( 'cat onos.pid' ).strip() )
Bob Lantz64382422016-06-03 22:51:39 -0700267 self.warningCount = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700268
269 # pylint: enable=arguments-differ
270
271 def stop( self ):
272 # XXX This will kill all karafs - too bad!
273 self.cmd( 'pkill -HUP -f karaf.jar && wait' )
274 self.cmd( 'rm -rf', self.dir )
275
Bob Lantz64382422016-06-03 22:51:39 -0700276 def sanityAlert( self, *args ):
277 "Alert to raise on sanityCheck failure"
278 info( '\n' )
279 if self.alertAction == 'exception':
280 raise Exception( *args )
281 if self.alertAction == 'warn':
282 warn( *args + ( '\n', ) )
283 elif self.alertAction == 'exit':
284 error( '***', *args +
285 ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) )
286 exit( 1 )
287
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700288 def isRunning( self ):
289 "Is our ONOS process still running?"
Bob Lantz64382422016-06-03 22:51:39 -0700290 cmd = ( 'ps -p %d >/dev/null 2>&1 && echo "running" ||'
291 'echo "not running"' )
292 return self.cmd( cmd % self.onosPid ).strip() == 'running'
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700293
Bob Lantz64382422016-06-03 22:51:39 -0700294 def checkLog( self ):
295 "Return log file errors and warnings"
296 log = join( self.dir, 'log' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700297 errors, warnings = [], []
Bob Lantz64382422016-06-03 22:51:39 -0700298 if isfile( log ):
299 lines = open( log ).read().split( '\n' )
300 errors = [ line for line in lines if 'ERROR' in line ]
301 warnings = [ line for line in lines if 'WARN'in line ]
302 return errors, warnings
303
304 def memAvailable( self ):
305 "Return available memory in KB (or -1 if we can't tell)"
306 lines = open( '/proc/meminfo' ).read().strip().split( '\n' )
307 entries = map( str.split, lines )
308 index = { entry[ 0 ]: entry for entry in entries }
309 # Check MemAvailable if present
310 default = ( None, '-1', 'kB' )
311 _name, count, unit = index.get( 'MemAvailable:', default )
312 if unit.lower() == 'kb':
313 return int( count )
314 return -1
315
316 def sanityCheck( self, lowMem=100000 ):
317 """Check whether we've quit or are running out of memory
318 lowMem: low memory threshold in KB (100000)"""
319 # Are we still running?
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700320 if not self.isRunning():
Bob Lantz64382422016-06-03 22:51:39 -0700321 self.sanityAlert( 'ONOS node %s has died' % self.name )
322 # Are there errors in the log file?
323 errors, warnings = self.checkLog()
324 if errors:
325 self.sanityAlert( 'ONOS startup errors:\n<<%s>>' %
326 '\n'.join( errors ) )
327 warningCount = len( warnings )
328 if warnings and warningCount > self.warningCount:
329 warn( '(%d warnings)' % len( warnings ) )
330 self.warningCount = warningCount
331 # Are we running out of memory?
332 mem = self.memAvailable()
333 if mem > 0 and mem < lowMem:
334 self.sanityAlert( 'Running out of memory (only %d KB available)'
335 % mem )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700336
Bob Lantz087b5d92016-05-06 11:39:04 -0700337 def waitStarted( self ):
338 "Wait until we've really started"
339 info( '(checking: karaf' )
340 while True:
Bob Lantz1451d722016-05-17 14:40:07 -0700341 status = self.ucmd( 'karaf status' ).lower()
Bob Lantz087b5d92016-05-06 11:39:04 -0700342 if 'running' in status and 'not running' not in status:
343 break
344 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700345 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700346 time.sleep( 1 )
347 info( ' ssh-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700348 waitListening( server=self, port=KarafPort, callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700349 info( ' openflow-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700350 waitListening( server=self, port=OpenFlowPort,
351 callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700352 info( ' client' )
353 while True:
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700354 result = quietRun( '%s -h %s "apps -a"' %
Bob Lantzbb37d872016-05-16 16:26:13 -0700355 ( self.client, self.IP() ), shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700356 if 'openflow' in result:
357 break
358 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700359 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700360 time.sleep( 1 )
Jon Halla43d0332016-08-04 15:02:23 -0700361 info( ' node-status' )
362 while True:
363 result = quietRun( '%s -h %s "nodes"' %
364 ( self.client, self.IP() ), shell=True )
365 nodeStr = 'id=%s, address=%s:%s, state=READY, updated' %\
366 ( self.IP(), self.IP(), CopycatPort )
367 if nodeStr in result:
368 break
369 info( '.' )
370 self.sanityCheck()
371 time.sleep( 1 )
Bob Lantz087b5d92016-05-06 11:39:04 -0700372 info( ')\n' )
373
374 def updateEnv( self, envDict ):
375 "Update environment variables"
Bob Lantz569bbec2016-06-03 18:51:16 -0700376 cmd = ';'.join( ( 'export %s="%s"' % ( var, val )
377 if val else 'unset %s' % var )
Bob Lantz087b5d92016-05-06 11:39:04 -0700378 for var, val in envDict.iteritems() )
379 self.cmd( cmd )
380
Bob Lantz1451d722016-05-17 14:40:07 -0700381 def ucmd( self, *args, **_kwargs ):
382 "Run command as $ONOS_USER using sudo -E -u"
383 if ONOS_USER != 'root': # don't bother with sudo
384 args = [ "sudo -E -u $ONOS_USER PATH=$PATH "
385 "bash -c '%s'" % ' '.join( args ) ]
386 return self.cmd( *args )
387
Bob Lantz087b5d92016-05-06 11:39:04 -0700388
389class ONOSCluster( Controller ):
390 "ONOS Cluster"
Bob Lantz57635162016-08-29 15:13:54 -0700391 # Offset for port forwarding
392 portOffset = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700393 def __init__( self, *args, **kwargs ):
394 """name: (first parameter)
395 *args: topology class parameters
396 ipBase: IP range for ONOS nodes
Bob Lantz57635162016-08-29 15:13:54 -0700397 forward: default port forwarding list
398 portOffset: offset to port base (optional)
Bob Lantz087b5d92016-05-06 11:39:04 -0700399 topo: topology class or instance
Bob Lantz64382422016-06-03 22:51:39 -0700400 nodeOpts: ONOSNode options
Bob Lantz57635162016-08-29 15:13:54 -0700401 **kwargs: additional topology parameters
402 By default, multiple ONOSClusters will increment
403 the portOffset automatically; alternately, it can
404 be specified explicitly.
405 """
Bob Lantz087b5d92016-05-06 11:39:04 -0700406 args = list( args )
407 name = args.pop( 0 )
408 topo = kwargs.pop( 'topo', None )
Bob Lantz930138e2016-06-23 18:53:19 -0700409 self.nat = kwargs.pop( 'nat', 'nat0' )
Bob Lantz64382422016-06-03 22:51:39 -0700410 nodeOpts = kwargs.pop( 'nodeOpts', {} )
Bob Lantz57635162016-08-29 15:13:54 -0700411 self.portOffset = kwargs.pop( 'portOffset', ONOSCluster.portOffset )
Jon Hall9b238ae2016-08-09 13:47:43 -0700412 # Pass in kwargs to the ONOSNodes instead of the cluster
413 "alertAction: exception|ignore|warn|exit (exception)"
414 alertAction = kwargs.pop( 'alertAction', None )
415 if alertAction:
416 nodeOpts[ 'alertAction'] = alertAction
Bob Lantz087b5d92016-05-06 11:39:04 -0700417 # Default: single switch with 1 ONOS node
418 if not topo:
419 topo = SingleSwitchTopo
420 if not args:
421 args = ( 1, )
422 if not isinstance( topo, Topo ):
423 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700424 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
425 self.forward = kwargs.pop( 'forward',
426 [ KarafPort, GUIPort, OpenFlowPort ] )
Bob Lantz087b5d92016-05-06 11:39:04 -0700427 super( ONOSCluster, self ).__init__( name, inNamespace=False )
428 fixIPTables()
429 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700430 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700431 host=partial( ONOSNode, **nodeOpts ),
432 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700433 controller=None )
Bob Lantz930138e2016-06-23 18:53:19 -0700434 if self.nat:
435 self.net.addNAT( self.nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700436 updateNodeIPs( self.env, self.nodes() )
437 self._remoteControllers = []
Bob Lantz57635162016-08-29 15:13:54 -0700438 # Update port offset for more ONOS clusters
439 ONOSCluster.portOffset += len( self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700440
441 def start( self ):
442 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700443 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
444 self.net.start()
445 for node in self.nodes():
Bob Lantz569bbec2016-06-03 18:51:16 -0700446 node.start( self.env, self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700447 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700448 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700449 self.waitStarted()
450 return
451
452 def waitStarted( self ):
453 "Wait until all nodes have started"
454 startTime = time.time()
455 for node in self.nodes():
456 info( node )
457 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700458 info( '*** Waited %.2f seconds for ONOS startup' %
459 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700460
461 def stop( self ):
462 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700463 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700464 for node in self.nodes():
465 node.stop()
466 self.net.stop()
467
468 def nodes( self ):
469 "Return list of ONOS nodes"
Bob Lantz8e576252016-08-29 14:05:59 -0700470 return [ h for h in self.net.hosts if isONOSNode( h ) ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700471
Bob Lantz930138e2016-06-23 18:53:19 -0700472 def configPortForwarding( self, ports=[], action='A' ):
473 """Start or stop port forwarding (any intf) for all nodes
474 ports: list of ports to forward
Bob Lantzbb37d872016-05-16 16:26:13 -0700475 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz930138e2016-06-23 18:53:19 -0700476 self.cmd( 'iptables -' + action, 'FORWARD -d', self.ipBase,
477 '-j ACCEPT' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700478 for port in ports:
479 for index, node in enumerate( self.nodes() ):
Bob Lantz57635162016-08-29 15:13:54 -0700480 ip, inport = node.IP(), port + self.portOffset + index
Bob Lantzbb37d872016-05-16 16:26:13 -0700481 # Configure a destination NAT rule
Bob Lantz930138e2016-06-23 18:53:19 -0700482 self.cmd( 'iptables -t nat -' + action,
483 'PREROUTING -t nat -p tcp --dport', inport,
484 '-j DNAT --to-destination %s:%s' % ( ip, port ) )
Bob Lantzbb37d872016-05-16 16:26:13 -0700485
Bob Lantz57635162016-08-29 15:13:54 -0700486
Bob Lantz087b5d92016-05-06 11:39:04 -0700487class ONOSSwitchMixin( object ):
488 "Mixin for switches that connect to an ONOSCluster"
489 def start( self, controllers ):
490 "Connect to ONOSCluster"
491 self.controllers = controllers
492 assert ( len( controllers ) is 1 and
Bob Lantz8e576252016-08-29 14:05:59 -0700493 isONOSCluster( controllers[ 0 ] ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700494 clist = controllers[ 0 ].nodes()
495 return super( ONOSSwitchMixin, self ).start( clist )
496
497class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
498 "OVSSwitch that can connect to an ONOSCluster"
499 pass
500
501class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
502 "UserSwitch that can connect to an ONOSCluster"
503 pass
504
505
506### Ugly utility routines
507
508def fixIPTables():
509 "Fix LinuxBridge warning"
510 for s in 'arp', 'ip', 'ip6':
511 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
512
513
514### Test code
515
516def test( serverCount ):
517 "Test this setup"
518 setLogLevel( 'info' )
519 net = Mininet( topo=SingleSwitchTopo( 3 ),
520 controller=[ ONOSCluster( 'c0', serverCount ) ],
521 switch=ONOSOVSSwitch )
522 net.start()
523 net.waitConnected()
524 CLI( net )
525 net.stop()
526
527
528### CLI Extensions
529
530OldCLI = CLI
531
532class ONOSCLI( OldCLI ):
533 "CLI Extensions for ONOS"
534
535 prompt = 'mininet-onos> '
536
537 def __init__( self, net, **kwargs ):
Bob Lantz503a4022016-08-29 18:08:37 -0700538 clusters = [ c.net for c in net.controllers
539 if isONOSCluster( c ) ]
540 net = MininetFacade( net, *clusters )
Bob Lantz087b5d92016-05-06 11:39:04 -0700541 OldCLI.__init__( self, net, **kwargs )
542
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700543 def onos1( self ):
544 "Helper function: return default ONOS node"
545 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
546
Bob Lantz087b5d92016-05-06 11:39:04 -0700547 def do_onos( self, line ):
548 "Send command to ONOS CLI"
549 c0 = self.mn.controllers[ 0 ]
Bob Lantz8e576252016-08-29 14:05:59 -0700550 if isONOSCluster( c0 ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700551 # cmdLoop strips off command name 'onos'
552 if line.startswith( ':' ):
553 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700554 onos1 = self.onos1().name
555 if line:
556 line = '"%s"' % line
557 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700558 quietRun( 'stty -echo' )
559 self.default( cmd )
560 quietRun( 'stty echo' )
561
562 def do_wait( self, line ):
563 "Wait for switches to connect"
564 self.mn.waitConnected()
565
566 def do_balance( self, line ):
567 "Balance switch mastership"
568 self.do_onos( ':balance-masters' )
569
570 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700571 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700572 self.default( '%s tail -f /tmp/%s/log' %
573 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700574
Bob Lantz64382422016-06-03 22:51:39 -0700575 def do_status( self, line ):
576 "Return status of ONOS cluster(s)"
577 for c in self.mn.controllers:
Bob Lantz8e576252016-08-29 14:05:59 -0700578 if isONOSCluster( c ):
Bob Lantz64382422016-06-03 22:51:39 -0700579 for node in c.net.hosts:
Bob Lantz8e576252016-08-29 14:05:59 -0700580 if isONOSNode( node ):
Bob Lantz64382422016-06-03 22:51:39 -0700581 errors, warnings = node.checkLog()
582 running = ( 'Running' if node.isRunning()
583 else 'Exited' )
584 status = ''
585 if errors:
586 status += '%d ERRORS ' % len( errors )
587 if warnings:
588 status += '%d warnings' % len( warnings )
589 status = status if status else 'OK'
590 info( node, '\t', running, '\t', status, '\n' )
591
Bob Lantzc96e2582016-06-13 18:57:04 -0700592 def do_arp( self, line ):
593 "Send gratuitous arps from all data network hosts"
594 startTime = time.time()
595 try:
596 count = int( line )
597 except:
598 count = 1
599 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700600 if '-U' not in quietRun( 'arping -h', shell=True ):
601 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700602 return
603 # This is much faster if we do it in parallel
604 for host in self.mn.net.hosts:
605 intf = host.defaultIntf()
606 # -b: keep using broadcasts; -f: quit after 1 reply
607 # -U: gratuitous ARP update
608 host.sendCmd( 'arping -bf -c', count, '-U -I',
609 intf.name, intf.IP() )
610 for host in self.mn.net.hosts:
611 # We could check the output here if desired
612 host.waitOutput()
613 info( '.' )
614 info( '\n' )
615 elapsed = time.time() - startTime
616 debug( 'Completed in %.2f seconds\n' % elapsed )
617
Bob Lantz64382422016-06-03 22:51:39 -0700618
619# For interactive use, exit on error
620exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
621ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
622
Bob Lantz087b5d92016-05-06 11:39:04 -0700623
624### Exports for bin/mn
625
626CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700627controllers = { 'onos': ONOSClusterInteractive,
628 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700629
630# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700631findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700632
633switches = { 'onos': ONOSOVSSwitch,
634 'onosovs': ONOSOVSSwitch,
635 'onosuser': ONOSUserSwitch,
636 'default': ONOSOVSSwitch }
637
Bob Lantzbb37d872016-05-16 16:26:13 -0700638# Null topology so we can control an external/hardware network
639topos = { 'none': Topo }
640
Bob Lantz087b5d92016-05-06 11:39:04 -0700641if __name__ == '__main__':
642 if len( argv ) != 2:
643 test( 3 )
644 else:
645 test( int( argv[ 1 ] ) )