Statistics
| Branch: | Tag: | Revision:

mininet / mininet / util.py @ 891a9e8b

History | View | Annotate | Download (17.7 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

    
14
# Command execution support
15

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

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

    
26
# pylint doesn't understand explicit type checking
27
# pylint: disable-msg=E1103
28

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

    
54

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

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

    
107
def errFail( *cmd, **kwargs ):
108
    "Run a command using errRun and raise exception on nonzero exit"
109
    out, err, ret = errRun( *cmd, **kwargs )
110
    if ret:
111
        raise Exception( "errFail: %s failed with return code %s: %s"
112
                         % ( cmd, ret, err ) )
113
    return out, err, ret
114

    
115
def quietRun( cmd, **kwargs ):
116
    "Run a command and return merged stdout and stderr"
117
    return errRun( cmd, stderr=STDOUT, **kwargs )[ 0 ]
118

    
119
# pylint: enable-msg=E1103
120
# pylint: disable-msg=E1101
121

    
122
def isShellBuiltin( cmd ):
123
    "Return True if cmd is a bash builtin."
124
    if isShellBuiltin.builtIns is None:
125
        isShellBuiltin.builtIns = quietRun( 'bash -c enable' )
126
    space = cmd.find( ' ' )
127
    if space > 0:
128
        cmd = cmd[ :space]
129
    return cmd in isShellBuiltin.builtIns
130

    
131
isShellBuiltin.builtIns = None
132

    
133
# pylint: enable-msg=E1101
134

    
135
# Interface management
136
#
137
# Interfaces are managed as strings which are simply the
138
# interface names, of the form 'nodeN-ethM'.
139
#
140
# To connect nodes, we create a pair of veth interfaces, and then place them
141
# in the pair of nodes that we want to communicate. We then update the node's
142
# list of interfaces and connectivity map.
143
#
144
# For the kernel datapath, switch interfaces
145
# live in the root namespace and thus do not have to be
146
# explicitly moved.
147

    
148
def makeIntfPair( intf1, intf2, addr1=None, addr2=None ):
149
    """Make a veth pair connecting intf1 and intf2.
150
       intf1: string, interface
151
       intf2: string, interface
152
       returns: success boolean"""
153
    # Delete any old interfaces with the same names
154
    quietRun( 'ip link del ' + intf1 )
155
    quietRun( 'ip link del ' + intf2 )
156
    # Create new pair
157
    if addr1 is None and addr2 is None:
158
        cmd = 'ip link add name ' + intf1 + ' type veth peer name ' + intf2
159
    else:
160
        cmd = ( 'ip link add name ' + intf1 + ' address ' + addr1 +
161
                ' type veth peer name ' + intf2 + ' address ' + addr2 )
162
    cmdOutput = quietRun( cmd )
163
    if cmdOutput == '':
164
        return True
165
    else:
166
        error( "Error creating interface pair: %s " % cmdOutput )
167
        return False
168

    
169
def retry( retries, delaySecs, fn, *args, **keywords ):
170
    """Try something several times before giving up.
171
       n: number of times to retry
172
       delaySecs: wait this long between tries
173
       fn: function to call
174
       args: args to apply to function call"""
175
    tries = 0
176
    while not fn( *args, **keywords ) and tries < retries:
177
        sleep( delaySecs )
178
        tries += 1
179
    if tries >= retries:
180
        error( "*** gave up after %i retries\n" % tries )
181
        exit( 1 )
182

    
183
def moveIntfNoRetry( intf, dstNode, srcNode=None, printError=False ):
184
    """Move interface to node, without retrying.
185
       intf: string, interface
186
        dstNode: destination Node
187
        srcNode: source Node or None (default) for root ns
188
        printError: if true, print error"""
189
    intf = str( intf )
190
    cmd = 'ip link set %s netns %s' % ( intf, dstNode.pid )
191
    if srcNode:
192
        cmdOutput = srcNode.cmd( cmd )
193
    else:
194
        cmdOutput = quietRun( cmd )
195
    if cmdOutput:
196
        if printError:
197
            error( '*** Error: moveIntf: ' + intf +
198
                   ' not successfully moved to ' + dstNode.name + '\n' )
199
        return False
200
    return True
201

    
202
def moveIntf( intf, dstNode, srcNode=None, printError=False,
203
             retries=3, delaySecs=0.001 ):
204
    """Move interface to node, retrying on failure.
205
       intf: string, interface
206
       dstNode: destination Node
207
       srcNode: source Node or None (default) for root ns
208
       printError: if true, print error"""
209
    retry( retries, delaySecs, moveIntfNoRetry, intf, dstNode,
210
          srcNode=srcNode, printError=printError )
211

    
212
# Support for dumping network
213

    
214
def dumpNodeConnections( nodes ):
215
    "Dump connections to/from nodes."
216

    
217
    def dumpConnections( node ):
218
        "Helper function: dump connections to node"
219
        for intf in node.intfList():
220
            output( ' %s:' % intf )
221
            if intf.link:
222
                intfs = [ intf.link.intf1, intf.link.intf2 ]
223
                intfs.remove( intf )
224
                output( intfs[ 0 ] )
225
            else:
226
                output( ' ' )
227

    
228
    for node in nodes:
229
        output( node.name )
230
        dumpConnections( node )
231
        output( '\n' )
232

    
233
def dumpNetConnections( net ):
234
    "Dump connections in network"
235
    nodes = net.controllers + net.switches + net.hosts
236
    dumpNodeConnections( nodes )
237

    
238
# IP and Mac address formatting and parsing
239

    
240
def _colonHex( val, bytecount ):
241
    """Generate colon-hex string.
242
       val: input as unsigned int
243
       bytecount: number of bytes to convert
244
       returns: chStr colon-hex string"""
245
    pieces = []
246
    for i in range( bytecount - 1, -1, -1 ):
247
        piece = ( ( 0xff << ( i * 8 ) ) & val ) >> ( i * 8 )
248
        pieces.append( '%02x' % piece )
249
    chStr = ':'.join( pieces )
250
    return chStr
251

    
252
def macColonHex( mac ):
253
    """Generate MAC colon-hex string from unsigned int.
254
       mac: MAC address as unsigned int
255
       returns: macStr MAC colon-hex string"""
256
    return _colonHex( mac, 6 )
257

    
258
def ipStr( ip ):
259
    """Generate IP address string from an unsigned int.
260
       ip: unsigned int of form w << 24 | x << 16 | y << 8 | z
261
       returns: ip address string w.x.y.z"""
262
    w = ( ip >> 24 ) & 0xff
263
    x = ( ip >> 16 ) & 0xff
264
    y = ( ip >> 8 ) & 0xff
265
    z = ip & 0xff
266
    return "%i.%i.%i.%i" % ( w, x, y, z )
267

    
268
def ipNum( w, x, y, z ):
269
    """Generate unsigned int from components of IP address
270
       returns: w << 24 | x << 16 | y << 8 | z"""
271
    return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
272

    
273
def ipAdd( i, prefixLen=8, ipBaseNum=0x0a000000 ):
274
    """Return IP address string from ints
275
       i: int to be added to ipbase
276
       prefixLen: optional IP prefix length
277
       ipBaseNum: option base IP address as int
278
       returns IP address as string"""
279
    imax = 0xffffffff >> prefixLen
280
    assert i <= imax, 'Not enough IP addresses in the subnet'
281
    mask = 0xffffffff ^ imax
282
    ipnum = ( ipBaseNum & mask ) + i
283
    return ipStr( ipnum )
284

    
285
def ipParse( ip ):
286
    "Parse an IP address and return an unsigned int."
287
    args = [ int( arg ) for arg in ip.split( '.' ) ]
288
    while ( len(args) < 4 ):
289
        args.append( 0 )
290
    return ipNum( *args )
291

    
292
def netParse( ipstr ):
293
    """Parse an IP network specification, returning
294
       address and prefix len as unsigned ints"""
295
    prefixLen = 0
296
    if '/' in ipstr:
297
        ip, pf = ipstr.split( '/' )
298
        prefixLen = int( pf )
299
    #if no prefix is specified, set the prefix to 24
300
    else:
301
        ip = ipstr
302
        prefixLen = 24
303
    return ipParse( ip ), prefixLen
304

    
305
def checkInt( s ):
306
    "Check if input string is an int"
307
    try:
308
        int( s )
309
        return True
310
    except ValueError:
311
        return False
312

    
313
def checkFloat( s ):
314
    "Check if input string is a float"
315
    try:
316
        float( s )
317
        return True
318
    except ValueError:
319
        return False
320

    
321
def makeNumeric( s ):
322
    "Convert string to int or float if numeric."
323
    if checkInt( s ):
324
        return int( s )
325
    elif checkFloat( s ):
326
        return float( s )
327
    else:
328
        return s
329

    
330
# Popen support
331

    
332
def pmonitor(popens, timeoutms=500, readline=True,
333
             readmax=1024 ):
334
    """Monitor dict of hosts to popen objects
335
       a line at a time
336
       timeoutms: timeout for poll()
337
       readline: return single line of output
338
       yields: host, line/output (if any)
339
       terminates: when all EOFs received"""
340
    poller = poll()
341
    fdToHost = {}
342
    for host, popen in popens.iteritems():
343
        fd = popen.stdout.fileno()
344
        fdToHost[ fd ] = host
345
        poller.register( fd, POLLIN )
346
        if not readline:
347
            # Use non-blocking reads
348
            flags = fcntl( fd, F_GETFL )
349
            fcntl( fd, F_SETFL, flags | O_NONBLOCK )
350
    while popens:
351
        fds = poller.poll( timeoutms )
352
        if fds:
353
            for fd, event in fds:
354
                host = fdToHost[ fd ]
355
                popen = popens[ host ]
356
                if event & POLLIN:
357
                    if readline:
358
                        # Attempt to read a line of output
359
                        # This blocks until we receive a newline!
360
                        line = popen.stdout.readline()
361
                    else:
362
                        line = popen.stdout.read( readmax )
363
                    yield host, line
364
                # Check for EOF
365
                elif event & POLLHUP:
366
                    poller.unregister( fd )
367
                    del popens[ host ]
368
        else:
369
            yield None, ''
370

    
371
# Other stuff we use
372
def sysctlTestAndSet( name, limit ):
373
    "Helper function to set sysctl limits"
374
    #convert non-directory names into directory names
375
    if '/' not in name:
376
        name = '/proc/sys/' + name.replace( '.', '/' )
377
    #read limit
378
    with open( name, 'r' ) as readFile:
379
        oldLimit = readFile.readline()
380
        if type( limit ) is int:
381
            #compare integer limits before overriding
382
            if int( oldLimit ) < limit:
383
                with open( name, 'w' ) as writeFile:
384
                    writeFile.write( "%d" % limit )
385
        else:
386
            #overwrite non-integer limits
387
            with open( name, 'w' ) as writeFile:
388
                writeFile.write( limit )
389

    
390
def rlimitTestAndSet( name, limit ):
391
    "Helper function to set rlimits"
392
    soft, hard = getrlimit( name )
393
    if soft < limit:
394
        hardLimit = hard if limit < hard else limit
395
        setrlimit( name, ( limit, hardLimit ) )
396

    
397
def fixLimits():
398
    "Fix ridiculously small resource limits."
399
    debug( "*** Setting resource limits\n" )
400
    try:
401
        rlimitTestAndSet( RLIMIT_NPROC, 8192 )
402
        rlimitTestAndSet( RLIMIT_NOFILE, 16384 )
403
        #Increase open file limit
404
        sysctlTestAndSet( 'fs.file-max', 10000 )
405
        #Increase network buffer space
406
        sysctlTestAndSet( 'net.core.wmem_max', 16777216 )
407
        sysctlTestAndSet( 'net.core.rmem_max', 16777216 )
408
        sysctlTestAndSet( 'net.ipv4.tcp_rmem', '10240 87380 16777216' )
409
        sysctlTestAndSet( 'net.ipv4.tcp_wmem', '10240 87380 16777216' )
410
        sysctlTestAndSet( 'net.core.netdev_max_backlog', 5000 )
411
        #Increase arp cache size
412
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh1', 4096 )
413
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh2', 8192 )
414
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh3', 16384 )
415
        #Increase routing table size
416
        sysctlTestAndSet( 'net.ipv4.route.max_size', 32768 )
417
        #Increase number of PTYs for nodes
418
        sysctlTestAndSet( 'kernel.pty.max', 20000 )
419
    except:
420
        warn( "*** Error setting resource limits. "
421
              "Mininet's performance may be affected.\n" )
422

    
423
def mountCgroups():
424
    "Make sure cgroups file system is mounted"
425
    mounts = quietRun( 'cat /proc/mounts' )
426
    cgdir = '/sys/fs/cgroup'
427
    csdir = cgdir + '/cpuset'
428
    if ('cgroup %s' % cgdir not in mounts and
429
            'cgroups %s' % cgdir not in mounts):
430
        raise Exception( "cgroups not mounted on " + cgdir )
431
    if 'cpuset %s' % csdir not in mounts:
432
        errRun( 'mkdir -p ' + csdir )
433
        errRun( 'mount -t cgroup -ocpuset cpuset ' + csdir )
434

    
435
def natural( text ):
436
    "To sort sanely/alphabetically: sorted( l, key=natural )"
437
    def num( s ):
438
        "Convert text segment to int if necessary"
439
        return int( s ) if s.isdigit() else s
440
    return [  num( s ) for s in re.split( r'(\d+)', text ) ]
441

    
442
def naturalSeq( t ):
443
    "Natural sort key function for sequences"
444
    return [ natural( x ) for x in t ]
445

    
446
def numCores():
447
    "Returns number of CPU cores based on /proc/cpuinfo"
448
    if hasattr( numCores, 'ncores' ):
449
        return numCores.ncores
450
    try:
451
        numCores.ncores = int( quietRun('grep -c processor /proc/cpuinfo') )
452
    except ValueError:
453
        return 0
454
    return numCores.ncores
455

    
456
def irange(start, end):
457
    """Inclusive range from start to end (vs. Python insanity.)
458
       irange(1,5) -> 1, 2, 3, 4, 5"""
459
    return range( start, end + 1 )
460

    
461
def custom( cls, **params ):
462
    "Returns customized constructor for class cls."
463
    # Note: we may wish to see if we can use functools.partial() here
464
    # and in customConstructor
465
    def customized( *args, **kwargs):
466
        "Customized constructor"
467
        kwargs = kwargs.copy()
468
        kwargs.update( params )
469
        return cls( *args, **kwargs )
470
    customized.__name__ = 'custom(%s,%s)' % ( cls, params )
471
    return customized
472

    
473
def splitArgs( argstr ):
474
    """Split argument string into usable python arguments
475
       argstr: argument string with format fn,arg2,kw1=arg3...
476
       returns: fn, args, kwargs"""
477
    split = argstr.split( ',' )
478
    fn = split[ 0 ]
479
    params = split[ 1: ]
480
    # Convert int and float args; removes the need for function
481
    # to be flexible with input arg formats.
482
    args = [ makeNumeric( s ) for s in params if '=' not in s ]
483
    kwargs = {}
484
    for s in [ p for p in params if '=' in p ]:
485
        key, val = s.split( '=', 1 )
486
        kwargs[ key ] = makeNumeric( val )
487
    return fn, args, kwargs
488

    
489
def customConstructor( constructors, argStr ):
490
    """Return custom constructor based on argStr
491
    The args and key/val pairs in argsStr will be automatically applied
492
    when the generated constructor is later used.
493
    """
494
    cname, newargs, kwargs = splitArgs( argStr )
495
    constructor = constructors.get( cname, None )
496

    
497
    if not constructor:
498
        raise Exception( "error: %s is unknown - please specify one of %s" %
499
                         ( cname, constructors.keys() ) )
500

    
501
    def customized( name, *args, **params ):
502
        "Customized constructor, useful for Node, Link, and other classes"
503
        params = params.copy()
504
        params.update( kwargs )
505
        if not newargs:
506
            return constructor( name, *args, **params )
507
        if args:
508
            warn( 'warning: %s replacing %s with %s\n' % (
509
                  constructor, args, newargs ) )
510
        return constructor( name, *newargs, **params )
511

    
512
    customized.__name__ = 'customConstructor(%s)' % argStr
513
    return customized
514

    
515
def buildTopo( topos, topoStr ):
516
    """Create topology from string with format (object, arg1, arg2,...).
517
    input topos is a dict of topo names to constructors, possibly w/args.
518
    """
519
    topo, args, kwargs = splitArgs( topoStr )
520
    if topo not in topos:
521
        raise Exception( 'Invalid topo name %s' % topo )
522
    return topos[ topo ]( *args, **kwargs )
523

    
524
def ensureRoot():
525
    """Ensure that we are running as root.
526

527
    Probably we should only sudo when needed as per Big Switch's patch.
528
    """
529
    if os.getuid() != 0:
530
        print "*** Mininet must run as root."
531
        exit( 1 )
532
    return