Statistics
| Branch: | Tag: | Revision:

mininet / mininet / util.py @ a4e93368

History | View | Annotate | Download (20.6 KB)

1
"Utility functions for Mininet."
2

    
3
from mininet.log import output, info, error, warn, debug
4

    
5
from time import sleep
6
from resource import getrlimit, setrlimit, RLIMIT_NPROC, RLIMIT_NOFILE
7
from select import poll, POLLIN, POLLHUP
8
from subprocess import call, check_call, Popen, PIPE, STDOUT
9
import re
10
from fcntl import fcntl, F_GETFL, F_SETFL
11
from os import O_NONBLOCK
12
import os
13
from functools import partial
14

    
15
# Command execution support
16

    
17
def run( cmd ):
18
    """Simple interface to subprocess.call()
19
       cmd: list of command params"""
20
    return call( cmd.split( ' ' ) )
21

    
22
def checkRun( cmd ):
23
    """Simple interface to subprocess.check_call()
24
       cmd: list of command params"""
25
    return check_call( cmd.split( ' ' ) )
26

    
27
# pylint doesn't understand explicit type checking
28
# pylint: disable=maybe-no-member
29

    
30
def oldQuietRun( *cmd ):
31
    """Run a command, routing stderr to stdout, and return the output.
32
       cmd: list of command params"""
33
    if len( cmd ) == 1:
34
        cmd = cmd[ 0 ]
35
        if isinstance( cmd, str ):
36
            cmd = cmd.split( ' ' )
37
    popen = Popen( cmd, stdout=PIPE, stderr=STDOUT )
38
    # We can't use Popen.communicate() because it uses
39
    # select(), which can't handle
40
    # high file descriptor numbers! poll() can, however.
41
    out = ''
42
    readable = poll()
43
    readable.register( popen.stdout )
44
    while True:
45
        while readable.poll():
46
            data = popen.stdout.read( 1024 )
47
            if len( data ) == 0:
48
                break
49
            out += data
50
        popen.poll()
51
        if popen.returncode is not None:
52
            break
53
    return out
54

    
55

    
56
# This is a bit complicated, but it enables us to
57
# monitor command output as it is happening
58

    
59
def errRun( *cmd, **kwargs ):
60
    """Run a command and return stdout, stderr and return code
61
       cmd: string or list of command and args
62
       stderr: STDOUT to merge stderr with stdout
63
       shell: run command using shell
64
       echo: monitor output to console"""
65
    # By default we separate stderr, don't run in a shell, and don't echo
66
    stderr = kwargs.get( 'stderr', PIPE )
67
    shell = kwargs.get( 'shell', False )
68
    echo = kwargs.get( 'echo', False )
69
    if echo:
70
        # cmd goes to stderr, output goes to stdout
71
        info( cmd, '\n' )
72
    if len( cmd ) == 1:
73
        cmd = cmd[ 0 ]
74
    # Allow passing in a list or a string
75
    if isinstance( cmd, str ) and not shell:
76
        cmd = cmd.split( ' ' )
77
        cmd = [ str( arg ) for arg in cmd ]
78
    elif isinstance( cmd, list ) and shell:
79
        cmd = " ".join( arg for arg in cmd )
80
    debug( '*** errRun:', cmd, '\n' )
81
    popen = Popen( cmd, stdout=PIPE, stderr=stderr, shell=shell )
82
    # We use poll() because select() doesn't work with large fd numbers,
83
    # and thus communicate() doesn't work either
84
    out, err = '', ''
85
    poller = poll()
86
    poller.register( popen.stdout, POLLIN )
87
    fdtofile = { popen.stdout.fileno(): popen.stdout }
88
    outDone, errDone = False, True
89
    if popen.stderr:
90
        fdtofile[ popen.stderr.fileno() ] = popen.stderr
91
        poller.register( popen.stderr, POLLIN )
92
        errDone = False
93
    while not outDone or not errDone:
94
        readable = poller.poll()
95
        for fd, event in readable:
96
            f = fdtofile[ fd ]
