#!/usr/bin/perl -w
# nagios: -epn
# Don't run this plugin in the embedded perl interpreter
# It hasn't been tested that way
#
#
############################## sgichk_cisco_qos ##############
my $Version='1.0';
# Date : May 22 2010
# Author  : Brent Bice
# Help : http://nagios.manubulon.com
# Licence : GPL - http://www.fsf.org/licenses/gpl.txt
# Contrib : Patric Proy, J. Jungmann, S. Probst, R. Leroy, M. Berger
# TODO : 
#################################################################
#
# Help : ./sgichk_cisco_qos.pl -h
#
use strict;
use Net::SNMP;
use Getopt::Long;

############### BASE DIRECTORY FOR TEMP FILE ########
my $o_base_dir="/tmp/tmp_Nagios_int.";
my $file_history=200;   # number of data to keep in files.

# Nagios specific

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

# SNMP Datas

my $Qdepth_table= '.1.3.6.1.4.1.9.9.166.1.18.1.1.1';
my $MaxQdepth_table = '.1.3.6.1.4.1.9.9.166.1.18.1.1.2';
my $POIndex_table = '.1.3.6.1.4.1.9.9.166.1.5.1.1.4';
my $ConfigIndex_table = '.1.3.6.1.4.1.9.9.166.1.5.1.1.2';
my $CMName_table = '.1.3.6.1.4.1.9.9.166.1.7.1.1.1';
my $QoSIfIndex_table = '.1.3.6.1.4.1.9.9.166.1.1.1.1.4';
my $IfDescr_table = '1.3.6.1.2.1.2.2.1.2';

my %status=(1=>'UNKNOWN',2=>'OTHER',3=>'OK',4=>'WARNING',5=>'FAILED');

# Globals


# Standard options
my $o_host = 		undef; 	# hostname
my $o_port = 		161; 	# port
my $o_help=		undef; 	# wan't some help ?
my $o_verb=		undef;	# verbose mode
my $o_version=		undef;	# print version

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
my $o_warn=50;
my $o_crit=80;

# functions

sub p_version { print "sgichk_cisco_qos 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>] [-w warn_percent] [-c crit_percent]\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 "\nCisco QoS queue depth Monitor for Nagios version ",$Version,"\n";
   print "GPL licence, (c)2010 Brent Bice\n\n";
   print_usage();
   print <<EOT;
-v, --verbose
   print extra debugging information (including interface list on the system)
-h, --help
   print this help message
-H, --hostname=HOST
   name or IP address of host to check
-w
   Queue Percent Full Warning level
-c
   Queue Percent Full Critical level
-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
EOT
}

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

sub check_options {
    Getopt::Long::Configure ("bundling");
	GetOptions(
   	'v'	=> \$o_verb,		'verbose'	=> \$o_verb,
	'w:i'	=> \$o_warn,		'c:i'		=> \$o_crit,
        '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
    );
    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"}}

    # 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
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 status table
my $resultQdepth = $session->get_table( Baseoid => $Qdepth_table );
if (!defined($resultQdepth)) {
   printf("ERROR: QDepth table : %s.\n", $session->error);
   $session->close;
   exit $ERRORS{"UNKNOWN"};
}

my $resultMaxQdepth = $session->get_table(Baseoid => $MaxQdepth_table);
if (!defined($resultMaxQdepth)) {
   printf("ERROR: Max QDepth table : %s.\n", $session->error);
   $session->close;
   exit $ERRORS{"UNKNOWN"};
}

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

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

my $resultCMName = $session->get_table(Baseoid => $CMName_table);
if (!defined($resultCMName)) {
   printf("ERROR: ClassMap Name table : %s.\n", $session->error);
   $session->close;
   exit $ERRORS{"UNKNOWN"};
}

my $resultIfIndex = $session->get_table(Baseoid => $QoSIfIndex_table);
if (!defined($resultIfIndex)) {
   printf("ERROR: QoS Interface Index table : %s.\n", $session->error);
   $session->close;
   exit $ERRORS{"UNKNOWN"};
}

my $resultIfDescr = $session->get_table(Baseoid => $IfDescr_table);
if (!defined($resultIfDescr)) {
   printf("ERROR: Interface Description table : %s.\n", $session->error);
   $session->close;
   exit $ERRORS{"UNKNOWN"};
}

$session->close;

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


my $num_sensor = 0;

# define the OK value
my $ok_val= 3; # As defined in the MIB
my $resultstr="";
my $result = $ERRORS{"OK"};   # assume all will be well

my @outstr = ();
my $perfstr = "\|";
foreach my $key ( keys %$resultQdepth) {
   #verb("OID : $key, QDepth : $$resultQdepth{$key}");
   my $Qdepth = $$resultQdepth{$key};
   my $MaxQDid = "";
   if ($key =~ /$Qdepth_table\.(.*)/) {
      $MaxQDid = $1;
      if (defined($$resultMaxQdepth{$MaxQdepth_table . "." . $MaxQDid})) {
         my $MaxQdepth = $$resultMaxQdepth{$MaxQdepth_table . "." . $MaxQDid};
         my $Qpercent = 0;
         if ($MaxQdepth > 0) {
            $Qpercent = ($Qdepth / $MaxQdepth) * 100;
#HACK for TESTING
#$Qpercent = 55;

            # That was easy.  Now for the tricky bit - getting the
            # interface name and ClassMap name...
            my $ifdescr = "";
            my $qname = "";
            if ($MaxQDid =~ /([0-9]+)\.([0-9]+)/) {
               my $ifnum = $1;   # the QoS interface index
               my $cmnum = $2;   # the classmap index
               my $ifindex = $$resultIfIndex{$QoSIfIndex_table . "." . $ifnum};
               $ifdescr = $$resultIfDescr{$IfDescr_table . "." . $ifindex};
               #verb("ifnum=$ifnum  ifindex=$ifindex  ifDescr = $ifdescr");

               # Ok, now for the ClassMap Name...
               my $QoSPOInum = $$resultPOIndex{$POIndex_table . "." .
                                  $ifnum .  "." . $cmnum};
               my $ConfigNum = $$resultConfigIndex{$ConfigIndex_table . "." .
                                  $ifnum . "." . $QoSPOInum};
               $qname = $$resultCMName{$CMName_table . "." .  $ConfigNum};
               #verb ("ifnum=$ifnum  QoSPOInum=$QoSPOInum  ConfigNum=$ConfigNum qname = $qname");
            }
            my $statstr = "$ifdescr : $qname = $Qpercent% Full";
            verb($statstr);
            push (@outstr, $statstr);

            if (($Qpercent > $o_crit) && ($result!=$ERRORS{'CRITICAL'})) {
               $result = $ERRORS{'CRITICAL'};
               $resultstr = $statstr;
            } elsif (($Qpercent > $o_warn) && ($result==$ERRORS{'OK'})) {
               $result = $ERRORS{'WARNING'};
               $resultstr = $statstr;
            }

            # Now handle perfstats stuff
            my $name = $ifdescr . "_" . $qname;
            $name =~ s/[ \#]/_/g;   # cleanup name
            $perfstr .= " $name=$Qpercent;$o_warn;$o_crit";
         }
      }
   }
}

verb ("perfstr = $perfstr");

if ($result == $ERRORS{'OK'}) {
   print "OK: All QoS Queues ok $perfstr\n";
} elsif ($result == $ERRORS{'UNKNOWN'}) {
   print "UNKNOWN: QoS Queues not ok $perfstr\n";
} elsif ($result == $ERRORS{'WARNING'}) {
   print "WARNING: $resultstr $perfstr\n";
} elsif ($result == $ERRORS{'CRITICAL'}) {
   print "CRITICAL: $resultstr $perfstr\n";
}

foreach my $i (@outstr) {
   print "$i\n";
}
exit $result;

