4 Simple example of sending output to multiple files and
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
15 from select import poll, POLLIN
16 from subprocess import Popen, PIPE
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()
28 fdToFile[ fd ] = tail.stdout
30 # Prepare to poll output files
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)
39 for fd, _flags in fdlist:
42 # Wait for a line of output
43 line = f.readline().strip()
44 yield host, decode( line )
46 # If we timed out, return nothing
48 for t in tails.values():
50 devnull.close() # Not really necessary
53 def monitorTest( N=3, seconds=3 ):
54 "Run pings and monitor multiple hosts"
55 topo = SingleSwitchTopo( N )
59 info( "Starting test...\n" )
61 outfiles, errfiles = {}, {}
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 ] )
69 h.cmdPrint('ping', server.IP(),
73 info( "Monitoring output for", seconds, "seconds\n" )
74 for h, line in monitorFiles( outfiles, seconds, timeoutms=500 ):
76 info( '%s: %s\n' % ( h.name, line ) )
82 if __name__ == '__main__':