3 # backup-script system for cloning systems using rsync
4 # Copyright (c)2008-2017 Alexander Barton <alex@barton.de>
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.
14 PIDFILE="/var/run/$NAME.pid"
23 declare -i count_all=0
24 declare -i count_started=0
26 declare -i count_ok_vanished=0
27 declare -i count_enabled=0
31 # Default settings, can be overwritten in backup-script.conf:
32 [ -d "/usr/local/etc/backup-script.d" ] \
33 && conf_d="/usr/local/etc/backup-script.d" \
34 || conf_d="/etc/backup-script.d"
38 default_backup_type="rsync"
39 default_source_root="/"
40 default_files="running-config"
41 default_target="/var/backups"
43 default_ssh_args_add=""
44 default_rsync_args_add=""
45 default_exclude_args_add=""
46 default_exclude_dirs_add=""
51 default_io_timeout="1800"
52 default_job_pre_exec=""
53 default_job_post_exec=""
62 echo "Usage: $NAME [<options>] [<job> [<job> [...]]]"
64 echo " -n, --dry-run Test run only, don't copy any data."
65 echo " -p, --progress Show progress, see rsync(1)."
66 echo " -t TAG, --tag TAG Only run jobs with tag TAG."
67 echo " -x, --no-exec Don't run global pre-/post-exec commands."
69 echo "When no <job> is given, all defined systems are used."
71 # shellcheck disable=SC2086
79 printf "%s\n" "$@" >&2
83 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
84 echo "Executing \"$post_exec\" ..."
85 if ! sh -c $post_exec; then
86 ErrorMsg "Warning: post-exec command failed!"
95 ErrorMsg "--> Got signal, cleaning up & aborting ..."
98 ErrorMsg -n "Aborted: " >&2; date
108 echo "Running job ${what}-exec command ..."
110 && cmd="$ssh_cmd ${user}@${system} $cmd"
111 echo -n "Start date (${what}-exec): "; date
113 if [ "$DRYRUN" -eq 0 ]; then
114 $SHELL -c "$cmd"; local ret=$?
116 echo " *** Trial run, not executing ${what}-exec command!"
119 if [ $ret -eq 0 ]; then
120 echo "The ${what}-exec command completed with status 0, OK."
122 ErrorMsg "The ${what}-exec command completed with ERRORS, code $ret!"
130 while [ -n "$dir" ]; do
131 findmnt -fn -o FSTYPE --raw "$dir" 2>/dev/null; local r=$?
132 if [ $r -eq 0 ]; then
134 elif [ $r -eq 127 ]; then
138 dir=$(dirname "$dir") || return 1
147 dir=$(dirname "$volume")
151 btrfs subvolume create "$volume" >/dev/null || return 1
154 zfs create "$(echo "$volume" | cut -c2-)" || return 1
157 ErrorMsg "CreateSubvolume: Incompatible FS type \"$fs\" on \"$dir\"!"
171 dir=$(dirname "source")
172 fs=$(GetFS "$source")
175 btrfs subvolume snapshot "$source" "$snapshot" >/dev/null || return 1
178 zfs snapshot "$snapshot" || return 1
179 link_name="$(echo "$snapshot" | cut -d@ -f2-)"
181 "current/.zfs/snapshot/$link_name" \
182 "$(dirname "$volume")/$link_name"
185 ErrorMsg "CloneSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
196 fs=$(GetFS "$source")
199 mv "$source" "$target" || return 1
203 "$(echo "$source" | cut -c2-)" \
204 "$(echo "$target" | cut -c2-)" \
208 ErrorMsg "RenameSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
220 fs=$(GetFS "$volume")
223 btrfs subvolume delete "$volume" >/dev/null || return 1
226 id="$(basename "$volume")"
227 if [ -h "$volume" ]; then
228 snapshot="$(dirname "$volume")/current@$id"
232 zfs destroy -r "$(echo "$snapshot" | cut -c2-)" >/dev/null || return 1
233 [ -h "$volume" ] && rm "$volume"
236 ErrorMsg "DeleteSubvolume: Incompatible FS type \"$fs\" on \"$volume\"!"
242 Initialize_Last_SysTarget_Snapshot() {
247 fs=$(GetFS "$sys_target")
250 # Search directory of last generation, if any
251 # shellcheck disable=SC2012
252 last=$(ls -1d "$sys_target"/[0-9]* 2>/dev/null | sort -r | head -n1)
253 if [ -n "$last" ]; then
254 if [ ! -d "$last" ]; then
255 ErrorMsg "Last snapshot \"$last\" seems not to be a directory!? \"$system\" skipped!"
260 sys_target="$sys_target/$(date +%Y%m%d-%H%M%S)"
261 snapshot="$sys_target"
264 # On ZFS, the last generation is always named "current"
265 if [ -e "$sys_target/current" ]; then
266 last="$sys_target/current"
267 if [ "$(uname)" = "Linux" ]; then
268 date=$(LC_ALL=C stat "$1" | grep "^Modify: " \
269 | cut -d':' -f2- | cut -d. -f1)
271 date=$(LC_ALL=C stat -f "%Sc" "$1")
273 date=$(echo "$date" | sed -e's/^ //g' -e 's/[-:]//g' -e 's/ /-/g')
277 date="$(date +%Y%m%d-%H%M%S)"
279 snapshot="$(echo "$sys_target/current" | cut -c2-)@$date"
280 sys_target="$sys_target/current"
283 ErrorMsg "Initialize_Last_SysTarget_Snapshot: Incompatible FS type \"$fs\" on \"$sys_target\"!"
289 # Search configuration file (last one is used as default!)
291 "/usr/local/etc/backup-script.conf" \
292 "/etc/backup-script.conf" \
293 "${conf_d}/backup-script.conf" \
294 "/usr/local/etc/backup-script.conf" \
296 [ -r "$conf" ] && break
299 # Read in configuration file
300 config_info="Configuration file is \"$conf\""
301 if [ -r "$conf" ]; then
302 # shellcheck source=/dev/null
305 config_info="${config_info} (not readable, using defaults)"
307 config_info="${config_info},\nusing \"$conf_d\" as configuration directory."
309 while [ $# -gt 0 ]; do
318 shift; TAG="$1"; shift
319 [ -n "$TAG" ] || Usage
332 echo -n "Started: "; date
333 echo -e "$config_info"
335 # Check rsync and its protocol version
336 if ! rsync=$(which "rsync" 2>/dev/null); then
337 ErrorMsg "Failed to detect rsync(1)! Is it installed in your \$PATH?"
340 if ! rsync_proto=$($rsync --version 2>/dev/null | head -n 1 | sed 's/.* protocol version \([0-9]*\)$/\1/'); then
341 ErrorMsg "Failed to detect protocol version of $rsync!"
344 echo "Rsync command is $rsync, protocol version $rsync_proto."
346 [[ -n "$TAG" ]] && echo "Running jobs tagged with \"$TAG\"."
349 if [ $# -ge 1 ]; then
351 if [ ! -r "${conf_d}/$s" ]; then
352 ErrorMsg "$NAME: Can' read \"${conf_d}/$s\"!"
355 sys+=("${conf_d}/$s")
361 if [[ -n "$setup_exec" && $PREPOSTEXEC -ne 0 ]]; then
362 echo "Executing \"$setup_exec\" ..."
363 if ! sh -c $setup_exec; then
364 ErrorMsg "Error: setup command failed!"; echo
365 ErrorMsg "Aborting backup."; echo
372 trap GotSignal SIGINT SIGTERM
374 # check and create PID file
375 if [ -e "$PIDFILE" ]; then
376 ErrorMsg "Lockfile \"$PIDFILE\" already exists."
377 ErrorMsg "Is an other instance still running?"
379 ErrorMsg -n "Aborted: " >&2; date
383 if ! touch "$PIDFILE" 2>/dev/null; then
384 ErrorMsg "Warning: can't create PID file \"$PIDFILE\"!"
387 echo "$$" >>"$PIDFILE"
390 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
391 echo "Executing \"$pre_exec\" ..."
392 if ! sh -c $pre_exec; then
393 ErrorMsg "Error: pre-exec command failed!"; echo
395 ErrorMsg "Aborting backup."; echo
402 for f in "${sys[@]}"; do
403 [[ -r "$f" && -f "$f" ]] || continue
405 fname=$(basename "$f")
407 "backup-script.conf"|*.sh)
412 # Set global defaults
414 backup_type="$default_backup_type"
416 source_root="$default_source_root"
417 files="$default_files"
418 target="$default_target"
419 ssh_args_add="$default_ssh_args_add"
420 rsync_args_add="$default_rsync_args_add"
421 exclude_args_add="$default_exclude_args_add"
422 exclude_dirs_add="$default_exclude_dirs_add"
423 compress="$default_compress"
425 local="$default_local"
426 generations="$default_generations"
427 job_pre_exec="$default_job_pre_exec"
428 job_post_exec="$default_job_post_exec"
430 io_timeout="$default_io_timeout"
432 # Compatibility with backup-pull(1) script: Save global values ...
433 pre_exec_saved="$pre_exec"
434 post_exec_saved="$post_exec"
436 # Compatibility with backup-pull(1) script: Set defaults
442 # Read in system configuration file
443 # shellcheck source=/dev/null
446 # Compatibility with backup-pull(1) script: Fix up configuration
447 [[ "$system" = "$fname" && -n "$host" ]] \
449 [[ "$source_root" = "$default_source_root" && -n "$source" ]] \
450 && source_root="$source"
451 [[ -z "$job_pre_exec" && -n "$pre_exec" ]] \
452 && job_pre_exec="$pre_exec"
453 [[ -z "$job_post_exec" && -n "$post_exec" ]] \
454 && job_post_exec="$post_exec"
456 # Compatibility with backup-pull(1) script: Restore global values ...
457 pre_exec="$pre_exec_saved"
458 post_exec="$post_exec_saved"
460 # Validate configuration
461 if [[ "$system" = "localhost" || "$system" = "127.0.0.1" ]]; then
467 # Add "NONE" tag when no tags are given in the config file:
468 [[ -z "$tags" ]] && tags="NONE"
470 [[ "$local" -eq 1 ]] && tags="$tags,LOCAL"
472 if [[ -n "$TAG" && "$TAG" != "ALL" ]]; then
473 if ! echo "$tags" | grep -E "(^|,)$TAG(,|$)" >/dev/null 2>&1; then
474 if [ "$DRYRUN" -ne 0 ]; then
475 echo "Tags of system \"$system\" don't match \"$TAG\": \"$tags\". Skipped."
482 # Make sure "source_root" ends with a slash ("/")
483 case "$source_root" in
487 source_root="$source_root/"
490 # Make sure "target" DOESN'T end with a slash ("/")
493 target=$( echo "$target" | sed -e 's/\/$//g' )
497 [ "$system" = "$fname" ] \
498 && systxt="\"$system\"" \
499 || systxt="\"$fname\" [\"$system\"]"
501 && echo "Working on $systxt ..." \
502 || echo "Working on $systxt (local system) ..."
504 count_all=$count_all+1
506 # Check if job is disabled
507 if [ "$backup_type" = "disabled" ]; then
508 echo "Job is DISABLED and will be skipped."
512 count_enabled=$count_enabled+1
514 # Check target directory
515 if [ -z "$target" ]; then
516 ErrorMsg "No target directory specified for \"$system\"!? Skipped!"
519 if [ ! -d "$target" ]; then
520 ErrorMsg "Target \"$target\" is not a directory!? \"$system\" skipped!"
524 sys_target="$target/$fname"
525 sys_root="$sys_target"
526 if [[ "$DRYRUN" -eq 0 && ! -e "$sys_target" ]]; then
527 if [ $generations -gt 0 ]; then
528 CreateSubvolume "$sys_target"; r=$?
530 mkdir -p "$sys_target"; r=$?
532 if [ $r -ne 0 ]; then
533 ErrorMsg "Can't create \"$sys_target\"!? \"$system\" skipped!"
538 if [[ "$local" -eq 0 && "$ping" -ne 0 ]]; then
539 # Check if system is alive
540 if ! ping -c 1 "$system" >/dev/null 2>&1; then
541 ErrorMsg "Host \"$system\" seems not to be alive!? Skipped."
544 echo "OK, host \"$system\" seems to be alive."
547 if [ $generations -gt 0 ]; then
548 # Make sure no old backup is stored in system directory
549 if [ -e "$sys_target/.stamp" ]; then
550 # There seems to be a genearation-less backup in the
552 ErrorMsg "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
556 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
558 if [[ -n "$last" && ! -e "$last/.stamp" ]]; then
559 # Old backup directory without "stamp file", continue
560 echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
561 if [ "$DRYRUN" -eq 0 ]; then
562 if ! RenameSubvolume "$last" "$sys_target"; then
563 ErrorMsg "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
567 echo " *** Trial run, not renaming snapshot \"$last\" to \"$sys_target\"!"
569 elif [ -n "$last" ]; then
570 # Old backup directory found, create new snapshot
571 echo "Found last snapshot in \"$last\"."
572 if [ "$DRYRUN" -eq 0 ]; then
573 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
574 if [ $r -ne 0 ]; then
575 ErrorMsg "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
578 echo "Created new snapshot in \"$snapshot\"."
580 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
583 # No old backup found, create new subvolume
584 if [ "$DRYRUN" -eq 0 ]; then
585 CreateSubvolume "$sys_target"; r=$?
586 if [ $r -ne 0 ]; then
587 ErrorMsg "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
590 echo "Created new subvolume in \"$sys_target\"."
592 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
598 [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
600 # execute job "pre-exec" command, if any
601 if [ -n "$job_pre_exec" ]; then
602 ExecJob pre "$job_pre_exec" ; ret=$?
603 if [ $ret -ne 0 ]; then
604 [ $ret -ne 99 ] && count_started=$count_started+1
605 ErrorMsg "Pre-exec command failed, \"$system\" skipped!"
610 # prepare (remote) command ...
611 if [[ "$backup_type" == "rsync" ]]; then
612 cmd="$rsync --archive --timeout=$io_timeout"
613 [ "$compress" -ne 0 ] && cmd="$cmd --compress"
614 [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
615 cmd="$cmd --delete-during --delete-excluded --sparse"
616 if [ "$VERBOSE" -gt 0 ]; then
617 [ "$rsync_proto" -ge 31 ] \
618 && cmd="$cmd --info=progress2" \
619 || cmd="$cmd --progress"
622 if [ "$source_root" = "$default_source_root" ]; then
632 "/var/cache/apt/**" \
636 cmd="$cmd --exclude=$dir"
639 [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
640 for dir in $exclude_dirs_add; do
641 cmd="$cmd --exclude=$dir"
643 [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
647 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
648 || cmd="$cmd $source_root $sys_target/"
649 elif [[ "$backup_type" == "scp" ]]; then
651 [ "$VERBOSE" -eq 0 ] && cmd="$cmd -q"
652 for file in $files; do
653 cmd="$cmd ${user}@${system}:$file $sys_target/"
656 ErrorMsg "Backup type \"$backup_type\" undefined, \"$system\" skipped!"
660 echo "Backing up to \"$sys_target\" ..."
661 echo -n "Start date: "; date
663 count_started=$count_started+1
666 if [ "$DRYRUN" -eq 0 ]; then
667 stamp_file="$sys_target/.stamp"
670 # Execute backup command:
671 start_t=$(date "+%s")
672 $SHELL -c "$cmd"; ret=$?
677 echo "start_t=$start_t"
680 echo "backup_host='$(hostname -f)'"
681 echo "backup_user='$(id -un)'"
684 echo " *** Trial run, not executing save command!"
688 if [ $ret -eq 20 ]; then
689 ErrorMsg "Backup of \"$system\" interrupted. Aborting ..."
693 echo -n "End date: "; date
694 if [[ $ret -eq 0 || $ret -eq 24 ]]; then
695 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
697 echo "System \"$system\" completed with status $ret, OK."
698 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
701 ErrorMsg "System \"$system\" completed with ERRORS, code $ret!"
704 # execute job "post-exec" command, if any
705 if [ -n "$job_post_exec" ]; then
706 ExecJob post "$job_post_exec"
709 if [ $generations -gt 0 ]; then
710 # Update "latest" symlink
711 if [ "$DRYRUN" -eq 0 ]; then
712 rm -f "$sys_root/latest"
713 ln -s "$sys_target" "$sys_root/latest"
715 # Clean up old generations
716 declare -i gen_count=$generations+2
717 # shellcheck disable=SC2012
718 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
719 if [[ -n "$to_delete" && $ok -eq 1 ]]; then
720 [ "$DRYRUN" -eq 0 ] \
721 && echo "Deleting old backup generations (keep $generations) ..." \
722 || echo " *** Trial run, not deleting old generations:"
723 for delete in $to_delete; do
724 dir="$sys_root/$delete"
725 if [ ! -e "$dir/.stamp" ]; then
726 ErrorMsg "Not deleting \"$dir\" of \"$system\", not a backup directory!?"
729 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
730 | cut -d':' -f2- | cut -d. -f1)
731 # shellcheck disable=SC2086
732 echo "Removing backup from" $last "..."
733 if [ "$DRYRUN" -eq 0 ]; then
734 DeleteSubvolume "$dir" \
735 || ErrorMsg "Failed to delete \"$dir\" of \"$system\"!"
738 echo -n "Clean up finished: "; date
739 elif [ -n "$to_delete" ]; then
740 ErrorMsg "There have been errors for \"$system\", not cleaning up old generations!"
742 echo "Nothing to clean up (keep up to $generations generations)."
746 destinations="$destinations $target"
752 if [ "$DRYRUN" -eq 0 ]; then
755 # shellcheck disable=SC2086
756 for dest in $(echo $destinations | sed -e 's/ /\n/g' | sort | uniq); do
760 paths_zfs="$paths_zfs $dest"
766 if [ -n "$paths" ]; then
767 # shellcheck disable=SC2086
771 if [ -n "$paths_zfs" ]; then
772 # shellcheck disable=SC2086
780 echo -n "Done: "; date
782 [ $count_all -eq 1 ] && s="" || s="s"
783 [ $count_enabled -eq $count_all ] \
784 && echo " - $count_all job$s defined (all enabled)," \
785 || echo " - $count_all job$s defined ($count_enabled enabled),"
786 [ $count_started -eq 1 ] && s="" || s="s"
787 echo " - $count_started job$s started,"
788 echo " - $count_ok done without errors."
791 if [ $count_started -ne $count_ok ]; then
792 echo "-----> THERE HAVE BEEN ERRORS! <-----"
795 elif [ $count_enabled -ne $count_started ]; then