]> arthur.barton.de Git - backup-script.git/blob - bin/backup-script
Add "[default_]exclude_dirs_add" options
[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                         "$volume/.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 trap GotSignal SIGINT
302
303 echo -n "Started: "; date
304 echo -e $config_info
305 echo
306
307 if [ $# -ge 1 ]; then
308         for s in "$@"; do
309                 if [ ! -r "${conf_d}/$s" ]; then
310                         echo "$NAME: Can' read \"${conf_d}/$s\"!"
311                         exit 3
312                 fi
313                 sys="$sys ${conf_d}/$s"
314         done
315 else
316         sys="${conf_d}/"*
317 fi
318
319 # check and create PID file
320 if [ -e "$PIDFILE" ]; then
321         echo "Lockfile \"$PIDFILE\" already exists."
322         echo "Is an other instance still running?"
323         echo
324         echo -n "Aborted: "; date
325         echo
326         exit 4
327 fi
328 touch "$PIDFILE" 2>/dev/null
329 if [ $? -ne 0 ]; then
330         echo "Warning: can't create PID file \"$PIDFILE\"!"
331         echo
332 else
333         echo "$$" >>"$PIDFILE"
334 fi
335
336 if [ -n "$pre_exec" ]; then
337         echo "Executing \"$pre_exec\" ..."
338         sh -c $pre_exec
339         if [ $? -ne 0 ]; then
340                 echo "Error: pre-exec command failed!"; echo
341                 CleanUp
342                 echo "Aborting backup."; echo
343                 exit 5
344         fi
345         sleep 2
346         echo
347 fi
348
349 for f in $sys; do
350         [ -r "$f" -a -f "$f" ] || continue
351
352         fname=$(basename "$f")
353         case "$fname" in
354                 "backup-script.conf"|*.sh)
355                         continue
356                         ;;
357         esac
358
359         # Set global defaults
360         system="$fname"
361         user="$default_user"
362         source_root="$default_source_root"
363         target="$default_target"
364         ssh_args_add="$default_ssh_args_add"
365         rsync_args_add="$default_rsync_args_add"
366         exclude_args_add="$default_exclude_args_add"
367         exclude_dirs_add="$default_exclude_dirs_add"
368         compress="$default_compress"
369         ping="$default_ping"
370         local="$default_local"
371         generations="$default_generations"
372         job_pre_exec="$default_job_pre_exec"
373         job_post_exec="$default_job_post_exec"
374
375         # Compatibility with backup-pull(1) script: Save global values ...
376         pre_exec_saved="$pre_exec"
377         post_exec_saved="$post_exec"
378
379         # Compatibility with backup-pull(1) script: Set defaults
380         unset host
381         unset source
382         unset pre_exec
383         unset post_exec
384
385         # Read in system configuration file
386         source "$f"
387
388         # Compatibility with backup-pull(1) script: Fix up configuration
389         [ "$system" = "$fname" -a -n "$host" ] \
390                 && system="$host"
391         [ "$source_root" = "$default_source_root" -a -n "$source" ] \
392                 && source_root="$source"
393         [ -z "$job_pre_exec" -a -n "$pre_exec" ] \
394                 && job_pre_exec="$pre_exec"
395         [ -z "$job_post_exec" -a -n "$post_exec" ] \
396                 && job_post_exec="$post_exec"
397
398         # Compatibility with backup-pull(1) script: Restore global values ...
399         pre_exec="$pre_exec_saved"
400         post_exec="$post_exec_saved"
401
402         # Validate configuration
403         if [ "$system" = "localhost" -o "$system" = "127.0.0.1" ]; then
404                 # Local system
405                 local=1
406                 compress=0
407         fi
408
409         # Make sure "source" ends with a slash ("/")
410         case "$source" in
411           "*/")
412                 ;;
413           "*")
414                 source="$source/"
415         esac
416
417         # Make sure "target" DOESN'T end with a slash ("/")
418         case "$target" in
419           "*/")
420                 target=$( echo "$target" | sed -e 's/\/$//g' )
421                 ;;
422         esac
423
424         [ "$system" = "$fname" ] \
425                 && systxt="\"$system\"" \
426                 || systxt="\"$fname\" [\"$system\"]"
427         [ "$local" -eq 0 ] \
428                 && echo "Working on $systxt ..." \
429                 || echo "Working on $systxt (local system) ..."
430
431         count_all=$count_all+1
432
433         # Check target directory
434         if [ -z "$target" ]; then
435                 echo "No target directory specified for \"$system\"!? Skipped!"
436                 echo; continue
437         fi
438         if [ ! -d "$target" ]; then
439                 echo "Target \"$target\" is not a directory!? \"$system\" skipped!"
440                 echo; continue
441         fi
442
443         sys_target="$target/$fname"
444         sys_root="$sys_target"
445         if [ "$DRYRUN" -eq 0 -a ! -e "$sys_target" ]; then
446                 if [ $generations -gt 0 ]; then
447                         CreateSubvolume "$sys_target"
448                 else
449                         mkdir -p "$sys_target"
450                 fi
451                 if [ $? -ne 0 ]; then
452                         echo "Can't create \"$sys_target\"!? \"$system\" skipped!"
453                         echo; continue
454                 fi
455         fi
456
457         if [ "$local" -eq 0 -a "$ping" -ne 0 ]; then
458                 # Check if system is alive
459                 ping -c 1 "$system" >/dev/null 2>&1
460                 if [ $? -ne 0 ]; then
461                         echo "Host \"$system\" seems not to be alive!? Skipped."
462                         echo; continue
463                 fi
464                 echo "OK, host \"$system\" seems to be alive."
465         fi
466
467         if [ $generations -gt 0 ]; then
468                 # Make sure no old backup is stored in system directory
469                 if [ -e "$sys_target/.stamp" ]; then
470                         # There seems to be a genearation-less backup in the
471                         # target directory!
472                         echo "Target directory \"$sys_target\" seems to be unclean!? \"$system\" skipped!"
473                         echo; continue
474                 fi
475
476                 Initialize_Last_SysTarget_Snapshot "$sys_target" || continue
477
478                 if [ -n "$last" -a ! -e "$last/.stamp" ]; then
479                         # Old backup directory without "stamp file", continue
480                         echo "Found incomplete snapshot in \"$last\", reusing and renaming it ..."
481                         RenameSubvolume "$last" "$sys_target"
482                         if [ $? -ne 0 ]; then
483                                 echo "Failed to rename last snapshot \"$last\" to \"$sys_target\"!? \"$system\" skipped!"
484                                 echo; continue
485                         fi
486                 elif [ -n "$last" ]; then
487                         # Old backup directory found, create new snapshot
488                         echo "Found last snapshot in \"$last\"."
489                         if [ "$DRYRUN" -eq 0 ]; then
490                                 CloneSubvolume "$last" "$sys_target" "$snapshot"; r=$?
491                                 if [ $r -ne 0 ]; then
492                                         echo "Can't create snapshot \"$snapshot\" of \"$last\", code $r!? \"$system\" skipped!"
493                                         echo; continue
494                                 fi
495                                 echo "Created new snapshot in \"$snapshot\"."
496                         else
497                                 echo " *** Trial run, not creating new snapshot in \"$snapshot\"!"
498                         fi
499                 else
500                         # No old backup found, create new subvolume
501                         if [ "$DRYRUN" -eq 0 ]; then
502                                 CreateSubvolume "$sys_target"; r=$?
503                                 if [ $r -ne 0 ]; then
504                                         echo "Can't create subvolume \"$sys_target\", code $r!? \"$system\" skipped!"
505                                         echo; continue
506                                 fi
507                                 echo "Created new subvolume in \"$sys_target\"."
508                         else
509                                 echo " *** Trial run, not creating new subvolume \"$sys_target\"!"
510                         fi
511                 fi
512         fi
513
514         ssh_cmd="ssh"
515         [ -n "$ssh_args_add" ] && ssh_cmd="$ssh_cmd $ssh_args_add"
516
517         # execute job "pre-exec" command, if any
518         if [ -n "$job_pre_exec" ]; then
519                 ExecJob pre "$job_pre_exec" ; ret=$?
520                 if [ $ret -ne 0 ]; then
521                         [ $ret -ne 99 ] && count_started=$count_started+1
522                         echo "Pre-exec command failed, \"$system\" skipped!"
523                         echo; continue
524                 fi
525         fi
526
527         # prepare (remote) command ...
528         cmd="rsync --archive"
529         [ "$compress" -ne 0 ] && cmd="$cmd --compress"
530         [ "$local" -eq 0 ] && cmd="$cmd --rsh=\"$ssh_cmd\""
531         cmd="$cmd --delete --delete-excluded --sparse"
532         [ "$VERBOSE" -gt 0 ] && cmd="$cmd --progress"
533         if [ "$source_root" = "$default_source_root" ]; then
534                 cmd="$cmd --exclude=/dev --exclude=/proc --exclude=/sys"
535                 cmd="$cmd --exclude=/run --exclude=/tmp --exclude=/var/tmp"
536                 cmd="$cmd --exclude=/media --exclude=/mnt --exclude=/net"
537                 cmd="$cmd --exclude=/var/cache/apt --exclude=/var/log"
538         fi
539         [ -n "$exclude_args_add" ] && cmd="$cmd $exclude_args_add"
540         for dir in $exclude_dirs_add; do
541                 cmd="$cmd --exclude=$dir"
542         done
543         [ -n "$rsync_args_add" ] && cmd="$cmd $rsync_args_add"
544
545         [ "$local" -eq 0 ] \
546                 && cmd="$cmd ${user}@${system}:$source_root $sys_target/" \
547                 || cmd="$cmd $source_root $sys_target/"
548
549         echo "Backing up to \"$sys_target\" ..."
550         echo -n "Start date: "; date
551         echo "$cmd"
552         count_started=$count_started+1
553         ok=0
554
555         if [ "$DRYRUN" -eq 0 ]; then
556                 rm -f "$sys_target/.stamp"
557                 $SHELL -c "$cmd"; ret=$?
558                 echo "code=$ret" >"$sys_target/.stamp"
559         else
560                 echo " *** Trial run, not executing synchronization command!"
561                 ret=0
562         fi
563
564         if [ $ret -eq 20 ]; then
565                 echo "Backup of \"$system\" interrupted. Aborting ..."
566                 GotSignal
567         fi
568
569         echo -n "End date: "; date
570         if [ $ret -eq 0 -o $ret -eq 24 ]; then
571                 [ $ret -eq 24 ] && count_ok_vanished=$count_ok_vanished+1
572
573                 echo "System \"$system\" completed with status $ret, OK."
574                 [ "$DRYRUN" -gt 0 ] || count_ok=$count_ok+1
575                 ok=1
576         else
577                 echo "System \"$system\" completed with ERRORS, code $ret!"
578         fi
579
580         # execute job "post-exec" command, if any
581         if [ -n "$job_post_exec" ]; then
582                 ExecJob post "$job_post_exec"
583         fi
584
585         if [ $generations -gt 0 ]; then
586                 # Update "latest" symlink
587                 if [ "$DRYRUN" -eq 0 ]; then
588                         rm -f "$sys_root/latest"
589                         ln -s "$sys_target" "$sys_root/latest"
590                 fi
591                 # Clean up old generations
592                 declare -i gen_count=$generations+2
593                 to_delete=$(ls -1t "$sys_root" 2>/dev/null | tail -n+$gen_count | sort)
594                 if [ -n "$to_delete" -a $ok -eq 1 ]; then
595                         [ "$DRYRUN" -eq 0 ] \
596                                 && echo "Deleting old backup generations (keep $generations) ..." \
597                                 || echo " *** Trial run, not deleting old generations:"
598                         for delete in $to_delete; do
599                                 dir="$sys_root/$delete"
600                                 if [ ! -e "$dir/.stamp" ]; then
601                                         echo "Not deleting \"$dir\", not a backup directory!?"
602                                         continue
603                                 fi
604                                 last=$(stat "$dir/.stamp" 2>/dev/null | grep "^Modify: " \
605                                  | cut -d':' -f2- | cut -d. -f1)
606                                 echo "Removing backup from" $last "..."
607                                 if [ "$DRYRUN" -eq 0 ]; then
608                                         DeleteSubvolume "$dir"
609                                         [ $? -eq 0 ] || \
610                                           echo "Failed to delete \"$dir\"!"
611                                 fi
612                         done
613                         echo -n "Clean up finished: "; date
614                 elif [ -n "$to_delete" ]; then
615                         echo "There have been errors, not cleaning up old generations!"
616                 else
617                         echo "Nothing to clean up."
618                 fi
619         fi
620
621         destinations="$destinations $target"
622         echo
623 done
624
625 sync
626
627 if [ "$DRYRUN" -eq 0 ]; then
628         paths=""
629         paths_zfs=""
630         for dest in $(echo $destinations | sed -e 's/ /\n/g' | sort | uniq); do
631                 fs=$(GetFS "$dest")
632                 case $fs in
633                   "zfs" )
634                         paths_zfs="$paths_zfs $dest"
635                         ;;
636                   *)
637                         paths="$paths $dest"
638                 esac
639         done
640         if [ -n "$paths" ]; then
641                 df -h $paths
642                 echo
643         fi
644         if [ -n "$paths_zfs" ]; then
645                 zfs list $paths_zfs
646                 echo
647         fi
648 fi
649
650 CleanUp
651
652 echo -n "Done: "; date
653 echo
654 [ $count_all -eq 1 ] && s="" || s="s"
655 echo " - $count_all job$s defined,"
656 [ $count_started -eq 1 ] && s="" || s="s"
657 echo " - $count_started job$s started,"
658 echo " - $count_ok done without errors."
659 echo
660
661 if [ $count_started -ne $count_ok ]; then
662         echo "----->  THERE HAVE BEEN ERRORS!  <-----"
663         echo
664         exit 6
665 elif [ $count_all -ne $count_started ]; then
666         exit 7
667 fi
668
669 # -eof-