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"
22 declare -i count_all=0
23 declare -i count_started=0
25 declare -i count_ok_vanished=0
26 declare -i count_enabled=0
30 # Default settings, can be overwritten in backup-script.conf:
31 [ -d "/usr/local/etc/backup-script.d" ] \
32 && conf_d="/usr/local/etc/backup-script.d" \
33 || conf_d="/etc/backup-script.d"
37 default_backup_type="rsync"
38 default_source_root="/"
39 default_files="running-config"
40 default_target="/var/backups"
42 default_ssh_args_add=""
43 default_rsync_args_add=""
44 default_exclude_args_add=""
45 default_exclude_dirs_add=""
50 default_io_timeout="1800"
51 default_job_pre_exec=""
52 default_job_post_exec=""
56 echo "Usage: $NAME [<options>] [<system> [<system> [...]]]"
58 echo " -n, --dry-run Test run only, don't copy any data."
59 echo " -p, --progress Show progress, see rsync(1)."
60 echo " -t TAG, --tag TAG Only run jobs with tag TAG."
62 echo "When no <system> is given, all defined systems are used."
70 if [ -n "$post_exec" ]; then
71 echo "Executing \"$post_exec\" ..."
74 echo "Warning: post-exec command failed!"
83 echo "--> Got break signal, cleaning up & aborting ..."
86 echo -n "Aborted: "; date
96 echo "Running job ${what}-exec command ..."
98 && cmd="$ssh_cmd ${user}@${system} $cmd"
99 echo -n "Start date (${what}-exec): "; date
101 if [ "$DRYRUN" -eq 0 ]; then
102 $SHELL -c "$cmd"; local ret=$?
104 echo " *** Trial run, not executing ${what}-exec command!"
108 && echo "The ${what}-exec command completed with status 0, OK." \
109 || echo "The ${what}-exec command completed with ERRORS, code $ret!"
116 while [ -n "$dir" ]; do
117 findmnt -fn -o FSTYPE --raw "$dir" 2>/dev/null; local r=$?
118 if [ $r -eq 0 ]; then
120 elif [ $r -eq 127 ]; then
124 dir=$(dirname "$dir") || return 1
133 dir=$(dirname "$volume")
137 btrfs subvolume create "$volume" >/dev/null || return 1
140 zfs create "$(echo "$volume" | cut -c2-)" || return 1
143 echo "CreateSubvolume: Incompatible FS type \"$fs\" on \"$dir\"!"
157 dir=$(dirname "source")
158 fs=$(GetFS "$source")
161 btrfs subvolume snapshot "$source" "$snapshot" >/dev/null || return 1
164 zfs snapshot "$snapshot" || return 1
165 link_name="$(echo "$snapshot" | cut -d@ -f2-)"
167 "current/.zfs/snapshot/$link_name" \
168 "$(dirname "$volume")/$link_name"
171 echo "CloneSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
182 fs=$(GetFS "$source")
185 mv "$source" "$target" || return 1
189 "$(echo "$source" | cut -c2-)" \
190 "$(echo "$target" | cut -c2-)" \
194 echo "RenameSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
206 fs=$(GetFS "$volume")
209 btrfs subvolume delete "$volume" >/dev/null || return 1
212 id="$(basename "$volume")"
213 if [ -h "$volume" ]; then
214 snapshot="$(dirname "$volume")/current@$id"
218 zfs destroy -r "$(echo "$snapshot" | cut -c2-)" >/dev/null || return 1
219 [ -h "$volume" ] && rm "$volume"
222 echo "DeleteSubvolume: Incompatible FS type \"$fs\" on \"$volume\"!"
228 Initialize_Last_SysTarget_Snapshot() {
233 fs=$(GetFS "$sys_target")
236 # Search directory of last generation, if any
237 last=$(ls -1d "$sys_target"/[0-9]* 2>/dev/null | sort -r | head -n1)
238 if [ -n "$last" ]; then
239 if [ ! -d "$last" ]; then
240 echo "Last snapshot \"$last\" seems not to be a directory!? \"$system\" skipped!"
245 sys_target="$sys_target/$(date +%Y%m%d-%H%M%S)"
246 snapshot="$sys_target"
249 # On ZFS, the last generation is always named "current"
250 if [ -e "$sys_target/current" ]; then
251 last="$sys_target/current"
252 if [ "$(uname)" = "Linux" ]; then
253 date=$(LC_ALL=C stat "$1" | grep "^Modify: " \
254 | cut -d':' -f2- | cut -d. -f1)
256 date=$(LC_ALL=C stat -f "%Sc" "$1")
258 date=$(echo "$date" | sed -e's/^ //g' -e 's/[-:]//g' -e 's/ /-/g')
262 date="$(date +%Y%m%d-%H%M%S)"
264 snapshot="$(echo "$sys_target/current" | cut -c2-)@$date"
265 sys_target="$sys_target/current"
268 echo "Initialize_Last_SysTarget_Snapshot: Incompatible FS type \"$fs\" on \"$sys_target\"!"
274 # Search configuration file (last one is used as default!)
276 "/usr/local/etc/backup-script.conf" \
277 "/etc/backup-script.conf" \
278 "${conf_d}/backup-script.conf" \
279 "/usr/local/etc/backup-script.conf" \
281 [ -r "$conf" ] && break
284 # Read in configuration file
285 config_info="Configuration file is \"$conf\""
286 if [ -r "$conf" ]; then
287 # shellcheck source=/dev/null
290 config_info="${config_info} (not readable, using defaults)"
292 config_info="${config_info},\nusing \"$conf_d\" as configuration directory."
294 while [ $# -gt 0 ]; do
303 shift; TAG="$1"; shift
304 [ -n "$TAG" ] || Usage
314 echo -n "Started: "; date
315 echo -e "$config_info"
317 # Check rsync and its protocol version
318 rsync=$(which "rsync" 2>/dev/null)
319 if [ $? -ne 0 ]; then
320 echo "Failed to detect rsync(1)! Is it installed in your \$PATH?"
323 rsync_proto=$($rsync --version 2>/dev/null | head -n 1 | sed 's/.* protocol version \([0-9]*\)$/\1/')
324 if [ $? -ne 0 ]; then
325 echo "Failed to detect protocol version of $rsync!"
328 echo "Rsync command is $rsync, protocol version $rsync_proto."
330 [[ -n "$TAG" ]] && echo "Running jobs tagged with \"$TAG\"."
333 if [ $# -ge 1 ]; then
335 if [ ! -r "${conf_d}/$s" ]; then
336 echo "$NAME: Can' read \"${conf_d}/$s\"!"
339 sys+=("${conf_d}/$s")
345 if [ -n "$setup_exec" ]; then
346 echo "Executing \"$setup_exec\" ..."
348 if [ $? -ne 0 ]; then
349 echo "Error: setup command failed!"; echo
350 echo "Aborting backup."; echo
357 trap GotSignal SIGINT
359 # check and create PID file
360 if [ -e "$PIDFILE" ]; then
361 echo "Lockfile \"$PIDFILE\" already exists."
362 echo "Is an other instance still running?"
364 echo -n "Aborted: "; date
368 touch "$PIDFILE" 2>/dev/null
369 if [ $? -ne 0 ]; then
370 echo "Warning: can't create PID file \"$PIDFILE\"!"
373 echo "$$" >>"$PIDFILE"
376 if [ -n "$pre_exec" ]; then
377 echo "Executing \"$pre_exec\" ..."
379 if [ $? -ne 0 ]; then
380 echo "Error: pre-exec command failed!"; echo
382 echo "Aborting backup."; echo
389 for f in "${sys[@]}"; do
390 [[ -r "$f" && -f "$f" ]] || continue
392 fname=$(basename "$f")
394 "backup-script.conf"|*.sh)
399 # Set global defaults
401 backup_type="$default_backup_type"
403 source_root="$default_source_root"
404 files="$default_files"
405 target="$default_target"
406 ssh_args_add="$default_ssh_args_add"
407 rsync_args_add="$default_rsync_args_add"
408 exclude_args_add="$default_exclude_args_add"
409 exclude_dirs_add="$default_exclude_dirs_add"
410 compress="$default_compress"
412 local="$default_local"
413 generations="$default_generations"
414 job_pre_exec="$default_job_pre_exec"
415 job_post_exec="$default_job_post_exec"
417 io_timeout="$default_io_timeout"
419 # Compatibility with backup-pull(1) script: Save global values ...
420 pre_exec_saved="$pre_exec"
421 post_exec_saved="$post_exec"
423 # Compatibility with backup-pull(1) script: Set defaults
429 # Read in system configuration file
430 # shellcheck source=/dev/null
433 # Compatibility with backup-pull(1) script: Fix up configuration
434 [[ "$system" = "$fname" && -n "$host" ]] \
436 [[ "$source_root" = "$default_source_root" && -n "$source" ]] \
437 && source_root="$source"
438 [[ -z "$job_pre_exec" && -n "$pre_exec" ]] \
439 && job_pre_exec="$pre_exec"
440 [[ -z "$job_post_exec" && -n "$post_exec" ]] \
441 && job_post_exec="$post_exec"
443 # Compatibility with backup-pull(1) script: Restore global values ...
444 pre_exec="$pre_exec_saved"
445 post_exec="$post_exec_saved"
447 # Validate configuration
448 if [[ "$system" = "localhost" || "$system" = "127.0.0.1" ]]; then
454 # Add "NONE" tag when no tags are given in the config file:
455 [[ -z "$tags" ]] && tags="NONE"
457 [[ "$local" -eq 1 ]] && tags="$tags,LOCAL"
459 if [[ -n "$TAG" && "$TAG" != "ALL" ]]; then
460 echo "$tags" | grep -E "(^|,)$TAG(,|$)" >/dev/null 2>&1
461 if [ $? -ne 0 ]; 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"
518 mkdir -p "$sys_target"
520 if [ $? -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 ping -c 1 "$system" >/dev/null 2>&1
529 if [ $? -ne 0 ]; then
530 echo "Host \"$system\" seems not to be alive!? Skipped."
533 echo "OK, host \"$system\" seems to be alive."
536 if [ $generations -gt 0 ]; then
537 # Make sure no old backup is stored in system directory
538 if [ -e "$sys_target/.stamp" ]; then
539 # There seems to be a genearation-less backup in the
541 echo "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
545 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
547 if [[ -n "$last" && ! -e "$last/.stamp" ]]; then
548 # Old backup directory without "stamp file", continue
549 echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
550 RenameSubvolume "$last" "$sys_target"
551 if [ $? -ne 0 ]; then
552 echo "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
555 elif [ -n "$last" ]; then
556 # Old backup directory found, create new snapshot
557 echo "Found last snapshot in \"$last\"."
558 if [ "$DRYRUN" -eq 0 ]; then
559 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
560 if [ $r -ne 0 ]; then
561 echo "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
564 echo "Created new snapshot in \"$snapshot\"."
566 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
569 # No old backup found, create new subvolume
570 if [ "$DRYRUN" -eq 0 ]; then
571 CreateSubvolume "$sys_target"; r=$?
572 if [ $r -ne 0 ]; then
573 echo "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
576 echo "Created new subvolume in \"$sys_target\"."
578 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
584 [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
586 # execute job "pre-exec" command, if any
587 if [ -n "$job_pre_exec" ]; then
588 ExecJob pre "$job_pre_exec" ; ret=$?
589 if [ $ret -ne 0 ]; then
590 [ $ret -ne 99 ] && count_started=$count_started+1
591 echo "Pre-exec command failed, \"$system\" skipped!"
596 # prepare (remote) command ...
597 if [[ "$backup_type" == "rsync" ]]; then
598 cmd="$rsync --archive --timeout=$io_timeout"
599 [ "$compress" -ne 0 ] && cmd="$cmd --compress"
600 [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
601 cmd="$cmd --delete-during --delete-excluded --sparse"
602 if [ "$VERBOSE" -gt 0 ]; then
603 [ "$rsync_proto" -ge 31 ] \
604 && cmd="$cmd --info=progress2" \
605 || cmd="$cmd --progress"
608 if [ "$source_root" = "$default_source_root" ]; then
618 "/var/cache/apt/**" \
622 cmd="$cmd --exclude=$dir"
625 [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
626 for dir in $exclude_dirs_add; do
627 cmd="$cmd --exclude=$dir"
629 [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
633 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
634 || cmd="$cmd $source_root $sys_target/"
635 elif [[ "$backup_type" == "scp" ]]; then
637 [ "$VERBOSE" -eq 0 ] && cmd="$cmd -q"
638 for file in $files; do
639 cmd="$cmd ${user}@${system}:$file $sys_target/"
642 echo "Backup type \"$backup_type\" undefined, \"$system\" skipped!"
646 echo "Backing up to \"$sys_target\" ..."
647 echo -n "Start date: "; date
649 count_started=$count_started+1
652 if [ "$DRYRUN" -eq 0 ]; then
653 stamp_file="$sys_target/.stamp"
656 # Execute backup command:
657 start_t=$(date "+%s")
658 $SHELL -c "$cmd"; ret=$?
661 echo "code=$ret" >"$stamp_file"
662 echo "start_t=$start_t" >>"$stamp_file"
663 echo "end_t=$end_t" >>"$stamp_file"
664 echo "cmd='$cmd'" >>"$stamp_file"
665 echo "backup_host='`hostname -f`'" >>"$stamp_file"
666 echo "backup_user='`id -un`'" >>"$stamp_file"
668 echo " *** Trial run, not executing save command!"
672 if [ $ret -eq 20 ]; then
673 echo "Backup of \"$system\" interrupted. Aborting ..."
677 echo -n "End date: "; date
678 if [[ $ret -eq 0 || $ret -eq 24 ]]; then
679 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
681 echo "System \"$system\" completed with status $ret, OK."
682 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
685 echo "System \"$system\" completed with ERRORS, code $ret!"
688 # execute job "post-exec" command, if any
689 if [ -n "$job_post_exec" ]; then
690 ExecJob post "$job_post_exec"
693 if [ $generations -gt 0 ]; then
694 # Update "latest" symlink
695 if [ "$DRYRUN" -eq 0 ]; then
696 rm -f "$sys_root/latest"
697 ln -s "$sys_target" "$sys_root/latest"
699 # Clean up old generations
700 declare -i gen_count=$generations+2
701 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
702 if [[ -n "$to_delete" && $ok -eq 1 ]]; then
703 [ "$DRYRUN" -eq 0 ] \
704 && echo "Deleting old backup generations (keep $generations) ..." \
705 || echo " *** Trial run, not deleting old generations:"
706 for delete in $to_delete; do
707 dir="$sys_root/$delete"
708 if [ ! -e "$dir/.stamp" ]; then
709 echo "Not deleting \"$dir\", not a backup directory!?"
712 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
713 | cut -d':' -f2- | cut -d. -f1)
714 echo "Removing backup from" $last "..."
715 if [ "$DRYRUN" -eq 0 ]; then
716 DeleteSubvolume "$dir"
718 echo "Failed to delete \"$dir\"!"
721 echo -n "Clean up finished: "; date
722 elif [ -n "$to_delete" ]; then
723 echo "There have been errors, not cleaning up old generations!"
725 echo "Nothing to clean up (keep up to $generations generations)."
729 destinations="$destinations $target"
735 if [ "$DRYRUN" -eq 0 ]; then
738 for dest in $(echo $destinations | sed -e 's/ /\n/g' | sort | uniq); do
742 paths_zfs="$paths_zfs $dest"
748 if [ -n "$paths" ]; then
752 if [ -n "$paths_zfs" ]; then
760 echo -n "Done: "; date
762 [ $count_all -eq 1 ] && s="" || s="s"
763 [ $count_enabled -eq $count_all ] \
764 && echo " - $count_all job$s defined (all enabled)," \
765 || echo " - $count_all job$s defined ($count_enabled enabled),"
766 [ $count_started -eq 1 ] && s="" || s="s"
767 echo " - $count_started job$s started,"
768 echo " - $count_ok done without errors."
771 if [ $count_started -ne $count_ok ]; then
772 echo "-----> THERE HAVE BEEN ERRORS! <-----"
775 elif [ $count_enabled -ne $count_started ]; then