Statistics
| Branch: | Tag: | Revision:

mininet / mininet / util.py @ d82900d3

History | View | Annotate | Download (17.3 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 ):
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
    cmd = 'ip link add name ' + intf1 + ' type veth peer name ' + intf2
158
    cmdOutput = quietRun( cmd )
159
    if cmdOutput == '':
160
        return True
161
    else:
162
        error( "Error creating interface pair: %s " % cmdOutput )
163
        return False
164

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

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

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

    
208
# Support for dumping network
209

    
210
def dumpNodeConnections( nodes ):
211
    "Dump connections to/from nodes."
212

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

    
224
    for node in nodes:
225
        output( node.name )
226
        dumpConnections( node )
227
        output( '\n' )
228

    
229
def dumpNetConnections( net ):
230
    "Dump connections in network"
231
    nodes = net.controllers + net.switches + net.hosts
232
    dumpNodeConnections( nodes )
233

    
234
# IP and Mac address formatting and parsing
235

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

    
248
def macColonHex( mac ):
249
    """Generate MAC colon-hex string from unsigned int.
250
       mac: MAC address as unsigned int
251
       returns: macStr MAC colon-hex string"""
252
    return _colonHex( mac, 6 )
253

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

    
264
def ipNum( w, x, y, z ):
265
    """Generate unsigned int from components of IP address
266
       returns: w << 24 | x << 16 | y << 8 | z"""
267
    return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
268

    
269
def ipAdd( i, prefixLen=8, ipBaseNum=0x0a000000 ):
270
    """Return IP address string from ints
271
       i: int to be added to ipbase
272
       prefixLen: optional IP prefix length
273
       ipBaseNum: option base IP address as int
274
       returns IP address as string"""
275
    imax = 0xffffffff >> prefixLen
276
    assert i <= imax
277
    mask = 0xffffffff ^ imax
278
    ipnum = ( ipBaseNum & mask ) + i
279
    return ipStr( ipnum )
280

    
281
def ipParse( ip ):
282
    "Parse an IP address and return an unsigned int."
283
    args = [ int( arg ) for arg in ip.split( '.' ) ]
284
    return ipNum( *args )
285

    
286
def netParse( ipstr ):
287
    """Parse an IP network specification, returning
288
       address and prefix len as unsigned ints"""
289
    prefixLen = 0
290
    if '/' in ipstr:
291
        ip, pf = ipstr.split( '/' )
292
        prefixLen = int( pf )
293
    return ipParse( ip ), prefixLen
294

    
295
def checkInt( s ):
296
    "Check if input string is an int"
297
    try:
298
        int( s )
299
        return True
300
    except ValueError:
301
        return False
302

    
303
def checkFloat( s ):
304
    "Check if input string is a float"
305
    try:
306
        float( s )
307
        return True
308
    except ValueError:
309
        return False
310

    
311
def makeNumeric( s ):
312
    "Convert string to int or float if numeric."
313
    if checkInt( s ):
314
        return int( s )
315
    elif checkFloat( s ):
316
        return float( s )
317
    else:
318
        return s
319

    
320
# Popen support
321

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

    
361
# Other stuff we use
362
def sysctlTestAndSet( name, limit ):
363
    "Helper function to set sysctl limits"
364
    #convert non-directory names into directory names
365
    if '/' not in name:
366
        name = '/proc/sys/' + name.replace( '.', '/' )
367
    #read limit
368
    with open( name, 'r' ) as readFile:
369
        oldLimit = readFile.readline()
370
        if type( limit ) is int:
371
            #compare integer limits before overriding
372
            if int( oldLimit ) < limit:
373
                with open( name, 'w' ) as writeFile:
374
                    writeFile.write( "%d" % limit )
375
        else:
376
            #overwrite non-integer limits
377
            with open( name, 'w' ) as writeFile:
378
                writeFile.write( limit )
379

    
380
def rlimitTestAndSet( name, limit ):
381
    "Helper function to set rlimits"
382
    soft, hard = getrlimit( name )
383
    if soft < limit:
384
        hardLimit = hard if limit < hard else limit
385
        setrlimit( name, ( limit, hardLimit ) )
386

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

    
413
def mountCgroups():
414
    "Make sure cgroups file system is mounted"
415
    mounts = quietRun( 'cat /proc/mounts' )
416
    cgdir = '/sys/fs/cgroup'
