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