#!/usr/bin/sh
# *****************************************************************************
#  Copyright 2004-2008 Hewlett-Packard Development Company, L.P. 
#  Confidential commercial computer software.  Valid license required.
# 
# This is the serviceguard in host monitor Virtual machine script
# The script can be configured to imdediatly fail over a guest or can
# be configured to be tolerant of reboots and panics.
# This script can not tell the difference between a reboot and a panic
# If either of these things happens with AUTOBOOT set to ON in the EFI
# then this script will detect and report the event.
# The user may modify the following variable to favor failover or
# restarting the package on the same member.
# *****************************************************************************
# @(#) $Id:$
# The number of times we will try to verify that the guest has rebooted or started before we failover reset on success
NUM_OF_RETRYS=10 
# Number of seconds to wait between retrys
MONITOR_INTERVAL=1
# The total number of guest failures/reboot/panics before failing over.
NUM_OF_FAILURES=10

# Retry counter
RETRYS=0
# Failure counter
FAILURES=0
# Current state flag
state=DOWN
# Current pid flag
pid=-1
# Guest status file
GSTAT=/var/opt/hpvm/guests/${1}/guest_status

# Maintenace Mode File
MAINTFILE=/etc/cmcluster/${1}/MAINTENACE_MODE_ENABLED

# Send the pid of the running script a HUP and it will reset FAILURES
trap 'FAILURES=0' HUP
while :; do
    state=`/opt/hpvm/bin/hpvmstatus -P ${1} -M | awk -F: '{print $11}'`
    if [[ -s ${GSTAT} ]] ; then
	pid=`sed -n '1s/ .*//p' ${GSTAT}`
    fi
    if [[ "${state}" = On ]] && ps -f -p ${pid} | grep -q $1$ || [[ -e ${MAINTFILE} ]] ; then
	RETRYS=0
	while kill -0 ${pid} 2>/dev/null ; do
	    sleep ${MONITOR_INTERVAL}
	done
	if [[ -e ${MAINTFILE} ]] ; then
	    sleep ${MONITOR_INTERVAL}
	    ((SECONDS%60)) || print -u "Warning $0 : maintenance mode enabled for guest : ${1}"
	else
	    print -u "Error $0 : detected a failure in guest : ${1}"
	    let FAILURES+=1
	fi
    fi
    let RETRYS+=1
    if [[ ${FAILURES} -gt ${NUM_OF_FAILURES} || ${RETRYS} -gt ${NUM_OF_RETRYS} ]] ; then
	exit 2  #to allow restart and failover
    fi
    sleep ${MONITOR_INTERVAL}
done
exit 0
