Debian Codegraph @

bin/mn

raw
1 #!/usr/bin/env python
2
3 """
4 Mininet runner
5 author: Brandon Heller ([email protected])
6
7 To see options:
8 sudo mn -h
9
10 Example to pull custom params (topo, switch, etc.) from a file:
11 sudo mn --custom ~/mininet/custom/custom_example.py
12 """
13
14 import os
15 import sys
16 import time
17
18 from functools import partial
19 from optparse import OptionParser # pylint: disable=deprecated-module
20 from sys import exit # pylint: disable=redefined-builtin
21
22 # Fix setuptools' evil madness, and open up (more?) security holes
23 if 'PYTHONPATH' in os.environ:
24 sys.path = os.environ[ 'PYTHONPATH' ].split( ':' ) + sys.path
25
26 # pylint: disable=wrong-import-position
27
28 from mininet.clean import cleanup
29 import mininet.cli
30 from mininet.log import lg, LEVELS, info, debug, warn, error, output
31 from mininet.net import Mininet, MininetWithControlNet, VERSION
32 from mininet.node import ( Host, CPULimitedHost, Controller, OVSController,
33 Ryu, NOX, RemoteController, findController,
34 DefaultController, NullController,
35 UserSwitch, OVSSwitch, OVSBridge,
36 IVSSwitch )
37 from mininet.nodelib import LinuxBridge
38 from mininet.link import Link, TCLink, TCULink, OVSLink
39 from mininet.topo import ( SingleSwitchTopo, LinearTopo,
40 SingleSwitchReversedTopo, MinimalTopo )
41 from mininet.topolib import TreeTopo, TorusTopo
42 from mininet.util import customClass, specialClass, splitArgs, buildTopo
43
44 # Experimental! cluster edition prototype
45 from mininet.examples.cluster import ( MininetCluster, RemoteHost,
46 RemoteOVSSwitch, RemoteLink,
47 SwitchBinPlacer, RandomPlacer,
48 ClusterCleanup )
49 from mininet.examples.clustercli import ClusterCLI
50
51
52 PLACEMENT = { 'block': SwitchBinPlacer, 'random': RandomPlacer }
53
54 # built in topologies, created only when run
55 TOPODEF = 'minimal'
56 TOPOS = { 'minimal': MinimalTopo,
57 'linear': LinearTopo,
58 'reversed': SingleSwitchReversedTopo,
59 'single': SingleSwitchTopo,
60 'tree': TreeTopo,
61 'torus': TorusTopo }
62
63 SWITCHDEF = 'default'
64 SWITCHES = { 'user': UserSwitch,
65 'ovs': OVSSwitch,
66 'ovsbr' : OVSBridge,
67 # Keep ovsk for compatibility with 2.0
68 'ovsk': OVSSwitch,
69 'ivs': IVSSwitch,
70 'lxbr': LinuxBridge,
71 'default': OVSSwitch }
72
73 HOSTDEF = 'proc'
74 HOSTS = { 'proc': Host,
75 'rt': specialClass( CPULimitedHost, defaults=dict( sched='rt' ) ),
76 'cfs': specialClass( CPULimitedHost, defaults=dict( sched='cfs' ) ) }
77
78 CONTROLLERDEF = 'default'
79 CONTROLLERS = { 'ref': Controller,
80 'ovsc': OVSController,
81 'nox': NOX,
82 'remote': RemoteController,
83 'ryu': Ryu,
84 'default': DefaultController, # Note: overridden below
85 'none': NullController }
86
87 LINKDEF = 'default'
88 LINKS = { 'default': Link, # Note: overridden below
89 'tc': TCLink,
90 'tcu': TCULink,
91 'ovs': OVSLink }
92
93 # TESTS dict can contain functions and/or Mininet() method names
94 # XXX: it would be nice if we could specify a default test, but
95 # this may be tricky
96 TESTS = { name: True
97 for name in ( 'pingall', 'pingpair', 'iperf', 'iperfudp' ) }
98
99 CLI = None # Set below if needed
100
101 # Locally defined tests
102 def allTest( net ):
103 "Run ping and iperf tests"
104 net.start()
105 net.ping()
106 net.iperf()
107
108 def nullTest( _net ):
109 "Null 'test' (does nothing)"
110 pass
111
112
113 TESTS.update( all=allTest, none=nullTest, build=nullTest )
114
115 # Map to alternate spellings of Mininet() methods
116 ALTSPELLING = { 'pingall': 'pingAll', 'pingpair': 'pingPair',
117 'iperfudp': 'iperfUdp' }
118
119 def runTests( mn, options ):
120 """Run tests
121 mn: Mininet object
122 option: list of test optinos """
123 # Split option into test name and parameters
124 for option in options:
125 # Multiple tests may be separated by '+' for now
126 for test in option.split( '+' ):
127 test, args, kwargs = splitArgs( test )
128 test = ALTSPELLING.get( test.lower(), test )
129 testfn = TESTS.get( test, test )
130 if callable( testfn ):
131 testfn( mn, *args, **kwargs )
132 elif hasattr( mn, test ):
133 getattr( mn, test )( *args, **kwargs )
134 else:
135 raise Exception( 'Test %s is unknown - please specify one of '
136 '%s ' % ( test, TESTS.keys() ) )
137
138
139 def addDictOption( opts, choicesDict, default, name, **kwargs ):
140 """Convenience function to add choices dicts to OptionParser.
141 opts: OptionParser instance
142 choicesDict: dictionary of valid choices, must include default
143 default: default choice key
144 name: long option name
145 kwargs: additional arguments to add_option"""
146 helpStr = ( '|'.join( sorted( choicesDict.keys() ) ) +
147 '[,param=value...]' )
148 helpList = [ '%s=%s' % ( k, v.__name__ )
149 for k, v in choicesDict.items() ]
150 helpStr += ' ' + ( ' '.join( helpList ) )
151 params = dict( type='string', default=default, help=helpStr )
152 params.update( **kwargs )
153 opts.add_option( '--' + name, **params )
154
155 def version( *_args ):
156 "Print Mininet version and exit"
157 output( "%s\n" % VERSION )
158 exit()
159
160
161 class MininetRunner( object ):
162 "Build, setup, and run Mininet."
163
164 def __init__( self ):
165 "Init."
166 self.options = None
167 self.args = None # May be used someday for more CLI scripts
168 self.validate = None
169
170 self.parseArgs()
171 self.setup()
172 self.begin()
173
174 def custom( self, _option, _opt_str, value, _parser ):
175 """Parse custom file and add params.
176 option: option e.g. --custom
177 opt_str: option string e.g. --custom
178 value: the value the follows the option
179 parser: option parser instance"""
180 files = []
181 if os.path.isfile( value ):
182 # Accept any single file (including those with commas)
183 files.append( value )
184 else:
185 # Accept a comma-separated list of filenames
186 files += value.split(',')
187
188 for fileName in files:
189 customs = {}
190 if os.path.isfile( fileName ):
191 # pylint: disable=exec-used
192 exec( compile( open( fileName ).read(), fileName, 'exec' ),
193 customs, customs )
194 for name, val in customs.items():
195 self.setCustom( name, val )
196 else:
197 raise Exception( 'could not find custom file: %s' % fileName )
198
199 def setCustom( self, name, value ):
200 "Set custom parameters for MininetRunner."
201 if name in ( 'topos', 'switches', 'hosts', 'controllers', 'links'
202 'testnames', 'tests' ):
203 # Update dictionaries
204 param = name.upper()
205 globals()[ param ].update( value )
206 elif name == 'validate':
207 # Add custom validate function
208 self.validate = value
209 else:
210 # Add or modify global variable or class
211 globals()[ name ] = value
212
213 def setNat( self, _option, opt_str, value, parser ):
214 "Set NAT option(s)"
215 assert self # satisfy pylint
216 parser.values.nat = True
217 # first arg, first char != '-'
218 if parser.rargs and parser.rargs[ 0 ][ 0 ] != '-':
219 value = parser.rargs.pop( 0 )
220 _, args, kwargs = splitArgs( opt_str + ',' + value )
221 parser.values.nat_args = args
222 parser.values.nat_kwargs = kwargs
223 else:
224 parser.values.nat_args = []
225 parser.values.nat_kwargs = {}
226
227 def parseArgs( self ):
228 """Parse command-line args and return options object.
229 returns: opts parse options dict"""
230
231 desc = ( "The %prog utility creates Mininet network from the\n"
232 "command line. It can create parametrized topologies,\n"
233 "invoke the Mininet CLI, and run tests." )
234
235 usage = ( '%prog [options]\n'
236 '(type %prog -h for details)' )
237
238 opts = OptionParser( description=desc, usage=usage )
239 addDictOption( opts, SWITCHES, SWITCHDEF, 'switch' )
240 addDictOption( opts, HOSTS, HOSTDEF, 'host' )
241 addDictOption( opts, CONTROLLERS, [], 'controller', action='append' )
242 addDictOption( opts, LINKS, LINKDEF, 'link' )
243 addDictOption( opts, TOPOS, TOPODEF, 'topo' )
244
245 opts.add_option( '--clean', '-c', action='store_true',
246 default=False, help='clean and exit' )
247 opts.add_option( '--custom', action='callback',
248 callback=self.custom,
249 type='string',
250 help='read custom classes or params from .py file(s)'
251 )
252 opts.add_option( '--test', default=[], action='append',
253 dest='test', help='|'.join( TESTS.keys() ) )
254 opts.add_option( '--xterms', '-x', action='store_true',
255 default=False, help='spawn xterms for each node' )
256 opts.add_option( '--ipbase', '-i', type='string', default='10.0.0.0/8',
257 help='base IP address for hosts' )
258 opts.add_option( '--mac', action='store_true',
259 default=False, help='automatically set host MACs' )
260 opts.add_option( '--arp', action='store_true',
261 default=False, help='set all-pairs ARP entries' )
262 opts.add_option( '--verbosity', '-v', type='choice',
263 choices=list( LEVELS.keys() ), default = 'info',
264 help = '|'.join( LEVELS.keys() ) )
265 opts.add_option( '--innamespace', action='store_true',
266 default=False, help='sw and ctrl in namespace?' )
267 opts.add_option( '--listenport', type='int', default=6654,
268 help='base port for passive switch listening' )
269 opts.add_option( '--nolistenport', action='store_true',
270 default=False, help="don't use passive listening " +
271 "port")
272 opts.add_option( '--pre', type='string', default=None,
273 help='CLI script to run before tests' )
274 opts.add_option( '--post', type='string', default=None,
275 help='CLI script to run after tests' )
276 opts.add_option( '--pin', action='store_true',
277 default=False, help="pin hosts to CPU cores "
278 "(requires --host cfs or --host rt)" )
279 opts.add_option( '--nat', action='callback', callback=self.setNat,
280 help="[option=val...] adds a NAT to the topology that"
281 " connects Mininet hosts to the physical network."
282 " Warning: This may route any traffic on the machine"
283 " that uses Mininet's"
284 " IP subnet into the Mininet network."
285 " If you need to change"
286 " Mininet's IP subnet, see the --ipbase option." )
287 opts.add_option( '--version', action='callback', callback=version,
288 help='prints the version and exits' )
289 opts.add_option( '--wait', '-w', action='store_true',
290 default=False, help='wait for switches to connect' )
291 opts.add_option( '--twait', '-t', action='store', type='int',
292 dest='wait',
293 help='timed wait (s) for switches to connect' )
294 opts.add_option( '--cluster', type='string', default=None,
295 metavar='server1,server2...',
296 help=( 'run on multiple servers (experimental!)' ) )
297 opts.add_option( '--placement', type='choice',
298 choices=list( PLACEMENT.keys() ), default='block',
299 metavar='block|random',
300 help=( 'node placement for --cluster '
301 '(experimental!) ' ) )
302
303 self.options, self.args = opts.parse_args()
304
305 # We don't accept extra arguments after the options
306 if self.args:
307 opts.print_help()
308 exit()
309
310 def setup( self ):
311 "Setup and validate environment."
312
313 # set logging verbosity
314 if LEVELS[self.options.verbosity] > LEVELS['output']:
315 warn( '*** WARNING: selected verbosity level (%s) will hide CLI '
316 'output!\n'
317 'Please restart Mininet with -v [debug, info, output].\n'
318 % self.options.verbosity )
319 lg.setLogLevel( self.options.verbosity )
320
321 # Maybe we'll reorganize this someday...
322 # pylint: disable=too-many-branches,too-many-statements,global-statement
323
324 def begin( self ):
325 "Create and run mininet."
326
327 global CLI
328
329 opts = self.options
330
331 if opts.cluster:
332 servers = opts.cluster.split( ',' )
333 for server in servers:
334 ClusterCleanup.add( server )
335
336 if opts.clean:
337 cleanup()
338 exit()
339
340 start = time.time()
341
342 if not opts.controller:
343 # Update default based on available controllers
344 CONTROLLERS[ 'default' ] = findController()
345 opts.controller = [ 'default' ]
346 if not CONTROLLERS[ 'default' ]:
347 opts.controller = [ 'none' ]
348 if opts.switch == 'default':
349 info( '*** No default OpenFlow controller found '
350 'for default switch!\n' )
351 info( '*** Falling back to OVS Bridge\n' )
352 opts.switch = 'ovsbr'
353 elif opts.switch not in ( 'ovsbr', 'lxbr' ):
354 raise Exception( "Could not find a default controller "
355 "for switch %s" %
356 opts.switch )
357
358 topo = buildTopo( TOPOS, opts.topo )
359 switch = customClass( SWITCHES, opts.switch )
360 host = customClass( HOSTS, opts.host )
361 controller = [ customClass( CONTROLLERS, c )
362 for c in opts.controller ]
363
364 if opts.switch == 'user' and opts.link == 'default':
365 debug( '*** Using TCULink with UserSwitch\n' )
366 # Use link configured correctly for UserSwitch
367 opts.link = 'tcu'
368
369 link = customClass( LINKS, opts.link )
370
371 if self.validate:
372 self.validate( opts )
373
374 if opts.nolistenport:
375 opts.listenport = None
376
377 # Handle innamespace, cluster options
378 if opts.innamespace and opts.cluster:
379 error( "Please specify --innamespace OR --cluster\n" )
380 exit()
381 Net = MininetWithControlNet if opts.innamespace else Mininet
382 if opts.cluster:
383 warn( '*** WARNING: Experimental cluster mode!\n'
384 '*** Using RemoteHost, RemoteOVSSwitch, RemoteLink\n' )
385 host, switch, link = RemoteHost, RemoteOVSSwitch, RemoteLink
386 Net = partial( MininetCluster, servers=servers,
387 placement=PLACEMENT[ opts.placement ] )
388 mininet.cli.CLI = ClusterCLI
389
390 # Wait for controllers to connect unless we're running null test
391 if ( opts.test and opts.test != [ 'none' ] and
392 isinstance( opts.wait, bool ) ):
393 opts.wait = True
394
395 mn = Net( topo=topo,
396 switch=switch, host=host, controller=controller, link=link,
397 ipBase=opts.ipbase, inNamespace=opts.innamespace,
398 xterms=opts.xterms, autoSetMacs=opts.mac,
399 autoStaticArp=opts.arp, autoPinCpus=opts.pin,
400 waitConnected=opts.wait,
401 listenPort=opts.listenport )
402
403 if opts.ensure_value( 'nat', False ):
404 with open( '/etc/resolv.conf' ) as f:
405 if 'nameserver 127.' in f.read():
406 warn( '*** Warning: loopback address in /etc/resolv.conf '
407 'may break host DNS over NAT\n')
408 mn.addNAT( *opts.nat_args, **opts.nat_kwargs ).configDefault()
409
410 # --custom files can set CLI or change mininet.cli.CLI
411 CLI = mininet.cli.CLI if CLI is None else CLI
412
413 if opts.pre:
414 CLI( mn, script=opts.pre )
415
416 mn.start()
417
418 if opts.test:
419 runTests( mn, opts.test )
420 else:
421 CLI( mn )
422
423 if opts.post:
424 CLI( mn, script=opts.post )
425
426 mn.stop()
427
428 elapsed = float( time.time() - start )
429 info( 'completed in %0.3f seconds\n' % elapsed )
430
431
432 if __name__ == "__main__":
433 try:
434 MininetRunner()
435 except KeyboardInterrupt:
436 info( "\n\nKeyboard Interrupt. Shutting down and cleaning up...\n\n")
437 cleanup()
438 except Exception: # pylint: disable=broad-except
439 # Print exception
440 type_, val_, trace_ = sys.exc_info()
441 errorMsg = ( "-"*80 + "\n" +
442 "Caught exception. Cleaning up...\n\n" +
443 "%s: %s\n" % ( type_.__name__, val_ ) +
444 "-"*80 + "\n" )
445 error( errorMsg )
446 # Print stack trace to debug log
447 import traceback
448 stackTrace = traceback.format_exc()
449 debug( stackTrace + "\n" )
450 cleanup()