#!/bin/bash
# Start/stop/restart the Parallels dispatcher daemon:
#
# chkconfig:   345 60 25
# description: Parallels dispatcher daemon
#

export PATH="/sbin:/usr/sbin:/usr/local/sbin:$PATH"
SERVICE_NAME='parallels-server'
DISPD_NAME='/usr/sbin/prl_disp_service'
DISPD64_NAME='/usr/sbin/prl_disp_service64'
PID_FILE='/var/run/prl_disp_service.pid'
WD_PID_FILE='/var/run/prl_disp_service_watchdog.pid'
LIB_FILE=''
INITD_FUNCTIONS_FILE='/etc/rc.d/init.d/functions'
LOG_FILE=/var/log/parallels.log

LIB_DIR="/usr/lib"
LIB_DIR_32="/usr/lib32"
LIB_DIR_64="/usr/lib64"
LIBEXEC_DIR="/usr/libexec"

BUSED_MNT="/buse"

FLOCK_MNT="/dev/prldnd"
FLOCK_DIR="/tmp/prldnd"
DSP_SHUTDOWN_OPTS=

# Increase max open files limit
ulimit -n 102400

for lib in $LIB_DIR $LIB_DIR_32 $LIB_DIR_64; do
	if [ -d "$lib/$SERVICE_NAME/scripts" ]; then
		LIB_DIR=$lib
		break
	fi
done

if [ -h $DISPD_NAME ]; then
	export PARALLELS_VM="$LIBEXEC_DIR"
else
	export PARALLELS_VM="$LIB_DIR/$SERVICE_NAME"
fi

SCRIPTS="$LIB_DIR/$SERVICE_NAME/scripts"
export PARALLELS_SCRIPTS="$SCRIPTS"
PRL_XCONF="$SCRIPTS/parallels-xconfig"

if [ "x${SERVICE_NAME}" = "xparallels-workstation" ]; then
	DSPD_CONFIG="/etc/parallels/dispatcher.workstation.xml"
elif [ "x${SERVICE_NAME}" = "xparallels-desktop" ]; then
	DSPD_CONFIG="/etc/parallels/dispatcher.desktop.xml"
else
	DSPD_CONFIG="/etc/parallels/dispatcher.xml"
fi

LOCK_FILE=
if [ -d '/var/lock' ]; then
	[ ! -d '/var/lock/subsys' ] && mkdir '/var/lock/subsys'
	LOCK_FILE="/var/lock/subsys/${SERVICE_NAME}"
fi

# FIXME:
# 1. Use options from /etc/sysconfig/parallels
# 2. Get rid of --mode server sign
OPTIONS='--mode server'

# Watchdog parameters:
#  We allow to restart dispatcher if it crashed not more than MAX_NUM_CRASHES
#  times in a last period of time MAX_CRASH_PERIOD
MAX_NUM_CRASHES=5
MAX_CRASH_PERIOD=$((60 * 60 * 24 * 30)) # 30 days in seconds

retcode=0

status() {
	if [ ! -s "$PID_FILE" ]; then
		perror "${SERVICE_NAME} is stopped"
		return 1
	fi

	pid="$(head -n1 "$PID_FILE")"

	if [ ! -r "/proc/$pid" ]; then
		perror "${SERVICE_NAME} is not running, but pid file exists"
		return 1
	fi

	echo "${SERVICE_NAME} (pid ${pid}) is running..."
	return 0
}

success() {
	echo -n " OK"
}

failure() {
	echo -n " FAILURE"
}

perror() {
	echo "$*" 1>&2
}

prl_log_message() {
	[ ! -f "$LOG_FILE" ] && touch "$LOG_FILE" && chmod 666 "$LOG_FILE"
	echo "`date +'%m-%d %T'`       $*" >>"$LOG_FILE"
}

if [ -f ${INITD_FUNCTIONS_FILE} ]; then
	. ${INITD_FUNCTIONS_FILE}
fi

LIB_FILE="$SCRIPTS/functions"
if [ -s "${LIB_FILE}" ]; then
	. "${LIB_FILE}"
