Last active
June 9, 2017 13:37
-
-
Save JoshCooley/6665e33cc1b8833ffc785747fd0654ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# app-name daemon | |
# chkconfig: 345 20 80 | |
# description: app-name daemon | |
# processname: process_name | |
# This init.d script makes twp assumptions | |
# 1) The script is run by root. Only root has the rights to su to the RUNTIME_USER. | |
# 2) The RUNTIME_USER a system user. Any user should work, so long as they have permissions to the project files. | |
NAME="app-name" | |
DESC="app-name daemon" | |
RUNTIME_USER="username" | |
SRC_PATH="/working/directory/for/app-name" | |
START_CMD="/path/to/executable --argument1 --argument2" | |
RELOAD_CMD="/path/to/executable --argument1 --argument2" | |
PROCMATCH="searchable process string" | |
PID="$(pgrep -f "${PROCMATCH}")" | |
case "$1" in | |
start) | |
if [[ ! $(id -u) -eq 0 ]]; then | |
echo "The ${NAME} service must be started as root!" | |
exit 1 | |
fi | |
if [[ "${PID}" ]]; then | |
echo "${NAME} already running, PID: ${PID}" | |
else | |
printf "%-40s\n" "Starting ${NAME}..." | |
su ${RUNTIME_USER} bash -c "cd ${SRC_PATH}; ${START_CMD}" | |
PID="$(pgrep -f "${PROCMATCH}")" | |
if [[ "${PID}" ]]; then | |
echo "${NAME} running, PID: ${PID}" | |
else | |
printf "-40%s\n" "Unable to start ${NAME}" | |
exit 1 | |
fi | |
fi | |
;; | |
reload) | |
if [[ ! $(id -u) -eq 0 ]]; then | |
echo "The ${NAME} service must be reloaded as root!" | |
exit 1 | |
fi | |
else | |
printf "%-40s\n" "Reloading ${NAME}..." | |
su ${RUNTIME_USER} bash -c "${RELOAD_CMD}" | |
if [[ $? -eq 0 ]]; then | |
echo "${NAME} reloaded" | |
else | |
printf "-40%s\n" "Unable to reload ${NAME}" | |
exit 1 | |
fi | |
fi | |
;; | |
status) | |
printf "%-40s\n" "Checking ${NAME}..." | |
if [[ "${PID}" ]]; then | |
echo "${NAME} running, PID: ${PID}" | |
else | |
printf "%-40s\n" "Service not running" | |
exit 1 | |
fi | |
;; | |
stop) | |
if [[ ! $(id -u) -eq 0 ]]; then | |
echo "The ${NAME} service must be stopped as root!" | |
exit 1 | |
fi | |
printf "%-40s\n" "Stopping ${NAME}, PID: ${PID}" | |
kill "${PID}" | |
if [[ $(pgrep -f "${PROCMATCH}") ]]; then | |
printf "%-40s" "${NAME} still running. Attempting hard stop." | |
kill -9 "${PID}" | |
if [[ $(pgrep -f "${PROCMATCH}") ]]; then | |
printf "%-40s\n" "Unable to stop ${NAME}" | |
else | |
printf "%-40s\n" "${NAME} stopped" | |
fi | |
else | |
printf "%-40s\n" "${NAME} stopped" | |
fi | |
;; | |
restart) | |
$0 stop | |
$0 start | |
;; | |
*) | |
echo "Usage: $0 {status|start|stop|reload|restart}" | |
exit 1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment