#!/usr/bin/perl
# rrd-xenpm.pl
# v1.0 - Nicolas AGIUS - 12/2010
# Usage : rrd-xenpm.pl 
#
###################################################################################
## Sonde RRD pour les cpufreq-states de XEN
#
# Copyright (C) 2010 Nicolas AGIUS <nicolas_agius@yahoo.fr>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
###################################################################################

use Storable;

my $cache_file="/var/lib/rrd-xenpm.cache";

# Load previous values
%cache = %{retrieve($cache_file)} if(-e $cache_file);


$cpu=0;
open(XENPM, "xenpm get-cpufreq-states|") or die "Can't read xenpm !\n";
while(<XENPM>)
{

	$cpu++ if(/^cpu\sid/);

	$freq=$1 if(/freq\s+\[(\d+)\sMHz\]/);

	if(/residency\s+\[(\d+)\sms\]/)
	{
		$values{$cpu}{$freq}=$1;
	}

}
close(XENPM);

# Save values to cache
store(\%values,$cache_file);


foreach $cpu (keys %values)
{
	$total_time=0;

	# Compute the total (each freq) elapsed time since the previous run
	foreach $freq (keys %{$values{$cpu}})
	{
		$total_time+= $values{$cpu}{$freq} - $cache{$cpu}{$freq};
	}

	$avg_freq=0;

	# Compute average frequency 
	foreach $freq (keys %{$values{$cpu}})
	{
		$avg_freq+=  ( ($values{$cpu}{$freq} - $cache{$cpu}{$freq}) / $total_time) * $freq;
	}
	print "CPU".($cpu-1)."=".(int($avg_freq)*1000*1000)."\n";
}

exit;

