blob: 8e163ad5395fc11689c63a143d33560464bf95e1 [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
Bob Lantz087b5d92016-05-06 11:39:04 -070065
66def defaultUser():
67 "Return a reasonable default user"
68 if 'SUDO_USER' in environ:
69 return environ[ 'SUDO_USER' ]
70 try:
71 user = quietRun( 'who am i' ).split()[ 0 ]
72 except:
73 user = 'nobody'
74 return user
75
Bob Lantz087b5d92016-05-06 11:39:04 -070076# Module vars, initialized below
Bob Lantz4b51d5c2016-05-27 14:47:38 -070077HOME = ONOS_ROOT = ONOS_USER = None
Bob Lantz087b5d92016-05-06 11:39:04 -070078ONOS_APPS = ONOS_WEB_USER = ONOS_WEB_PASS = ONOS_TAR = None
79
80def initONOSEnv():
81 """Initialize ONOS environment (and module) variables
82 This is ugly and painful, but they have to be set correctly
83 in order for the onos-setup-karaf script to work.
84 nodes: list of ONOS nodes
85 returns: ONOS environment variable dict"""
86 # pylint: disable=global-statement
Bob Lantz4b51d5c2016-05-27 14:47:38 -070087 global HOME, ONOS_ROOT, ONOS_USER
Bob Lantz087b5d92016-05-06 11:39:04 -070088 global ONOS_APPS, ONOS_WEB_USER, ONOS_WEB_PASS
89 env = {}
90 def sd( var, val ):
91 "Set default value for environment variable"
92 env[ var ] = environ.setdefault( var, val )
93 return env[ var ]
Bob Lantz4b51d5c2016-05-27 14:47:38 -070094 assert environ[ 'HOME' ]
Bob Lantz087b5d92016-05-06 11:39:04 -070095 HOME = sd( 'HOME', environ[ 'HOME' ] )
Bob Lantz087b5d92016-05-06 11:39:04 -070096 ONOS_ROOT = sd( 'ONOS_ROOT', join( HOME, 'onos' ) )
Bob Lantz087b5d92016-05-06 11:39:04 -070097 environ[ 'ONOS_USER' ] = defaultUser()
98 ONOS_USER = sd( 'ONOS_USER', defaultUser() )
99 ONOS_APPS = sd( 'ONOS_APPS',
100 'drivers,openflow,fwd,proxyarp,mobility' )
101 # ONOS_WEB_{USER,PASS} isn't respected by onos-karaf:
102 environ.update( ONOS_WEB_USER='karaf', ONOS_WEB_PASS='karaf' )
103 ONOS_WEB_USER = sd( 'ONOS_WEB_USER', 'karaf' )
104 ONOS_WEB_PASS = sd( 'ONOS_WEB_PASS', 'karaf' )
105 return env
106
107
108def updateNodeIPs( env, nodes ):
109 "Update env dict and environ with node IPs"
110 # Get rid of stale junk
111 for var in 'ONOS_NIC', 'ONOS_CELL', 'ONOS_INSTANCES':
112 env[ var ] = ''
113 for var in environ.keys():
114 if var.startswith( 'OC' ):
115 env[ var ] = ''
116 for index, node in enumerate( nodes, 1 ):
117 var = 'OC%d' % index
118 env[ var ] = node.IP()
119 env[ 'OCI' ] = env[ 'OCN' ] = env[ 'OC1' ]
120 env[ 'ONOS_INSTANCES' ] = '\n'.join(
121 node.IP() for node in nodes )
122 environ.update( env )
123 return env
124
125
126tarDefaultPath = 'buck-out/gen/tools/package/onos-package/onos.tar.gz'
127
Bob Lantz1451d722016-05-17 14:40:07 -0700128def unpackONOS( destDir='/tmp', run=quietRun ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700129 "Unpack ONOS and return its location"
130 global ONOS_TAR
131 environ.setdefault( 'ONOS_TAR', join( ONOS_ROOT, tarDefaultPath ) )
132 ONOS_TAR = environ[ 'ONOS_TAR' ]
133 tarPath = ONOS_TAR
134 if not isfile( tarPath ):
135 raise Exception( 'Missing ONOS tarball %s - run buck build onos?'
136 % tarPath )
137 info( '(unpacking %s)' % destDir)
Bob Lantz1451d722016-05-17 14:40:07 -0700138 cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s"'
Bob Lantz087b5d92016-05-06 11:39:04 -0700139 % ( destDir, destDir, tarPath) )
Bob Lantz1451d722016-05-17 14:40:07 -0700140 run( cmds, shell=True, verbose=True )
141 # We can use quietRun for this usually
142 tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True)
143 tarOutput = tarOutput.split()[ 0 ].strip()
144 assert '/' in tarOutput
145 onosDir = join( destDir, dirname( tarOutput ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700146 # Add symlink to log file
Bob Lantz1451d722016-05-17 14:40:07 -0700147 run( 'cd %s; ln -s onos*/apache* karaf;'
148 'ln -s karaf/data/log/karaf.log log' % destDir,
149 shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700150 return onosDir
151
152
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700153def waitListening( server, port=80, callback=None, sleepSecs=.5,
154 proc='java' ):
155 "Simplified netstat version of waitListening"
156 while True:
157 lines = server.cmd( 'netstat -natp' ).strip().split( '\n' )
158 entries = [ line.split() for line in lines ]
159 portstr = ':%s' % port
160 listening = [ entry for entry in entries
161 if len( entry ) > 6 and portstr in entry[ 3 ]
162 and proc in entry[ 6 ] ]
163 if listening:
164 break
Bob Lantz64382422016-06-03 22:51:39 -0700165 info( '.' )
166 if callback:
167 callback()
168 time.sleep( sleepSecs )
Bob Lantz64382422016-06-03 22:51:39 -0700169
170
Bob Lantz087b5d92016-05-06 11:39:04 -0700171### Mininet classes
172
173def RenamedTopo( topo, *args, **kwargs ):
174 """Return specialized topo with renamed hosts
175 topo: topo class/class name to specialize
176 args, kwargs: topo args
177 sold: old switch name prefix (default 's')
178 snew: new switch name prefix
179 hold: old host name prefix (default 'h')
180 hnew: new host name prefix
181 This may be used from the mn command, e.g.
182 mn --topo renamed,single,spref=sw,hpref=host"""
183 sold = kwargs.pop( 'sold', 's' )
184 hold = kwargs.pop( 'hold', 'h' )
185 snew = kwargs.pop( 'snew', 'cs' )
186 hnew = kwargs.pop( 'hnew' ,'ch' )
187 topos = {} # TODO: use global TOPOS dict
188 if isinstance( topo, str ):
189 # Look up in topo directory - this allows us to
190 # use RenamedTopo from the command line!
191 if topo in topos:
192 topo = topos.get( topo )
193 else:
194 raise Exception( 'Unknown topo name: %s' % topo )
195 # pylint: disable=no-init
196 class RenamedTopoCls( topo ):
197 "Topo subclass with renamed nodes"
198 def addNode( self, name, *args, **kwargs ):
199 "Add a node, renaming if necessary"
200 if name.startswith( sold ):
201 name = snew + name[ len( sold ): ]
202 elif name.startswith( hold ):
203 name = hnew + name[ len( hold ): ]
204 return topo.addNode( self, name, *args, **kwargs )
205 return RenamedTopoCls( *args, **kwargs )
206
207
208class ONOSNode( Controller ):
209 "ONOS cluster node"
210
Bob Lantz087b5d92016-05-06 11:39:04 -0700211 def __init__( self, name, **kwargs ):
Bob Lantz64382422016-06-03 22:51:39 -0700212 "alertAction: exception|ignore|warn|exit (exception)"
Bob Lantz087b5d92016-05-06 11:39:04 -0700213 kwargs.update( inNamespace=True )
Bob Lantz64382422016-06-03 22:51:39 -0700214 self.alertAction = kwargs.pop( 'alertAction', 'exception' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700215 Controller.__init__( self, name, **kwargs )
216 self.dir = '/tmp/%s' % self.name
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700217 self.client = self.dir + '/karaf/bin/client'
Bob Lantz087b5d92016-05-06 11:39:04 -0700218 self.ONOS_HOME = '/tmp'
Bob Lantz55562ea2016-06-17 18:19:03 -0700219 self.cmd( 'rm -rf', self.dir )
220 self.ONOS_HOME = unpackONOS( self.dir, run=self.ucmd )
Bob Lantz087b5d92016-05-06 11:39:04 -0700221
222 # pylint: disable=arguments-differ
223
Bob Lantz569bbec2016-06-03 18:51:16 -0700224 def start( self, env, nodes=() ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700225 """Start ONOS on node
Bob Lantz569bbec2016-06-03 18:51:16 -0700226 env: environment var dict
227 nodes: all nodes in cluster"""
Bob Lantz087b5d92016-05-06 11:39:04 -0700228 env = dict( env )
Bob Lantz087b5d92016-05-06 11:39:04 -0700229 env.update( ONOS_HOME=self.ONOS_HOME )
230 self.updateEnv( env )
231 karafbin = glob( '%s/apache*/bin' % self.ONOS_HOME )[ 0 ]
232 onosbin = join( ONOS_ROOT, 'tools/test/bin' )
233 self.cmd( 'export PATH=%s:%s:$PATH' % ( onosbin, karafbin ) )
234 self.cmd( 'cd', self.ONOS_HOME )
Bob Lantz1451d722016-05-17 14:40:07 -0700235 self.ucmd( 'mkdir -p config && '
Bob Lantz569bbec2016-06-03 18:51:16 -0700236 'onos-gen-partitions config/cluster.json',
237 ' '.join( node.IP() for node in nodes ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700238 info( '(starting %s)' % self )
239 service = join( self.ONOS_HOME, 'bin/onos-service' )
Bob Lantz1451d722016-05-17 14:40:07 -0700240 self.ucmd( service, 'server 1>../onos.log 2>../onos.log'
241 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700242 self.onosPid = int( self.cmd( 'cat onos.pid' ).strip() )
Bob Lantz64382422016-06-03 22:51:39 -0700243 self.warningCount = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700244
245 # pylint: enable=arguments-differ
246
247 def stop( self ):
248 # XXX This will kill all karafs - too bad!
249 self.cmd( 'pkill -HUP -f karaf.jar && wait' )
250 self.cmd( 'rm -rf', self.dir )
251
Bob Lantz64382422016-06-03 22:51:39 -0700252 def sanityAlert( self, *args ):
253 "Alert to raise on sanityCheck failure"
254 info( '\n' )
255 if self.alertAction == 'exception':
256 raise Exception( *args )
257 if self.alertAction == 'warn':
258 warn( *args + ( '\n', ) )
259 elif self.alertAction == 'exit':
260 error( '***', *args +
261 ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) )
262 exit( 1 )
263
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700264 def isRunning( self ):
265 "Is our ONOS process still running?"
Bob Lantz64382422016-06-03 22:51:39 -0700266 cmd = ( 'ps -p %d >/dev/null 2>&1 && echo "running" ||'
267 'echo "not running"' )
268 return self.cmd( cmd % self.onosPid ).strip() == 'running'
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700269
Bob Lantz64382422016-06-03 22:51:39 -0700270 def checkLog( self ):
271 "Return log file errors and warnings"
272 log = join( self.dir, 'log' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700273 errors, warnings = [], []
Bob Lantz64382422016-06-03 22:51:39 -0700274 if isfile( log ):
275 lines = open( log ).read().split( '\n' )
276 errors = [ line for line in lines if 'ERROR' in line ]
277 warnings = [ line for line in lines if 'WARN'in line ]
278 return errors, warnings
279
280 def memAvailable( self ):
281 "Return available memory in KB (or -1 if we can't tell)"
282 lines = open( '/proc/meminfo' ).read().strip().split( '\n' )
283 entries = map( str.split, lines )
284 index = { entry[ 0 ]: entry for entry in entries }
285 # Check MemAvailable if present
286 default = ( None, '-1', 'kB' )
287 _name, count, unit = index.get( 'MemAvailable:', default )
288 if unit.lower() == 'kb':
289 return int( count )
290 return -1
291
292 def sanityCheck( self, lowMem=100000 ):
293 """Check whether we've quit or are running out of memory
294 lowMem: low memory threshold in KB (100000)"""
295 # Are we still running?
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700296 if not self.isRunning():
Bob Lantz64382422016-06-03 22:51:39 -0700297 self.sanityAlert( 'ONOS node %s has died' % self.name )
298 # Are there errors in the log file?
299 errors, warnings = self.checkLog()
300 if errors:
301 self.sanityAlert( 'ONOS startup errors:\n<<%s>>' %
302 '\n'.join( errors ) )
303 warningCount = len( warnings )
304 if warnings and warningCount > self.warningCount:
305 warn( '(%d warnings)' % len( warnings ) )
306 self.warningCount = warningCount
307 # Are we running out of memory?
308 mem = self.memAvailable()
309 if mem > 0 and mem < lowMem:
310 self.sanityAlert( 'Running out of memory (only %d KB available)'
311 % mem )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700312
Bob Lantz087b5d92016-05-06 11:39:04 -0700313 def waitStarted( self ):
314 "Wait until we've really started"
315 info( '(checking: karaf' )
316 while True:
Bob Lantz1451d722016-05-17 14:40:07 -0700317 status = self.ucmd( 'karaf status' ).lower()
Bob Lantz087b5d92016-05-06 11:39:04 -0700318 if 'running' in status and 'not running' not in status:
319 break
320 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700321 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700322 time.sleep( 1 )
323 info( ' ssh-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700324 waitListening( server=self, port=KarafPort, callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700325 info( ' openflow-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700326 waitListening( server=self, port=OpenFlowPort,
327 callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700328 info( ' client' )
329 while True:
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700330 result = quietRun( '%s -h %s "apps -a"' %
Bob Lantzbb37d872016-05-16 16:26:13 -0700331 ( self.client, self.IP() ), shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700332 if 'openflow' in result:
333 break
334 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700335 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700336 time.sleep( 1 )
337 info( ')\n' )
338
339 def updateEnv( self, envDict ):
340 "Update environment variables"
Bob Lantz569bbec2016-06-03 18:51:16 -0700341 cmd = ';'.join( ( 'export %s="%s"' % ( var, val )
342 if val else 'unset %s' % var )
Bob Lantz087b5d92016-05-06 11:39:04 -0700343 for var, val in envDict.iteritems() )
344 self.cmd( cmd )
345
Bob Lantz1451d722016-05-17 14:40:07 -0700346 def ucmd( self, *args, **_kwargs ):
347 "Run command as $ONOS_USER using sudo -E -u"
348 if ONOS_USER != 'root': # don't bother with sudo
349 args = [ "sudo -E -u $ONOS_USER PATH=$PATH "
350 "bash -c '%s'" % ' '.join( args ) ]
351 return self.cmd( *args )
352
Bob Lantz087b5d92016-05-06 11:39:04 -0700353
354class ONOSCluster( Controller ):
355 "ONOS Cluster"
356 def __init__( self, *args, **kwargs ):
357 """name: (first parameter)
358 *args: topology class parameters
359 ipBase: IP range for ONOS nodes
Bob Lantzbb37d872016-05-16 16:26:13 -0700360 forward: default port forwarding list,
Bob Lantz087b5d92016-05-06 11:39:04 -0700361 topo: topology class or instance
Bob Lantz64382422016-06-03 22:51:39 -0700362 nodeOpts: ONOSNode options
Bob Lantz087b5d92016-05-06 11:39:04 -0700363 **kwargs: additional topology parameters"""
364 args = list( args )
365 name = args.pop( 0 )
366 topo = kwargs.pop( 'topo', None )
Bob Lantz930138e2016-06-23 18:53:19 -0700367 self.nat = kwargs.pop( 'nat', 'nat0' )
Bob Lantz64382422016-06-03 22:51:39 -0700368 nodeOpts = kwargs.pop( 'nodeOpts', {} )
Bob Lantz087b5d92016-05-06 11:39:04 -0700369 # Default: single switch with 1 ONOS node
370 if not topo:
371 topo = SingleSwitchTopo
372 if not args:
373 args = ( 1, )
374 if not isinstance( topo, Topo ):
375 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700376 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
377 self.forward = kwargs.pop( 'forward',
378 [ KarafPort, GUIPort, OpenFlowPort ] )
Bob Lantz087b5d92016-05-06 11:39:04 -0700379 super( ONOSCluster, self ).__init__( name, inNamespace=False )
380 fixIPTables()
381 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700382 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700383 host=partial( ONOSNode, **nodeOpts ),
384 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700385 controller=None )
Bob Lantz930138e2016-06-23 18:53:19 -0700386 if self.nat:
387 self.net.addNAT( self.nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700388 updateNodeIPs( self.env, self.nodes() )
389 self._remoteControllers = []
390
391 def start( self ):
392 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700393 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
394 self.net.start()
395 for node in self.nodes():
Bob Lantz569bbec2016-06-03 18:51:16 -0700396 node.start( self.env, self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700397 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700398 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700399 self.waitStarted()
400 return
401
402 def waitStarted( self ):
403 "Wait until all nodes have started"
404 startTime = time.time()
405 for node in self.nodes():
406 info( node )
407 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700408 info( '*** Waited %.2f seconds for ONOS startup' %
409 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700410
411 def stop( self ):
412 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700413 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700414 for node in self.nodes():
415 node.stop()
416 self.net.stop()
417
418 def nodes( self ):
419 "Return list of ONOS nodes"
420 return [ h for h in self.net.hosts if isinstance( h, ONOSNode ) ]
421
Bob Lantz930138e2016-06-23 18:53:19 -0700422 def configPortForwarding( self, ports=[], action='A' ):
423 """Start or stop port forwarding (any intf) for all nodes
424 ports: list of ports to forward
Bob Lantzbb37d872016-05-16 16:26:13 -0700425 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz930138e2016-06-23 18:53:19 -0700426 self.cmd( 'iptables -' + action, 'FORWARD -d', self.ipBase,
427 '-j ACCEPT' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700428 for port in ports:
429 for index, node in enumerate( self.nodes() ):
430 ip, inport = node.IP(), port + index
431 # Configure a destination NAT rule
Bob Lantz930138e2016-06-23 18:53:19 -0700432 self.cmd( 'iptables -t nat -' + action,
433 'PREROUTING -t nat -p tcp --dport', inport,
434 '-j DNAT --to-destination %s:%s' % ( ip, port ) )
Bob Lantzbb37d872016-05-16 16:26:13 -0700435
Bob Lantz930138e2016-06-23 18:53:19 -0700436
Bob Lantz087b5d92016-05-06 11:39:04 -0700437class ONOSSwitchMixin( object ):
438 "Mixin for switches that connect to an ONOSCluster"
439 def start( self, controllers ):
440 "Connect to ONOSCluster"
441 self.controllers = controllers
442 assert ( len( controllers ) is 1 and
443 isinstance( controllers[ 0 ], ONOSCluster ) )
444 clist = controllers[ 0 ].nodes()
445 return super( ONOSSwitchMixin, self ).start( clist )
446
447class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
448 "OVSSwitch that can connect to an ONOSCluster"
449 pass
450
451class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
452 "UserSwitch that can connect to an ONOSCluster"
453 pass
454
455
456### Ugly utility routines
457
458def fixIPTables():
459 "Fix LinuxBridge warning"
460 for s in 'arp', 'ip', 'ip6':
461 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
462
463
464### Test code
465
466def test( serverCount ):
467 "Test this setup"
468 setLogLevel( 'info' )
469 net = Mininet( topo=SingleSwitchTopo( 3 ),
470 controller=[ ONOSCluster( 'c0', serverCount ) ],
471 switch=ONOSOVSSwitch )
472 net.start()
473 net.waitConnected()
474 CLI( net )
475 net.stop()
476
477
478### CLI Extensions
479
480OldCLI = CLI
481
482class ONOSCLI( OldCLI ):
483 "CLI Extensions for ONOS"
484
485 prompt = 'mininet-onos> '
486
487 def __init__( self, net, **kwargs ):
488 c0 = net.controllers[ 0 ]
489 if isinstance( c0, ONOSCluster ):
490 net = MininetFacade( net, cnet=c0.net )
491 OldCLI.__init__( self, net, **kwargs )
492
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700493 def onos1( self ):
494 "Helper function: return default ONOS node"
495 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
496
Bob Lantz087b5d92016-05-06 11:39:04 -0700497 def do_onos( self, line ):
498 "Send command to ONOS CLI"
499 c0 = self.mn.controllers[ 0 ]
500 if isinstance( c0, ONOSCluster ):
501 # cmdLoop strips off command name 'onos'
502 if line.startswith( ':' ):
503 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700504 onos1 = self.onos1().name
505 if line:
506 line = '"%s"' % line
507 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700508 quietRun( 'stty -echo' )
509 self.default( cmd )
510 quietRun( 'stty echo' )
511
512 def do_wait( self, line ):
513 "Wait for switches to connect"
514 self.mn.waitConnected()
515
516 def do_balance( self, line ):
517 "Balance switch mastership"
518 self.do_onos( ':balance-masters' )
519
520 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700521 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700522 self.default( '%s tail -f /tmp/%s/log' %
523 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700524
Bob Lantz64382422016-06-03 22:51:39 -0700525 def do_status( self, line ):
526 "Return status of ONOS cluster(s)"
527 for c in self.mn.controllers:
528 if isinstance( c, ONOSCluster ):
529 for node in c.net.hosts:
530 if isinstance( node, ONOSNode ):
531 errors, warnings = node.checkLog()
532 running = ( 'Running' if node.isRunning()
533 else 'Exited' )
534 status = ''
535 if errors:
536 status += '%d ERRORS ' % len( errors )
537 if warnings:
538 status += '%d warnings' % len( warnings )
539 status = status if status else 'OK'
540 info( node, '\t', running, '\t', status, '\n' )
541
Bob Lantzc96e2582016-06-13 18:57:04 -0700542 def do_arp( self, line ):
543 "Send gratuitous arps from all data network hosts"
544 startTime = time.time()
545 try:
546 count = int( line )
547 except:
548 count = 1
549 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700550 if '-U' not in quietRun( 'arping -h', shell=True ):
551 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700552 return
553 # This is much faster if we do it in parallel
554 for host in self.mn.net.hosts:
555 intf = host.defaultIntf()
556 # -b: keep using broadcasts; -f: quit after 1 reply
557 # -U: gratuitous ARP update
558 host.sendCmd( 'arping -bf -c', count, '-U -I',
559 intf.name, intf.IP() )
560 for host in self.mn.net.hosts:
561 # We could check the output here if desired
562 host.waitOutput()
563 info( '.' )
564 info( '\n' )
565 elapsed = time.time() - startTime
566 debug( 'Completed in %.2f seconds\n' % elapsed )
567
Bob Lantz64382422016-06-03 22:51:39 -0700568
569# For interactive use, exit on error
570exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
571ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
572
Bob Lantz087b5d92016-05-06 11:39:04 -0700573
574### Exports for bin/mn
575
576CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700577controllers = { 'onos': ONOSClusterInteractive,
578 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700579
580# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700581findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700582
583switches = { 'onos': ONOSOVSSwitch,
584 'onosovs': ONOSOVSSwitch,
585 'onosuser': ONOSUserSwitch,
586 'default': ONOSOVSSwitch }
587
Bob Lantzbb37d872016-05-16 16:26:13 -0700588# Null topology so we can control an external/hardware network
589topos = { 'none': Topo }
590
Bob Lantz087b5d92016-05-06 11:39:04 -0700591if __name__ == '__main__':
592 if len( argv ) != 2:
593 test( 3 )
594 else:
595 test( int( argv[ 1 ] ) )