Statistics
| Branch: | Tag: | Revision:

mininet / mininet / net.py @ f7b29333

History | View | Annotate | Download (35.3 KB)

1
"""
2

3
    Mininet: A simple networking testbed for OpenFlow/SDN!
4

5
author: Bob Lantz (rlantz@cs.stanford.edu)
6
author: Brandon Heller (brandonh@stanford.edu)
7

8
Mininet creates scalable OpenFlow test networks by using
9
process-based virtualization and network namespaces.
10

11
Simulated hosts are created as processes in separate network
12
namespaces. This allows a complete OpenFlow network to be simulated on
13
top of a single Linux kernel.
14

15
Each host has:
16

17
A virtual console (pipes to a shell)
18
A virtual interfaces (half of a veth pair)
19
A parent shell (and possibly some child processes) in a namespace
20

21
Hosts have a network interface which is configured via ifconfig/ip
22
link/etc.
23

24
This version supports both the kernel and user space datapaths
25
from the OpenFlow reference implementation (openflowswitch.org)
26
as well as OpenVSwitch (openvswitch.org.)
27

28
In kernel datapath mode, the controller and switches are simply
29
processes in the root namespace.
30

31
Kernel OpenFlow datapaths are instantiated using dpctl(8), and are
32
attached to the one side of a veth pair; the other side resides in the
33
host namespace. In this mode, switch processes can simply connect to the
34
controller via the loopback interface.
35

36
In user datapath mode, the controller and switches can be full-service
37
nodes that live in their own network namespaces and have management
38
interfaces and IP addresses on a control network (e.g. 192.168.123.1,
39
currently routed although it could be bridged.)
40

41
In addition to a management interface, user mode switches also have
42
several switch interfaces, halves of veth pairs whose other halves
43
reside in the host nodes that the switches are connected to.
44

45
Consistent, straightforward naming is important in order to easily
46
identify hosts, switches and controllers, both from the CLI and
47
from program code. Interfaces are named to make it easy to identify
48
which interfaces belong to which node.
49

50
The basic naming scheme is as follows:
51

52
    Host nodes are named h1-hN
53
    Switch nodes are named s1-sN
54
    Controller nodes are named c0-cN
55
    Interfaces are named {nodename}-eth0 .. {nodename}-ethN
56

57
Note: If the network topology is created using mininet.topo, then
58
node numbers are unique among hosts and switches (e.g. we have
59
h1..hN and SN..SN+M) and also correspond to their default IP addresses
60
of 10.x.y.z/8 where x.y.z is the base-256 representation of N for
61
hN. This mapping allows easy determination of a node's IP
62
address from its name, e.g. h1 -> 10.0.0.1, h257 -> 10.0.1.1.
63

64
Note also that 10.0.0.1 can often be written as 10.1 for short, e.g.
65
"ping 10.1" is equivalent to "ping 10.0.0.1".
66

67
Currently we wrap the entire network in a 'mininet' object, which
68
constructs a simulated network based on a network topology created
69
using a topology object (e.g. LinearTopo) from mininet.topo or
70
mininet.topolib, and a Controller which the switches will connect
71
to. Several configuration options are provided for functions such as
72
automatically setting MAC addresses, populating the ARP table, or
73
even running a set of terminals to allow direct interaction with nodes.
74

75
After the network is created, it can be started using start(), and a
76
variety of useful tasks maybe performed, including basic connectivity
77
and bandwidth tests and running the mininet CLI.
78

79
Once the network is up and running, test code can easily get access
80
to host and switch objects which can then be used for arbitrary
81
experiments, typically involving running a series of commands on the
82
hosts.
83

84
After all desired tests or activities have been completed, the stop()
85
method may be called to shut down the network.
86

87
"""
88

    
89
import os
90
import re
91
import select
92
import signal
93
import random
94

    
95
from time import sleep
96
from itertools import chain, groupby
97
from math import ceil
98

    
99
from mininet.cli import CLI
100
from mininet.log import info, error, debug, output, warn
101
from mininet.node import ( Node, Host, OVSKernelSwitch, DefaultController,
102
                           Controller )
103
from mininet.nodelib import NAT
104
from mininet.link import Link, Intf
105
from mininet.util import quietRun, fixLimits, numCores, ensureRoot
106
from mininet.util import macColonHex, ipStr, ipParse, netParse, ipAdd
107
from mininet.term import cleanUpScreens, makeTerms
108

    
109
# Mininet version: should be consistent with README and LICENSE
110
VERSION = "2.2.0+"
111

    
112
class Mininet( object ):
113
    "Network emulation with hosts spawned in network namespaces."
