Statistics
| Branch: | Tag: | Revision:

mininet / mininet / util.py @ a4e93368

History | View | Annotate | Download (20.6 KB)

1 80a8fa62 Bob Lantz
"Utility functions for Mininet."
2 220890a0 Brandon Heller
3 4ea0c093 Brian O'Connor
from mininet.log import output, info, error, warn, debug
4 50cebe67 Bob Lantz
5 867a6d67 Brian O'Connor
from time import sleep
6 b20c9470 Brian O'Connor
from resource import getrlimit, setrlimit, RLIMIT_NPROC, RLIMIT_NOFILE
7 31fe4f1b Bob Lantz
from select import poll, POLLIN, POLLHUP
8 220890a0 Brandon Heller
from subprocess import call, check_call, Popen, PIPE, STDOUT
9 134a75ef Bob Lantz
import re
10 50cebe67 Bob Lantz
from fcntl import fcntl, F_GETFL, F_SETFL
11
from os import O_NONBLOCK
12 bcfb3009 Brandon Heller
import os
13 a565bdd5 cody burkard
from functools import partial
14 82b72072 Bob Lantz
15
# Command execution support
16 220890a0 Brandon Heller
17 80a8fa62 Bob Lantz
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 efc9a01c Bob Lantz
    return check_call( cmd.split( ' ' ) )
26 80a8fa62 Bob Lantz
27 82b72072 Bob Lantz
# pylint doesn't understand explicit type checking
28 061598f0 Bob Lantz
# pylint: disable=maybe-no-member
29 82b72072 Bob Lantz
30 daa576c4 Bob Lantz
def oldQuietRun( *cmd ):
31 80a8fa62 Bob Lantz
    """Run a command, routing stderr to stdout, and return the output.
32
       cmd: list of command params"""
33 8bc00379 Bob Lantz
    if len( cmd ) == 1:
34
        cmd = cmd[ 0 ]
35 82b72072 Bob Lantz
        if isinstance( cmd, str ):
36
            cmd = cmd.split( ' ' )
37 80a8fa62 Bob Lantz
    popen = Popen( cmd, stdout=PIPE, stderr=STDOUT )
38 220890a0 Brandon Heller
    # We can't use Popen.communicate() because it uses
39
    # select(), which can't handle
40
    # high file descriptor numbers! poll() can, however.
41 134a75ef Bob Lantz
    out = ''
42 daa576c4 Bob Lantz
    readable = poll()
43 80a8fa62 Bob Lantz
    readable.register( popen.stdout )
44 220890a0 Brandon Heller
    while True:
45
        while readable.poll():
46 80a8fa62 Bob Lantz
            data = popen.stdout.read( 1024 )
47
            if len( data ) == 0:
48 220890a0 Brandon Heller
                break
49 134a75ef Bob Lantz
            out += data
50 220890a0 Brandon Heller
        popen.poll()
51 7a506047 Brandon Heller
        if popen.returncode is not None:
52 220890a0 Brandon Heller
            break
53 134a75ef Bob Lantz
    return out
