3 # backup-script system for cloning systems using rsync
4 # Copyright (c)2008-2016 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=""
57 echo "Usage: $NAME [<options>] [<job> [<job> [...]]]"
59 echo " -n, --dry-run Test run only, don't copy any data."
60 echo " -p, --progress Show progress, see rsync(1)."
61 echo " -t TAG, --tag TAG Only run jobs with tag TAG."
62 echo " -x, --no-exec Don't run global pre-/post-exec commands."
64 echo "When no <job> is given, all defined systems are used."
66 # shellcheck disable=SC2086
73 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
74 echo "Executing \"$post_exec\" ..."
75 if ! sh -c $post_exec; then
76 echo "Warning: post-exec command failed!"
85 echo "--> Got signal, cleaning up & aborting ..."
88 echo -n "Aborted: "; date
98 echo "Running job ${what}-exec command ..."
100 && cmd="$ssh_cmd ${user}@${system} $cmd"
101 echo -n "Start date (${what}-exec): "; date
103 if [ "$DRYRUN" -eq 0 ]; then
104 $SHELL -c "$cmd"; local ret=$?
106 echo " *** Trial run, not executing ${what}-exec command!"
110 && echo "The ${what}-exec command completed with status 0, OK." \
111 || echo "The ${what}-exec command completed with ERRORS, code $ret!"
118 while [ -n "$dir" ]; do
119 findmnt -fn -o FSTYPE --raw "$dir" 2>/dev/null; local r=$?
120 if [ $r -eq 0 ]; then
122 elif [ $r -eq 127 ]; then
126 dir=$(dirname "$dir") || return 1
135 dir=$(dirname "$volume")
139 btrfs subvolume create "$volume" >/dev/null || return 1
142 zfs create "$(echo "$volume" | cut -c2-)" || return 1
145 echo "CreateSubvolume: Incompatible FS type \"$fs\" on \"$dir\"!"
159 dir=$(dirname "source")
160 fs=$(GetFS "$source")
163 btrfs subvolume snapshot "$source" "$snapshot" >/dev/null || return 1
166 zfs snapshot "$snapshot" || return 1
167 link_name="$(echo "$snapshot" | cut -d@ -f2-)"
169 "current/.zfs/snapshot/$link_name" \
170 "$(dirname "$volume")/$link_name"
173 echo "CloneSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
184 fs=$(GetFS "$source")
187 mv "$source" "$target" || return 1
191 "$(echo "$source" | cut -c2-)" \
192 "$(echo "$target" | cut -c2-)" \
196 echo "RenameSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
208 fs=$(GetFS "$volume")
211 btrfs subvolume delete "$volume" >/dev/null || return 1
214 id="$(basename "$volume")"
215 if [ -h "$volume" ]; then
216 snapshot="$(dirname "$volume")/current@$id"
220 zfs destroy -r "$(echo "$snapshot" | cut -c2-)" >/dev/null || return 1
221 [ -h "$volume" ] && rm "$volume"
224 echo "DeleteSubvolume: Incompatible FS type \"$fs\" on \"$volume\"!"
230 Initialize_Last_SysTarget_Snapshot() {
235 fs=$(GetFS "$sys_target")
238 # Search directory of last generation, if any
239 # shellcheck disable=SC2012
240 last=$(ls -1d "$sys_target"/[0-9]* 2>/dev/null | sort -r | head -n1)
241 if [ -n "$last" ]; then
242 if [ ! -d "$last" ]; then
243 echo "Last snapshot \"$last\" seems not to be a directory!? \"$system\" skipped!"
248 sys_target="$sys_target/$(date +%Y%m%d-%H%M%S)"
249 snapshot="$sys_target"
252 # On ZFS, the last generation is always named "current"
253 if [ -e "$sys_target/current" ]; then
254 last="$sys_target/current"
255 if [ "$(uname)" = "Linux" ]; then
256 date=$(LC_ALL=C stat "$1" | grep "^Modify: " \
257 | cut -d':' -f2- | cut -d. -f1)
259 date=$(LC_ALL=C stat -f "%Sc" "$1")
261 date=$(echo "$date" | sed -e's/^ //g' -e 's/[-:]//g' -e 's/ /-/g')
265 date="$(date +%Y%m%d-%H%M%S)"
267 snapshot="$(echo "$sys_target/current" | cut -c2-)@$date"
268 sys_target="$sys_target/current"
271 echo "Initialize_Last_SysTarget_Snapshot: Incompatible FS type \"$fs\" on \"$sys_target\"!"
277 # Search configuration file (last one is used as default!)
279 "/usr/local/etc/backup-script.conf" \
280 "/etc/backup-script.conf" \
281 "${conf_d}/backup-script.conf" \
282 "/usr/local/etc/backup-script.conf" \
284 [ -r "$conf" ] && break
287 # Read in configuration file
288 config_info="Configuration file is \"$conf\""
289 if [ -r "$conf" ]; then
290 # shellcheck source=/dev/null
293 config_info="${config_info} (not readable, using defaults)"
295 config_info="${config_info},\nusing \"$conf_d\" as configuration directory."
297 while [ $# -gt 0 ]; do
306 shift; TAG="$1"; shift
307 [ -n "$TAG" ] || Usage
320 echo -n "Started: "; date
321 echo -e "$config_info"
323 # Check rsync and its protocol version
324 if ! rsync=$(which "rsync" 2>/dev/null); then
325 echo "Failed to detect rsync(1)! Is it installed in your \$PATH?"
328 if ! rsync_proto=$($rsync --version 2>/dev/null | head -n 1 | sed 's/.* protocol version \([0-9]*\)$/\1/'); then
329 echo "Failed to detect protocol version of $rsync!"
332 echo "Rsync command is $rsync, protocol version $rsync_proto."
334 [[ -n "$TAG" ]] && echo "Running jobs tagged with \"$TAG\"."
337 if [ $# -ge 1 ]; then
339 if [ ! -r "${conf_d}/$s" ]; then
340 echo "$NAME: Can' read \"${conf_d}/$s\"!"
343 sys+=("${conf_d}/$s")
349 if [[ -n "$setup_exec" && $PREPOSTEXEC -ne 0 ]]; then
350 echo "Executing \"$setup_exec\" ..."
351 if ! sh -c $setup_exec; then
352 echo "Error: setup command failed!"; echo
353 echo "Aborting backup."; echo
360 trap GotSignal SIGINT SIGTERM
362 # check and create PID file
363 if [ -e "$PIDFILE" ]; then
364 echo "Lockfile \"$PIDFILE\" already exists."
365 echo "Is an other instance still running?"
367 echo -n "Aborted: "; date
371 if ! touch "$PIDFILE" 2>/dev/null; then
372 echo "Warning: can't create PID file \"$PIDFILE\"!"
375 echo "$$" >>"$PIDFILE"
378 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
379 echo "Executing \"$pre_exec\" ..."
380 if ! sh -c $pre_exec; then
381 echo "Error: pre-exec command failed!"; echo
383 echo "Aborting backup."; echo
390 for f in "${sys[@]}"; do
391 [[ -r "$f" && -f "$f" ]] || continue
393 fname=$(basename "$f")
395 "backup-script.conf"|*.sh)
400 # Set global defaults
402 backup_type="$default_backup_type"
404 source_root="$default_source_root"
405 files="$default_files"
406 target="$default_target"
407 ssh_args_add="$default_ssh_args_add"
408 rsync_args_add="$default_rsync_args_add"
409 exclude_args_add="$default_exclude_args_add"
410 exclude_dirs_add="$default_exclude_dirs_add"
411 compress="$default_compress"
413 local="$default_local"
414 generations="$default_generations"
415 job_pre_exec="$default_job_pre_exec"
416 job_post_exec="$default_job_post_exec"
418 io_timeout="$default_io_timeout"
420 # Compatibility with backup-pull(1) script: Save global values ...
421 pre_exec_saved="$pre_exec"
422 post_exec_saved="$post_exec"
424 # Compatibility with backup-pull(1) script: Set defaults
430 # Read in system configuration file
431 # shellcheck source=/dev/null
434 # Compatibility with backup-pull(1) script: Fix up configuration
435 [[ "$system" = "$fname" && -n "$host" ]] \
437 [[ "$source_root" = "$default_source_root" && -n "$source" ]] \
438 && source_root="$source"
439 [[ -z "$job_pre_exec" && -n "$pre_exec" ]] \
440 && job_pre_exec="$pre_exec"
441 [[ -z "$job_post_exec" && -n "$post_exec" ]] \
442 && job_post_exec="$post_exec"
444 # Compatibility with backup-pull(1) script: Restore global values ...
445 pre_exec="$pre_exec_saved"
446 post_exec="$post_exec_saved"
448 # Validate configuration
449 if [[ "$system" = "localhost" || "$system" = "127.0.0.1" ]]; then
455 # Add "NONE" tag when no tags are given in the config file:
456 [[ -z "$tags" ]] && tags="NONE"
458 [[ "$local" -eq 1 ]] && tags="$tags,LOCAL"
460 if [[ -n "$TAG" && "$TAG" != "ALL" ]]; then
461 if ! echo "$tags" | grep -E "(^|,)$TAG(,|$)" >/dev/null 2>&1; then
462 if [ "$DRYRUN" -ne 0 ]; then
463 echo "Tags of system \"$system\" don't match \"$TAG\": \"$tags\". Skipped."
470 # Make sure "source_root" ends with a slash ("/")
471 case "$source_root" in
475 source_root="$source_root/"
478 # Make sure "target" DOESN'T end with a slash ("/")
481 target=$( echo "$target" | sed -e 's/\/$//g' )
485 [ "$system" = "$fname" ] \
486 && systxt="\"$system\"" \
487 || systxt="\"$fname\" [\"$system\"]"
489 && echo "Working on $systxt ..." \
490 || echo "Working on $systxt (local system) ..."
492 count_all=$count_all+1
494 # Check if job is disabled
495 if [ "$backup_type" = "disabled" ]; then
496 echo "Job is DISABLED and will be skipped."
500 count_enabled=$count_enabled+1
502 # Check target directory
503 if [ -z "$target" ]; then
504 echo "No target directory specified for \"$system\"!? Skipped!"
507 if [ ! -d "$target" ]; then
508 echo "Target \"$target\" is not a directory!? \"$system\" skipped!"
512 sys_target="$target/$fname"
513 sys_root="$sys_target"
514 if [[ "$DRYRUN" -eq 0 && ! -e "$sys_target" ]]; then
515 if [ $generations -gt 0 ]; then
516 CreateSubvolume "$sys_target"; r=$?
518 mkdir -p "$sys_target"; r=$?
520 if [ $r -ne 0 ]; then
521 echo "Can't create \"$sys_target\"!? \"$system\" skipped!"
526 if [[ "$local" -eq 0 && "$ping" -ne 0 ]]; then
527 # Check if system is alive
528 if ! ping -c 1 "$system" >/dev/null 2>&1; then
529 echo "Host \"$system\" seems not to be alive!? Skipped."
532 echo "OK, host \"$system\" seems to be alive."
535 if [ $generations -gt 0 ]; then
536 # Make sure no old backup is stored in system directory
537 if [ -e "$sys_target/.stamp" ]; then
538 # There seems to be a genearation-less backup in the
540 echo "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
544 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
546 if [[ -n "$last" && ! -e "$last/.stamp" ]]; then
547 # Old backup directory without "stamp file", continue
548 echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
549 if [ "$DRYRUN" -eq 0 ]; then
550 if ! RenameSubvolume "$last" "$sys_target"; then
551 echo "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
555 echo " *** Trial run, not renaming snapshot \"$last\" to \"$sys_target\"!"
557 elif [ -n "$last" ]; then
558 # Old backup directory found, create new snapshot
559 echo "Found last snapshot in \"$last\"."
560 if [ "$DRYRUN" -eq 0 ]; then
561 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
562 if [ $r -ne 0 ]; then
563 echo "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
566 echo "Created new snapshot in \"$snapshot\"."
568 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
571 # No old backup found, create new subvolume
572 if [ "$DRYRUN" -eq 0 ]; then
573 CreateSubvolume "$sys_target"; r=$?
574 if [ $r -ne 0 ]; then
575 echo "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
578 echo "Created new subvolume in \"$sys_target\"."
580 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
586 [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
588 # execute job "pre-exec" command, if any
589 if [ -n "$job_pre_exec" ]; then
590 ExecJob pre "$job_pre_exec" ; ret=$?
591 if [ $ret -ne 0 ]; then
592 [ $ret -ne 99 ] && count_started=$count_started+1
593 echo "Pre-exec command failed, \"$system\" skipped!"
598 # prepare (remote) command ...
599 if [[ "$backup_type" == "rsync" ]]; then
600 cmd="$rsync --archive --timeout=$io_timeout"
601 [ "$compress" -ne 0 ] && cmd="$cmd --compress"
602 [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
603 cmd="$cmd --delete-during --delete-excluded --sparse"
604 if [ "$VERBOSE" -gt 0 ]; then
605 [ "$rsync_proto" -ge 31 ] \
606 && cmd="$cmd --info=progress2" \
607 || cmd="$cmd --progress"
610 if [ "$source_root" = "$default_source_root" ]; then
620 "/var/cache/apt/**" \
624 cmd="$cmd --exclude=$dir"
627 [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
628 for dir in $exclude_dirs_add; do
629 cmd="$cmd --exclude=$dir"
631 [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
635 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
636 || cmd="$cmd $source_root $sys_target/"
637 elif [[ "$backup_type" == "scp" ]]; then
639 [ "$VERBOSE" -eq 0 ] && cmd="$cmd -q"
640 for file in $files; do
641 cmd="$cmd ${user}@${system}:$file $sys_target/"
644 echo "Backup type \"$backup_type\" undefined, \"$system\" skipped!"
648 echo "Backing up to \"$sys_target\" ..."
649 echo -n "Start date: "; date
651 count_started=$count_started+1
654 if [ "$DRYRUN" -eq 0 ]; then
655 stamp_file="$sys_target/.stamp"
658 # Execute backup command:
659 start_t=$(date "+%s")
660 $SHELL -c "$cmd"; ret=$?
665 echo "start_t=$start_t"
668 echo "backup_host='$(hostname -f)'"
669 echo "backup_user='$(id -un)'"
672 echo " *** Trial run, not executing save command!"
676 if [ $ret -eq 20 ]; then
677 echo "Backup of \"$system\" interrupted. Aborting ..."
681 echo -n "End date: "; date
682 if [[ $ret -eq 0 || $ret -eq 24 ]]; then
683 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
685 echo "System \"$system\" completed with status $ret, OK."
686 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
689 echo "System \"$system\" completed with ERRORS, code $ret!"
692 # execute job "post-exec" command, if any
693 if [ -n "$job_post_exec" ]; then
694 ExecJob post "$job_post_exec"
697 if [ $generations -gt 0 ]; then
698 # Update "latest" symlink
699 if [ "$DRYRUN" -eq 0 ]; then
700 rm -f "$sys_root/latest"
701 ln -s "$sys_target" "$sys_root/latest"
703 # Clean up old generations
704 declare -i gen_count=$generations+2
705 # shellcheck disable=SC2012
706 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
707 if [[ -n "$to_delete" && $ok -eq 1 ]]; then
708 [ "$DRYRUN" -eq 0 ] \
709 && echo "Deleting old backup generations (keep $generations) ..." \
710 || echo " *** Trial run, not deleting old generations:"
711 for delete in $to_delete; do
712 dir="$sys_root/$delete"
713 if [ ! -e "$dir/.stamp" ]; then
714 echo "Not deleting \"$dir\", not a backup directory!?"
717 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
718 | cut -d':' -f2- | cut -d. -f1)
719 # shellcheck disable=SC2086
720 echo "Removing backup from" $last "..."
721 if [ "$DRYRUN" -eq 0 ]; then
722 DeleteSubvolume "$dir" \
723 || echo "Failed to delete \"$dir\"!"
726 echo -n "Clean up finished: "; date
727 elif [ -n "$to_delete" ]; then
728 echo "There have been errors, not cleaning up old generations!"
730 echo "Nothing to clean up (keep up to $generations generations)."
734 destinations="$destinations $target"
740 if [ "$DRYRUN" -eq 0 ]; then
743 # shellcheck disable=SC2086
744 for dest in $(echo $destinations | sed -e 's/ /\n/g' | sort | uniq); do
748 paths_zfs="$paths_zfs $dest"
754 if [ -n "$paths" ]; then
755 # shellcheck disable=SC2086
759 if [ -n "$paths_zfs" ]; then
760 # shellcheck disable=SC2086
768 echo -n "Done: "; date
770 [ $count_all -eq 1 ] && s="" || s="s"
771 [ $count_enabled -eq $count_all ] \
772 && echo " - $count_all job$s defined (all enabled)," \
773 || echo " - $count_all job$s defined ($count_enabled enabled),"
774 [ $count_started -eq 1 ] && s="" || s="s"
775 echo " - $count_started job$s started,"
776 echo " - $count_ok done without errors."
779 if [ $count_started -ne $count_ok ]; then
780 echo "-----> THERE HAVE BEEN ERRORS! <-----"
783 elif [ $count_enabled -ne $count_started ]; then