punktdateien/bash/jobrunner/daemon.sh

68 lines
1.6 KiB
Bash
Executable file

#!/bin/bash
# jeremystartm's jobrunner
# Logging functions
function log() {
echo "${*}"
echo "${*}" >> "/tmp/jobrunner/jobrunner.log"
}
function logcmd() {
log ":: Execute: ${*}"
${*} &>> "/tmp/jobrunner/jobrunner.log"
}
# Set default timeout
[[ -z "${JOBRUNNER_TIMEOUT}" ]] && export "JOBRUNNER_TIMEOUT=0.5s"
# Create runtime directory
if [ -a "/tmp/jobrunner/" ] && [ ! -d "/tmp/jobrunner/" ]; then
echo ":: Error: \"/tmp/jobrunner/\" is not a directory, aborting."
else
echo ":: Creating runtime directory"
mkdir -p "/tmp/jobrunner/"
echo "" > /tmp/jobrunner/jobrunner.{cmd,log}
fi
# Check for PID file
if [ -f "/tmp/jobrunner/jobrunner.pid" ]; then
log ":: Error: The jobrunner daemon is already running."
log " If you think that this is an error, remove"
log " \"/tmp/jobrunner/jobrunner.pid\"."
exit 1
fi
# Write PID file
log ":: Writing PID"
echo "$$" > "/tmp/jobrunner/jobrunner.pid"
log ":: Started jobrunner daemon"
# Enter loop
while true; do
# Create jobrunner runtime directory if missing
if [ ! -d "/tmp/jobrunner/" ]; then
logcmd mkdir -p "/tmp/jobrunner/"
echo "$$" > "/tmp/jobrunner/jobrunner.pid"
fi
if [ -f "/tmp/jobrunner/jobrunner.cmd" ]; then
log "Executing command"
# Read command file
JOBRUNNER_COMMAND="$(cat "/tmp/jobrunner/jobrunner.cmd")"
logcmd rm -rf "/tmp/jobrunner/jobrunner.cmd"
# Check if contains exit action
if [ "${JOBRUNNER_COMMAND}" == "EXIT" ]; then
log "Exiting, as requested"
logcmd rm -rf "/tmp/jobrunner/"
exit 0
fi
# Execute command in subprocess
bash -c "${JOBRUNNER_COMMAND}" &
fi
# Sleep specified amount
sleep "${JOBRUNNER_TIMEOUT}"
done