54 220890a0 Brandon Heller
55 14ff3ad3 Bob Lantz
56 daa576c4 Bob Lantz
# This is a bit complicated, but it enables us to
57 6e64deec Bob Lantz
# monitor command output as it is happening
58 daa576c4 Bob Lantz
59 14ff3ad3 Bob Lantz
def errRun( *cmd, **kwargs ):
60 daa576c4 Bob Lantz
    """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 551a3666 Bob Lantz
    if echo:
70
        # cmd goes to stderr, output goes to stdout
71
        info( cmd, '\n' )
72 a565bdd5 cody burkard
    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 959586bc Bob Lantz
    debug( '*** errRun:', cmd, '\n' )
81 daa576c4 Bob Lantz
    popen = Popen( cmd, stdout=PIPE, stderr=stderr, shell=shell )
82 cfd38113 Bob Lantz
    # We use poll() because select() doesn't work with large fd numbers,
83
    # and thus communicate() doesn't work either
84 daa576c4 Bob Lantz
    out, err = '', ''
85
    poller = poll()
86
    poller.register( popen.stdout, POLLIN )
87
    fdtofile = { popen.stdout.fileno(): popen.stdout }
88 cfd38113 Bob Lantz
    outDone, errDone = False, True
89 daa576c4 Bob Lantz
    if popen.stderr:
90
        fdtofile[ popen.stderr.fileno() ] = popen.stderr
91
        poller.register( popen.stderr, POLLIN )
92 cfd38113 Bob Lantz
        errDone = False
93
    while not outDone or not errDone:
94 daa576c4 Bob Lantz
        readable = poller.poll()
95 28ce13d1 Bob Lantz
        for fd, event in readable:
96 daa576c4 Bob Lantz
            f = fdtofile[ fd ]
97 28ce13d1 Bob Lantz
            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 98a8231c Bob Lantz
            else:  # POLLHUP or something unexpected
110 28ce13d1 Bob Lantz
                if f == popen.stdout:
111 cfd38113 Bob Lantz
                    outDone = True
112 28ce13d1 Bob Lantz
                elif f == popen.stderr:
113 cfd38113 Bob Lantz
                    errDone = True
114 28ce13d1 Bob Lantz
                poller.unregister( fd )
115
116 cfd38113 Bob Lantz
    returncode = popen.wait()
117 30ebb852 Bob Lantz
    debug( out, err, returncode )
118 daa576c4 Bob Lantz
    return out, err, returncode
119
120 551a3666 Bob Lantz
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 a5af91d0 Bob Lantz
        raise Exception( "errFail: %s failed with return code %s: %s"
125
                         % ( cmd, ret, err ) )
126 551a3666 Bob Lantz
    return out, err, ret
127
128 daa576c4 Bob Lantz
def quietRun( cmd, **kwargs ):
129
    "Run a command and return merged stdout and stderr"
130
    return errRun( cmd, stderr=STDOUT, **kwargs )[ 0 ]
131 220890a0 Brandon Heller
132 061598f0 Bob Lantz
# pylint: enable=maybe-no-member
133 82b72072 Bob Lantz
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 220890a0 Brandon Heller
# 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 7a4a865b Bob Lantz
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 b1ec912d Bob Lantz
       runCmd: function to run shell commands (quietRun)
169 c265deed Bob Lantz
       returns: ip link add result"""
170 7a4a865b Bob Lantz
    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 220890a0 Brandon Heller
    # Create new pair
178 7a4a865b Bob Lantz
    netns = 1 if not node2 else node2.pid
179 eba13f0c cody burkard
    if addr1 is None and addr2 is None:
180 7a4a865b Bob Lantz
        cmdOutput = runCmd( 'ip link add name %s '
181
                            'type veth peer name %s '
182
                            'netns %s' % ( intf1, intf2, netns ) )
183 eba13f0c cody burkard
    else:
184 7a4a865b Bob Lantz
        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 2e704f99 Andrew Ferguson
    if cmdOutput == '':
191
        return True
192
    else:
193 254fae2d Bob Lantz
        raise Exception( "Error creating interface pair (%s,%s): %s " %
194
                         ( intf1, intf2, cmdOutput ) )
195 2e704f99 Andrew Ferguson
        return False
196 80a8fa62 Bob Lantz
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 82b72072 Bob Lantz
        error( "*** gave up after %i retries\n" % tries )
209 80a8fa62 Bob Lantz
        exit( 1 )
