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