Sunday, January 20, 2008

Script to Generate CPU Graphs With Perl And Sar

Sar CPU Statistics Graph Generated With The Perl GifGraph Module

Hey There, - Quick Note: Click on the above image to see it in its actual 800x600 resolution.

For today's post, I'll keep it short and sweet (due to the sleep deprivation suffered from my Friday/Saturday overnight work. We all need to sleep sometime. Anytime is good for me at this point ;)

Hope you enjoy the script below. It's written in Perl and will, theoretically, run on Solaris Unix and RedHat Linux.

Why only theoretically? Actually, it will work on both, but I wrote this script to run on Solaris and the output from "sar -u" on RedHat is in slightly different order (so the array elements I use to seed the Graph values in this script won't directly translate, but can be easily modified). You can run it easily by just invoking it (as it is, it should be run on the host it's measuring, since it runs sar at the time you invoke it):

./sarcpugraph.pl

Hope you enjoy this and can use the basic concept to help you generate all sorts of different graphs and charts from sar. I prefer the numbers, straight up, but some folks like to look at lines and bars and strangely colored pies. It's a free world ;)

The sample gif attached above is what your typical output will look like. Blogspot has trimmed it from the 800x600 resolution it was generated at. If you want to see it at that size, just click on it and the link should take you to the full version!

Enjoy,




Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

#
# Sarcpugraph.pl
# Make Fun CPU Graphs For People Who
# Like To See That Sort Of Thing
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

use GIFgraph::lines;
open(SARU, "/usr/sbin/sar -u|");
@saru = <SARU>;
close(SARU);
$my_graph = new GIFgraph::lines(800,600);
$my_graph->set(
x_label => 'Time',
y1_label => 'Percentage',
y2_label => 'Percentage',
title => 'CPU Usage By Server - host',
y1_max_value => 100,
y2_max_value => 100,
y_min_value => 0,
y_tick_number => 5,
long_ticks => 1,
x_ticks => 0,
legend_marker_width => 24,
line_width => 10,
bar_spacing => 0,
gifx => 800,
gify => 600,
transparent => 1,
dclrs => [ qw( red green ) ],
);
$my_graph->set_legend( qw( CPU_Utilization ) );
$a = $b = 0;
foreach $line (@saru) {
next if ( ($line !~ /:/) || ($line =~ /\//));
@line=split(" ", $line);
if ( ( $a % 12 ) != 0 ) {
$pandata0[$a] = undef;
} else {
$line[0] =~ s/:00$//;
$pandata0[$a] = $line[0];
}
$pandata1[$b] = 100-$line[4];
$a++;
$b++;
}
if ( ! $c ) {
@pandata0[0] = `date "+%H:%M"`;
@pandata1[1] = 0;
}
@data = (\@pandata0, \@pandata1);
$my_graph->plot_to_gif( "/my/stats/directory/saru.gif", \@data );


, Mike