fix typo
[distro-setup] / system-status
1 #!/bin/bash
2 # Copyright (C) 2019 Ian Kelling
3 # SPDX-License-Identifier: AGPL-3.0-or-later
4
5 # usage: runs once every 15 seconds unless any args are passed, or we
6 # then just runs once and have verbose output. On battery power, run
7 # once per minute.
8
9 if [ -z "$BASH_VERSION" ]; then echo "error: shell is not bash" >&2; exit 1; fi
10
11 if [[ $EUID != 1000 ]]; then
12 echo "$0: error, expected to be user 1000"
13 exit 1
14 fi
15
16 source /a/bin/errhandle/err
17 status_file=/dev/shm/iank-status
18
19 shopt -s nullglob
20 shopt -s dotglob
21 shopt -s extglob
22
23 for p in ~/.gem/ruby/*/bin; do
24 PATH="$PATH:$p"
25 done
26
27
28 verbose=false
29 if [[ $1 ]]; then
30 verbose=true
31 fi
32 v() {
33 if $verbose; then
34 printf "%s\n" "$*"
35 fi
36 }
37 p() { printf "%s\n" "$*"; }
38 # log-once COUNT NAME [MESSAGE]
39 lo() {
40 if type -p ifne &>/dev/null; then
41 /usr/local/bin/log-once "$@" | ifne mail -s "$HOSTNAME: system-status $2" root@localhost
42 fi
43 }
44
45 loday() {
46 if type -p ifne &>/dev/null; then
47 /usr/local/bin/log-once "$@" | ifne mail -s "$HOSTNAME: system-status $2" daylert@iankelling.org
48 fi
49 }
50 # rm glob
51 rmg() {
52 if (( $# )); then
53 rm -f "$@"
54 fi
55 }
56
57 # todo, consider migrating some of these alerts into prometheus
58 write-status() {
59 chars=("${first_chars[@]}")
60
61 services=( epanicclean )
62 case $HOSTNAME in
63 bk|je|li) : ;;
64 *)
65 services+=(
66 systemstatus
67 btrfsmaintstop
68 dynamicipupdate
69 )
70 bads=()
71 if systemctl show -p SubState --value ${services[@]} | grep -E -v '^(running|)$' &>/dev/null; then
72 for s in ${services[@]}; do
73 if [[ $(systemctl show -p SubState --value $s 2>&1) != running ]]; then
74 bads+=($s)
75 fi
76 done
77 chars+=(MYSERS)
78 fi
79 p ${bads[*]} | lo -240 mysers
80 ;;
81 esac
82
83 case $HOSTNAME in
84 kd)
85 services=(
86 prometheus-node-exporter
87 prometheus-alertmanager
88 prometheus
89 )
90 bads=()
91 if systemctl show -p SubState --value ${services[@]} | grep -E -v '^(running|)$' &>/dev/null; then
92 for s in ${services[@]}; do
93 if [[ $(systemctl show -p SubState --value $s 2>&1) != running ]]; then
94 bads+=($s)
95 fi
96 done
97 chars+=(PROM)
98 fi
99 p ${bads[*]} | lo -240 prom
100 ;;
101 esac
102
103
104 # this section copied from servicepid()
105 unit=exim4
106 pid=$(systemctl show --property MainPID --value $unit ||:)
107 case $pid in
108 [1-9]*) : ;;
109 *)
110 dir=/sys/fs/cgroup/system.slice
111 if [[ ! -d $dir ]]; then
112 dir=/sys/fs/cgroup/systemd/system.slice
113 fi;
114 pid=$(head -n1 $dir/${unit%.service}.service/cgroup.procs ||:)
115 ;;
116 esac
117 if [[ ! $pid ]]; then
118 chars+=(EXIM)
119 fi
120
121
122 if [[ -e /a/bin/bash_unpublished/source-state ]]; then
123 # /a gets remounted due to btrbk, ignore error code for file doesnt exist
124 source /a/bin/bash_unpublished/source-state || [[ $? == 1 ]]
125 fi
126
127
128 ## check if last snapshot was recent
129 old_snap_limit=$(( 3 * 60 * 60 ))
130 for vol in a o q; do
131 case $vol in
132 o) btrbk_root=/mnt/o/btrbk ;;
133 *) btrbk_root=/mnt/root/btrbk ;;
134 esac
135 # this section generally copied from btrbk scripts, but
136 # this part modified to speed things up by about half a second.
137 # I'm not sure if its quite as reliable, but it looks pretty safe.
138 # Profiled it using time and also adding to the top of the file:
139 # set -x
140 # PS4='+ $(date "+%2N") '
141 # allow failure in case there are no snapshots yet.
142 # shellcheck disable=SC2012
143 shopt -s nullglob
144 files=($btrbk_root/$vol.20*)
145 shopt -u nullglob
146 if (( ! ${#files[@]} )); then
147 continue
148 fi
149 snaps=($(ls -1avdr "${files[@]}" 2>/dev/null |head -n1 || : ))
150 now=$EPOCHSECONDS
151 maxtime=0
152 for s in ${snaps[@]}; do
153 file=${s##*/}
154 t=$(date -d $(sed -r 's/(.{4})(..)(.{5})(..)(.*)/\1-\2-\3:\4:\5/' <<<${file#$vol.}) +%s)
155 if (( t > maxtime )); then
156 maxtime=$t
157 fi
158 done
159 snapshotmsg=
160 last_snap_age=$(( now - maxtime ))
161 last_snap_hours=$(( last_snap_age / 60 / 60 ))
162 if (( last_snap_age > old_snap_limit )); then
163 chars+=(OLD-SNAP-${last_snap_hours}h)
164 snapshotmsg="/$vol snapshot older than 4 hours"
165 if [[ $MAIL_HOST == "$HOSTNAME" ]]; then
166 p "$snapshotmsg" | lo -1 old-snapshot
167 fi
168 # not bothering to get info on all volumes if we find an old one.
169 break
170 fi
171 done
172
173
174 if [[ $MAIL_HOST == "$HOSTNAME" ]]; then
175
176 bouncemsg=
177 glob=(/m/md/bounces/new/*)
178 if [[ -e ${glob[0]} ]]; then
179 chars+=(BOUNCE)
180 bouncemsg="message in /m/md/bounces/new"
181 fi
182 p $bouncemsg | loday -1 bounce
183 # emails without the S (seen) flag. this only checks the last flag,
184 # but its good enough for me.
185 glob=(/m/md/alerts/{new,cur}/!(*,S))
186 if [[ -e ${glob[0]} ]]; then
187 chars+=(A)
188 fi
189
190 glob=(/m/md/daylert/{new,cur}/!(*,S))
191 if [[ -e ${glob[0]} ]]; then
192 chars+=(DAY)
193 fi
194
195 bbkmsg=
196 if [[ $(systemctl is-active btrbk.timer) != active ]]; then
197 chars+=(BTRBK.TIMER)
198 bbkmsg="not enabled"
199 fi
200 p "$bbkmsg" | lo -480 btrbk.timer
201
202
203
204 # commented out, only using timetrap retrospectively.
205 # # clock us out in timetrap if are idle too long
206 # if [[ -e /p/.timetrap.db ]]; then
207 # export DISPLAY=:0
208 # if type -p xprintidle &>/dev/null && xidle=$(xprintidle 2>/dev/null); then
209 # if [[ $xidle == [0-9]* ]]; then
210 # sheet=$(sqlite3 /p/.timetrap.db "select sheet from entries where end is NULL;")
211 # idle=300000
212 # if [[ $sheet == w ]]; then
213 # idle=900000
214 # fi
215 # if [[ $sheet && $xidle -gt $idle ]]; then
216 # timetrap out
217 # fi
218 # fi
219 # fi
220 # fi
221 else # end if $MAIL_HOST
222 rmg /home/iank/cron-errors/bounce* \
223 /home/iank/cron-errors/btrbk.timer* \
224 /home/iank/cron-errors/old-snapshot*
225 fi
226
227 if ip l show tunfsf &>/dev/null; then
228 # this is for tracking dns over tls issue, which
229 # fixvpndns() in brc2 fixes.
230 stat=$(resolvectl dnsovertls tunfsf 2>/dev/null ||: )
231 read -r _ _ _ istls <<<"$stat"
232 case $istls in
233 no) : ;;
234 *)
235 printf "%s\n" "$istls" | ts >> /tmp/istls.log
236 chars+=("T:$istls")
237 ;;
238 esac
239 fi
240
241 # We do this once every 5 minutes, since this is not a grave problem.
242 # For formatted elisp, see /b/ds/unsaved-buffers.el
243 elisp='(format "%s" (-reduce-from (lambda (acc buf) (let ((bpath (buffer-file-name buf))) (if (and bpath (buffer-modified-p buf)) (cons bpath acc ) acc))) nil (buffer-list)))'
244 if [[ ! $last_emacs_check || $emacsfiles ]] || (( last_emacs_check < EPOCHSECONDS - 300 )); then
245 if pgrep -G iank -u iank -f 'emacs --daemon' &>/dev/null; then
246 # i dun care if this fails
247 emacsfiles="$(timeout 1 emacsclient -a /usr/bin/true --eval "$elisp" 2>/dev/null | sed '/^"nil"$/d;s/^"(/E: /;s/)"$//' ||:)"
248 if [[ $emacsfiles ]]; then
249 chars+=("$emacsfiles")
250 fi
251 fi
252 last_emacs_check=$EPOCHSECONDS
253 fi
254
255
256 glob=(/nocow/btrfs-stale/*)
257 if [[ -e ${glob[0]} ]]; then
258 chars+=(STALE)
259 fi
260 var_mail_msg=
261 if [[ $(find /var/mail -type f \! -empty -print -quit) ]]; then
262 var_mail_msg="message in /var/mail"
263 fi
264 p $var_mail_msg | loday -1 var_mail
265
266 # early in install process, we dont have permission yet for exiqgrep.
267 # 1100 helps allow for system restarts
268 qlen=$(/usr/sbin/exiqgrep -o 1100 -c -b | awk '{print $1}') ||:
269 qmsg=
270 if ((qlen)); then
271 qmsg="queue length $qlen"
272 chars+=("q $qlen")
273 fi
274 case $HOSTNAME in
275 # No point in emailing about the mailq on a host where we don't
276 # check email.
277 $MAIL_HOST)
278 p $qmsg | loday -120 qlen
279 ;;
280 *)
281 rmg /home/iank/cron-errors/qlen*
282 ;;
283 esac
284
285 begin=false
286
287 # todo: make this robust to the case of /a not being mounted
288 if ! make -C /b/ds -q ~/.local/distro-begin 2>/dev/null || [[ $(<~/.local/distro-begin) != 0 ]]; then
289 begin=true
290 fi
291
292 end=false
293 if ! make -C /b/ds -q ~/.local/distro-end 2>/dev/null || [[ $(<~/.local/distro-end) != 0 ]]; then
294 end=true
295 fi
296
297 # these conditions are so we dont have an overly verbose prompt
298 if $begin && $end; then
299 chars+=(D)
300 elif $begin; then
301 chars+=(DB)
302 elif $end; then
303 chars+=(DE)
304 else
305 source /a/bin/ds/script-files
306 f=~/.local/conflink
307 # shellcheck disable=SC2043
308 for _ in 1; do
309 if [[ -e $f ]]; then
310 now=$EPOCHSECONDS
311 fsec=$(stat -c%Y $f)
312 # the / 60 makes it 0-59 seconds less strict, +1 to help make sure we
313 # dont have any false positives.
314 fmin=$(( (fsec - now + 1 ) / 60 ))
315 fminplus=$(( fmin + 60*24 ))
316 # Filesystem files get copied, so find any newer than the last run.
317 # The rest are hueristics:
318 # Given the last time we added a file in git, is that newer than the last conflink run.
319 # Given new files not added to git, were they modified more recently than the last conflink? but,
320 # push their modification time back by a day so we can develop them before needing to add them to git.
321
322 all_dirs=({/a/bin/ds,/p/c}{/filesystem,/machine_specific/$HOSTNAME/filesystem})
323 # This part is copied from conflink
324 for x in /p/c/machine_specific/*.hosts /a/bin/ds/machine_specific/*.hosts; do
325 if grep -qxF $HOSTNAME $x; then all_dirs+=( ${x%.hosts} ); fi
326 done
327
328 # Just because i forget a lot, -mmin -NUM means files modified <= NUM minutes ago
329 if (( fmin < 0 )) && [[ $(find ${all_my_scripts[@]} ${all_dirs[@]} -mmin $fmin -type f -print -quit 2>/dev/null) ]]; then
330 v conflink newer filesystem files
331 chars+=(CONFLINK)
332 break
333 fi
334
335 for d in /a/bin/distro-setup /p/c; do
336 [[ -d $d ]] || continue
337 cd $d
338 if [[ ! -e .git ]]; then
339 # some hosts i dont push all of /p/c
340 continue
341 fi
342 if (( $(date -d "$(git log --diff-filter=ACR --format=%aD -1)" +%s) > fsec )); then
343 v conflink: newer files checked in to git
344 chars+=(CONFLINK)
345 break
346 fi
347
348 untracked=()
349 while read -r l; do
350 untracked+=("$l")
351 done < <(git ls-files -o --exclude-standard)
352 if [[ ${untracked[0]} && $(find "${untracked[@]}" -mmin $fminplus -type f -print -quit) ]]; then
353 v conflink: untracked in $d
354 chars+=(CONFLINK)
355 break
356 fi
357 done
358 cd /
359
360 fi
361 if [[ ! -e $f || $(<$f) != 0 ]]; then
362 v conflink: last run not found or failed
363 chars+=(CONFLINK)
364 break
365 fi
366 done
367 fi
368
369 # if [[ $(grep -v "exim user lost privilege for using -C option" /var/log/exim4/paniclog 2>/dev/null ||:) ]]; then
370 if [[ -s /var/log/exim4/paniclog ]]; then
371 chars+=("PANIC!")
372 # leave it up to epanic-clean to send email notification
373 fi
374
375 if [[ ! -e $status_file || -w $status_file ]]; then
376 if [[ -e /a/bin/bash_unpublished/source-state ]]; then
377 cat /a/bin/bash_unpublished/source-state >$status_file
378 fi
379
380 if [[ ${chars[*]} ]]; then
381 echo "ps_char=\"${chars[*]} \$ps_char\"" >>$status_file
382 fi
383 fi
384 }
385
386 # This prevents me having to mute notifications when I'm going to bed.
387 mute() {
388 local locked
389 export DISPLAY=:0
390 locked=false
391 if lock_info=$(xscreensaver-command -time); then
392 if [[ $lock_info != *non-blanked* ]]; then
393 locked=true
394 fi
395 else
396 locked=true
397 fi
398 midnight=$(date -d 00:00 +%s)
399 mdiff=$(( EPOCHSECONDS - midnight ))
400 if $locked && (( mdiff < 6 || mdiff > 21 )); then
401 case $(pactl get-sink-mute @DEFAULT_SINK@ | awk '{print $2}') in
402 no)
403 pactl set-sink-mute @DEFAULT_SINK@ true
404 ;;
405 esac
406 fi
407 if ! $locked && (( mdiff > 6 || mdiff < 12 )) && [[ ! -e /tmp/ianknap ]]; then
408 case $(pactl get-sink-mute @DEFAULT_SINK@ | awk '{print $2}') in
409 yes)
410 pactl set-sink-mute @DEFAULT_SINK@ false
411 ;;
412 esac
413 fi
414 }
415
416 # use this if we want to do something just once per minute
417 first_chars=()
418
419 write-status
420 if [[ $1 ]]; then
421 cat $status_file
422 exit 0
423 fi
424
425 main-loop() {
426 while true; do
427 power=true
428 if [[ -e /sys/class/power_supply/AC/online && $(</sys/class/power_supply/AC/online) == 0 ]]; then
429 power=false
430 fi
431 wait=15
432 if ! $power; then
433 if systemctl -q is-active bitcoind; then
434 bitcoinoff
435 fi
436 wait=60
437 fi
438
439 sleep $wait
440 write-status
441 mute
442 done
443 }
444
445 # ensure our long operations are one line so we are not prone errors
446 # from this file being modified.
447 main-loop