version 0.4.1
[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 function process_action() {
244         local file="$1"
245         local suffix="$2"
246
247         setfile $file
248
249         # skip over this config if "when" option
250         # is not set to the current time.
251         getconf when "$defaultwhen"
252         if [ "$processnow" == 1 ]; then
253                 info "running $file because of --now"
254         else
255                 IFS=$'\t\n'
256                 for w in $when; do
257                         IFS=$' \t\n'
258                         isnow "$w"
259                         ret=$?
260                         IFS=$'\t\n'
261                         if [ $ret == 0 ]; then
262                                 debug "skipping $file because it is not $w"
263                                 return
264                         else
265                                 info "running $file because it is $w"
266                         fi
267                 done
268                 IFS=$' \t\n'
269         fi
270         
271         echo_debug_msg=1
272         # call the handler:
273         ret=`( . $scriptdir/$suffix $file )`
274         retcode="$?"
275         warnings=`echo $ret | grep -e "^Warning: " | wc -l`
276         errors=`echo $ret | grep -e "^Error: \|^Fatal: " | wc -l`
277         if [ $errors != 0 ]; then
278                 msg "*failed* -- $file"
279                 errormsg="$errormsg\n== errors from $file ==\n\n$ret\n"
280         elif [ $warnings != 0 ]; then
281                 msg "*warning* -- $file"
282                 errormsg="$errormsg\n== warnings from $file ==\n\n$ret\n"
283         elif [ $retcode == 0 ]; then
284                 msg "success -- $file"
285         else
286                 msg "unknown -- $file"
287         fi
288         echo_debug_msg=0
289 }
290
291 #####################################################
292 ## MAIN
293
294 setupcolors
295 conffile="/etc/backupninja.conf"
296
297 ## process command line options
298
299 while [ $# -ge 1 ]; do
300         case $1 in
301                 -h|--help) usage;;
302                 -d|--debug) debug=1;;
303                 -t|--test) test=1;debug=1;;
304                 -n|--now) processnow=1;;
305                 -f|--conffile)
306                         if [ -f $2 ]; then
307                                 conffile=$2
308                         else
309                                 fatal "-f|--conffile option must be followed by an existing filename"
310                                 usage
311                         fi
312                         # we shift here to avoid processing the file path 
313                         shift
314                         ;;
315                 *)
316                         fatal "Unknown option $1"
317                         usage
318                         ;;
319         esac
320         shift
321 done                                                                                                                                                                                                            
322
323 ## Load and confirm basic configuration values
324
325 # bootstrap
326 [ -r "$conffile" ] || fatal "Configuration file $conffile not found."
327 scriptdir=`grep scriptdirectory $conffile | awk '{print $3}'`
328 [ -n "$scriptdir" ] || fatal "Cound not find entry 'scriptdirectory' in $conffile"
329 [ -d "$scriptdir" ] || fatal "Script directory $scriptdir not found."
330 setfile $conffile
331
332 # get global config options (second param is the default)
333 getconf configdirectory /etc/backup.d
334 getconf reportemail
335 getconf reportsuccess yes
336 getconf reportwarning yes
337 getconf loglevel 3
338 getconf when "Everyday at 01:00"
339 defaultwhen=$when
340 getconf logfile /var/log/backupninja.log
341 getconf usecolors "yes"
342 getconf SLAPCAT /usr/sbin/slapcat
343 getconf RDIFFBACKUP /usr/bin/rdiff-backup
344 getconf MYSQL /usr/bin/mysql
345 getconf MYSQLHOTCOPY /usr/bin/mysqlhotcopy
346 getconf MYSQLDUMP /usr/bin/mysqldump
347 getconf GZIP /bin/gzip
348
349 [ -d "$configdirectory" ] || fatal "Configuration directory '$configdirectory' not found."
350
351 if [ "$UID" != "0" ]; then
352         echo "$0 can only be run as root"
353         exit 1
354 fi
355
356 ## Process each configuration file
357
358 info "====== starting at "`date`" ======"
359
360 # by default, don't make files which are world or group readable.
361 umask 077
362
363 errors=0
364
365 for file in $configdirectory/*; do
366         [ -f $file ] || continue;
367
368         check_perms $file
369         suffix="${file##*.}"
370         base=`basename $file`
371         if [ "${base:0:1}" == "0" ]; then
372                 info "Skipping $file"
373                 continue
374         fi
375
376         if [ -e "$scriptdir/$suffix" ]; then
377                 process_action $file $suffix
378         else
379                 error "Can't process file '$file': no handler script for suffix '$suffix'"
380                 msg "*missing handler* -- $file"
381         fi
382 done
383
384 ## mail the messages to the report address
385
386 if [ "$reportemail" == "" ]; then doit=0
387 elif [ $errors != 0 ]; then doit=1
388 elif [ "$reportsuccess" == "yes" ]; then doit=1
389 elif [ "$reportwarning" == "yes" -a $warnings != 0 ]; then doit=1
390 else doit=0
391 fi
392
393 if [ $doit == 1 ]; then
394         hostname=`hostname`
395         {
396                 for ((i=0; i < ${#messages[@]} ; i++)); do
397                         echo ${messages[$i]}
398                 done
399                 echo -e "$errormsg"
400         } | mail $reportemail -s "backupninja: $hostname"
401 fi
402
403 info "====== finished at "`date`" ======"
404
405 ############################################################