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