Update and rename MantenerFIFO to MantenerFIFO.md
[vsorcdistro/.git] / mininet / examples / multiping.py
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
12 from mininet.net import Mininet
13 from mininet.node import Node
14 from mininet.topo import SingleSwitchTopo
15 from mininet.log import info, setLogLevel
16
17 from select import poll, POLLIN
18 from time import time
19
20 def chunks( l, n ):
21     "Divide list l into chunks of size n - thanks Stackoverflow"
22     return [ l[ i: i + n ] for i in range( 0, len( l ), n ) ]
23
24 def startpings( host, targetips ):
25     "Tell host to repeatedly ping targets"
26
27     targetips = ' '.join( targetips )
28
29     # Simple ping loop
30     cmd = ( 'while true; do '
31             ' for ip in %s; do ' % targetips +
32             '  echo -n %s "->" $ip ' % host.IP() +
33             '   `ping -c1 -w 1 $ip | grep packets` ;'
34             '  sleep 1;'
35             ' done; '
36             'done &' )
37
38     info( '*** Host %s (%s) will be pinging ips: %s\n' %
39           ( host.name, host.IP(), targetips ) )
40
41     host.cmd( cmd )
42
43 def multiping( netsize, chunksize, seconds):
44     "Ping subsets of size chunksize in net of size netsize"
45
46     # Create network and identify subnets
47     topo = SingleSwitchTopo( netsize )
48     net = Mininet( topo=topo, waitConnected=True )
49     net.start()
50     hosts = net.hosts
51     subnets = chunks( hosts, chunksize )
52
53     # Create polling object
54     fds = [ host.stdout.fileno() for host in hosts ]
55     poller = poll()
56     for fd in fds:
57         poller.register( fd, POLLIN )
58
59     # Start pings
60     for subnet in subnets:
61         ips = [ host.IP() for host in subnet ]
62         #adding bogus to generate packet loss
63         ips.append( '10.0.0.200' )
64         for host in subnet:
65             startpings( host, ips )
66
67     # Monitor output
68     endTime = time() + seconds
69     while time() < endTime:
70         readable = poller.poll(1000)
71         for fd, _mask in readable:
72             node = Node.outToNode[ fd ]
73             info( '%s:' % node.name, node.monitor().strip(), '\n' )
74
75     # Stop pings
76     for host in hosts:
77         host.cmd( 'kill %while' )
78
79     net.stop()
80
81
82 if __name__ == '__main__':
83     setLogLevel( 'info' )
84     multiping( netsize=20, chunksize=4, seconds=10 )