#!/usr/bin/perl -w
# nagios: -epn
# Don't run this plugin in the embedded perl interpreter
# It doesn't seem to work that way
#
############################## sgichk_cuda_chassis ##############
my $Version='1.0';
# Date : Jan 20 2012
# Author  : Brent Bice (bbice@sgi.com)
# TODO : 
#################################################################
#
# Help : ./sgichk_cuda_chassis.pl -h
#
use strict;
use Net::SNMP;
use Getopt::Long;

# Nagios specific

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

# SNMP Datas

my $sysLoadOID = '.1.3.6.1.4.1.20632.2.13';
my $sysFanOID = '.1.3.6.1.4.1.20632.2.14';
my $cpuFanOID = '.1.3.6.1.4.1.20632.2.15';
my $cpuTempOID = '.1.3.6.1.4.1.20632.2.16';
my $raidStatusOID = '.1.3.6.1.4.1.20632.2.19';

# 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 $o_admin=		undef;	# admin status instead of oper
my $o_chkadmin=		undef;	# admin status instead of oper
my $o_inverse=  	undef;	# Critical when up
my $o_dormant=        	undef;  # Dormant state is OK
my $verbose=		undef;	# verbose mode
my $o_version=		undef;	# print version
my $o_l_warn=		20;     # system load warning threshold
my $o_l_crit=		60;     # system load critical threshold
my $o_fan_warn=		7000;   # fan speed warning threshold
my $o_fan_crit=		5000;   # fan speed critical threshold
my $o_temp_warn=	50;     # cpu temp warning threshold
my $o_temp_crit=	60;     # cpu temp critical threshold

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

# functions

sub p_version { print "sgichk_cuda_chassis 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] [-w <num_messages>] [-c <num_messages>]\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 "\nUptime Monitor for Nagios version ",$Version,"\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
-w, --warning
   The number of messages in any queue that'll generate a WARNING event
-c, --critical
   The number of messages in any queue that'll generate a CRITICAL event
--loadwarn
   The warning threshold for System Load (not the same as unix load average)
   Default = 20
--loadcrit
   The critical threshold for System Load (not the same as unix load average)
   Default = 60
--tempwarn
   The warning threshold for CPU Temperature (in Celsius)
   Default = 50
--tempcrit
   The critical threshold for CPU Temperature (in Celsius)
   Default = 60
--fanwarn
   The warning threshold for FAN RPMs
   Default = 7000
--fancrit
   The critical threshold for FAN RPMs
   Default = 5000
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,
	'n:s'   => \$o_descr,           'name:s'        => \$o_descr,
        '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,
        'loadwarn:i'	=> \$o_l_warn,
        'loadcrit:i'	=> \$o_l_crit,
        'fanwarn:i'	=> \$o_fan_warn,
        'fancrit:i'	=> \$o_fan_crit,
        'tempwarn:i'	=> \$o_temp_warn,
        'tempcrit:i'	=> \$o_temp_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");
}

# Get cuda_chassis according to SNMP
my $snmpstats = $session->get_request( 
	-varbindlist => [ $sysLoadOID, $sysFanOID, $cpuFanOID,
                          $cpuTempOID, $raidStatusOID ]
);
if (!defined($snmpstats)) {
   printf("ERROR: Couldn't fetch queue stats via SNMP : %s.\n", $session->error);
   $session->close;
   exit $ERRORS{"UNKNOWN"};
}

# Only a few ms left...
alarm(0);

my $perfstr = "\|";
my @outstr = ();
my $result = $ERRORS{'OK'};
my $resstr = "OK: Chassis Stats are ok";

# Check system load
if (defined($$snmpstats{$sysLoadOID})) {
   my $tstr = "sysLoad=$$snmpstats{$sysLoadOID}";
   push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if ($$snmpstats{$sysLoadOID} >= $o_l_crit) {
      $result = $ERRORS{'CRITICAL'};
      $resstr = "CRITICAL: $tstr";
   } elsif (($$snmpstats{$sysLoadOID} >= $o_l_warn) && ($result == $ERRORS{'OK'})) {
      $result = $ERRORS{'WARNING'};
      $resstr = "WARNING: $tstr";
   }
}

# Check system fan speed
if (defined($$snmpstats{$sysFanOID})) {
   my $tstr = "sysFan=$$snmpstats{$sysFanOID}";
   push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if ($$snmpstats{$sysFanOID} < $o_fan_crit) {
      $result = $ERRORS{'CRITICAL'};
      $resstr = "CRITICAL: $tstr";
   } elsif (($$snmpstats{$sysFanOID} < $o_fan_warn) && ($result == $ERRORS{'OK'})) {
      $result = $ERRORS{'WARNING'};
      $resstr = "WARNING: $tstr";
   }
}

# Check cpu fan speed
if (defined($$snmpstats{$cpuFanOID})) {
   my $tstr = "cpuFan=$$snmpstats{$cpuFanOID}";
   push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if ($$snmpstats{$cpuFanOID} < $o_fan_crit) {
      $result = $ERRORS{'CRITICAL'};
      $resstr = "CRITICAL: $tstr";
   } elsif (($$snmpstats{$cpuFanOID} < $o_fan_warn) && ($result == $ERRORS{'OK'})) {
      $result = $ERRORS{'WARNING'};
      $resstr = "WARNING: $tstr";
   }
}

# Check CPU Temp
if (defined($$snmpstats{$cpuTempOID})) {
   my $tstr = "cpuTemp=$$snmpstats{$cpuTempOID}";
   push (@outstr, $tstr);
   $perfstr .= " $tstr";
   if ($$snmpstats{$cpuTempOID} >= $o_temp_crit) {
      $result = $ERRORS{'CRITICAL'};
      $resstr = "CRITICAL: $tstr";
   } elsif (($$snmpstats{$cpuTempOID} >= $o_temp_warn) && ($result == $ERRORS{'OK'})) {
      $result = $ERRORS{'WARNING'};
      $resstr = "WARNING: $tstr";
   }
}

# Check RAID Status
if (defined($$snmpstats{$raidStatusOID})) {
   chomp ($$snmpstats{$raidStatusOID});
   my $tstr = "raidStatus=$$snmpstats{$raidStatusOID}";
   push (@outstr, $tstr);
   if (!($$snmpstats{$raidStatusOID} =~ /RAID status OK/)) {
      $result = $ERRORS{'WARNING'};
      $resstr = "WARNING: $tstr";
   }
}


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

