fix stuck on email error
[log-quiet] / sysd-mail-once
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16
17 set -eE -o pipefail
18 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
19
20 errors=3
21 cbase=$HOME/sysd-mail-once-state
22 to=root
23 case "$1" in
24 -h|--help)
25 cat <<EOF
26 Usage: sysd-mail-once [-t TO_ADDRESS] [-ERRORS] SERVICE COMMAND [ARGS...]
27 For systemd timers, email (with exim) on repeated failure & success after failure.
28
29 In the service triggered by the timer, prepend this script to the ExecStart.
30 The email will contain the service's logs for the last ERRORS runs.
31
32
33 Stores error counts in $cbase
34
35 -ERRORS: ERRORS is the number of failurs to accumulate before mailing the error.
36 Default is 3.
37 EOF
38 exit 0
39 ;;
40 -[0-9]*)
41 errors=${1#-}
42 shift
43 ;;
44 -t)
45 to="$2"
46 shift 2
47 ;;
48 esac
49 service=$1
50 shift
51
52 c=$cbase/$service # c for command file path base
53
54 glob="$c[0-9]*"
55 arr=($glob); file="${arr[0]}"; [[ $glob != "$file" ]] || file=
56 [[ -d $cbase ]] || mkdir -p $cbase
57
58 if [[ ! $file ]]; then
59 cursor=$(journalctl --show-cursor -qn0|sed 's/^\s*--\scursor:\s*//')
60 fi
61
62 code=0
63 "$@" || code=$?
64 if (( code )); then
65 send_mail=false
66 if [[ $file ]]; then
67 i=${file#$c}
68 if (( i < errors )); then
69 new_file=$c$((i+1))
70 mv $file $new_file
71 file=$new_file
72 if [[ $file == $c$errors ]]; then
73 send_mail=true
74 fi
75 fi
76 else
77 file=${c}1
78 printf "%s\n" "$cursor" >$file
79 if (( errors == 1 )); then
80 send_mail=true
81 fi
82 fi
83 if $send_mail; then
84 exim -odf -t <<EOF
85 To: $to
86 From: $USER@$(hostname -f)
87 Subject: $HOSTNAME: $service exit code: $code
88
89 $(journalctl -u $service.service --after-cursor=$(<$file))
90 EOF
91 fi
92 else
93 if [[ $file ]]; then
94 rm -f $file
95 if [[ $file == $c$errors ]]; then
96 exim -odf -t <<EOF
97 To: $to
98 From: $USER@$(hostname -f)
99 Subject: $HOSTNAME: $service success
100
101 EOF
102 fi
103 fi
104 fi