97
            if event & POLLIN:
98
                data = f.read( 1024 )
99
                if echo:
100
                    output( data )
101
                if f == popen.stdout:
102
                    out += data
103
                    if data == '':
104
                        outDone = True
105
                elif f == popen.stderr:
106
                    err += data
107
                    if data == '':
108
                        errDone = True
109
            else:  # POLLHUP or something unexpected
110
                if f == popen.stdout:
111
                    outDone = True
112
                elif f == popen.stderr:
113
                    errDone = True
114
                poller.unregister( fd )
115

    
116
    returncode = popen.wait()
117
    debug( out, err, returncode )
118
    return out, err, returncode
119

    
120
def errFail( *cmd, **kwargs ):
121
    "Run a command using errRun and raise exception on nonzero exit"
122
    out, err, ret = errRun( *cmd, **kwargs )
123
    if ret:
124
        raise Exception( "errFail: %s failed with return code %s: %s"
125
                         % ( cmd, ret, err ) )
126
    return out, err, ret
127

    
128
def quietRun( cmd, **kwargs ):
129
    "Run a command and return merged stdout and stderr"
130
    return errRun( cmd, stderr=STDOUT, **kwargs )[ 0 ]
131

    
132
# pylint: enable=maybe-no-member
133

    
134
def isShellBuiltin( cmd ):
135
    "Return True if cmd is a bash builtin."
136
    if isShellBuiltin.builtIns is None:
137
        isShellBuiltin.builtIns = quietRun( 'bash -c enable' )
138
    space = cmd.find( ' ' )
139
    if space > 0:
140
        cmd = cmd[ :space]
141
    return cmd in isShellBuiltin.builtIns
142

    
143
isShellBuiltin.builtIns = None
144

    
145
# Interface management
146
#
147
# Interfaces are managed as strings which are simply the
148
# interface names, of the form 'nodeN-ethM'.
149
#
150
# To connect nodes, we create a pair of veth interfaces, and then place them
151
# in the pair of nodes that we want to communicate. We then update the node's
152
# list of interfaces and connectivity map.
153
#
154
# For the kernel datapath, switch interfaces
155
# live in the root namespace and thus do not have to be
156
# explicitly moved.
157

    
158
def makeIntfPair( intf1, intf2, addr1=None, addr2=None, node1=None, node2=None,
159
                  deleteIntfs=True, runCmd=None ):
160
    """Make a veth pair connnecting new interfaces intf1 and intf2
161
       intf1: name for interface 1
162
       intf2: name for interface 2
163
       addr1: MAC address for interface 1 (optional)
164
       addr2: MAC address for interface 2 (optional)
165
       node1: home node for interface 1 (optional)
166
       node2: home node for interface 2 (optional)
167
       deleteIntfs: delete intfs before creating them
168
       runCmd: function to run shell commands (quietRun)
169
       returns: ip link add result"""
170
    if not runCmd:
171
        runCmd = quietRun if not node1 else node1.cmd
172
        runCmd2 = quietRun if not node2 else node2.cmd
173
    if deleteIntfs:
174
        # Delete any old interfaces with the same names
175
        runCmd( 'ip link del ' + intf1 )
176
        runCmd2( 'ip link del ' + intf2 )
177
    # Create new pair
178
    netns = 1 if not node2 else node2.pid
179
    if addr1 is None and addr2 is None:
180
        cmdOutput = runCmd( 'ip link add name %s '
181
                            'type veth peer name %s '
182
                            'netns %s' % ( intf1, intf2, netns ) )
183
    else:
184
        cmdOutput = runCmd( 'ip link add name %s '
185
                            'address %s '
186
                            'type veth peer name %s '
187
                            'address %s '
188
                            'netns %s' %
189
                            (  intf1, addr1, intf2, addr2, netns ) )
190
    if cmdOutput == '':
191
        return True
192
    else:
193
        raise Exception( "Error creating interface pair (%s,%s): %s " %
194
                         ( intf1, intf2, cmdOutput ) )
195
        return False
