Statistics
| Branch: | Tag: | Revision:

mininet / examples / multiping.py @ edf60032

History | View | Annotate | Download (2.22 KB)

1
#!/usr/bin/python
2

    
3
"""
4
multiping.py: monitor multiple sets of hosts using ping
5

6
This demonstrates how one may send a simple shell script to
7
multiple hosts and monitor their output interactively for a period=
8
of time.
9
"""
10

    
11
from mininet.net import Mininet
12
from mininet.node import Node
13
from mininet.topo import SingleSwitchTopo
14
from mininet.log import setLogLevel
15

    
16
from select import poll, POLLIN
17
from time import time
18

    
19
def chunks( l, n ):
20
    "Divide list l into chunks of size n - thanks Stackoverflow"
21
    return [ l[ i: i + n ] for i in range( 0, len( l ), n ) ]
22

    
23
def startpings( host, targetips ):
24
    "Tell host to repeatedly ping targets"
25

    
26
    targetips.append( '10.0.0.200' )
27

    
28
    targetips = ' '.join( targetips )
29

    
30
    # BL: Not sure why loopback intf isn't up!
31
    host.cmd( 'ifconfig lo up' )
32

    
33
    # Simple ping loop
34
    cmd = ( 'while true; do '
35
            ' for ip in %s; do ' % targetips +
36
            '  echo -n %s "->" $ip ' % host.IP() +
37
            '   `ping -c1 -w 1 $ip | grep packets` ;'
38
            '  sleep 1;'
39
            ' done; '
40
            'done &' )
41

    
42
    print ( '*** Host %s (%s) will be pinging ips: %s' %
43
            ( host.name, host.IP(), targetips ) )
44

    
45
    host.cmd( cmd )
46

    
47
def multiping( netsize, chunksize, seconds):
48
    "Ping subsets of size chunksize in net of size netsize"
49

    
50
    # Create network and identify subnets
51
    topo = SingleSwitchTopo( netsize )
52
    net = Mininet( topo=topo )
53
    net.start()
54
    hosts = net.hosts
55
    subnets = chunks( hosts, chunksize )
56

    
57
    # Create polling object
58
    fds = [ host.stdout.fileno() for host in hosts ]
59
    poller = poll()
60
    for fd in fds:
61
        poller.register( fd, POLLIN )
62

    
63
    # Start pings
64
    for subnet in subnets:
65
        ips = [ host.IP() for host in subnet ]
66
        for host in subnet:
67
            startpings( host, ips )
68

    
69
    # Monitor output
70
    endTime = time() + seconds
71
    while time() < endTime:
72
        readable = poller.poll(1000)
73
        for fd, _mask in readable:
74
            node = Node.outToNode[ fd ]
75
            print '%s:' % node.name, node.monitor().strip()
76

    
77
    # Stop pings
78
    for host in hosts:
79
        host.cmd( 'kill %while' )
80

    
81
    net.stop()
82

    
83

    
84
if __name__ == '__main__':
85
    setLogLevel( 'info' )
86
    multiping( netsize=20, chunksize=4, seconds=10 )