else
	perror
	failure
	perror "ERROR while loading Parallels library"
	perror "Please reinstall Parallels Server"
	perror
	exit 1
fi

check_retcode() {
	[ "x${1}" = "x0" ] && success || failure
	echo
}

applesmc_mod="applesmc"
apple_detect="/usr/sbin/acpi_hdr_dump"

applesmc_module_load() {
	# Check for Apple hardware and module existence
	[ -f "$apple_detect" ] && \
			 "$apple_detect" "/proc/acpi/dsdt" | grep -iq "apple" 2>/dev/null
	if [ $? -eq 0 ] && [ -f /lib/modules/$(uname -r)/kernel/drivers/hwmon/"$applesmc_mod".ko ]; then
		modprobe "$applesmc_mod" >/dev/null 2>&1 || perror "Could not load applesmc module."
	fi
}

applesmc_module_unload() {
	# Check module is loaded
	lsmod | grep -q "$applesmc_mod" 2>/dev/null
	if [ $? -eq 0 ]; then
		modprobe -r "$applesmc_mod" >/dev/null 2>&1 || perror "Could not unload applesmc module."
	fi
}

vz_modules_load() {
	# Check if vz and psbm installed
	if [ -f /etc/init.d/vz ] && [ -f /etc/parallels-release ]; then
		/etc/init.d/vz init
		modprobe bridge >/dev/null 2>&1
	fi
}

function mount_vz()
{
	if [ -x /etc/init.d/vz ]; then
		/etc/init.d/vz vzmount 2>/dev/null
	fi
}

mount_pfcache() {
	if [ -x /etc/init.d/vz ]; then
		/etc/init.d/vz pfcachemount 2>/dev/null
	fi
}

parallels_modules_load() {
	echo -n '    Loading Parallels kernel modules:'

	if [ "x${SERVICE_NAME}" = "xparallels-server" ]; then
		# kmod_load contains exit inside, so do workaround
		exit() { return $1; }
	fi

	kmod_load
	_retcode=$?

	[ "x${SERVICE_NAME}" = "xparallels-server" ] && unset exit

	check_retcode $_retcode

	if [ "x${_retcode}" != "x0" ]; then
		perror
		perror "Could not load the kernel modules."
		if [ "x${SERVICE_NAME}" != "xparallels-server" ]; then
			perror "Please, run $SCRIPTS/process-kmods.sh script with root privelegies."
		fi
		perror
	fi

	[ "x${_retcode}" != "x0" -a "x${SERVICE_NAME}" != "xparallels-server" ] && exit ${_retcode}

	return $_retcode
}

parallels_modules_unload() {
	echo -n '    Unloading Parallels kernel modules:'
	kmod_unload
	_retcode=$?
	check_retcode $_retcode
	[ "x${_retcode}" != "x0" ] && exit ${_retcode}

	return $_retcode
}

HDIR="/dev/hugetlbfs"
mount_hugetlbfs() {
	mkdir -p "$HDIR"
	mount -t hugetlbfs hugetlbfs "$HDIR" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		perror "Could not mount hugetlbfs to $HDIR"
		return 1
	fi
	mkdir -p "${HDIR}/parallels"
}

umount_hugetlbfs() {
	mount | grep -qs "$HDIR"
	[ $? -ne 0 ] && return 0
	umount "$HDIR" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		perror "Could not umount $HDIR"
		return 1
	fi
}

mount_bused() {
	[ ! -d $BUSED_MNT ] && mkdir -p $BUSED_MNT
	mount | grep -qs "$BUSED_MNT"
	[ $? -eq 0 ] && return 0
	mount $BUSED_MNT > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		perror "Could not mount bused to $BUSED_MNT"
		return 1
	fi
}

umount_bused() {
	umount "$BUSED_MNT" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		perror "Could not umount $BUSED_MNT"
		return 1
	fi
}