114

    
115
    def __init__( self, topo=None, switch=OVSKernelSwitch, host=Host,
116
                  controller=DefaultController, link=Link, intf=Intf,
117
                  build=True, xterms=False, cleanup=False, ipBase='10.0.0.0/8',
118
                  inNamespace=False,
119
                  autoSetMacs=False, autoStaticArp=False, autoPinCpus=False,
120
                  listenPort=None, waitConnected=False ):
121
        """Create Mininet object.
122
           topo: Topo (topology) object or None
123
           switch: default Switch class
124
           host: default Host class/constructor
125
           controller: default Controller class/constructor
126
           link: default Link class/constructor
127
           intf: default Intf class/constructor
128
           ipBase: base IP address for hosts,
129
           build: build now from topo?
130
           xterms: if build now, spawn xterms?
131
           cleanup: if build now, cleanup before creating?
132
           inNamespace: spawn switches and controller in net namespaces?
133
           autoSetMacs: set MAC addrs automatically like IP addresses?
134
           autoStaticArp: set all-pairs static MAC addrs?
135
           autoPinCpus: pin hosts to (real) cores (requires CPULimitedHost)?
136
           listenPort: base listening port to open; will be incremented for
137
               each additional switch in the net if inNamespace=False"""
138
        self.topo = topo
139
        self.switch = switch
140
        self.host = host
141
        self.controller = controller
142
        self.link = link
143
        self.intf = intf
144
        self.ipBase = ipBase
145
        self.ipBaseNum, self.prefixLen = netParse( self.ipBase )
146
        self.nextIP = 1  # start for address allocation
147
        self.inNamespace = inNamespace
148
        self.xterms = xterms
149
        self.cleanup = cleanup
150
        self.autoSetMacs = autoSetMacs
151
        self.autoStaticArp = autoStaticArp
152
        self.autoPinCpus = autoPinCpus
153
        self.numCores = numCores()
154
        self.nextCore = 0  # next core for pinning hosts to CPUs
155
        self.listenPort = listenPort
156
        self.waitConn = waitConnected
157

    
158
        self.hosts = []
159
        self.switches = []
160
        self.controllers = []
161
        self.links = []
162

    
163
        self.nameToNode = {}  # name to Node (Host/Switch) objects
164

    
165
        self.terms = []  # list of spawned xterm processes
166

    
167
        Mininet.init()  # Initialize Mininet if necessary
168

    
169
        self.built = False
170
        if topo and build:
171
            self.build()
172

    
173
    def waitConnected( self, timeout=None, delay=.5 ):
174
        """wait for each switch to connect to a controller,
175
           up to 5 seconds
176
           timeout: time to wait, or None to wait indefinitely
177
           delay: seconds to sleep per iteration
178
           returns: True if all switches are connected"""
179
        info( '*** Waiting for switches to connect\n' )
180
        time = 0
181
        remaining = list( self.switches )
182
        while True:
183
            for switch in tuple( remaining ):
184
                if switch.connected():
185
                    info( '%s ' % switch )
186
                    remaining.remove( switch )
187
            if not remaining:
188
                info( '\n' )
189
                return True
190
            if time > timeout and timeout is not None:
191
                break
192
            sleep( delay )
193
            time += delay
194
        warn( 'Timed out after %d seconds\n' % time )
195
        for switch in remaining:
196
            if not switch.connected():
197
                warn( 'Warning: %s is not connected to a controller\n'
198
                      % switch.name )
199
            else:
200
                remaining.remove( switch )
201
        return not remaining
202

    
203
    def addHost( self, name, cls=None, **params ):
204
        """Add host.
205
           name: name of host to add
206
           cls: custom host class/constructor (optional)
207
           params: parameters for host
208
           returns: added host"""
209
        # Default IP and MAC addresses
210
        defaults = { 'ip': ipAdd( self.nextIP,
211
                                  ipBaseNum=self.ipBaseNum,
212
                                  prefixLen=self.prefixLen ) +
213
                                  '/%s' % self.prefixLen }
214
        if self.autoSetMacs:
215
            defaults[ 'mac' ] = macColonHex( self.nextIP )
216
        if self.autoPinCpus:
217
            defaults[ 'cores' ] = self.nextCore
218
            self.nextCore = ( self.nextCore + 1 ) % self.numCores
219
        self.nextIP += 1
220
        defaults.update( params )
221
        if not cls:
222
            cls = self.host
223
        h = cls( name, **defaults )
224
        self.hosts.append( h )
225
        self.nameToNode[ name ] = h
226
        return h
227

    
228
    def addSwitch( self, name, cls=None, **params ):
