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"
25 while [[ $1 == -* ]]; do
29 Usage: sysd-mail-once [-t TO_ADDRESS] [-ERRORS] SERVICE COMMAND [COMMAND_ARGS...]
31 For use with systemd timers, to email (with exim) on repeated failure &
32 success after failure.
34 In the service triggered by the timer, prepend this script to the ExecStart.
35 The email will contain the service's logs for the last ERRORS runs.
38 Stores error counts in $cbase
40 -ERRORS ERRORS is the number of failurs to accumulate before mailing the error.
43 -t TO_ADDRESS Address to email about errors
44 -n Dry run. Execute command but only print out what we would do in response.
59 echo "error: unexpected arg: $1"
67 echo "error: expected at least 2 args after options. args:"
75 # maybe run, depending on $dryrun
83 # maybe run, with stdin
86 printf "%s <<'EOF'\n" "$*"
94 printf "dryrun: %s\n" "$*"
97 c
=$cbase/$service # c for command file path base
104 arr
=($glob); file="${arr[0]}"; [[ $glob != "$file" ]] ||
file=
105 if [[ $dryrun && $file ]]; then
109 if ! [[ -d $cbase ]]; then
113 if [[ ! $file ]]; then
114 cursor
=$
(journalctl
--show-cursor -qn0|
sed 's/^\s*--\scursor:\s*//')
123 if (( i
< errors
)); then
127 if [[ $file == $c$errors ]]; then
134 printf "dryrun: creating $file, contents: %s\n" "$cursor"
136 printf "%s\n" "$cursor" >$file
138 if (( errors
== 1 )); then
143 echo "sysd-mail-once: emailing on $errors errors. exit code: $code"
144 mi exim
-odf -t <<EOF
146 From: $(id -u -n)@$(hostname -f)
147 Subject: $HOSTNAME: $service exit code: $code
149 $(journalctl -u $service.service --after-cursor="$(<$file)")
155 if [[ $file == $c$errors ]]; then
156 echo "sysd-mail-once: emailing success after >= $errors errors."
157 mi exim
-odf -t <<EOF
159 From: $(id -u -n)@$(hostname -f)
160 Subject: $HOSTNAME: $service success