#! /bin/ksh

# @(#)oracle_db_restart.sho	1.26 99/04/30 SMI
# Copyright 04/30/99 Sun Microsystems, Inc.  All Rights Reserved.
#
# oracle_db_restart <parent_process_id> <instance> - script for internal use by
#    the HA DBMS fault	monitor to restart the database it is monitoring.
#
# Environment:
# HA_ENV - name of HA environment file
# HA_METASETSERVE - list of the meta hosts to run on the local host
#


# Copyright 03/30/99 Sun Microsystems, Inc.  All Rights Reserved.
# @(#)oracle_boiler	1.31 99/03/30 SMI

# begin of common ha-dbms boilerplate

# remember our name
argv0=`basename $0`

# Get the BASEDIR and PRODUCTDIR settings from the installed pkgs
_basedir=`pkgparam SUNWscor BASEDIR 2>/dev/null`
_productdir=`pkgparam SUNWscor PRODUCTDIR 2>/dev/null`
_basedir=${_basedir:=""}
_productdir=${_productdir:="SUNWcluster"}

LOGGER=/usr/bin/logger
PATH=${_basedir}/${_productdir}/bin:${_basedir}/${_productdir}/ha/oracle:${PATH}
export PATH
HA_FILES=/etc/${_basedir}/SUNWscor; export HA_FILES
HA_VAR=/var/${_basedir}/SUNWscor; export HA_VAR

# include HA utilities library
. dbms_utilities
if [ $? -ne 0 ]; then
	$LOGGER -p local7.err -t "$HA_SLOGTAG" "$argv0: Cannot find HA utilities library"
	exit 1
fi

HA_CLUSTER=$CLUSTNAME; export HA_CLUSTER

# some default files and locations
# don't move this up - it depends on HA_FILES, which gets set above
HA_DATABASES=haoracle_databases
HA_DB_SUPPORT=${HA_FILES}/haoracle_support; export HA_DB_SUPPORT
ds=oracle

PREFIX="SUNWcluster.ha.${ds}"
HA_FM_NAME="fault_mon"

# verify that we have the haoracle_support file
if [ ! -r $HA_DB_SUPPORT ] ; then
  logerr "4000" \
	"file ${HA_DB_SUPPORT} does not exist or is not readable!"
  exit 2
fi


# talk_start ... - echo the args, run them, and evaluate return value
talk_start() {
  	logprint "$$: $*"
  	if $* ; then
    		return 0
  	else
    		logprint "$$: $* ... failed"
    		return 1
  	fi
}


# talk_start_bg ... - print the args, then run them in the background
talk_start_bg() {
  	logprint "$$: $*"
  	$* &
  	}


# get_pid [ -u userid ] pattern - find the process id of a running program
# if called with "-u userid", only process for that user will be considered
get_pid() {
	if [ "$1" = "-u" ] ; then
		ps_args="-f -u $2"
		shift
		shift
	else
		ps_args="-ef"
	fi
	PID=`/usr/bin/ps $ps_args | grep "\<$*\>" | nawk -v pat="$*" '
 BEGIN { 
   search_pat = substr(pat, 0, 79)
   }
 { if ( match($0, search_pat) )
     if ( ! match($0, "nawk -v pat=") )
       print $2
  }
'`
}


# kill_proc pattern - find and terminate a process
kill_proc() {
  	logprint "Killing $*..." 
  	get_pid $*
  	if [ "$PID" ] ; then
    		for p in ${PID} ; do
      			logprint "Killing process id $p"
      			kill $p
    		done
    		echo
  	else
    		logprint "process \"$*\" could not be located..." 
  	fi
}

# read_ha_databases instance - find an entry in the HA_DATABASES file,
# 	parse it apart, and return in variables. Assumes that oracle_home
#	is set!
read_ha_databases() {
	conf_line=$(get_instance "${ds}" "$1")
        set_inst_name $1

	if [ "$conf_line" = "" ] ; then
		logerr "4010" "$1 missing from HA ORACLE CCD!"
		return 1
	fi
        on_off_mode=`echo "$conf_line" | cut -s -f 1`
	logical_host=`echo "$conf_line" | cut -s -f 3`
	poll_cycle=`echo "$conf_line" | cut -s -f 4`
	connect_cycle=`echo "$conf_line" | cut -s -f 5`
	timeout=`echo "$conf_line" | cut -s -f 6`
	restart_delay=`echo "$conf_line" | cut -s -f 7`
	db_login=`echo "$conf_line" | cut -s -f 8`
	init_ora=`echo "$conf_line" | cut -s -f 9`
        listener_name=`echo "$conf_line" | cut -s -f 10`

        set_logical_host $logical_host
	return 0
}

