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