#! /usr/bin/ksh
#
# ident "@(#)oracle_listener_stop.ksh 1.7     00/03/01 SMI"
#
# Copyright (c) 1999-2000 by Sun Microsystems, Inc.
# All rights reserved.
#
# HA-Oracle STOP method
#
# RT: oracle_listener
#
# Parameters passed:  -R <resource name> -T <type> -G <group>
#
#
#! /usr/bin/ksh
#
# ident "@(#)dbms_lib.ksh 1.17     02/01/23 SMI"
#
# Copyright (c) 1999-2002 by Sun Microsystems, Inc.
# All rights reserved.
#
############################################################ 
#
# DBMS library
#
############################################################ 

set -ufp
MYDIR=`/bin/dirname $0`
BINDIR=`/bin/dirname $0`
ETCDIR="$BINDIR/../etc"
DEBUG_LEVEL=-1
unset PATH
export PATH="/bin:/usr/cluster/bin"
DEBUG_LOGFILE=""
DEBUG_LOG_SIZE=300000
ARGUMENTS="$0 ${@:-""}"
RESOURCE_NAME=""
RESOURCE_TYPE=""
RESOURCE_GROUP=""
SCLOGGER=/usr/cluster/lib/sc/scds_syslog

TRAPSIGNALS="TERM KILL"
trap "trap - $TRAPSIGNALS; /usr/bin/pkill -g $$;exit 1" $TRAPSIGNALS


#############################################################
# syslog_tag
#
#	prints syslog_tag as SC[pkg.method]: GROUP:RESOURCE
#
#############################################################
syslog_tag()
{
	print "SC[${pkg:-??}.${method:-??}]:${RESOURCE_GROUP:-??}:${RESOURCE_NAME:-??}" 
}

#############################################################
#  scds_syslog <priority> <formattext> <parameters> 
#############################################################

scds_syslog()
{
typeset priority=""
typeset msg_format=""
typeset tag=""
typeset msg

	$SCLOGGER "$@" & 

	while getopts :p:t:m: opt
	do
  	case $opt in
		p)      priority="$OPTARG";;
		t)      tag="$OPTARG";;
		m)      msg_format="$OPTARG";;
		*)	;;
  	esac
	done

	shift `expr $OPTIND - 1`

	msg=$(/usr/bin/printf "${msg_format}" ${@:-} )

	[ -z "${TRACE_INIT:-""}" ] && init_trace

	[ "${DEBUG_LOGFILE}"  != "/dev/console" ] && \
	    print -r -- "$(date '+%b %d %T') $tag: $msg" >> $DEBUG_LOGFILE
}

#############################################################
#  write_trace <text> <parameters> 
#   Other information: TAG format 
#############################################################

write_trace()
{
typeset msg_text=${1:-""}
typeset msg

shift

	msg=$(/usr/bin/printf "${msg_text}" ${@:-} )
	[ -z "${TRACE_INIT:-""}" ] && init_trace
	[ "${DEBUG_LOGFILE}"  != "/dev/console" ] && \
	    print -r -- "$(date '+%b %d %T') $(syslog_tag): $msg" >> $DEBUG_LOGFILE
}

#############################################################
#  read_arguments()
#  
#  Set Globals variables:
#     RESOURCE_NAME, RESOURCE_TYPE RESOURCE_GROUP
#
#############################################################
read_arguments()
{

typeset rc=0
typeset invalid_option=""
typeset save_opt=""
typeset save_optarg=""

while getopts :R:T:G: opt
do
  case $opt in
       R)      	RESOURCE_NAME="$OPTARG";;
       T)      	RESOURCE_TYPE="$OPTARG";;
       G)      	RESOURCE_GROUP="$OPTARG";;
       *)      	invalid_option="YES"; 
		save_opt="$opt"
		save_optarg="$OPTARG"
		 ;;
  esac
done

	if [ -z "$RESOURCE_NAME" \
		-o -z "$RESOURCE_TYPE" \
		-o -z "$RESOURCE_GROUP"  \
		-o -n "$invalid_option" ]; then

		scds_syslog -p error -t $(syslog_tag) -m \
	 		"Initialization failed. Invalid command line  %s %s" \
			"$save_optarg" "$save_opt"
		rc=1;
	fi
	
	return $rc

}

#############################################################
# check_resource_setup
#
#############################################################
check_resource_setup()
{
        if [ -z "$RESOURCE_NAME" \
                -o -z "$RESOURCE_TYPE" \
                -o -z "$RESOURCE_GROUP" ]; then
		return 1
	else
		return 0
	fi
}


