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