#!/bin/bash
#
# Helper script to start, stop, and interact with the WebObs Scheduler.
#

# How many time to wait for the process to exit after sending it the TERM
# signal (see man timeout(1) for details).
WAIT_TIMEOUT=20s


# Load the 'woconf' function
. /etc/webobs.d/../CODE/shells/wolib.bash
# Load configuration from WEBOBS.rc as WO__* environment variables.
woconf 'WO__'
# Load configuration from file $WEBOBS{CONF_SCHEDULER} as SC__* environment
# variables.
woconf 'SC__' 'CONF_SCHEDULER'


DAEMON_SCRIPT=scheduler.pl
PID_FILE="${WO__ROOT_LOGS}/${DAEMON_SCRIPT%%.*}.pid"

savedpid=$(cat $PID_FILE 2>/dev/null)
if [[ -n $savedpid ]] && kill -0 $savedpid 2> /dev/null; then
	# A PID was saved and the corresponding process exists
	if ps -o cmd --no-headers -p $savedpid | grep -q "\b$DAEMON_SCRIPT\b"; then
		running=1
	else
		rm -f "$PID_FILE"
		echo "Warning: PID file references PID $savedpid" \
			"but this process does not seem to be running" \
			"'$DAEMON_SCRIPT' and was deleted."
		running=0
	fi
else
	# PID file is missing or the referenced process is not alive (or not ours)
	# Delete any stale PID file to ensure the daemon can start.
	rm -f "$PID_FILE"
	running=0
fi

holdon="Connecting to scheduler..."

case "$1" in

	start)
		if [[ $running -eq 1 ]]; then
			echo "Scheduler already running with PID $savedpid"
			exit 1
		fi
		cd /etc/webobs.d/../CODE/cgi-bin
		if [ -n "${SC__ERROR_FILE}" ]; then
			echo "--- Scheduler started $(date +'%F %T')" >> $SC__ERROR_FILE
			perl $DAEMON_SCRIPT $SC__CMD_OPTS 2>> $SC__ERROR_FILE &
			bg_pid=$!
		else
			perl $DAEMON_SCRIPT $SC__CMD_OPTS &
			bg_pid=$!
		fi
		# Make the pid file available before exiting (required for systemd support)
		echo $bg_pid > "$PID_FILE"
		;;

	stop|terminate|kill)
		# Exit with 0 if not running
		# (this allows the command to be used by systemd as 'ExecStop=')
		if [[ $running -ne 1 ]]; then
			echo "Scheduler is stopped."
			exit 0
		fi
		;;&  # continue testing other patterns

	status|ps|qs|runq|jobq|verbose|quiet|stop|pause|resume|flog|submit|killjob|enq|deq)
		if [[ $running -ne 1 ]]; then
			echo "Error: scheduler is not running."
			exit 1;
		fi
		listening=$({ netstat -uln 2> /dev/null || ss -uln; } | grep -c ":${SC__PORT}\b" 2>/dev/null)
		if [[ ${listening} -ne 1 ]]; then
			echo "Error: scheduler is not listening on UDP port ${SC__PORT}."
			exit 1;
		fi
		;;&  # Continue testing other patterns

	status)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd stat"'
		;;

	ps)
		ps -p $savedpid -osid --no-headers | xargs ps -H -o pid,pgrp,etime,pcpu,pmem,vsize,cmd -s
		;;

	qs)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd qs"'
		;;

	runq)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd runq"'
		;;

	jobq)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd jobq"'
		;;

	verbose)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd verbose"'
		;;

	quiet)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd quiet"'
		;;

	stop)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd stop"'
		;;

	pause)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd pause"'
		;;

	resume)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd resume"'
		;;

	flog)
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl 'msg=>"cmd flog"'
		;;

	submit)
		shift
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl "msg=>\"job $@\""
		;;

	killjob)
		shift
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl "msg=>\"killjob $@\""
		;;

	enq)
		shift
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl "msg=>\"enq $@\""
		;;

	deq)
		shift
		echo $holdon
		perl /etc/webobs.d/../CODE/cgi-bin/wsudp.pl "msg=>\"deq $@\""
		;;

	kill)
		kill -9 $savedpid
		rm -f "$PID_FILE"
		;;

	terminate)
		echo "shutdown requested: sending SIGTERM to pid $savedpid."
		if kill -TERM $savedpid; then
			timeout $WAIT_TIMEOUT sh -c "while kill -0 $savedpid 2> /dev/null; do sleep 1; done"
			rc=$?
			if [[ $rc -eq 0 ]]; then
				echo "Scheduler has exited."
			elif [[ $rc -eq 124 ]]; then
				echo "warning: scheduler has not exited after $WAIT_TIMEOUT."
			else
				echo "error while waiting for the scheduler to exit."
			fi
		else
			echo "error sending signal to $savedpid: unable to stop the scheduler."
		fi
		;;

	*)
		echo "Usage: $0 {enq|deq|flog|jobq|terminate|kill|pause|ps|qs|quiet|resume|runq|start|status|stop|submit|killjob|verbose}"
		echo "       start          start, if not already active"
		echo "       stop           stop, $DAEMON_SCRIPT will wait for active kids to end"
		echo "       pause          hold execution (suspend jobs processing)"
		echo "       resume         resume execution"
		echo "       terminate      request immediate exit, killing any running jobs"
		echo "       kill           force immediate exit, really not recommended"
		echo "       verbose        log verbosity"
		echo "       quiet          log verbosity"
		echo "       status         display status/indicators/settings"
		echo "       qs             display summary internal queues (jobq,runq,*miss,enqs)"
		echo "       jobq           display jobQ"
		echo "       runq           display runQ"
		echo "       ps             display executing processes (active kids trees)"
		echo "       flog           force log backup and cleanup"
		echo "       enq            enq (lock) scheduler's resource(s): enq {resource | resource1+...+resourceN}"
		echo "       deq            deq (free) scheduler's resource(s): deq {resource | resource1+...+resourceN}"
		echo "       submit         place a job on the jobQ, requiring additional arg:"
		echo "                      1) jid=n   where n is the job's id from the jobs definition table"
		echo "                   or 2) keyword:value{,keyword:value,...}   where"
		echo "                         keyword in [XEQ1,XEQ2,XEQ3,MAXSYSLOAD,LOGPATH,RES,UID]\n"
		echo "       killjob        kill a job process, requiring additional arg: kid=. Note that"
		echo "                      job outputs and temporary files might remain and must be checked.\n"
		exit 1
esac