#############################################################
# error_exit()
#
#############################################################
error_exit()
{
  typeset exit_code="${1:-0}"
  exit $exit_code
}

#############################################################
# extract_property_value()
#
#  For extended properties, API returns data type followed by value
#  This function discards first line (data type) and prints 
#	remaining lines.
#
#############################################################
extract_property_value()
{
	typeset type
	typeset value
	typeset rc=0
	
	read type 
	rc=$?
	[ $rc -ne 0 ] && return $rc

	while read value
	do
		print $value
	done
		
	rc=$?
	return $rc
}

#############################################################
# read_property_value()
#
#############################################################
read_property_value()
{

typeset api_command
typeset rc
typeset log_flag="YES"
typeset option_tag
typeset extension=""

	case "$1" in
		R_description| \
		Type| \
		On_off_switch| \
		Monitored_switch| \
		Resource_state| \
		Cheap_probe_interval| \
		Thorough_probe_interval| \
		Retry_count| \
		Retry_interval| \
		Failover_mode| \
		Resource_dependencies| \
		Resource_dependencies_weak| \
		Logical_hostnames_used| \
		Status| \
		START_TIMEOUT| \
		STOP_TIMEOUT| \
		PRIMARIES_CHANGED_TIMEOUT | \
		VALIDATE_TIMEOUT| \
		UPDATE_TIMEOUT| \
		INIT_TIMEOUT| \
		FINI_TIMEOUT| \
		BOOT_TIMEOUT| \
		MONITOR_START_TIMEOUT| \
		MONITOR_STOP_TIMEOUT| \
		MONITOR_CHECK_TIMEOUT| \
		Status_Node| \
		Resource_state_Node)
		option_tag="$1"
		extension=""
		;;
	DEBUG_LOGFILE| \
	DEBUG_LOG_SIZE| \
	DEBUG_LEVEL) 
		log_flag=""
		option_tag="Extension"
		extension="$*"
		;;
	*)
		option_tag="Extension"
		extension="$*"
		;;
	esac

	if [ -z "$extension" ]; then
		scha_resource_get -O $option_tag \
	 	-R "$RESOURCE_NAME" -G "$RESOURCE_GROUP"
	else
		scha_resource_get -O $option_tag \
		 -R "$RESOURCE_NAME" -G "$RESOURCE_GROUP" $extension \
		| extract_property_value
	fi

	rc=$?
	if [ $rc -ne 0 ]; then
                if [ "$log_flag" == "YES" ]; then
			scds_syslog -p error -t $(syslog_tag) -m \
                	    "Error (%s) when reading property %s." "$rc" "$1" 
		fi
	fi	
	return $rc
}

#############################################################
# check_user_env
#
#############################################################
check_user_env()
{
	typeset rc=0

        if [ -z "${USER_ENV:-""}" ]; then
		return $rc
	fi

	if [ ! -f "$USER_ENV" ]; then
		scds_syslog -p error -t $(syslog_tag) -m \
	 	    "file specified in USER_ENV parameter %s does not exist" \
		    $USER_ENV
		rc=1
        fi
	return $rc
}

