blob: 6314eb03b5138366ee5d5d715cea092d372866a0 [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 Lantza2ccaa52016-06-29 18:26:06 -0700138 success = '*** SUCCESS ***'
139 cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s" && echo "%s"'
140 % ( destDir, destDir, tarPath, success ) )
141 result = run( cmds, shell=True, verbose=True )
142 if success not in result:
143 raise Exception( 'Failed to unpack ONOS archive %s in %s:\n%s\n' %
144 ( tarPath, destDir, result ) )
Bob Lantz1451d722016-05-17 14:40:07 -0700145 # We can use quietRun for this usually
146 tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True)
147 tarOutput = tarOutput.split()[ 0 ].strip()
148 assert '/' in tarOutput
149 onosDir = join( destDir, dirname( tarOutput ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700150 # Add symlink to log file
Bob Lantz1451d722016-05-17 14:40:07 -0700151 run( 'cd %s; ln -s onos*/apache* karaf;'
152 'ln -s karaf/data/log/karaf.log log' % destDir,
153 shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700154 return onosDir
155
156
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700157def waitListening( server, port=80, callback=None, sleepSecs=.5,
158 proc='java' ):
159 "Simplified netstat version of waitListening"
160 while True:
161 lines = server.cmd( 'netstat -natp' ).strip().split( '\n' )
162 entries = [ line.split() for line in lines ]
163 portstr = ':%s' % port
164 listening = [ entry for entry in entries
165 if len( entry ) > 6 and portstr in entry[ 3 ]
166 and proc in entry[ 6 ] ]
167 if listening:
168 break
Bob Lantz64382422016-06-03 22:51:39 -0700169 info( '.' )
170 if callback:
171 callback()
172 time.sleep( sleepSecs )
Bob Lantz64382422016-06-03 22:51:39 -0700173
174
Bob Lantz087b5d92016-05-06 11:39:04 -0700175### Mininet classes
176
177def RenamedTopo( topo, *args, **kwargs ):
178 """Return specialized topo with renamed hosts
179 topo: topo class/class name to specialize
180 args, kwargs: topo args
181 sold: old switch name prefix (default 's')
182 snew: new switch name prefix
183 hold: old host name prefix (default 'h')
184 hnew: new host name prefix
185 This may be used from the mn command, e.g.
186 mn --topo renamed,single,spref=sw,hpref=host"""
187 sold = kwargs.pop( 'sold', 's' )
188 hold = kwargs.pop( 'hold', 'h' )
189 snew = kwargs.pop( 'snew', 'cs' )
190 hnew = kwargs.pop( 'hnew' ,'ch' )
191 topos = {} # TODO: use global TOPOS dict
192 if isinstance( topo, str ):
193 # Look up in topo directory - this allows us to
194 # use RenamedTopo from the command line!
195 if topo in topos:
196 topo = topos.get( topo )
197 else:
198 raise Exception( 'Unknown topo name: %s' % topo )
199 # pylint: disable=no-init
200 class RenamedTopoCls( topo ):
201 "Topo subclass with renamed nodes"
202 def addNode( self, name, *args, **kwargs ):
203 "Add a node, renaming if necessary"
204 if name.startswith( sold ):
205 name = snew + name[ len( sold ): ]
206 elif name.startswith( hold ):
207 name = hnew + name[ len( hold ): ]
208 return topo.addNode( self, name, *args, **kwargs )
209 return RenamedTopoCls( *args, **kwargs )
210
211
212class ONOSNode( Controller ):
213 "ONOS cluster node"
214
Bob Lantz087b5d92016-05-06 11:39:04 -0700215 def __init__( self, name, **kwargs ):
Bob Lantz64382422016-06-03 22:51:39 -0700216 "alertAction: exception|ignore|warn|exit (exception)"
Bob Lantz087b5d92016-05-06 11:39:04 -0700217 kwargs.update( inNamespace=True )
Bob Lantz64382422016-06-03 22:51:39 -0700218 self.alertAction = kwargs.pop( 'alertAction', 'exception' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700219 Controller.__init__( self, name, **kwargs )
220 self.dir = '/tmp/%s' % self.name
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700221 self.client = self.dir + '/karaf/bin/client'
Bob Lantz087b5d92016-05-06 11:39:04 -0700222 self.ONOS_HOME = '/tmp'
Bob Lantz55562ea2016-06-17 18:19:03 -0700223 self.cmd( 'rm -rf', self.dir )
224 self.ONOS_HOME = unpackONOS( self.dir, run=self.ucmd )
Bob Lantz087b5d92016-05-06 11:39:04 -0700225
226 # pylint: disable=arguments-differ
227
Bob Lantz569bbec2016-06-03 18:51:16 -0700228 def start( self, env, nodes=() ):
Bob Lantz087b5d92016-05-06 11:39:04 -0700229 """Start ONOS on node
Bob Lantz569bbec2016-06-03 18:51:16 -0700230 env: environment var dict
231 nodes: all nodes in cluster"""
Bob Lantz087b5d92016-05-06 11:39:04 -0700232 env = dict( env )
Bob Lantz087b5d92016-05-06 11:39:04 -0700233 env.update( ONOS_HOME=self.ONOS_HOME )
234 self.updateEnv( env )
235 karafbin = glob( '%s/apache*/bin' % self.ONOS_HOME )[ 0 ]
236 onosbin = join( ONOS_ROOT, 'tools/test/bin' )
237 self.cmd( 'export PATH=%s:%s:$PATH' % ( onosbin, karafbin ) )
238 self.cmd( 'cd', self.ONOS_HOME )
Bob Lantz1451d722016-05-17 14:40:07 -0700239 self.ucmd( 'mkdir -p config && '
Bob Lantz569bbec2016-06-03 18:51:16 -0700240 'onos-gen-partitions config/cluster.json',
241 ' '.join( node.IP() for node in nodes ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700242 info( '(starting %s)' % self )
243 service = join( self.ONOS_HOME, 'bin/onos-service' )
Bob Lantz1451d722016-05-17 14:40:07 -0700244 self.ucmd( service, 'server 1>../onos.log 2>../onos.log'
245 ' & echo $! > onos.pid; ln -s `pwd`/onos.pid ..' )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700246 self.onosPid = int( self.cmd( 'cat onos.pid' ).strip() )
Bob Lantz64382422016-06-03 22:51:39 -0700247 self.warningCount = 0
Bob Lantz087b5d92016-05-06 11:39:04 -0700248
249 # pylint: enable=arguments-differ
250
251 def stop( self ):
252 # XXX This will kill all karafs - too bad!
253 self.cmd( 'pkill -HUP -f karaf.jar && wait' )
254 self.cmd( 'rm -rf', self.dir )
255
Bob Lantz64382422016-06-03 22:51:39 -0700256 def sanityAlert( self, *args ):
257 "Alert to raise on sanityCheck failure"
258 info( '\n' )
259 if self.alertAction == 'exception':
260 raise Exception( *args )
261 if self.alertAction == 'warn':
262 warn( *args + ( '\n', ) )
263 elif self.alertAction == 'exit':
264 error( '***', *args +
265 ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) )
266 exit( 1 )
267
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700268 def isRunning( self ):
269 "Is our ONOS process still running?"
Bob Lantz64382422016-06-03 22:51:39 -0700270 cmd = ( 'ps -p %d >/dev/null 2>&1 && echo "running" ||'
271 'echo "not running"' )
272 return self.cmd( cmd % self.onosPid ).strip() == 'running'
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700273
Bob Lantz64382422016-06-03 22:51:39 -0700274 def checkLog( self ):
275 "Return log file errors and warnings"
276 log = join( self.dir, 'log' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700277 errors, warnings = [], []
Bob Lantz64382422016-06-03 22:51:39 -0700278 if isfile( log ):
279 lines = open( log ).read().split( '\n' )
280 errors = [ line for line in lines if 'ERROR' in line ]
281 warnings = [ line for line in lines if 'WARN'in line ]
282 return errors, warnings
283
284 def memAvailable( self ):
285 "Return available memory in KB (or -1 if we can't tell)"
286 lines = open( '/proc/meminfo' ).read().strip().split( '\n' )
287 entries = map( str.split, lines )
288 index = { entry[ 0 ]: entry for entry in entries }
289 # Check MemAvailable if present
290 default = ( None, '-1', 'kB' )
291 _name, count, unit = index.get( 'MemAvailable:', default )
292 if unit.lower() == 'kb':
293 return int( count )
294 return -1
295
296 def sanityCheck( self, lowMem=100000 ):
297 """Check whether we've quit or are running out of memory
298 lowMem: low memory threshold in KB (100000)"""
299 # Are we still running?
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700300 if not self.isRunning():
Bob Lantz64382422016-06-03 22:51:39 -0700301 self.sanityAlert( 'ONOS node %s has died' % self.name )
302 # Are there errors in the log file?
303 errors, warnings = self.checkLog()
304 if errors:
305 self.sanityAlert( 'ONOS startup errors:\n<<%s>>' %
306 '\n'.join( errors ) )
307 warningCount = len( warnings )
308 if warnings and warningCount > self.warningCount:
309 warn( '(%d warnings)' % len( warnings ) )
310 self.warningCount = warningCount
311 # Are we running out of memory?
312 mem = self.memAvailable()
313 if mem > 0 and mem < lowMem:
314 self.sanityAlert( 'Running out of memory (only %d KB available)'
315 % mem )
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700316
Bob Lantz087b5d92016-05-06 11:39:04 -0700317 def waitStarted( self ):
318 "Wait until we've really started"
319 info( '(checking: karaf' )
320 while True:
Bob Lantz1451d722016-05-17 14:40:07 -0700321 status = self.ucmd( 'karaf status' ).lower()
Bob Lantz087b5d92016-05-06 11:39:04 -0700322 if 'running' in status and 'not running' not in status:
323 break
324 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700325 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700326 time.sleep( 1 )
327 info( ' ssh-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700328 waitListening( server=self, port=KarafPort, callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700329 info( ' openflow-port' )
Bob Lantz64382422016-06-03 22:51:39 -0700330 waitListening( server=self, port=OpenFlowPort,
331 callback=self.sanityCheck )
Bob Lantz087b5d92016-05-06 11:39:04 -0700332 info( ' client' )
333 while True:
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700334 result = quietRun( '%s -h %s "apps -a"' %
Bob Lantzbb37d872016-05-16 16:26:13 -0700335 ( self.client, self.IP() ), shell=True )
Bob Lantz087b5d92016-05-06 11:39:04 -0700336 if 'openflow' in result:
337 break
338 info( '.' )
Bob Lantz64382422016-06-03 22:51:39 -0700339 self.sanityCheck()
Bob Lantz087b5d92016-05-06 11:39:04 -0700340 time.sleep( 1 )
341 info( ')\n' )
342
343 def updateEnv( self, envDict ):
344 "Update environment variables"
Bob Lantz569bbec2016-06-03 18:51:16 -0700345 cmd = ';'.join( ( 'export %s="%s"' % ( var, val )
346 if val else 'unset %s' % var )
Bob Lantz087b5d92016-05-06 11:39:04 -0700347 for var, val in envDict.iteritems() )
348 self.cmd( cmd )
349
Bob Lantz1451d722016-05-17 14:40:07 -0700350 def ucmd( self, *args, **_kwargs ):
351 "Run command as $ONOS_USER using sudo -E -u"
352 if ONOS_USER != 'root': # don't bother with sudo
353 args = [ "sudo -E -u $ONOS_USER PATH=$PATH "
354 "bash -c '%s'" % ' '.join( args ) ]
355 return self.cmd( *args )
356
Bob Lantz087b5d92016-05-06 11:39:04 -0700357
358class ONOSCluster( Controller ):
359 "ONOS Cluster"
360 def __init__( self, *args, **kwargs ):
361 """name: (first parameter)
362 *args: topology class parameters
363 ipBase: IP range for ONOS nodes
Bob Lantzbb37d872016-05-16 16:26:13 -0700364 forward: default port forwarding list,
Bob Lantz087b5d92016-05-06 11:39:04 -0700365 topo: topology class or instance
Bob Lantz64382422016-06-03 22:51:39 -0700366 nodeOpts: ONOSNode options
Bob Lantz087b5d92016-05-06 11:39:04 -0700367 **kwargs: additional topology parameters"""
368 args = list( args )
369 name = args.pop( 0 )
370 topo = kwargs.pop( 'topo', None )
Bob Lantz930138e2016-06-23 18:53:19 -0700371 self.nat = kwargs.pop( 'nat', 'nat0' )
Bob Lantz64382422016-06-03 22:51:39 -0700372 nodeOpts = kwargs.pop( 'nodeOpts', {} )
Bob Lantz087b5d92016-05-06 11:39:04 -0700373 # Default: single switch with 1 ONOS node
374 if not topo:
375 topo = SingleSwitchTopo
376 if not args:
377 args = ( 1, )
378 if not isinstance( topo, Topo ):
379 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700380 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
381 self.forward = kwargs.pop( 'forward',
382 [ KarafPort, GUIPort, OpenFlowPort ] )
Bob Lantz087b5d92016-05-06 11:39:04 -0700383 super( ONOSCluster, self ).__init__( name, inNamespace=False )
384 fixIPTables()
385 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700386 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700387 host=partial( ONOSNode, **nodeOpts ),
388 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700389 controller=None )
Bob Lantz930138e2016-06-23 18:53:19 -0700390 if self.nat:
391 self.net.addNAT( self.nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700392 updateNodeIPs( self.env, self.nodes() )
393 self._remoteControllers = []
394
395 def start( self ):
396 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700397 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
398 self.net.start()
399 for node in self.nodes():
Bob Lantz569bbec2016-06-03 18:51:16 -0700400 node.start( self.env, self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700401 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700402 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700403 self.waitStarted()
404 return
405
406 def waitStarted( self ):
407 "Wait until all nodes have started"
408 startTime = time.time()
409 for node in self.nodes():
410 info( node )
411 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700412 info( '*** Waited %.2f seconds for ONOS startup' %
413 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700414
415 def stop( self ):
416 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700417 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700418 for node in self.nodes():
419 node.stop()
420 self.net.stop()
421
422 def nodes( self ):
423 "Return list of ONOS nodes"
424 return [ h for h in self.net.hosts if isinstance( h, ONOSNode ) ]
425
Bob Lantz930138e2016-06-23 18:53:19 -0700426 def configPortForwarding( self, ports=[], action='A' ):
427 """Start or stop port forwarding (any intf) for all nodes
428 ports: list of ports to forward
Bob Lantzbb37d872016-05-16 16:26:13 -0700429 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz930138e2016-06-23 18:53:19 -0700430 self.cmd( 'iptables -' + action, 'FORWARD -d', self.ipBase,
431 '-j ACCEPT' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700432 for port in ports:
433 for index, node in enumerate( self.nodes() ):
434 ip, inport = node.IP(), port + index
435 # Configure a destination NAT rule
Bob Lantz930138e2016-06-23 18:53:19 -0700436 self.cmd( 'iptables -t nat -' + action,
437 'PREROUTING -t nat -p tcp --dport', inport,
438 '-j DNAT --to-destination %s:%s' % ( ip, port ) )
Bob Lantzbb37d872016-05-16 16:26:13 -0700439
Bob Lantz930138e2016-06-23 18:53:19 -0700440
Bob Lantz087b5d92016-05-06 11:39:04 -0700441class ONOSSwitchMixin( object ):
442 "Mixin for switches that connect to an ONOSCluster"
443 def start( self, controllers ):
444 "Connect to ONOSCluster"
445 self.controllers = controllers
446 assert ( len( controllers ) is 1 and
447 isinstance( controllers[ 0 ], ONOSCluster ) )
448 clist = controllers[ 0 ].nodes()
449 return super( ONOSSwitchMixin, self ).start( clist )
450
451class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
452 "OVSSwitch that can connect to an ONOSCluster"
453 pass
454
455class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
456 "UserSwitch that can connect to an ONOSCluster"
457 pass
458
459
460### Ugly utility routines
461
462def fixIPTables():
463 "Fix LinuxBridge warning"
464 for s in 'arp', 'ip', 'ip6':
465 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
466
467
468### Test code
469
470def test( serverCount ):
471 "Test this setup"
472 setLogLevel( 'info' )
473 net = Mininet( topo=SingleSwitchTopo( 3 ),
474 controller=[ ONOSCluster( 'c0', serverCount ) ],
475 switch=ONOSOVSSwitch )
476 net.start()
477 net.waitConnected()
478 CLI( net )
479 net.stop()
480
481
482### CLI Extensions
483
484OldCLI = CLI
485
486class ONOSCLI( OldCLI ):
487 "CLI Extensions for ONOS"
488
489 prompt = 'mininet-onos> '
490
491 def __init__( self, net, **kwargs ):
492 c0 = net.controllers[ 0 ]
493 if isinstance( c0, ONOSCluster ):
494 net = MininetFacade( net, cnet=c0.net )
495 OldCLI.__init__( self, net, **kwargs )
496
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700497 def onos1( self ):
498 "Helper function: return default ONOS node"
499 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
500
Bob Lantz087b5d92016-05-06 11:39:04 -0700501 def do_onos( self, line ):
502 "Send command to ONOS CLI"
503 c0 = self.mn.controllers[ 0 ]
504 if isinstance( c0, ONOSCluster ):
505 # cmdLoop strips off command name 'onos'
506 if line.startswith( ':' ):
507 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700508 onos1 = self.onos1().name
509 if line:
510 line = '"%s"' % line
511 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700512 quietRun( 'stty -echo' )
513 self.default( cmd )
514 quietRun( 'stty echo' )
515
516 def do_wait( self, line ):
517 "Wait for switches to connect"
518 self.mn.waitConnected()
519
520 def do_balance( self, line ):
521 "Balance switch mastership"
522 self.do_onos( ':balance-masters' )
523
524 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700525 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700526 self.default( '%s tail -f /tmp/%s/log' %
527 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700528
Bob Lantz64382422016-06-03 22:51:39 -0700529 def do_status( self, line ):
530 "Return status of ONOS cluster(s)"
531 for c in self.mn.controllers:
532 if isinstance( c, ONOSCluster ):
533 for node in c.net.hosts:
534 if isinstance( node, ONOSNode ):
535 errors, warnings = node.checkLog()
536 running = ( 'Running' if node.isRunning()
537 else 'Exited' )
538 status = ''
539 if errors:
540 status += '%d ERRORS ' % len( errors )
541 if warnings:
542 status += '%d warnings' % len( warnings )
543 status = status if status else 'OK'
544 info( node, '\t', running, '\t', status, '\n' )
545
Bob Lantzc96e2582016-06-13 18:57:04 -0700546 def do_arp( self, line ):
547 "Send gratuitous arps from all data network hosts"
548 startTime = time.time()
549 try:
550 count = int( line )
551 except:
552 count = 1
553 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700554 if '-U' not in quietRun( 'arping -h', shell=True ):
555 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700556 return
557 # This is much faster if we do it in parallel
558 for host in self.mn.net.hosts:
559 intf = host.defaultIntf()
560 # -b: keep using broadcasts; -f: quit after 1 reply
561 # -U: gratuitous ARP update
562 host.sendCmd( 'arping -bf -c', count, '-U -I',
563 intf.name, intf.IP() )
564 for host in self.mn.net.hosts:
565 # We could check the output here if desired
566 host.waitOutput()
567 info( '.' )
568 info( '\n' )
569 elapsed = time.time() - startTime
570 debug( 'Completed in %.2f seconds\n' % elapsed )
571
Bob Lantz64382422016-06-03 22:51:39 -0700572
573# For interactive use, exit on error
574exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
575ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
576
Bob Lantz087b5d92016-05-06 11:39:04 -0700577
578### Exports for bin/mn
579
580CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700581controllers = { 'onos': ONOSClusterInteractive,
582 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700583
584# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700585findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700586
587switches = { 'onos': ONOSOVSSwitch,
588 'onosovs': ONOSOVSSwitch,
589 'onosuser': ONOSUserSwitch,
590 'default': ONOSOVSSwitch }
591
Bob Lantzbb37d872016-05-16 16:26:13 -0700592# Null topology so we can control an external/hardware network
593topos = { 'none': Topo }
594
Bob Lantz087b5d92016-05-06 11:39:04 -0700595if __name__ == '__main__':
596 if len( argv ) != 2:
597 test( 3 )
598 else:
599 test( int( argv[ 1 ] ) )