Statistics
| Branch: | Tag: | Revision:

mininet / mininet / util.py @ 4ea0c093

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

    
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
    return quietRun( cmd )
159

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

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

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

    
204
# Support for dumping network
205

    
206
def dumpNodeConnections( nodes ):
207
    "Dump connections to/from nodes."
208

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

    
220
    for node in nodes:
221
        output( node.name )
222
        dumpConnections( node )
223
        output( '\n' )
224

    
225
def dumpNetConnections( net ):
226
    "Dump connections in network"
227
    nodes = net.controllers + net.switches + net.hosts
228
    dumpNodeConnections( nodes )
229

    
230
# IP and Mac address formatting and parsing
231

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

    
244
def macColonHex( mac ):
245
    """Generate MAC colon-hex string from unsigned int.
246
       mac: MAC address as unsigned int
247
       returns: macStr MAC colon-hex string"""
248
    return _colonHex( mac, 6 )
249

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

    
260
def ipNum( w, x, y, z ):
261
    """Generate unsigned int from components of IP address
262
       returns: w << 24 | x << 16 | y << 8 | z"""
263
    return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
264

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

    
277
def ipParse( ip ):
278
    "Parse an IP address and return an unsigned int."
279
    args = [ int( arg ) for arg in ip.split( '.' ) ]
280
    return ipNum( *args )
281

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

    
291
def checkInt( s ):
292
    "Check if input string is an int"
293
    try:
294
        int( s )
295
        return True
296
    except ValueError:
297
        return False
298

    
299
def checkFloat( s ):
300
    "Check if input string is a float"
301
    try:
302
        float( s )
303
        return True
304
    except ValueError:
305
        return False
306

    
307
def makeNumeric( s ):
308
    "Convert string to int or float if numeric."
309
    if checkInt( s ):
310
        return int( s )
311
    elif checkFloat( s ):
312
        return float( s )
313
    else:
314
        return s
315

    
316
# Popen support
317

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

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

    
376
def rlimitTestAndSet( name, limit ):
377
    "Helper function to set rlimits"
378
    soft, hard = getrlimit( name )
379
    if soft < limit:
380
        hardLimit = hard if limit < hard else limit
381
        setrlimit( name, ( limit, hardLimit ) )
382

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

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

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

    
429
def naturalSeq( t ):
430
    "Natural sort key function for sequences"
431
    return [ natural( x ) for x in t ]
432

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

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

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

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

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

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

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

    
499
    customized.__name__ = 'customConstructor(%s)' % argStr
500
    return customized
501

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

    
511
def ensureRoot():
512
    """Ensure that we are running as root.
513

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