#!/usr/bin/perl
#########################################################################
# Description : Check OpenHA Cluster Status by SNMP
# Version : 1.0
# Author: Fabrice Le Dorze	
# Date: March 23 2016
# Licence : GPL - http://www.fsf.org/licenses/gpl.txt
#########################################################################

# Get program path
my $REVISION=1.0;
use Data::Dumper;
use Getopt::Std;
my $code=3;

sub usage
{
    print <<EOF;
Nagios plugin to check OpenHA service states

Usage:
  $0 [--help | -h] [--version | -v][-s <service1>[<service2>,...]][-e]

Options:
  -h	Print this help information
  -v	Print version of plugin
  -s	comma serarated list of services to check
  -e	exclude service specified by -s above
EOF
}

sub help
{
    print "$0 $REVISION\n";
    print "\n";
    &usage;
    print "\n";
}

getopts("hves:");

if ($opt_h)
{
    &help;
    exit $code;
}
if ($opt_v)
{
    print "$PROGNAME $REVISION\n";
    exit $code;
}
my $results=`export EZ="/usr/local/cluster" && source \$EZ/env.sh && \$EZ_BIN/service -s 2>&1`;
my %services;
my @lines=split(/\n/,$results);
map {s/\n//g} @lines;
foreach my $index (0 .. $#lines)
{
    my $line=$lines[$index]; 
    next if ($line=~/defined/);
    if ($line=~/Service: (.*)$/)
    {
        $services{$1}->{'Primary'}=(grep{/Primary/} ($lines[$index+1],$lines[$index+2]))[0];
        $services{$1}->{'Secondary'}=(grep{/Secondary/} ($lines[$index+1],$lines[$index+2]))[0];
    }

}

print "UNKNOWN : could services state of OpenHA cluster\n" and exit $code unless(%services);

# Services to check and missing services
my @missing_services;
if ($opt_s)
{
    if ($opt_e)
    {
        # exclude specified services from %services
        delete @services { split(/,/,$opt_s) };
        @services_to_check=keys %services;
    }
    else
    {
        @services_to_check=split(/,/,$opt_s);
        foreach my $service (@services_to_check)
        {
            push  @missing_services, $service unless ($services{$service});
        }
    }
}
else
{
    @services_to_check=keys %services;
}

# State of services
my @bad_services;
foreach my $service (@services_to_check)
{
   push @bad_services, $service unless ($services{$service}->{'Primary'}=~/STARTED/ and $services{$service}->{'Secondary'}=~/STOPPED/)
}
my $message;
$code=0;
if ($#missing_services>-1)
{
    $message="missing service(s) (".join(", ",@missing_services)."), ";
    $code=2;
}
if ($#bad_services>-1)
{
    $message.="service(s) in bad state (".join(", ",@bad_services)."),";
    $code=2;
}

if ($code==2)
{
    print "CRITICAL, OpenHA Cluster NOK : ".$message."see details.\n";
}
else
{
    print "OK : All selected services of OpenHA Cluster in good state (".join(", ",@services_to_check)."), see details.\n";
}


print $results;
exit $code;