196

    
197
def retry( retries, delaySecs, fn, *args, **keywords ):
198
    """Try something several times before giving up.
199
       n: number of times to retry
200
       delaySecs: wait this long between tries
201
       fn: function to call
202
       args: args to apply to function call"""
203
    tries = 0
204
    while not fn( *args, **keywords ) and tries < retries:
205
        sleep( delaySecs )
206
        tries += 1
207
    if tries >= retries:
208
        error( "*** gave up after %i retries\n" % tries )
209
        exit( 1 )
210

    
211
def moveIntfNoRetry( intf, dstNode, printError=False ):
212
    """Move interface to node, without retrying.
213
       intf: string, interface
214
        dstNode: destination Node
215
        printError: if true, print error"""
216
    intf = str( intf )
217
    cmd = 'ip link set %s netns %s' % ( intf, dstNode.pid )
218
    cmdOutput = quietRun( cmd )
219
    # If ip link set does not produce any output, then we can assume
220
    # that the link has been moved successfully.
221
    if cmdOutput:
222
        if printError:
223
            error( '*** Error: moveIntf: ' + intf +
224
                   ' not successfully moved to ' + dstNode.name + ':\n',
225
                   cmdOutput )
226
        return False
227
    return True
228

    
229
def moveIntf( intf, dstNode, printError=True,
230
              retries=3, delaySecs=0.001 ):
231
    """Move interface to node, retrying on failure.
232
       intf: string, interface
233
       dstNode: destination Node
234
       printError: if true, print error"""
235
    retry( retries, delaySecs, moveIntfNoRetry, intf, dstNode,
236
           printError=printError )
237

    
238
# Support for dumping network
239

    
240
def dumpNodeConnections( nodes ):
241
    "Dump connections to/from nodes."
242

    
243
    def dumpConnections( node ):
244
        "Helper function: dump connections to node"
245
        for intf in node.intfList():
246
            output( ' %s:' % intf )
247
            if intf.link:
248
                intfs = [ intf.link.intf1, intf.link.intf2 ]
249
                intfs.remove( intf )
250
                output( intfs[ 0 ] )
251
            else:
252
                output( ' ' )
253

    
254
    for node in nodes:
255
        output( node.name )
256
        dumpConnections( node )
257
        output( '\n' )
258

    
259
def dumpNetConnections( net ):
260
    "Dump connections in network"
261
    nodes = net.controllers + net.switches + net.hosts
262
    dumpNodeConnections( nodes )
263

    
264
def dumpPorts( switches ):
265
    "dump interface to openflow port mappings for each switch"
266
    for switch in switches:
267
        output( '%s ' % switch.name )
268
        for intf in switch.intfList():
269
            port = switch.ports[ intf ]
270
            output( '%s:%d ' % ( intf, port ) )
271
        output( '\n' )
272

    
273
# IP and Mac address formatting and parsing
274

    
275
def _colonHex( val, bytecount ):
276
    """Generate colon-hex string.
277
       val: input as unsigned int
278
       bytecount: number of bytes to convert
279
       returns: chStr colon-hex string"""
280
    pieces = []
281
    for i in range( bytecount - 1, -1, -1 ):
282
        piece = ( ( 0xff << ( i * 8 ) ) & val ) >> ( i * 8 )
283
        pieces.append( '%02x' % piece )
284
    chStr = ':'.join( pieces )
285
    return chStr
286

    
287
def macColonHex( mac ):
288
    """Generate MAC colon-hex string from unsigned int.
289
       mac: MAC address as unsigned int
290
       returns: macStr MAC colon-hex string"""
291
    return _colonHex( mac, 6 )
292

    
293
def ipStr( ip ):
294
    """Generate IP address string from an unsigned int.
295
       ip: unsigned int of form w << 24 | x << 16 | y << 8 | z
296
       returns: ip address string w.x.y.z"""
297
    w = ( ip >> 24 ) & 0xff
298
    x = ( ip >> 16 ) & 0xff
299
    y = ( ip >> 8 ) & 0xff
300
    z = ip & 0xff
