]> arthur.barton.de Git - backup-script.git/blob - bin/backup-script
5c070261358369d1ef1f36652ea877878ac19023
[backup-script.git] / bin / backup-script
1 #!/bin/bash
2 #
3 # backup-script system for cloning systems using rsync
4 # Copyright (c)2008-2015 Alexander Barton <alex@barton.de>
5 #
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.
11 #
12
13 NAME=$(basename "$0")
14 PIDFILE="/var/run/$NAME.pid"
15
16 DRYRUN=0
17 VERBOSE=0
18
19 export LC_ALL=C
20
21 declare -i count_all=0
22 declare -i count_started=0
23 declare -i count_ok=0
24 declare -i count_ok_vanished=0
25
26 destinations=""
27
28 # Default settings, can be overwritten in backup-script.conf:
29 [ -d "/usr/local/etc/backup-script.d" ] \
30         && conf_d="/usr/local/etc/backup-script.d" \
31         || conf_d="/etc/backup-script.d"
32 pre_exec=""
33 post_exec=""
34 default_source_root="/"
35 default_target="/var/backups"
36 default_user="root"
37 default_ssh_args_add=""
38 default_rsync_args_add=""
39 default_exclude_args_add=""
40 default_exclude_dirs_add=""
41 default_compress=1
42 default_ping=1
43 default_local=0
44 default_generations=0
45 default_job_pre_exec=""
46 default_job_post_exec=""
47
48 Usage() {
49         echo "Usage: $NAME [<options>] [<system> [<system> [...]]]"
50         echo
51         echo "  -p, --progress    Show progress, see rsync(1)."
52         echo "  -n, --dry-run     Test run only, don't copy any data."
53         echo
54         echo "When no <system> is given, all defined systems are used."
55         echo
56         echo -e $config_info
57         echo
58         exit 2
59 }
60
61 CleanUp() {
62         if [ -n "$post_exec" ]; then
63                 echo "Executing \"$post_exec\" ..."
64                 sh -c $post_exec
65                 if [ $? -ne 0 ]; then
66                         echo "Warning: post-exec command failed!"
67                 fi
68                 echo
69         fi
70         rm -f "$PIDFILE"
71 }
72
73 GotSignal() {
74         echo
75         echo "--> Got break signal, cleaning up & aborting ..."
76         echo
77         CleanUp
78         echo -n "Aborted: "; date
79         echo
80         sleep 3
81         exit 9
82 }
83
84 ExecJob() {
85         local what="$1"
86         local cmd="$2"
87
88         echo "Running job ${what}-exec command ..."
89         [ "$local" -eq 0 ] \
90                 && cmd="$ssh_cmd ${user}@${system} $cmd"
91         echo -n "Start date (${what}-exec): "; date
92         echo "$cmd"
93         if [ "$DRYRUN" -eq 0 ]; then
94                 $SHELL -c "$cmd"; local ret=$?
95         else
96                 echo " *** Trial run, not executing ${what}-exec command!"
97                 ret=0
98         fi
99         [ $ret -eq 0 ] \
100                 && echo "The ${what}-exec command completed with status 0, OK." \
101                 || echo "The ${what}-exec command completed with ERRORS, code $ret!"
102         return $ret
103 }
104
105 GetFS() {
106         local dir="$1"
107
108         while [ -n "$dir" ]; do
109                 findmnt -fn -o FSTYPE --raw "$dir" 2>/dev/null; local r=$?
110                 if [ $r -eq 0 ]; then
111                         return 0
112                 elif [ $r -eq 127 ]; then
113                         echo "UNKNOWN"
114                         return 1
115                 fi
116                 dir=$(dirname "$dir") || return 1
117         done
118 }
119
120 CreateSubvolume() {
121         local volume="$1"
122         local fs
123         local dir
124
125         dir=$(dirname "$volume")
126         fs=$(GetFS "$dir")
127         case "$fs" in
128           "btrfs")
129                 btrfs subvolume create "$volume"  >/dev/null || return 1
130                 ;;
131           "zfs")
132                 zfs create "$(echo "$volume" | cut -c2-)" || return 1
133                 ;;
134           *)
135                 echo "CreateSubvolume: Incompatible FS type \"$fs\" on \"$dir\"!"
136                 return 9
137         esac
138         return 0
139 }
140
141 CloneSubvolume() {
142         local source="$1"
143         local volume="$2"
144         local snapshot="$3"
145         local dir
146         local fs
147         local link_name
148
149         dir=$(dirname "source")
150         fs=$(GetFS "$source")
151         case "$fs" in
152           "btrfs")
153                 btrfs subvolume snapshot "$source" "$snapshot"  >/dev/null || return 1
154                 ;;
155           "zfs")
156                 zfs snapshot "$snapshot" || return 1
157                 link_name="$(echo "$snapshot" | cut -d@ -f2-)"
158                 ln -s \
159                         "current/.zfs/snapshot/$link_name" \
160                         "$(dirname "$volume")/$link_name"
161                 ;;
162           *)
163                 echo "CloneSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
164                 return 9
165         esac
166         return 0
167 }
168
169 RenameSubvolume() {
170         local source="$1"
171         local target="$2"
172         local fs
173
174         fs=$(GetFS "$source")
175         case "$fs" in
176           "btrfs")
177                 mv "$source" "$target" || return 1
178                 ;;
179           "zfs")
180                 zfs rename \
181                   "$(echo "$source" | cut -c2-)" \
182                   "$(echo "$target" | cut -c2-)" \
183                         || return 1
184                 ;;
185           *)
186                 echo "RenameSubvolume: Incompatible FS type \"$fs\" on \"$source\"!"
187                 return 9
188         esac
189         return 0
190 }
191
192 DeleteSubvolume() {
193         local volume="$1"
194         local fs
195         local id
196         local snapshot
197
198         fs=$(GetFS "$volume")
199         case "$fs" in
200           "btrfs")
201                 btrfs subvolume delete "$volume" >/dev/null || return 1
202                 ;;
203           "zfs")
204                 id="$(basename "$volume")"
205                 if [ -h "$volume" ]; then
206                         snapshot="$(dirname "$volume")/current@$id"
207                 else
208                         snapshot="$volume"
209                 fi
210                 zfs destroy -r "$(echo "$snapshot" | cut -c2-)" >/dev/null || return 1
211                 [ -h "$volume" ] && rm "$volume"
212                 ;;
213           *)
214                 echo "DeleteSubvolume: Incompatible FS type \"$fs\" on \"$volume\"!"
215                 return 9
216         esac
217         return 0
218 }
219
220 Initialize_Last_SysTarget_Snapshot() {
221         sys_target="$1"
222         unset last
223         unset snapshot
224
225         fs=$(GetFS "$sys_target")
226         case "$fs" in
227           "btrfs")
228                 # Search directory of last generation, if any
229                 last=$(ls -1d "$sys_target"/[0-9]* 2>/dev/null | sort -r | head -n1)
230                 if [ -n "$last" ]; then
231                         if [ ! -d "$last" ]; then
232                                 echo "Last snapshot \"$last\" seems not to be a directory!? \"$system\" skipped!"
233                                 echo
234                                 return 1
235                         fi
236                 fi
237                 sys_target="$sys_target/$(date +%Y%m%d-%H%M%S)"
238                 snapshot="$sys_target"
239                 ;;
240           "zfs")
241                 # On ZFS, the last generation is always named "current"
242                 if [ -e "$sys_target/current" ]; then
243                         last="$sys_target/current"
244                         if [ "$(uname)" = "Linux" ]; then
245                                 date=$(LC_ALL=C stat "$1" | grep "^Modify: " \
246                                  | cut -d':' -f2- | cut -d. -f1)
247                         else
248                                 date=$(LC_ALL=C stat -f "%Sc" "$1")
249                         fi
250                         date=$(echo "$date" | sed -e's/^ //g' -e 's/[-:]//g' -e 's/ /-/g')
251
252                 else
253                         last=""
254                         date="$(date +%Y%m%d-%H%M%S)"
255                 fi
256                 snapshot="$(echo "$sys_target/current" | cut -c2-)@$date"
257                 sys_target="$sys_target/current"
258                 ;;
259           *)
260                 echo "Initialize_Last_SysTarget_Snapshot: Incompatible FS type \"$fs\" on \"$sys_target\"!"
261                 return 1
262         esac
263         return 0
264 }
265
266 # Search configuration file (last one is used as default!)
267 for conf in \
268         "/usr/local/etc/backup-script.conf" \
269         "/etc/backup-script.conf" \
270         "${conf_d}/backup-script.conf" \
271         "/usr/local/etc/backup-script.conf" \
272 ; do
273         [ -r "$conf" ] && break
274 done
275
276 # Read in configuration file
277 config_info="Configuration file is \"$conf\""
278 if [ -r "$conf" ]; then
279         source "$conf"
280 else
281         config_info="${config_info} (not readable, using defaults)"
282 fi
283 config_info="${config_info},\nusing \"$conf_d\" as configuration directory."
284
285 while [ $# -gt 0 ]; do
286         case "$1" in
287           "-n"|"--dry-run")
288                 DRYRUN=1; shift
289                 ;;
290           "-p"|"--progress")
291                 VERBOSE=1; shift
292                 ;;
293           "-"*)
294                 Usage
295                 ;;
296           *)
297                 break
298         esac
299 done
300
301 echo -n "Started: "; date
302 echo -e "$config_info"
303
304 # Check rsync and its protocol version
305 rsync=$(which "rsync" 2>/dev/null)
306 if [ $? -ne 0 ]; then
307         echo "Failed to detect rsync(1)! Is it installed in your \$PATH?"
308         exit 1
309 fi
310 rsync_proto=$($rsync --version 2>/dev/null | head -n 1 | sed 's/.*  protocol version \([0-9]*\)$/\1/')
311 if [ $? -ne 0 ]; then
312         echo "Failed to detect protocol version of $rsync!"
313         exit 1
314 fi
315 echo "Rsync command is $rsync, protocol version $rsync_proto."
316 echo
317
318 trap GotSignal SIGINT
319
320 if [ $# -ge 1 ]; then
321         for s in "$@"; do
322                 if [ ! -r "${conf_d}/$s" ]; then
323                         echo "$NAME: Can' read \"${conf_d}/$s\"!"
324                         exit 3
325                 fi
326                 sys="$sys ${conf_d}/$s"
327         done
328 else
329         sys="${conf_d}/"*
330 fi
331
332 # check and create PID file
333 if [ -e "$PIDFILE" ]; then
334         echo "Lockfile \"$PIDFILE\" already exists."
335         echo "Is an other instance still running?"
336         echo
337         echo -n "Aborted: "; date
338         echo
339         exit 4
340 fi
341 touch "$PIDFILE" 2>/dev/null
342 if [ $? -ne 0 ]; then
343         echo "Warning: can't create PID file \"$PIDFILE\"!"
344         echo
345 else
346         echo "$$" >>"$PIDFILE"
347 fi
348
349 if [ -n "$pre_exec" ]; then
350         echo "Executing \"$pre_exec\" ..."
351         sh -c $pre_exec
352         if [ $? -ne 0 ]; then
353                 echo "Error: pre-exec command failed!"; echo
354                 CleanUp
355                 echo "Aborting backup."; echo
356                 exit 5
357         fi
358         sleep 2
359         echo
360 fi
361
362 for f in $sys; do
363         [[ -r "$f" && -f "$f" ]] || continue
364
365         fname=$(basename "$f")
366         case "$fname" in
367                 "backup-script.conf"|*.sh)
368                         continue
369                         ;;
370         esac
371
372         # Set global defaults
373         system="$fname"
374         user="$default_user"
375         source_root="$default_source_root"
376         target="$default_target"
377         ssh_args_add="$default_ssh_args_add"
378         rsync_args_add="$default_rsync_args_add"
379         exclude_args_add="$default_exclude_args_add"
380         exclude_dirs_add="$default_exclude_dirs_add"
381         compress="$default_compress"
382         ping="$default_ping"
383         local="$default_local"
384         generations="$default_generations"
385         job_pre_exec="$default_job_pre_exec"
386         job_post_exec="$default_job_post_exec"
387
388         # Compatibility with backup-pull(1) script: Save global values ...
389         pre_exec_saved="$pre_exec"
390         post_exec_saved="$post_exec"
391
392         # Compatibility with backup-pull(1) script: Set defaults
393         host=""
394         unset source
395         unset pre_exec
396         unset post_exec
397
398         # Read in system configuration file
399         source "$f"
400
401         # Compatibility with backup-pull(1) script: Fix up configuration
402         [[ "$system" = "$fname" && -n "$host" ]] \
403                 && system="$host"
404         [[ "$source_root" = "$default_source_root" && -n "$source" ]] \
405                 && source_root="$source"
406         [[ -z "$job_pre_exec" && -n "$pre_exec" ]] \
407                 && job_pre_exec="$pre_exec"
408         [[ -z "$job_post_exec" && -n "$post_exec" ]] \
409                 && job_post_exec="$post_exec"
410
411         # Compatibility with backup-pull(1) script: Restore global values ...
412         pre_exec="$pre_exec_saved"
413         post_exec="$post_exec_saved"
414
415         # Validate configuration
416         if [[ "$system" = "localhost" || "$system" = "127.0.0.1" ]]; then
417                 # Local system
418                 local=1
419                 compress=0
420         fi
421
422         # Make sure "source" ends with a slash ("/")
423         case "$source" in
424           "*/")
425                 ;;
426           "*")
427                 source="$source/"
428         esac
429
430         # Make sure "target" DOESN'T end with a slash ("/")
431         case "$target" in
432           "*/")
433                 target=$( echo "$target" | sed -e 's/\/$//g' )
434                 ;;
435         esac
436
437         [ "$system" = "$fname" ] \
438                 && systxt="\"$system\"" \
439                 || systxt="\"$fname\" [\"$system\"]"
440         [ "$local" -eq 0 ] \
441                 && echo "Working on $systxt ..." \
442                 || echo "Working on $systxt (local system) ..."
443
444         count_all=$count_all+1
445
446         # Check target directory
447         if [ -z "$target" ]; then
448                 echo "No target directory specified for \"$system\"!? Skipped!"
449                 echo; continue
450         fi
451         if [ ! -d "$target" ]; then
452                 echo "Target \"$target\" is not a directory!? \"$system\" skipped!"
453                 echo; continue
454         fi
455
456         sys_target="$target/$fname"
457         sys_root="$sys_target"
458         if [[ "$DRYRUN" -eq 0 && ! -e "$sys_target" ]]; then
459                 if [ $generations -gt 0 ]; then
460                         CreateSubvolume "$sys_target"
461                 else
462                         mkdir -p "$sys_target"
463                 fi
464                 if [ $? -ne 0 ]; then
465                         echo "Can't create \"$sys_target\"!? \"$system\" skipped!"
466                         echo; continue
467                 fi
468         fi
469
470         if [[ "$local" -eq 0 && "$ping" -ne 0 ]]; then
471                 # Check if system is alive
472                 ping -c 1 "$system" >/dev/null 2>&1
473                 if [ $? -ne 0 ]; then
474                         echo "Host \"$system\" seems not to be alive!? Skipped."
475                         echo; continue
476                 fi
477                 echo "OK, host \"$system\" seems to be alive."
478         fi
479
480         if [ $generations -gt 0 ]; then
481                 # Make sure no old backup is stored in system directory
482                 if [ -e "$sys_target/.stamp" ]; then
483                         # There seems to be a genearation-less backup in the
484                         # target directory!
485                         echo "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
486                         echo; continue
487                 fi
488
489                 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
490
491                 if [[ -n "$last" && ! -e "$last/.stamp" ]]; then
492                         # Old backup directory without "stamp file", continue
493                         echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
494                         RenameSubvolume "$last" "$sys_target"
495                         if [ $? -ne 0 ]; then
496                                 echo "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
497                                 echo; continue
498                         fi
499                 elif [ -n "$last" ]; then
500                         # Old backup directory found, create new snapshot
501                         echo "Found last snapshot in \"$last\"."
502                         if [ "$DRYRUN" -eq 0 ]; then
503                                 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
504                                 if [ $r -ne 0 ]; then
505                                         echo "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
506                                         echo; continue
507                                 fi
508                                 echo "Created new snapshot in \"$snapshot\"."
509                         else
510                                 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
511                         fi
512                 else
513                         # No old backup found, create new subvolume
514                         if [ "$DRYRUN" -eq 0 ]; then
515                                 CreateSubvolume "$sys_target"; r=$?
516                                 if [ $r -ne 0 ]; then
517                                         echo "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
518                                         echo; continue
519                                 fi
520                                 echo "Created new subvolume in \"$sys_target\"."
521                         else
522                                 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
523                         fi
524                 fi
525         fi
526
527         ssh_cmd="ssh"
528         [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
529
530         # execute job "pre-exec" command, if any
531         if [ -n "$job_pre_exec" ]; then
532                 ExecJob pre "$job_pre_exec" ; ret=$?
533                 if [ $ret -ne 0 ]; then
534                         [ $ret -ne 99 ] && count_started=$count_started+1
535                         echo "Pre-exec command failed, \"$system\" skipped!"
536                         echo; continue
537                 fi
538         fi
539
540         # prepare (remote) command ...
541         cmd="$rsync --archive"
542         [ "$compress" -ne 0 ] && cmd="$cmd --compress"
543         [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
544         cmd="$cmd --delete --delete-excluded --sparse"
545         if [ "$VERBOSE" -gt 0 ]; then
546                 [ "$rsync_proto" -ge 31 ] \
547                         && cmd="$cmd --info=progress2" \
548                         || cmd="$cmd --progress"
549         fi
550         if [ "$source_root" = "$default_source_root" ]; then
551                 for dir in \
552                         "/dev/**" \
553                         "/media/**" \
554                         "/mnt/**" \
555                         "/net/**" \
556                         "/proc/**" \
557                         "/run/**" \
558                         "/sys/**" \
559                         "/tmp/**" \
560                         "/var/cache/apt/**" \
561                         "/var/log/**" \
562                         "/var/tmp/**" \
563                 ; do
564                         cmd="$cmd --exclude=$dir"
565                 done
566         fi
567         [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
568         for dir in $exclude_dirs_add; do
569                 cmd="$cmd --exclude=$dir"
570         done
571         [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
572
573         [ "$local" -eq 0 ] \
574                 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
575                 || cmd="$cmd $source_root $sys_target/"
576
577         echo "Backing up to \"$sys_target\" ..."
578         echo -n "Start date: "; date
579         echo "$cmd"
580         count_started=$count_started+1
581         ok=0
582
583         if [ "$DRYRUN" -eq 0 ]; then
584                 rm -f "$sys_target/.stamp"
585                 $SHELL -c "$cmd"; ret=$?
586                 echo "code=$ret" >"$sys_target/.stamp"
587         else
588                 echo " *** Trial run, not executing synchronization command!"
589                 ret=0
590         fi
591
592         if [ $ret -eq 20 ]; then
593                 echo "Backup of \"$system\" interrupted. Aborting ..."
594                 GotSignal
595         fi
596
597         echo -n "End date: "; date
598         if [[ $ret -eq 0 || $ret -eq 24 ]]; then
599                 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
600
601                 echo "System \"$system\" completed with status $ret, OK."
602                 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
603                 ok=1
604         else
605                 echo "System \"$system\" completed with ERRORS, code $ret!"
606         fi
607
608         # execute job "post-exec" command, if any
609         if [ -n "$job_post_exec" ]; then
610                 ExecJob post "$job_post_exec"
611         fi
612
613         if [ $generations -gt 0 ]; then
614                 # Update "latest" symlink
615                 if [ "$DRYRUN" -eq 0 ]; then
616                         rm -f "$sys_root/latest"
617                         ln -s "$sys_target" "$sys_root/latest"
618                 fi
619                 # Clean up old generations
620                 declare -i gen_count=$generations+2
621                 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
622                 if [[ -n "$to_delete" && $ok -eq 1 ]]; then
623                         [ "$DRYRUN" -eq 0 ] \
624                                 && echo "Deleting old backup generations (keep $generations) ..." \
625                                 || echo " *** Trial run, not deleting old generations:"
626                         for delete in $to_delete; do
627                                 dir="$sys_root/$delete"
628                                 if [ ! -e "$dir/.stamp" ]; then
629                                         echo "Not deleting \"$dir\", not a backup directory!?"
630                                         continue
631                                 fi
632                                 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
633                                  | cut -d':' -f2- | cut -d. -f1)
634                                 echo "Removing backup from" $last "..."
635                                 if [ "$DRYRUN" -eq 0 ]; then
636                                         DeleteSubvolume "$dir"
637                                         [ $? -eq 0 ] || \
638                                           echo "Failed to delete \"$dir\"!"
639                                 fi
640                         done
641                         echo -n "Clean up finished: "; date
642                 elif [ -n "$to_delete" ]; then
643                         echo "There have been errors, not cleaning up old generations!"
644                 else
645                         echo "Nothing to clean up."
646                 fi
647         fi
648
649         destinations="$destinations $target"
650         echo
651 done
652
653 sync
654
655 if [ "$DRYRUN" -eq 0 ]; then
656         paths=""
657         paths_zfs=""
658         for dest in $(echo $destinations | sed -e 's/ /\n/g' | sort | uniq); do
659                 fs=$(GetFS "$dest")
660                 case $fs in
661                   "zfs" )
662                         paths_zfs="$paths_zfs $dest"
663                         ;;
664                   *)
665                         paths="$paths $dest"
666                 esac
667         done
668         if [ -n "$paths" ]; then
669                 df -h $paths
670                 echo
671         fi
672         if [ -n "$paths_zfs" ]; then
673                 zfs list $paths_zfs
674                 echo
675         fi
676 fi
677
678 CleanUp
679
680 echo -n "Done: "; date
681 echo
682 [ $count_all -eq 1 ] && s="" || s="s"
683 echo " - $count_all job$s defined,"
684 [ $count_started -eq 1 ] && s="" || s="s"
685 echo " - $count_started job$s started,"
686 echo " - $count_ok done without errors."
687 echo
688
689 if [ $count_started -ne $count_ok ]; then
690         echo "----->  THERE HAVE BEEN ERRORS!  <-----"
691         echo
692         exit 6
693 elif [ $count_all -ne $count_started ]; then
694         exit 7
695 fi
696
697 # -eof-