229
        """Add switch.
230
           name: name of switch to add
231
           cls: custom switch class/constructor (optional)
232
           returns: added switch
233
           side effect: increments listenPort ivar ."""
234
        defaults = { 'listenPort': self.listenPort,
235
                     'inNamespace': self.inNamespace }
236
        defaults.update( params )
237
        if not cls:
238
            cls = self.switch
239
        sw = cls( name, **defaults )
240
        if not self.inNamespace and self.listenPort:
241
            self.listenPort += 1
242
        self.switches.append( sw )
243
        self.nameToNode[ name ] = sw
244
        return sw
245

    
246
    def addController( self, name='c0', controller=None, **params ):
247
        """Add controller.
248
           controller: Controller class"""
249
        # Get controller class
250
        if not controller:
251
            controller = self.controller
252
        # Construct new controller if one is not given
253
        if isinstance( name, Controller ):
254
            controller_new = name
255
            # Pylint thinks controller is a str()
256
            # pylint: disable=maybe-no-member
257
            name = controller_new.name
258
            # pylint: enable=maybe-no-member
259
        else:
260
            controller_new = controller( name, **params )
261
        # Add new controller to net
262
        if controller_new:  # allow controller-less setups
263
            self.controllers.append( controller_new )
264
            self.nameToNode[ name ] = controller_new
265
        return controller_new
266

    
267
    def addNAT( self, name='nat0', connect=True, inNamespace=False,
268
                **params):
269
        """Add a NAT to the Mininet network
270
           name: name of NAT node
271
           connect: switch to connect to | True (s1) | None
272
           inNamespace: create in a network namespace
273
           params: other NAT node params, notably:
274
               ip: used as default gateway address"""
275
        nat = self.addHost( name, cls=NAT, inNamespace=inNamespace,
276
                            subnet=self.ipBase, **params )
277
        # find first switch and create link
278
        if connect:
279
            if not isinstance( connect, Node ):
280
                # Use first switch if not specified
281
                connect = self.switches[ 0 ]
282
            # Connect the nat to the switch
283
            self.addLink( nat, self.switches[ 0 ] )
284
            # Set the default route on hosts
285
            natIP = nat.params[ 'ip' ].split('/')[ 0 ]
286
            for host in self.hosts:
287
                if host.inNamespace:
288
                    host.setDefaultRoute( 'via %s' % natIP )
289
        return nat
290

    
291
    # BL: We now have four ways to look up nodes
292
    # This may (should?) be cleaned up in the future.
293
    def getNodeByName( self, *args ):
294
        "Return node(s) with given name(s)"
295
        if len( args ) == 1:
296
            return self.nameToNode[ args[ 0 ] ]
297
        return [ self.nameToNode[ n ] for n in args ]
298

    
299
    def get( self, *args ):
300
        "Convenience alias for getNodeByName"
301
        return self.getNodeByName( *args )
302

    
303
    # Even more convenient syntax for node lookup and iteration
304
    def __getitem__( self, key ):
305
        """net [ name ] operator: Return node(s) with given name(s)"""
306
        return self.nameToNode[ key ]
307

    
308
    def __iter__( self ):
309
        "return iterator over node names"
310
        for node in chain( self.hosts, self.switches, self.controllers ):
311
            yield node.name
312

    
313
    def __len__( self ):
314
        "returns number of nodes in net"
315
        return ( len( self.hosts ) + len( self.switches ) +
316
                 len( self.controllers ) )
317

    
318
    def __contains__( self, item ):
319
        "returns True if net contains named node"
320
        return item in self.nameToNode
321

    
322
    def keys( self ):
323
        "return a list of all node names or net's keys"
324
        return list( self )
325

    
326
    def values( self ):
327
        "return a list of all nodes or net's values"
328
        return [ self[name] for name in self ]
329

    
330
    def items( self ):
331
        "return (key,value) tuple list for every node in net"
332
        return zip( self.keys(), self.values() )
333

    
334
    @staticmethod
335
    def randMac():
336
        "Return a random, non-multicast MAC address"
337
        return macColonHex( random.randint(1, 2**48 - 1) & 0xfeffffffffff |
338
                            0x020000000000 )
339

    
340
    def addLink( self, node1, node2, port1=None, port2=None,
341
                 cls=None, **params ):
342
        """"Add a link from node1 to node2
343
            node1: source node (or name)
344
            node2: dest node (or name)
345
            port1: source port (optional)
346
            port2: dest port (optional)
347
            cls: link class (optional)
348
            params: additional link params (optional)
349
            returns: link object"""
350
        # Accept node objects or names
351
        node1 = node1 if not isinstance( node1, basestring ) else self[ node1 ]
