Files
box/bin/swarm-worker-supervise.sh
T

91 lines
2.7 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
#
# swarm-worker-supervise.sh — tmux supervisor for the swarm worker daemon.
#
# Manages a detached tmux session named "swarm-worker" that runs the worker
# main loop and logs to logs/swarm-worker.log.
#
# The worker itself is a PLACEHOLDER until bin/swarm_worker/daemon.py lands.
# When it does, update WORKER_CMD and WORKER_MATCH below.
#
# Usage: swarm-worker-supervise.sh {start|stop|restart|status}
#
set -euo pipefail
SESSION="swarm-worker"
SOCKET_PATH="/tmp/tmux-muse.sock"
LOG_DIR="/home/super/Projects/NetVM/logs"
LOG_FILE="${LOG_DIR}/swarm-worker.log"
# Placeholder worker. Replace with:
# WORKER_CMD="python3 /home/super/Projects/NetVM/bin/swarm_worker/daemon.py"
# when the real daemon exists. WORKER_MATCH must uniquely match the worker
# process command line; the [a] bracket trick keeps pgrep from matching itself.
WORKER_CMD="python3 /home/super/Projects/NetVM/bin/swarm_worker/daemon.py"
WORKER_MATCH='swarm_worker/daemon.[p]y'
session_exists() {
tmux -S "$SOCKET_PATH" has-session -t "$SESSION" 2>/dev/null
}
worker_alive() {
pgrep -f "$WORKER_MATCH" >/dev/null 2>&1
}
do_start() {
mkdir -p "$LOG_DIR"
if session_exists; then
echo "already running (tmux session $SESSION exists on $SOCKET_PATH)"
return 0
fi
tmux -S "$SOCKET_PATH" new-session -d -s "$SESSION" "$WORKER_CMD >>\"$LOG_FILE\" 2>&1"
sleep 1
if worker_alive; then
echo "started tmux session $SESSION on $SOCKET_PATH (logging to $LOG_FILE)"
else
echo "WARNING: session $SESSION created on $SOCKET_PATH but worker process not detected yet"
fi
}
do_stop() {
local stopped=0
if session_exists; then
tmux -S "$SOCKET_PATH" kill-session -t "$SESSION" 2>/dev/null || true
stopped=1
fi
# Also clean up accidental session on default socket if present
if tmux has-session -t "$SESSION" 2>/dev/null; then
tmux kill-session -t "$SESSION" 2>/dev/null || true
stopped=1
fi
if [ "$stopped" -eq 1 ]; then
echo "stopped tmux session $SESSION"
else
echo "not running (no tmux session $SESSION)"
fi
}
do_status() {
if ! session_exists; then
echo "STOPPED - no tmux session '$SESSION'"
return 1
fi
if worker_alive; then
echo "ALIVE - tmux session '$SESSION' exists and worker process is running"
return 0
fi
echo "DEGRADED - tmux session '$SESSION' exists but no worker process found"
return 2
}
case "${1:-}" in
start) do_start ;;
stop) do_stop ;;
restart) do_stop; sleep 1; do_start ;;
status) do_status ;;
*)
echo "Usage: $(basename "$0") {start|stop|restart|status}" >&2
exit 2
;;
esac