naywatch: add log when naywatch activates
[feed/routing.git] / naywatch / files / naywatch.sh
1 #!/bin/sh
2
3 . /lib/functions.sh
4 . /lib/functions/network.sh
5
6 CHECK_INTERVAL=$1
7 shift
8 WATCHDOG_TIMEOUT=$1
9 shift
10 USE_WATCHDOG=$1
11 shift
12 SAVE_LOGS=$1
13 shift
14 INTERFACES="$*"
15
16 ACTIVE=0
17 NO_NEIGHBORS_COUNT=0
18 MIN_KICK=5
19
20 log() {
21 local msg="$1"
22 logger -t naywatch "$msg"
23 }
24
25 write_logs() {
26 save_log() {
27 eval $1 > /root/$(date +%s)-"$1".log
28 }
29 config_load naywatch
30 config_list_foreach general save_cmd save_log
31 sync
32 }
33
34 neighbors_available() {
35 local phy
36
37 for interface in $INTERFACES; do
38 network_get_physdev phy $interface > /dev/null 2>&1
39 linklocal=$(ip -6 a list dev $phy | grep "scope link" | awk '{print $2}' | sed 's/\/64//') 2> /dev/null
40 ips=$(ping ff02::1%$phy -w5 -W5 -c2 | awk '/from/{print($4)}' | sed 's/.$//') 2> /dev/null
41 for ip in $ips; do
42 if [ $ip != $linklocal ] && [ $(owipcalc $ip linklocal) -eq 1 ]; then
43 echo 1
44 return 0
45 fi
46 done
47 done
48
49 echo 0
50 }
51
52 activate_watchdog() {
53 # disable openwrt instrumentation:
54 ubus call system watchdog '{"magicclose":true,"stop":true,"timeout":'${WATCHDOG_TIMEOUT}'}' > /dev/null
55 exec 3>/dev/watchdog
56 }
57
58 reboot_now() {
59 # copied from watch-cat
60 reboot &
61
62 [ "$1" -ge 1 ] && {
63 sleep "$1"
64 echo 1 >/proc/sys/kernel/sysrq
65 echo b >/proc/sysrq-trigger
66 }
67 }
68
69 no_neighbors() {
70 log "No Neighbors Available!"
71
72 NO_NEIGHBORS_COUNT=$(($NO_NEIGHBORS_COUNT+1))
73
74 if [ $ACTIVE -eq 0 ]; then
75 return 0
76 fi
77
78 if [ $SAVE_LOGS -eq 1 ]; then
79 log "Saving Logs!"
80 write_logs
81 fi
82
83 if [ $USE_WATCHDOG -eq 0 ] && [ $NO_NEIGHBORS_COUNT -gt $MIN_KICK ]; then
84 reboot_now 10
85 fi
86 }
87
88 log "Naywatch Started!"
89
90 neighbors() {
91 if [ $ACTIVE -eq 0 ]; then
92 log "Naywatch Activated!"
93 fi
94 ACTIVE=1
95 NO_NEIGHBORS_COUNT=0
96 if [ $USE_WATCHDOG -eq 1 ]; then
97 echo 1 >&3
98 fi
99 }
100
101 not_active() {
102 if [ $USE_WATCHDOG -eq 1 ]; then
103 echo 1 >&3
104 fi
105 }
106
107 if [ $USE_WATCHDOG -eq 1 ]; then
108 activate_watchdog
109 fi
110
111 while [ 1 ]; do
112 # first sleep
113 sleep $CHECK_INTERVAL
114
115 has_neighbor=$(neighbors_available)
116 if [ $has_neighbor -eq 0 ] && [ $ACTIVE -eq 1 ]; then
117 no_neighbors
118 elif [ $has_neighbor -eq 1 ]; then
119 neighbors
120 else
121 not_active
122 fi
123 done
124
125 exit 0