mount_flock() {
	lsmod | grep -qs prl_flock || return 0
	mkdir -p "$FLOCK_MNT" "$FLOCK_DIR" > /dev/null 2>&1
	chmod a+w "$FLOCK_DIR"

	mount none -t prl_flock "$FLOCK_MNT" -o source="$FLOCK_DIR" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		perror "Could not mount prl_flock to $FLOCK_MNT"
		return 1
	fi
}

umount_flock() {
	mount | grep -qs "${FLOCK_MNT##*/}"
	[ $? -ne 0 ] && return 0
	umount "$FLOCK_MNT" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		perror "Could not umount $FLOCK_MNT"
		return 1
	fi

	rmdir "$FLOCK_MNT" "$FLOCK_DIR" > /dev/null 2>&1 || true
}

run_dispatcher() {
	test "$(uname -m)" = 'x86_64' && test -x "${DISPD64_NAME}" &&
		run_dispd_path=$DISPD64_NAME ||
		run_dispd_path=$DISPD_NAME
	${run_dispd_path} ${OPTIONS} --pidfile "${PID_FILE}" >/dev/null 2>&1
	return $?
}


run_watchdog() {
	prl_log_message "watchdog: starting"
	cd /

	# start watching
	crash_ts_list=
	while true; do
		dsp_crash=1
		if [ -s "${PID_FILE}" ]; then
			pid_file=$(cat "${PID_FILE}" 2>/dev/null)
			[ -n "${pid_file}" ] && ! kill -0 "${pid_file}" >/dev/null 2>&1 && [ "${pid_file}" == "$(cat "${PID_FILE}" 2>/dev/null)" ] && dsp_crash=0
		fi
		if [ ${dsp_crash} -ne 0 ]; then
			sleep 60
			continue
		fi
		# timestamp of current processed crash
		this_crash_ts=`date +%s`
		prl_log_message "watchdog: prl_disp_service crash detected"

		# drop crashes from list which are older then defined period
		if [ -n "$crash_ts_list" ]; then
			new_crash_ts_list=
			IFS=$'\n'
			for ts in $crash_ts_list; do
				if [ $(($this_crash_ts - $ts)) -lt $MAX_CRASH_PERIOD ]; then
					new_crash_ts_list=${new_crash_ts_list}${new_crash_ts_list:+$'\n'}${ts}
				fi
			done
			unset IFS
			crash_ts_list=$new_crash_ts_list
		fi

		crash_ts_list=${crash_ts_list}${crash_ts_list:+$'\n'}${this_crash_ts}
		num_crashes=`echo "$crash_ts_list" | wc -l`
		if [ $num_crashes -gt $MAX_NUM_CRASHES ]; then
			prl_log_message "watchdog: crash throttle limit" \
				"(${MAX_NUM_CRASHES} times / ${MAX_CRASH_PERIOD} sec)" \
				"is reached. Exit"
			break
		fi

		prl_log_message "watchdog: restarting prl_disp_service"
		run_dispatcher
		retcode=$?
		[ $retcode -ne 0 ] &&
			prl_log_message "watchdog: failed to run dispatcher, code = $retcode"
	done
}


