#!/usr/bin/perl

use strict;
use warnings;
use RRDs;

# $Id: process_stats.pl 146 2008-06-22 16:14:43Z ed $
# $URL: svn+ssh://fw/repos/code/perl/process/process_stats.pl $

# locate the cpu stats
sub get_stats {
	my $requied = shift;

	open( F, "/proc/stat" )	
		or die( "cannot open proc: $!" );
	my @l = <F>;
	close(F);

	my @ll = grep { /^cpu[0-9]+/ } @l;

	foreach( @ll ) {
		(my $cpu, my $user, my $nice, my $system, my $idle, my $iowait, my $irq, my $softirq ) = ( $_ =~ /^cpu([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/ );

		if( $cpu eq $requied ) {
			my %hash;
			$hash{'cpu'} = $cpu;
			$hash{'user'} = $user;
			$hash{'nice'} = $nice;
			$hash{'system'} = $system;
			$hash{'idle'} = $idle;
			$hash{'iowait'} = $iowait;
			$hash{'irq'} = $irq;
			$hash{'softirq'} = $softirq;
			return( %hash );
		}
	}
	return( undef );
}

# this function just returns the diff from second of first.
sub subtract {
	my $first_hr = shift;
	my $second_hr = shift;
	my %first = %$first_hr;
	my %second = %$second_hr;
	my %return;

	foreach( keys %second ) {
		$return{$_} = $second{$_} - $first{$_};
	}
	return( %return );
}

sub do_cpu {
	my $num = shift;
	my %cpu1 = get_stats( $num );
	sleep(1);
	my %cpu12 = get_stats( $num );

	my %result = subtract( \%cpu1, \%cpu12 );
	my $total = 0;

	foreach( keys %result ) {
		$total += $result{$_};
	}

	my $string;
	$string = sprintf( "%d:%d:%d:%d:%d:%d:%d", $result{'user'}, $result{'nice'}, $result{'system'}, $result{'idle'}, $result{'iowait'}, $result{'irq'}, $result{'softirq'} );
#	foreach( keys %result ) {
#		print( $_, "\t", ( $total / 100 ) * $result{$_}, "\n" );
#	}
	#print( "$string\n" );
	RRDs::update( "cpu$num.rrd", "N:$string" );
	open( LOG, ">>update.log" );
	print( LOG "rrdtool update cpu$num.rrd ", time(),":", $string, "\n" );
	close(LOG);

	print RRDs::error, "\n" if( defined( RRDs::error ) );
}

sub main {
	do_cpu( $ARGV[0] );
}

main();

