mirror of
https://github.com/obra/superpowers.git
synced 2026-06-12 05:39:05 +08:00
stop-server.sh read server.pid and SIGKILL'd that PID with no checks. After a
reboot or PID wraparound the pid file can point at an unrelated, live process —
which we would then kill.
Verify the PID is actually our server (a running 'node ... server.cjs') before
signalling it. If ownership can't be proven, fail closed: remove the stale pid
file and report {status: stale_pid} without killing anything. Real servers still
stop ({status: stopped}); a missing pid file still reports not_running.
Adds stop-server.test.sh covering: an unrelated reused PID is left alone, a real
server is stopped, and a missing pid file.
Refs #1703
75 lines
1.9 KiB
Bash
Executable File
75 lines
1.9 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Stop the brainstorm server and clean up
|
|
# Usage: stop-server.sh <session_dir>
|
|
#
|
|
# Kills the server process. Only deletes session directory if it's
|
|
# under /tmp (ephemeral). Persistent directories (.superpowers/) are
|
|
# kept so mockups can be reviewed later.
|
|
|
|
SESSION_DIR="$1"
|
|
|
|
if [[ -z "$SESSION_DIR" ]]; then
|
|
echo '{"error": "Usage: stop-server.sh <session_dir>"}'
|
|
exit 1
|
|
fi
|
|
|
|
STATE_DIR="${SESSION_DIR}/state"
|
|
PID_FILE="${STATE_DIR}/server.pid"
|
|
|
|
# Confirm a PID is actually our brainstorm server (node running server.cjs),
|
|
# not a reused/unrelated process whose PID was recycled into a stale pid file.
|
|
is_brainstorm_server() {
|
|
kill -0 "$1" 2>/dev/null || return 1
|
|
case "$(ps -p "$1" -o command= 2>/dev/null)" in
|
|
*node*server.cjs*) return 0 ;;
|
|
*) return 1 ;;
|
|
esac
|
|
}
|
|
|
|
if [[ -f "$PID_FILE" ]]; then
|
|
pid=$(cat "$PID_FILE")
|
|
|
|
# Refuse to signal a PID we can't prove is our server. A stale pid file may
|
|
# point at an unrelated process after a reboot/PID wraparound.
|
|
if ! is_brainstorm_server "$pid"; then
|
|
rm -f "$PID_FILE"
|
|
echo '{"status": "stale_pid"}'
|
|
exit 0
|
|
fi
|
|
|
|
# Try to stop gracefully, fallback to force if still alive
|
|
kill "$pid" 2>/dev/null || true
|
|
|
|
# Wait for graceful shutdown (up to ~2s)
|
|
for i in {1..20}; do
|
|
if ! kill -0 "$pid" 2>/dev/null; then
|
|
break
|
|
fi
|
|
sleep 0.1
|
|
done
|
|
|
|
# If still running, escalate to SIGKILL
|
|
if kill -0 "$pid" 2>/dev/null; then
|
|
kill -9 "$pid" 2>/dev/null || true
|
|
|
|
# Give SIGKILL a moment to take effect
|
|
sleep 0.1
|
|
fi
|
|
|
|
if kill -0 "$pid" 2>/dev/null; then
|
|
echo '{"status": "failed", "error": "process still running"}'
|
|
exit 1
|
|
fi
|
|
|
|
rm -f "$PID_FILE" "${STATE_DIR}/server.log"
|
|
|
|
# Only delete ephemeral /tmp directories
|
|
if [[ "$SESSION_DIR" == /tmp/* ]]; then
|
|
rm -rf "$SESSION_DIR"
|
|
fi
|
|
|
|
echo '{"status": "stopped"}'
|
|
else
|
|
echo '{"status": "not_running"}'
|
|
fi
|