#############################################################
# set_user_env
#
#############################################################
set_user_env()
{
        typeset param
        typeset val
	typeset aa_line

        [ -z "${USER_ENV:-""}" ] && return 0

	check_user_env || return $rc

        while read aa_line
        do
        	[ -z ${aa_line:-""} ] && continue

		if [[ "$aa_line" == \#* ]]; then
		  continue
		fi

                # Now ensure that the line read is of the form
                # VARIABLE=VALUE

                if [[ "$aa_line" != *\=* ]]; then
                        scds_syslog -p warning -t $(syslog_tag) -m \
                            "Incorrect syntax in the environment file %s. Ignoring %s"\
                            "${USER_ENV}" "${aa_line}"
                        continue
                fi

        	val="${aa_line##*=}"
        	param="${aa_line%%=*}"

		# Ensure that Variable is a valid KSH variable

		if [[ "$param" != @([A-Z]|[a-z]|_)*([A-Z]|[a-z]|[0-9]|_) ]];then
			scds_syslog -p warning -t $(syslog_tag) -m \
			    "Invalid variable name in the Environment file %s. \
Ignoring %s" "${USER_ENV}" "${aa_line}"
			continue
		fi

        	eval ${param}=\"${val}\"
		export $param
                TRACE_MESSAGE="Setting environment variable: %s=%s"
		write_trace "${TRACE_MESSAGE}" "${param}" "${val}"
	done < $USER_ENV

}

#############################################################
# init_trace()
#
#############################################################
init_trace()
{
	typeset debugdir

        [ ${DEBUG_LEVEL} -eq -1 ] && DEBUG_LEVEL=$(read_property_value DEBUG_LEVEL)

	[ -z "${DEBUG_LEVEL}" ] && DEBUG_LEVEL=0

	TRACE_INIT="done"

	if [ -z "${DEBUG_LOGFILE}" ]; then
		DEBUG_LOGFILE="/dev/console"
		return
	fi

	debugdir=$(/bin/dirname "${DEBUG_LOGFILE}") 

	[ -n "$debugdir" ] && /bin/mkdir -p "$debugdir"

	if [[ "$DEBUG_LOGFILE" == *\. ]];then
   		DEBUG_LOGFILE="${DEBUG_LOGFILE}${RESOURCE_NAME:-""}"
	fi

	[ -z "$DEBUG_LOG_SIZE" ] && DEBUG_LOG_SIZE=300000 

	touch $DEBUG_LOGFILE 2> /dev/null

       	exec 2>> $DEBUG_LOGFILE

	rotate_log 
}

#############################################################
# rotate_log()
#
#############################################################
rotate_log()
{
        typeset log_size=0

	[ ! -f "$DEBUG_LOGFILE" ] && return
	( 
        log_size=$(/bin/ls -l "$DEBUG_LOGFILE" | /bin/awk '{print $5}')
        [ $log_size -lt $DEBUG_LOG_SIZE ] && return

        [ -f ${DEBUG_LOGFILE}.1 ] &&  /bin/rm -f "${DEBUG_LOGFILE}.1"
        [ -f ${DEBUG_LOGFILE}.0 ] && /bin/mv ${DEBUG_LOGFILE}.0 ${DEBUG_LOGFILE}.1
        /bin/mv "${DEBUG_LOGFILE}" "${DEBUG_LOGFILE}.0"
        /bin/touch "${DEBUG_LOGFILE}"
	) &
}

#############################################################
# set_status
#   Sets resource status
#	Parameter 1: <status> (not validated)
#		 OK,  DEGRADED,  FAULTED, UNKNOWN, or OFFLINE. 
#	Parameter 2: <message> (optional)
#############################################################
set_status()
{
	typeset rstatus="${1:-UNKNOWN}"
	typeset rmsg=${2:-""}
	typeset prev_status

	prev_status=$(read_property_value Status)

	# WARNING: Assumption here is that all previous scha_resource_setstatus
	# commands did NOT use the -m option. If it was ever used, more
	# parsing of prev_status is required here
	
	if [ "$prev_status" = "$rstatus" ]; then
		return 0
	fi

	if [ -n "${rmsg}" ]; then
		scha_resource_setstatus -s $rstatus -m "$rmsg" \
			-R $RESOURCE_NAME -G $RESOURCE_GROUP
	else
		scha_resource_setstatus -s $rstatus \
			-R $RESOURCE_NAME -G $RESOURCE_GROUP
	fi
}

#############################################################
#
# hastorageplus_validation
#
# Arguments: Arguments to be passed to hasp_check program
# 
# This function checks if resource is dependent on SPlus resource and 
# state of SPlus resource.
#
# This function is expected to be called from validate or monitor_check
# methods, if some validations failed.
# 
# If this resource is dependent on SPlus resource, validations 
# are possible only on the node that has SPlus resource online.
# 
# return 0 - if resource depends on HAStoragePlus resource
#		and HASP resource is on-line on some other node
# 
#        1 - All other cases
# 
#############################################################

hastorageplus_validation() 
{
  	typeset rc=0

	#
	# hasp_check return codes 
	# 1 - Internal error
	#
	# 2 - No dependency on HASToragePlus resource
	#
	# 3 - One or more of the SUNW.HAStoragePlus resources
	#     that this resource depends on is in a different RG.
	#
	# 4 - One or more of the SUNW.HAStoragePlus resources
	#     that this resource depends on is not online anywhere.
	#
	# 5 - All the SUNW.HAStoragePlus resources that this 
	#     resource depends on are not online on this node. 
	#
	# 6 - All the SUNW.HAStoragePlus resources that this
	#     resource depends on are online on the local node. 	
	#


	if [ ! -f /usr/cluster/bin/hasp_check ]; then

		# hasp_check binary does not exist
		# return error
	
		return 1
	fi

	/usr/cluster/bin/hasp_check "$@"
 	hasp_status=$?
 
	case "$hasp_status" in
 
	   1)	rc=1
	   	scds_syslog -p error -t $(syslog_tag) -m \
	    	   "Error in hasp_check. Validation failed."
	   	;;
		   	
	   3)	rc=1
	   	scds_syslog -p error -t $(syslog_tag) -m \
	    	   "This resource depends on a HAStoragePlus resouce \
that is in a different Resource Group. This configuration is not supported." 
	   	;;

	   4)	rc=1
	   	scds_syslog -p error -t $(syslog_tag) -m \
	    	   "This resource depends on a HAStoragePlus resouce \
that is not online. Unable to perform validations."
	   	;;


	   5)	rc=0
	   	scds_syslog -p warning -t $(syslog_tag) -m \
		   "This resource depends on a HAStoragePlus resouce \
that is not online on this node. Ignoring validation errors." 
	   	;; 

	   # Return code 2, 6 or any other.
 	   *) 	rc=1;; 
	esac

	return $rc

}
#include_dbms_lib
#
#! /usr/bin/ksh
#
# ident "@(#)oracle_listener_lib.ksh 1.10     00/03/01 SMI"
#
# Copyright (c) 1999-2000 by Sun Microsystems, Inc.
# All rights reserved.
#
# HA-Oracle Library routines method
# 
# Parameters passed:  -R <resource name> -T <type> -G <group>
#
#
####################################################################
initialize()
{

	#
	# uncomment to turn on tracing in all functions
	# typeset -ft $(typeset +f)
	#

        pkg=SUNWscor.oracle_listener

	DEBUG_LOGFILE="/var/opt/SUNWscor/oracle_listener/message_log."

	DEBUG_LOG_SIZE=300000

	MONITOR_RETRY_COUNT=1

	MONITOR_RETRY_INTERVAL=5

	MONITOR_TAG_PREFIX=ORALSNR_MON

}

#############################################################
#
#############################################################
read_parameters()
{
	ORACLE_HOME=$(read_property_value ORACLE_HOME)

	LISTENER_NAME=$(read_property_value LISTENER_NAME)
 
	USER_ENV=$(read_property_value USER_ENV) 

	STOP_TIMEOUT=$(read_property_value STOP_TIMEOUT)
	[ -z "$STOP_TIMEOUT" ] && STOP_TIMEOUT=60 

	START_TIMEOUT=$(read_property_value START_TIMEOUT)
	[ -z "$START_TIMEOUT" ] && START_TIMEOUT=60 

	RETRY_COUNT=$(read_property_value Retry_count)
	[ -z "$RETRY_COUNT" ] && RETRY_COUNT=-1 

	RETRY_INTERVAL=$(read_property_value Retry_interval)
	[ -z "$RETRY_INTERVAL" ] && RETRY_INTERVAL=-1 

	THOROUGH_PROBE_INTERVAL=$(read_property_value Thorough_probe_interval)
	[ -z "$THOROUGH_PROBE_INTERVAL" ] && THOROUGH_PROBE_INTERVAL=30 
}

#############################################################
#
#############################################################
validate_parameters()
{
	if [ ! -d "$ORACLE_HOME" ]; then
		scds_syslog -p error -t $(syslog_tag) -m \
		    "Validation failed. ORACLE_HOME %s does not exist" \
		    $ORACLE_HOME
		return 1
	fi

	if [ ! -f "$ORACLE_HOME/bin/lsnrctl" ]; then
		scds_syslog -p error -t $(syslog_tag) -m \
		    "Validation failed. Listener binaries not found ORACLE_HOME=%s" \
		    $ORACLE_HOME
		return 1
	fi

        ORACLE_OWNER=$(/bin/ls -l ${ORACLE_HOME}/bin/lsnrctl | /bin/nawk '{print $3}')
	if [ -z "$LISTENER_NAME" ]; then
		scds_syslog -p error -t $(syslog_tag) -m \
		    "Validation failed. Listener_name not set"
		return 1
	fi

}

#############################################################
#
#############################################################
export_env()
{
	LD_LIBRARY_PATH=${ORACLE_HOME}/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
	export ORACLE_HOME LD_LIBRARY_PATH LISTENER_NAME USER_ENV 
}
		