# find_oracle instance - finds and sets various Oracle related variables:
#	ORACLE_HOME SQLDBA PFILE LD_LIBRARY_PATH
# in case of a problem, it returns with an empty ORACLE_HOME variable

find_oracle() {

	typeset my_node
	typeset physical_hosts

  	ORATAB=/var/opt/oracle/oratab

  	ORACLE_HOME=""
	SQLDBA=""
        read_ha_databases $1
        if [ $? -ne 0 ]; then
                return 1
        fi
        my_node=`uname -n`
        physical_hosts=$(haget -f physical_hosts -h $logical_host | tr '\012' ' ')
        is_member "$my_node" "$physical_hosts"
        if [ $? -ne 0 ] ; then
                return 1
        fi


	if oratab_line=`grep "^[	 ]*$1:" $ORATAB` ; then
		oracle_home=`echo $oratab_line | awk -F: '{print $2}' -`
		if [ -d $oracle_home ] && [ -n "`disk_mounted $1`" ] ; then
			if [ ! -f $oracle_home/orainst/RELVER ] ; then
				export ORACLE_HOME=$oracle_home
				if [ -f $oracle_home/bin/svrmgrl ] ; then

	ora_version=`$oracle_home/bin/svrmgrl command=exit |awk '/PL\/SQL (Release|Version)/ {substr($3,1,3) ; print substr($3,1,3)} '`

				elif [ -f $oracle_home/bin/sqldba ] ; then

	ora_version=`$ORACLE_HOME/bin/sqldba command=exit | awk '/SQL\*DBA: (Release|Version)/ {split($3, V, ".") ; print V[1]}'`

				else logerr "4031" \
					    "Check Oracle installation"

				fi
                        ora_majversion=`echo $ora_version | cut -d. -f1`
				if [ $ora_majversion -lt 8 ] ; then
				logerr "4032" \
					"Release Version missing. Check Oracle installation"
					exit 1;
				fi
			else
			ora_version=`grep RELEASE_VERSION $oracle_home/orainst/RELVER | cut -d= -f2` 

			fi

			if [ "$ora_version" = "" ] ; then
				logerr "4030" \
	"RELEASE_VERSION missing from RELVER file"
				exit 1
			fi

                        ora_majversion=`echo $ora_version | cut -d. -f1`
                        if [ $ora_majversion -eq 8 ];then
                                SQLDBA="${oracle_home}/bin/svrmgrl"
                        else
				ora_subversion=`echo $ora_version | cut -d. -f2`
				ora_rel=`echo $ora_version | cut -d. -f3`
				if [ "$ora_rel" = "" ] ; then
					ora_rel=0
				fi

				# check if the oracle version is supported
				# The versions we will support are:  7.3.[>=2] ,
				# 7.2.[>=3] , and 7.1.[>=6].
				if [ $ora_subversion -eq 3 -a $ora_rel -lt 2 -o \
			     		$ora_subversion -eq 2 -a $ora_rel -lt 3 -o \
			     		$ora_subversion -eq 1 -a $ora_rel -lt 6 ] ; then
					logerr "4040" \
						"Oracle $ora_version not supported!"
					exit 1;
				fi
	
				# release 7.3 use svrmgrl to connect to the instance
				if [ $ora_subversion -ge 3 ] ; then
					SQLDBA="${oracle_home}/bin/svrmgrl"
				else
					SQLDBA="${oracle_home}/bin/sqldba"
				fi
                        fi

			if [ -x ${SQLDBA} ] ; then
				read_ha_databases $1
				ORACLE_HOME="$oracle_home"
				PFILE="$init_ora"
			else
				logerr "4060" \
				"${SQLDBA} does not exist or is not executable!"
			fi
		fi
	else
		logerr "4070" "Database '$1' not found in ${ORATAB}"
	fi
	LD_LIBRARY_PATH=${ORACLE_HOME}/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
    	export ORACLE_HOME SQLDBA PFILE LD_LIBRARY_PATH
}

