#!/usr/bin/perl -w
#    ---------------------------------------------------------------------------
#    Infoblox Grid replication . Copyright 2010 Lionel Cottin (cottin@free.fr)
#    ---------------------------------------------------------------------------
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#    ---------------------------------------------------------------------------
#
my $version = "0.1";
my $release = "2010/06/18";

#
# Interesting MIB entries
# -----------------------
my $gridMemberIP     = ".1.3.6.1.4.1.7779.3.1.1.2.1.2.1.1"; # Grid members table
my $gridMemberStatus = ".1.3.6.1.4.1.7779.3.1.1.2.1.2.1.2"; # Grid members status


use Getopt::Std;
use Net::SNMP qw(:snmp);

#-------------------------------------------------------------------------------
#    Global variable declarations
#-------------------------------------------------------------------------------
my @str = ("OK", "WARNING", "CRITICAL", "UNKNOWN"); # Nagios status strings
my (
   $usage,              # Help message
   $hostname,           # Target router
   $community,          # SNMP community (v2c only)
   $base_oid,           # Base OID
   $state,              # Nagios status: 3=unknown, 2=critical, 1=warning, 0=ok, -1=error
   $short,              # Message for $SERVICEOUTPUT$
   $result,             # Temp variable to store SNMP results
   $message,            # Final message to print out
   %grid                # Grid hash for all status information
);


#-------------------------------------------------------------------------------
#    Global variable initializations
#-------------------------------------------------------------------------------
$usage = <<"EOF";
usage:  $0 [-h] -H <hostname> -C <community>

Version: $version
Released on: $release

Nagios check for Infoblox Grid replication using SNMP version 2c
Returns a CRITICAL status if one of the members is not Online.

!!! Use this against a Grid master only !!!

[-h]                  : Print this message
[-H] <hostname>       : IP Address or Hostname
[-C] <community>      : SNMP Community String  (default = "public")
[-d]                  : enable debug output
 
EOF

$state = 0; # Assume OK nagios status by default

#-------------------------------------------------------------------------------
#                              Input Phase
#-------------------------------------------------------------------------------
die $usage if (!getopts('hH:C:d') || $opt_h);
die $usage if (!$opt_H || !$opt_C || $opt_h);
$hostname = $opt_H;
$community = $opt_C || "public"; undef $opt_C; #use twice to remove Perl warning

if($opt_d) {
  print "Target hostname  : $hostname\n";
  print "SNMPv2 community : $community\n";
}

#-------------------------------------------------------------------------------
# Open an SNMPv2 session with the remote agent
#-------------------------------------------------------------------------------
my ($session, $error) = Net::SNMP->session(
        -version     => 'snmpv2c',
        -nonblocking => 1,
        -timeout     => 2,
        -hostname    => $hostname,
        -community   => $community
);

if (!defined($session)) {
  printf("ERROR: %s.\n", $error);
  exit (-1);
}

#-------------------------------------------------------------------------------
# Get Grid members IPs
#-------------------------------------------------------------------------------
$base_oid = $gridMemberIP;
$result = $session->get_bulk_request(
        -callback       => [\&cb_bulk, {}],
        -maxrepetitions => 20,
        -varbindlist => [$base_oid]
);
if (!defined($result)) {
  printf("ERROR: %s.\n", $session->error);
  $session->close;
  exit (-1);
}
snmp_dispatcher();
undef $result;

#-------------------------------------------------------------------------------
# Get Grid members status
#-------------------------------------------------------------------------------
$base_oid = $gridMemberStatus;
$result = $session->get_bulk_request(
        -callback       => [\&cb_bulk, {}],
        -maxrepetitions => 20,
        -varbindlist => [$base_oid]
);
if (!defined($result)) {
  printf("ERROR: %s.\n", $session->error);
  $session->close;
  exit (-1);
}
snmp_dispatcher();
undef $result;


#-------------------------------------------------------------------------------
# Process results
#-------------------------------------------------------------------------------
$short = " ";
$state = 0; # OK Status by default
foreach my $i ( keys %grid ) {
  if  ( $grid{$i}{"state"} ne "Online" ) {
    $state = 2;
  }
  $short = $short . "$grid{$i}{ip}:$grid{$i}{state} ";
}
$message = "Grid status ($short): $str[$state]\n";
print $message;
exit $state;

#-------------------------------------------------------------------------------
# Subroutines
#-------------------------------------------------------------------------------
sub cb_bulk
{
  my ($session, $table) = @_;
  if (!defined($session->var_bind_list)) {
    printf("ERROR: %s\n", $session->error);
    exit -1;
  } else {
    #---------------------------------------------------------------
    # Loop through each of the OIDs in the response and assign
    # the key/value pairs to the anonymous hash that is passed
    # to the callback.  Make sure that we are still in the table
    # before assigning the key/values.
    #---------------------------------------------------------------
    my $next;
    foreach my $oid (oid_lex_sort(keys(%{$session->var_bind_list}))) {
      if (!oid_base_match($base_oid, $oid)) {
        $next = undef;
        last;   
      }      
      $next = $oid;
      $table->{$oid} = $session->var_bind_list->{$oid};
    } 
    #---------------------------------------------------------------
    # If $next is defined we need to send another request
    # to get more of the table.
    #---------------------------------------------------------------
    if (defined($next)) {
      $result = $session->get_bulk_request(
                -callback       => [\&get_bulk, $table],
                -maxrepetitions => 10,
                -varbindlist    => [$next]
                );
      if (!defined($result)) {
        printf("ERROR: %s\n", $session->error);
        exit -1;
      } 
    } else {
      #-------------------------------------------------------
      # We are no longer in the table, so print the results.
      #-------------------------------------------------------
      foreach my $oid (oid_lex_sort(keys(%{$table}))) {
        #-----------------------------------------------
        # Handle result from gridMemberIP walk
        #-----------------------------------------------
        if ($oid =~ /^$gridMemberIP(.*)$/) {
          if($opt_d) {
            print "Member $1: $table->{$oid}\n";
          }
          $grid{$1}{"ip"} = $table->{$oid};
        #-----------------------------------------------
        # Handle result from gridMemberStatus walk
        #-----------------------------------------------
        } elsif ($oid =~ /^$gridMemberStatus(.*)$/) {
          if($opt_d) {
            print "Member $1: $table->{$oid}\n";
          }
          $grid{$1}{"state"} = $table->{$oid};
        }
      }
    }
  }
}