#############################################################
#  Temporary routine
#############################################################
monitor_running()
{
	pmfadm -q ${MONITOR_TAG} 
	return $?
}
#############################################################
#
#############################################################
listener_running()
{
 typeset running
	running=$(/bin/ps -u $ORACLE_OWNER -o args | \
			/bin/grep tnslsnr | /bin/grep -w "${LISTENER_NAME} ")
                        
	if [ -n "$running" ]; then
		return 0
	fi

	return 1
}

#############################################################
#
#############################################################
startup_listener()
{
	typeset rc
	typeset timeout=${1:-0}

	listener_running 
	if [ $? -eq 0 ]; then
 		write_trace "listener %s is running. No need to start listener" \
		    "${LISTENER_NAME}"
		set_status OK
		return 0
	fi

	scds_syslog -p info -t $(syslog_tag) -m \
	    "Starting listener %s." \
            "${LISTENER_NAME}"

	export_env
	
	check_user_env	

	if [ $timeout -eq 0 ]; then
		su $ORACLE_OWNER -c "$BINDIR/oracle_listener_manage start" \
		>>  "$DEBUG_LOGFILE"
	else
		hatimerun -t $timeout \
		su $ORACLE_OWNER -c "$BINDIR/oracle_listener_manage start"  \
		>>  "$DEBUG_LOGFILE"
	fi

	# Sleep for some time. Listener process 'tnslsnr' gets started,
	# by lsnrctl, but may fail immediately if listener does not exist in 
	# listener.ora file
 
	sleep 3

	listener_running 
	rc=$?
	if [ $rc -ne 0 ]; then
		scds_syslog -p error -t $(syslog_tag) -m \
 		    "Failed to start listener %s." \
                    "${LISTENER_NAME}"
		set_status FAULTED
		return $rc
	else
		scds_syslog -p info -t $(syslog_tag) -m \
 		    "Listener %s started." \
                    "${LISTENER_NAME}"
		set_status OK
	fi

	return 0
}

#############################################################
#
#############################################################
shutdown_listener()
{
typeset -i immediate_timeout=0
typeset -i abort_timeout=0
typeset mode=${1:-"STOP"}
typeset rc=0

	set_status OFFLINE
	listener_running 
	if [ $? -ne 0 ]; then
 		write_trace "listener %s is not running." "${LISTENER_NAME}"
		return 0
	fi
 		
	scds_syslog -p info -t $(syslog_tag) -m \
	    "Stopping listener %s." \
            "${LISTENER_NAME}"

	export_env

	check_user_env

	if [ "$mode" = "STOP" ]; then 
		let "immediate_timeout = $STOP_TIMEOUT - $SECONDS - 6"
		[ $immediate_timeout -le 0 ] && immediate_timeout=2
		hatimerun -t $immediate_timeout \
	  	   su $ORACLE_OWNER -c "$BINDIR/oracle_listener_manage stop" \
			>>  "$DEBUG_LOGFILE"
		
		rc=$?
		sleep 3
		listener_running
		if [ $? -ne 0 ]; then
			scds_syslog -p info -t $(syslog_tag) -m \
			    "Listener %s stopped successfully" \
			    "${LISTENER_NAME}" 
			set_status OFFLINE
			return 0
		else
			scds_syslog -p warning -t $(syslog_tag) -m \
			    "Listener %s did not stop.(%s)" \
			    "${LISTENER_NAME}" $rc 
		fi
	fi
	
	write_trace "Killing listener %s" "${LISTENER_NAME}"
	$BINDIR/oracle_listener_manage kill >>  "$DEBUG_LOGFILE" 
	rc=$?
	sleep 3
	listener_running
	if [ $? -eq 0 ]; then
		scds_syslog -p error -t $(syslog_tag) -m \
		    "Failed to kill listener process for %s" \
		     "${LISTENER_NAME}" 
		rc=1
		set_status FAULTED
	fi
	return $rc
}

#############################################################
#
#############################################################

restart_listener()
{
	listener_running && shutdown_listener
	startup_listener $START_TIMEOUT
}

#############################################################
#
#############################################################
monitor_setup()
{
        MONITOR_TAG=${MONITOR_TAG_PREFIX}_${RESOURCE_NAME}
}

#include_listener_lib
#
#
method=stop
#############################################################
#
#############################################################
main()
{
	initialize

	read_arguments "${@:-}" || error_exit $?

	read_parameters

	set_status UNKNOWN

        validate_parameters || error_exit $?

	shutdown_listener 

	exit 0
 	
}

main "${@:-}"
