#!/usr/bin/perl -w
#
# Program check_hydra_jobs
# Written by: Popov Maxim (gentoozoid@gmail.com)
# License: GPL
#
# "check_hydra_jobs.pl" plugin to check the state of Hydra jobs.
#
# you need DBD-Oracle and DBI from CPAN.org as
# well as some Oracle client stuff to use it.
#

use DBI;
$ENV{"ORACLE_HOME"}="/usr/lib/oracle/10.2.0.3/client";

my $host = shift || &usage ("no host specified");
my $sid  = shift || &usage ("no sid specified");
my $port = shift || &usage ("no port specified");
my $dbuser = shift || &usage ("no user specified");
my $dbpass = shift || &usage ("no password specified");
my $joblist = shift || &usage ("no jobs specified!");

my $dbh = DBI->connect(	"dbi:Oracle:host=$host;port=$port;sid=$sid", $dbuser, $dbpass, { PrintError => 0, AutoCommit => 1, RaiseError => 0 } )
	|| &error ("cannot connect: $DBI::errstr\n");

my $exit_code = -1;

%statuscode=("1034","Waiting","2034","Running","3034","Starting","4034","Blocked","5034","Deleted","6034","Error","7034","Stopped");

my @totaljobs = split('=',$joblist);
my $n = 0;
my $emergency = 0;
while ($totaljobs[$n]) {
    ($jobid,$jobname) = split(':',$totaljobs[$n]);
    $sth = $dbh->prepare("SELECT N_JOB_STATE_ID FROM SS_V_JOBS WHERE N_JOB_ID=$jobid") 
    	|| &error("Cannot prepare request : $DBI::errstr\n");
    $sth->execute 
    	|| &error("Cannot execute request : $DBI::errstr\n");
    $n++;
    while (($statusid) = $sth->fetchrow) {
    	$status .= "$jobname: <" .$statuscode{$statusid}."> ";
    	if ($statusid == ( 4034 || 6034 || 7034)) {
    	    $emergency = 1;
    	}
    }
}

$dbh->disconnect 
	|| &error ("Cannot disconnect from database : $dbh->errstr\n");

print STDOUT $status."\n";
if ($emergency == 1) {
    exit (2);
} else {
    exit (0);
}

sub usage {
	print "@_\n" if @_;
	print "usage : check_hydra_jobs.pl <host> <sid> <port> <user> <passwd> <jobid1:name1=jobid2:name2=...>\n";
	exit (-1);
}

sub error {
	print "@_\n" if @_;
	exit (2);
}
