#!/usr/bin/perl
# rrd-cpu.pl
# v3.0 - Nicolas AGIUS - 03/2010
#
###################################################################################
## Sonde MRTG pour la charge processeur
#
# Copyright (C) 2006 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.
#
###################################################################################

###################################################################################
# 
# Structure du fichier /proc/stat
#
#    * user: normal processes executing in user mode
#    * nice: niced processes executing in user mode
#    * system: processes executing in kernel mode
#    * idle: twiddling thumbs
#    * iowait: waiting for I/O to complete
#    * irq: servicing interrupts
#    * softirq: servicing softirqs
#
###################################################################################

use Storable;

# /proc/stat report CPU usage in jiffies.
#
# CPU times in second = jiffies/HZ and
# HZ is at 100 on my system as reported
# by the sysconf() C funtion :
#
#// Begin C code
##include <unistd.h>
##include <stdio.h>
#
#int main()
#{
#        printf("HZ=%i\n",sysconf(_SC_CLK_TCK));
#}
#// EOF

my $HZ=100;

### CPU% ###

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

# Initialisation 
my %cache = ( timestamp => 0, user => 0 , nice => 0 , system => 0 , iowait => 0, irq => 0, softirq => 0 );

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

# Read new value
open(STAT,"</proc/stat") or die "Cannot open stat file";
<STAT> =~ /^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/;
close(STAT);

my %values = ( timestamp => time(), user => $1 , nice => $2 , system => $3 , iowait => $5, irq => $6, softirq => $7 );

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

#Compute CPU% for last period for each columns
my $period=$values{'timestamp'}-$cache{'timestamp'};
foreach(keys(%values))
{
	next if(/timestamp/); # pas d'affichage du timestamps
	print uc($_)."=";
	print (($values{$_}-$cache{$_})/$HZ)*100/$period;
	print "\n";
}

### END-CPU% ###

### LOADAVG ###

open(LOADAVG,"</proc/loadavg") or die("Cannot open /proc/loadavg");
<LOADAVG> =~ /^\S+\s(\S+)/;
close LOADAVG;
print "LOADAVG=$1\n";

### END-LOADAVG ###

exit(0);
