Update and rename MantenerFIFO to MantenerFIFO.md
[vsorcdistro/.git] / mininet / examples / multipoll.py
1 #!/usr/bin/python
2
3 """
4 Simple example of sending output to multiple files and
5 monitoring them
6 """
7
8
9 from mininet.topo import SingleSwitchTopo
10 from mininet.net import Mininet
11 from mininet.log import info, setLogLevel
12 from mininet.util import decode
13
14 from time import time
15 from select import poll, POLLIN
16 from subprocess import Popen, PIPE
17
18
19 def monitorFiles( outfiles, seconds, timeoutms ):
20     "Monitor set of files and return [(host, line)...]"
21     devnull = open( '/dev/null', 'w' )
22     tails, fdToFile, fdToHost = {}, {}, {}
23     for h, outfile in outfiles.items():
24         tail = Popen( [ 'tail', '-f', outfile ],
25                       stdout=PIPE, stderr=devnull )
26         fd = tail.stdout.fileno()
27         tails[ h ] = tail
28         fdToFile[ fd ] = tail.stdout
29         fdToHost[ fd ] = h
30     # Prepare to poll output files
31     readable = poll()
32     for t in tails.values():
33         readable.register( t.stdout.fileno(), POLLIN )
34     # Run until a set number of seconds have elapsed
35     endTime = time() + seconds
36     while time() < endTime:
37         fdlist = readable.poll(timeoutms)
38         if fdlist:
39             for fd, _flags in fdlist:
40                 f = fdToFile[ fd ]
41                 host = fdToHost[ fd ]
42                 # Wait for a line of output
43                 line = f.readline().strip()
44                 yield host, decode( line )
45         else:
46             # If we timed out, return nothing
47             yield None, ''
48     for t in tails.values():
49         t.terminate()
50     devnull.close()  # Not really necessary
51
52
53 def monitorTest( N=3, seconds=3 ):
54     "Run pings and monitor multiple hosts"
55     topo = SingleSwitchTopo( N )
56     net = Mininet( topo )
57     net.start()
58     hosts = net.hosts
59     info( "Starting test...\n" )
60     server = hosts[ 0 ]
61     outfiles, errfiles = {}, {}
62     for h in hosts:
63         # Create and/or erase output files
64         outfiles[ h ] = '/tmp/%s.out' % h.name
65         errfiles[ h ] = '/tmp/%s.err' % h.name
66         h.cmd( 'echo >', outfiles[ h ] )
67         h.cmd( 'echo >', errfiles[ h ] )
68         # Start pings
69         h.cmdPrint('ping', server.IP(),
70                    '>', outfiles[ h ],
71                    '2>', errfiles[ h ],
72                    '&' )
73     info( "Monitoring output for", seconds, "seconds\n" )
74     for h, line in monitorFiles( outfiles, seconds, timeoutms=500 ):
75         if h:
76             info( '%s: %s\n' % ( h.name, line ) )
77     for h in hosts:
78         h.cmd('kill %ping')
79     net.stop()
80
81
82 if __name__ == '__main__':
83     setLogLevel('info')
84     monitorTest()