352
        node2 = node2 if not isinstance( node2, basestring ) else self[ node2 ]
353
        options = dict( params )
354
        # Port is optional
355
        if port1 is not None:
356
            options.setdefault( 'port1', port1 )
357
        if port2 is not None:
358
            options.setdefault( 'port2', port2 )
359
        # Set default MAC - this should probably be in Link
360
        options.setdefault( 'addr1', self.randMac() )
361
        options.setdefault( 'addr2', self.randMac() )
362
        cls = self.link if cls is None else cls
363
        link = cls( node1, node2, **options )
364
        self.links.append( link )
365
        return link
366

    
367
    def configHosts( self ):
368
        "Configure a set of hosts."
369
        for host in self.hosts:
370
            info( host.name + ' ' )
371
            intf = host.defaultIntf()
372
            if intf:
373
                host.configDefault()
374
            else:
375
                # Don't configure nonexistent intf
376
                host.configDefault( ip=None, mac=None )
377
            # You're low priority, dude!
378
            # BL: do we want to do this here or not?
379
            # May not make sense if we have CPU lmiting...
380
            # quietRun( 'renice +18 -p ' + repr( host.pid ) )
381
            # This may not be the right place to do this, but
382
            # it needs to be done somewhere.
383
        info( '\n' )
384

    
385
    def buildFromTopo( self, topo=None ):
386
        """Build mininet from a topology object
387
           At the end of this function, everything should be connected
388
           and up."""
389

    
390
        # Possibly we should clean up here and/or validate
391
        # the topo
392
        if self.cleanup:
393
            pass
394

    
395
        info( '*** Creating network\n' )
396

    
397
        if not self.controllers and self.controller:
398
            # Add a default controller
399
            info( '*** Adding controller\n' )
400
            classes = self.controller
401
            if not isinstance( classes, list ):
402
                classes = [ classes ]
403
            for i, cls in enumerate( classes ):
404
                # Allow Controller objects because nobody understands currying
405
                if isinstance( cls, Controller ):
406
                    self.addController( cls )
407
                else:
408
                    self.addController( 'c%d' % i, cls )
409

    
410
        info( '*** Adding hosts:\n' )
411
        for hostName in topo.hosts():
412
            self.addHost( hostName, **topo.nodeInfo( hostName ) )
413
            info( hostName + ' ' )
414

    
415
        info( '\n*** Adding switches:\n' )
416
        for switchName in topo.switches():
417
            self.addSwitch( switchName, **topo.nodeInfo( switchName) )
418
            info( switchName + ' ' )
419

    
420
        info( '\n*** Adding links:\n' )
421
        for srcName, dstName, params in topo.links(
422
                sort=True, withInfo=True ):
423
            self.addLink( **params )
424
            info( '(%s, %s) ' % ( srcName, dstName ) )
425

    
426
        info( '\n' )
427

    
428
    def configureControlNetwork( self ):
429
        "Control net config hook: override in subclass"
430
        raise Exception( 'configureControlNetwork: '
431
                         'should be overriden in subclass', self )
432

    
433
    def build( self ):
434
        "Build mininet."
435
        if self.topo:
436
            self.buildFromTopo( self.topo )
437
        if self.inNamespace:
438
            self.configureControlNetwork()
439
        info( '*** Configuring hosts\n' )
440
        self.configHosts()
441
        if self.xterms:
442
            self.startTerms()
443
        if self.autoStaticArp:
444
            self.staticArp()
445
        self.built = True
446

    
447
    def startTerms( self ):
448
        "Start a terminal for each node."
449
        if 'DISPLAY' not in os.environ:
450
            error( "Error starting terms: Cannot connect to display\n" )
451
            return
452
        info( "*** Running terms on %s\n" % os.environ[ 'DISPLAY' ] )
453
        cleanUpScreens()
454
        self.terms += makeTerms( self.controllers, 'controller' )
455
        self.terms += makeTerms( self.switches, 'switch' )
456
        self.terms += makeTerms( self.hosts, 'host' )
457

    
458
    def stopXterms( self ):
459
        "Kill each xterm."
460
        for term in self.terms:
461
            os.kill( term.pid, signal.SIGKILL )
462
        cleanUpScreens()
463

    
464
    def staticArp( self ):
465
        "Add all-pairs ARP entries to remove the need to handle broadcast."
466
        for src in self.hosts:
467
            for dst in self.hosts:
468
                if src != dst:
469
                    src.setARP( ip=dst.IP(), mac=dst.MAC() )
470

    
471
    def start( self ):
472
        "Start controller and switches."
473
        if not self.built:
474
            self.build()
475
        info( '*** Starting controller\n' )
