fixed bug which caused report emails to be sent even if now actions
[matthijs/upstream/backupninja.git] / backupninja
1 #!/bin/bash
2 #                          |\_
3 # B A C K U P N I N J A   /()/
4 #                         `\|
5 #
6 # Copyright (C) 2004 riseup.net -- property is theft.
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18
19 #####################################################
20 ## FUNCTIONS
21
22 function setupcolors() {
23         BLUE="\033[34;01m"
24         GREEN="\033[32;01m"
25         YELLOW="\033[33;01m"
26         PURPLE="\033[35;01m"
27         RED="\033[31;01m"
28         OFF="\033[0m"
29         CYAN="\033[36;01m"
30 }
31
32 #function run() {
33 #       RUNERROR=0
34 #       debug 0 "$@"
35 #       returnstring=`$@ 2>&1`
36 #       RUNERROR=$?
37 #       RUNERRORS=$[RUNERRORS+RUNERROR]
38 #       if [ "$RUNERROR" != 0 ]; then
39 #               debug 3 "Exitcode $RUNERROR returned when running: $@"
40 #               debug 3 "$returnstring"
41 #       else
42 #               debug 0 "$returnstring"
43 #       fi
44 #       return $RUNERROR
45 #}
46
47 # We have the following message levels:
48 # 0 - debug - blue
49 # 1 - normal messages - green
50 # 2 - warnings - yellow
51 # 3 - errors - orange
52 # 4 - fatal - red
53 # First variable passed is the error level, all others are printed
54
55 # if 1, echo out all warnings, errors, or fatal
56 # used to capture output from handlers
57 echo_debug_msg=0
58
59 usecolor=yes
60
61 function printmsg() {
62         [ ${#@} -gt 1 ] || return
63          
64         types=(Debug Info Warning Error Fatal)
65         type=$1
66         print=$[4-type]
67         typestr=${types[$type]}
68         if [ "$usecolor" == "yes" ]; then
69                 colors=($BLUE $GREEN $YELLOW $RED $PURPLE)
70                 color=${colors[$type]}
71                 endcolor=$OFF
72         fi
73         
74         shift
75         
76         if [ "$echo_debug_msg" != "0" -a "$type" -gt "1" ]; then
77                 echo -e "$typestr: $@"
78         fi
79         
80         if [ "$debug" == 1 ]; then
81                 echo -e "${color}$typestr: $@${endcolor}" >&2
82         fi
83         
84         if [ $print -lt $loglevel ]; then
85                 if [ -w "$logfile" ]; then
86                         echo -e "${color}$typestr: $@${endcolor}" >> $logfile
87                 fi
88         fi
89 }
90
91 function debug() {
92         printmsg 0 "$@"
93 }
94 function info() {
95         printmsg 1 "$@"
96 }
97 function warning() {
98         printmsg 2 "$@"
99 }
100 function error() {
101         printmsg 3 "$@" 
102 }
103 function fatal() {
104         printmsg 4 "$@"
105         exit 2
106 }
107
108 msgcount=0
109 function msg {
110         messages[$msgcount]=$1
111         let "msgcount += 1"
112 }
113
114 function setfile() {
115         CURRENT_CONF_FILE=$1
116 }
117
118 function setsection() {
119         CURRENT_SECTION=$1
120 }
121
122 #
123 # sets a global var with name equal to $1
124 # to the value of the configuration parameter $1
125 # $2 is the default.
126
127
128 function getconf() {
129         CURRENT_PARAM=$1
130         ret=`awk -f $scriptdir/parseini S=$CURRENT_SECTION P=$CURRENT_PARAM $CURRENT_CONF_FILE`
131         # if nothing is returned, set the default
132         if [ "$ret" == "" -a "$2" != "" ]; then
133                 ret="$2"
134         fi
135
136         # replace * with %, so that it is not globbed.
137         ret="${ret//\\*/__star__}"
138
139         # this is weird, but single quotes are needed to 
140         # allow for returned values with spaces. $ret is still expanded
141         # because it is in an 'eval' statement.
142         eval $1='$ret'
143 }
144
145 #
146 # enforces very strict permissions on configuration file $file.
147 #
148
149 function check_perms() {
150         local file=$1
151         local perms=`ls -ld $file`
152         perms=${perms:4:6}
153         if [ "$perms" != "------" ]; then
154                 fatal "Configuration files must not be group or world readable! Dying on file $file"
155         fi
156         if [ `ls -ld $file | awk '{print $3}'` != "root" ]; then
157                 fatal "Configuration files must be owned by root! Dying on file $file"
158         fi
159 }
160
161 # simple lowercase function
162 function tolower() {
163         echo "$1" | tr [:upper:] [:lower:]
164 }
165
166 # simple to integer function
167 function toint() {
168         echo "$1" | tr [:alpha:] -d 
169 }
170
171 #
172 # function isnow(): returns 1 if the time/day passed as $1 matches
173 # the current time/day.
174 #
175 # format is <day> at <time>:
176 #   sunday at 16
177 #   8th at 01
178 #   everyday at 22
179 #
180
181 # we grab the current time once, since processing
182 # all the configs might take more than an hour.
183 nowtime=`date +%H`
184 nowday=`date +%d`
185 nowdayofweek=`date +%A`
186 nowdayofweek=`tolower "$nowdayofweek"`
187
188 function isnow() {
189         local when="$1"
190         set -- $when
191         whendayofweek=$1; at=$2; whentime=$3;
192         whenday=`toint "$whendayofweek"`
193         whendayofweek=`tolower "$whendayofweek"`
194         whentime=`echo "$whentime" | sed 's/:[0-9][0-9]$//'`
195
196         if [ "$whendayofweek" == "everyday" ]; then
197                 whendayofweek=$nowdayofweek
198         fi
199
200         if [ "$whenday" == "" ]; then
201                 if [ "$whendayofweek" != "$nowdayofweek" ]; then
202                         whendayofweek=${whendayofweek%s}
203                         if [ "$whendayofweek" != "$nowdayofweek" ]; then
204                                 return 0
205                         fi
206                 fi
207         elif [ "$whenday" != "$nowday" ]; then
208                 return 0
209         fi
210
211         [ "$at" == "at" ] || return 0
212         [ "$whentime" == "$nowtime" ] || return 0
213
214         return 1
215 }
216
217 function usage() {
218         cat << EOF
219 $0 usage:
220 This script allows you to coordinate system backup by dropping a few
221 simple configuration files into /etc/backup.d/. Typically, this
222 script is run hourly from cron.
223
224 The following options are available:
225 -h, --help           This usage message
226 -d, --debug          Run in debug mode, where all log messages are
227                      output to the current shell.
228 -f, --conffile FILE  Use FILE for the main configuration instead
229                      of /etc/backupninja.conf
230 -t, --test           Run in test mode, no actions are actually taken.
231 -n, --now            Perform actions now, instead of when they
232                      might be scheduled.
233 When using colored output, there are:
234 EOF
235         debug=1
236         debug   "Debugging info (when run with -d)"
237         info    "Informational messages (verbosity level 4)"
238         warning "Warnings (verbosity level 3 and up)"
239         error   "Errors (verbosity level 2 and up)"
240         fatal   "Fatal, halting errors (always shown)"
241 }
242
243 ##
244 ## this function handles the running of a backup action
245 ##
246 ## these globals are modified:
247 ## fatals, errors, warnings, actions_run, errormsg
248 ##
249
250 function process_action() {
251         local file="$1"
252         local suffix="$2"
253
254         setfile $file
255
256         # skip over this config if "when" option
257         # is not set to the current time.
258         getconf when "$defaultwhen"
259         if [ "$processnow" == 1 ]; then
260                 info "running $file because of --now"
261         else
262                 IFS=$'\t\n'
263                 for w in $when; do
264                         IFS=$' \t\n'
265                         isnow "$w"
266                         ret=$?
267                         IFS=$'\t\n'
268                         if [ $ret == 0 ]; then
269                                 debug "skipping $file because it is not $w"
270                                 return
271                         else
272                                 info "running $file because it is $w"
273                         fi
274                 done
275                 IFS=$' \t\n'
276         fi
277         
278         let "actions_run += 1"
279         echo_debug_msg=1
280
281         # call the handler:
282         ret=`( . $scriptdir/$suffix $file )`
283         retcode="$?"
284
285         _warnings=`echo $ret | grep "Warning: " | wc -l`
286         _errors=`echo $ret | grep "Error: " | wc -l`
287         _fatals=`echo $ret | grep "Fatal: " | wc -l`
288
289         if [ $_fatals != 0 ]; then
290                 msg "*failed* -- $file"
291                 errormsg="$errormsg\n== failures from $file ==\n\n$ret\n"
292         elif [ $_errors != 0 ]; then
293                 msg "*error* -- $file"
294                 errormsg="$errormsg\n== errors from $file ==\n\n$ret\n"
295         elif [ $_warnings != 0 ]; then
296                 msg "*warning* -- $file"
297                 errormsg="$errormsg\n== warnings from $file ==\n\n$ret\n"
298         elif [ $retcode == 0 ]; then
299                 msg "success -- $file"
300         else
301                 msg "unknown -- $file"
302         fi
303
304         echo_debug_msg=0        
305         let "fatals += _fatals"
306         let "errors += _errors"
307         let "warnings += _warnings"
308 }
309
310 #####################################################
311 ## MAIN
312
313 setupcolors
314 conffile="/etc/backupninja.conf"
315 loglevel=3
316
317 ## process command line options
318
319 while [ $# -ge 1 ]; do
320         case $1 in
321                 -h|--help) usage;;
322                 -d|--debug) debug=1;;
323                 -t|--test) test=1;debug=1;;
324                 -n|--now) processnow=1;;
325                 -f|--conffile)
326                         if [ -f $2 ]; then
327                                 conffile=$2
328                         else
329                                 fatal "-f|--conffile option must be followed by an existing filename"
330                                 usage
331                         fi
332                         # we shift here to avoid processing the file path 
333                         shift
334                         ;;
335                 *)
336                         fatal "Unknown option $1"
337                         usage
338                         ;;
339         esac
340         shift
341 done                                                                                                                                                                                                            
342
343 ## Load and confirm basic configuration values
344
345 # bootstrap
346 [ -r "$conffile" ] || fatal "Configuration file $conffile not found."
347 scriptdir=`grep scriptdirectory $conffile | awk '{print $3}'`
348 [ -n "$scriptdir" ] || fatal "Cound not find entry 'scriptdirectory' in $conffile"
349 [ -d "$scriptdir" ] || fatal "Script directory $scriptdir not found."
350 setfile $conffile
351
352 # get global config options (second param is the default)
353 getconf configdirectory /etc/backup.d
354 getconf reportemail
355 getconf reportsuccess yes
356 getconf reportwarning yes
357 getconf loglevel 3
358 getconf when "Everyday at 01:00"
359 defaultwhen=$when
360 getconf logfile /var/log/backupninja.log
361 getconf usecolors "yes"
362 getconf SLAPCAT /usr/sbin/slapcat
363 getconf RDIFFBACKUP /usr/bin/rdiff-backup
364 getconf MYSQL /usr/bin/mysql
365 getconf MYSQLHOTCOPY /usr/bin/mysqlhotcopy
366 getconf MYSQLDUMP /usr/bin/mysqldump
367 getconf GZIP /bin/gzip
368
369 [ -d "$configdirectory" ] || fatal "Configuration directory '$configdirectory' not found."
370
371 if [ "$UID" != "0" ]; then
372         echo "$0 can only be run as root"
373         exit 1
374 fi
375
376 ## Process each configuration file
377
378 # by default, don't make files which are world or group readable.
379 umask 077
380
381 # these globals are set by process_action()
382 fatals=0
383 errors=0
384 warnings=0
385 actions_run=0
386 errormsg=""
387
388 for file in $configdirectory/*; do
389         [ -f $file ] || continue;
390
391         check_perms $file
392         suffix="${file##*.}"
393         base=`basename $file`
394         if [ "${base:0:1}" == "0" ]; then
395                 info "Skipping $file"
396                 continue
397         fi
398
399         if [ -e "$scriptdir/$suffix" ]; then
400                 process_action $file $suffix
401         else
402                 error "Can't process file '$file': no handler script for suffix '$suffix'"
403                 msg "*missing handler* -- $file"
404         fi
405 done
406
407 ## mail the messages to the report address
408
409 if [ $actions_run == 0 ]; then doit=0
410 elif [ "$reportemail" == "" ]; then doit=0
411 elif [ $fatals != 0 ]; then doit=1
412 elif [ $errors != 0 ]; then doit=1
413 elif [ "$reportsuccess" == "yes" ]; then doit=1
414 elif [ "$reportwarning" == "yes" -a $warnings != 0 ]; then doit=1
415 else doit=0
416 fi
417
418 if [ $doit == 1 ]; then
419         debug "send report to $reportemail"
420         hostname=`hostname`
421         [ $warnings == 0 ] || subject="WARNING"
422         [ $errors == 0 ] || subject="ERROR"
423         [ $fatals == 0 ] || subject="FAILED"
424         
425         {
426                 for ((i=0; i < ${#messages[@]} ; i++)); do
427                         echo ${messages[$i]}
428                 done
429                 echo -e "$errormsg"
430         } | mail $reportemail -s "backupninja: $hostname $subject"
431 fi
432