#!/usr/bin/python

#
# The following is written by a novice python programmer it isn't worth
# reading for style, but it gets points for usefulness...
#
import fileinput
import re
import fpformat


# Maps file descriptor to a tuple.  The order of the tuple is:
# filename, execution time, bytes read, bytes written.
fdMap = {}

# This basically accumulates the same info as above but is keyed off of
# file name rather then descriptor.  When a file is closed the stats in
# here get accumulated into this one based on the first field of the fdMap 
# tuple.
fileTime = {}

# Accumulates all time that didn't get accounted for in fileTime.
# key is the system call, the value is the total time accumulated.
syscallTime = {}

# name, time, bytes read, bytes written
# Setup the make the way it is given to you.
# If output it redirected technically this is wrong, deal with it.
# I can't find a way to get any more information about this.
fdMap[ "0" ] = ( "<builtin-stdin>", 0, 0, 0 )
fdMap[ "1" ] = ( "<builtin-stdout>", 0, 0, 0 )
fdMap[ "2" ] = ( "<builtin-stderr>", 0, 0, 0 )

# Read all the files from the command line, open them and parse them
# one by one.  I believe it assumes stdin if no files listed on the
# command line.
for line in fileinput.input():
	#print line;

	# Look for a write.
	result = re.match( "[0-9]*\.[0-9]* write\((?P<fd>[0-9-]*),.*\) = (?P<bytes>[0-9-]*) <(?P<time>[0-9]*\.[0-9]*)>", line );

	if( result ):
		# Update the fdMap statistics.
		fd = result.group( "fd" );
		time = float( result.group( "time" ) );
		bytes = long( result.group( "bytes" ) );

		if( fdMap.has_key( fd ) ):
			value = fdMap[ fd ];
			value = ( value[0], value[1] + time, value[2], value[3] + bytes );
			fdMap[fd] = value;

		# If it isn't -1 and it isn't in the map there is a logical
		# error in the code.  Were missing an important system call
		# basically.
		elif( fd != "-1" ):
			print "Working on fd: ", fd, "and it isn't in the map"
			print line;
			exit( -1 );
		
		continue;

	# Look for read calls in the output of strace.
	result = re.match( "[0-9]*\.[0-9]* read\((?P<fd>[0-9-]*),.*\) = (?P<bytes>[0-9-]*) <(?P<time>[0-9]*\.[0-9]*)>", line );

	if( result ):
		# Update fdMap to include this call.
		fd = result.group( "fd" );
		time = float( result.group( "time" ) );
		bytes = long( result.group( "bytes" ) );

		if( fdMap.has_key( fd ) ):
			value = fdMap[ fd ];
			value = ( value[0], value[1] + time, value[2] + bytes, value[3] );
			fdMap[fd] = value;
		elif( fd != "-1" ):
			exit( -1 );
		
		continue;

	# socket creates a valid fd, so pay attention to it.
	# notice that it the the file name is hard coded.  A creative
	# coder would keep track of all that too!
	result = re.match( "[0-9]*\.[0-9]* socket\(.*\) = (?P<fd>[0-9-]*).*<(?P<time>[0-9]*\.[0-9]*)>", line );
	if( result ):
		fd = result.group( "fd" );
		time = float( result.group( "time" ) );

		if( fdMap.has_key( fd ) ):
			exit ( -1 )
		elif( fd != "-1" ):
			fdMap[ fd ] = ( "<socket>", time, 0, 0 )
		continue;
		
		
	

	# Keep track of the opens.  Fill in the fdMap with a blank entry
	# for the newly opened file.
	result = re.match( "[0-9]*\.[0-9]* open\((?P<name>\".*\"), .*\) = (?P<fd>[0-9-]*).*<(?P<time>[0-9]*\.[0-9]*)>", line );
	if( result ):
		fd = result.group("fd");
		name  = result.group("name");
		time = float( result.group("time") );

		if( fdMap.has_key( fd  ) ):
			print "problem";
			exit( -1 );
		elif( fd != "-1" ):
			fdMap[ fd ] = ( name, time, 0, 0 )
		continue;

	# Keep track of closes.
	result = re.match( "[0-9]*\.[0-9]* close\((?P<fd>.*)\) *= (?P<rc>[0-9-]*) <(?P<time>[0-9]*\.[0-9]*)>", line );
	if( result ):
		# TODO: keep track of the close times also.
		fd = result.group( "fd" );
		# Get the value from fdMap.
		value = fdMap[ fd ];
		# Now update the fileTime map to include this usage
		# of the statistics.
		tuple = fileTime.get( value[0],  ( float("0.0"), long( 0 ), long( 0 ) ) );
		fileTime[ value[0] ] = ( value[1] + tuple[0], value[2] + tuple[1], value[3] + tuple[2] );

		# Delete it out of the fdMap, it was closed.
		del fdMap[ fd ];
		continue;

	# Match any other system call and accumulate its time also.
	result = re.match( "[0-9]*\.[0-9]* (?P<syscall>[^\(]*\().*<(?P<time>[0-9]*\.[0-9]*)>$", line )

	if( result ):
		syscall = result.group( "syscall" );
		time = float( result.group( "time" ) );
		total = syscallTime.get( syscall, float("0.0" ) ); 
		syscallTime[ syscall ] = total + time;
		continue;

	# Print out the unmatched lines, should only be the exec
	# that is the very first system call.  I really should write a
	# match for that too, but I am lazy.
	print "Unmatched line: ", line

	

# Print out the output of each line.
# piping the output of this script into sort -n will give you the list
# of the biggest consumers of time.  At the very bottom.

# output the file I/O times per file.
for key in fileTime.keys():
	print fpformat.fix( fileTime[ key ][0], 8 ), fpformat.fix( fileTime[ key ][1], 8 ), fpformat.fix( fileTime[ key ][2], 8 ), key; 

# Output the syscall times.
for key in syscallTime.keys():
	print fpformat.fix( syscallTime[ key ], 8 ), key; 

