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
21 cbase
=$HOME/sysd-mail-once-state
24 while [[ $1 == -* ]]; do
28 Usage: sysd-mail-once [-t TO_ADDRESS] [-ERRORS] SERVICE COMMAND [COMMAND_ARGS...]
30 For use with systemd timers, to email (with exim) on repeated failure &
31 success after failure.
33 In the service triggered by the timer, prepend this script to the ExecStart.
34 The email will contain the service's logs for the last ERRORS runs.
37 Stores error counts in $cbase
39 -ERRORS ERRORS is the number of failurs to accumulate before mailing the error.
42 -t TO_ADDRESS Address to email about errors
43 -n Dry run. Execute command but only print out what we would do in response.
58 echo "error: unexpected arg: $1"
66 echo "error: expected at least 2 args after options. args:"
74 # maybe run, depending on $dryrun
82 # maybe run, with stdin
85 printf "%s <<'EOF'\n" "$*"
93 printf "dryrun: %s\n" "$*"
96 c
=$cbase/$service # c for command file path base
103 arr
=($glob); file="${arr[0]}"; [[ $glob != "$file" ]] ||
file=
104 if [[ $dryrun && $file ]]; then
108 if ! [[ -d $cbase ]]; then
112 if [[ ! $file ]]; then
113 cursor
=$
(journalctl
--show-cursor -qn0|
sed 's/^\s*--\scursor:\s*//')
122 if (( i
< errors
)); then
126 if [[ $file == $c$errors ]]; then
133 printf "dryrun: creating $file, contents: %s\n" "$cursor"
135 printf "%s\n" "$cursor" >$file
137 if (( errors
== 1 )); then
142 echo "sysd-mail-once: emailing on $errors errors. exit code: $code"
143 mi exim
-odf -t <<EOF
145 From: $USER@$(hostname -f)
146 Subject: $HOSTNAME: $service exit code: $code
148 $(journalctl -u $service.service --after-cursor="$(<$file)")
154 if [[ $file == $c$errors ]]; then
155 echo "sysd-mail-once: emailing success after >= $errors errors."
156 mi exim
-odf -t <<EOF
158 From: $USER@$(hostname -f)
159 Subject: $HOSTNAME: $service success