#!/usr/bin/env bash # Aggressive WireGuard keepalive watchdog for physical guest (wg-dy / wg-dy-cn). # Handshake alone is not enough — also probe peer reachability and bounce fast. set -euo pipefail STATE_DIR="${WIREGUARD_WATCH_STATE_DIR:-/run}" WIREGUARD_WATCH_INTERVAL="${WIREGUARD_WATCH_INTERVAL:-15}" WIREGUARD_STALE_SECONDS="${WIREGUARD_STALE_SECONDS:-90}" WIREGUARD_RESTART_COOLDOWN="${WIREGUARD_RESTART_COOLDOWN:-60}" WIREGUARD_PING_TIMEOUT="${WIREGUARD_PING_TIMEOUT:-2}" WIREGUARD_PING_COUNT="${WIREGUARD_PING_COUNT:-2}" # Physical dual-edge: watch BOTH tunnels WIREGUARD_WATCH_IFACES="${WIREGUARD_WATCH_IFACES:-wg-dy wg-dy-cn}" # iface -> expected peer address on that /24 (for ping probe) peer_ip_for() { case "$1" in wg-dy) echo "10.8.0.1" ;; wg-dy-cn) echo "10.9.0.1" ;; *) echo "" ;; esac } log() { printf '[wireguard-watch] %s\n' "$*" } positive_int() { case "${1:-}" in ''|*[!0-9]*) return 1 ;; *) [ "$1" -gt 0 ] ;; esac } normalize() { positive_int "$WIREGUARD_WATCH_INTERVAL" || WIREGUARD_WATCH_INTERVAL=15 positive_int "$WIREGUARD_STALE_SECONDS" || WIREGUARD_STALE_SECONDS=90 positive_int "$WIREGUARD_RESTART_COOLDOWN" || WIREGUARD_RESTART_COOLDOWN=60 positive_int "$WIREGUARD_PING_TIMEOUT" || WIREGUARD_PING_TIMEOUT=2 positive_int "$WIREGUARD_PING_COUNT" || WIREGUARD_PING_COUNT=2 if [ "$WIREGUARD_WATCH_INTERVAL" -lt 10 ]; then WIREGUARD_WATCH_INTERVAL=10; fi # Allow aggressive stale threshold (min 45s) — NAT mappings die silently if [ "$WIREGUARD_STALE_SECONDS" -lt 45 ]; then WIREGUARD_STALE_SECONDS=45; fi if [ "$WIREGUARD_RESTART_COOLDOWN" -lt 30 ]; then WIREGUARD_RESTART_COOLDOWN=30; fi } interface_has_keepalive_peer() { local iface="$1" wg show "$iface" dump 2>/dev/null | awk ' NR > 1 { ka = (NF >= 9) ? $9 : $8 if (ka != "" && ka != "off" && ka != "0") found = 1 } END { exit found ? 0 : 1 } ' } # Ensure PersistentKeepalive is live on peers (runtime + conf when possible). ensure_keepalive() { local iface="$1" conf="/etc/wireguard/${1}.conf" peer # Runtime: set KA=15 on every peer if missing/zero while read -r peer; do [ -n "$peer" ] || continue wg set "$iface" peer "$peer" persistent-keepalive 15 2>/dev/null || true done < <(wg show "$iface" peers 2>/dev/null || true) # Persist into conf so restarts keep it if [ -f "$conf" ] && ! grep -qE '^[[:space:]]*PersistentKeepalive[[:space:]]*=' "$conf"; then if grep -qE '^[[:space:]]*AllowedIPs[[:space:]]*=' "$conf"; then sed -i '/^[[:space:]]*AllowedIPs[[:space:]]*=/a PersistentKeepalive = 15' "$conf" 2>/dev/null || true else printf '\nPersistentKeepalive = 15\n' >>"$conf" 2>/dev/null || true fi elif [ -f "$conf" ]; then # Tighten existing keepalive to <=15 sed -i -E 's/^([[:space:]]*PersistentKeepalive[[:space:]]*=[[:space:]]*)[0-9]+/\115/' "$conf" 2>/dev/null || true fi } handshake_age_sec() { local iface="$1" now="$2" wg show "$iface" dump 2>/dev/null | awk -v now="$now" ' NR > 1 { latest = (NF >= 9) ? $6 : $5 if (latest == "" || latest+0 == 0) { print 999999; exit } age = now - latest if (age < 0) age = 0 print age+0 exit } END { if (NR <= 1) print 999999 } ' } peer_ping_ok() { local peer="$1" [ -n "$peer" ] || return 0 ping -c "$WIREGUARD_PING_COUNT" -W "$WIREGUARD_PING_TIMEOUT" "$peer" >/dev/null 2>&1 } http_probe_ok() { # Optional: curl peer:8014/api/health when probing wg-dy (app path) local iface="$1" case "$iface" in wg-dy) curl -sS -m 3 -o /dev/null -w '' http://10.8.0.1:8014/api/health 2>/dev/null && return 0 # Peer is hub; health is on THIS host — probe through tunnel from VPS perspective N/A. # Instead probe that we can reach the peer host at all via ICMP already. return 1 ;; *) return 1 ;; esac } restart_interface() { local iface="$1" # Template unit wg-quick@.service often won't show in list-unit-files for instances. if [ -f /lib/systemd/system/wg-quick@.service ] || [ -f /usr/lib/systemd/system/wg-quick@.service ] \ || systemctl cat "wg-quick@${iface}.service" >/dev/null 2>&1; then systemctl reset-failed "wg-quick@${iface}.service" >/dev/null 2>&1 || true if systemctl restart "wg-quick@${iface}.service"; then return 0 fi log "WARN: systemctl restart wg-quick@${iface} failed; falling back to wg-quick" fi if command -v wg-quick >/dev/null 2>&1 && [ -f "/etc/wireguard/${iface}.conf" ]; then wg-quick down "$iface" >/dev/null 2>&1 || true wg-quick up "$iface" else log "WARN: cannot restart $iface" return 1 fi } watch_once() { local now iface last_restart_var last_restart age peer reason command -v wg >/dev/null 2>&1 || return 0 command -v systemctl >/dev/null 2>&1 || return 0 now="$(date +%s)" for iface in $WIREGUARD_WATCH_IFACES; do [ -n "$iface" ] || continue if ! ip link show "$iface" >/dev/null 2>&1; then log "iface $iface missing — bringing up" restart_interface "$iface" || true continue fi ensure_keepalive "$iface" reason="" age="$(handshake_age_sec "$iface" "$now")" positive_int "$age" || age=999999 if [ "$age" -ge "$WIREGUARD_STALE_SECONDS" ]; then reason="handshake_stale age=${age}s" fi peer="$(peer_ip_for "$iface")" if [ -n "$peer" ] && ! peer_ping_ok "$peer"; then if [ -n "$reason" ]; then reason="${reason}+ping_fail:${peer}" else # Only bounce on ping fail if handshake is also aging (>45s) to avoid flap on brief loss if [ "$age" -ge 45 ]; then reason="ping_fail:${peer} age=${age}s" fi fi fi [ -n "$reason" ] || continue last_restart_var="$STATE_DIR/douyinweb-wireguard-watch-${iface}.last" last_restart="$(cat "$last_restart_var" 2>/dev/null || echo 0)" positive_int "$last_restart" || last_restart=0 if [ $((now - last_restart)) -lt "$WIREGUARD_RESTART_COOLDOWN" ]; then log "stale $iface ($reason) but cooldown $((now - last_restart))s < ${WIREGUARD_RESTART_COOLDOWN}s" continue fi log "Restarting $iface; $reason; threshold=${WIREGUARD_STALE_SECONDS}s" if restart_interface "$iface"; then mkdir -p "$STATE_DIR" 2>/dev/null || true date +%s >"$last_restart_var" sleep 2 ensure_keepalive "$iface" peer="$(peer_ip_for "$iface")" if [ -n "$peer" ]; then if peer_ping_ok "$peer"; then log "OK $iface peer $peer reachable after restart" else log "WARN $iface still cannot ping $peer after restart" fi fi else log "FAIL restart $iface" fi done } normalize if [ "${1:-}" = "once" ]; then watch_once exit 0 fi log "interval=${WIREGUARD_WATCH_INTERVAL}s stale=${WIREGUARD_STALE_SECONDS}s cooldown=${WIREGUARD_RESTART_COOLDOWN}s ifaces=${WIREGUARD_WATCH_IFACES}" while true; do watch_once || true sleep "$WIREGUARD_WATCH_INTERVAL" done