#!/usr/bin/perl -w
# nagios: +epn
#
############################## sgichk_snmp_system ##############
my $Version='1.2';
# Date : Apr 16, 2012
# Author  : Brent Bice (bbice@sgi.com)
# TODO : 
#################################################################
#
# Help : ./sgichk_snmp_system.pl -h
#
use strict;
use Net::SNMP;
use Getopt::Long;
use Cache::Memcached;

############### BASE DIRECTORY FOR TEMP FILE ########

# Nagios specific

my $TIMEOUT = 15;
my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);

# SNMP Datas

my $CPU_table = '.1.3.6.1.4.1.2021.11';
my $UserCPU = $CPU_table . '.50.0';
my $NiceCPU = $CPU_table . '.51.0';
my $SystemCPU = $CPU_table . '.52.0';
my $IdleCPU = $CPU_table . '.53.0';
my $WaitCPU = $CPU_table . '.54.0';
my $KernelCPU = $CPU_table . '.55.0';
my $IntCPU = $CPU_table . '.56.0';
my $SoftIRQCPU = $CPU_table . '.61.0';
my $SwapIN = $CPU_table . '.62.0';
my $SwapOUT = $CPU_table . '.63.0';
my $PageIN = $CPU_table . '.58.0';
my $PageOUT = $CPU_table . '.57.0';

my $mem_table = '.1.3.6.1.4.1.2021.4';
my $TotReal = $mem_table . '.5.0';
my $AvaReal = $mem_table . '.6.0';
my $TotFree = $mem_table . '.11.0';
my $MemBuffer = $mem_table . '.14.0';
my $MemCache = $mem_table . '.15.0';
my $SwapTotal = $mem_table . '.3.0';
my $SwapFree = $mem_table . '.4.0';

my $load_table = '.1.3.6.1.4.1.2021.10.1.3';

my $hostCPUTable = '.1.3.6.1.2.1.25.3.3.1.2';
my $hostTotMem = '.1.3.6.1.2.1.25.2.2';
my $hostStorTable = '.1.3.6.1.2.1.25.2.3.1';
my $StorDescr = $hostStorTable . '.3';
my $StorUnits = $hostStorTable . '.4';
my $StorSize = $hostStorTable . '.5';
my $StorUsed = $hostStorTable . '.6';

# Globals


# Standard options
my $o_host = 		undef; 	# hostname
my $o_port = 		161; 	# port
my $o_descr =		'.*'; 	# description filter
my $o_help=		undef; 	# wan't some help ?
my $verbose=		undef;	# verbose mode
my $o_version=		undef;	# print version
my $o_load_warn=	undef;	# Load Avg Warning Threshold
my $o_load_crit=	undef;	# Load Avg Critical Threshold
my $o_mem_warn=		undef;	# Memory Usage Warning Threshold
my $o_mem_crit=		undef;	# Memory Usage Critical Threshold
my $o_swap_warn=	undef;	# Swap Usage Warning Threshold
my $o_swap_crit=	undef;	# Swap Usage Critical Threshold
my $o_idle_warn=	undef;	# Idle CPU Warning Threshold
my $o_idle_crit=	undef;	# Idle CPU Critical Threshold
my $o_nice_warn=	undef;	# Nice CPU Warning Threshold
my $o_nice_crit=	undef;	# Nice CPU Critical Threshold
my $o_sys_warn=		undef;	# System CPU Warning Threshold
my $o_sys_crit=		undef;	# System CPU Critical Threshold
my $o_wait_warn=	undef;	# I/O Wait CPU Warning Threshold
my $o_wait_crit=	undef;	# I/O Wait CPU Critical Threshold
my $o_user_warn=	undef;	# User CPU Warning Threshold
my $o_user_crit=	undef;	# User CPU Critical Threshold
my $o_use_mib2=		undef;  # Use mib2 host mib instead of net-snmp

my $o_timeout=  undef; 		# Timeout (Default 5)
# SNMP Message size parameter (Makina Corpus contrib)
my $o_octetlength=undef;
# Login options specific
my $o_community = 	undef; 	# community
my $o_version2	= undef;	#use snmp v2c
my $o_login=	undef;		# Login for snmpv3
my $o_passwd=	undef;		# Pass for snmpv3
my $v3protocols=undef;	# V3 protocol list.
my $o_authproto='md5';		# Auth protocol
my $o_privproto='des';		# Priv protocol
my $o_privpass= undef;		# priv password

# Readable names for counters (M. Berger contrib)
my @countername = ( "in=" , "out=" , "errors-in=" , "errors-out=" , "discard-in=" , "discard-out=" );
my $checkperf_out_desc;

# functions

sub p_version { print "sgichk_snmp_system version : $Version\n"; }