210
211 c265deed Bob Lantz
def moveIntfNoRetry( intf, dstNode, printError=False ):
212 80a8fa62 Bob Lantz
    """Move interface to node, without retrying.
213
       intf: string, interface
214 c771b2d7 Bob Lantz
        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 c265deed Bob Lantz
    cmdOutput = quietRun( cmd )
219 41a54f05 cody burkard
    # If ip link set does not produce any output, then we can assume
220
    # that the link has been moved successfully.
221 a3d51b77 cody burkard
    if cmdOutput:
222 80a8fa62 Bob Lantz
        if printError:
223 82b72072 Bob Lantz
            error( '*** Error: moveIntf: ' + intf +
224 c265deed Bob Lantz
                   ' not successfully moved to ' + dstNode.name + ':\n',
225
                   cmdOutput )
226 220890a0 Brandon Heller
        return False
227
    return True
228
229 b1ec912d Bob Lantz
def moveIntf( intf, dstNode, printError=True,
230 7a3159c9 Bob Lantz
              retries=3, delaySecs=0.001 ):
231 80a8fa62 Bob Lantz
    """Move interface to node, retrying on failure.
232
       intf: string, interface
233 c771b2d7 Bob Lantz
       dstNode: destination Node
234 80a8fa62 Bob Lantz
       printError: if true, print error"""
235 c771b2d7 Bob Lantz
    retry( retries, delaySecs, moveIntfNoRetry, intf, dstNode,
236 c265deed Bob Lantz
           printError=printError )
237 80a8fa62 Bob Lantz
238 beb05a71 Bob Lantz
# 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 e3621eb0 Brandon Heller
259 beb05a71 Bob Lantz
def dumpNetConnections( net ):
260
    "Dump connections in network"
261
    nodes = net.controllers + net.switches + net.hosts
262
    dumpNodeConnections( nodes )
263 82b72072 Bob Lantz
264 08643fe6 cody burkard
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 82b72072 Bob Lantz
# IP and Mac address formatting and parsing
274 80a8fa62 Bob Lantz
275 14ff3ad3 Bob Lantz
def _colonHex( val, bytecount ):
276 80a8fa62 Bob Lantz
    """Generate colon-hex string.
277
       val: input as unsigned int
278 ab594b6a Bob Lantz
       bytecount: number of bytes to convert
279 80a8fa62 Bob Lantz
       returns: chStr colon-hex string"""
280 54037995 Brandon Heller
    pieces = []
281 14ff3ad3 Bob Lantz
    for i in range( bytecount - 1, -1, -1 ):
282 80a8fa62 Bob Lantz
        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 891a9e8b cody burkard
    return _colonHex( mac, 6 )
292 80a8fa62 Bob Lantz
293
def ipStr( ip ):
294 d44a5843 Bob Lantz
    """Generate IP address string from an unsigned int.
295
       ip: unsigned int of form w << 24 | x << 16 | y << 8 | z
296 8204a1b6 Bob Lantz
       returns: ip address string w.x.y.z"""
297 82f483f5 Bob Lantz
    w = ( ip >> 24 ) & 0xff
298 14ff3ad3 Bob Lantz
    x = ( ip >> 16 ) & 0xff
299
    y = ( ip >> 8 ) & 0xff
300 d44a5843 Bob Lantz
    z = ip & 0xff
301
    return "%i.%i.%i.%i" % ( w, x, y, z )
302
303
def ipNum( w, x, y, z ):
304 82f483f5 Bob Lantz
    """Generate unsigned int from components of IP address
