(no commit message)
[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
147         # this is weird, but single quotes are needed to 
148         # allow for returned values with spaces. $ret is still expanded
149         # because it is in an 'eval' statement.
150         eval $1='$ret'
151 }
152
153 #
154 # enforces very strict permissions on configuration file $file.
155 #
156
157 function check_perms() {
158         local file=$1
159         local perms=`ls -ld $file`
160         perms=${perms:4:6}
161         if [ "$perms" != "------" ]; then
162                 echo "Configuration files must not be group or world readable! Dying on file $file"
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                 echo "Configuration files must be owned by root! Dying on file $file"
167                 fatal "Configuration files must be owned by root! Dying on file $file"
168         fi
169 }
170
171 # simple lowercase function
172 function tolower() {
173         echo "$1" | tr [:upper:] [:lower:]
174 }
175
176 # simple to integer function
177 function toint() {
178         echo "$1" | tr [:alpha:] -d 
179 }
180
181 #
182 # function isnow(): returns 1 if the time/day passed as $1 matches
183 # the current time/day.
184 #
185 # format is <day> at <time>:
186 #   sunday at 16
187 #   8th at 01
188 #   everyday at 22
189 #
190
191 # we grab the current time once, since processing
192 # all the configs might take more than an hour.
193 nowtime=`date +%H`
194 nowday=`date +%d`
195 nowdayofweek=`date +%A`
196 nowdayofweek=`tolower "$nowdayofweek"`
197
198 function isnow() {
199         local when="$1"
200         set -- $when
201         whendayofweek=$1; at=$2; whentime=$3;
202         whenday=`toint "$whendayofweek"`
203         whendayofweek=`tolower "$whendayofweek"`
204         whentime=`echo "$whentime" | sed 's/:[0-9][0-9]$//' | sed -r 's/^([0-9])$/0\1/'`
205
206         if [ "$whendayofweek" == "everyday" -o "$whendayofweek" == "daily" ]; then
207                 whendayofweek=$nowdayofweek
208         fi
209
210         if [ "$whenday" == "" ]; then
211                 if [ "$whendayofweek" != "$nowdayofweek" ]; then
212                         whendayofweek=${whendayofweek%s}
213                         if [ "$whendayofweek" != "$nowdayofweek" ]; then
214                                 return 0
215                         fi
216                 fi
217         elif [ "$whenday" != "$nowday" ]; then
218                 return 0
219         fi
220
221         [ "$at" == "at" ] || return 0
222         [ "$whentime" == "$nowtime" ] || return 0
223
224         return 1
225 }
226
227 function usage() {
228         cat << EOF
229 $0 usage:
230 This script allows you to coordinate system backup by dropping a few
231 simple configuration files into /etc/backup.d/. Typically, this
232 script is run hourly from cron.
233
234 The following options are available:
235 -h, --help           This usage message
236 -d, --debug          Run in debug mode, where all log messages are
237                      output to the current shell.
238 -f, --conffile FILE  Use FILE for the main configuration instead
239                      of /etc/backupninja.conf
240 -t, --test           Run in test mode, no actions are actually taken.
241 -n, --now            Perform actions now, instead of when they
242                      might be scheduled.
243     --run FILE       Execute the specified action file and then exit.    
244 When using colored output, there are:
245 EOF
246         debug=1
247         debug   "Debugging info (when run with -d)"
248         info    "Informational messages (verbosity level 4)"
249         warning "Warnings (verbosity level 3 and up)"
250         error   "Errors (verbosity level 2 and up)"
251         fatal   "Fatal, halting errors (always shown)"
252 }
253
254 ##
255 ## this function handles the running of a backup action
256 ##
257 ## these globals are modified:
258 ## fatals, errors, warnings, actions_run, errormsg
259 ##
260
261 function process_action() {
262         local file="$1"
263         local suffix="$2"
264
265         setfile $file
266
267         # skip over this config if "when" option
268         # is not set to the current time.
269         getconf when "$defaultwhen"
270         if [ "$processnow" == 1 ]; then
271                 info "running $file because of --now"
272         elif [ "$when" == "hourly" ]; then
273                 debug "running $file because 'when = hourly'"
274         else
275                 IFS=$'\t\n'
276                 for w in $when; do
277                         IFS=$' \t\n'
278                         isnow "$w"
279                         ret=$?
280                         IFS=$'\t\n'
281                         if [ $ret == 0 ]; then
282                                 debug "skipping $file because it is not $w"
283                                 return
284                         else
285                                 info "running $file because it is $w"
286                         fi
287                 done
288                 IFS=$' \t\n'
289         fi
290         
291         let "actions_run += 1"
292
293         # call the handler:
294         local bufferfile="/tmp/backupninja.buffer.$$"
295         echo "" > $bufferfile
296         echo_debug_msg=1
297         (
298                 . $scriptdir/$suffix $file
299         ) 2>&1 | (
300                 while read a; do
301                         echo $a >> $bufferfile
302                         [ $debug ] && colorize "$a"
303                 done
304         )
305         retcode=$?
306         # ^^^^^^^^ we have a problem! we can't grab the return code "$?". grrr.
307         echo_debug_msg=0
308
309         _warnings=`cat $bufferfile | grep "^Warning: " | wc -l`
310         _errors=`cat $bufferfile | grep "^Error: " | wc -l`
311         _fatals=`cat $bufferfile | grep "^Fatal: " | wc -l`
312         
313         ret=`grep "\(^Warning: \|^Error: \|^Fatal: \)" $bufferfile`
314         rm $bufferfile
315         if [ $_fatals != 0 ]; then
316                 msg "*failed* -- $file"
317                 errormsg="$errormsg\n== failures from $file ==\n\n$ret\n"
318         elif [ $_errors != 0 ]; then
319                 msg "*error* -- $file"
320                 errormsg="$errormsg\n== errors from $file ==\n\n$ret\n"
321         elif [ $_warnings != 0 ]; then
322                 msg "*warning* -- $file"
323                 errormsg="$errormsg\n== warnings from $file ==\n\n$ret\n"
324         else
325                 msg "success -- $file"
326 #       elif [ $retcode == 0 ]; then
327 #               msg "success -- $file"
328 #       else
329 #               msg "unknown -- $file"
330         fi
331
332         let "fatals += _fatals"
333         let "errors += _errors"
334         let "warnings += _warnings"     
335 }
336
337 #####################################################
338 ## MAIN
339
340 setupcolors
341 conffile="/etc/backupninja.conf"
342 loglevel=3
343
344 ## process command line options
345
346 while [ $# -ge 1 ]; do
347         case $1 in
348                 -h|--help) usage;;
349                 -d|--debug) debug=1;;
350                 -t|--test) test=1;debug=1;;
351                 -n|--now) processnow=1;;
352                 -f|--conffile)
353                         if [ -f $2 ]; then
354                                 conffile=$2
355                         else
356                                 echo "-f|--conffile option must be followed by an existing filename"
357                                 fatal "-f|--conffile option must be followed by an existing filename"
358                                 usage
359                         fi
360                         # we shift here to avoid processing the file path 
361                         shift
362                         ;;
363                 --run)
364                         debug=1
365                         if [ -f $2 ]; then
366                                 singlerun=$2
367                                 processnow=1
368                         else
369                                 echo "--run option must be fallowed by a backupninja action file"
370                                 fatal "--run option must be fallowed by a backupninja action file"
371                                 usage
372                         fi
373                         shift
374                         ;;
375                 *)
376                         debug=1
377                         echo "Unknown option $1"
378                         fatal "Unknown option $1"
379                         usage
380                         exit
381                         ;;
382         esac
383         shift
384 done                                                                                                                                                                                                            
385
386 #if [ $debug ]; then
387 #       usercolors=yes
388 #fi
389
390 ## Load and confirm basic configuration values
391
392 # bootstrap
393 if [ ! -r "$conffile" ]; then
394         echo "Configuration file $conffile not found." 
395         fatal "Configuration file $conffile not found."
396 fi
397
398 scriptdir=`grep scriptdirectory $conffile | awk '{print $3}'`
399 if [ ! -n "$scriptdir" ]; then
400         echo "Cound not find entry 'scriptdirectory' in $conffile" 
401         fatal "Cound not find entry 'scriptdirectory' in $conffile"
402 fi
403
404 if [ ! -d "$scriptdir" ]; then
405         echo "Script directory $scriptdir not found." 
406         fatal "Script directory $scriptdir not found."
407 fi
408
409 setfile $conffile
410
411 # get global config options (second param is the default)
412 getconf configdirectory /etc/backup.d
413 getconf reportemail
414 getconf reportsuccess yes
415 getconf reportwarning yes
416 getconf loglevel 3
417 getconf when "Everyday at 01:00"
418 defaultwhen=$when
419 getconf logfile /var/log/backupninja.log
420 getconf usecolors "yes"
421 getconf SLAPCAT /usr/sbin/slapcat
422 getconf LDAPSEARCH /usr/bin/ldapsearch
423 getconf RDIFFBACKUP /usr/bin/rdiff-backup
424 getconf MYSQL /usr/bin/mysql
425 getconf MYSQLHOTCOPY /usr/bin/mysqlhotcopy
426 getconf MYSQLDUMP /usr/bin/mysqldump
427 getconf GZIP /bin/gzip
428 getconf RSYNC /usr/bin/rsync
429 getconf vservers no
430 getconf VSERVERINFO /usr/sbin/vserver-info
431 getconf VSERVER /usr/sbin/vserver
432 getconf VROOTDIR `$VSERVERINFO info SYSINFO |grep vserver-Rootdir | awk '{print $2}'`
433
434 if [ ! -d "$configdirectory" ]; then
435         echo "Configuration directory '$configdirectory' not found."
436         fatal "Configuration directory '$configdirectory' not found."
437 fi
438
439 [ -f "$logfile" ] || touch $logfile
440
441 if [ "$UID" != "0" ]; then
442         echo "$0 can only be run as root"
443         exit 1
444 fi
445
446 if [ "$VSERVERS" = "yes" -a ! -d $VROOTDIR ]; then
447         echo "vservers option set in config, but $VROOTDIR is not a directory!"
448         fatal "vservers option set in config, but $VROOTDIR is not a directory!"
449 fi
450
451 ## Process each configuration file
452
453 # by default, don't make files which are world or group readable.
454 umask 077
455
456 # these globals are set by process_action()
457 fatals=0
458 errors=0
459 warnings=0
460 actions_run=0
461 errormsg=""
462
463 if [ "$singlerun" ]; then
464         files=$singlerun
465 else
466         files=`find $configdirectory -mindepth 1 | sort -n`
467 fi
468
469 for file in $files; do
470         [ -f "$file" ] || continue
471
472         check_perms $file
473         suffix="${file##*.}"
474         base=`basename $file`
475         if [ "${base:0:1}" == "0" ]; then
476                 info "Skipping $file"
477                 continue
478         fi
479
480         if [ -e "$scriptdir/$suffix" ]; then
481                 process_action $file $suffix
482         else
483                 error "Can't process file '$file': no handler script for suffix '$suffix'"
484                 msg "*missing handler* -- $file"
485         fi
486 done
487
488 ## mail the messages to the report address
489
490 if [ $actions_run == 0 ]; then doit=0
491 elif [ "$reportemail" == "" ]; then doit=0
492 elif [ $fatals != 0 ]; then doit=1
493 elif [ $errors != 0 ]; then doit=1
494 elif [ "$reportsuccess" == "yes" ]; then doit=1
495 elif [ "$reportwarning" == "yes" -a $warnings != 0 ]; then doit=1
496 else doit=0
497 fi
498
499 if [ $doit == 1 ]; then
500         debug "send report to $reportemail"
501         hostname=`hostname`
502         [ $warnings == 0 ] || subject="WARNING"
503         [ $errors == 0 ] || subject="ERROR"
504         [ $fatals == 0 ] || subject="FAILED"
505         
506         {
507                 for ((i=0; i < ${#messages[@]} ; i++)); do
508                         echo ${messages[$i]}
509                 done
510                 echo -e "$errormsg"
511         } | mail $reportemail -s "backupninja: $hostname $subject"
512 fi
513