Skip to content

Instantly share code, notes, and snippets.

@jglenn9k
Created November 24, 2013 21:52
Show Gist options
  • Save jglenn9k/7632861 to your computer and use it in GitHub Desktop.
Save jglenn9k/7632861 to your computer and use it in GitHub Desktop.
NodeJS Supervisor Start/Stop Script
#!/bin/sh
#---------------------------------
# nodesupervisor Start/Stop Script
#---------------------------------
#---------------------------------
# chkconfig: 2345 99 99
# description: NodeJS Supervisor
# --------------------------------
RUNAS='nodejs'
SCRIPT=${0##*/}
SU=/sbin/runuser
WHOAMI=$(/usr/bin/whoami)
SYSCONFIG=/etc/sysconfig/nodesupervisor
SUPERVISOR=/usr/local/bin/supervisor
NPM=/usr/local/bin/npm
NODEJS=/usr/local/bin/node
ACTION=${1}
LOGDIR=/var/log/nodejs
TEE=/usr/bin/tee
KILLALL=/usr/bin/killall
REV=/usr/bin/rev
CUT=/usr/bin/cut
# export NODE_PATH=/usr/local/node/node-v0.10.17/lib/node_modules
# If this script is run as part of a runlevel change or as the root user,
# invoke it again as the proper user then exit.
if [[ ${SCRIPT} =~ ^[SK][0-9][0-9] ]]; then
[[ ${SCRIPT} =~ ^S[0-9][0-9] ]] && ACTION=start
[[ ${SCRIPT} =~ ^K[0-9][0-9] ]] && ACTION=stop
$(readlink -f ${0}) ${ACTION}
exit $?
elif [[ ${WHOAMI} == 'root' ]]; then
continue
# ${SU} - ${RUNAS} -c "${0} $@"
# exit $?
elif [[ ${WHOAMI} != 'nodejs' ]]; then
echo "This app intends to be run as the nodejs user or as root (where it automatically switches to run as nodejs)"
exit 1
fi
# --------------------------------
function start () {
# Read The sysconfig file for node apps to start and start them
while read line; do
APPLICATION=${line}
LOGFILE=$(awk -F/ '{ print $(NF-2)"-"$NF}' <<< "${APPLICATION}").log
# Dirty hack that does the same as removing $NF with awk but keeps my field separators in place
WORKINGDIR=$(${REV} <<< "${APPLICATION}" | ${CUT} -d/ -f2- | ${REV})
APPLOG=${LOGDIR}/${LOGFILE}
if [ -e ${APPLICATION} ]; then
cd ${WORKINGDIR}
${NPM} install -d >> ${APPLOG} 2>&1
### FIXME: Only do SU - RUNAS if not nodejs
${SU} - ${RUNAS} -c "${SUPERVISOR} -w ${WORKINGDIR} ${APPLICATION} 2>&1 | ${TEE} -a ${APPLOG} > /dev/null" &
else
echo Error: ${APPLICATION} does not exist.
fi
done < ${SYSCONFIG}
}
function stop () {
# I know a bad hack but it works
${KILLALL} ${NODEJS}
}
function restart () {
stop
start
}
function usage () {
echo "Usage: $0 (start|stop|restart)"
}
case ${ACTION} in
start )
start ;;
stop )
stop ;;
restart )
restart ;;
* )
usage ;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment