blob: 051b3b3fb21a1c25df63302380c0e8b22df90695 [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()
Jon Hall25485592016-08-19 13:56:14 -0700120 if nodes:
121 env[ 'OCI' ] = env[ 'OCN' ] = env[ 'OC1' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700122 env[ 'ONOS_INSTANCES' ] = '\n'.join(
123 node.IP() for node in nodes )
124 environ.update( env )
125 return env
126
127
128tarDefaultPath = 'buck-out/gen/tools/package/onos-package/onos.tar.gz'
129
Bob Lantz1451d722016-05-17 14:40:07 -0700130def unpackONOS( destDir='/tmp', run=quietRun ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700131 "Unpack ONOS and return its location"
132 global ONOS_TAR
133 environ.setdefault( 'ONOS_TAR', join( ONOS_ROOT, tarDefaultPath ) )
134 ONOS_TAR = environ[ 'ONOS_TAR' ]
135 tarPath = ONOS_TAR
136 if not isfile( tarPath ):
137 raise Exception( 'Missing ONOS tarball %s - run buck build onos?'
138 % tarPath )
139 info( '(unpacking %s)' % destDir)
Bob Lantza2ccaa52016-06-29 18:26:06 -0700140 success = '*** SUCCESS ***'
141 cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s" && echo "%s"'
142 % ( destDir, destDir, tarPath, success ) )
143 result = run( cmds, shell=True, verbose=True )
144 if success not in result:
145 raise Exception( 'Failed to unpack ONOS archive %s in %s:\n%s\n' %
146 ( tarPath, destDir, result ) )
Bob Lantz1451d722016-05-17 14:40:07 -0700147 # We can use quietRun for this usually
148 tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True)
149 tarOutput = tarOutput.split()[ 0 ].strip()
150 assert '/' in tarOutput
151 onosDir = join( destDir, dirname( tarOutput ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700152 # Add symlink to log file
Bob Lantz1451d722016-05-17 14:40:07 -0700153 run( 'cd %s; ln -s onos*/apache* karaf;'
154 'ln -s karaf/data/log/karaf.log log' % destDir,
155 shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700156 return onosDir
157
158
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700159def waitListening( server, port=80, callback=None, sleepSecs=.5,
160 proc='java' ):
161 "Simplified netstat version of waitListening"
162 while True:
163 lines = server.cmd( 'netstat -natp' ).strip().split( '\n' )
164 entries = [ line.split() for line in lines ]
165 portstr = ':%s' % port
166 listening = [ entry for entry in entries
167 if len( entry ) > 6 and portstr in entry[ 3 ]
168 and proc in entry[ 6 ] ]
169 if listening:
170 break
Bob Lantz64382422016-06-03 22:51:39 -0700171 info( '.' )
172 if callback:
173 callback()
174 time.sleep( sleepSecs )
Bob Lantz64382422016-06-03 22:51:39 -0700175
176
Bob Lantz087b5d92016-05-06 11:39:04 -0700177### Mininet classes
178
179def RenamedTopo( topo, *args, **kwargs ):
180 """Return specialized topo with renamed hosts
181 topo: topo class/class name to specialize
182 args, kwargs: topo args
183 sold: old switch name prefix (default 's')
184 snew: new switch name prefix
185 hold: old host name prefix (default 'h')
186 hnew: new host name prefix
187 This may be used from the mn command, e.g.
188 mn --topo renamed,single,spref=sw,hpref=host"""
189 sold = kwargs.pop( 'sold', 's' )
190 hold = kwargs.pop( 'hold', 'h' )
191 snew = kwargs.pop( 'snew', 'cs' )
192 hnew = kwargs.pop( 'hnew' ,'ch' )
193 topos = {} # TODO: use global TOPOS dict
194 if isinstance( topo, str ):
195 # Look up in topo directory - this allows us to
196 # use RenamedTopo from the command line!
197 if topo in topos:
198 topo = topos.get( topo )
199 else:
200 raise Exception( 'Unknown topo name: %s' % topo )
201 # pylint: disable=no-init
202 class RenamedTopoCls( topo ):
203 "Topo subclass with renamed nodes"
204 def addNode( self, name, *args, **kwargs ):
205 "Add a node, renaming if necessary"
206 if name.startswith( sold ):
207 name = snew + name[ len( sold ): ]
208 elif name.startswith( hold ):
209 name = hnew + name[ len( hold ): ]
210 return topo.addNode( self, name, *args, **kwargs )
211 return RenamedTopoCls( *args, **kwargs )
212
213
Bob Lantz8e576252016-08-29 14:05:59 -0700214# We accept objects that "claim" to be a particular class,
215# since the class definitions can be both execed (--custom) and
216# imported (in another custom file), which breaks isinstance().
217# In order for this to work properly, a class should not be
218# renamed so as to inappropriately omit or include the class
219# name text. Note that mininet.util.specialClass renames classes
220# by adding the specialized parameter names and values.
221
222def isONOSNode( obj ):
223 "Does obj claim to be some kind of ONOSNode?"
224 return ( isinstance( obj, ONOSNode) or
225 'ONOSNode' in type( obj ).__name__ )
226
227def isONOSCluster( obj ):
228 "Does obj claim to be some kind of ONOSCluster?"
229 return ( isinstance( obj, ONOSCluster ) or
230 'ONOSCluster' in type( obj ).__name__ )
231
232
Bob Lantz087b5d92016-05-06 11:39:04 -0700233class ONOSNode( Controller ):
234 "ONOS cluster node"
235
Bob Lantz087b5d92016-05-06 11:39:04 -0700236 def __init__( self, name, **kwargs ):
Bob Lantz64382422016-06-03 22:51:39 -0700237 "alertAction: exception|ignore|warn|exit (exception)"
Bob Lantz087b5d92016-05-06 11:39:04 -0700238 kwargs.update( inNamespace=True )
Bob Lantz64382422016-06-03 22:51:39 -0700239 self.alertAction = kwargs.pop( 'alertAction', 'exception' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700240 Controller.__init__( self, name, **kwargs )
241 self.dir = '/tmp/%s' % self.name
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700242 self.client = self.dir + '/karaf/bin/client'
Bob Lantz087b5d92016-05-06 11:39:04 -0700243 self.ONOS_HOME = '/tmp'
Bob Lantz55562ea2016-06-17 18:19:03 -0700244 self.cmd( 'rm -rf', self.dir )
245 self.ONOS_HOME = unpackONOS( self.dir, run=self.ucmd )
Jon Hall25485592016-08-19 13:56:14 -0700246 self.ONOS_ROOT = ONOS_ROOT
Bob Lantz087b5d92016-05-06 11:39:04 -0700247
248 # pylint: disable=arguments-differ
249
Bob Lantz569bbec2016-06-03 18:51:16 -0700250 def start( self, env, nodes=() ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700251 """Start ONOS on node
Bob Lantz569bbec2016-06-03 18:51:16 -0700252 env: environment var dict
253 nodes: all nodes in cluster"""
Bob Lantz087b5d92016-05-06 11:39:04 -0700254 env = dict( env )
Bob Lantz087b5d92016-05-06 11:39:04 -0700255 env.update( ONOS_HOME=self.ONOS_HOME )
256 self.updateEnv( env )
257 karafbin = glob( '%s/apache*/bin' % self.ONOS_HOME )[ 0 ]
258 onosbin = join( ONOS_ROOT, 'tools/test/bin' )
259 self.cmd( 'export PATH=%s:%s:$PATH' % ( onosbin, karafbin ) )
260 self.cmd( 'cd', self.ONOS_HOME )
Bob Lantz1451d722016-05-17 14:40:07 -0700261 self.ucmd( 'mkdir -p config && '
Bob Lantz569bbec2016-06-03 18:51:16 -0700262 'onos-gen-partitions config/cluster.json',
263 ' '.join( node.IP() for node in nodes ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700264 info( '(starting %s)' % self )
265 service = join( self.ONOS_HOME, 'bin/onos-service' )
Bob Lantz1451d722016-05-17 14:40:07 -0700266 self.ucmd( service, 'server 1>../onos.log 2>../onos.log'
267 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700268 self.onosPid = int( self.cmd( 'cat onos.pid' ).strip() )
Bob Lantz64382422016-06-03 22:51:39 -0700269 self.warningCount = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700270
271 # pylint: enable=arguments-differ
272
273 def stop( self ):
274 # XXX This will kill all karafs - too bad!
275 self.cmd( 'pkill -HUP -f karaf.jar && wait' )
276 self.cmd( 'rm -rf', self.dir )
277
Bob Lantz64382422016-06-03 22:51:39 -0700278 def sanityAlert( self, *args ):
279 "Alert to raise on sanityCheck failure"
280 info( '\n' )
281 if self.alertAction == 'exception':
282 raise Exception( *args )
283 if self.alertAction == 'warn':
284 warn( *args + ( '\n', ) )
285 elif self.alertAction == 'exit':
286 error( '***', *args +
287 ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) )
288 exit( 1 )
289
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700290 def isRunning( self ):
291 "Is our ONOS process still running?"
Bob Lantz64382422016-06-03 22:51:39 -0700292 cmd = ( 'ps -p %d >/dev/null 2>&1 && echo "running" ||'
293 'echo "not running"' )
294 return self.cmd( cmd % self.onosPid ).strip() == 'running'
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700295
Bob Lantz64382422016-06-03 22:51:39 -0700296 def checkLog( self ):
297 "Return log file errors and warnings"
298 log = join( self.dir, 'log' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700299 errors, warnings = [], []
Bob Lantz64382422016-06-03 22:51:39 -0700300 if isfile( log ):
301 lines = open( log ).read().split( '\n' )
302 errors = [ line for line in lines if 'ERROR' in line ]
303 warnings = [ line for line in lines if 'WARN'in line ]
304 return errors, warnings
305
306 def memAvailable( self ):
307 "Return available memory in KB (or -1 if we can't tell)"
308 lines = open( '/proc/meminfo' ).read().strip().split( '\n' )
309 entries = map( str.split, lines )
310 index = { entry[ 0 ]: entry for entry in entries }
311 # Check MemAvailable if present
312 default = ( None, '-1', 'kB' )
313 _name, count, unit = index.get( 'MemAvailable:', default )
314 if unit.lower() == 'kb':
315 return int( count )
316 return -1
317
318 def sanityCheck( self, lowMem=100000 ):
319 """Check whether we've quit or are running out of memory
320 lowMem: low memory threshold in KB (100000)"""
321 # Are we still running?
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700322 if not self.isRunning():
Bob Lantz64382422016-06-03 22:51:39 -0700323 self.sanityAlert( 'ONOS node %s has died' % self.name )
324 # Are there errors in the log file?
325 errors, warnings = self.checkLog()
326 if errors:
327 self.sanityAlert( 'ONOS startup errors:\n<<%s>>' %
328 '\n'.join( errors ) )
329 warningCount = len( warnings )
330 if warnings and warningCount > self.warningCount:
331 warn( '(%d warnings)' % len( warnings ) )
332 self.warningCount = warningCount
333 # Are we running out of memory?
334 mem = self.memAvailable()
335 if mem > 0 and mem < lowMem:
336 self.sanityAlert( 'Running out of memory (only %d KB available)'
337 % mem )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700338
Bob Lantz087b5d92016-05-06 11:39:04 -0700339 def waitStarted( self ):
340 "Wait until we've really started"
341 info( '(checking: karaf' )
342 while True:
Bob Lantz1451d722016-05-17 14:40:07 -0700343 status = self.ucmd( 'karaf status' ).lower()
Bob Lantz087b5d92016-05-06 11:39:04 -0700344 if 'running' in status and 'not running' not in status:
345 break
346 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700347 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700348 time.sleep( 1 )
349 info( ' ssh-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700350 waitListening( server=self, port=KarafPort, callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700351 info( ' openflow-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700352 waitListening( server=self, port=OpenFlowPort,
353 callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700354 info( ' client' )
355 while True:
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700356 result = quietRun( '%s -h %s "apps -a"' %
Bob Lantzbb37d872016-05-16 16:26:13 -0700357 ( self.client, self.IP() ), shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700358 if 'openflow' in result:
359 break
360 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700361 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700362 time.sleep( 1 )
Jon Halla43d0332016-08-04 15:02:23 -0700363 info( ' node-status' )
364 while True:
365 result = quietRun( '%s -h %s "nodes"' %
366 ( self.client, self.IP() ), shell=True )
367 nodeStr = 'id=%s, address=%s:%s, state=READY, updated' %\
368 ( self.IP(), self.IP(), CopycatPort )
369 if nodeStr in result:
370 break
371 info( '.' )
372 self.sanityCheck()
373 time.sleep( 1 )
Bob Lantz087b5d92016-05-06 11:39:04 -0700374 info( ')\n' )
375
376 def updateEnv( self, envDict ):
377 "Update environment variables"
Bob Lantz569bbec2016-06-03 18:51:16 -0700378 cmd = ';'.join( ( 'export %s="%s"' % ( var, val )
379 if val else 'unset %s' % var )
Bob Lantz087b5d92016-05-06 11:39:04 -0700380 for var, val in envDict.iteritems() )
381 self.cmd( cmd )
382
Bob Lantz1451d722016-05-17 14:40:07 -0700383 def ucmd( self, *args, **_kwargs ):
384 "Run command as $ONOS_USER using sudo -E -u"
385 if ONOS_USER != 'root': # don't bother with sudo
386 args = [ "sudo -E -u $ONOS_USER PATH=$PATH "
387 "bash -c '%s'" % ' '.join( args ) ]
388 return self.cmd( *args )
389
Bob Lantz087b5d92016-05-06 11:39:04 -0700390
391class ONOSCluster( Controller ):
392 "ONOS Cluster"
Bob Lantz57635162016-08-29 15:13:54 -0700393 # Offset for port forwarding
394 portOffset = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700395 def __init__( self, *args, **kwargs ):
396 """name: (first parameter)
397 *args: topology class parameters
398 ipBase: IP range for ONOS nodes
Bob Lantz57635162016-08-29 15:13:54 -0700399 forward: default port forwarding list
400 portOffset: offset to port base (optional)
Bob Lantz087b5d92016-05-06 11:39:04 -0700401 topo: topology class or instance
Bob Lantz64382422016-06-03 22:51:39 -0700402 nodeOpts: ONOSNode options
Bob Lantz57635162016-08-29 15:13:54 -0700403 **kwargs: additional topology parameters
404 By default, multiple ONOSClusters will increment
405 the portOffset automatically; alternately, it can
406 be specified explicitly.
407 """
Bob Lantz087b5d92016-05-06 11:39:04 -0700408 args = list( args )
409 name = args.pop( 0 )
410 topo = kwargs.pop( 'topo', None )
Bob Lantz930138e2016-06-23 18:53:19 -0700411 self.nat = kwargs.pop( 'nat', 'nat0' )
Bob Lantz64382422016-06-03 22:51:39 -0700412 nodeOpts = kwargs.pop( 'nodeOpts', {} )
Bob Lantz57635162016-08-29 15:13:54 -0700413 self.portOffset = kwargs.pop( 'portOffset', ONOSCluster.portOffset )
Jon Hall9b238ae2016-08-09 13:47:43 -0700414 # Pass in kwargs to the ONOSNodes instead of the cluster
415 "alertAction: exception|ignore|warn|exit (exception)"
416 alertAction = kwargs.pop( 'alertAction', None )
417 if alertAction:
418 nodeOpts[ 'alertAction'] = alertAction
Bob Lantz087b5d92016-05-06 11:39:04 -0700419 # Default: single switch with 1 ONOS node
420 if not topo:
421 topo = SingleSwitchTopo
422 if not args:
423 args = ( 1, )
424 if not isinstance( topo, Topo ):
425 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700426 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
427 self.forward = kwargs.pop( 'forward',
428 [ KarafPort, GUIPort, OpenFlowPort ] )
Bob Lantz087b5d92016-05-06 11:39:04 -0700429 super( ONOSCluster, self ).__init__( name, inNamespace=False )
430 fixIPTables()
431 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700432 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700433 host=partial( ONOSNode, **nodeOpts ),
434 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700435 controller=None )
Bob Lantz930138e2016-06-23 18:53:19 -0700436 if self.nat:
437 self.net.addNAT( self.nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700438 updateNodeIPs( self.env, self.nodes() )
439 self._remoteControllers = []
Bob Lantz57635162016-08-29 15:13:54 -0700440 # Update port offset for more ONOS clusters
441 ONOSCluster.portOffset += len( self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700442
443 def start( self ):
444 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700445 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
446 self.net.start()
447 for node in self.nodes():
Bob Lantz569bbec2016-06-03 18:51:16 -0700448 node.start( self.env, self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700449 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700450 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700451 self.waitStarted()
452 return
453
454 def waitStarted( self ):
455 "Wait until all nodes have started"
456 startTime = time.time()
457 for node in self.nodes():
458 info( node )
459 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700460 info( '*** Waited %.2f seconds for ONOS startup' %
461 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700462
463 def stop( self ):
464 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700465 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700466 for node in self.nodes():
467 node.stop()
468 self.net.stop()
469
470 def nodes( self ):
471 "Return list of ONOS nodes"
Bob Lantz8e576252016-08-29 14:05:59 -0700472 return [ h for h in self.net.hosts if isONOSNode( h ) ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700473
Bob Lantz930138e2016-06-23 18:53:19 -0700474 def configPortForwarding( self, ports=[], action='A' ):
475 """Start or stop port forwarding (any intf) for all nodes
476 ports: list of ports to forward
Bob Lantzbb37d872016-05-16 16:26:13 -0700477 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz930138e2016-06-23 18:53:19 -0700478 self.cmd( 'iptables -' + action, 'FORWARD -d', self.ipBase,
479 '-j ACCEPT' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700480 for port in ports:
481 for index, node in enumerate( self.nodes() ):
Bob Lantz57635162016-08-29 15:13:54 -0700482 ip, inport = node.IP(), port + self.portOffset + index
Bob Lantzbb37d872016-05-16 16:26:13 -0700483 # Configure a destination NAT rule
Bob Lantz930138e2016-06-23 18:53:19 -0700484 self.cmd( 'iptables -t nat -' + action,
485 'PREROUTING -t nat -p tcp --dport', inport,
486 '-j DNAT --to-destination %s:%s' % ( ip, port ) )
Bob Lantzbb37d872016-05-16 16:26:13 -0700487
Bob Lantz57635162016-08-29 15:13:54 -0700488
Bob Lantz087b5d92016-05-06 11:39:04 -0700489class ONOSSwitchMixin( object ):
490 "Mixin for switches that connect to an ONOSCluster"
491 def start( self, controllers ):
492 "Connect to ONOSCluster"
493 self.controllers = controllers
494 assert ( len( controllers ) is 1 and
Bob Lantz8e576252016-08-29 14:05:59 -0700495 isONOSCluster( controllers[ 0 ] ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700496 clist = controllers[ 0 ].nodes()
497 return super( ONOSSwitchMixin, self ).start( clist )
498
499class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
500 "OVSSwitch that can connect to an ONOSCluster"
501 pass
502
503class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
504 "UserSwitch that can connect to an ONOSCluster"
505 pass
506
507
508### Ugly utility routines
509
510def fixIPTables():
511 "Fix LinuxBridge warning"
512 for s in 'arp', 'ip', 'ip6':
513 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
514
515
516### Test code
517
518def test( serverCount ):
519 "Test this setup"
520 setLogLevel( 'info' )
521 net = Mininet( topo=SingleSwitchTopo( 3 ),
522 controller=[ ONOSCluster( 'c0', serverCount ) ],
523 switch=ONOSOVSSwitch )
524 net.start()
525 net.waitConnected()
526 CLI( net )
527 net.stop()
528
529
530### CLI Extensions
531
532OldCLI = CLI
533
534class ONOSCLI( OldCLI ):
535 "CLI Extensions for ONOS"
536
537 prompt = 'mininet-onos> '
538
539 def __init__( self, net, **kwargs ):
Bob Lantz503a4022016-08-29 18:08:37 -0700540 clusters = [ c.net for c in net.controllers
541 if isONOSCluster( c ) ]
542 net = MininetFacade( net, *clusters )
Bob Lantz087b5d92016-05-06 11:39:04 -0700543 OldCLI.__init__( self, net, **kwargs )
544
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700545 def onos1( self ):
546 "Helper function: return default ONOS node"
547 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
548
Bob Lantz087b5d92016-05-06 11:39:04 -0700549 def do_onos( self, line ):
550 "Send command to ONOS CLI"
551 c0 = self.mn.controllers[ 0 ]
Bob Lantz8e576252016-08-29 14:05:59 -0700552 if isONOSCluster( c0 ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700553 # cmdLoop strips off command name 'onos'
554 if line.startswith( ':' ):
555 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700556 onos1 = self.onos1().name
557 if line:
558 line = '"%s"' % line
559 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700560 quietRun( 'stty -echo' )
561 self.default( cmd )
562 quietRun( 'stty echo' )
563
564 def do_wait( self, line ):
565 "Wait for switches to connect"
566 self.mn.waitConnected()
567
568 def do_balance( self, line ):
569 "Balance switch mastership"
570 self.do_onos( ':balance-masters' )
571
572 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700573 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700574 self.default( '%s tail -f /tmp/%s/log' %
575 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700576
Bob Lantz64382422016-06-03 22:51:39 -0700577 def do_status( self, line ):
578 "Return status of ONOS cluster(s)"
579 for c in self.mn.controllers:
Bob Lantz8e576252016-08-29 14:05:59 -0700580 if isONOSCluster( c ):
Bob Lantz64382422016-06-03 22:51:39 -0700581 for node in c.net.hosts:
Bob Lantz8e576252016-08-29 14:05:59 -0700582 if isONOSNode( node ):
Bob Lantz64382422016-06-03 22:51:39 -0700583 errors, warnings = node.checkLog()
584 running = ( 'Running' if node.isRunning()
585 else 'Exited' )
586 status = ''
587 if errors:
588 status += '%d ERRORS ' % len( errors )
589 if warnings:
590 status += '%d warnings' % len( warnings )
591 status = status if status else 'OK'
592 info( node, '\t', running, '\t', status, '\n' )
593
Bob Lantzc96e2582016-06-13 18:57:04 -0700594 def do_arp( self, line ):
595 "Send gratuitous arps from all data network hosts"
596 startTime = time.time()
597 try:
598 count = int( line )
599 except:
600 count = 1
601 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700602 if '-U' not in quietRun( 'arping -h', shell=True ):
603 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700604 return
605 # This is much faster if we do it in parallel
606 for host in self.mn.net.hosts:
607 intf = host.defaultIntf()
608 # -b: keep using broadcasts; -f: quit after 1 reply
609 # -U: gratuitous ARP update
610 host.sendCmd( 'arping -bf -c', count, '-U -I',
611 intf.name, intf.IP() )
612 for host in self.mn.net.hosts:
613 # We could check the output here if desired
614 host.waitOutput()
615 info( '.' )
616 info( '\n' )
617 elapsed = time.time() - startTime
618 debug( 'Completed in %.2f seconds\n' % elapsed )
619
Bob Lantz64382422016-06-03 22:51:39 -0700620
621# For interactive use, exit on error
622exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
623ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
624
Bob Lantz087b5d92016-05-06 11:39:04 -0700625
626### Exports for bin/mn
627
628CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700629controllers = { 'onos': ONOSClusterInteractive,
630 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700631
632# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700633findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700634
635switches = { 'onos': ONOSOVSSwitch,
636 'onosovs': ONOSOVSSwitch,
637 'onosuser': ONOSUserSwitch,
638 'default': ONOSOVSSwitch }
639
Bob Lantzbb37d872016-05-16 16:26:13 -0700640# Null topology so we can control an external/hardware network
641topos = { 'none': Topo }
642
Bob Lantz087b5d92016-05-06 11:39:04 -0700643if __name__ == '__main__':
644 if len( argv ) != 2:
645 test( 3 )
646 else:
647 test( int( argv[ 1 ] ) )