301
    return "%i.%i.%i.%i" % ( w, x, y, z )
302

    
303
def ipNum( w, x, y, z ):
304
    """Generate unsigned int from components of IP address
305
       returns: w << 24 | x << 16 | y << 8 | z"""
306
    return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
307

    
308
def ipAdd( i, prefixLen=8, ipBaseNum=0x0a000000 ):
309
    """Return IP address string from ints
310
       i: int to be added to ipbase
311
       prefixLen: optional IP prefix length
312
       ipBaseNum: option base IP address as int
313
       returns IP address as string"""
314
    imax = 0xffffffff >> prefixLen
315
    assert i <= imax, 'Not enough IP addresses in the subnet'
316
    mask = 0xffffffff ^ imax
317
    ipnum = ( ipBaseNum & mask ) + i
318
    return ipStr( ipnum )
319

    
320
def ipParse( ip ):
321
    "Parse an IP address and return an unsigned int."
322
    args = [ int( arg ) for arg in ip.split( '.' ) ]
323
    while len(args) < 4:
324
        args.append( 0 )
325
    return ipNum( *args )
326

    
327
def netParse( ipstr ):
328
    """Parse an IP network specification, returning
329
       address and prefix len as unsigned ints"""
330
    prefixLen = 0
331
    if '/' in ipstr:
332
        ip, pf = ipstr.split( '/' )
333
        prefixLen = int( pf )
334
    #if no prefix is specified, set the prefix to 24
335
    else:
336
        ip = ipstr
337
        prefixLen = 24
338
    return ipParse( ip ), prefixLen
339

    
340
def checkInt( s ):
341
    "Check if input string is an int"
342
    try:
343
        int( s )
344
        return True
345
    except ValueError:
346
        return False
347

    
348
def checkFloat( s ):
349
    "Check if input string is a float"
350
    try:
351
        float( s )
352
        return True
353
    except ValueError:
354
        return False
355

    
356
def makeNumeric( s ):
357
    "Convert string to int or float if numeric."
358
    if checkInt( s ):
359
        return int( s )
360
    elif checkFloat( s ):
361
        return float( s )
362
    else:
363
        return s
364

    
365
# Popen support
366

    
367
def pmonitor(popens, timeoutms=500, readline=True,
368
             readmax=1024 ):
369
    """Monitor dict of hosts to popen objects
370
       a line at a time
371
       timeoutms: timeout for poll()
372
       readline: return single line of output
373
       yields: host, line/output (if any)
374
       terminates: when all EOFs received"""
375
    poller = poll()
376
    fdToHost = {}
377
    for host, popen in popens.iteritems():
378
        fd = popen.stdout.fileno()
379
        fdToHost[ fd ] = host
380
        poller.register( fd, POLLIN )
381
        if not readline:
382
            # Use non-blocking reads
383
            flags = fcntl( fd, F_GETFL )
384
            fcntl( fd, F_SETFL, flags | O_NONBLOCK )
385
    while popens:
386
        fds = poller.poll( timeoutms )
387
        if fds:
388
            for fd, event in fds:
389
                host = fdToHost[ fd ]
390
                popen = popens[ host ]
391
                if event & POLLIN:
392
                    if readline:
393
                        # Attempt to read a line of output
394
                        # This blocks until we receive a newline!
395
                        line = popen.stdout.readline()
396
                    else:
397
                        line = popen.stdout.read( readmax )
398
                    yield host, line
399
                # Check for EOF
400
                elif event & POLLHUP:
401
                    poller.unregister( fd )
402
                    del popens[ host ]
403
        else:
404
            yield None, ''
405

    
406
# Other stuff we use
407
def sysctlTestAndSet( name, limit ):
408
    "Helper function to set sysctl limits"
409
    #convert non-directory names into directory names
410
    if '/' not in name:
411
        name = '/proc/sys/' + name.replace( '.', '/' )
412
    #read limit
413
    with open( name, 'r' ) as readFile:
414
        oldLimit = readFile.readline()
415
        if isinstance( limit, int ):
416
            #compare integer limits before overriding
