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