417
    csdir = cgdir + '/cpuset'
418
    if ('cgroup %s' % cgdir not in mounts and
419
            'cgroups %s' % cgdir not in mounts):
420
        raise Exception( "cgroups not mounted on " + cgdir )
421
    if 'cpuset %s' % csdir not in mounts:
422
        errRun( 'mkdir -p ' + csdir )
423
        errRun( 'mount -t cgroup -ocpuset cpuset ' + csdir )
424

    
425
def natural( text ):
426
    "To sort sanely/alphabetically: sorted( l, key=natural )"
427
    def num( s ):
428
        "Convert text segment to int if necessary"
429
        return int( s ) if s.isdigit() else s
430
    return [  num( s ) for s in re.split( r'(\d+)', text ) ]
431

    
432
def naturalSeq( t ):
433
    "Natural sort key function for sequences"
434
    return [ natural( x ) for x in t ]
435

    
436
def numCores():
437
    "Returns number of CPU cores based on /proc/cpuinfo"
438
    if hasattr( numCores, 'ncores' ):
439
        return numCores.ncores
440
    try:
441
        numCores.ncores = int( quietRun('grep -c processor /proc/cpuinfo') )
442
    except ValueError:
443
        return 0
444
    return numCores.ncores
445

    
446
def irange(start, end):
447
    """Inclusive range from start to end (vs. Python insanity.)
448
       irange(1,5) -> 1, 2, 3, 4, 5"""
449
    return range( start, end + 1 )
450

    
451
def custom( cls, **params ):
452
    "Returns customized constructor for class cls."
453
    # Note: we may wish to see if we can use functools.partial() here
454
    # and in customConstructor
455
    def customized( *args, **kwargs):
456
        "Customized constructor"
457
        kwargs = kwargs.copy()
458
        kwargs.update( params )
459
        return cls( *args, **kwargs )
460
    customized.__name__ = 'custom(%s,%s)' % ( cls, params )
461
    return customized
462

    
463
def splitArgs( argstr ):
464
    """Split argument string into usable python arguments
465
       argstr: argument string with format fn,arg2,kw1=arg3...
466
       returns: fn, args, kwargs"""
467
    split = argstr.split( ',' )
468
    fn = split[ 0 ]
469
    params = split[ 1: ]
470
    # Convert int and float args; removes the need for function
471
    # to be flexible with input arg formats.
472
    args = [ makeNumeric( s ) for s in params if '=' not in s ]
473
    kwargs = {}
474
    for s in [ p for p in params if '=' in p ]:
475
        key, val = s.split( '=', 1 )
476
        kwargs[ key ] = makeNumeric( val )
477
    return fn, args, kwargs
478

    
479
def customConstructor( constructors, argStr ):
480
    """Return custom constructor based on argStr
481
    The args and key/val pairs in argsStr will be automatically applied
482
    when the generated constructor is later used.
483
    """
484
    cname, newargs, kwargs = splitArgs( argStr )
485
    constructor = constructors.get( cname, None )
486

    
487
    if not constructor:
488
        raise Exception( "error: %s is unknown - please specify one of %s" %
489
                         ( cname, constructors.keys() ) )
490

    
491
    def customized( name, *args, **params ):
492
        "Customized constructor, useful for Node, Link, and other classes"
493
        params = params.copy()
494
        params.update( kwargs )
495
        if not newargs:
496
            return constructor( name, *args, **params )
497
        if args:
498
            warn( 'warning: %s replacing %s with %s\n' % (
499
                  constructor, args, newargs ) )
500
        return constructor( name, *newargs, **params )
501

    
502
    customized.__name__ = 'customConstructor(%s)' % argStr
503
    return customized
504

    
505
def buildTopo( topos, topoStr ):
506
    """Create topology from string with format (object, arg1, arg2,...).
507
    input topos is a dict of topo names to constructors, possibly w/args.
508
    """
509
    topo, args, kwargs = splitArgs( topoStr )
510
    if topo not in topos:
511
        raise Exception( 'Invalid topo name %s' % topo )
512
    return topos[ topo ]( *args, **kwargs )
513

    
514
def ensureRoot():
515
    """Ensure that we are running as root.
516

517
    Probably we should only sudo when needed as per Big Switch's patch.
518
    """
519
    if os.getuid() != 0:
520
        print "*** Mininet must run as root."
521
        exit( 1 )
522
    return