Statistics
| Branch: | Tag: | Revision:

mininet / mininet / util.py @ 30ebb852

History | View | Annotate | Download (20.2 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
        error( "Error creating interface pair: %s " % cmdOutput )
194
        return False
195

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

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

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

    
237
# Support for dumping network
238

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

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

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

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

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

    
272
# IP and Mac address formatting and parsing
273

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

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

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

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

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

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

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

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

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

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

    
364
# Popen support
365

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

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

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

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

    
459

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

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

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

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

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

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

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

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

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

    
538
    def customized( name, *args, **params ):
539
        "Customized constructor, useful for Node, Link, and other classes"
540
        params = params.copy()
541
        params.update( kwargs )
542
        if not newargs:
543
            return constructor( name, *args, **params )
544
        if args:
545
            warn( 'warning: %s replacing %s with %s\n' % (
546
                  constructor, args, newargs ) )
547
        return constructor( name, *newargs, **params )
548

    
549
    customized.__name__ = 'customConstructor(%s)' % argStr
550
    return customized
551

    
552
def buildTopo( topos, topoStr ):
553
    """Create topology from string with format (object, arg1, arg2,...).
554
    input topos is a dict of topo names to constructors, possibly w/args.
555
    """
556
    topo, args, kwargs = splitArgs( topoStr )
557
    if topo not in topos:
558
        raise Exception( 'Invalid topo name %s' % topo )
559
    return topos[ topo ]( *args, **kwargs )
560

    
561
def ensureRoot():
562
    """Ensure that we are running as root.
563

564
    Probably we should only sudo when needed as per Big Switch's patch.
565
    """
566
    if os.getuid() != 0:
567
        print "*** Mininet must run as root."
568
        exit( 1 )
569
    return
570

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