305 d44a5843 Bob Lantz
       returns: w << 24 | x << 16 | y << 8 | z"""
306 1052f8a0 Brandon Heller
    return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
307 d44a5843 Bob Lantz
308 5a8bb489 Bob Lantz
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 8204a1b6 Bob Lantz
    imax = 0xffffffff >> prefixLen
315 68e2e45f Brian O'Connor
    assert i <= imax, 'Not enough IP addresses in the subnet'
316 8204a1b6 Bob Lantz
    mask = 0xffffffff ^ imax
317
    ipnum = ( ipBaseNum & mask ) + i
318 5a8bb489 Bob Lantz
    return ipStr( ipnum )
319 d44a5843 Bob Lantz
320
def ipParse( ip ):
321
    "Parse an IP address and return an unsigned int."
322
    args = [ int( arg ) for arg in ip.split( '.' ) ]
323 b1ec912d Bob Lantz
    while len(args) < 4:
324 b3055067 Cody Burkard
        args.append( 0 )
325 d44a5843 Bob Lantz
    return ipNum( *args )
326 bb941950 Brandon Heller
327 82f483f5 Bob Lantz
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 b3055067 Cody Burkard
    #if no prefix is specified, set the prefix to 24
335
    else:
336
        ip = ipstr
337
        prefixLen = 24
338 82f483f5 Bob Lantz
    return ipParse( ip ), prefixLen
339
340 bb941950 Brandon Heller
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 740d7ce3 Bob Lantz
        return s
364 bcacfc05 Bob Lantz
365 50cebe67 Bob Lantz
# 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 31fe4f1b Bob Lantz
    while popens:
386 50cebe67 Bob Lantz
        fds = poller.poll( timeoutms )
387
        if fds:
388 31fe4f1b Bob Lantz
            for fd, event in fds:
389 50cebe67 Bob Lantz
                host = fdToHost[ fd ]
390
                popen = popens[ host ]
391 31fe4f1b Bob Lantz
                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 50cebe67 Bob Lantz
                # Check for EOF
400 31fe4f1b Bob Lantz
                elif event & POLLHUP:
401
                    poller.unregister( fd )
402
                    del popens[ host ]
403 50cebe67 Bob Lantz
        else:
404
            yield None, ''
405 bcacfc05 Bob Lantz
406 82b72072 Bob Lantz
# Other stuff we use
407 b20c9470 Brian O'Connor
def sysctlTestAndSet( name, limit ):
408 867a6d67 Brian O'Connor
    "Helper function to set sysctl limits"
409
    #convert non-directory names into directory names
410
    if '/' not in name:
411 b635fd9e Brian O'Connor
        name = '/proc/sys/' + name.replace( '.', '/' )
412 b20c9470 Brian O'Connor
    #read limit
413 4ea0c093 Brian O'Connor
    with open( name, 'r' ) as readFile:
414
        oldLimit = readFile.readline()
415 c273f490 Bob Lantz
        if isinstance( limit, int ):
416 4ea0c093 Brian O'Connor
            #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 b20c9470 Brian O'Connor
425
def rlimitTestAndSet( name, limit ):
426 867a6d67 Brian O'Connor
    "Helper function to set rlimits"
427 b20c9470 Brian O'Connor
    soft, hard = getrlimit( name )
428
    if soft < limit:
429
        hardLimit = hard if limit < hard else limit
430
        setrlimit( name, ( limit, hardLimit ) )
431 bcacfc05 Bob Lantz
432 82b72072 Bob Lantz
def fixLimits():
433
    "Fix ridiculously small resource limits."
434 4ea0c093 Brian O'Connor
    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 18aab5b7 Bob Lantz
    # pylint: disable=broad-except
455 b1ec912d Bob Lantz
    except Exception:
456 4ea0c093 Brian O'Connor
        warn( "*** Error setting resource limits. "
457
              "Mininet's performance may be affected.\n" )
458 061598f0 Bob Lantz
    # pylint: enable=broad-except
459
460 a7648e78 Bob Lantz
461
def mountCgroups():
462
    "Make sure cgroups file system is mounted"
463 433ca2ec Piyush Srivastava
    mounts = quietRun( 'cat /proc/mounts' )
464 a7648e78 Bob Lantz
    cgdir = '/sys/fs/cgroup'
465
    csdir = cgdir + '/cpuset'
466 433ca2ec Piyush Srivastava
    if ('cgroup %s' % cgdir not in mounts and
467
            'cgroups %s' % cgdir not in mounts):
468 a7648e78 Bob Lantz
        raise Exception( "cgroups not mounted on " + cgdir )
469 433ca2ec Piyush Srivastava
    if 'cpuset %s' % csdir not in mounts:
470 149a1f56 Bob Lantz
        errRun( 'mkdir -p ' + csdir )
471
        errRun( 'mount -t cgroup -ocpuset cpuset ' + csdir )
472 134a75ef Bob Lantz
473
def natural( text ):
474
    "To sort sanely/alphabetically: sorted( l, key=natural )"
475
    def num( s ):
476 14ff3ad3 Bob Lantz
        "Convert text segment to int if necessary"
477 5a8bb489 Bob Lantz
        return int( s ) if s.isdigit() else s
478 94f088d7 Bob Lantz
    return [  num( s ) for s in re.split( r'(\d+)', str( text ) ) ]
479 551a3666 Bob Lantz
480 5a8bb489 Bob Lantz
def naturalSeq( t ):
481
    "Natural sort key function for sequences"
482
    return [ natural( x ) for x in t ]
483
484 551a3666 Bob Lantz
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 d8c88bed Bob Lantz
494 5a8bb489 Bob Lantz
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 d8c88bed Bob Lantz
def custom( cls, **params ):
500
    "Returns customized constructor for class cls."
501 4b1dc93b Bob Lantz
    # Note: we may wish to see if we can use functools.partial() here
502
    # and in customConstructor
503 d8c88bed Bob Lantz
    def customized( *args, **kwargs):
504 14ff3ad3 Bob Lantz
        "Customized constructor"
505 4b1dc93b Bob Lantz
        kwargs = kwargs.copy()
506 d8c88bed Bob Lantz
        kwargs.update( params )
507
        return cls( *args, **kwargs )
508 22b8e5e4 Bob Lantz
    customized.__name__ = 'custom(%s,%s)' % ( cls, params )
509 d8c88bed Bob Lantz
    return customized
510 928c0761 Brandon Heller
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 5fae96eb Bob Lantz
        key, val = s.split( '=', 1 )
524 928c0761 Brandon Heller
        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 edf60032 Brandon Heller
                         ( cname, constructors.keys() ) )
538 928c0761 Brandon Heller
539 a4e93368 Bob Lantz
    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 928c0761 Brandon Heller
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 bcfb3009 Brandon Heller
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 cf5bbd59 cody burkard
581 a565bdd5 cody burkard
def waitListening( client=None, server='127.0.0.1', port=80, timeout=None ):
582 7c5d2771 cody burkard
    """Wait until server is listening on port.