417
            if int( oldLimit ) < limit:
418
                with open( name, 'w' ) as writeFile:
419
                    writeFile.write( "%d" % limit )
420
        else:
421
            #overwrite non-integer limits
422
            with open( name, 'w' ) as writeFile:
423
                writeFile.write( limit )
424

    
425
def rlimitTestAndSet( name, limit ):
426
    "Helper function to set rlimits"
427
    soft, hard = getrlimit( name )
428
    if soft < limit:
429
        hardLimit = hard if limit < hard else limit
430
        setrlimit( name, ( limit, hardLimit ) )
431

    
432
def fixLimits():
433
    "Fix ridiculously small resource limits."
434
    debug( "*** Setting resource limits\n" )
435
    try:
436
        rlimitTestAndSet( RLIMIT_NPROC, 8192 )
437
        rlimitTestAndSet( RLIMIT_NOFILE, 16384 )
438
        #Increase open file limit
439
        sysctlTestAndSet( 'fs.file-max', 10000 )
440
        #Increase network buffer space
441
        sysctlTestAndSet( 'net.core.wmem_max', 16777216 )
442
        sysctlTestAndSet( 'net.core.rmem_max', 16777216 )
443
        sysctlTestAndSet( 'net.ipv4.tcp_rmem', '10240 87380 16777216' )
444
        sysctlTestAndSet( 'net.ipv4.tcp_wmem', '10240 87380 16777216' )
445
        sysctlTestAndSet( 'net.core.netdev_max_backlog', 5000 )
446
        #Increase arp cache size
447
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh1', 4096 )
448
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh2', 8192 )
449
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh3', 16384 )
450
        #Increase routing table size
451
        sysctlTestAndSet( 'net.ipv4.route.max_size', 32768 )
452
        #Increase number of PTYs for nodes
453
        sysctlTestAndSet( 'kernel.pty.max', 20000 )
454
    # pylint: disable=broad-except
455
    except Exception:
456
        warn( "*** Error setting resource limits. "
457
              "Mininet's performance may be affected.\n" )
458
    # pylint: enable=broad-except
459

    
460

    
461
def mountCgroups():
462
    "Make sure cgroups file system is mounted"
463
    mounts = quietRun( 'cat /proc/mounts' )
464
    cgdir = '/sys/fs/cgroup'
465
    csdir = cgdir + '/cpuset'
466
    if ('cgroup %s' % cgdir not in mounts and
467
            'cgroups %s' % cgdir not in mounts):
468
        raise Exception( "cgroups not mounted on " + cgdir )
469
    if 'cpuset %s' % csdir not in mounts:
470
        errRun( 'mkdir -p ' + csdir )
471
        errRun( 'mount -t cgroup -ocpuset cpuset ' + csdir )
472

    
473
def natural( text ):
474
    "To sort sanely/alphabetically: sorted( l, key=natural )"
475
    def num( s ):
476
        "Convert text segment to int if necessary"
477
        return int( s ) if s.isdigit() else s
478
    return [  num( s ) for s in re.split( r'(\d+)', str( text ) ) ]
479

    
480
def naturalSeq( t ):
481
    "Natural sort key function for sequences"
482
    return [ natural( x ) for x in t ]
483

    
484
def numCores():
485
    "Returns number of CPU cores based on /proc/cpuinfo"
486
    if hasattr( numCores, 'ncores' ):
487
        return numCores.ncores
488
    try:
489
        numCores.ncores = int( quietRun('grep -c processor /proc/cpuinfo') )
490
    except ValueError:
491
        return 0
492
    return numCores.ncores
493

    
494
def irange(start, end):
495
    """Inclusive range from start to end (vs. Python insanity.)
496
       irange(1,5) -> 1, 2, 3, 4, 5"""
497
    return range( start, end + 1 )
498

    
499
def custom( cls, **params ):
500
    "Returns customized constructor for class cls."
501
    # Note: we may wish to see if we can use functools.partial() here
502
    # and in customConstructor
503
    def customized( *args, **kwargs):
