blob: 60b6c35615d21a4b6d067e90be86c59335bb518e [file] [log] [blame]
Bob Lantzc7c05402013-12-16 21:22:12 -08001#!/usr/bin/env python
2
3"""
Bob Lantz7ead0532013-12-17 20:41:20 -08004onos.py: A basic (?) ONOS Controller() subclass for Mininet
Bob Lantzc7c05402013-12-16 21:22:12 -08005
6We implement the following classes:
7
8ONOSController: a custom Controller() subclass to start ONOS
9OVSSwitchONOS: a custom OVSSwitch() switch that connects to multiple controllers.
10
11We use single Zookeeper and Cassandra instances for now.
12
13As a custom file, exports:
14
15--controller onos
16--switch ovso
17
18Usage:
19
20$ sudo ./onos.py
21
22This will start up a simple 2-host, 2 ONOS network
23
24$ sudo mn --custom onos.py --controller onos,2 --switch ovso
25"""
26
27from mininet.node import Controller, OVSSwitch
28from mininet.net import Mininet
29from mininet.cli import CLI
Bob Lantz7ead0532013-12-17 20:41:20 -080030from mininet.topo import LinearTopo
31from mininet.log import setLogLevel, info, warn
Bob Lantzc7c05402013-12-16 21:22:12 -080032from mininet.util import quietRun
33
Bob Lantza0930822013-12-17 21:00:41 -080034# This should be cleaned up to avoid interfering with mn
Bob Lantzc7c05402013-12-16 21:22:12 -080035from shutil import copyfile
36from os import environ
37from functools import partial
Bob Lantza0930822013-12-17 21:00:41 -080038import time
Bob Lantz7ead0532013-12-17 20:41:20 -080039from sys import argv
Bob Lantzc7c05402013-12-16 21:22:12 -080040
41class ONOS( Controller ):
42 "Custom controller class for ONOS"
43
44 # Directories and configuration templates
45 home = environ[ 'HOME' ]
46 onosDir = home + "/ONOS"
47 zookeeperDir = home + "/zookeeper-3.4.5"
48 dirBase = '/tmp'
49 logDir = dirBase + '/onos-%s.logs'
50 cassDir = dirBase + '/onos-%s.cassandra'
51 configFile = dirBase + '/onos-%s.properties'
52 logbackFile = dirBase + '/onos-%s.logback'
Bob Lantz7ead0532013-12-17 20:41:20 -080053
54 # Base ONOS modules
55 baseModules = (
56 'net.floodlightcontroller.core.FloodlightProvider',
57 'net.floodlightcontroller.threadpool.ThreadPool',
58 'net.onrc.onos.ofcontroller.floodlightlistener.NetworkGraphPublisher',
59 'net.floodlightcontroller.ui.web.StaticWebRoutable',
60 'net.onrc.onos.datagrid.HazelcastDatagrid',
61 'net.onrc.onos.ofcontroller.flowmanager.FlowManager',
62 'net.onrc.onos.ofcontroller.flowprogrammer.FlowProgrammer',
63 'net.onrc.onos.ofcontroller.topology.TopologyManager',
64 'net.onrc.onos.registry.controller.ZookeeperRegistry'
65 )
66
67 # Additions for reactive forwarding
68 reactiveModules = (
69 'net.onrc.onos.ofcontroller.proxyarp.ProxyArpManager',
70 'net.onrc.onos.ofcontroller.core.config.DefaultConfiguration',
71 'net.onrc.onos.ofcontroller.forwarding.Forwarding'
72 )
73
74 # Module parameters
Bob Lantzc7c05402013-12-16 21:22:12 -080075 ofbase = 6633
Bob Lantz7ead0532013-12-17 20:41:20 -080076 restbase = 8080
77 jmxbase = 7189
Bob Lantzc7c05402013-12-16 21:22:12 -080078
Bob Lantzc7c05402013-12-16 21:22:12 -080079 fc = 'net.floodlightcontroller.'
Bob Lantzc7c05402013-12-16 21:22:12 -080080
Bob Lantz7ead0532013-12-17 20:41:20 -080081 perNodeConfigBase = {
82 fc + 'core.FloodlightProvider.openflowport': ofbase,
83 fc + 'restserver.RestApiServer.port': restbase,
84 fc + 'core.FloodlightProvider.controllerid': 0
85 }
86
87 staticConfig = {
88 'net.onrc.onos.ofcontroller.floodlightlistener.NetworkGraphPublisher.dbconf':
89 '/tmp/cassandra.titan',
90 'net.onrc.onos.datagrid.HazelcastDatagrid.datagridConfig':
91 onosDir + '/conf/hazelcast.xml',
92 'net.floodlightcontroller.core.FloodlightProvider.workerthreads': 16,
93 'net.floodlightcontroller.forwarding.Forwarding.idletimeout': 5,
94 'net.floodlightcontroller.forwarding.Forwarding.hardtimeout': 0
95 }
96
97 proctag = 'mn-onos-id'
Bob Lantzc7c05402013-12-16 21:22:12 -080098
Bob Lantz7a4d6102013-12-17 00:34:55 -080099 # For maven debugging
100 # mvn = 'mvn -o -e -X'
Bob Lantzc7c05402013-12-16 21:22:12 -0800101
Bob Lantz7ead0532013-12-17 20:41:20 -0800102 def __init__( self, name, n=1, reactive=True, runAsRoot=False, **params):
Bob Lantzc7c05402013-12-16 21:22:12 -0800103 """n: number of ONOS instances to run (1)
Bob Lantz7ead0532013-12-17 20:41:20 -0800104 reactive: run in reactive mode (True)
105 runAsRoot: run ONOS as root (False)"""
Bob Lantzc7c05402013-12-16 21:22:12 -0800106 self.check()
Bob Lantzc7c05402013-12-16 21:22:12 -0800107 self.count = n
Bob Lantz7ead0532013-12-17 20:41:20 -0800108 self.reactive = reactive
109 self.runAsRoot = runAsRoot
Bob Lantzc7c05402013-12-16 21:22:12 -0800110 self.ids = range( 0, self.count )
111 Controller.__init__( self, name, **params )
112 # We don't need to run as root, and it can interfere
113 # with starting Zookeeper manually
Bob Lantz7ead0532013-12-17 20:41:20 -0800114 self.user = None
115 if not self.runAsRoot:
116 try:
117 self.user = quietRun( 'who am i' ).split()[ 0 ]
118 self.sendCmd( 'su', self.user )
119 self.waiting = False
120 except:
121 warn( '__init__: failed to drop privileges\n' )
Bob Lantzc7c05402013-12-16 21:22:12 -0800122 # Need to run commands from ONOS dir
123 self.cmd( 'cd', self.onosDir )
124 self.cmd( 'export PATH=$PATH:%s' % self.onosDir )
Bob Lantz7a4d6102013-12-17 00:34:55 -0800125 if hasattr( self, 'mvn' ):
126 self.cmd( 'export MVN="%s"' % self.mvn )
Bob Lantzc7c05402013-12-16 21:22:12 -0800127
128 def check( self ):
Bob Lantz7ead0532013-12-17 20:41:20 -0800129 "Check for ONOS prerequisites"
Bob Lantzc7c05402013-12-16 21:22:12 -0800130 if not quietRun( 'which java' ):
131 raise Exception( 'java not found -'
132 ' make sure it is installed and in $PATH' )
133 if not quietRun( 'which mvn' ):
134 raise Exception( 'Maven (mvn) not found -'
135 ' make sure it is installed and in $PATH' )
136
Bob Lantz7ead0532013-12-17 20:41:20 -0800137
138 def waitNetstat( self, pid ):
139 """Wait for pid to show up in netstat
140 We assume that once a process is listening on some
141 port, it is ready to go!"""
142 while True:
143 output = self.cmd( 'sudo netstat -natp | grep %s/' % pid )
144 if output:
145 return output
146 info( '.' )
Bob Lantza0930822013-12-17 21:00:41 -0800147 time.sleep( 1 )
Bob Lantz7ead0532013-12-17 20:41:20 -0800148
149 def waitStart( self, procname, pattern ):
150 "Wait for at least one of procname to show up in netstat"
151 info( '* Waiting for %s startup' % procname )
152 result = self.cmd( 'pgrep -f %s' % pattern ).split()[ 0 ]
153 pid = int( result )
154 output = self.waitNetstat( pid )
155 info( '\n* %s process %d is listening\n' % ( procname, pid ) )
156 info( output )
157
Bob Lantzc7c05402013-12-16 21:22:12 -0800158 def startCassandra( self ):
159 "Start Cassandra"
160 self.cmd( 'start-cassandra.sh start' )
Bob Lantz7ead0532013-12-17 20:41:20 -0800161 self.waitStart( 'Cassandra', 'apache-cassandra' )
Bob Lantzc7c05402013-12-16 21:22:12 -0800162 status = self.cmd( 'start-cassandra.sh status' )
Bob Lantz7ead0532013-12-17 20:41:20 -0800163 if 'running' not in status:
Bob Lantzc7c05402013-12-16 21:22:12 -0800164 raise Exception( 'Cassandra startup failed: ' + status )
165
166 def stopCassandra( self ):
167 "Stop Cassandra"
168 self.cmd( 'start-cassandra.sh stop' )
169
170 def startZookeeper( self, initcfg=True ):
171 "Start Zookeeper"
172 # Reinitialize configuration file
173 if initcfg:
174 cfg = self.zookeeperDir + '/conf/zoo.cfg'
175 template = self.zookeeperDir + '/conf/zoo_sample.cfg'
176 copyfile( template, cfg )
177 self.cmd( 'start-zk.sh restart' )
Bob Lantz7ead0532013-12-17 20:41:20 -0800178 self.waitStart( 'Zookeeper', 'zookeeper' )
Bob Lantzc7c05402013-12-16 21:22:12 -0800179 status = self.cmd( 'start-zk.sh status' )
180 if 'Error' in status:
181 raise Exception( 'Zookeeper startup failed: ' + status )
182
183 def stopZookeeper( self ):
184 "Stop Zookeeper"
185 self.cmd( 'start-zk.sh stop' )
186
Bob Lantz7ead0532013-12-17 20:41:20 -0800187 def genProperties( self, id, path='/tmp' ):
188 "Generate ONOS properties file"
189 filename = path + '/onos-%s.properties' % id
190 with open( filename, 'w' ) as f:
191 # Write modules list
192 modules = list( self.baseModules )
193 if self.reactive:
194 modules += list( self.reactiveModules )
195 f.write( 'floodlight.modules = %s\n' %
196 ',\\\n'.join( modules ) )
197 # Write other parameters
198 for var, val in self.perNodeConfigBase.iteritems():
199 if type( val ) is int:
200 val += id
201 f.write( '%s = %s\n' % ( var, val ) )
202 for var, val in self.staticConfig.iteritems():
203 f.write( '%s = %s\n' % ( var, val ) )
204 return filename
205
206 def setVars( self, id, propsFile ):
207 """Set and return environment vars
208 id: ONOS instance number
209 propsFile: properties file name"""
Bob Lantzc7c05402013-12-16 21:22:12 -0800210 # ONOS directories and files
211 logdir = self.logDir % id
212 cassdir = self.cassDir % id
213 logback = self.logbackFile % id
214 jmxport = self.jmxbase + id
215 self.cmd( 'mkdir -p', logdir, cassdir )
216 self.cmd( 'export ONOS_LOGDIR="%s"' % logdir )
217 self.cmd( 'export ZOO_LOG_DIR="%s"' % logdir )
218 self.cmd( 'export CASS_DIR="%s"' % cassdir )
219 self.cmd( 'export ONOS_LOGBACK="%s"' % logback )
220 self.cmd( 'export JMX_PORT=%s' % jmxport )
Bob Lantz7ead0532013-12-17 20:41:20 -0800221 self.cmd( 'export JVM_OPTS="-D%s=%s"' % (
222 self.proctag, id ) )
223 self.cmd( 'export ONOS_PROPS="%s"' % propsFile )
Bob Lantzc7c05402013-12-16 21:22:12 -0800224
225 def startONOS( self, id ):
226 """Start ONOS
Bob Lantz7ead0532013-12-17 20:41:20 -0800227 id: new instance number"""
Bob Lantza0930822013-12-17 21:00:41 -0800228 start = time.time()
Bob Lantz7ead0532013-12-17 20:41:20 -0800229 self.stopONOS( id )
230 propsFile = self.genProperties( id )
231 self.setVars( id, propsFile )
Bob Lantzc7c05402013-12-16 21:22:12 -0800232 self.cmdPrint( 'start-onos.sh startnokill' )
Bob Lantz7ead0532013-12-17 20:41:20 -0800233 # start-onos.sh waits for ONOS startup
Bob Lantza0930822013-12-17 21:00:41 -0800234 elapsed = time.time() - start
Bob Lantz7ead0532013-12-17 20:41:20 -0800235 info( '* ONOS %s started in %.2f seconds\n' % ( id, elapsed ) )
Bob Lantzc7c05402013-12-16 21:22:12 -0800236
237 def stopONOS( self, id ):
238 """Shut down ONOS
239 id: identifier for instance"""
240 pid = self.cmd( "jps -v | grep %s=%s | awk '{print $1}'" %
241 ( self.proctag, id ) ).strip()
242 if pid:
243 self.cmdPrint( 'kill', pid )
244
245 def start( self, *args ):
246 "Start ONOS instances"
247 info( '* Starting Cassandra\n' )
248 self.startCassandra()
249 info( '* Starting Zookeeper\n' )
250 self.startZookeeper()
251 for id in self.ids:
252 info( '* Starting ONOS %s\n' % id )
253 self.startONOS( id )
254
255 def stop( self, *args ):
256 "Stop ONOS instances"
257 for id in self.ids:
258 info( '* Stopping ONOS %s\n' % id )
259 self.stopONOS( id )
Bob Lantz7ead0532013-12-17 20:41:20 -0800260 info( '* Stopping Zookeeper\n' )
Bob Lantzc7c05402013-12-16 21:22:12 -0800261 self.stopZookeeper()
262 info( '* Stopping Cassandra\n' )
263 self.stopCassandra()
264
265 def clist( self ):
266 "Return list of controller specifiers (proto:ip:port)"
267 return [ 'tcp:127.0.0.1:%s' % ( self.ofbase + id )
268 for id in range( 0, self.count ) ]
269
270
271class OVSSwitchONOS( OVSSwitch ):
272 "OVS switch which connects to multiple controllers"
273 def start( self, controllers ):
274 OVSSwitch.start( self, controllers )
275 assert len( controllers ) == 1
276 c0 = controllers[ 0 ]
277 assert type( c0 ) == ONOS
278 clist = ','.join( c0.clist() )
279 self.cmd( 'ovs-vsctl set-controller', self, clist)
280 # Reconnect quickly to controllers (1s vs. 15s max_backoff)
281 for uuid in self.controllerUUIDs():
282 if uuid.count( '-' ) != 4:
283 # Doesn't look like a UUID
284 continue
285 uuid = uuid.strip()
286 self.cmd( 'ovs-vsctl set Controller', uuid,
287 'max_backoff=1000' )
288
289
Bob Lantz7ead0532013-12-17 20:41:20 -0800290def waitConnected( switches ):
291 "Wait until all switches connect to controllers"
Bob Lantza0930822013-12-17 21:00:41 -0800292 start = time.time()
Bob Lantz7ead0532013-12-17 20:41:20 -0800293 info( '* Waiting for switches to connect...\n' )
294 for s in switches:
295 info( s )
296 while not s.connected():
297 info( '.' )
Bob Lantza0930822013-12-17 21:00:41 -0800298 time.sleep( 1 )
Bob Lantz7ead0532013-12-17 20:41:20 -0800299 info( ' ' )
Bob Lantza0930822013-12-17 21:00:41 -0800300 elapsed = time.time() - start
Bob Lantz7ead0532013-12-17 20:41:20 -0800301 info( '\n* Connected in %.2f seconds\n' % elapsed )
302
303
Bob Lantzc7c05402013-12-16 21:22:12 -0800304controllers = { 'onos': ONOS }
305switches = { 'ovso': OVSSwitchONOS }
306
307
308if __name__ == '__main__':
Bob Lantz7ead0532013-12-17 20:41:20 -0800309 # Simple test for ONOS() controller class
Bob Lantzc7c05402013-12-16 21:22:12 -0800310 setLogLevel( 'info' )
Bob Lantz7ead0532013-12-17 20:41:20 -0800311 size = 2 if len( argv ) != 2 else int( argv[ 1 ] )
312 net = Mininet( topo=LinearTopo( size ),
Bob Lantzc7c05402013-12-16 21:22:12 -0800313 controller=partial( ONOS, n=2 ),
314 switch=OVSSwitchONOS )
315 net.start()
Bob Lantz7ead0532013-12-17 20:41:20 -0800316 waitConnected( net.switches )
Bob Lantzc7c05402013-12-16 21:22:12 -0800317 CLI( net )
318 net.stop()