sub print_usage {
    print "Usage: $0 [-v] -H <host> -C <snmp_community> [-2] | (-l login -x passwd [-X pass -L <authp>,<privp>)]  [-p <port>] [-o <octet_length>] [-t <timeout>] [-V] [--load-warn=<int>] [--load-crit=<int>] [--idle-warn=<percent>] [--idle-crit=<percent>] [--nice-warn=<percent>] [--nice-crit=<percent] [--sys-warn=<percent>] [--sys-crit=<percent>] [--wait-warn=<percent>] [--wait-crit=<percent>] [--user-warn=<percent>] [--user-crit=<percent>] [--mem-warn=<percent>] [--mem-crit=<percent>] [--swap-warn=<percent>] [--swap-crit=<percent>] [--use-mib2]\n";
}

sub isnnum { # Return true if arg is not a number
  my $num = shift;
  if ( $num =~ /^(\d+\.?\d*)|(^\.\d+)$/ ) { return 0 ;}
  return 1;
}

sub help {
   print "\nSNMP System Performance Monitor for Nagios version ",$Version,"\n";
   print "GPL licence, (c)2004-2007 Patrick Proy\n\n";
   print_usage();
   print <<EOT;
-v, --verbose
   print extra debugging information
-h, --help
   print this help message
-H, --hostname=HOST
   name or IP address of host to check
-C, --community=COMMUNITY NAME
   community name for the host's SNMP agent (implies v1 protocol)
-l, --login=LOGIN ; -x, --passwd=PASSWD, -2, --v2c
   Login and auth password for snmpv3 authentication 
   If no priv password exists, implies AuthNoPriv 
   -2 : use snmp v2c
-X, --privpass=PASSWD
   Priv password for snmpv3 (AuthPriv protocol)
-L, --protocols=<authproto>,<privproto>
   <authproto> : Authentication protocol (md5|sha : default md5)
   <privproto> : Priv protocole (des|aes : default des) 
-P, --port=PORT
   SNMP port (Default 161)
-o, --octetlength=INTEGER
  max-size of the SNMP message, usefull in case of Too Long responses.
  Be carefull with network filters. Range 484 - 65535, default are
  usually 1472,1452,1460 or 1440.     
-t, --timeout=INTEGER
   timeout for SNMP in seconds (Default: 5)   
-V, --version
   prints version number
--load-warn=<integer> --load-crit=<integer>
   At what load averages do you want the plugin to send notifications.
--mem-warn=<integer> --mem-crit=<integer>
   At what percentage of memory usage do you want notifications of.
--swap-warn=<integer> --swap-crit=<integer>
   At what percentage of swap usage do you want notifications of.
--idle-warn=<integer> --idle-crit=<integer>
   At what percentages of Idle CPU or less do you want notifcations of.
--sys-warn=<integer> --sys-crit=<integer>
   At what percentages of System CPU or more do you want notifcations of.
--nice-warn=<integer> --nice-crit=<integer>
   At what percentages of Nice CPU or more do you want notifcations of.
--wait-warn=<integer> --wait-crit=<integer>
   At what percentages of I/O Wait CPU or more do you want notifcations of.
--user-warn=<integer> --user-crit=<integer>
   At what percentages of User CPU or more do you want notifcations of.
--use-mib2
   Don't use net-snmp queries, use mib2 host queries instead
   In mib2 mode, the only warning/critical thresholds that currently work are
   user-warn/user-crit, idle-warn/idle-crit, mem-warn/mem-crit, and
   swap-warn/swap-crit.
EOT
}

# For verbose output
sub verb { my $t=shift; print $t,"\n" if defined($verbose) ; }