583
       returns True if server is listening"""
584 b1ec912d Bob Lantz
    runCmd = ( client.cmd if client else
585 7a3159c9 Bob Lantz
               partial( quietRun, shell=True ) )
586 b1ec912d Bob Lantz
    if not runCmd( 'which telnet' ):
587 cf5bbd59 cody burkard
        raise Exception('Could not find telnet' )
588 18aab5b7 Bob Lantz
    # pylint: disable=maybe-no-member
589 9a8bdfd7 Bob Lantz
    serverIP = server if isinstance( server, basestring ) else server.IP()
590 cf5bbd59 cody burkard
    cmd = ( 'sh -c "echo A | telnet -e A %s %s"' %
591 7a3159c9 Bob Lantz
            ( serverIP, port ) )
592 cf5bbd59 cody burkard
    time = 0
593 342d47cf Bob Lantz
    while 'Connected' not in runCmd( cmd ):
594 cf5bbd59 cody burkard
        if timeout:
595 7c5d2771 cody burkard
            print time
596 cf5bbd59 cody burkard
            if time >= timeout:
597
                error( 'could not connect to %s on port %d\n'
598 a565bdd5 cody burkard
                       % ( server, port ) )
599 7c5d2771 cody burkard
                return False
600 cf5bbd59 cody burkard
        output('waiting for', server,
601
               'to listen on port', port, '\n')
602
        sleep( .5 )
603
        time += .5
604 7c5d2771 cody burkard
    return True