]> arthur.barton.de Git - backup-script.git/blob - bin/backup-script
Look for configuration file in /usr/local/etc/, too
[backup-script.git] / bin / backup-script
1 #!/bin/bash
2 #
3 # backup-script system for cloning systems using rsync
4 # Copyright (c)2008-2015 Alexander Barton <alex@barton.de>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 # Please read the file COPYING, README and AUTHORS for more information.
11 #
12
13 NAME=$(basename "$0")
14 PIDFILE="/var/run/$NAME.pid"
15
16 DRYRUN=0
17 VERBOSE=0
18
19 export LC_ALL=C
20
21 declare -i count_all=0
22 declare -i count_started=0
23 declare -i count_ok=0
24 declare -i count_ok_vanished=0
25
26 destinations=""
27
28 # Default settings, can be overwritten in backup-script.conf:
29 conf_d="/etc/backup-script.d"
30 pre_exec=""
31 post_exec=""
32 default_source_root="/"
33 default_target=""
34 default_user="root"
35 default_ssh_args_add=""
36 default_rsync_args_add=""
37 default_exclude_args_add=""
38 default_compress=1
39 default_ping=1
40 default_local=0
41 default_generations=0
42 default_job_pre_exec=""
43 default_job_post_exec=""
44
45 Usage() {
46         echo "Usage: $NAME [<options>] [<system> [<system> [...]]]"
47         echo
48         echo "  -p, --progress    Show progress, see rsync(1)."
49         echo "  -n, --dry-run     Test run only, don't copy any data."
50         echo
51         echo "When no <system> is given, all defined systems are used."
52         echo
53         exit 1
54 }
55
56 CleanUp() {
57         if [ -n "$post_exec" ]; then
58                 echo "Executing \"$post_exec\" ..."
59                 sh -c $post_exec
60                 if [ $? -ne 0 ]; then
61                         echo "Warning: post-exec command failed!"
62                 fi
63                 echo
64         fi
65         rm -f "$PIDFILE"
66 }
67
68 GotSignal() {
69         echo
70         echo "--> Got break signal, cleaning up & aborting ..."
71         echo
72         CleanUp
73         echo -n "Aborted: "; date
74         echo
75         sleep 3
76         exit 9
77 }
78
79 ExecJob() {
80         local what="$1"
81         local cmd="$2"
82
83         echo "Running job ${what}-exec command ..."
84         [ "$local" -eq 0 ] \
85                 && cmd="$ssh_cmd ${user}@${system} $cmd"
86         echo -n "Start date (${what}-exec): "; date
87         echo "$cmd"
88         if [ "$DRYRUN" -eq 0 ]; then
89                 $SHELL -c "$cmd"; local ret=$?
90         else
91                 echo " *** Trial run, not executing ${what}-exec command!"
92                 ret=0
93         fi
94         [ $ret -eq 0 ] \
95                 && echo "The ${what}-exec command completed with status 0, OK." \
96                 || echo "The ${what}-exec command completed with ERRORS, code $ret!"
97         return $ret
98 }
99
100 GetFS() {
101         local dir="$1"
102
103         while [ -n "$dir" ]; do
104                 findmnt -fn -o FSTYPE --raw "$dir" 2>/dev/null; local r=$?
105                 if [ $r -eq 0 ]; then
106                         return 0
107                 elif [ $r -eq 127 ]; then
108                         echo "UNKNOWN"
109                         return 1
110                 fi
111                 dir=$(dirname "$dir") || return 1
112         done
113 }
114
115 CreateSubvolume() {
116         local volume="$1"
117         local fs
118         local dir
119
120         dir=$(dirname "$volume")
121         fs=$(GetFS "$dir")
122         case "$fs" in
123           "btrfs")
124                 btrfs subvolume create "$volume"  >/dev/null || return 1
125                 ;;
126           "zfs")
127                 zfs create "$(echo "$volume" | cut -c2-)" || return 1
128                 ;;
129           *)
130                 echo "CreateSubvolume: Incompatible FS type \"$fs\" on \"$dir\"!"
131                 return 9
132         esac
133         return 0
134 }
135
136 CloneSubvolume() {
137         local source="$1"
138         local volume="$2"
139         local snapshot="$3"
140         local dir
141         local fs
142         local link_name
143
144         dir=$(dirname "source")
145         fs=$(GetFS "$source")
146         case "$fs" in
147           "btrfs")
148                 btrfs subvolume snapshot "$source" "$snapshot"  >/dev/null || return 1
149                 ;;
150           "zfs")
151                 zfs snapshot "$snapshot" || return 1
152                 link_name="$(echo "$snapshot" | cut -d@ -f2-)"
153                 ln -s \
154                         "$volume/.zfs/snapshot/$link_name" \
155                         "$(dirname "$volume")/$link_name"
156                 ;;
157           *)
158                 echo "CloneSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
159                 return 9
160         esac
161         return 0
162 }
163
164 RenameSubvolume() {
165         local source="$1"
166         local target="$2"
167         local fs
168
169         fs=$(GetFS "$source")
170         case "$fs" in
171           "btrfs")
172                 mv "$source" "$target" || return 1
173                 ;;
174           "zfs")
175                 zfs rename \
176                   "$(echo "$source" | cut -c2-)" \
177                   "$(echo "$target" | cut -c2-)" \
178                         || return 1
179                 ;;
180           *)
181                 echo "RenameSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
182                 return 9
183         esac
184         return 0
185 }
186
187 DeleteSubvolume() {
188         local volume="$1"
189         local fs
190         local id
191         local snapshot
192
193         fs=$(GetFS "$volume")
194         case "$fs" in
195           "btrfs")
196                 btrfs subvolume delete "$volume" >/dev/null || return 1
197                 ;;
198           "zfs")
199                 id="$(basename "$volume")"
200                 if [ -h "$volume" ]; then
201                         snapshot="$(dirname "$volume")/current@$id"
202                 else
203                         snapshot="$volume"
204                 fi
205                 zfs destroy -r "$(echo "$snapshot" | cut -c2-)" >/dev/null || return 1
206                 [ -h "$volume" ] && rm "$volume"
207                 ;;
208           *)
209                 echo "DeleteSubvolume: Incompatible FS type \"$fs\" on \"$volume\"!"
210                 return 9
211         esac
212         return 0
213 }
214
215 Initialize_Last_SysTarget_Snapshot() {
216         sys_target="$1"
217         unset last
218         unset snapshot
219
220         fs=$(GetFS "$sys_target")
221         case "$fs" in
222           "btrfs")
223                 # Search directory of last generation, if any
224                 last=$(ls -1d "$sys_target"/[0-9]* 2>/dev/null | sort -r | head -n1)
225                 if [ -n "$last" ]; then
226                         if [ ! -d "$last" ]; then
227                                 echo "Last snapshot \"$last\" seems not to be a directory!? \"$system\" skipped!"
228                                 echo
229                                 return 1
230                         fi
231                 fi
232                 sys_target="$sys_target/$(date +%Y%m%d-%H%M%S)"
233                 snapshot="$sys_target"
234                 ;;
235           "zfs")
236                 # On ZFS, the last generation is always named "current"
237                 if [ -e "$sys_target/current" ]; then
238                         last="$sys_target/current"
239                         if [ "$(uname)" = "Linux" ]; then
240                                 date=$(LC_ALL=C stat "$1" | grep "^Modify: " \
241                                  | cut -d':' -f2- | cut -d. -f1)
242                         else
243                                 date=$(LC_ALL=C stat -f "%Sc" "$1")
244                         fi
245                         date=$(echo "$date" | sed -e's/^ //g' -e 's/[-:]//g' -e 's/ /-/g')
246
247                 else
248                         last=""
249                         date="$(date +%Y%m%d-%H%M%S)"
250                 fi
251                 snapshot="$(echo "$sys_target/current" | cut -c2-)@$date"
252                 sys_target="$sys_target/current"
253                 ;;
254           *)
255                 echo "Initialize_Last_SysTarget_Snapshot: Incompatible FS type \"$fs\" on \"$sys_target\"!"
256                 return 1
257         esac
258         return 0
259 }
260
261 # Search configuration file (last one is used as default!)
262 for conf in \
263         "/usr/local/etc/backup-script.conf" \
264         "${conf_d}/backup-script.conf" \
265         "/etc/backup-script.conf" \
266 ; do
267         [ -r "$conf" ] && break
268 done
269
270 while [ $# -gt 0 ]; do
271         case "$1" in
272           "-n"|"--dry-run")
273                 DRYRUN=1; shift
274                 ;;
275           "-p"|"--progress")
276                 VERBOSE=1; shift
277                 ;;
278           "-"*)
279                 Usage
280                 ;;
281           *)
282                 break
283         esac
284 done
285
286 trap GotSignal SIGINT
287
288 echo -n "Started: "; date
289
290 # Read in configuration file
291 if [ -r "$conf" ]; then
292         echo "Reading configuration: \"$conf\" ..."
293         source "$conf"
294 else
295         echo "No configuration file found, using defaults."
296 fi
297 echo
298
299 if [ $# -ge 1 ]; then
300         for s in "$@"; do
301                 if [ ! -r "${conf_d}/$s" ]; then
302                         echo "$NAME: Can' read \"${conf_d}/$s\"!"
303                         exit 1
304                 fi
305                 sys="$sys ${conf_d}/$s"
306         done
307 else
308         sys="${conf_d}/"*
309 fi
310
311 # check and create PID file
312 if [ -e "$PIDFILE" ]; then
313         echo "Lockfile \"$PIDFILE\" already exists."
314         echo "Is an other instance still running?"
315         echo
316         echo -n "Aborted: "; date
317         echo
318         exit 3
319 fi
320 touch "$PIDFILE" 2>/dev/null
321 if [ $? -ne 0 ]; then
322         echo "Warning: can't create PID file \"$PIDFILE\"!"
323         echo
324 else
325         echo "$$" >>"$PIDFILE"
326 fi
327
328 if [ -n "$pre_exec" ]; then
329         echo "Executing \"$pre_exec\" ..."
330         sh -c $pre_exec
331         if [ $? -ne 0 ]; then
332                 echo "Error: pre-exec command failed!"; echo
333                 CleanUp
334                 echo "Aborting backup."; echo
335                 exit 2
336         fi
337         sleep 2
338         echo
339 fi
340
341 for f in $sys; do
342         [ -r "$f" -a -f "$f" ] || continue
343
344         fname=$(basename "$f")
345         case "$fname" in
346                 "backup-script.conf"|*.sh)
347                         continue
348                         ;;
349         esac
350
351         # Set global defaults
352         system="$fname"
353         user="$default_user"
354         source_root="$default_source_root"
355         target="$default_target"
356         ssh_args_add="$default_ssh_args_add"
357         rsync_args_add="$default_rsync_args_add"
358         exclude_args_add="$default_exclude_args_add"
359         compress="$default_compress"
360         ping="$default_ping"
361         local="$default_local"
362         generations="$default_generations"
363         job_pre_exec="$default_job_pre_exec"
364         job_post_exec="$default_job_post_exec"
365
366         # Compatibility with backup-pull(1) script: Save global values ...
367         pre_exec_saved="$pre_exec"
368         post_exec_saved="$post_exec"
369
370         # Compatibility with backup-pull(1) script: Set defaults
371         unset host
372         unset source
373         unset pre_exec
374         unset post_exec
375
376         # Read in system configuration file
377         source "$f"
378
379         # Compatibility with backup-pull(1) script: Fix up configuration
380         [ "$system" = "$fname" -a -n "$host" ] \
381                 && system="$host"
382         [ "$source_root" = "$default_source_root" -a -n "$source" ] \
383                 && source_root="$source"
384         [ -z "$job_pre_exec" -a -n "$pre_exec" ] \
385                 && job_pre_exec="$pre_exec"
386         [ -z "$job_post_exec" -a -n "$post_exec" ] \
387                 && job_post_exec="$post_exec"
388
389         # Compatibility with backup-pull(1) script: Restore global values ...
390         pre_exec="$pre_exec_saved"
391         post_exec="$post_exec_saved"
392
393         # Validate configuration
394         [ "$system" = "localhost" -o "$system" = "127.0.0.1" ] && local=1
395
396         # Make sure "source" ends with a slash ("/")
397         case "$source" in
398           "*/")
399                 ;;
400           "*")
401                 source="$source/"
402         esac
403
404         # Make sure "target" DOESN'T end with a slash ("/")
405         case "$target" in
406           "*/")
407                 target=$( echo "$target" | sed -e 's/\/$//g' )
408                 ;;
409         esac
410
411         [ "$system" = "$fname" ] \
412                 && systxt="\"$system\"" \
413                 || systxt="\"$fname\" [\"$system\"]"
414         [ "$local" -eq 0 ] \
415                 && echo "Working on $systxt ..." \
416                 || echo "Working on $systxt (local system) ..."
417
418         count_all=$count_all+1
419
420         # Check target directory
421         if [ -z "$target" ]; then
422                 echo "No target directory specified for \"$system\"!? Skipped!"
423                 echo; continue
424         fi
425         if [ ! -d "$target" ]; then
426                 echo "Target \"$target\" is not a directory!? \"$system\" skipped!"
427                 echo; continue
428         fi
429
430         sys_target="$target/$fname"
431         sys_root="$sys_target"
432         if [ "$DRYRUN" -eq 0 -a ! -e "$sys_target" ]; then
433                 if [ $generations -gt 0 ]; then
434                         CreateSubvolume "$sys_target"
435                 else
436                         mkdir -p "$sys_target"
437                 fi
438                 if [ $? -ne 0 ]; then
439                         echo "Can't create \"$sys_target\"!? \"$system\" skipped!"
440                         echo; continue
441                 fi
442         fi
443
444         if [ "$local" -eq 0 -a "$ping" -ne 0 ]; then
445                 # Check if system is alive
446                 ping -c 1 "$system" >/dev/null 2>&1
447                 if [ $? -ne 0 ]; then
448                         echo "Host \"$system\" seems not to be alive!? Skipped."
449                         echo; continue
450                 fi
451                 echo "OK, host \"$system\" seems to be alive."
452         fi
453
454         if [ $generations -gt 0 ]; then
455                 # Make sure no old backup is stored in system directory
456                 if [ -e "$sys_target/.stamp" ]; then
457                         # There seems to be a genearation-less backup in the
458                         # target directory!
459                         echo "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
460                         echo; continue
461                 fi
462
463                 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
464
465                 if [ -n "$last" -a ! -e "$last/.stamp" ]; then
466                         # Old backup directory without "stamp file", continue
467                         echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
468                         RenameSubvolume "$last" "$sys_target"
469                         if [ $? -ne 0 ]; then
470                                 echo "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
471                                 echo; continue
472                         fi
473                 elif [ -n "$last" ]; then
474                         # Old backup directory found, create new snapshot
475                         echo "Found last snapshot in \"$last\"."
476                         if [ "$DRYRUN" -eq 0 ]; then
477                                 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
478                                 if [ $r -ne 0 ]; then
479                                         echo "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
480                                         echo; continue
481                                 fi
482                                 echo "Created new snapshot in \"$snapshot\"."
483                         else
484                                 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
485                         fi
486                 else
487                         # No old backup found, create new subvolume
488                         if [ "$DRYRUN" -eq 0 ]; then
489                                 CreateSubvolume "$sys_target"; r=$?
490                                 if [ $r -ne 0 ]; then
491                                         echo "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
492                                         echo; continue
493                                 fi
494                                 echo "Created new subvolume in \"$sys_target\"."
495                         else
496                                 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
497                         fi
498                 fi
499         fi
500
501         ssh_cmd="ssh"
502         [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
503
504         # execute job "pre-exec" command, if any
505         if [ -n "$job_pre_exec" ]; then
506                 ExecJob pre "$job_pre_exec" ; ret=$?
507                 if [ $ret -ne 0 ]; then
508                         [ $ret -ne 99 ] && count_started=$count_started+1
509                         echo "Pre-exec command failed, \"$system\" skipped!"
510                         echo; continue
511                 fi
512         fi
513
514         # prepare (remote) command ...
515         cmd="rsync --archive"
516         [ "$compress" -ne 0 ] && cmd="$cmd --compress"
517         [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
518         cmd="$cmd --delete --delete-excluded --sparse"
519         [ "$VERBOSE" -gt 0 ] && cmd="$cmd --progress"
520         if [ "$source_root" = "$default_source_root" ]; then
521                 cmd="$cmd --exclude=/dev --exclude=/proc --exclude=/sys"
522                 cmd="$cmd --exclude=/run --exclude=/tmp --exclude=/var/tmp"
523                 cmd="$cmd --exclude=/media --exclude=/mnt --exclude=/net"
524                 cmd="$cmd --exclude=/var/cache/apt --exclude=/var/log"
525         fi
526         [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
527         [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
528
529         [ "$local" -eq 0 ] \
530                 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
531                 || cmd="$cmd $source_root $sys_target/"
532
533         echo "Backing up to \"$sys_target\" ..."
534         echo -n "Start date: "; date
535         echo "$cmd"
536         count_started=$count_started+1
537         ok=0
538
539         if [ "$DRYRUN" -eq 0 ]; then
540                 rm -f "$sys_target/.stamp"
541                 $SHELL -c "$cmd"; ret=$?
542                 echo "code=$ret" >"$sys_target/.stamp"
543         else
544                 echo " *** Trial run, not executing synchronization command!"
545                 ret=0
546         fi
547
548         if [ $ret -eq 20 ]; then
549                 echo "Backup of \"$system\" interrupted. Aborting ..."
550                 CleanUp
551                 exit 1
552         fi
553
554         echo -n "End date: "; date
555         if [ $ret -eq 0 -o $ret -eq 24 ]; then
556                 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
557
558                 echo "System \"$system\" completed with status $ret, OK."
559                 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
560                 ok=1
561         else
562                 echo "System \"$system\" completed with ERRORS, code $ret!"
563         fi
564
565         # execute job "post-exec" command, if any
566         if [ -n "$job_post_exec" ]; then
567                 ExecJob post "$job_post_exec"
568         fi
569
570         if [ $generations -gt 0 ]; then
571                 # Update "latest" symlink
572                 if [ "$DRYRUN" -eq 0 ]; then
573                         rm -f "$sys_root/latest"
574                         ln -s "$sys_target" "$sys_root/latest"
575                 fi
576                 # Clean up old generations
577                 declare -i gen_count=$generations+2
578                 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
579                 if [ -n "$to_delete" -a $ok -eq 1 ]; then
580                         [ "$DRYRUN" -eq 0 ] \
581                                 && echo "Deleting old backup generations (keep $generations) ..." \
582                                 || echo " *** Trial run, not deleting old generations:"
583                         for delete in $to_delete; do
584                                 dir="$sys_root/$delete"
585                                 if [ ! -e "$dir/.stamp" ]; then
586                                         echo "Not deleting \"$dir\", not a backup directory!?"
587                                         continue
588                                 fi
589                                 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
590                                  | cut -d':' -f2- | cut -d. -f1)
591                                 echo "Removing backup from" $last "..."
592                                 if [ "$DRYRUN" -eq 0 ]; then
593                                         DeleteSubvolume "$dir"
594                                         [ $? -eq 0 ] || \
595                                           echo "Failed to delete \"$dir\"!"
596                                 fi
597                         done
598                         echo -n "Clean up finished: "; date
599                 elif [ -n "$to_delete" ]; then
600                         echo "There have been errors, not cleaning up old generations!"
601                 else
602                         echo "Nothing to clean up."
603                 fi
604         fi
605
606         destinations="$destinations $target"
607         echo
608 done
609
610 sync
611
612 paths=$( echo $destinations | sed -e 's/ /\n/g' | sort | uniq )
613 if [ "$DRYRUN" -eq 0 -a -n "$paths" ]; then
614         df -h $paths
615         echo
616 fi
617
618 CleanUp
619
620 echo -n "Done: "; date
621 echo
622 [ $count_all -eq 1 ] && s="" || s="s"
623 echo " - $count_all job$s defined,"
624 [ $count_started -eq 1 ] && s="" || s="s"
625 echo " - $count_started job$s started,"
626 echo " - $count_ok done without errors."
627 echo
628
629 if [ $count_started -ne $count_ok ]; then
630         echo "----->  THERE HAVE BEEN ERRORS!  <-----"
631         echo
632 fi
633
634 # -eof-