Debian Codegraph @

usr/share/rear/backup/NETFS/default/500_make_backup.sh

raw symbols SCIP
1 #
2 # 500_make_backup.sh
3 #
4
5 function set_tar_features () {
6 # Default tar options
7 TAR_OPTIONS=
8 # Test for features in tar
9 # true if at supports the --warning option (v1.23+)
10 FEATURE_TAR_WARNINGS=
11 local tar_version="$( get_version tar --version )"
12 if version_newer "$tar_version" 1.23 ; then
13 FEATURE_TAR_WARNINGS="y"
14 TAR_OPTIONS+=" --warning=no-xdev"
15 fi
16 FEATURE_TAR_IS_SET=1
17 }
18
19 local backup_prog_rc
20
21 local scheme="$( url_scheme "$BACKUP_URL" )"
22 local path="$( url_path "$BACKUP_URL" )"
23 local opath="$( backup_path "$scheme" "$path" )"
24 test "$opath" && mkdir $v -p "$opath"
25
26 # In any case show an initial basic info what is currently done
27 # so that it is more clear where subsequent messages belong to:
28 LogPrint "Making backup (using backup method $BACKUP)"
29
30 # Verify that preconditions to make the backup are fulfilled and error out if not:
31 if is_true "$BACKUP_PROG_CRYPT_ENABLED" ; then
32 # Backup archive encryption is only supported with 'tar':
33 test "tar" = "$BACKUP_PROG" || Error "Backup archive encryption is only supported with BACKUP_PROG=tar"
34 # Backup archive encryption is impossible without a BACKUP_PROG_CRYPT_KEY value.
35 # Avoid that the BACKUP_PROG_CRYPT_KEY value is shown in debugscript mode
36 # cf. the comment of the UserInput function in lib/_input-output-functions.sh
37 # how to keep things confidential when usr/sbin/rear is run in debugscript mode
38 # ('2>>/dev/$SECRET_OUTPUT_DEV' should be sufficient here because 'test' does not output on stdout):
39 { test "$BACKUP_PROG_CRYPT_KEY" ; } 2>>/dev/$SECRET_OUTPUT_DEV || Error "BACKUP_PROG_CRYPT_KEY must be set for backup archive encryption"
40 LogPrint "Encrypting backup archive with key defined in BACKUP_PROG_CRYPT_KEY"
41 fi
42
43 # Log what is included in the backup and what is excluded from the backup
44 # cf. backup/NETFS/default/400_create_include_exclude_files.sh
45 Log "Backup include list $TMP_DIR/backup-include.txt"
46 while read -r backup_include_item ; do
47 test "$backup_include_item" && Log " $backup_include_item"
48 done < $TMP_DIR/backup-include.txt
49 Log "Backup exclude list $TMP_DIR/backup-exclude.txt"
50 while read -r backup_exclude_item ; do
51 test "$backup_exclude_item" && Log " $backup_exclude_item"
52 done < $TMP_DIR/backup-exclude.txt
53
54 # Check if the backup needs to be split or not (on multiple ISOs).
55 # Dummy split command when the backup is not split (the default case).
56 # Let 'dd' read and write up to 1M=1024*1024 bytes at a time to speed up things
57 # for example from only 500KiB/s (with the 'dd' default of 512 bytes)
58 # via a 100MBit network connection to about its full capacity
59 # cf. https://github.com/rear/rear/issues/2369
60 SPLIT_COMMAND="dd of=$backuparchive bs=1M"
61 if test $ISO_MAX_SIZE ; then
62 is_positive_integer $ISO_MAX_SIZE || Error "ISO_MAX_SIZE must be a positive integer value"
63 # Tell the user when ISO_MAX_SIZE is less than 600MiB because then things will likely not work
64 # because a usual recovery system with FIRMWARE_FILES is more than 300MiB
65 # cf. https://github.com/rear/rear/pull/2347#issuecomment-602812451
66 # so that there is less than 300MiB left for the actual backup split chunk size:
67 test $ISO_MAX_SIZE -ge 600 || LogPrintError "ISO_MAX_SIZE should be at least 600 MiB"
68 # Computation of the actual backup split chunk size
69 # by subtracting the recovery system file sizes (kernel, initrd, ISOLINUX files, UEFI files if used)
70 # from the ISO_MAX_SIZE value, see the ISO_MAX_SIZE explanation in default.conf why that is done.
71 # Size of the recovery system initrd in bytes:
72 INITRD_BYTES=$( stat -c '%s' $TMP_DIR/$REAR_INITRD_FILENAME )
73 is_positive_integer $INITRD_BYTES || Error "Cannot determine size of the recovery system initrd $TMP_DIR/$REAR_INITRD_FILENAME"
74 # Size of the recovery system initrd in MiB + 1MiB to be safe against integer (floor) rounding:
75 INITRD_SIZE=$(( INITRD_BYTES / 1024 / 1024 + 1 ))
76 # Size of the recovery system kernel in bytes:
77 KERNEL_BYTES=$( stat -c '%s' $KERNEL_FILE )
78 is_positive_integer $KERNEL_BYTES || Error "Cannot determine size of the recovery system kernel $KERNEL_FILE"
79 # Size of the recovery system kernel in MiB + 1MiB to be safe against integer (floor) rounding:
80 KERNEL_SIZE=$(( KERNEL_BYTES / 1024 / 1024 + 1 ))
81 # We assume 15MiB is sufficient size for the ISOLINUX bootloader files:
82 ISOLINUX_SIZE=15
83 # We assume 30MiB is sufficient size for additional UEFI bootloader files:
84 UEFI_SIZE=0
85 is_true $USING_UEFI_BOOTLOADER && UEFI_SIZE=30
86 # Size of the recovery system and its bootloader in MiB:
87 RECOVERY_SYSTEM_SIZE=$(( INITRD_SIZE + KERNEL_SIZE + ISOLINUX_SIZE + UEFI_SIZE ))
88 # Tell the user when the recovery system plus ISO bootloader is extraordinarily large because that may indicate a problem elsewehre:
89 test $RECOVERY_SYSTEM_SIZE -gt 1000 && LogPrintError "Extraordinarily large recovery system plus ISO bootloader $RECOVERY_SYSTEM_SIZE MiB"
90 # Size of the actual backup split chunk size in MiB:
91 BACKUP_SPLIT_CHUNK_SIZE=$(( ISO_MAX_SIZE - RECOVERY_SYSTEM_SIZE ))
92 # When the actual backup split chunk size is less than 100MiB we consider it too small to be useful in practice:
93 test $BACKUP_SPLIT_CHUNK_SIZE -ge 100 || Error "Backup split chunk size $BACKUP_SPLIT_CHUNK_SIZE less than 100 MiB (ISO_MAX_SIZE too small?)"
94 # Split the 'tar' backup (at stdin) in chunks of BACKUP_SPLIT_CHUNK_SIZE MiB using 'backup.tar.gz.' as prefix with numeric suffixes:
95 LogPrint "Backup gets split in chunks of $BACKUP_SPLIT_CHUNK_SIZE MiB (ISO_MAX_SIZE $ISO_MAX_SIZE minus recovery system size $RECOVERY_SYSTEM_SIZE)"
96 SPLIT_COMMAND="split -d -b ${BACKUP_SPLIT_CHUNK_SIZE}m - ${backuparchive}."
97 fi
98
99 # Used by "tar" method to record which pipe command failed
100 FAILING_BACKUP_PROG_FILE="$TMP_DIR/failing_backup_prog"
101 FAILING_BACKUP_PROG_RC_FILE="$TMP_DIR/failing_backup_prog_rc"
102
103 # Do not show the BACKUP_PROG_CRYPT_KEY value in a log file
104 # where BACKUP_PROG_CRYPT_KEY is only used if BACKUP_PROG_CRYPT_ENABLED is true
105 # therefore 'Log ... BACKUP_PROG_CRYPT_KEY ...' is used (and not '$BACKUP_PROG_CRYPT_KEY')
106 # but '$BACKUP_PROG_CRYPT_KEY' must be used in the actual command call which means
107 # the BACKUP_PROG_CRYPT_KEY value would appear in the log when rear is run in debugscript mode
108 # so that stderr of the confidential command is redirected to /dev/null
109 # cf. the comment of the UserInput function in lib/_input-output-functions.sh
110 # how to keep things confidential when rear is run in debugscript mode
111 # because it is more important to not leak out user secrets into a log file
112 # than having stderr error messages when a confidential command fails
113 # cf. https://github.com/rear/rear/issues/2155
114 LogPrint "Creating $BACKUP_PROG archive '$backuparchive'"
115 ProgressStart "Preparing archive operation"
116 # Begin backup subshell:
117 (
118 case "$(basename ${BACKUP_PROG})" in
119 # tar compatible programs here
120 (tar)
121 set_tar_features
122
123 if is_true "$BACKUP_PROG_CRYPT_ENABLED" ; then
124 Log $BACKUP_PROG $TAR_OPTIONS --sparse --block-number --totals --verbose \
125 --no-wildcards-match-slash --one-file-system \
126 --ignore-failed-read "${BACKUP_PROG_OPTIONS[@]}" \
127 $BACKUP_PROG_CREATE_NEWER_OPTIONS \
128 ${BACKUP_PROG_BLOCKS:+-b $BACKUP_PROG_BLOCKS} "${BACKUP_PROG_COMPRESS_OPTIONS[@]}" \
129 -X $TMP_DIR/backup-exclude.txt -C / -c -f - \
130 $(cat $TMP_DIR/backup-include.txt) $RUNTIME_LOGFILE \| $BACKUP_PROG_CRYPT_OPTIONS BACKUP_PROG_CRYPT_KEY \| $SPLIT_COMMAND
131 else
132 Log $BACKUP_PROG $TAR_OPTIONS --sparse --block-number --totals --verbose \
133 --no-wildcards-match-slash --one-file-system \
134 --ignore-failed-read "${BACKUP_PROG_OPTIONS[@]}" \
135 $BACKUP_PROG_CREATE_NEWER_OPTIONS \
136 ${BACKUP_PROG_BLOCKS:+-b $BACKUP_PROG_BLOCKS} "${BACKUP_PROG_COMPRESS_OPTIONS[@]}" \
137 -X $TMP_DIR/backup-exclude.txt -C / -c -f - \
138 $(cat $TMP_DIR/backup-include.txt) $RUNTIME_LOGFILE \| $SPLIT_COMMAND
139 fi
140
141 if is_true "$BACKUP_PROG_CRYPT_ENABLED" ; then
142 backup_prog_shortnames=(
143 "$(basename $(echo "$BACKUP_PROG" | awk '{ print $1 }'))"
144 "$(basename $(echo "$BACKUP_PROG_CRYPT_OPTIONS" | awk '{ print $1 }'))"
145 "$(basename $(echo "$SPLIT_COMMAND" | awk '{ print $1 }'))"
146 )
147 $BACKUP_PROG $TAR_OPTIONS --sparse --block-number --totals --verbose \
148 --no-wildcards-match-slash --one-file-system \
149 --ignore-failed-read "${BACKUP_PROG_OPTIONS[@]}" \
150 $BACKUP_PROG_CREATE_NEWER_OPTIONS \
151 ${BACKUP_PROG_BLOCKS:+-b $BACKUP_PROG_BLOCKS} \
152 "${BACKUP_PROG_COMPRESS_OPTIONS[@]}" \
153 -X $TMP_DIR/backup-exclude.txt -C / -c -f - \
154 $(cat $TMP_DIR/backup-include.txt) $RUNTIME_LOGFILE | \
155 { $BACKUP_PROG_CRYPT_OPTIONS "$BACKUP_PROG_CRYPT_KEY" ; } 2>>/dev/$SECRET_OUTPUT_DEV | \
156 $SPLIT_COMMAND
157 pipes_rc=( ${PIPESTATUS[@]} )
158 else
159 backup_prog_shortnames=(
160 "$(basename $(echo "$BACKUP_PROG" | awk '{ print $1 }'))"
161 "$(basename $(echo "$SPLIT_COMMAND" | awk '{ print $1 }'))"
162 )
163 $BACKUP_PROG $TAR_OPTIONS --sparse --block-number --totals --verbose \
164 --no-wildcards-match-slash --one-file-system \
165 --ignore-failed-read "${BACKUP_PROG_OPTIONS[@]}" \
166 $BACKUP_PROG_CREATE_NEWER_OPTIONS \
167 ${BACKUP_PROG_BLOCKS:+-b $BACKUP_PROG_BLOCKS} \
168 "${BACKUP_PROG_COMPRESS_OPTIONS[@]}" \
169 -X $TMP_DIR/backup-exclude.txt -C / -c -f - \
170 $(cat $TMP_DIR/backup-include.txt) $RUNTIME_LOGFILE | \
171 $SPLIT_COMMAND
172 pipes_rc=( ${PIPESTATUS[@]} )
173 fi
174
175 # Variable used to record the short name of piped commands in case of
176 # error, e.g. ( "tar" "cat" "dd" ) in case of unencrypted and unsplit backup.
177 for index in "${!backup_prog_shortnames[@]}" ; do
178 [ -n "${backup_prog_shortnames[$index]}" ] || BugError "No computed shortname for pipe component $index"
179 done
180
181 # Ensure that the numbers of pipe components and return codes match.
182 [ ${#backup_prog_shortnames[@]} -eq ${#pipes_rc[@]} ] || BugError "Mismatching numbers of pipe components and return codes"
183
184 # Exit code logic:
185 # * don't return rc=1 unless from tar (exit code 1 is reserved for "tar" warning about modified files)
186 # * process exit code in pipe's reverse order
187 # - if last command failed (e.g. "dd"), return an error
188 # - otherwise if previous command failed (e.g. "encrypt"), return an error
189 # ...
190 # - otherwise return "tar" exit code
191 # When an error occurs, record the program name in $FAILING_BACKUP_PROG_FILE
192 # and real exit code in $FAILING_BACKUP_PROG_RC_FILE.
193 let index=${#pipes_rc[@]}-1
194 while [ $index -ge 0 ] ; do
195 rc=${pipes_rc[$index]}
196 if [ $rc -ne 0 ] ; then
197 echo "${backup_prog_shortnames[$index]}" > $FAILING_BACKUP_PROG_FILE
198 echo "$rc" > $FAILING_BACKUP_PROG_RC_FILE
199 if [ $rc -eq 1 ] && [ "${backup_prog_shortnames[$index]}" != "tar" ] ; then
200 rc=2
201 fi
202 # Exit the backup subshell with non-zero exit code:
203 exit $rc
204 fi
205 # This pipe command succeeded, check the previous one
206 let index--
207 done
208 # Success - exit the backup subshell with zero exit code:
209 exit 0
210 ;;
211 (rsync)
212 # make sure that the target is a directory
213 mkdir -p $v "$backuparchive" >&2
214 Log $BACKUP_PROG --verbose "${BACKUP_RSYNC_OPTIONS[@]}" --one-file-system --delete \
215 --exclude-from=$TMP_DIR/backup-exclude.txt --delete-excluded \
216 $(cat $TMP_DIR/backup-include.txt) "$backuparchive"
217 $BACKUP_PROG --verbose "${BACKUP_RSYNC_OPTIONS[@]}" --one-file-system --delete \
218 --exclude-from=$TMP_DIR/backup-exclude.txt --delete-excluded \
219 $(cat $TMP_DIR/backup-include.txt) "$backuparchive" >&2
220 ;;
221 (*)
222 Log "Using unsupported backup program '$BACKUP_PROG'"
223 Log $BACKUP_PROG "${BACKUP_PROG_COMPRESS_OPTIONS[@]}" \
224 $BACKUP_PROG_OPTIONS_CREATE_ARCHIVE $TMP_DIR/backup-exclude.txt \
225 "${BACKUP_PROG_OPTIONS[@]}" "$backuparchive" \
226 $(cat $TMP_DIR/backup-include.txt) $RUNTIME_LOGFILE > "$backuparchive"
227 $BACKUP_PROG "${BACKUP_PROG_COMPRESS_OPTIONS[@]}" \
228 $BACKUP_PROG_OPTIONS_CREATE_ARCHIVE $TMP_DIR/backup-exclude.txt \
229 "${BACKUP_PROG_OPTIONS[@]}" "$backuparchive" \
230 $(cat $TMP_DIR/backup-include.txt) $RUNTIME_LOGFILE > "$backuparchive"
231 ;;
232 esac 2> "${TMP_DIR}/${BACKUP_PROG_ARCHIVE}.log"
233 # For the rsync and default case the backup prog is the last in the case entry
234 # and the case .. esac is the last command in the backup subshell.
235 # As a result the return code of the backup subshell is the return code of the backup prog.
236 # For the tar case (where tar is not the last program) special exit code logic is done.
237 ) &
238 BackupPID=$!
239 # End backup subshell.
240
241 starttime=$SECONDS
242 # Give the backup software a good chance to start working:
243 sleep 1
244
245 # return disk usage in bytes
246 function get_disk_used() {
247 let "$(stat -f -c 'used=(%b-%f)*%S' $1)"
248 echo $used
249 }
250
251 # While the backup runs in a subshell, display some progress information to the user.
252 # ProgressInfo texts have a space at the end to get the 'OK' from ProgressStop shown separated.
253 test "$PROGRESS_WAIT_SECONDS" || PROGRESS_WAIT_SECONDS=1
254 case "$( basename $BACKUP_PROG )" in
255 (tar)
256 while sleep $PROGRESS_WAIT_SECONDS ; kill -0 $BackupPID 2>/dev/null; do
257 #blocks="$(stat -c %b ${backuparchive})"
258 #size="$((blocks*512))"
259 size="$(stat -c %s ${backuparchive}* | awk '{s+=$1} END {print s}')"
260 ProgressInfo "Archived $((size/1024/1024)) MiB [avg $((size/1024/(SECONDS-starttime))) KiB/sec] "
261 done
262 ;;
263 (rsync)
264 # since we do not want to do a $(du -s) run every second we count disk usage instead
265 # this obviously leads to wrong results in case something else is writing to the same
266 # disk at the same time as is very likely with a networked file system. For local disks
267 # this should be good enough and in any case this is only some eye candy.
268 # TODO: Find a fast way to count the actual transfer data, preferable getting the info from rsync.
269 let old_disk_used="$(get_disk_used "$backuparchive")"
270 while sleep $PROGRESS_WAIT_SECONDS ; kill -0 $BackupPID 2>/dev/null; do
271 let disk_used="$(get_disk_used "$backuparchive")" size=disk_used-old_disk_used
272 ProgressInfo "Archived $((size/1024/1024)) MiB [avg $((size/1024/(SECONDS-starttime))) KiB/sec] "
273 done
274 ;;
275 (*)
276 while sleep $PROGRESS_WAIT_SECONDS ; kill -0 $BackupPID 2>/dev/null; do
277 size="$(stat -c "%s" "$backuparchive")" || {
278 kill -9 $BackupPID
279 ProgressError
280 Error "$(basename $BACKUP_PROG) failed to create the archive file"
281 }
282 ProgressInfo "Archived $((size/1024/1024)) MiB [avg $((size/1024/(SECONDS-starttime))) KiB/sec] "
283 done
284 ;;
285 esac
286 ProgressStop
287 transfertime="$((SECONDS-starttime))"
288
289 # harvest return code from background job. The kill -0 $BackupPID loop above should
290 # have made sure that this wait won't do any real "waiting" :-)
291 wait $BackupPID
292 backup_prog_rc=$?
293
294 if [[ $BACKUP_INTEGRITY_CHECK =~ ^[yY1] && "$(basename ${BACKUP_PROG})" = "tar" ]] ; then
295 (cd $(dirname "$backuparchive") && md5sum $(basename "$backuparchive") > "${backuparchive}".md5 || md5sum $(basename "$backuparchive").?? > "${backuparchive}".md5)
296 fi
297
298 # TODO: Why do we sleep here after 'wait $BackupPID'?
299 sleep 1
300
301 # Everyone should see this warning, even if not verbose:
302 case "$(basename $BACKUP_PROG)" in
303 (tar)
304 if (( $backup_prog_rc != 0 )); then
305 prog="$(cat $FAILING_BACKUP_PROG_FILE)"
306 # Suppress purely informational tar messages from output like
307 # tar: Removing leading / from member names
308 # tar: Removing leading / from hard link targets
309 # tar: /var/spool/postfix/private/discard: socket ignored
310 # but keep actual tar error or warning messages like
311 # tar: /etc/grub.d/README: file changed as we read it
312 # and show only messages that are prefixed with "$prog:" (like 'tar:' or 'dd:')
313 # which works when 'tar' or 'dd' fail but falsely suppresses messages from 'openssl'
314 # FIXME see https://github.com/rear/rear/pull/2466#discussion_r466347471
315 if (( $backup_prog_rc == 1 )); then
316 LogUserOutput "WARNING: $prog ended with return code 1 and below output (last 5 lines):
317 ---snip---
318 $( sed -n -e '/^tar: .*\(socket ignored\|Removing leading\)/d;/^'"$prog"':/s/^/ /p' "${TMP_DIR}/${BACKUP_PROG_ARCHIVE}.log" | tail -n5 )
319 ----------
320 This means that files have been modified during the archiving
321 process. As a result the backup may not be completely consistent
322 or may not be a perfect copy of the system. Relax-and-Recover
323 will continue, however it is highly advisable to verify the
324 backup in order to be sure to safely recover this system.
325 "
326 else
327 rc=$(cat $FAILING_BACKUP_PROG_RC_FILE)
328 Error "$prog failed with return code $rc and below output (last 5 lines):
329 ---snip---
330 $( sed -n -e '/^tar: .*\(socket ignored\|Removing leading\)/d;/^'"$prog"':/s/^/ /p' "${TMP_DIR}/${BACKUP_PROG_ARCHIVE}.log" | tail -n5 )
331 ----------
332 This means that the archiving process ended prematurely, or did
333 not even start. As a result it is unlikely you can recover this
334 system properly. Relax-and-Recover is therefore aborting execution.
335 "
336 fi
337 fi
338 ;;
339 (*)
340 if (( $backup_prog_rc > 0 )) ; then
341 Error "$(basename $BACKUP_PROG) failed with return code $backup_prog_rc
342
343 This means that the archiving process ended prematurely, or did
344 not even start. As a result it is unlikely you can recover this
345 system properly. Relax-and-Recover is therefore aborting execution.
346 "
347 fi
348 ;;
349 esac
350
351 tar_message="$(tac $RUNTIME_LOGFILE | grep -m1 '^Total bytes written: ')"
352 if [ $backup_prog_rc -eq 0 -a "$tar_message" ] ; then
353 LogPrint "$tar_message in $transfertime seconds."
354 elif [ "$size" ]; then
355 LogPrint "Archived $((size/1024/1024)) MiB in $((transfertime)) seconds [avg $((size/1024/transfertime)) KiB/sec]"
356 fi
357
358 ### Copy progress log to backup media
359 cp $v "${TMP_DIR}/${BACKUP_PROG_ARCHIVE}.log" "${opath}/${BACKUP_PROG_ARCHIVE}.log" >&2
360
361 # vim: set et ts=4 sw=4: