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