476
        for controller in self.controllers:
477
            info( controller.name + ' ')
478
            controller.start()
479
        info( '\n' )
480
        info( '*** Starting %s switches\n' % len( self.switches ) )
481
        for switch in self.switches:
482
            info( switch.name + ' ')
483
            switch.start( self.controllers )
484
        info( '\n' )
485
        if self.waitConn:
486
            self.waitConnected()
487

    
488
    def stop( self ):
489
        "Stop the controller(s), switches and hosts"
490
        info( '*** Stopping %i controllers\n' % len( self.controllers ) )
491
        for controller in self.controllers:
492
            info( controller.name + ' ' )
493
            controller.stop()
494
        info( '\n' )
495
        if self.terms:
496
            info( '*** Stopping %i terms\n' % len( self.terms ) )
497
            self.stopXterms()
498
        info( '*** Stopping %i links\n' % len( self.links ) )
499
        for link in self.links:
500
            info( '.' )
501
            link.stop()
502
        info( '\n' )
503
        info( '*** Stopping %i switches\n' % len( self.switches ) )
504
        stopped = {}
505
        for swclass, switches in groupby(
506
                sorted( self.switches, key=type ), type ):
507
            switches = tuple( switches )
508
            if ( hasattr( swclass, 'batchShutdown' ) and
509
                 swclass.batchShutdown( switches ) ):
510
                stopped.update( { s: s for s in switches } )
511
        for switch in self.switches:
512
            info( switch.name + ' ' )
513
            if switch not in stopped:
514
                switch.stop()
515
            switch.terminate()
516
        info( '\n' )
517
        info( '*** Stopping %i hosts\n' % len( self.hosts ) )
518
        for host in self.hosts:
519
            info( host.name + ' ' )
520
            host.terminate()
521
        info( '\n*** Done\n' )
522

    
523
    def run( self, test, *args, **kwargs ):
524
        "Perform a complete start/test/stop cycle."
525
        self.start()
526
        info( '*** Running test\n' )
527
        result = test( *args, **kwargs )
528
        self.stop()
529
        return result
530

    
531
    def monitor( self, hosts=None, timeoutms=-1 ):
532
        """Monitor a set of hosts (or all hosts by default),
533
           and return their output, a line at a time.
534
           hosts: (optional) set of hosts to monitor
535
           timeoutms: (optional) timeout value in ms
536
           returns: iterator which returns host, line"""
537
        if hosts is None:
538
            hosts = self.hosts
539
        poller = select.poll()
540
        h1 = hosts[ 0 ]  # so we can call class method fdToNode
541
        for host in hosts:
542
            poller.register( host.stdout )
543
        while True:
544
            ready = poller.poll( timeoutms )
545
            for fd, event in ready:
546
                host = h1.fdToNode( fd )
547
                if event & select.POLLIN:
548
                    line = host.readline()
549
                    if line is not None:
550
                        yield host, line
551
            # Return if non-blocking
552
            if not ready and timeoutms >= 0:
553
                yield None, None
554

    
555
    # XXX These test methods should be moved out of this class.
556
    # Probably we should create a tests.py for them
557

    
558
    @staticmethod
559
    def _parsePing( pingOutput ):
560
        "Parse ping output and return packets sent, received."
561
        # Check for downed link
562
        if 'connect: Network is unreachable' in pingOutput:
563
            return 1, 0
564
        r = r'(\d+) packets transmitted, (\d+) received'
565
        m = re.search( r, pingOutput )
566
        if m is None:
567
            error( '*** Error: could not parse ping output: %s\n' %
568
                   pingOutput )
569
            return 1, 0
570
        sent, received = int( m.group( 1 ) ), int( m.group( 2 ) )
571
        return sent, received
572

    
573
    def ping( self, hosts=None, timeout=None ):
574
        """Ping between all specified hosts.
575
           hosts: list of hosts
576
           timeout: time to wait for a response, as string
577
           returns: ploss packet loss percentage"""
578
        # should we check if running?
579
        packets = 0
580
        lost = 0
581
        ploss = None
582
        if not hosts:
583
            hosts = self.hosts
584
            output( '*** Ping: testing ping reachability\n' )
585
        for node in hosts:
586
            output( '%s -> ' % node.name )
587
            for dest in hosts:
588
                if node != dest:
589
                    opts = ''
590
                    if timeout:
591
                        opts = '-W %s' % timeout
592
                    if dest.intfs:
593
                        result = node.cmd( 'ping -c1 %s %s' %
594
                                           (opts, dest.IP()) )
595
                        sent, received = self._parsePing( result )
596
                    else:
597
                        sent, received = 0, 0
598
                    packets += sent
599
                    if received > sent:
600
                        error( '*** Error: received too many packets' )
601
                        error( '%s' % result )
602
                        node.cmdPrint( 'route' )
603
                        exit( 1 )
604
                    lost += sent - received
605
                    output( ( '%s ' % dest.name ) if received else 'X ' )
606
            output( '\n' )
607
        if packets > 0:
608
            ploss = 100.0 * lost / packets
609
            received = packets - lost
610
            output( "*** Results: %i%% dropped (%d/%d received)\n" %
611
                    ( ploss, received, packets ) )
612
        else:
613
            ploss = 0
614
            output( "*** Warning: No packets sent\n" )
615
        return ploss
616

    
617
    @staticmethod
618
    def _parsePingFull( pingOutput ):
619
        "Parse ping output and return all data."
620
        errorTuple = (1, 0, 0, 0, 0, 0)
621
        # Check for downed link
622
        r = r'[uU]nreachable'
623
        m = re.search( r, pingOutput )
624
        if m is not None:
625
            return errorTuple
626
        r = r'(\d+) packets transmitted, (\d+) received'
627
        m = re.search( r, pingOutput )
628
        if m is None:
629
            error( '*** Error: could not parse ping output: %s\n' %
630
                   pingOutput )
631
            return errorTuple
632
        sent, received = int( m.group( 1 ) ), int( m.group( 2 ) )
633
        r = r'rtt min/avg/max/mdev = '
634
        r += r'(\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+) ms'
635
        m = re.search( r, pingOutput )
636
        if m is None:
637
            if received == 0:
638
                return errorTuple
639
            error( '*** Error: could not parse ping output: %s\n' %
640
                   pingOutput )
641
            return errorTuple
642
        rttmin = float( m.group( 1 ) )
643
        rttavg = float( m.group( 2 ) )
644
        rttmax = float( m.group( 3 ) )
645
        rttdev = float( m.group( 4 ) )
646
        return sent, received, rttmin, rttavg, rttmax, rttdev
647

    
648
    def pingFull( self, hosts=None, timeout=None ):
649
        """Ping between all specified hosts and return all data.
650
           hosts: list of hosts
651
           timeout: time to wait for a response, as string
652
           returns: all ping data; see function body."""
653
        # should we check if running?
654
        # Each value is a tuple: (src, dsd, [all ping outputs])
655
        all_outputs = []
656
        if not hosts:
657
            hosts = self.hosts
658
            output( '*** Ping: testing ping reachability\n' )
659
        for node in hosts:
660
            output( '%s -> ' % node.name )
661
            for dest in hosts:
662
                if node != dest:
663
                    opts = ''
664
                    if timeout:
665
                        opts = '-W %s' % timeout
666
                    result = node.cmd( 'ping -c1 %s %s' % (opts, dest.IP()) )
667
                    outputs = self._parsePingFull( result )
668
                    sent, received, rttmin, rttavg, rttmax, rttdev = outputs
669
                    all_outputs.append( (node, dest, outputs) )
670
                    output( ( '%s ' % dest.name ) if received else 'X ' )
671
            output( '\n' )
672
        output( "*** Results: \n" )
673
        for outputs in all_outputs:
674
            src, dest, ping_outputs = outputs
675
            sent, received, rttmin, rttavg, rttmax, rttdev = ping_outputs
676
            output( " %s->%s: %s/%s, " % (src, dest, sent, received ) )
677
            output( "rtt min/avg/max/mdev %0.3f/%0.3f/%0.3f/%0.3f ms\n" %
678
                    (rttmin, rttavg, rttmax, rttdev) )
679
        return all_outputs
680

    
681
    def pingAll( self, timeout=None ):
682
        """Ping between all hosts.
683
           returns: ploss packet loss percentage"""
684
        return self.ping( timeout=timeout )
685

    
686
    def pingPair( self ):
687
        """Ping between first two hosts, useful for testing.
688
           returns: ploss packet loss percentage"""
689
        hosts = [ self.hosts[ 0 ], self.hosts[ 1 ] ]
690
        return self.ping( hosts=hosts )
691

    
692
    def pingAllFull( self ):
693
        """Ping between all hosts.
694
           returns: ploss packet loss percentage"""
695
        return self.pingFull()
696

    
697
    def pingPairFull( self ):
698
        """Ping between first two hosts, useful for testing.
699
           returns: ploss packet loss percentage"""
700
        hosts = [ self.hosts[ 0 ], self.hosts[ 1 ] ]
701
        return self.pingFull( hosts=hosts )
702

    
703
    @staticmethod
704
    def _parseIperf( iperfOutput ):
705
        """Parse iperf output and return bandwidth.
706
           iperfOutput: string
707
           returns: result string"""
708
        r = r'([\d\.]+ \w+/sec)'
709
        m = re.findall( r, iperfOutput )
710
        if m:
711
            return m[-1]
712
        else:
713
            # was: raise Exception(...)
714
            error( 'could not parse iperf output: ' + iperfOutput )
715
            return ''
716

    
717
    # XXX This should be cleaned up
718

    
719
    def iperf( self, hosts=None, l4Type='TCP', udpBw='10M', fmt=None,
720
               seconds=5):
721
        """Run iperf between two hosts.
722
           hosts: list of hosts; if None, uses first and last hosts
723
           l4Type: string, one of [ TCP, UDP ]
724
           udpBw: bandwidth target for UDP test
725
           fmt: iperf format argument if any
726
           seconds: iperf time to transmit
727
           returns: two-element array of [ server, client ] speeds
728
           note: send() is buffered, so client rate can be much higher than
729
           the actual transmission rate; on an unloaded system, server
730
           rate should be much closer to the actual receive rate"""
731
        if not quietRun( 'which telnet' ):
732
            error( 'Cannot find telnet in $PATH - required for iperf test' )
733
            return
734
        hosts = hosts or [ self.hosts[ 0 ], self.hosts[ -1 ] ]
735
        assert len( hosts ) == 2
736
        client, server = hosts
737
        output( '*** Iperf: testing ' + l4Type + ' bandwidth between ' )
738
        output( "%s and %s\n" % ( client.name, server.name ) )
739
        server.cmd( 'killall -9 iperf' )
740
        iperfArgs = 'iperf '
741
        bwArgs = ''
742
        if l4Type == 'UDP':
743
            iperfArgs += '-u '
744
            bwArgs = '-b ' + udpBw + ' '
745
        elif l4Type != 'TCP':
746
            raise Exception( 'Unexpected l4 type: %s' % l4Type )
747
        if fmt:
748
            iperfArgs += '-f %s ' % fmt
749
        server.sendCmd( iperfArgs + '-s', printPid=True )
750
        servout = ''
751
        while server.lastPid is None:
752
            servout += server.monitor()
753
        if l4Type == 'TCP':
754
            while 'Connected' not in client.cmd(
755
                    'sh -c "echo A | telnet -e A %s 5001"' % server.IP()):
756
                info( 'Waiting for iperf to start up...' )
757
                sleep(.5)
758
        cliout = client.cmd( iperfArgs + '-t %d -c ' % seconds +
759
                             server.IP() + ' ' + bwArgs )
760
        debug( 'Client output: %s\n' % cliout )
761
        server.sendInt()
762
        servout += server.waitOutput()
763
        debug( 'Server output: %s\n' % servout )
764
        result = [ self._parseIperf( servout ), self._parseIperf( cliout ) ]
765
        if l4Type == 'UDP':
766
            result.insert( 0, udpBw )
767
        output( '*** Results: %s\n' % result )
768
        return result
769

    
770
    def runCpuLimitTest( self, cpu, duration=5 ):
771
        """run CPU limit test with 'while true' processes.
772
        cpu: desired CPU fraction of each host
773
        duration: test duration in seconds (integer)
774
        returns a single list of measured CPU fractions as floats.
775
        """
776
        cores = int( quietRun( 'nproc' ) )
777
        pct = cpu * 100
778
        info( '*** Testing CPU %.0f%% bandwidth limit\n' % pct )
779
        hosts = self.hosts
780
        cores = int( quietRun( 'nproc' ) )
781
        # number of processes to run a while loop on per host
782
        num_procs = int( ceil( cores * cpu ) )
783
        pids = {}
784
        for h in hosts:
785
            pids[ h ] = []
786
            for _core in range( num_procs ):
787
                h.cmd( 'while true; do a=1; done &' )
788
                pids[ h ].append( h.cmd( 'echo $!' ).strip() )
789
        outputs = {}
790
        time = {}
791
        # get the initial cpu time for each host
792
        for host in hosts:
793
            outputs[ host ] = []
794
            with open( '/sys/fs/cgroup/cpuacct/%s/cpuacct.usage' %
795
                       host, 'r' ) as f:
796
                time[ host ] = float( f.read() )
797
        for _ in range( duration ):
798
            sleep( 1 )
799
            for host in hosts:
800
                with open( '/sys/fs/cgroup/cpuacct/%s/cpuacct.usage' %
801
                           host, 'r' ) as f:
802
                    readTime = float( f.read() )
803
                outputs[ host ].append( ( ( readTime - time[ host ] )
804
                                        / 1000000000 ) / cores * 100 )
805
                time[ host ] = readTime
806
        for h, pids in pids.items():
807
            for pid in pids:
808
                h.cmd( 'kill -9 %s' % pid )
809
        cpu_fractions = []
810
        for _host, outputs in outputs.items():
811
            for pct in outputs:
812
                cpu_fractions.append( pct )
813
        output( '*** Results: %s\n' % cpu_fractions )
814
        return cpu_fractions
815

    
816
    # BL: I think this can be rewritten now that we have
817
    # a real link class.
818
    def configLinkStatus( self, src, dst, status ):
819
        """Change status of src <-> dst links.
820
           src: node name
821
           dst: node name
822
           status: string {up, down}"""
823
        if src not in self.nameToNode:
824
            error( 'src not in network: %s\n' % src )
825
        elif dst not in self.nameToNode:
826
            error( 'dst not in network: %s\n' % dst )
827
        else:
828
            if isinstance( src, basestring ):
829
                src = self.nameToNode[ src ]
830
            if isinstance( dst, basestring ):
831
                dst = self.nameToNode[ dst ]
832
            connections = src.connectionsTo( dst )
833
            if len( connections ) == 0:
834
                error( 'src and dst not connected: %s %s\n' % ( src, dst) )
835
            for srcIntf, dstIntf in connections:
836
                result = srcIntf.ifconfig( status )
837
                if result:
838
                    error( 'link src status change failed: %s\n' % result )
839
                result = dstIntf.ifconfig( status )
840
                if result:
841
                    error( 'link dst status change failed: %s\n' % result )
842

    
843
    def interact( self ):
844
        "Start network and run our simple CLI."
845
        self.start()
846
        result = CLI( self )
847
        self.stop()
848
        return result
849

    
850
    inited = False
851

    
852
    @classmethod
853
    def init( cls ):
854
        "Initialize Mininet"
855
        if cls.inited:
856
            return
857
        ensureRoot()
858
        fixLimits()
859
        cls.inited = True
860

    
861

    
862
class MininetWithControlNet( Mininet ):
863

    
864
    """Control network support:
865

866
       Create an explicit control network. Currently this is only
867
       used/usable with the user datapath.
868

869
       Notes:
870

871
       1. If the controller and switches are in the same (e.g. root)
872
          namespace, they can just use the loopback connection.
873

874
       2. If we can get unix domain sockets to work, we can use them
875
          instead of an explicit control network.
876

877
       3. Instead of routing, we could bridge or use 'in-band' control.
878

879
       4. Even if we dispense with this in general, it could still be
880
          useful for people who wish to simulate a separate control
881
          network (since real networks may need one!)
882

883
       5. Basically nobody ever used this code, so it has been moved
884
          into its own class.
885

886
       6. Ultimately we may wish to extend this to allow us to create a
887
          control network which every node's control interface is
888
          attached to."""
889

    
890
    def configureControlNetwork( self ):
891
        "Configure control network."
892
        self.configureRoutedControlNetwork()
893

    
894
    # We still need to figure out the right way to pass
895
    # in the control network location.
896

    
897
    def configureRoutedControlNetwork( self, ip='192.168.123.1',
898
                                       prefixLen=16 ):
899
        """Configure a routed control network on controller and switches.
900
           For use with the user datapath only right now."""
901
        controller = self.controllers[ 0 ]
902
        info( controller.name + ' <->' )
903
        cip = ip
904
        snum = ipParse( ip )
905
        for switch in self.switches:
906
            info( ' ' + switch.name )
907
            link = self.link( switch, controller, port1=0 )
908
            sintf, cintf = link.intf1, link.intf2
909
            switch.controlIntf = sintf
910
            snum += 1
911
            while snum & 0xff in [ 0, 255 ]:
912
                snum += 1
913
            sip = ipStr( snum )
914
            cintf.setIP( cip, prefixLen )
915
            sintf.setIP( sip, prefixLen )
916
            controller.setHostRoute( sip, cintf )
917
            switch.setHostRoute( cip, sintf )
918
        info( '\n' )
919
        info( '*** Testing control network\n' )
920
        while not cintf.isUp():
921
            info( '*** Waiting for', cintf, 'to come up\n' )
922
            sleep( 1 )
923
        for switch in self.switches:
924
            while not sintf.isUp():
925
                info( '*** Waiting for', sintf, 'to come up\n' )
926
                sleep( 1 )
927
            if self.ping( hosts=[ switch, controller ] ) != 0:
928
                error( '*** Error: control network test failed\n' )
929
                exit( 1 )
930
        info( '\n' )