parallels_start() {

	# Kill PW 2.2 DHCP server
	ps -A | grep -q prl_dhcpd.bin
	if [ $? -eq 0 ]; then
		kill `pidof prl_dhcpd.bin`
		[ $? -ne 0 ] && echo 'Could not kill prl_dhcpd.bin process'
	fi

	vz_modules_load

	test -s "${PID_FILE}" && test -r "/proc/$(cat ${PID_FILE})" && exit
	echo 'Starting Parallels services'

	parallels_modules_load
	applesmc_module_load

	mount_hugetlbfs
	mount_flock
	mount_bused
	mount_vz
	mount_pfcache

	echo -n '    Starting Parallels network daemon:'
	network_start >/dev/null 2>&1
	retcode=$?
	check_retcode $retcode

	# error in starting network service is fatal
	[ "x${retcode}" != "x0" ] && exit ${retcode}

	echo -n '    Starting Parallels dispatcher daemon:'
	run_dispatcher
	retcode=$?
	[ "x${LOCK_FILE}" != "x" -a "x${retcode}" = "x0" ] && touch "${LOCK_FILE}"
	check_retcode $retcode
	[ "x${retcode}" != "x0" ] && exit ${retcode}

	# Run dispatcher' watchdog if only it is not running already
	pid_file=$(cat "${WD_PID_FILE}" 2>/dev/null)
	if [ -z "${pid_file}" ] || ! kill -0 "${pid_file}" >/dev/null 2>&1; then
		run_watchdog </dev/null >/dev/null 2>&1 &
		echo $! >"$WD_PID_FILE"
	fi

	# Patch xorg.conf according to set of not-assigned video cards
	${PRL_XCONF}

	# Reconfig DNS server for bind vnic interfaces
	which rndc >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		rndc reconfig
		[ $? -ne 0 ] && prl_log_message "'rndc reconfig' failed"
	else
		prl_log_message "'rndc' is missing. DNS server won't bind vnic interfaces."
	fi
}

parallels_stop() {
	echo 'Stopping Parallels services'

	# Kill and cleanup dispatcher's watchdog
	if [ -s "${WD_PID_FILE}" ]; then
		kill $(cat "${WD_PID_FILE}") >/dev/null 2>&1
		rm -f "${WD_PID_FILE}"
	fi

	if [ -s "${PID_FILE}" ]; then
		echo -n "    Stopping Parallels dispatcher daemon:"
		pid="$(head -n1 "${PID_FILE}")"

		/usr/bin/prlsrvctl shutdown --force $DSP_SHUTDOWN_OPTS > /dev/null 2>&1
		retcode=$?

		time_to_wait=999999
		sleep_time=1
		if [ -r "${DSPD_CONFIG}" ]; then
			config_field='VmTimeoutOnShutdown'
			time_to_wait=$(cat "${DSPD_CONFIG}" |
				grep $config_field | head -n1 |
				awk -v FS="<${config_field}>" '{print $2}' |
				awk -v FS="</${config_field}>" '{print $1}')
		fi

		# give dispatcher some time to deinitialize himself
		let "time_to_wait += 10"
		
		while kill -0 $pid 2> /dev/null && [ $time_to_wait -gt 0 ]; do
			sleep $sleep_time
			let "time_to_wait -= $sleep_time"
		done

		if kill -0 $pid 2> /dev/null; then
			kill -9 "$pid" 2>/dev/null
			retcode=9
		fi

		[ -f "${PID_FILE}" ] && rm -f "${PID_FILE}"

		check_retcode $retcode
		if [ "x${retcode}" = "x9" ]; then
			msg='  Parallels dispatcher killed'
			perror "${msg}"
			echo "${msg}" >>"${LOG_FILE}"
		fi
	else
		perror "    Parallels dispatcher daemon is not running"
	fi

	echo -n '    Stopping Parallels networking:'
	network_stop >/dev/null 2>&1
	retcode=$?
	check_retcode $retcode

	applesmc_module_unload
	umount_bused
	umount_flock
	umount_hugetlbfs
	parallels_modules_unload
	[ "x${retcode}" = "x0" ] && retcode=$?

	[ "x${retcode}" = "x0" ] && rm -f "${LOCK_FILE}"
}

case "${1}" in
	start)
		parallels_start
		;;
	stop)
		parallels_stop
		;;
	restart)
		parallels_stop
		parallels_start
		;;
	condrestart)
		status -p $PID_FILE $SERVICE_NAME >/dev/null 2>&1
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			if grep -q pram /proc/filesystems; then
				DSP_SHUTDOWN_OPTS='--suspend-vm-to-pram'
			fi
			parallels_stop
			parallels_start
		elif [ $RETVAL -eq 2 ]; then
			parallels_start
		fi
		retcode=0;
		;;
	status)
		status -p $PID_FILE  $SERVICE_NAME
		retcode=$?
		;;
	*)
		echo "Usage: ${0} start|stop|restart|status"
		retcode=1
		;;
esac
exit $retcode

