659fa92633860892a18a4b430ed1c027a3197cbb
2 # Copyright (C) 2016 Ian Kelling
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
18 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
22 cbase
="${tmp[0]}/sysd-mail-once-state"
26 while [[ $1 == -* ]]; do
30 Usage: sysd-mail-once [-t TO_ADDRESS] [-ERRORS] SERVICE COMMAND [COMMAND_ARGS...]
32 For use with systemd timers, to email (with exim) on repeated failure &
33 success after failure.
35 In the service triggered by the timer, prepend this script to the ExecStart.
36 The email will contain the service's logs for the last ERRORS runs.
39 Stores error counts in $cbase
41 -ERRORS ERRORS is the number of failurs to accumulate before mailing the error.
44 -a Email the logs of all errors intead of just the last one.
45 -t TO_ADDRESS Address to email about errors
46 -n Dry run. Execute command but only print out what we would do in response.
64 echo "error: unexpected arg: $1"
72 echo "error: expected at least 2 args after options. args:"
80 # maybe run, depending on $dryrun
88 # maybe run, with stdin
91 printf "%s <<'EOF'\n" "$*"
100 printf "dryrun: %s\n" "$*"
104 c
=$cbase/$service # c for command file path base
109 arr
=($glob); file="${arr[0]}"; [[ $glob != "$file" ]] ||
file=
114 if ! [[ -d $cbase ]]; then
123 cursor
=$
(journalctl
--show-cursor -qn0|
sed 's/^\s*--\scursor:\s*//')
126 if (( i
< errors
)); then
130 if [[ $file == $c$errors ]]; then
134 printf "dryrun: appending to file $file: %s\n" "$cursor"
136 printf "%s\n" "$cursor" >>$file
143 printf "dryrun: creating $file, contents: %s\n" "$cursor"
145 printf "%s\n" "$cursor" >$file
147 if (( errors
== 1 )); then
153 cursor
=$
(head -n1 $file)
155 cursor
=$
(tail -n1 $file)
157 echo "sysd-mail-once: emailing on $errors errors. exit code: $code"
158 mi exim
-odf -t <<EOF
160 From: $(id -u -n)@$(hostname -f)
161 Subject: $HOSTNAME: $service exit code: $code
163 $(journalctl -u $service.service --after-cursor="$cursor")
169 if [[ $file == $c$errors ]]; then
170 echo "sysd-mail-once: emailing success after >= $errors errors."
171 mi exim
-odf -t <<EOF
173 From: $(id -u -n)@$(hostname -f)
174 Subject: $HOSTNAME: $service success