blob: 069f680be6fd55b265878c9d664d1a4450f7f567 [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', {} )
Jon Hall9b238ae2016-08-09 13:47:43 -0700373 # Pass in kwargs to the ONOSNodes instead of the cluster
374 "alertAction: exception|ignore|warn|exit (exception)"
375 alertAction = kwargs.pop( 'alertAction', None )
376 if alertAction:
377 nodeOpts[ 'alertAction'] = alertAction
Bob Lantz087b5d92016-05-06 11:39:04 -0700378 # Default: single switch with 1 ONOS node
379 if not topo:
380 topo = SingleSwitchTopo
381 if not args:
382 args = ( 1, )
383 if not isinstance( topo, Topo ):
384 topo = RenamedTopo( topo, *args, hnew='onos', **kwargs )
Bob Lantzbb37d872016-05-16 16:26:13 -0700385 self.ipBase = kwargs.pop( 'ipBase', '192.168.123.0/24' )
386 self.forward = kwargs.pop( 'forward',
387 [ KarafPort, GUIPort, OpenFlowPort ] )
Bob Lantz087b5d92016-05-06 11:39:04 -0700388 super( ONOSCluster, self ).__init__( name, inNamespace=False )
389 fixIPTables()
390 self.env = initONOSEnv()
Bob Lantzbb37d872016-05-16 16:26:13 -0700391 self.net = Mininet( topo=topo, ipBase=self.ipBase,
Bob Lantz64382422016-06-03 22:51:39 -0700392 host=partial( ONOSNode, **nodeOpts ),
393 switch=LinuxBridge,
Bob Lantz087b5d92016-05-06 11:39:04 -0700394 controller=None )
Bob Lantz930138e2016-06-23 18:53:19 -0700395 if self.nat:
396 self.net.addNAT( self.nat ).configDefault()
Bob Lantz087b5d92016-05-06 11:39:04 -0700397 updateNodeIPs( self.env, self.nodes() )
398 self._remoteControllers = []
399
400 def start( self ):
401 "Start up ONOS cluster"
Bob Lantz087b5d92016-05-06 11:39:04 -0700402 info( '*** ONOS_APPS = %s\n' % ONOS_APPS )
403 self.net.start()
404 for node in self.nodes():
Bob Lantz569bbec2016-06-03 18:51:16 -0700405 node.start( self.env, self.nodes() )
Bob Lantz087b5d92016-05-06 11:39:04 -0700406 info( '\n' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700407 self.configPortForwarding( ports=self.forward, action='A' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700408 self.waitStarted()
409 return
410
411 def waitStarted( self ):
412 "Wait until all nodes have started"
413 startTime = time.time()
414 for node in self.nodes():
415 info( node )
416 node.waitStarted()
Bob Lantzbb37d872016-05-16 16:26:13 -0700417 info( '*** Waited %.2f seconds for ONOS startup' %
418 ( time.time() - startTime ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700419
420 def stop( self ):
421 "Shut down ONOS cluster"
Bob Lantzbb37d872016-05-16 16:26:13 -0700422 self.configPortForwarding( ports=self.forward, action='D' )
Bob Lantz087b5d92016-05-06 11:39:04 -0700423 for node in self.nodes():
424 node.stop()
425 self.net.stop()
426
427 def nodes( self ):
428 "Return list of ONOS nodes"
429 return [ h for h in self.net.hosts if isinstance( h, ONOSNode ) ]
430
Bob Lantz930138e2016-06-23 18:53:19 -0700431 def configPortForwarding( self, ports=[], action='A' ):
432 """Start or stop port forwarding (any intf) for all nodes
433 ports: list of ports to forward
Bob Lantzbb37d872016-05-16 16:26:13 -0700434 action: A=add/start, D=delete/stop (default: A)"""
Bob Lantz930138e2016-06-23 18:53:19 -0700435 self.cmd( 'iptables -' + action, 'FORWARD -d', self.ipBase,
436 '-j ACCEPT' )
Bob Lantzbb37d872016-05-16 16:26:13 -0700437 for port in ports:
438 for index, node in enumerate( self.nodes() ):
439 ip, inport = node.IP(), port + index
440 # Configure a destination NAT rule
Bob Lantz930138e2016-06-23 18:53:19 -0700441 self.cmd( 'iptables -t nat -' + action,
442 'PREROUTING -t nat -p tcp --dport', inport,
443 '-j DNAT --to-destination %s:%s' % ( ip, port ) )
Bob Lantzbb37d872016-05-16 16:26:13 -0700444
Bob Lantz930138e2016-06-23 18:53:19 -0700445
Bob Lantz087b5d92016-05-06 11:39:04 -0700446class ONOSSwitchMixin( object ):
447 "Mixin for switches that connect to an ONOSCluster"
448 def start( self, controllers ):
449 "Connect to ONOSCluster"
450 self.controllers = controllers
451 assert ( len( controllers ) is 1 and
452 isinstance( controllers[ 0 ], ONOSCluster ) )
453 clist = controllers[ 0 ].nodes()
454 return super( ONOSSwitchMixin, self ).start( clist )
455
456class ONOSOVSSwitch( ONOSSwitchMixin, OVSSwitch ):
457 "OVSSwitch that can connect to an ONOSCluster"
458 pass
459
460class ONOSUserSwitch( ONOSSwitchMixin, UserSwitch):
461 "UserSwitch that can connect to an ONOSCluster"
462 pass
463
464
465### Ugly utility routines
466
467def fixIPTables():
468 "Fix LinuxBridge warning"
469 for s in 'arp', 'ip', 'ip6':
470 quietRun( 'sysctl net.bridge.bridge-nf-call-%stables=0' % s )
471
472
473### Test code
474
475def test( serverCount ):
476 "Test this setup"
477 setLogLevel( 'info' )
478 net = Mininet( topo=SingleSwitchTopo( 3 ),
479 controller=[ ONOSCluster( 'c0', serverCount ) ],
480 switch=ONOSOVSSwitch )
481 net.start()
482 net.waitConnected()
483 CLI( net )
484 net.stop()
485
486
487### CLI Extensions
488
489OldCLI = CLI
490
491class ONOSCLI( OldCLI ):
492 "CLI Extensions for ONOS"
493
494 prompt = 'mininet-onos> '
495
496 def __init__( self, net, **kwargs ):
497 c0 = net.controllers[ 0 ]
498 if isinstance( c0, ONOSCluster ):
499 net = MininetFacade( net, cnet=c0.net )
500 OldCLI.__init__( self, net, **kwargs )
501
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700502 def onos1( self ):
503 "Helper function: return default ONOS node"
504 return self.mn.controllers[ 0 ].net.hosts[ 0 ]
505
Bob Lantz087b5d92016-05-06 11:39:04 -0700506 def do_onos( self, line ):
507 "Send command to ONOS CLI"
508 c0 = self.mn.controllers[ 0 ]
509 if isinstance( c0, ONOSCluster ):
510 # cmdLoop strips off command name 'onos'
511 if line.startswith( ':' ):
512 line = 'onos' + line
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700513 onos1 = self.onos1().name
514 if line:
515 line = '"%s"' % line
516 cmd = '%s client -h %s %s' % ( onos1, onos1, line )
Bob Lantz087b5d92016-05-06 11:39:04 -0700517 quietRun( 'stty -echo' )
518 self.default( cmd )
519 quietRun( 'stty echo' )
520
521 def do_wait( self, line ):
522 "Wait for switches to connect"
523 self.mn.waitConnected()
524
525 def do_balance( self, line ):
526 "Balance switch mastership"
527 self.do_onos( ':balance-masters' )
528
529 def do_log( self, line ):
Bob Lantz4b51d5c2016-05-27 14:47:38 -0700530 "Run tail -f /tmp/onos1/log; press control-C to stop"
Bob Lantz9ba19dc2016-06-13 20:22:07 -0700531 self.default( '%s tail -f /tmp/%s/log' %
532 ( self.onos1(), self.onos1() ) )
Bob Lantz087b5d92016-05-06 11:39:04 -0700533
Bob Lantz64382422016-06-03 22:51:39 -0700534 def do_status( self, line ):
535 "Return status of ONOS cluster(s)"
536 for c in self.mn.controllers:
537 if isinstance( c, ONOSCluster ):
538 for node in c.net.hosts:
539 if isinstance( node, ONOSNode ):
540 errors, warnings = node.checkLog()
541 running = ( 'Running' if node.isRunning()
542 else 'Exited' )
543 status = ''
544 if errors:
545 status += '%d ERRORS ' % len( errors )
546 if warnings:
547 status += '%d warnings' % len( warnings )
548 status = status if status else 'OK'
549 info( node, '\t', running, '\t', status, '\n' )
550
Bob Lantzc96e2582016-06-13 18:57:04 -0700551 def do_arp( self, line ):
552 "Send gratuitous arps from all data network hosts"
553 startTime = time.time()
554 try:
555 count = int( line )
556 except:
557 count = 1
558 # Technically this check should be on the host
Bob Lantzc3de5152016-06-17 17:13:57 -0700559 if '-U' not in quietRun( 'arping -h', shell=True ):
560 warn( 'Please install iputils-arping.\n' )
Bob Lantzc96e2582016-06-13 18:57:04 -0700561 return
562 # This is much faster if we do it in parallel
563 for host in self.mn.net.hosts:
564 intf = host.defaultIntf()
565 # -b: keep using broadcasts; -f: quit after 1 reply
566 # -U: gratuitous ARP update
567 host.sendCmd( 'arping -bf -c', count, '-U -I',
568 intf.name, intf.IP() )
569 for host in self.mn.net.hosts:
570 # We could check the output here if desired
571 host.waitOutput()
572 info( '.' )
573 info( '\n' )
574 elapsed = time.time() - startTime
575 debug( 'Completed in %.2f seconds\n' % elapsed )
576
Bob Lantz64382422016-06-03 22:51:39 -0700577
578# For interactive use, exit on error
579exitOnError = dict( nodeOpts={ 'alertAction': 'exit' } )
580ONOSClusterInteractive = specialClass( ONOSCluster, defaults=exitOnError )
581
Bob Lantz087b5d92016-05-06 11:39:04 -0700582
583### Exports for bin/mn
584
585CLI = ONOSCLI
Bob Lantz64382422016-06-03 22:51:39 -0700586controllers = { 'onos': ONOSClusterInteractive,
587 'default': ONOSClusterInteractive }
Bob Lantz087b5d92016-05-06 11:39:04 -0700588
589# XXX Hack to change default controller as above doesn't work
Bob Lantz64382422016-06-03 22:51:39 -0700590findController = lambda: controllers[ 'default' ]
Bob Lantz087b5d92016-05-06 11:39:04 -0700591
592switches = { 'onos': ONOSOVSSwitch,
593 'onosovs': ONOSOVSSwitch,
594 'onosuser': ONOSUserSwitch,
595 'default': ONOSOVSSwitch }
596
Bob Lantzbb37d872016-05-16 16:26:13 -0700597# Null topology so we can control an external/hardware network
598topos = { 'none': Topo }
599
Bob Lantz087b5d92016-05-06 11:39:04 -0700600if __name__ == '__main__':
601 if len( argv ) != 2:
602 test( 3 )
603 else:
604 test( int( argv[ 1 ] ) )