#!/sbin/openrc-run description="Dead‑man switch: ping a host, restart a service if ping fails" # The services you want to restart SERVICES="wg-quick.wg0 wg-quick.wg1" PING_HOST="10.70.0.2" LOG="/var/log/tunnel-watchdog.log" FAIL_COUNT_LIMIT=5 PING_TIMEOUT=1 PING_COUNT=1 restart_service() { for i in ${SERVICES} do einfo "Restarting $i" /etc/init.d/$i restart done } depend() { need net } start() { ebegin "Starting tunnel-watchdog daemon" echo $(date)" Starting tunnel watchdog on IP $PING_HOST" >> ${LOG} while : ; do # Perform a quick ping. -q quiet, -c N packets, -W T timeout if ! ping -q -c ${PING_COUNT} -W ${PING_TIMEOUT} ${PING_HOST} >/dev/null 2>&1; then fail_count=$((fail_count + 1)) echo $(date)" Ping to ${PING_HOST} failed (attempt ${fail_count})" >> ${LOG} else fail_count=0 fi # If we hit the threshold, restart if [ "${fail_count}" -ge "${FAIL_COUNT_LIMIT}" ]; then echo $(date)" Consecutive failures reached ${FAIL_COUNT_LIMIT}: restarting ${SERVICES}" >> ${LOG} restart_service fail_count=0 fi # Wait a bit before the next check sleep 5 done & PID=$! echo ${PID} > /var/run/tunnel-watchdog.pid eend 0 } stop() { ebegin "Stopping ping‑restart daemon" if [ -f /var/run/tunnel-watchdog.pid ]; then PID=$(cat /var/run/tunnel-watchdog.pid) kill -9 "${PID}" 2>/dev/null rm /var/run/tunnel-watchdog.pid else eend 255 fi eend 0 }