Statistics
| Branch: | Tag: | Revision:

mininet / mininet / net.py @ c702840a

History | View | Annotate | Download (35.6 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
        started = {}
485
        for swclass, switches in groupby(
486
            sorted( self.switches, key=type ), type ):
487
            switches = tuple( switches )
488
            if hasattr( swclass, 'batchStartup' ):
489
                success = swclass.batchStartup( switches )
490
                started.update( { s: s for s in success } )
491
        info( '\n' )
492
        if self.waitConn:
493
            self.waitConnected()
494

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

    
530
    def run( self, test, *args, **kwargs ):
531
        "Perform a complete start/test/stop cycle."
532
        self.start()
533
        info( '*** Running test\n' )
534
        result = test( *args, **kwargs )
535
        self.stop()
536
        return result
537

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

    
562
    # XXX These test methods should be moved out of this class.
563
    # Probably we should create a tests.py for them
564

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

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

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

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

    
688
    def pingAll( self, timeout=None ):
689
        """Ping between all hosts.
690
           returns: ploss packet loss percentage"""
691
        return self.ping( timeout=timeout )
692

    
693
    def pingPair( self ):
694
        """Ping between first two hosts, useful for testing.
695
           returns: ploss packet loss percentage"""
696
        hosts = [ self.hosts[ 0 ], self.hosts[ 1 ] ]
697
        return self.ping( hosts=hosts )
698

    
699
    def pingAllFull( self ):
700
        """Ping between all hosts.
701
           returns: ploss packet loss percentage"""
702
        return self.pingFull()
703

    
704
    def pingPairFull( self ):
705
        """Ping between first two hosts, useful for testing.
706
           returns: ploss packet loss percentage"""
707
        hosts = [ self.hosts[ 0 ], self.hosts[ 1 ] ]
708
        return self.pingFull( hosts=hosts )
709

    
710
    @staticmethod
711
    def _parseIperf( iperfOutput ):
712
        """Parse iperf output and return bandwidth.
713
           iperfOutput: string
714
           returns: result string"""
715
        r = r'([\d\.]+ \w+/sec)'
716
        m = re.findall( r, iperfOutput )
717
        if m:
718
            return m[-1]
719
        else:
720
            # was: raise Exception(...)
721
            error( 'could not parse iperf output: ' + iperfOutput )
722
            return ''
723

    
724
    # XXX This should be cleaned up
725

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

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

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

    
850
    def interact( self ):
851
        "Start network and run our simple CLI."
852
        self.start()
853
        result = CLI( self )
854
        self.stop()
855
        return result
856

    
857
    inited = False
858

    
859
    @classmethod
860
    def init( cls ):
861
        "Initialize Mininet"
862
        if cls.inited:
863
            return
864
        ensureRoot()
865
        fixLimits()
866
        cls.inited = True
867

    
868

    
869
class MininetWithControlNet( Mininet ):
870

    
871
    """Control network support:
872

873
       Create an explicit control network. Currently this is only
874
       used/usable with the user datapath.
875

876
       Notes:
877

878
       1. If the controller and switches are in the same (e.g. root)
879
          namespace, they can just use the loopback connection.
880

881
       2. If we can get unix domain sockets to work, we can use them
882
          instead of an explicit control network.
883

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

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

890
       5. Basically nobody ever used this code, so it has been moved
891
          into its own class.
892

893
       6. Ultimately we may wish to extend this to allow us to create a
894
          control network which every node's control interface is
895
          attached to."""
896

    
897
    def configureControlNetwork( self ):
898
        "Configure control network."
899
        self.configureRoutedControlNetwork()
900

    
901
    # We still need to figure out the right way to pass
902
    # in the control network location.
903

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