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=""
58 echo "Usage: $NAME [<options>] [<job> [<job> [...]]]"
60 echo " -n, --dry-run Test run only, don't copy any data."
61 echo " -p, --progress Show progress, see rsync(1)."
62 echo " -t TAG, --tag TAG Only run jobs with tag TAG."
63 echo " -x, --no-exec Don't run global pre-/post-exec commands."
65 echo "When no <job> is given, all defined systems are used."
67 # shellcheck disable=SC2086
75 printf "%s\n" "$@" >&2
79 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
80 echo "Executing \"$post_exec\" ..."
81 if ! sh -c $post_exec; then
82 ErrorMsg "Warning: post-exec command failed!"
91 ErrorMsg "--> Got signal, cleaning up & aborting ..."
94 ErrorMsg -n "Aborted: " >&2; date
104 echo "Running job ${what}-exec command ..."
106 && cmd="$ssh_cmd ${user}@${system} $cmd"
107 echo -n "Start date (${what}-exec): "; date
109 if [ "$DRYRUN" -eq 0 ]; then
110 $SHELL -c "$cmd"; local ret=$?
112 echo " *** Trial run, not executing ${what}-exec command!"
115 if [ $ret -eq 0 ]; then
116 echo "The ${what}-exec command completed with status 0, OK."
118 ErrorMsg "The ${what}-exec command completed with ERRORS, code $ret!"
126 while [ -n "$dir" ]; do
127 findmnt -fn -o FSTYPE --raw "$dir" 2>/dev/null; local r=$?
128 if [ $r -eq 0 ]; then
130 elif [ $r -eq 127 ]; then
134 dir=$(dirname "$dir") || return 1
143 dir=$(dirname "$volume")
147 btrfs subvolume create "$volume" >/dev/null || return 1
150 zfs create "$(echo "$volume" | cut -c2-)" || return 1
153 ErrorMsg "CreateSubvolume: Incompatible FS type \"$fs\" on \"$dir\"!"
167 dir=$(dirname "source")
168 fs=$(GetFS "$source")
171 btrfs subvolume snapshot "$source" "$snapshot" >/dev/null || return 1
174 zfs snapshot "$snapshot" || return 1
175 link_name="$(echo "$snapshot" | cut -d@ -f2-)"
177 "current/.zfs/snapshot/$link_name" \
178 "$(dirname "$volume")/$link_name"
181 ErrorMsg "CloneSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
192 fs=$(GetFS "$source")
195 mv "$source" "$target" || return 1
199 "$(echo "$source" | cut -c2-)" \
200 "$(echo "$target" | cut -c2-)" \
204 ErrorMsg "RenameSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
216 fs=$(GetFS "$volume")
219 btrfs subvolume delete "$volume" >/dev/null || return 1
222 id="$(basename "$volume")"
223 if [ -h "$volume" ]; then
224 snapshot="$(dirname "$volume")/current@$id"
228 zfs destroy -r "$(echo "$snapshot" | cut -c2-)" >/dev/null || return 1
229 [ -h "$volume" ] && rm "$volume"
232 ErrorMsg "DeleteSubvolume: Incompatible FS type \"$fs\" on \"$volume\"!"
238 Initialize_Last_SysTarget_Snapshot() {
243 fs=$(GetFS "$sys_target")
246 # Search directory of last generation, if any
247 # shellcheck disable=SC2012
248 last=$(ls -1d "$sys_target"/[0-9]* 2>/dev/null | sort -r | head -n1)
249 if [ -n "$last" ]; then
250 if [ ! -d "$last" ]; then
251 ErrorMsg "Last snapshot \"$last\" seems not to be a directory!? \"$system\" skipped!"
256 sys_target="$sys_target/$(date +%Y%m%d-%H%M%S)"
257 snapshot="$sys_target"
260 # On ZFS, the last generation is always named "current"
261 if [ -e "$sys_target/current" ]; then
262 last="$sys_target/current"
263 if [ "$(uname)" = "Linux" ]; then
264 date=$(LC_ALL=C stat "$1" | grep "^Modify: " \
265 | cut -d':' -f2- | cut -d. -f1)
267 date=$(LC_ALL=C stat -f "%Sc" "$1")
269 date=$(echo "$date" | sed -e's/^ //g' -e 's/[-:]//g' -e 's/ /-/g')
273 date="$(date +%Y%m%d-%H%M%S)"
275 snapshot="$(echo "$sys_target/current" | cut -c2-)@$date"
276 sys_target="$sys_target/current"
279 ErrorMsg "Initialize_Last_SysTarget_Snapshot: Incompatible FS type \"$fs\" on \"$sys_target\"!"
285 # Search configuration file (last one is used as default!)
287 "/usr/local/etc/backup-script.conf" \
288 "/etc/backup-script.conf" \
289 "${conf_d}/backup-script.conf" \
290 "/usr/local/etc/backup-script.conf" \
292 [ -r "$conf" ] && break
295 # Read in configuration file
296 config_info="Configuration file is \"$conf\""
297 if [ -r "$conf" ]; then
298 # shellcheck source=/dev/null
301 config_info="${config_info} (not readable, using defaults)"
303 config_info="${config_info},\nusing \"$conf_d\" as configuration directory."
305 while [ $# -gt 0 ]; do
314 shift; TAG="$1"; shift
315 [ -n "$TAG" ] || Usage
328 echo -n "Started: "; date
329 echo -e "$config_info"
331 # Check rsync and its protocol version
332 if ! rsync=$(which "rsync" 2>/dev/null); then
333 ErrorMsg "Failed to detect rsync(1)! Is it installed in your \$PATH?"
336 if ! rsync_proto=$($rsync --version 2>/dev/null | head -n 1 | sed 's/.* protocol version \([0-9]*\)$/\1/'); then
337 ErrorMsg "Failed to detect protocol version of $rsync!"
340 echo "Rsync command is $rsync, protocol version $rsync_proto."
342 [[ -n "$TAG" ]] && echo "Running jobs tagged with \"$TAG\"."
345 if [ $# -ge 1 ]; then
347 if [ ! -r "${conf_d}/$s" ]; then
348 ErrorMsg "$NAME: Can' read \"${conf_d}/$s\"!"
351 sys+=("${conf_d}/$s")
357 if [[ -n "$setup_exec" && $PREPOSTEXEC -ne 0 ]]; then
358 echo "Executing \"$setup_exec\" ..."
359 if ! sh -c $setup_exec; then
360 ErrorMsg "Error: setup command failed!"; echo
361 ErrorMsg "Aborting backup."; echo
368 trap GotSignal SIGINT SIGTERM
370 # check and create PID file
371 if [ -e "$PIDFILE" ]; then
372 ErrorMsg "Lockfile \"$PIDFILE\" already exists."
373 ErrorMsg "Is an other instance still running?"
375 ErrorMsg -n "Aborted: " >&2; date
379 if ! touch "$PIDFILE" 2>/dev/null; then
380 ErrorMsg "Warning: can't create PID file \"$PIDFILE\"!"
383 echo "$$" >>"$PIDFILE"
386 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
387 echo "Executing \"$pre_exec\" ..."
388 if ! sh -c $pre_exec; then
389 ErrorMsg "Error: pre-exec command failed!"; echo
391 ErrorMsg "Aborting backup."; echo
398 for f in "${sys[@]}"; do
399 [[ -r "$f" && -f "$f" ]] || continue
401 fname=$(basename "$f")
403 "backup-script.conf"|*.sh)
408 # Set global defaults
410 backup_type="$default_backup_type"
412 source_root="$default_source_root"
413 files="$default_files"
414 target="$default_target"
415 ssh_args_add="$default_ssh_args_add"
416 rsync_args_add="$default_rsync_args_add"
417 exclude_args_add="$default_exclude_args_add"
418 exclude_dirs_add="$default_exclude_dirs_add"
419 compress="$default_compress"
421 local="$default_local"
422 generations="$default_generations"
423 job_pre_exec="$default_job_pre_exec"
424 job_post_exec="$default_job_post_exec"
426 io_timeout="$default_io_timeout"
428 # Compatibility with backup-pull(1) script: Save global values ...
429 pre_exec_saved="$pre_exec"
430 post_exec_saved="$post_exec"
432 # Compatibility with backup-pull(1) script: Set defaults
438 # Read in system configuration file
439 # shellcheck source=/dev/null
442 # Compatibility with backup-pull(1) script: Fix up configuration
443 [[ "$system" = "$fname" && -n "$host" ]] \
445 [[ "$source_root" = "$default_source_root" && -n "$source" ]] \
446 && source_root="$source"
447 [[ -z "$job_pre_exec" && -n "$pre_exec" ]] \
448 && job_pre_exec="$pre_exec"
449 [[ -z "$job_post_exec" && -n "$post_exec" ]] \
450 && job_post_exec="$post_exec"
452 # Compatibility with backup-pull(1) script: Restore global values ...
453 pre_exec="$pre_exec_saved"
454 post_exec="$post_exec_saved"
456 # Validate configuration
457 if [[ "$system" = "localhost" || "$system" = "127.0.0.1" ]]; then
463 # Add "NONE" tag when no tags are given in the config file:
464 [[ -z "$tags" ]] && tags="NONE"
466 [[ "$local" -eq 1 ]] && tags="$tags,LOCAL"
468 if [[ -n "$TAG" && "$TAG" != "ALL" ]]; then
469 if ! echo "$tags" | grep -E "(^|,)$TAG(,|$)" >/dev/null 2>&1; then
470 if [ "$DRYRUN" -ne 0 ]; then
471 echo "Tags of system \"$system\" don't match \"$TAG\": \"$tags\". Skipped."
478 # Make sure "source_root" ends with a slash ("/")
479 case "$source_root" in
483 source_root="$source_root/"
486 # Make sure "target" DOESN'T end with a slash ("/")
489 target=$( echo "$target" | sed -e 's/\/$//g' )
493 [ "$system" = "$fname" ] \
494 && systxt="\"$system\"" \
495 || systxt="\"$fname\" [\"$system\"]"
497 && echo "Working on $systxt ..." \
498 || echo "Working on $systxt (local system) ..."
500 count_all=$count_all+1
502 # Check if job is disabled
503 if [ "$backup_type" = "disabled" ]; then
504 echo "Job is DISABLED and will be skipped."
508 count_enabled=$count_enabled+1
510 # Check target directory
511 if [ -z "$target" ]; then
512 ErrorMsg "No target directory specified for \"$system\"!? Skipped!"
515 if [ ! -d "$target" ]; then
516 ErrorMsg "Target \"$target\" is not a directory!? \"$system\" skipped!"
520 sys_target="$target/$fname"
521 sys_root="$sys_target"
522 if [[ "$DRYRUN" -eq 0 && ! -e "$sys_target" ]]; then
523 if [ $generations -gt 0 ]; then
524 CreateSubvolume "$sys_target"; r=$?
526 mkdir -p "$sys_target"; r=$?
528 if [ $r -ne 0 ]; then
529 ErrorMsg "Can't create \"$sys_target\"!? \"$system\" skipped!"
534 if [[ "$local" -eq 0 && "$ping" -ne 0 ]]; then
535 # Check if system is alive
536 if ! ping -c 1 "$system" >/dev/null 2>&1; then
537 ErrorMsg "Host \"$system\" seems not to be alive!? Skipped."
540 echo "OK, host \"$system\" seems to be alive."
543 if [ $generations -gt 0 ]; then
544 # Make sure no old backup is stored in system directory
545 if [ -e "$sys_target/.stamp" ]; then
546 # There seems to be a genearation-less backup in the
548 ErrorMsg "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
552 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
554 if [[ -n "$last" && ! -e "$last/.stamp" ]]; then
555 # Old backup directory without "stamp file", continue
556 echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
557 if [ "$DRYRUN" -eq 0 ]; then
558 if ! RenameSubvolume "$last" "$sys_target"; then
559 ErrorMsg "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
563 echo " *** Trial run, not renaming snapshot \"$last\" to \"$sys_target\"!"
565 elif [ -n "$last" ]; then
566 # Old backup directory found, create new snapshot
567 echo "Found last snapshot in \"$last\"."
568 if [ "$DRYRUN" -eq 0 ]; then
569 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
570 if [ $r -ne 0 ]; then
571 ErrorMsg "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
574 echo "Created new snapshot in \"$snapshot\"."
576 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
579 # No old backup found, create new subvolume
580 if [ "$DRYRUN" -eq 0 ]; then
581 CreateSubvolume "$sys_target"; r=$?
582 if [ $r -ne 0 ]; then
583 ErrorMsg "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
586 echo "Created new subvolume in \"$sys_target\"."
588 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
594 [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
596 # execute job "pre-exec" command, if any
597 if [ -n "$job_pre_exec" ]; then
598 ExecJob pre "$job_pre_exec" ; ret=$?
599 if [ $ret -ne 0 ]; then
600 [ $ret -ne 99 ] && count_started=$count_started+1
601 ErrorMsg "Pre-exec command failed, \"$system\" skipped!"
606 # prepare (remote) command ...
607 if [[ "$backup_type" == "rsync" ]]; then
608 cmd="$rsync --archive --timeout=$io_timeout"
609 [ "$compress" -ne 0 ] && cmd="$cmd --compress"
610 [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
611 cmd="$cmd --delete-during --delete-excluded --sparse"
612 if [ "$VERBOSE" -gt 0 ]; then
613 [ "$rsync_proto" -ge 31 ] \
614 && cmd="$cmd --info=progress2" \
615 || cmd="$cmd --progress"
618 if [ "$source_root" = "$default_source_root" ]; then
628 "/var/cache/apt/**" \
632 cmd="$cmd --exclude=$dir"
635 [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
636 for dir in $exclude_dirs_add; do
637 cmd="$cmd --exclude=$dir"
639 [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
643 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
644 || cmd="$cmd $source_root $sys_target/"
645 elif [[ "$backup_type" == "scp" ]]; then
647 [ "$VERBOSE" -eq 0 ] && cmd="$cmd -q"
648 for file in $files; do
649 cmd="$cmd ${user}@${system}:$file $sys_target/"
652 ErrorMsg "Backup type \"$backup_type\" undefined, \"$system\" skipped!"
656 echo "Backing up to \"$sys_target\" ..."
657 echo -n "Start date: "; date
659 count_started=$count_started+1
662 if [ "$DRYRUN" -eq 0 ]; then
663 stamp_file="$sys_target/.stamp"
666 # Execute backup command:
667 start_t=$(date "+%s")
668 $SHELL -c "$cmd"; ret=$?
673 echo "start_t=$start_t"
676 echo "backup_host='$(hostname -f)'"
677 echo "backup_user='$(id -un)'"
680 echo " *** Trial run, not executing save command!"
684 if [ $ret -eq 20 ]; then
685 ErrorMsg "Backup of \"$system\" interrupted. Aborting ..."
689 echo -n "End date: "; date
690 if [[ $ret -eq 0 || $ret -eq 24 ]]; then
691 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
693 echo "System \"$system\" completed with status $ret, OK."
694 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
697 ErrorMsg "System \"$system\" completed with ERRORS, code $ret!"
700 # execute job "post-exec" command, if any
701 if [ -n "$job_post_exec" ]; then
702 ExecJob post "$job_post_exec"
705 if [ $generations -gt 0 ]; then
706 # Update "latest" symlink
707 if [ "$DRYRUN" -eq 0 ]; then
708 rm -f "$sys_root/latest"
709 ln -s "$sys_target" "$sys_root/latest"
711 # Clean up old generations
712 declare -i gen_count=$generations+2
713 # shellcheck disable=SC2012
714 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
715 if [[ -n "$to_delete" && $ok -eq 1 ]]; then
716 [ "$DRYRUN" -eq 0 ] \
717 && echo "Deleting old backup generations (keep $generations) ..." \
718 || echo " *** Trial run, not deleting old generations:"
719 for delete in $to_delete; do
720 dir="$sys_root/$delete"
721 if [ ! -e "$dir/.stamp" ]; then
722 ErrorMsg "Not deleting \"$dir\" of \"$system\", not a backup directory!?"
725 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
726 | cut -d':' -f2- | cut -d. -f1)
727 # shellcheck disable=SC2086
728 echo "Removing backup from" $last "..."
729 if [ "$DRYRUN" -eq 0 ]; then
730 DeleteSubvolume "$dir" \
731 || ErrorMsg "Failed to delete \"$dir\" of \"$system\"!"
734 echo -n "Clean up finished: "; date
735 elif [ -n "$to_delete" ]; then
736 ErrorMsg "There have been errors for \"$system\", not cleaning up old generations!"
738 echo "Nothing to clean up (keep up to $generations generations)."
742 destinations="$destinations $target"
748 if [ "$DRYRUN" -eq 0 ]; then
751 # shellcheck disable=SC2086
752 for dest in $(echo $destinations | sed -e 's/ /\n/g' | sort | uniq); do
756 paths_zfs="$paths_zfs $dest"
762 if [ -n "$paths" ]; then
763 # shellcheck disable=SC2086
767 if [ -n "$paths_zfs" ]; then
768 # shellcheck disable=SC2086
776 echo -n "Done: "; date
778 [ $count_all -eq 1 ] && s="" || s="s"
779 [ $count_enabled -eq $count_all ] \
780 && echo " - $count_all job$s defined (all enabled)," \
781 || echo " - $count_all job$s defined ($count_enabled enabled),"
782 [ $count_started -eq 1 ] && s="" || s="s"
783 echo " - $count_started job$s started,"
784 echo " - $count_ok done without errors."
787 if [ $count_started -ne $count_ok ]; then
788 echo "-----> THERE HAVE BEEN ERRORS! <-----"
791 elif [ $count_enabled -ne $count_started ]; then