ops: owner-wifi-stability.sh, Wi-Fi watchdog for rnr5090 (gateway ping, escalating recovery, failure snapshots in /run)

show | install | remove | status, --dry-run; optional --disable-powersave (+ --install-iw), --disable-aspm, --reboot-after-min.
Tested read-only on the server (show, install/remove --dry-run, run --dry-run --simulate-fail); install was not run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-03 00:02:20 +01:00
co-authored by Claude Sonnet 5.5
parent 44fb442f5a
commit e45bb83808
2 changed files with 518 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
# scripts/ops
Owner-run helpers for the 5090 server (`rnr5090`). Each script prints its usage when run without arguments.
## owner-wifi-stability.sh
The server has no free router port and runs on Wi-Fi only (MediaTek MT7925, `mt7925e`, `wlp9s0`, netplan + systemd-networkd +
`netplan-wpa-wlp9s0.service`). On 2026-11-02 the link went silent at about 21:35Z with no wpa_supplicant, networkd or kernel message
and never came back until a power cycle at 22:46Z. The script installs `leleka-wifi-watchdog`, a root loop service that pings the
gateway every 20 s and, after 3 failures in a row, recovers in escalating steps (L1 `ip link` down/up, L2 restart the supervisor and
`networkctl reconfigure`, L3 `modprobe -r/modprobe mt7925e`), logging to the journal and to `/run/leleka-wifi-watchdog/` (RAM). At
each failure it writes a snapshot (addresses, link counters, signal, PCIe ASPM state, last kernel lines, supervisor journal) to
`/run/leleka-wifi-watchdog/snapshots/`, so the next drop is diagnosable.
```
bash owner-wifi-stability.sh show # read-only: configuration found here and the install plan
bash owner-wifi-stability.sh install --dry-run # prints the plan, changes nothing
sudo bash owner-wifi-stability.sh install # watchdog only
sudo bash owner-wifi-stability.sh install --disable-powersave --install-iw # + Wi-Fi power save off (needs the iw package)
sudo bash owner-wifi-stability.sh install --disable-aspm # + mt7925e disable_aspm=1 (next module load)
sudo bash owner-wifi-stability.sh install --reboot-after-min 45 # + last resort reboot (kills GPU jobs)
bash owner-wifi-stability.sh status # counters, action log, snapshots
sudo bash owner-wifi-stability.sh remove
```
`install` never brings the link down and never touches sshd (22), the rescue sshd (2222, `rescue-sshd.sh`), docker or the GPU queue.
Do not run `install` with `--disable-aspm` and then reload the module over an SSH session that rides on the same Wi-Fi.
Test without changing anything (the loop only prints what it would do, probes and snapshots are read-only):
```
WD_SETTLE=1 bash owner-wifi-stability.sh run --dry-run --iface wlp9s0 --module mt7925e --simulate-fail 22 --interval 1 --max-loops 26
```
+485
View File
@@ -0,0 +1,485 @@
#!/usr/bin/env bash
# rnr5090: make the Wi-Fi link (MediaTek MT7925, driver mt7925e, interface wlp9s0) self-healing and make the next drop
# diagnosable. Owner-run: `show`, `status` and `--dry-run` need no root and change nothing; `install` and `remove` need root.
#
# bash owner-wifi-stability.sh show # read-only: how networking is configured here + what install would do
# sudo bash owner-wifi-stability.sh install # watchdog service only (the default, safest set)
# sudo bash owner-wifi-stability.sh install --disable-powersave --install-iw # + Wi-Fi power save off (needs the `iw` package)
# sudo bash owner-wifi-stability.sh install --disable-aspm # + mt7925e option disable_aspm=1 (next module load)
# sudo bash owner-wifi-stability.sh install --reboot-after-min 45 # + last resort: reboot after 45 min of dead link
# bash owner-wifi-stability.sh status # service state, counters, action log, snapshots (no root needed)
# sudo bash owner-wifi-stability.sh remove # stop and remove everything this script installed
# add --dry-run to install/remove to only print the actions; --iface IF to name another interface (default: first wireless one)
#
# What the installed service `leleka-wifi-watchdog` does (a loop, one probe every 20 s, root, no disk writes except the journal):
# probe : ping the default gateway of the Wi-Fi interface (1 packet, 2 s timeout).
# fail : 3 consecutive failures (about 60 s) = outage. A snapshot is written at the first failure and before every recovery step.
# steps : L1 `ip link set IF down/up`; (about 90 s later, if still dead) L2 restart the supervising daemon (here: netplan-wpa-IF.service,
# the wpa_supplicant of netplan; otherwise wpa_supplicant@IF, iwd or NetworkManager, whichever is active) and `networkctl
# reconfigure IF`; (again about 90 s later) L3 `modprobe -r mt7925e; modprobe mt7925e`, then restart the supervisor.
# After L3 it repeats L3 at most every 5 min. Every step is bounded by a timeout (a wedged driver cannot hang the loop).
# log : every action goes to the journal (`journalctl -u leleka-wifi-watchdog`) and to /run/leleka-wifi-watchdog/actions.log (RAM).
# state : /run/leleka-wifi-watchdog/{counters,state,actions.log,snapshots/*.txt} (RAM only, newest 20 snapshots, log trimmed at 256 KB).
# snapshot: ip -br a, routes, link counters, iw / nmcli / wpa_cli state if present, signal (wpa_cli signal_poll or iw station dump),
# PCIe ASPM and runtime-PM state, the last 30 kernel lines with mt7925|IF, supervisor and networkd journal, sshd listeners.
#
# Separate, clearly named options (all off by default):
# --disable-powersave the watchdog runs `iw dev IF set power_save off` at start, after every recovery step and every ~5 min if it
# finds it on. Needs `iw` (not installed on this server): add --install-iw to `apt-get install -y iw`.
# --disable-aspm writes /etc/modprobe.d/leleka-wifi-stability.conf: `options mt7925e disable_aspm=1`. Takes effect at the next
# load of the module (reboot, or the watchdog's L3). It does not change the running link.
# --reboot-after-min N after L3 has been tried and the link has been dead N minutes (N >= 30) run `systemctl reboot`; never before the
# machine has been up 15 min, so it cannot loop faster than every 30+ min. Kills running GPU jobs: think first.
# (The PCIe runtime PM of the card is already `on` = disabled here, so there is no flag for it.)
#
# Not touched, by design: sshd (port 22), the rescue sshd (port 2222, scripts/ops/rescue-sshd.sh, lives in /run/rescue), docker, the GPU
# queue. The watchdog only runs ip/networkctl/systemctl/modprobe/iw against the Wi-Fi interface, its supervisor and its kernel module.
#
# Testing without changing anything (the loop in dry mode only prints what it WOULD do; probes and snapshots are read-only):
# bash owner-wifi-stability.sh run --dry-run --iface wlp9s0 --module mt7925e --simulate-fail 8 --interval 1 --max-loops 12
set -uo pipefail
NAME=leleka-wifi-watchdog
BIN=/usr/local/sbin/$NAME
UNIT=/etc/systemd/system/$NAME.service
MODCONF=/etc/modprobe.d/leleka-wifi-stability.conf
STATE=/run/$NAME
SELF=$(readlink -f "${BASH_SOURCE[0]:-/nonexistent}" 2>/dev/null || true)
cmd=""; IFACE=""; MODULE=""; DRY=0
OPT_PS=0; OPT_IW=0; OPT_ASPM=0; OPT_REBOOT=0
INTERVAL=20; FAILS=3; MAX_LOOPS=0; SIM_FAIL=0; GW_OVERRIDE=""
usage() { sed -n '2,39p' "${BASH_SOURCE[0]:-$0}" 2>/dev/null | sed 's/^# \{0,1\}//'; }
die() { echo "owner-wifi-stability: $*" >&2; exit 2; }
isnum() { case "${1:-}" in ''|*[!0-9]*) return 1 ;; *) return 0 ;; esac; }
[ $# -gt 0 ] || { usage; exit 0; }
cmd=$1; shift
case "$cmd" in show|install|remove|status|run) ;; -h|--help|help) usage; exit 0 ;; *) die "unknown command: $cmd (show | install | remove | status)" ;; esac
while [ $# -gt 0 ]; do
case "$1" in
--iface) IFACE=${2:?interface name}; shift ;;
--module) MODULE=${2:?module name}; shift ;;
--dry-run) DRY=1 ;;
--disable-powersave) OPT_PS=1 ;;
--install-iw) OPT_IW=1 ;;
--disable-aspm) OPT_ASPM=1 ;;
--reboot-after-min) OPT_REBOOT=${2:?minutes}; shift ;;
--interval) INTERVAL=${2:?seconds}; shift ;;
--fails) FAILS=${2:?count}; shift ;;
--max-loops) MAX_LOOPS=${2:?count}; shift ;;
--simulate-fail) SIM_FAIL=${2:?count}; shift ;;
--gateway) GW_OVERRIDE=${2:?ip}; shift ;;
-h|--help) usage; exit 0 ;;
*) die "unknown argument: $1" ;;
esac
shift
done
for v in OPT_REBOOT INTERVAL FAILS MAX_LOOPS SIM_FAIL; do isnum "${!v}" || die "$v must be a number"; done
{ [ "$OPT_REBOOT" -eq 0 ] || [ "$OPT_REBOOT" -ge 30 ]; } || die "--reboot-after-min must be 0 (off) or >= 30"
{ [ "$FAILS" -ge 2 ] && [ "$FAILS" -le 10 ]; } || die "--fails must be 2..10"
{ [ "$INTERVAL" -ge 5 ] || [ "$DRY" = 1 ]; } || die "--interval must be >= 5 seconds"
if [ "$cmd" = run ] && [ "$DRY" = 0 ] && { [ "$SIM_FAIL" -gt 0 ] || [ "$MAX_LOOPS" -gt 0 ]; }; then die "--simulate-fail and --max-loops are for --dry-run only"; fi
say() { printf '%s\n' "$*"; }
now_iso() { date -u +%FT%TZ; }
need_root() { [ "$(id -u)" -eq 0 ] || { echo "run as root (sudo): $cmd changes the system" >&2; exit 1; }; }
# ------------------------------------------------------------------ detection
detect_iface() {
[ -n "$IFACE" ] && return 0
local d
for d in /sys/class/net/*/wireless; do [ -d "$d" ] && { IFACE=$(basename "$(dirname "$d")"); return 0; }; done
IFACE=wlp9s0
}
detect_hw() { # driver module and PCI address of the interface; kept from start so a removed module is still known
local dev=/sys/class/net/$IFACE/device
BDF=""; DRIVER=""
[ -e "$dev" ] && BDF=$(basename "$(readlink -f "$dev")")
[ -e "$dev/driver" ] && DRIVER=$(basename "$(readlink -f "$dev/driver")")
if [ -z "$MODULE" ] && [ -e "$dev/driver/module" ]; then MODULE=$(basename "$(readlink -f "$dev/driver/module")"); fi
return 0
}
unit_active() { systemctl is-active --quiet "$1" 2>/dev/null; }
supervisors() { # units that supervise the Wi-Fi association here, in order of preference (the first active one) + NetworkManager if active
if unit_active "netplan-wpa-$IFACE.service"; then say "netplan-wpa-$IFACE.service"
elif unit_active "wpa_supplicant@$IFACE.service"; then say "wpa_supplicant@$IFACE.service"
elif unit_active iwd.service; then say "iwd.service"
elif unit_active wpa_supplicant.service; then say "wpa_supplicant.service"
fi
if unit_active NetworkManager.service; then say "NetworkManager.service"; fi
}
gateway_of() { # prints "gw dev" ; prefers the default route of IFACE
local g
g=$(ip -4 route show default dev "$IFACE" 2>/dev/null | awk '{for(i=1;i<NF;i++) if($i=="via"){print $(i+1); exit}}')
if [ -n "$g" ]; then say "$g $IFACE"; return 0; fi
g=$(ip -4 route show default 2>/dev/null | awk '{for(i=1;i<NF;i++) if($i=="via"){print $(i+1); exit}}')
if [ -n "$g" ]; then say "$g other"; return 0; fi
return 1
}
# ------------------------------------------------------------------ show
cmd_show() {
detect_iface; detect_hw
say "== host =="; say "$(uname -n) kernel $(uname -r), $(now_iso), uptime $(uptime -p 2>/dev/null)"
say "== wireless interface =="
say "interface: $IFACE driver: ${DRIVER:-?} module: ${MODULE:-?} pci: ${BDF:-?}"
ip -br a 2>/dev/null | grep -E "^($IFACE|eno1|lo)\b" | sed 's/^/ /'
ip -4 route show default 2>/dev/null | sed 's/^/ route: /'
say "== stack =="
local u
for u in systemd-networkd NetworkManager wpa_supplicant "netplan-wpa-$IFACE" iwd systemd-resolved; do
printf ' %-28s %s\n' "$u" "$(systemctl is-active "$u" 2>/dev/null || true)"
done
say " netplan files: $(ls /etc/netplan 2>/dev/null | tr '\n' ' ') (contents not printed: they hold the passphrase)"
say " supervisor(s) the watchdog would restart at L2: $(supervisors | tr '\n' ' ')"
say " networkd view:"; networkctl status "$IFACE" --no-pager -n 0 2>/dev/null | grep -E "State:|Online|Address:|Gateway:|Wi-Fi access point|Driver" | sed 's/^ */ /'
local idx lease
idx=$(cat "/sys/class/net/$IFACE/ifindex" 2>/dev/null || true); lease=/run/systemd/netif/leases/$idx
if [ -r "$lease" ]; then say " DHCP lease: $(grep -E '^(T1|T2|LIFETIME)=' "$lease" | tr '\n' ' ')"; else say " DHCP lease: ($lease not readable; run as root to see T1/T2/LIFETIME)"; fi
say "== power / ASPM =="
if [ -n "$MODULE" ] && [ -d "/sys/module/$MODULE/parameters" ]; then
local p; for p in /sys/module/"$MODULE"/parameters/*; do say " module param $MODULE.$(basename "$p") = $(cat "$p" 2>/dev/null)"; done
fi
[ -n "$BDF" ] && {
say " pci runtime PM: control=$(cat /sys/bus/pci/devices/"$BDF"/power/control 2>/dev/null) status=$(cat /sys/bus/pci/devices/"$BDF"/power/runtime_status 2>/dev/null) l1_aspm=$(cat /sys/bus/pci/devices/"$BDF"/link/l1_aspm 2>/dev/null)"
if [ "$(id -u)" -eq 0 ] && command -v lspci >/dev/null; then lspci -vvs "$BDF" 2>/dev/null | grep -E 'LnkCtl:|L1SubCtl1' | sed 's/^[[:space:]]*/ lspci: /'; fi
}
say " pcie_aspm policy: $(cat /sys/module/pcie_aspm/parameters/policy 2>/dev/null) cmdline: $(tr ' ' '\n' </proc/cmdline | grep -E 'aspm' | tr '\n' ' ')"
if command -v iw >/dev/null; then say " wifi power save: $(iw dev "$IFACE" get power_save 2>&1)"
else say " wifi power save: unknown (iw is not installed; kernel default CFG80211_DEFAULT_PS=$(grep -h CFG80211_DEFAULT_PS "/boot/config-$(uname -r)" 2>/dev/null | cut -d= -f2))"; fi
say " tools: iw=$(command -v iw || echo no) iwconfig=$(command -v iwconfig || echo no) nmcli=$(command -v nmcli || echo no) wpa_cli=$(command -v wpa_cli || echo no) networkctl=$(command -v networkctl || echo no)"
say "== gateway =="
local g; g=$(gateway_of || true)
if [ -n "$g" ]; then say " gateway: $g"; ping -n -q -c 4 -i 0.4 -W 2 "${g%% *}" 2>&1 | tail -2 | sed 's/^/ /'; else say " no default route"; fi
say "== installed watchdog =="
[ -x "$BIN" ] && say " $BIN present" || say " $BIN absent"
[ -f "$UNIT" ] && say " $UNIT present, active=$(systemctl is-active $NAME 2>/dev/null || true), enabled=$(systemctl is-enabled $NAME 2>/dev/null || true)" || say " $UNIT absent"
[ -f "$MODCONF" ] && say " $MODCONF present: $(tr '\n' ' ' <"$MODCONF")" || say " $MODCONF absent"
say "== what 'install' would do with these flags (nothing is changed by show) =="
EXEC=0; do_install
}
# ------------------------------------------------------------------ bounded execution and logging
ACTLOG="$STATE/actions.log"
declare -A C=([probes]=0 [probe_failures]=0 [incidents]=0 [l1]=0 [l2]=0 [l3]=0 [recoveries]=0 [reboots]=0 [snapshots]=0)
log() {
local m="$*"
printf '%s\n' "$m"
[ "$DRY" = 1 ] && return 0
printf '%s %s\n' "$(now_iso)" "$m" >>"$ACTLOG" 2>/dev/null || true
local sz; sz=$(stat -c %s "$ACTLOG" 2>/dev/null || echo 0)
if [ "$sz" -gt 262144 ]; then tail -n 500 "$ACTLOG" >"$ACTLOG.tmp" 2>/dev/null && mv -f "$ACTLOG.tmp" "$ACTLOG"; fi
}
run_bounded() { # run_bounded SECONDS cmd args... ; 124 on timeout (the child gets TERM and is left alone: it may sit in D state)
local t=$1 pid i=0 max; shift; max=$((t * 5))
"$@" &
pid=$!
while kill -0 "$pid" 2>/dev/null; do
if [ "$i" -ge "$max" ]; then log "TIMEOUT after ${t}s: $* (pid $pid left running)"; kill "$pid" 2>/dev/null || true; return 124; fi
sleep 0.2; i=$((i + 1))
done
wait "$pid"
}
act() { # act SECONDS cmd args... : the only way recovery code changes anything
local t=$1; shift
if [ "$DRY" = 1 ]; then log "DRY-RUN would run (timeout ${t}s): $*"; return 0; fi
log "run: $*"
run_bounded "$t" "$@"
local rc=$?
[ "$rc" -eq 0 ] || log "exit $rc: $*"
return 0
}
save_counters() {
[ "$DRY" = 1 ] && return 0
local k; for k in "${!C[@]}"; do printf '%s=%s\n' "$k" "${C[$k]}"; done | sort >"$STATE/counters.tmp" 2>/dev/null && mv -f "$STATE/counters.tmp" "$STATE/counters"
}
load_counters() {
[ -r "$STATE/counters" ] || return 0
local k v; while IFS='=' read -r k v; do isnum "$v" && [ -n "${C[$k]+x}" ] && C[$k]=$v; done <"$STATE/counters"
}
bump() { C[$1]=$((${C[$1]} + 1)); save_counters; }
# ------------------------------------------------------------------ snapshot
tc() { timeout -k 1 5 "$@" 2>&1 | head -n 80; }
sec() { printf '\n== %s ==\n' "$1"; }
write_snapshot() { # prints the snapshot to stdout
local tag=$1 g=${2:-}
sec "meta"; say "time=$(now_iso) tag=$tag iface=$IFACE module=$MODULE pci=$BDF gateway=${g:-none} fails=${fails:-0} level=${level:-0} uptime=$(cut -d' ' -f1 /proc/uptime)s"
say "counters: $(for k in "${!C[@]}"; do printf '%s=%s ' "$k" "${C[$k]}"; done)"
sec "ip -br a"; tc ip -br a
sec "ip route"; tc ip route
sec "ip neigh (gateway)"; if [ -n "$g" ]; then tc ip neigh show "$g"; fi
sec "ip -s link $IFACE"; tc ip -s link show "$IFACE"
sec "sysfs"; local f; for f in operstate carrier carrier_changes carrier_up_count carrier_down_count; do say "$f=$(cat /sys/class/net/$IFACE/$f 2>&1)"; done
sec "signal / link"
if command -v iw >/dev/null; then tc iw dev "$IFACE" link; tc iw dev "$IFACE" station dump; tc iw dev "$IFACE" get power_save; fi
if command -v iwconfig >/dev/null; then tc iwconfig "$IFACE"; fi
if command -v nmcli >/dev/null; then tc nmcli -t device show "$IFACE"; fi
if command -v wpa_cli >/dev/null; then tc wpa_cli -p /run/wpa_supplicant -i "$IFACE" status; tc wpa_cli -p /run/wpa_supplicant -i "$IFACE" signal_poll; fi
tc cat /proc/net/wireless
sec "networkctl"; tc networkctl status "$IFACE" --no-pager -n 5
sec "pci $BDF"
if [ -n "$BDF" ]; then
say "runtime_status=$(cat /sys/bus/pci/devices/$BDF/power/runtime_status 2>&1) control=$(cat /sys/bus/pci/devices/$BDF/power/control 2>&1) l1_aspm=$(cat /sys/bus/pci/devices/$BDF/link/l1_aspm 2>&1) speed=$(cat /sys/bus/pci/devices/$BDF/current_link_speed 2>&1)"
if command -v lspci >/dev/null && [ "$(id -u)" -eq 0 ]; then timeout -k 1 5 lspci -vvs "$BDF" 2>&1 | grep -E 'LnkCtl:|LnkSta:|L1SubCtl1|DevSta:' ; fi
fi
[ -n "$MODULE" ] && for f in /sys/module/$MODULE/parameters/*; do [ -e "$f" ] && say "param $(basename "$f")=$(cat "$f" 2>&1)"; done
sec "kernel: last 30 lines with mt7925|$IFACE (without the 'Ignore NSS change' noise)"
{ dmesg --time-format iso 2>/dev/null || journalctl -k --no-pager -o short-iso 2>/dev/null; } | grep -E "mt7925|$IFACE" | grep -v 'Ignore NSS change' | tail -n 30
say "(last AP frame logged as 'Ignore NSS change', i.e. the last time the receive path demonstrably worked: $({ dmesg --time-format iso 2>/dev/null || journalctl -k --no-pager -o short-iso 2>/dev/null; } | grep 'Ignore NSS change' | tail -n 1))"
sec "journal: supervisor + networkd, last 20"
timeout -k 1 8 journalctl --no-pager -n 20 -o short-iso -u "netplan-wpa-$IFACE" -u systemd-networkd -u wpa_supplicant -u NetworkManager -u iwd 2>&1 | cut -c1-220
sec "listeners: sshd 22 and rescue 2222 (must stay up)"; ss -tln 2>/dev/null | grep -E ':(22|2222)\b'
}
snap_file() { write_snapshot "$@" >"$SNAPFILE" 2>&1; }
snapshot() { # snapshot TAG GATEWAY
local tag=$1 g=${2:-}
bump snapshots
if [ "$DRY" = 1 ]; then
local out; out=$(write_snapshot "$tag" "$g" 2>&1)
log "DRY-RUN snapshot '$tag': would write $(printf '%s\n' "$out" | wc -l) lines to $STATE/snapshots/ ; first lines follow"
printf '%s\n' "$out" | head -n "${WD_SNAP_LINES:-6}" | sed 's/^/ | /'
return 0
fi
install -d -m 755 "$STATE/snapshots"
SNAPFILE="$STATE/snapshots/snap-$(date -u +%Y%m%dT%H%M%SZ)-$tag.txt"
run_bounded 40 snap_file "$tag" "$g"
log "snapshot written: $SNAPFILE ($(wc -c <"$SNAPFILE" 2>/dev/null || echo 0) bytes)"
ls -1t "$STATE/snapshots" 2>/dev/null | tail -n +21 | while read -r old; do rm -f "$STATE/snapshots/$old"; done
}
# ------------------------------------------------------------------ recovery steps
ps_off() {
[ "$OPT_PS" = 1 ] || return 0
command -v iw >/dev/null || { log "power save: iw is missing, cannot disable"; return 0; }
if [ "$DRY" = 0 ] && iw dev "$IFACE" get power_save 2>/dev/null | grep -q ': off'; then return 0; fi
act 10 iw dev "$IFACE" set power_save off
}
step_l1() {
act 15 ip link set "$IFACE" down
[ "$DRY" = 1 ] || sleep 2
act 15 ip link set "$IFACE" up
}
step_l2() {
local s sups; sups=$(supervisors)
[ -n "$sups" ] || log "no active supervisor found for $IFACE"
for s in $sups; do act 60 systemctl restart "$s"; done
if unit_active systemd-networkd.service && command -v networkctl >/dev/null; then act 30 networkctl reconfigure "$IFACE"; fi
}
step_l3() {
if [ -z "$MODULE" ]; then log "L3 skipped: kernel module of $IFACE unknown"; return 0; fi
local s sups; sups=$(supervisors)
act 15 ip link set "$IFACE" down
for s in $sups; do act 60 systemctl stop "$s"; done
act 40 modprobe -r "$MODULE"
[ "$DRY" = 1 ] || sleep 3
act 60 modprobe "$MODULE"
if [ "$DRY" = 0 ]; then
local i; for i in $(seq 1 30); do [ -e "/sys/class/net/$IFACE" ] && break; sleep 1; done
[ -e "/sys/class/net/$IFACE" ] || log "L3: $IFACE did not come back within 30 s"
command -v udevadm >/dev/null && act 15 udevadm settle -t 10
fi
for s in $sups; do act 60 systemctl restart "$s"; done
act 15 ip link set "$IFACE" up
if unit_active systemd-networkd.service && command -v networkctl >/dev/null; then act 30 networkctl reconfigure "$IFACE"; fi
}
# ------------------------------------------------------------------ the loop
probe() { # sets PROBE_REASON, GW; returns 0 when the gateway answers
GW=""; PROBE_REASON=""
if [ "$SIM_FAIL" -gt 0 ] && [ "${C[probes]}" -le "$SIM_FAIL" ]; then PROBE_REASON="simulated failure"; GW=$(gateway_of | cut -d' ' -f1); return 1; fi
if [ -n "$GW_OVERRIDE" ]; then GW=$GW_OVERRIDE
else
local g; g=$(gateway_of) || { PROBE_REASON="no default route"; return 1; }
GW=${g%% *}
fi
[ -e "/sys/class/net/$IFACE" ] || { PROBE_REASON="interface $IFACE is gone"; return 1; }
if timeout -k 1 5 ping -n -q -c 1 -W 2 "$GW" >/dev/null 2>&1; then return 0; fi
PROBE_REASON="gateway $GW does not answer"; return 1
}
write_state() {
[ "$DRY" = 1 ] && return 0
printf 'time=%s\nok=%s\nconsecutive_fails=%s\nlevel=%s\ngateway=%s\nreason=%s\nincident_started=%s\n' "$(now_iso)" "$1" "$fails" "$level" "$GW" "$PROBE_REASON" "$incident_iso" >"$STATE/state.tmp" 2>/dev/null && mv -f "$STATE/state.tmp" "$STATE/state"
}
escalate() {
local next=$((level + 1)) settle=${WD_SETTLE:-30} # WD_SETTLE: only for dry-run tests
[ "$next" -gt 3 ] && next=3
if [ "$OPT_REBOOT" -gt 0 ] && [ "$level" -ge 3 ] && [ $((SECONDS - incident_start)) -ge $((OPT_REBOOT * 60)) ]; then
local up; up=$(cut -d. -f1 /proc/uptime)
if [ "${up:-0}" -ge 900 ]; then
snapshot "before-reboot" "$GW"; bump reboots
log "ACTION reboot: link dead for $(((SECONDS - incident_start) / 60)) min after L3 (--reboot-after-min $OPT_REBOOT)"
act 30 systemctl reboot
fails=0; settle_until=$((SECONDS + 300)); return 0
fi
fi
snapshot "before-L$next" "$GW"
log "ACTION L$next (outage: $FAILS consecutive failed probes, last: $PROBE_REASON)"
case "$next" in 1) step_l1 ;; 2) step_l2 ;; 3) step_l3 ;; esac
bump "l$next"
[ "$level" -ge 3 ] && settle=$((settle * 10))
level=$next; fails=0; settle_until=$((SECONDS + settle))
ps_off
}
run_loop() {
detect_iface; detect_hw
[ "$DRY" = 1 ] || { need_root; install -d -m 755 "$STATE"; }
load_counters
local fails=0 level=0 settle_until=0 incident_start=0 incident_iso="" loops=0 start=$SECONDS ok_prev=1
log "started: iface=$IFACE module=$MODULE pci=$BDF interval=${INTERVAL}s outage=${FAILS} fails supervisors='$(supervisors | tr '\n' ' ')' powersave_off=$OPT_PS reboot_after_min=$OPT_REBOOT dry_run=$DRY"
ps_off
while :; do
loops=$((loops + 1)); C[probes]=$((${C[probes]} + 1))
if probe; then
if [ "$fails" -gt 0 ] || [ "$level" -gt 0 ]; then
log "link OK again: gateway $GW answers (after $(($(date +%s) - ${incident_epoch:-$(date +%s)})) s, highest step L$level)"
[ "$level" -gt 0 ] && bump recoveries
fi
fails=0; level=0; incident_start=0; incident_iso=""; settle_until=0; ok_prev=1
write_state 1
else
C[probe_failures]=$((${C[probe_failures]} + 1)); ok_prev=0
if [ "$SECONDS" -lt "$settle_until" ]; then
log "probe failed ($PROBE_REASON); settling after the last step, not counted"
elif [ $((SECONDS - start)) -lt 120 ] && [ "$PROBE_REASON" = "no default route" ]; then
log "probe failed ($PROBE_REASON); boot grace period, not counted"
else
fails=$((fails + 1))
if [ "$incident_start" -eq 0 ]; then incident_start=$SECONDS; incident_epoch=$(date +%s); incident_iso=$(now_iso); fi
log "probe failed $fails/$FAILS: $PROBE_REASON"
[ "$fails" -eq 1 ] && [ "$level" -eq 0 ] && snapshot "first-fail" "$GW"
if [ "$fails" -ge "$FAILS" ]; then
[ "$level" -eq 0 ] && bump incidents
escalate
fi
fi
save_counters; write_state 0
fi
[ "$ok_prev" = 1 ] && [ $((loops % 15)) -eq 0 ] && ps_off
if [ "$MAX_LOOPS" -gt 0 ] && [ "$loops" -ge "$MAX_LOOPS" ]; then log "max loops reached, exiting (dry run)"; break; fi
sleep "$INTERVAL"
done
save_counters
}
# ------------------------------------------------------------------ install / remove
CHANGED=0
sync_file() { # sync_file DEST MODE CONTENT : plan when EXEC=0, write when EXEC=1; sets CHANGED=1 when it differs
local dest=$1 mode=$2 content=$3 st
if [ ! -e "$dest" ]; then st=create; elif [ "$(cat "$dest" 2>/dev/null)" = "$content" ]; then st=same; else st=update; fi
say " [$st] $dest (mode $mode)"
[ "$st" = same ] && return 0
CHANGED=1
[ "$EXEC" = 1 ] || return 0
install -d "$(dirname "$dest")"
printf '%s\n' "$content" >"$dest.tmp" && chmod "$mode" "$dest.tmp" && mv -f "$dest.tmp" "$dest"
}
sync_self() {
local st
if [ ! -e "$BIN" ]; then st=create; elif [ -n "$SELF" ] && cmp -s "$SELF" "$BIN"; then st=same; else st=update; fi
say " [$st] $BIN (copy of this script, mode 755)"
[ "$st" = same ] && return 0
CHANGED=1
[ "$EXEC" = 1 ] || return 0
[ -n "$SELF" ] && [ -f "$SELF" ] || die "cannot find this script's own file to copy (run it as a file, not from stdin)"
install -D -m 755 "$SELF" "$BIN"
}
unit_text() {
local args="run --iface $IFACE --module $MODULE"
[ "$OPT_PS" = 1 ] && args="$args --disable-powersave"
[ "$OPT_REBOOT" -gt 0 ] && args="$args --reboot-after-min $OPT_REBOOT"
cat <<EOF
[Unit]
Description=Wi-Fi link watchdog for $IFACE: gateway ping, escalating recovery, failure snapshots in /run
Documentation=file:$BIN
After=network.target
[Service]
Type=simple
ExecStart=$BIN $args
Restart=always
RestartSec=10
RuntimeDirectory=$NAME
RuntimeDirectoryPreserve=yes
Nice=5
ProtectHome=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
EOF
}
do_install() {
detect_iface; detect_hw
[ -n "$MODULE" ] || die "cannot determine the kernel module of $IFACE (pass --module NAME)"
[ -e "/sys/class/net/$IFACE/wireless" ] || [ "$cmd" = show ] || die "$IFACE is not a wireless interface"
if [ "$OPT_PS" = 1 ] && ! command -v iw >/dev/null && [ "$OPT_IW" = 0 ]; then
die "--disable-powersave needs the 'iw' package (not installed): add --install-iw, or run: sudo apt-get install -y iw"
fi
say "install plan for $IFACE ($MODULE, pci ${BDF:-?}); sshd 22 and rescue sshd 2222 are not touched; no link is brought down by install:"
if [ "$OPT_IW" = 1 ]; then
if command -v iw >/dev/null; then say " [same] package iw already installed"; else say " [create] apt-get install -y iw (downloads from the Ubuntu mirror, writes /usr and the dpkg database)"; [ "$EXEC" = 1 ] && { act 300 apt-get install -y iw; CHANGED=1; }; fi
fi
CHANGED=0
sync_self
local want; want=$(unit_text)
sync_file "$UNIT" 644 "$want"
if [ "$OPT_ASPM" = 1 ]; then sync_file "$MODCONF" 644 "# written by owner-wifi-stability.sh --disable-aspm: PCIe ASPM off for the Wi-Fi card; applies at the next module load
options $MODULE disable_aspm=1"; fi
local active; active=$(systemctl is-active $NAME 2>/dev/null || true)
if [ "$CHANGED" = 1 ] || [ "$active" != active ]; then
say " [do] systemctl daemon-reload; systemctl enable $NAME; systemctl $([ "$active" = active ] && echo restart || echo start) $NAME (service is currently: ${active:-unknown})"
else
say " [same] service $NAME is enabled and active with the same unit"
fi
[ "$OPT_PS" = 1 ] && say " [do] the service runs: iw dev $IFACE set power_save off (at start, after each recovery step, every ~5 min if found on)"
[ "$OPT_ASPM" = 1 ] && say " [note] disable_aspm=1 takes effect at the next load of $MODULE (reboot, or the watchdog's L3); running link unchanged"
[ "$OPT_REBOOT" -gt 0 ] && say " [note] reboot after ${OPT_REBOOT} min of dead link, only if up >= 15 min"
if [ "$EXEC" = 1 ]; then
systemctl daemon-reload
systemctl enable "$NAME" >/dev/null 2>&1
if [ "$CHANGED" = 1 ] && [ "$active" = active ]; then systemctl restart "$NAME"; elif [ "$active" != active ]; then systemctl start "$NAME"; fi
say "installed. check: bash $BIN status | journalctl -u $NAME -f"
fi
}
cmd_install() {
EXEC=0; do_install
if [ "$DRY" = 1 ]; then say "DRY RUN: nothing was changed."; return 0; fi
need_root
say "applying..."; EXEC=1; do_install
}
cmd_remove() {
say "remove plan:"
say " [do] systemctl disable --now $NAME (if present)"
local f; for f in "$UNIT" "$BIN" "$MODCONF"; do [ -e "$f" ] && say " [delete] $f" || say " [absent] $f"; done
say " [delete] $STATE (RAM only: counters, action log, snapshots)"
say " [note] left alone: the iw package, a running power-save setting and a loaded module option until the next reload/reboot"
if [ "$DRY" = 1 ]; then say "DRY RUN: nothing was changed."; return 0; fi
need_root
systemctl disable --now "$NAME" 2>/dev/null || true
rm -f "$UNIT" "$BIN" "$MODCONF"
systemctl daemon-reload 2>/dev/null || true
rm -rf --one-file-system "$STATE"
say "removed."
}
# ------------------------------------------------------------------ status
cmd_status() {
say "service: active=$(systemctl is-active $NAME 2>/dev/null || true) enabled=$(systemctl is-enabled $NAME 2>/dev/null || true) since: $(systemctl show -p ActiveEnterTimestamp --value $NAME 2>/dev/null)"
if [ -r "$STATE/state" ]; then say "-- last probe ($STATE/state)"; sed 's/^/ /' "$STATE/state"; else say "(no $STATE/state: service not running, or not installed)"; fi
if [ -r "$STATE/counters" ]; then say "-- counters"; tr '\n' ' ' <"$STATE/counters"; say ""; fi
if [ -r "$ACTLOG" ]; then say "-- last actions ($ACTLOG)"; tail -n 20 "$ACTLOG" | sed 's/^/ /'; fi
if [ -d "$STATE/snapshots" ]; then say "-- snapshots ($STATE/snapshots), newest first"; ls -1t "$STATE/snapshots" | head -n 10 | sed 's/^/ /'; fi
say "-- journal"; journalctl -u "$NAME" -n 15 --no-pager -o short-iso 2>&1 | cut -c1-200
}
case "$cmd" in
show) EXEC=0; cmd_show ;;
install) cmd_install ;;
remove) cmd_remove ;;
status) detect_iface; cmd_status ;;
run) run_loop ;;
esac