#!/usr/bin/perl -w
# ======================================================================
#
# Perl Source File -- Created with SAPIEN Technologies PrimalScript 3.1
#
# NAME: check_processor_use.pl
#
# AUTHOR: Jeremy D. Pavleck , Capella University, jpavleck@gmail.com
# DATE  : 9/23/2005
#
# PURPOSE: Runs mpstat and spits out the CPU info
#
#
# REVISIONS:
#			1.0 - 9/23 - Initial version
#			1.1 - 10/14 - mpstat alone will only return the processor 
#			from boot. To get accurate results, you need to run it 2 times
#			and capture the end result.
#
# ======================================================================
#
# Simple perl script to parse the output of /usr/bin/mpstat -a
#
#
#
# Tue Nov 23 09:56:08 PST 2004
# SET minf mjf xcal  intr ithr  csw icsw migr smtx  srw syscl  usr sys  wt idl sze
#  0   98   0  167   233  123  215    0    3    3    0   347    0   1   0  99   4
#
#
my $verbose = 0; 
use Getopt::Std;
%options=();
getopt("cwh",\%options);

@mpstat = `mpstat -a 1 2 | tail -1`;
for $line (@mpstat) {
  chomp($line);
  $line =~ s/\s+/,/g;
  ($filler, $set, $minf, $mjf, $xcal, $intr, $ithr, $csw, $icsw, $migr, $smtx, $srw, $syscl, $usr, $sys, $wt, $idl, $sze) = split(/,/,"$line");
  $usage = $usr + $sys;
  if($usage >= $options{w}) {
   $exit = 1;
  }
  elsif($usage >= $options{c}) {
   $exit = 2; 
  }
  else {
  $exit = 0
  }
}
if($exit == 0) {
  print "OK: CPU usage is within normal limits. Total: $usage% User: $usr% System: $sys%\n";
  exit 0;
}
elsif($exit == 1) {
  print "WARNING: CPU Usage has exceeded $options{w}% - Total: $usage% User: $usr% System: $sys%\n";
  exit 1;
}
elsif($exit == 2) {
  print "CRITICAL: CPU Usage has exceeded $options{c} - Total: $usage% User: $usr% System: $sys%\n";
  exit 2;
}

if($verbose == 0) {
print "$filler, $set, $minf, $mjf, $xcal, $intr, $ithr, $csw, $icsw, $migr, $smtx, $srw, $syscl, $usr, $sys, $wt, $idl, $sze\n";
exit 0;
}