sub check_options {
    Getopt::Long::Configure ("bundling");
	GetOptions(
   	'v'	=> \$verbose,		'verbose'	=> \$verbose,
        'h'     => \$o_help,    	'help'        	=> \$o_help,
        'H:s'   => \$o_host,		'hostname:s'	=> \$o_host,
        'p:i'   => \$o_port,   		'port:i'	=> \$o_port,
        'C:s'   => \$o_community,	'community:s'	=> \$o_community,
	'2'	=> \$o_version2,	'v2c'		=> \$o_version2,		
	'l:s'	=> \$o_login,		'login:s'	=> \$o_login,
	'x:s'	=> \$o_passwd,		'passwd:s'	=> \$o_passwd,
	'X:s'	=> \$o_privpass,	'privpass:s'	=> \$o_privpass,
	'L:s'	=> \$v3protocols,	'protocols:s'	=> \$v3protocols,   
        't:i'   => \$o_timeout,    	'timeout:i'	=> \$o_timeout,
	'o:i'   => \$o_octetlength,    	'octetlength:i' => \$o_octetlength,
	'use-mib2' => \$o_use_mib2,
	'load-warn:i' => \$o_load_warn,
	'load-crit:i' => \$o_load_crit,
	'mem-warn:i' => \$o_mem_warn,
	'mem-crit:i' => \$o_mem_crit,
	'swap-warn:i' => \$o_swap_warn,
	'swap-crit:i' => \$o_swap_crit,
	'idle-warn:i' => \$o_idle_warn,
	'idle-crit:i' => \$o_idle_crit,
	'nice-warn:i' => \$o_nice_warn,
	'nice-crit:i' => \$o_nice_crit,
	'sys-warn:i' => \$o_sys_warn,
	'sys-crit:i' => \$o_sys_crit,
	'wait-warn:i' => \$o_wait_warn,
	'wait-crit:i' => \$o_wait_crit,
	'user-warn:i' => \$o_user_warn,
	'user-crit:i' => \$o_user_crit,
    );
    if (defined ($o_help) ) { help(); exit $ERRORS{"UNKNOWN"}};
    if (defined($o_version)) { p_version(); exit $ERRORS{"UNKNOWN"}};
    if ( ! defined($o_host) ) # check host
	{ print_usage(); exit $ERRORS{"UNKNOWN"}}
    if (defined($o_descr)) { #substitute commas for pipes
       $o_descr =~ s/,/|/g;
    }

    # check snmp information
    if ( !defined($o_community) && (!defined($o_login) || !defined($o_passwd)) )
	{ print "Put snmp login info!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
	if ((defined($o_login) || defined($o_passwd)) && (defined($o_community) || defined($o_version2)) )
	{ print "Can't mix snmp v1,2c,3 protocols!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
	if (defined ($v3protocols)) {
	  if (!defined($o_login)) { print "Put snmp V3 login info with protocols!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
	  my @v3proto=split(/,/,$v3protocols);
	  if ((defined ($v3proto[0])) && ($v3proto[0] ne "")) {$o_authproto=$v3proto[0];	}	# Auth protocol
	  if (defined ($v3proto[1])) {$o_privproto=$v3proto[1];	}	# Priv  protocol
	  if ((defined ($v3proto[1])) && (!defined($o_privpass))) {
	    print "Put snmp V3 priv login info with priv protocols!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
	}
	if (defined($o_timeout) && (isnnum($o_timeout) || ($o_timeout < 2) || ($o_timeout > 60))) 
	  { print "Timeout must be >1 and <60 !\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
	if (!defined($o_timeout)) {$o_timeout=5;}

    #### octet length checks
    if (defined ($o_octetlength) && (isnnum($o_octetlength) || $o_octetlength > 65535 || $o_octetlength < 484 )) {
		print "octet lenght must be < 65535 and > 484\n";print_usage(); exit $ERRORS{"UNKNOWN"};
    }	
}
    
########## MAIN #######

check_options();

# Check gobal timeout if snmp screws up
if (defined($TIMEOUT)) {
  verb("Alarm at $TIMEOUT + 5");
  alarm($TIMEOUT+5);
} else {
  verb("no timeout defined : $o_timeout + 10");
  alarm ($o_timeout+10);
}

$SIG{'ALRM'} = sub {
 print "No answer from host\n";
 exit $ERRORS{"UNKNOWN"};
};

# Connect to host
my ($session,$error);
if ( defined($o_login) && defined($o_passwd)) {
  # SNMPv3 login
  if (!defined ($o_privpass)) {
  verb("SNMPv3 AuthNoPriv login : $o_login, $o_authproto");
    ($session, $error) = Net::SNMP->session(
      -hostname   	=> $o_host,
      -version		=> '3',
      -port      	=> $o_port,
      -username		=> $o_login,
      -authpassword	=> $o_passwd,
      -authprotocol	=> $o_authproto,
      -timeout          => $o_timeout
    );  
  } else {
    verb("SNMPv3 AuthPriv login : $o_login, $o_authproto, $o_privproto");
    ($session, $error) = Net::SNMP->session(
      -hostname   	=> $o_host,
      -version		=> '3',
      -username		=> $o_login,
      -port      	=> $o_port,
      -authpassword	=> $o_passwd,
      -authprotocol	=> $o_authproto,
      -privpassword	=> $o_privpass,
	  -privprotocol => $o_privproto,
      -timeout          => $o_timeout
    );
  }
} else {
  if (defined ($o_version2)) {
    # SNMPv2c Login
	verb("SNMP v2c login");
	($session, $error) = Net::SNMP->session(
       -hostname  => $o_host,
	   -version   => 2,
       -community => $o_community,
       -port      => $o_port,
       -timeout   => $o_timeout
    );
  } else {
    # SNMPV1 login
	verb("SNMP v1 login");
    ($session, $error) = Net::SNMP->session(
       -hostname  => $o_host,
       -community => $o_community,
       -port      => $o_port,
       -timeout   => $o_timeout
    );
  }
}
if (!defined($session)) {
   printf("ERROR opening session: %s.\n", $error);
   exit $ERRORS{"UNKNOWN"};
}

if (defined($o_octetlength)) {
	my $oct_resultat=undef;
	my $oct_test= $session->max_msg_size();
	verb(" actual max octets:: $oct_test");
	$oct_resultat = $session->max_msg_size($o_octetlength);
	if (!defined($oct_resultat)) {
		 printf("ERROR: Session settings : %s.\n", $session->error);
		 $session->close;
		 exit $ERRORS{"UNKNOWN"};
	}
	$oct_test= $session->max_msg_size();
	verb(" new max octets:: $oct_test");
}

my $perfstr = "\|";
my @outstr = ();
my $result = $ERRORS{'OK'};
my $resstr = "OK: System stats are acceptable";

if (!defined($o_use_mib2)) {
   my $cpu1 = $session->get_table( Baseoid => $CPU_table );
   my $cputime = time;
   if (!defined($cpu1)) {
      printf("ERROR: CPU Stats table : %s.\n", $session->error);
      $session->close;
      exit $ERRORS{"UNKNOWN"};
   }
   
   my $cache = new Cache::Memcached {
      'servers' => [
          '127.0.0.1:11211',
       ],
   };
   my $UserCPUc = 0;
   my $NiceCPUc = 0;
   my $SystemCPUc = 0;
   my $IdleCPUc = 0;
   my $WaitCPUc = 0;
   my $KernelCPUc = 0;
   my $IntCPUc = 0;
   my $SoftIRQCPUc = 0;
   my $PageINc = 0;
   my $PageOUTc = 0;
   my $SwapINc = 0;
   my $SwapOUTc = 0;
   
   my $UserCPUp = 0;
   my $NiceCPUp = 0;
   my $SystemCPUp = 0;
   my $IdleCPUp = 0;
   my $WaitCPUp = 0;
   my $KernelCPUp = 0;
   my $IntCPUp = 0;
   my $SoftIRQCPUp = 0;
   my $PageINr = 0;
   my $PageOUTr = 0;
   my $SwapINr = 0;
   my $SwapOUTr = 0;
   
   my $deltaTime = 0;
   
   my $oUserCPUc = $cache->get("$o_host.UserCPUc");
   my $oNiceCPUc = $cache->get("$o_host.NiceCPUc");
   my $oSystemCPUc = $cache->get("$o_host.SystemCPUc");
   my $oIdleCPUc = $cache->get("$o_host.IdleCPUc");
   my $oWaitCPUc = $cache->get("$o_host.WaitCPUc");
   my $oKernelCPUc = $cache->get("$o_host.KernelCPUc");
   my $oIntCPUc = $cache->get("$o_host.IntCPUc");
   my $oSoftIRQCPUc = $cache->get("$o_host.SoftIRQCPUc");
   my $oPageINc = $cache->get("$o_host.PageINc");
   my $oPageOUTc = $cache->get("$o_host.PageOUTc");
   my $oSwapINc = $cache->get("$o_host.SwapINc");
   my $oSwapOUTc = $cache->get("$o_host.SwapOUTc");
   my $oldcputime = $cache->get("$o_host.cpu.time");
   my $cpuDelta = $cache->get("$o_host.cpuDelta");
   
   # If we don't have any old stats, sleep 10 seconds and fetch a new set
   if (!defined($oldcputime)) {   # we don't have any old counters to use
      $oldcputime = $cputime;
      $oUserCPUc = $$cpu1{$UserCPU};
      $oNiceCPUc = $$cpu1{$NiceCPU};
      $oSystemCPUc = $$cpu1{$SystemCPU};
      $oIdleCPUc = $$cpu1{$IdleCPU};
      $oWaitCPUc = $$cpu1{$WaitCPU};
      $oKernelCPUc = $$cpu1{$KernelCPU};
      $oIntCPUc = $$cpu1{$IntCPU};
      $oSoftIRQCPUc = $$cpu1{$SoftIRQCPU};
      $oPageINc = $$cpu1{$PageIN};
      $oPageOUTc = $$cpu1{$PageOUT};
      $oSwapINc = $$cpu1{$SwapIN};
      $oSwapOUTc = $$cpu1{$SwapOUT};
   
      sleep(10);   #Sleep for 10 seconds, then fetch cpu stats again
      $cpu1 = $session->get_table( Baseoid => $CPU_table );
      $cputime = time;
   }
   
   if (!defined ($oUserCPUc)) { $oUserCPUc = 0; }
   if (!defined ($oNiceCPUc)) { $oNiceCPUc = 0; }
   if (!defined ($oSystemCPUc)) { $oSystemCPUc = 0; }
   if (!defined ($oIdleCPUc)) { $oIdleCPUc = 0; }
   if (!defined ($oWaitCPUc)) { $oWaitCPUc = 0; }
   if (!defined ($oKernelCPUc)) { $oKernelCPUc = 0; }
   if (!defined ($oIntCPUc)) { $oIntCPUc = 0; }
   if (!defined ($oSoftIRQCPUc)) { $oSoftIRQCPUc = 0; }
   if (!defined ($oPageINc)) { $oPageINc = 0; }
   if (!defined ($oPageOUTc)) { $oPageOUTc = 0; }
   if (!defined ($oSwapINc)) { $oSwapINc = 0; }
   if (!defined ($oSwapOUTc)) { $oSwapOUTc = 0; }
   
   if (defined($$cpu1{$UserCPU})) { $UserCPUc = $$cpu1{$UserCPU}; }
   if (defined($$cpu1{$NiceCPU})) { $NiceCPUc = $$cpu1{$NiceCPU}; }
   if (defined($$cpu1{$SystemCPU})) { $SystemCPUc = $$cpu1{$SystemCPU}; }
   if (defined($$cpu1{$IdleCPU})) { $IdleCPUc = $$cpu1{$IdleCPU}; }
   if (defined($$cpu1{$WaitCPU})) { $WaitCPUc = $$cpu1{$WaitCPU}; }
   if (defined($$cpu1{$KernelCPU})) { $KernelCPUc = $$cpu1{$KernelCPU}; }
   if (defined($$cpu1{$IntCPU})) { $IntCPUc = $$cpu1{$IntCPU}; }
   if (defined($$cpu1{$SoftIRQCPU})) { $SoftIRQCPUc = $$cpu1{$SoftIRQCPU}; }
   if (defined($$cpu1{$PageIN})) { $PageINc = $$cpu1{$PageIN}; }
   if (defined($$cpu1{$PageOUT})) { $PageOUTc = $$cpu1{$PageOUT}; }
   if (defined($$cpu1{$SwapIN})) { $SwapINc = $$cpu1{$SwapIN}; }
   if (defined($$cpu1{$SwapOUT})) { $SwapOUTc = $$cpu1{$SwapOUT}; }
   
   $deltaTime = $cputime - $oldcputime;
   if (!defined ($cpuDelta) || ($cpuDelta == 0)) { # Compute CPU delta
      #print "Time to re-compute cpuDelta\n";
   
      my $totcpu = 0;
      $totcpu += ($UserCPUc - $oUserCPUc);
      $totcpu += ($NiceCPUc - $oNiceCPUc);
      $totcpu += ($SystemCPUc - $oSystemCPUc);
      $totcpu += ($IdleCPUc - $oIdleCPUc);
      if (defined($oWaitCPUc)) { $totcpu += ($WaitCPUc - $oWaitCPUc); }
      if (defined($oIntCPUc)) { $totcpu += ($IntCPUc - $oIntCPUc); }
      if (defined($oSoftIRQCPUc)) {$totcpu += ($SoftIRQCPUc - $oSoftIRQCPUc); }
      #
      # The KernelCPU counter appears to be just a portion of SystemCPU,
      # not an additive counter.
   
      $totcpu = $totcpu / $deltaTime;
   #print "Total Delta appears to be $totcpu\n";
      $cpuDelta = int($totcpu / 100 + 0.5);
      $cache->set($o_host.".cpuDelta",$cpuDelta,3600);
   }
   #print "Divisor appears to be $cpuDelta\n";
   
   $UserCPUp = (($UserCPUc - $oUserCPUc) / $deltaTime) / $cpuDelta;
   $NiceCPUp = (($NiceCPUc - $oNiceCPUc) / $deltaTime) / $cpuDelta;
   $SystemCPUp = (($SystemCPUc - $oSystemCPUc) / $deltaTime) / $cpuDelta;
   $IdleCPUp = (($IdleCPUc - $oIdleCPUc) / $deltaTime) / $cpuDelta;
   $WaitCPUp = (($WaitCPUc - $oWaitCPUc) / $deltaTime) / $cpuDelta;
   $KernelCPUp = (($KernelCPUc - $oKernelCPUc) / $deltaTime) / $cpuDelta;
   $IntCPUp = (($IntCPUc - $oIntCPUc) / $deltaTime) / $cpuDelta;
   $SoftIRQCPUp = (($SoftIRQCPUc - $oSoftIRQCPUc) / $deltaTime) / $cpuDelta;
   $PageINr = (($PageINc - $oPageINc) / $deltaTime);
   $PageOUTr = (($PageOUTc - $oPageOUTc) / $deltaTime);
   $SwapINr = (($SwapINc - $oSwapINc) / $deltaTime);
   $SwapOUTr = (($SwapOUTc - $oSwapOUTc) / $deltaTime);
   
   if (defined($$cpu1{$UserCPU})) { $cache->set($o_host.".UserCPUc",$UserCPUc,500); }
   if (defined($$cpu1{$NiceCPU})) { $cache->set($o_host.".NiceCPUc",$NiceCPUc,500); }
   if (defined($$cpu1{$SystemCPU})) { $cache->set($o_host.".SystemCPUc",$SystemCPUc,500); }
   if (defined($$cpu1{$IdleCPU})) { $cache->set($o_host.".IdleCPUc",$IdleCPUc,500); }
   if (defined($$cpu1{$WaitCPU})) { $cache->set($o_host.".WaitCPUc",$WaitCPUc,500); }
   if (defined($$cpu1{$KernelCPU})) { $cache->set($o_host.".KernelCPUc",$KernelCPUc,500); }
   if (defined($$cpu1{$IntCPU})) { $cache->set($o_host.".IntCPUc",$IntCPUc,500); }
   if (defined($$cpu1{$SoftIRQCPU})) { $cache->set($o_host.".SoftIRQCPUc",$SoftIRQCPUc,500); }
   if (defined($$cpu1{$PageIN})) { $cache->set($o_host.".PageINc",$PageINc,500); }
   if (defined($$cpu1{$PageOUT})) { $cache->set($o_host.".PageOUTc",$PageOUTc,500); }
   if (defined($$cpu1{$SwapIN})) { $cache->set($o_host.".SwapINc",$SwapINc,500); }
   if (defined($$cpu1{$SwapOUT})) { $cache->set($o_host.".SwapOUTc",$SwapOUTc,500); }
   $cache->set("$o_host.cpu.time",$cputime,500);
   
   # Sanity check of cpu percentages
   if (($UserCPUp > 110) || ($UserCPUp < 0)) { $UserCPUp = 0; }
   if (($NiceCPUp > 110) || ($NiceCPUp < 0)) { $NiceCPUp = 0; }
   if (($SystemCPUp > 110) || ($SystemCPUp < 0)) { $SystemCPUp = 0; }
   if (($IdleCPUp > 110) || ($IdleCPUp < 0)) { $IdleCPUp = 100; }
   if (($WaitCPUp > 110) || ($WaitCPUp < 0)) { $WaitCPUp = 0; }
   if (($KernelCPUp > 110) || ($KernelCPUp < 0)) { $KernelCPUp = 0; }
   if (($IntCPUp > 110) || ($IntCPUp < 0)) { $IntCPUp = 0; }
   if (($SoftIRQCPUp > 110) || ($SoftIRQCPUp < 0)) { $SoftIRQCPUp = 0; }
   if (($PageINr > 10000000000) || ($PageINr < 0)) { $PageINr = 0; }
   if (($PageOUTr > 10000000000) || ($PageOUTr < 0)) { $PageOUTr = 0; }
   if (($SwapINr > 10000000000) || ($SwapINr < 0)) { $SwapINr = 0; }
   if (($SwapOUTr > 10000000000) || ($SwapOUTr < 0)) { $SwapOUTr = 0; }
   
   if (defined($oldcputime)) {  # only check CPU stats if we had a valid delta
      if (defined($o_idle_warn)) {
         if ($IdleCPUp < $o_idle_warn) {
            $resstr = "WARNING: Idle CPU = $IdleCPUp";
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_idle_crit)) {
         if ($IdleCPUp < $o_idle_crit) {
            $resstr = "CRITICAL: Idle CPU = $IdleCPUp";
            $result = $ERRORS{'CRITICAL'};
         }
      }
   
      if (defined($o_sys_warn)) {
         if ($SystemCPUp >= $o_sys_warn) {
            $resstr = "WARNING: System CPU = $SystemCPUp";
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_sys_crit)) {
         if ($SystemCPUp >= $o_sys_crit) {
            $resstr = "CRITICAL: System CPU = $SystemCPUp";
            $result = $ERRORS{'CRITICAL'};
         }
      }
   
      if (defined($o_nice_warn)) {
         if ($NiceCPUp >= $o_nice_warn) {
            $resstr = "WARNING: Nice CPU = $NiceCPUp";
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_nice_crit)) {
         if ($NiceCPUp >= $o_nice_crit) {
            $resstr = "CRITICAL: Nice CPU = $NiceCPUp";
            $result = $ERRORS{'CRITICAL'};
         }
      }
   
      if (defined($o_wait_warn)) {
         if ($WaitCPUp >= $o_wait_warn) {
            $resstr = "WARNING: Wait CPU = $WaitCPUp";
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_wait_crit)) {
         if ($WaitCPUp >= $o_wait_crit) {
            $resstr = "CRITICAL: Wait CPU = $WaitCPUp";
            $result = $ERRORS{'CRITICAL'};
         }
      }
   
      if (defined($o_user_warn)) {
         if ($UserCPUp >= $o_user_warn) {
            $resstr = "WARNING: User CPU = $UserCPUp";
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_user_crit)) {
         if ($UserCPUp >= $o_user_crit) {
            $resstr = "CRITICAL: User CPU = $UserCPUp";
            $result = $ERRORS{'CRITICAL'};
         }
      }
   }
   
   my $tstr;
   $tstr = sprintf("UserCPU=%.3f", $UserCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("NiceCPU=%.3f", $NiceCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("SystemCPU=%.3f", $SystemCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("IdleCPU=%.3f", $IdleCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("WaitCPU=%.3f", $WaitCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("KernelCPU=%.3f", $KernelCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("IntCPU=%.3f", $IntCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("SoftIRQCPU=%.3f", $SoftIRQCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("PageIN=%.1f", $PageINr); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("PageOUT=%.1f", $PageOUTr); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("SwapIN=%.1f", $SwapINr); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   $tstr = sprintf("SwapOUT=%.1f", $SwapOUTr); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   
   my $mem = $session->get_table( Baseoid => $mem_table );
   if (!defined($mem)) {
      printf("ERROR: mem Stats table : %s.\n", $session->error);
      $session->close;
      exit $ERRORS{"UNKNOWN"};
   }
   
   my $memreal = $$mem{$TotReal};
   my $memfree = $$mem{$TotFree};
   my $membuff = $$mem{$MemBuffer};
   my $memcache = $$mem{$MemCache};
   my $avareal = $$mem{$AvaReal};
   if (defined($memreal) && defined($memfree)) {
      #my $memperc = $memfree / $memreal * 100;
      #print "Mem Free = $memperc %\n";
      my $memused = 0;
      if (defined ($membuff) && defined($memcache)) {
         $memused = $memreal - ($avareal + $membuff + $memcache);
      } else {
         $memused = $memreal - $avareal;
      }
      my $memperc = $memused / $memreal * 100;
      $tstr = sprintf ("mem_used=%.3f", $memperc); push (@outstr, $tstr);
      $perfstr .= " $tstr";
   
      if (defined($o_mem_warn)) {
         if ($memperc >= $o_mem_warn) {
            $resstr = sprintf ("WARNING: Memory Used=%.3f percent", $memperc);
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_mem_crit)) {
         if ($memperc >= $o_mem_crit) {
            $resstr = sprintf ("CRITICAL: Memory Used=%.3f percent", $memperc);
            $result = $ERRORS{'CRITICAL'};
         }
      }
   }
   
   my $loads = $session->get_table( Baseoid => $load_table );
   if (!defined($loads)) {
      printf("ERROR: Load Avg Stats table : %s.\n", $session->error);
      $session->close;
      exit $ERRORS{"UNKNOWN"};
   }
   my $load1 = $$loads{$load_table.".1"};
   my $load5 = $$loads{$load_table.".2"};
   my $load15 = $$loads{$load_table.".3"};
   if (defined($load1)) {
      $tstr = "Load avgs = $load1, $load5, $load15";
      push (@outstr, $tstr);
      $perfstr .= " load1=$load1 load5=$load5 load15=$load15";
      if (defined($o_load_warn)) {
         if (($load1>$o_load_warn) || ($load5>$o_load_warn) ||
             ($load15>$o_load_warn)) {
            $resstr = "WARNING: $tstr";
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_load_crit)) {
         if (($load1>$o_load_crit) || ($load5>$o_load_crit) ||
             ($load15>$o_load_crit)) {
            $resstr = "CRITICAL: $tstr";
            $result = $ERRORS{'CRITICAL'};
         }
      }
   }
   
   my $swapfree = $$mem{$SwapFree};
   my $swaptotal = $$mem{$SwapTotal};
   if (defined($swapfree) && defined($swaptotal) && ($swaptotal > 0)) {
      #my $memperc = $memfree / $memreal * 100;
      #print "Mem Free = $memperc %\n";
      my $swapused = $swaptotal - $swapfree;
      my $swapperc = $swapused / $swaptotal * 100;
      $tstr = sprintf ("swap_used=%.3f", $swapperc); push (@outstr, $tstr);
      $perfstr .= " $tstr";
   
      if (defined($o_swap_warn)) {
         if ($swapperc >= $o_swap_warn) {
            $resstr = sprintf ("WARNING: Swap Used=%.3f percent", $swapperc);
            $result = $ERRORS{'WARNING'};
         }
      }
      if (defined($o_swap_crit)) {
         if ($swapperc >= $o_swap_crit) {
            $resstr = sprintf ("CRITICAL: Swap Used=%.3f percent", $swapperc);
            $result = $ERRORS{'CRITICAL'};
         }
      }
   }
} else {   # Use MIB2 Host MIB instead
   my $cpu = $session->get_table( Baseoid => $hostCPUTable );
   if (!defined($cpu)) {
      printf("ERROR: MIB2 Host CPU Stats table : %s.\n", $session->error);
      $session->close;
      exit $ERRORS{"UNKNOWN"};
   }

   my $stor = $session->get_table( Baseoid => $hostStorTable );
   if (!defined($stor)) {
      printf("ERROR: MIB2 Host Storage table : %s.\n", $session->error);
      $session->close;
      exit $ERRORS{"UNKNOWN"};
   }

   # compute average cpu usage
   my $CPUp = 0;
   my $numCPUs = 0;
   my $cputot = 0;
   foreach my $key (keys %$cpu) {
      $numCPUs++;
      $cputot += $$cpu{$key};
   }
   if ($numCPUs > 0) {
      $CPUp = $cputot / $numCPUs;   # Avg of all cpu cores
   }

   my $IdleCPUp = 100 - $CPUp;

   my $tstr;
   $tstr = sprintf("UserCPU=%.3f", $CPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if (defined($o_user_warn)) {
      if ($CPUp >= $o_user_warn) {
         $resstr = "WARNING: $tstr";
         $result = $ERRORS{'WARNING'};
      }
   }
   if (defined($o_user_crit)) {
      if ($CPUp >= $o_user_crit) {
         $resstr = "CRITICAL: $tstr";
         $result = $ERRORS{'CRITICAL'};
      }
   }

   $tstr = sprintf("IdleCPU=%.3f", $IdleCPUp); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if (defined($o_idle_warn)) {
      if ($IdleCPUp < $o_idle_warn) {
         $resstr = "WARNING: $tstr";
         $result = $ERRORS{'WARNING'};
      }
   }
   if (defined($o_idle_crit)) {
      if ($IdleCPUp < $o_idle_crit) {
         $resstr = "CRITICAL: $tstr";
         $result = $ERRORS{'CRITICAL'};
      }
   }

   # Now check mem/swap stats
   my $mem_used = 0;
   my $swap_used = 0;
   my $mem_used_val = 0;
   my $mem_size_val = 0;
   my $virt_used_val = 0;
   my $virt_size_val = 0;
   foreach my $key (keys %$stor) {
      if ($key =~ /$StorDescr\.(.*)/) {
         my $ind = $1;
         my $size = $$stor{$StorSize . '.' . $ind};
         my $used = $$stor{$StorUsed . '.' . $ind};
         my $descr = $$stor{$key};
         if ($descr =~ /Physical Memory/) {
            $mem_used_val = $used;
            $mem_size_val = $size;
         }
         if ($descr =~ /Virtual Memory/) {
            $virt_used_val = $used;
            $virt_size_val = $size;
         }
      }
   }

   if ($mem_size_val > 0) {
      $mem_used = $mem_used_val / $mem_size_val * 100;
   }
   # swap is actually virtual memory used minus physical memory used
   if ($virt_size_val > 0) {
      $swap_used = ($virt_used_val - $mem_used_val) / $virt_size_val * 100;
   }

   $tstr = sprintf("mem_used=%.3f", $mem_used); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if (defined($o_mem_warn)) {
      if ($mem_used >= $o_mem_warn) {
         $resstr = "WARNING: $tstr";
         $result = $ERRORS{'WARNING'};
      }
   }
   if (defined($o_mem_crit)) {
      if ($mem_used >= $o_mem_crit) {
         $resstr = "CRITICAL: $tstr";
         $result = $ERRORS{'CRITICAL'};
      }
   }

   $tstr = sprintf("swap_used=%.3f", $swap_used); push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if (defined($o_swap_warn)) {
      if ($swap_used >= $o_swap_warn) {
         $resstr = "WARNING: $tstr";
         $result = $ERRORS{'WARNING'};
      }
   }
   if (defined($o_swap_crit)) {
      if ($swap_used >= $o_swap_crit) {
         $resstr = "CRITICAL: $tstr";
         $result = $ERRORS{'CRITICAL'};
      }
   }
}

print "$resstr $perfstr\n";
foreach (@outstr) { print "$_\n"; }
exit $result;

