#!/sbin/sh
#  Copyright 2004-2006 Hewlett-Packard Development Company, L.P.
# Confidential commercial computer software.  Valid license required.
#
# NOTE:    This script is not configurable!  Any changes made to this
#          script will be overwritten when you upgrade to the next
#          release of HP-UX.  Use /etc/rc.config to make changes.
#
# This script insures connectivity of the HPVM guest during
# vswitch failover in a HPVM serviceguard in host
# cluster. 
# It does this by mornitoring syslog.log looking for serviceguard
# Primary to Standby network failover events.  When this script
# identifies one of these events it will atomatically halt, delete,
# create and then boot the vswitch associated with the failed device
# onto the standby physical network device identified by serviceguard.
# This script is started as part of the rc3.d boot sequence
###############################################################################
# @(#) $Id: vswitchmon.sh 4656 2006-06-14 04:11:33Z tharple $

trap "" 1
PATH=/sbin:/usr/sbin:/usr/bin:/usr/local/bin
export PATH

# Allow unset shell variables during substitution
set +u

# Full pathname to command/files
alias awk=/usr/bin/awk
alias grep=/usr/bin/grep
alias hpvmnet=/opt/hpvm/bin/hpvmnet
alias kill=/usr/bin/kill
alias logger=/usr/bin/logger
alias ls=/usr/bin/ls
alias ps=/usr/bin/ps
alias rm=/usr/bin/rm
alias sed=/usr/bin/sed
alias sleep=/usr/bin/sleep
alias swlist=/usr/sbin/swlist
alias tail=/usr/bin/tail
alias wc=/usr/bin/wc
alias ifconfig=/usr/sbin/ifconfig

COMMAND=/sbin/init.d/vswitchmon
CMD=${COMMAND##*/}
PIDFILE=/tmp/${CMD}.pid

# Global variable used for debug and logging

DEBUG=false
if ${DEBUG} ; then
    LOGFILE=/tmp/${CMD}.log
    SLOGFILE=/tmp/${CMD}_S.log
else
    LOGFILE=/dev/null
    SLOGFILE=/dev/null
fi

# Global variable used for the syslog cleanup and rotation detection

SYSLOG=/var/adm/syslog/syslog.log
SLINODE=
SLSIZE=
SLPOLL=10

##########################
function set_syslog
##########################
{
    ${DEBUG} && set -x
    typeset syslog=`sed -n '/syslog.log/s/.*[[:space:]][[:space:]]*//p' /etc/syslog.conf`
    if [[ ${syslog} != ${SYSLOG} ]] ; then
	if [[ -s ${syslog} ]] ; then
	    SYSLOG=${syslog}
	else
	    log "Warn: Ignoring /etc/syslog.conf entry : ${syslog}"
	fi
	log "Warn: Using syslog file : ${SYSLOG}"
    fi
}
##########################
function syslog_monitor
##########################
{
    ${DEBUG} && set -x
    typeset inode
    typeset size
    typeset x
    while ls -il ${SYSLOG} | read inode x x x x size x; do
	if [[ ${inode} -ne ${SLINODE:=${inode}} || ${size} -lt ${SLSIZE:=${size}} ]] ; then
	# restart this application
	    log "Warn: ${SYSLOG}  rotation detected : restarting ${CMD}"
	    ${0} restart
	    exit
	fi
	SLSIZE=${size}
	sleep ${SLPOLL}
    done
}

##########################
function log
##########################
{
    print -u2 "${*}"
    logger -t "${CMD}[${$}]" "${*}"
}

##########################
function vswitch_status
##########################
{
    typeset status=`hpvmnet ${1:+ -S ${1}} -M 2>/dev/null | awk -F: '!vs||$1==vs{print $4}' vs=${1}`
    typeset exit=1
    if [[ ${#} = 3 ]] ; then
	eval [[ ${status} ${2} ${3} ]]
	exit=${?}
    elif [[ -n ${status} ]] ; then
	exit=0
    else
	exit=1
    fi
    return ${exit}
}
##########################
function ifconfig_status
##########################
{
    typeset x
    typeset flags
    typeset ip
    typeset exit=1
    ifconfig ${1} | { read x flags ; read x ip x x ; }
    if [[ ${#} = [12] ]] ; then
	if [[ ${flags} = *UP* ]] ; then
	    exit=0
	fi
	if [[ ${#} = 2 ]] ; then
	    print ${ip}
	fi
    else
	eval [[ ${ip} ${2} ${3} ]]
	exit=${?}
    fi
    return ${exit}
}

##########################
function cmcld_monitor
##########################
{
    ${DEBUG} && set -x
    typeset error=0
    typeset state=read
    typeset ipmismatch=false
    typeset start
    typeset to from 
    typeset vto vfrom 
    typeset ipto
    typeset mon day time host app mesg
    trap "" 1
    trap '/usr/bin/logger -t "${CMD}[${$}]" "Info: Exiting..."' EXIT
    log "Info: Starting : vswitch monitor"
    set_syslog
    start=`wc -l < ${SYSLOG}`
    tail -n +${start} -f ${SYSLOG} | 
    while [[ ${state} != exit ]] ; do
	case ${state} in
	    (read)
	    read mon day time host app mesg
	    # SG network daemon change: SG 11.17 cmcld ; SG 11.18 cmnetd
	    if [[ ${app} = cm@(net|cl)d[[]+([0-9])[]]: ]] ; then
		case ${mesg} in
		    ("lan"+([0-9])" switched to lan"+([0-9]))
		    log "Info: Detected cmcld activity : ${mesg} "
		    from=${mesg%% *} 
		    to=${mesg##* } 
		    ipto=`ifconfig_status ${to} ip`
		    vto="" 
		    vfrom=""
		    ${DEBUG} && hpvmnet >&2
		    eval `hpvmnet | awk '$5==to{print "vto="$1};$5==from{print "vfrom="$1}' to=${to} from=${from}`
		    if [[ -n ${vto} ]] ; then
			if ${ipmismatch} ; then
			    log "Warn: Cannot move vswitch ${vto} from ${from} to ${to} : already configured"
			else
			    log "Error: Cannot move vswitch ${vto} from ${from} to ${to} : already configured"
			fi
		    fi
		    if [[ -n ${vfrom} ]] ; then
			state=change
		    else
			if ! ${ipmismatch} ; then
			    log "Info: No vswitch configured on ${from}"
			fi
		    fi
		    ipmismatch=false
		    ;;
		esac
	    fi
	    ;;
	    (change)
	    if ifconfig_status ${from} = ${ipto} ; then
		# This is unexpected and means the IP address is back on the original interface
		log "Warn: IP Address mis-match : ${ipto} found on interface ${from} expected ${to}"
		ipmismatch=true
		state=read
	    else
		# Other wise we can change the nic#.  This code will handle
		#  the current state of the vswitch, stop it, change the nic
		#  value, and restart.  On error, it attempts to replace things
		#  as they were before the change attempt was attempted.
		if hpvmnet -C -S ${vfrom} -n ${to#lan} ; then
		    state=plumb
		else
		    log "Error: Cannot change vswitch ${vto} on interface ${to}"
		    state=read
		fi
	    fi
	    ;;
	    (halt)
	    if ifconfig_status ${from} = ${ipto} ; then
		# This is unexpected and means the IP address is back on the original interface
		log "Warn: IP Address mis-match : ${ipto} found on interface ${from} expected ${to}"
		ipmismatch=true
		state=read
	    else
		if vswitch_status ${vfrom} != Down ; then
		    if hpvmnet -F -h -S ${vfrom} ; then
			state=plumb
		    else
			log "Error: Cannot halt vswitch ${vto}"
			state=read
		    fi
		else
		    state=plumb
		fi
	    fi
	    ;;
	    (plumb)
	    if ifconfig_status ${from} = ${ipto} ; then
		# This is unexpected and means the IP address is back on the original interface
		log "Warn: IP Address mis-match : ${ipto} found on interface ${from} expected ${to}"
		ipmismatch=true
		state=boot
	    else
		if ifconfig ${from} unplumb ; then
		    if ifconfig ${from} plumb ; then
			state=read
		    else
			log "Error: ifconfig ${from} plumb : failed"
			state=read
		    fi
		else
		    log "Error: ifconfig ${from} unplumb : failed"
		    state=read
		fi
	    fi
	    ;;
	    (delete)
	    if ifconfig_status ${from} = ${ipto} ; then
		# This is unexpected and means the IP address is back on the original interface
		log "Warn: IP Address mis-match : ${ipto} found on interface ${from} expected ${to}"
		ipmismatch=true
		state=boot
	    else
		if vswitch_status ${vfrom} = Down ; then
		    if hpvmnet -F -d -S ${vfrom} ; then
			state=create
		    else
			log "Error: Cannot delete vswitch ${vto}"
			state=read
		    fi
		else
		    state=halt
		fi
	    fi
	    ;;
	    (create)
	    if ifconfig_status ${from} = ${ipto} ; then
		# This is unexpected and means the IP address is back on the original interface
		log "Warn: IP Address mis-match : ${ipto} found on interface ${from} expected ${to}"
		state=restore
		ipmismatch=true
	    else
		if vswitch_status ${vfrom} ; then
		    # If the vswitch exist, it needs to be deleted first
		    state=delete
		else
		# Other wise we can attempt to change the lan#
		    if hpvmnet -C -S ${vfrom} -n ${to#lan} ; then
			state=boot
		    else
			log "Error: Cannot create vswitch ${vto} on interface ${to}"
		    fi
		fi
	    fi
	    ;;
	    (restore)
	    log "Info: Restoring vswitch ${vfrom} to interface ${from}"
	    if hpvmnet -c -S ${vfrom} -n ${from#lan} ; then
		state=boot
	    else
		log "Error: Cannot restore vswitch ${vfrom} to interface ${from}"
		state=read
	    fi
	    ;;
	    (boot)
	    if ifconfig_status ${from} = ${ipto} && ! ${ipmismatch}; then
		# This is unexpected and means the IP address is back on the original interface
		log "Warn: IP Address mis-match : ${ipto} found on interface ${from} expected ${to}"
		ipmismatch=true
		state=read
	    else
		if vswitch_status ${vfrom} = Down ; then
		    if hpvmnet -b -S ${vfrom} ; then
			if ! ${ipmismatch} ; then
			    log "Info: Moved vswitch ${vfrom} from interface ${from} to ${to}"
			fi
		    else
			log "Error: Cannot boot vswitch ${vfrom}"
			
		    fi
		    state=read
		else
		    state=create
		fi
	    fi
	    ;;
	    (reset)
	    if hpvmnet -F -r -S ${vfrom} ; then
		log "Info: Restarting vswitch ${vfrom}"
	    else
		log "Error: Cannot restart vswitch ${vto}"
	    fi
	    state=read
	    ;;
	esac
    done
    print "This function should not return"
    return ${error}
}

##########################
function start_vswitchmon
##########################
{
    ${DEBUG} && set -x
    # If Servicegurad is installed and at least one package references hpvm then start the vswitch monitor
    if [[ -x /usr/sbin/cmviewcl ]] && grep -q hpvm /etc/cmcluster/*/* 2>/dev/null ; then
	if [[ -x ${COMMAND} ]] ; then
	    ${COMMAND} cmcld </dev/null >/dev/null 2>>${LOGFILE} &
	    echo ${!} >${PIDFILE}
	    ${COMMAND} syslog </dev/null >/dev/null 2>>${SLOGFILE} &
	    echo ${!} >>${PIDFILE}
	    exit 4
	else
	    log "Error: Failed to start ${COMMAND}"
	    exit 1
	fi
    else
	exit 2
    fi
}

##########################
function halt_vswitchmon
##########################
{
    ${DEBUG} && set -x
    typeset pid
    for pid in $(<${PIDFILE}) ; do
	if ps -f -p ${pid} | grep -q ${CMD} ; then
	    kill ${pid} `ps -ef | awk '$3==pid{print $2}' pid=${pid}`	
	    sleep 1
	fi
	if ps -f -p ${pid} | grep -q ${CMD} ; then
	    kill -9 ${pid} `ps -ef | awk '$3==pid{print $2}' pid=${pid}`	
	fi
    done
}

#############
# Main script
#############

case ${1} in

    start_msg)
	echo "Start HP Virtual Machine ServiceGuard Toolkit."
	;;

    stop_msg)
	echo "Stop HP Virtual Machine ServiceGuard Toolkit."
	;;

    start)
	start_vswitchmon
	;;
    stop)
	halt_vswitchmon
	;;
    restart)
	halt_vswitchmon
	start_vswitchmon
	;;
    cmcld)
        trap '/usr/bin/logger -t "${CMD}[${$}]" "Info : Exiting..."' EXIT
	cmcld_monitor
	;;
    syslog)
	syslog_monitor
	;;
    *)
        echo "usage: ${CMD} {start|stop|restart}"
        ;;
esac

exit 0


