#!/opt/LifeKeeper/bin/perl
# Copyright (c) 2020, 2022 SIOS Technology Corp.
########################################################################
#
# Title:    Load balancer helth proble
#
# Description:  This script checks the health of a particular resource
#               instance. It should return 0 if the resource is OK or
#               if the resource does not exist or the script fails 
#               for some reason. The script should return <> 0 only in
#               the case of resource failure. The script should invoke
#               sendevent to start local recovery or switchover of a
#               failed resource.
#
# Usage:    quickCheck -t tagname -i id
#
#           where:
#           "tagname" is the resource tag name
#           "id" is the resource ID
#
#           NOTE: quickCheck should not be called directly from restore,
#           but restore should do checks equivalent to a quickCheck
#
# Logging:  All data sent to STDERR will be logged in the lifekeeper
#           log at the INFO level.
#
# ******* IMPORTANT NOTE:
#           QUICKCHECK SCRIPTS ARE RUN PERIODICALLY AND OFTEN.  OUTPUT
#           FROM THIS SCRIPT WILL, THEREFORE, BE LOGGED PERIODICALLY AND
#           OFTEN IN THE LIFEKEEPER LOG.  HANDLE OUTPUT ACCORDINGLY.
#              

use Getopt::Std; # use the standard getopt package
BEGIN { require '/etc/default/LifeKeeper.pl'; } # use the LifeKeeper libraries
use LK;
use LKBase;
use vars qw($opt_t $opt_i);

sub parseOptions { # noparams

	getopts('t:i:');
	$tag = "$opt_t";
	$id = "$opt_i";
};

sub checkResourceState { # params: tag 

	my $tag = shift;
	@_ = LK::ins_list('', '', '', '', $tag, '');
	@_ = split /\001/, $_[0];
	return $_[6]; # state is the 7th field
};


#############################
# Main execution begins here
#############################

# parse command line options
parseOptions;

# $tag and $id are set now if they were given on the command line

# now check the resource
my $state = checkResourceState($tag);
if ("$state" ne "ISP") {
	LKBase::LogMsg({'LOGFILE' => 1}, LK::LK_ERROR, "gen-lb", "quickCheck", $tag, 127009, "Resource out of service");
	exit 0;
}

# Check if daemon is running.
my $pidfile = "$ENV{'LKROOT'}/config/$id.pid";
my $pid;
if(open(my $PID, "< $pidfile")) {
	$pid=<$PID>;
	close($PID);
	#
	# $perl expects to include full path of perl command like /opt/LifeKeeper/bin/perl.
	# $cmd expects to include the full path of Gen-LB restore script like
	# /opt/LifeKeeper/subsys/gen/resources/app/actions/!restore/$tag.
	#
	my ($perl, $cmd) = split / /, `ps $pid | awk '{if (\$1 == "$pid") print \$5, \$6}'`;
	if (! defined $perl || $perl !~ /\/perl$/ || ! defined $cmd || $cmd !~/restore\/$tag$/) {
		LKBase::LogMsg({'STDERR' => 1}, LK::LK_ERROR, "gen-lb", "quickCheck", $tag, 127010, "Daemon not running.");
		exit 1;
	}
}

# Check receive of health check.
if (LK::flg_test('', "$id-hc-ng")) {
	exit 0;
} else {
	exit 1;
}
