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=""
61 echo "Usage: $NAME [<options>] [<job> [<job> [...]]]"
63 echo " -n, --dry-run Test run only, don't copy any data."
64 echo " -p, --progress Show progress, see rsync(1)."
65 echo " -t TAG, --tag TAG Only run jobs with tag TAG."
66 echo " -x, --no-exec Don't run global pre-/post-exec commands."
68 echo "When no <job> is given, all defined systems are used."
70 # shellcheck disable=SC2086
78 printf "%s\\n" "$@" >&2
82 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
83 echo "Executing \"$post_exec\" ..."
84 if ! sh -c $post_exec; then
85 ErrorMsg "Warning: post-exec command failed!"
94 ErrorMsg "--> Got signal, cleaning up & aborting ..."
97 ErrorMsg "Aborted: $(date)" >&2
107 echo "Running job ${what}-exec command ..."
109 && cmd="$ssh_cmd ${user}@${system} $cmd"
110 echo "Start date (${what}-exec): $(date)"
112 if [ "$DRYRUN" -eq 0 ]; then
113 $SHELL -c "$cmd"; local ret=$?
115 echo " *** Trial run, not executing ${what}-exec command!"
118 if [ $ret -eq 0 ]; then
119 echo "The ${what}-exec command completed with status 0, OK."
121 ErrorMsg "The ${what}-exec command completed with ERRORS, code $ret!"
129 while [ -n "$dir" ]; do
130 findmnt -fn -o FSTYPE --raw "$dir" 2>/dev/null; local r=$?
131 if [ $r -eq 0 ]; then
133 elif [ $r -eq 127 ]; then
137 dir=$(dirname "$dir") || return 1
146 dir=$(dirname "$volume")
150 btrfs subvolume create "$volume" >/dev/null || return 1
153 zfs create "$(echo "$volume" | cut -c2-)" || return 1
156 ErrorMsg "CreateSubvolume: Incompatible FS type \"$fs\" on \"$dir\"!"
170 dir=$(dirname "source")
171 fs=$(GetFS "$source")
174 btrfs subvolume snapshot "$source" "$snapshot" >/dev/null || return 1
177 zfs snapshot "$snapshot" || return 1
178 link_name="$(echo "$snapshot" | cut -d@ -f2-)"
180 "current/.zfs/snapshot/$link_name" \
181 "$(dirname "$volume")/$link_name"
184 ErrorMsg "CloneSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
195 fs=$(GetFS "$source")
198 mv "$source" "$target" || return 1
202 "$(echo "$source" | cut -c2-)" \
203 "$(echo "$target" | cut -c2-)" \
207 ErrorMsg "RenameSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
219 fs=$(GetFS "$volume")
222 btrfs subvolume delete "$volume" >/dev/null || return 1
225 id="$(basename "$volume")"
226 if [ -h "$volume" ]; then
227 snapshot="$(dirname "$volume")/current@$id"
231 zfs destroy -r "$(echo "$snapshot" | cut -c2-)" >/dev/null || return 1
232 [ -h "$volume" ] && rm "$volume"
235 ErrorMsg "DeleteSubvolume: Incompatible FS type \"$fs\" on \"$volume\"!"
241 Initialize_Last_SysTarget_Snapshot() {
246 fs=$(GetFS "$sys_target")
249 # Search directory of last generation, if any
250 # shellcheck disable=SC2012
251 last=$(ls -1d "$sys_target"/[0-9]* 2>/dev/null | sort -r | head -n1)
252 if [ -n "$last" ]; then
253 if [ ! -d "$last" ]; then
254 ErrorMsg "Last snapshot \"$last\" seems not to be a directory!? \"$system\" skipped!"
259 sys_target="$sys_target/$(date +%Y%m%d-%H%M%S)"
260 snapshot="$sys_target"
263 # On ZFS, the last generation is always named "current"
264 if [ -e "$sys_target/current" ]; then
265 last="$sys_target/current"
266 if [ "$(uname)" = "Linux" ]; then
267 date=$(LC_ALL=C stat "$1" | grep "^Modify: " \
268 | cut -d':' -f2- | cut -d. -f1)
270 date=$(LC_ALL=C stat -f "%Sc" "$1")
272 date=$(echo "$date" | sed -e's/^ //g' -e 's/[-:]//g' -e 's/ /-/g')
276 date="$(date +%Y%m%d-%H%M%S)"
278 snapshot="$(echo "$sys_target/current" | cut -c2-)@$date"
279 sys_target="$sys_target/current"
282 ErrorMsg "Initialize_Last_SysTarget_Snapshot: Incompatible FS type \"$fs\" on \"$sys_target\"!"
288 # Search configuration file (last one is used as default!)
290 "/usr/local/etc/backup-script.conf" \
291 "/etc/backup-script.conf" \
292 "${conf_d}/backup-script.conf" \
293 "/usr/local/etc/backup-script.conf" \
295 [ -r "$conf" ] && break
298 # Read in configuration file
299 config_info="Configuration file is \"$conf\""
300 if [ -r "$conf" ]; then
301 # shellcheck source=/dev/null
304 config_info="${config_info} (not readable, using defaults)"
306 config_info="${config_info},\\nusing \"$conf_d\" as configuration directory."
308 while [ $# -gt 0 ]; do
317 shift; TAG="$1"; shift
318 [ -n "$TAG" ] || Usage
331 echo "Started: $(date)"
332 echo -e "$config_info"
334 # Check rsync and its protocol version
335 if ! rsync=$(which "rsync" 2>/dev/null); then
336 ErrorMsg "Failed to detect rsync(1)! Is it installed in your \$PATH?"
339 if ! rsync_proto=$($rsync --version 2>/dev/null | head -n 1 | sed 's/.* protocol version \([0-9]*\)$/\1/'); then
340 ErrorMsg "Failed to detect protocol version of $rsync!"
343 echo "Rsync command is $rsync, protocol version $rsync_proto."
345 [[ -n "$TAG" ]] && echo "Running jobs tagged with \"$TAG\"."
348 if [ $# -ge 1 ]; then
350 if [ ! -r "${conf_d}/$s" ]; then
351 ErrorMsg "$NAME: Can' read \"${conf_d}/$s\"!"
354 sys+=("${conf_d}/$s")
360 if [[ -n "$setup_exec" && $PREPOSTEXEC -ne 0 ]]; then
361 echo "Executing \"$setup_exec\" ..."
362 if ! sh -c $setup_exec; then
363 ErrorMsg "Error: setup command failed!"; echo
364 ErrorMsg "Aborting backup."; echo
371 trap GotSignal SIGINT SIGTERM
373 # check and create PID file
374 if [ -e "$PIDFILE" ]; then
375 ErrorMsg "Lockfile \"$PIDFILE\" already exists."
376 ErrorMsg "Is an other instance still running?"
378 ErrorMsg "Aborted: $(date)" >&2
382 if ! touch "$PIDFILE" 2>/dev/null; then
383 ErrorMsg "Warning: can't create PID file \"$PIDFILE\"!"
386 echo "$$" >>"$PIDFILE"
389 if [[ -n "$pre_exec" && $PREPOSTEXEC -ne 0 ]]; then
390 echo "Executing \"$pre_exec\" ..."
391 if ! sh -c $pre_exec; then
392 ErrorMsg "Error: pre-exec command failed!"; echo
394 ErrorMsg "Aborting backup."; echo
401 for f in "${sys[@]}"; do
402 [[ -r "$f" && -f "$f" ]] || continue
404 fname=$(basename "$f")
406 "backup-script.conf"|*.sh)
411 # Set global defaults
413 backup_type="$default_backup_type"
415 source_root="$default_source_root"
416 files="$default_files"
417 target="$default_target"
418 ssh_args_add="$default_ssh_args_add"
419 rsync_args_add="$default_rsync_args_add"
420 exclude_args_add="$default_exclude_args_add"
421 exclude_dirs_add="$default_exclude_dirs_add"
422 compress="$default_compress"
424 local="$default_local"
425 generations="$default_generations"
426 job_pre_exec="$default_job_pre_exec"
427 job_post_exec="$default_job_post_exec"
429 io_timeout="$default_io_timeout"
431 # Compatibility with backup-pull(1) script: Save global values ...
432 pre_exec_saved="$pre_exec"
433 post_exec_saved="$post_exec"
435 # Compatibility with backup-pull(1) script: Set defaults
441 # Read in system configuration file
442 # shellcheck source=/dev/null
445 # Compatibility with backup-pull(1) script: Fix up configuration
446 [[ "$system" = "$fname" && -n "$host" ]] \
448 [[ "$source_root" = "$default_source_root" && -n "$source" ]] \
449 && source_root="$source"
450 [[ -z "$job_pre_exec" && -n "$pre_exec" ]] \
451 && job_pre_exec="$pre_exec"
452 [[ -z "$job_post_exec" && -n "$post_exec" ]] \
453 && job_post_exec="$post_exec"
455 # Compatibility with backup-pull(1) script: Restore global values ...
456 pre_exec="$pre_exec_saved"
457 post_exec="$post_exec_saved"
459 # Validate configuration
460 if [[ "$system" = "localhost" || "$system" = "127.0.0.1" ]]; then
466 # Add "NONE" tag when no tags are given in the config file:
467 [[ -z "$tags" ]] && tags="NONE"
469 [[ "$local" -eq 1 ]] && tags="$tags,LOCAL"
471 if [[ -n "$TAG" && "$TAG" != "ALL" ]]; then
472 if ! echo "$tags" | grep -E "(^|,)$TAG(,|$)" >/dev/null 2>&1; then
473 if [ "$DRYRUN" -ne 0 ]; then
474 echo "Tags of system \"$system\" don't match \"$TAG\": \"$tags\". Skipped."
481 # Make sure "source_root" ends with a slash ("/")
482 case "$source_root" in
486 source_root="$source_root/"
489 # Make sure "target" DOESN'T end with a slash ("/")
492 target=$( echo "$target" | sed -e 's/\/$//g' )
496 [ "$system" = "$fname" ] \
497 && systxt="\"$system\"" \
498 || systxt="\"$fname\" [\"$system\"]"
500 && echo "Working on $systxt ..." \
501 || echo "Working on $systxt (local system) ..."
503 count_all=$count_all+1
505 # Check if job is disabled
506 if [ "$backup_type" = "disabled" ]; then
507 echo "Job is DISABLED and will be skipped."
511 count_enabled=$count_enabled+1
513 # Check target directory
514 if [ -z "$target" ]; then
515 ErrorMsg "No target directory specified for \"$system\"!? Skipped!"
518 if [ ! -d "$target" ]; then
519 ErrorMsg "Target \"$target\" is not a directory!? \"$system\" skipped!"
523 sys_target="$target/$fname"
524 sys_root="$sys_target"
525 if [[ "$DRYRUN" -eq 0 && ! -e "$sys_target" ]]; then
526 if [ $generations -gt 0 ]; then
527 CreateSubvolume "$sys_target"; r=$?
529 mkdir -p "$sys_target"; r=$?
531 if [ $r -ne 0 ]; then
532 ErrorMsg "Can't create \"$sys_target\"!? \"$system\" skipped!"
537 if [[ "$local" -eq 0 && "$ping" -ne 0 ]]; then
538 # Check if system is alive
539 if ! ping -c 1 "$system" >/dev/null 2>&1; then
540 ErrorMsg "Host \"$system\" seems not to be alive!? Skipped."
543 echo "OK, host \"$system\" seems to be alive."
546 if [ $generations -gt 0 ]; then
547 # Make sure no old backup is stored in system directory
548 if [ -e "$sys_target/.stamp" ]; then
549 # There seems to be a genearation-less backup in the
551 ErrorMsg "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
555 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
557 if [[ -n "$last" && ! -e "$last/.stamp" ]]; then
558 # Old backup directory without "stamp file", continue
559 echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
560 if [ "$DRYRUN" -eq 0 ]; then
561 if ! RenameSubvolume "$last" "$sys_target"; then
562 ErrorMsg "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
566 echo " *** Trial run, not renaming snapshot \"$last\" to \"$sys_target\"!"
568 elif [ -n "$last" ]; then
569 # Old backup directory found, create new snapshot
570 echo "Found last snapshot in \"$last\"."
571 if [ "$DRYRUN" -eq 0 ]; then
572 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
573 if [ $r -ne 0 ]; then
574 ErrorMsg "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
577 echo "Created new snapshot in \"$snapshot\"."
579 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
582 # No old backup found, create new subvolume
583 if [ "$DRYRUN" -eq 0 ]; then
584 CreateSubvolume "$sys_target"; r=$?
585 if [ $r -ne 0 ]; then
586 ErrorMsg "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
589 echo "Created new subvolume in \"$sys_target\"."
591 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
597 [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
599 # execute job "pre-exec" command, if any
600 if [ -n "$job_pre_exec" ]; then
601 ExecJob pre "$job_pre_exec" ; ret=$?
602 if [ $ret -ne 0 ]; then
603 [ $ret -ne 99 ] && count_started=$count_started+1
604 ErrorMsg "Pre-exec command failed, \"$system\" skipped!"
609 # prepare (remote) command ...
610 if [[ "$backup_type" == "rsync" ]]; then
611 cmd="$rsync --archive --timeout=$io_timeout"
612 [ "$compress" -ne 0 ] && cmd="$cmd --compress"
613 [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
614 cmd="$cmd --delete-during --delete-excluded --sparse"
615 if [ "$VERBOSE" -gt 0 ]; then
616 [ "$rsync_proto" -ge 31 ] \
617 && cmd="$cmd --info=progress2" \
618 || cmd="$cmd --progress"
621 if [ "$source_root" = "$default_source_root" ]; then
631 "/var/cache/apt/**" \
635 cmd="$cmd --exclude=$dir"
638 [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
639 for dir in $exclude_dirs_add; do
640 cmd="$cmd --exclude=$dir"
642 [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
646 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
647 || cmd="$cmd $source_root $sys_target/"
648 elif [[ "$backup_type" == "scp" ]]; then
650 [ "$VERBOSE" -eq 0 ] && cmd="$cmd -q"
651 for file in $files; do
652 cmd="$cmd ${user}@${system}:$file $sys_target/"
655 ErrorMsg "Backup type \"$backup_type\" undefined, \"$system\" skipped!"
659 echo "Backing up to \"$sys_target\" ..."
660 echo "Start date: $(date)"
662 count_started=$count_started+1
665 if [ "$DRYRUN" -eq 0 ]; then
666 stamp_file="$sys_target/.stamp"
669 # Execute backup command:
670 start_t=$(date "+%s")
671 $SHELL -c "$cmd"; ret=$?
676 echo "start_t=$start_t"
679 echo "backup_host='$(hostname -f)'"
680 echo "backup_user='$(id -un)'"
683 echo " *** Trial run, not executing save command!"
687 if [ $ret -eq 20 ]; then
688 ErrorMsg "Backup of \"$system\" interrupted. Aborting ..."
692 echo "End date: $(date)"
693 if [[ $ret -eq 0 || $ret -eq 24 ]]; then
694 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
696 echo "System \"$system\" completed with status $ret, OK."
697 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
700 ErrorMsg "System \"$system\" completed with ERRORS, code $ret!"
703 # execute job "post-exec" command, if any
704 if [ -n "$job_post_exec" ]; then
705 ExecJob post "$job_post_exec"
708 if [ $generations -gt 0 ]; then
709 # Update "latest" symlink
710 if [ "$DRYRUN" -eq 0 ]; then
711 rm -f "$sys_root/latest"
712 ln -s "$sys_target" "$sys_root/latest"
714 # Clean up old generations
715 declare -i gen_count=$generations+2
716 # shellcheck disable=SC2012
717 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
718 if [[ -n "$to_delete" && $ok -eq 1 ]]; then
719 [ "$DRYRUN" -eq 0 ] \
720 && echo "Deleting old backup generations (keep $generations) ..." \
721 || echo " *** Trial run, not deleting old generations:"
722 for delete in $to_delete; do
723 dir="$sys_root/$delete"
724 if [ ! -e "$dir/.stamp" ]; then
725 ErrorMsg "Not deleting \"$dir\" of \"$system\", not a backup directory!?"
728 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
729 | cut -d':' -f2- | cut -d. -f1)
730 # shellcheck disable=SC2086
731 echo "Removing backup from" $last "..."
732 if [ "$DRYRUN" -eq 0 ]; then
733 DeleteSubvolume "$dir" \
734 || ErrorMsg "Failed to delete \"$dir\" of \"$system\"!"
737 echo "Clean up finished: $(date)"
738 elif [ -n "$to_delete" ]; then
739 ErrorMsg "There have been errors for \"$system\", not cleaning up old generations!"
741 echo "Nothing to clean up (keep up to $generations generations)."
745 destinations="$destinations $target"
751 if [ "$DRYRUN" -eq 0 ]; then
754 # shellcheck disable=SC2086
755 for dest in $(echo $destinations | sed -e 's/ /\n/g' | sort | uniq); do
759 paths_zfs="$paths_zfs $dest"
765 if [ -n "$paths" ]; then
766 # shellcheck disable=SC2086
770 if [ -n "$paths_zfs" ]; then
771 # shellcheck disable=SC2086
781 [ $count_all -eq 1 ] && s="" || s="s"
782 [ $count_enabled -eq $count_all ] \
783 && echo " - $count_all job$s defined (all enabled)," \
784 || echo " - $count_all job$s defined ($count_enabled enabled),"
785 [ $count_started -eq 1 ] && s="" || s="s"
786 echo " - $count_started job$s started,"
787 echo " - $count_ok done without errors."
790 if [ $count_started -ne $count_ok ]; then
791 echo "-----> THERE HAVE BEEN ERRORS! <-----"
794 elif [ $count_enabled -ne $count_started ]; then