deployd/interpreter/extensions/daemon
Arija A. 42cd6b7787
Add more security checks
Signed-off-by: Arija A. <ari@ari.lt>
2025-07-21 16:40:18 +03:00

76 lines
2 KiB
Bash

#!/bin/sh
# daemon_trystop <name>
# Stops the daemon by reading its PID file, sends SIGTERM, waits, then SIGKILL if needed.
daemon_trystop() {
daemon_name="$1"
[ -z "$daemon_name" ] && return 1
pidfile="/tmp/.deployd-daemon-$(echo "$daemon_name" | sha1sum | cut -d ' ' -f 1).pid"
if [ ! -f "$pidfile" ]; then
info "[daemon_trystop] PID file not found: $pidfile"
return 0
fi
pid="$(cat "$pidfile")"
if [ -z "$pid" ] || ! kill -0 "$pid" 2>/dev/null; then
info "[daemon_trystop] No running process with PID $pid"
rm -f "$pidfile"
return 0
fi
info "[daemon_trystop] Sending TERM to PID $pid"
kill "$pid"
# Wait up to 10s for process to exit
idx=0
while kill -0 "$pid" 2>/dev/null && [ $idx -lt 10 ]; do
sleep 1
idx=$((idx + 1))
done
if kill -0 "$pid" 2>/dev/null; then
info "[daemon_trystop] Process did not stop, sending KILL"
kill -9 "$pid"
else
info "[daemon_trystop] Process $pid stopped gracefully"
fi
rm -f "$pidfile"
}
# daemon_exec <name> [args...]
# Starts the daemon specified by <name> with the given command-line [args...].
# Attempts to start the daemon up to 5 times if it fails to launch successfully.
daemon_exec() {
daemon_name="$1"
pidfile="/tmp/.deployd-daemon-$(echo "$daemon_name" | sha1sum | cut -d ' ' -f 1).pid"
daemon_trystop "$daemon_name"
max_retries=5
attempt=0
while [ $attempt -lt $max_retries ]; do
setsid --fork /bin/sh -c '
"$@" &
echo "$!" >'"$pidfile"'
' "$@"
sleep 2
if [ -f "$pidfile" ]; then
pid="$(cat "$pidfile")"
if kill -0 "$pid" 2>/dev/null; then
return 0
fi
fi
attempt="$((attempt + 1))"
error "Daemon '$daemon_name' failed to start (attempt $attempt/$max_retries), retrying..."
sleep 1
done
error "Daemon '$daemon_name' failed to start after $max_retries attempts."
return 1
}