make_rpc_call() {
  	logprint "Calling $3 for instance $2 on host $1..."
  	ha_dbms_call $1 $2 $3 
  	}


get_remote_host(){
	get_diskgroups $1 $2
        RSHHOST=""
        for X in `haget  -f private_links -h $HA_REMOTEHOST` ; do
          net_pinghost $X > /dev/null 2>&1
          if [ $? -eq 0 ] ; then
                RSHHOST=$X
                export RSHHOST
                return 0
          fi
        done
        return 1
        }


#end of common ha-dbms boiler plate
#include_boiler

prog="${HA_FM_NAME}"

if [ $# -ne 2 ] ; then
  	logerr "${prog}.4007" "usage: $argv0 <parent_process_id> <instance_name>"
  	exit 2
fi

# startup_oracle: db_owner oracle_home sid 

PPID=$1
ORACLE_SID=$2 
export ORACLE_SID
find_oracle $ORACLE_SID
oracle_owner=`ls -ld ${ORACLE_HOME} | nawk '{print $3}'`

# copy the RELVER file to be used by fault monitor, especially
# when oracle binaries are installed on the logical host,
# then RELVER need to be copied to the private disk

        #LPID="`getpids tnslsnr`"
        #if [ "${LPID}" = "" ] ; then
	export LISTENER_NAME=${listener_name:="LISTENER"}
/usr/bin/ps -e -u $oracle_owner -o args | grep -w "tnslsnr $LISTENER_NAME " | grep -v "grep" > /dev/null
    if [ $? -ne 0 ]; then
       lognotice "${prog}.2000" "starting up SQL*Net V2 listener"
       su  $oracle_owner -c sh << EOF > /dev/console 2>&1
 	 	LD_LIBRARY_PATH=$LD_LIBRARY_PATH
		export LD_LIBRARY_PATH
		$ORACLE_HOME/bin/lsnrctl start $LISTENER_NAME & 
EOF
    fi

#------ end of starting up listener ---------

# Did we find the instance?
if [ "$ORACLE_HOME" != "" ] && [ -n "`disk_mounted $ORACLE_SID`" ] ; then
    	oracle_owner=`ls -ld ${ORACLE_HOME} | nawk '{print $3}'`
    	# check for clean shutdown
    	if [ -f ${ORACLE_HOME}/dbs/sgadef${ORACLE_SID}.dbf -o \
	     -f ${ORACLE_HOME}/dbs/sgadef${ORACLE_SID}.ora ] ; then

      		lognotice "${prog}.2010" \
			"\"${ORACLE_SID}\" possibly left running when system went down (system crash?)"
su $oracle_owner -c sh << EOF
		LD_LIBRARY_PATH=$LD_LIBRARY_PATH
		export LD_LIBRARY_PATH
      		echo "connect internal
shutdown abort" | ${SQLDBA}
EOF
      		if [ $? -ne 0 ] ; then
			logerr "${prog}.4017" \
			 "shutdown abort failed for \"${ORACLE_SID}\" - notify Database Administrator"
			logerr  "${prog}.4027" \
			"Oracle database \"${ORACLE_SID}\" NOT started"
			exit 1
      		fi
    	fi

      	if [ -r "$PFILE" ] ; then
		# make sure fault monitoring did not get stopped in the meantime
		if `kill -0 $PPID > /dev/null` ; then
			lognotice "${prog}.2020" \
				"Starting up instance $ORACLE_SID PFILE=$PFILE"
su $oracle_owner -c sh << EOF
			LD_LIBRARY_PATH=$LD_LIBRARY_PATH
			export LD_LIBRARY_PATH
		      	echo "connect internal
startup PFILE=$PFILE" | ${SQLDBA}
EOF
      			if [ $? -ne 0 ] ; then
				logerr "${prog}.4027" \
					"Oracle database \"${ORACLE_SID}\" NOT started"
      			fi
		else
			lognotice "${prog}.2030" \
				"Re-start aborted because fault monitor terminated"
		fi
	else
		logerr "${prog}.4047" \
			"Oracle parameter file $PFILE does not exist or is not readable!"
	fi
	  
else
    	logerr "${prog}.4027" "Oracle database \"${ORACLE_SID}\" NOT started"
fi