504
        "Customized constructor"
505
        kwargs = kwargs.copy()
506
        kwargs.update( params )
507
        return cls( *args, **kwargs )
508
    customized.__name__ = 'custom(%s,%s)' % ( cls, params )
509
    return customized
510

    
511
def splitArgs( argstr ):
512
    """Split argument string into usable python arguments
513
       argstr: argument string with format fn,arg2,kw1=arg3...
514
       returns: fn, args, kwargs"""
515
    split = argstr.split( ',' )
516
    fn = split[ 0 ]
517
    params = split[ 1: ]
518
    # Convert int and float args; removes the need for function
519
    # to be flexible with input arg formats.
520
    args = [ makeNumeric( s ) for s in params if '=' not in s ]
521
    kwargs = {}
522
    for s in [ p for p in params if '=' in p ]:
523
        key, val = s.split( '=', 1 )
524
        kwargs[ key ] = makeNumeric( val )
525
    return fn, args, kwargs
526

    
527
def customConstructor( constructors, argStr ):
528
    """Return custom constructor based on argStr
529
    The args and key/val pairs in argsStr will be automatically applied
530
    when the generated constructor is later used.
531
    """
532
    cname, newargs, kwargs = splitArgs( argStr )
533
    constructor = constructors.get( cname, None )
534

    
535
    if not constructor:
536
        raise Exception( "error: %s is unknown - please specify one of %s" %
537
                         ( cname, constructors.keys() ) )
538

    
539
    if not newargs and not kwargs:
540
        return constructor
541

    
542
    if not isinstance( constructor, type ):
543
        raise Exception( "error: invalid arguments %s" % argStr )
544

    
545
    # Return a customized subclass
546
    cls = constructor
547
    class CustomClass( cls ):
548
        "Customized subclass, useful for Node, Link, and other classes"
549
        def __init__( self, name, *args, **params ):
550
            params = params.copy()
551
            params.update( kwargs )
552
            if not newargs:
553
                return cls.__init__( self, name, *args, **params )
554
            if args:
555
                warn( 'warning: %s replacing %s with %s\n' %
556
                      ( constructor, args, newargs ) )
557
                return cls.__init__( self, name, *newargs, **params )
558

    
559
    CustomClass.__name__ = '%s%s' % ( cls.__name__, kwargs )
560
    return CustomClass
561

    
562
def buildTopo( topos, topoStr ):
563
    """Create topology from string with format (object, arg1, arg2,...).
564
    input topos is a dict of topo names to constructors, possibly w/args.
565
    """
566
    topo, args, kwargs = splitArgs( topoStr )
567
    if topo not in topos:
568
        raise Exception( 'Invalid topo name %s' % topo )
569
    return topos[ topo ]( *args, **kwargs )
570

    
571
def ensureRoot():
572
    """Ensure that we are running as root.
573

574
    Probably we should only sudo when needed as per Big Switch's patch.
575
    """
576
    if os.getuid() != 0:
577
        print "*** Mininet must run as root."
578
        exit( 1 )
579
    return
580

    
581
def waitListening( client=None, server='127.0.0.1', port=80, timeout=None ):
582
    """Wait until server is listening on port.
583
       returns True if server is listening"""
584
    runCmd = ( client.cmd if client else
585
               partial( quietRun, shell=True ) )
586
    if not runCmd( 'which telnet' ):
587
        raise Exception('Could not find telnet' )
588
    # pylint: disable=maybe-no-member
589
    serverIP = server if isinstance( server, basestring ) else server.IP()
590
    cmd = ( 'sh -c "echo A | telnet -e A %s %s"' %
591
            ( serverIP, port ) )
592
    time = 0
593
    while 'Connected' not in runCmd( cmd ):
594
        if timeout:
595
            print time
596
            if time >= timeout:
597
                error( 'could not connect to %s on port %d\n'
598
                       % ( server, port ) )
599
                return False
600
        output('waiting for', server,
601
               'to listen on port', port, '\n')
602
        sleep( .5 )
603
        time += .5
604
    return True