Debian Codegraph @

usr/share/rear/lib/layout-functions.sh

raw symbols SCIP
1 # Utility functions for the system layout processing.
2
3 # Each file will be only saved once by save_original_file()
4 # and all subsequent save_original_file() for the same file do nothing
5 # because each saved file is remembered in the SAVED_ORIGINAL_FILES array:
6 SAVED_ORIGINAL_FILES=()
7 SAVED_ORIGINAL_FILE_SUFFIX="orig"
8
9 # Save the original content of the file $1 to $1.$START_DATE_TIME_NUMBER.$2.orig
10 # or to $1.$START_DATE_TIME_NUMBER.$WORKFLOW.$MASTER_PID.orig when no $2 is specified:
11 save_original_file() {
12 local filename="$1"
13 test -r "$filename" || return 1
14 IsInArray "$filename" "${SAVED_ORIGINAL_FILES[@]}" && return 0
15 local extension="$2"
16 test "$extension" || extension=$WORKFLOW.$MASTER_PID
17 local saved_original_file="$filename.$START_DATE_TIME_NUMBER.$extension.$SAVED_ORIGINAL_FILE_SUFFIX"
18 cp -ar $filename $saved_original_file && SAVED_ORIGINAL_FILES+=( "$filename" )
19 }
20
21 # Restore the saved original content of the original file named $1
22 # that was saved as $1.$START_DATE_TIME_NUMBER.$2.orig or $1.$START_DATE_TIME_NUMBER.$WORKFLOW.$MASTER_PID.orig
23 restore_original_file() {
24 local filename="$1"
25 local extension="$2"
26 test "$extension" || extension=$WORKFLOW.$MASTER_PID
27 local saved_original_file="$filename.$START_DATE_TIME_NUMBER.$extension.$SAVED_ORIGINAL_FILE_SUFFIX"
28 test -r "$saved_original_file" || return 1
29 cp -ar $saved_original_file $filename
30 }
31
32 # Generate code to recreate a device $1 of type $2 and then mount it.
33 # Note that we do not handle partitioning here.
34 create_device() {
35 local device="$1"
36 local type="$2"
37 local name # used to extract the actual name of the device
38
39 cat <<EOF >> "$LAYOUT_CODE"
40 if create_component "$device" "$type" ; then
41 EOF
42 echo "# Create $device ($type)" >> "$LAYOUT_CODE"
43 if type -t create_$type >/dev/null ; then
44 create_$type "$device"
45 fi
46 cat <<EOF >> "$LAYOUT_CODE"
47 component_created "$device" "$type"
48 else
49 LogPrint "Skipping $device ($type) as it has already been created."
50 fi
51
52 EOF
53 }
54
55 # Generate code to mount a device $1 of type $2 ('mountonly' workflow).
56 do_mount_device() {
57 local device="$1"
58 local type="$2"
59 local name # used to extract the actual name of the device
60
61 cat <<EOF >> "$LAYOUT_CODE"
62 if create_component "$device" "$type" ; then
63 EOF
64 # This can be used a.o. to decrypt a LUKS device
65 echo "# Open $device ($type)" >> "$LAYOUT_CODE"
66 if type -t open_$type >/dev/null ; then
67 open_$type "$device"
68 fi
69
70 # If the device is mountable, it will then be mounted
71 echo "# Mount $device ($type)" >> "$LAYOUT_CODE"
72 if type -t mount_$type >/dev/null ; then
73 mount_$type "$device"
74 fi
75 cat <<EOF >> "$LAYOUT_CODE"
76 component_created "$device" "$type"
77 else
78 LogPrint "Skipping $device ($type) as it has already been mounted."
79 fi
80
81 EOF
82 }
83
84 abort_recreate() {
85 Log "Error detected during restore."
86 Log "Restoring saved original $LAYOUT_FILE"
87 restore_original_file "$LAYOUT_FILE"
88 }
89
90 abort_dasd_format() {
91 Log "Error detected during DASD formatting."
92 Log "Restoring saved original $DASD_FORMAT_FILE"
93 restore_original_file "$DASD_FORMAT_FILE"
94 }
95
96 # Test and log if a component $1 (type $2) needs to be recreated.
97 create_component() {
98 local device="$1"
99 local type="$2"
100 # If a touchfile already exists, no need to recreate this component.
101 local touchfile="$type-${device//\//-}"
102 if [ -e "$LAYOUT_TOUCHDIR/$touchfile" ] ; then
103 return 1
104 else
105 return 0
106 fi
107 }
108
109 # Mark a component as created.
110 component_created() {
111 local device=$1
112 local type=$2
113 # Create a touchfile.
114 local touchfile="$type-${device//\//-}"
115 touch "$LAYOUT_TOUCHDIR/$touchfile"
116 }
117
118 # Generate dependencies between disks as found in $LAYOUT_FILE.
119 # This will be written to $LAYOUT_DEPS.
120 # Also generate a list of disks to be restored in $LAYOUT_TODO.
121 generate_layout_dependencies() {
122 # $LAYOUT_DEPS is a list of:
123 # <item> <depends on>
124 : > $LAYOUT_DEPS
125
126 # $LAYOUT_TODO is a list of:
127 # [todo|done] <type> <item>
128 : > $LAYOUT_TODO
129
130 local type dev remainder name disk disks vgrp dm_vgrp lvol dm_lvol part mp fs bd nmp temp_nm
131 while read type remainder ; do
132 case $type in
133 disk)
134 name=$(echo "$remainder" | cut -d " " -f "1")
135 add_component "$name" "disk"
136 ;;
137 part)
138 # disk is the first field of the remainder
139 disk=$(echo "$remainder" | cut -d " " -f "1")
140 name=$(echo "$remainder" | cut -d " " -f "6")
141 add_dependency "$name" "$disk"
142 add_component "$name" "part"
143 ;;
144 lvmgrp)
145 name=$(echo "$remainder" | cut -d " " -f "1")
146 add_component "$name" "lvmgrp"
147 ;;
148 lvmdev)
149 vgrp=$(echo "$remainder" | cut -d " " -f "1")
150 part=$(echo "$remainder" | cut -d " " -f "2")
151 add_dependency "$vgrp" "pv:$part"
152 add_dependency "pv:$part" "$part"
153 add_component "pv:$part" "lvmdev"
154 ;;
155 lvmvol)
156 vgrp=$(echo "$remainder" | cut -d " " -f "1")
157 lvol=$(echo "$remainder" | cut -d " " -f "2")
158 # When a LV is a Thin, then we need to create the Thin Pool first
159 pool=$(echo "$remainder" | grep -Eow "thinpool:\\S+" | cut -d ":" -f 2)
160
161 # Vgs and Lvs containing - in their name have a double dash in DM
162 dm_vgrp=${vgrp//-/--}
163 dm_lvol=${lvol//-/--}
164 dm_pool=${pool//-/--}
165
166 dm_prefix="/dev/mapper/${dm_vgrp#/dev/}"
167 add_dependency "$dm_prefix-$dm_lvol" "$vgrp"
168 [ -z "$pool" ] || add_dependency "$dm_prefix-$dm_lvol" "$dm_prefix-$dm_pool"
169 add_component "$dm_prefix-$dm_lvol" "lvmvol"
170 ;;
171 raidarray)
172 name=$(echo "$remainder" | cut -d " " -f "1")
173 disks=$(echo "$remainder" | sed -r "s/.*devices=([^ ]+).*/\1/" | tr ',' ' ')
174 for disk in $disks ; do
175 add_dependency "$name" "$disk"
176 done
177 add_component "$name" "raidarray"
178 ;;
179 fs|btrfsmountedsubvol)
180 dev=$(echo "$remainder" | cut -d " " -f "1")
181 mp=$(echo "$remainder" | cut -d " " -f "2")
182 add_dependency "$type:$mp" "$dev"
183 add_component "$type:$mp" "$type"
184
185 # find dependencies on other filesystems
186 while read dep_type bd dep_mp junk; do
187 if [ "$dep_mp" != "/" ] ; then
188 # make sure we only match complete paths
189 # e.g. not /data as a parent of /data1
190 temp_dep_mp="$dep_mp/"
191 else
192 temp_dep_mp="$dep_mp"
193 fi
194
195 if [ "${mp#$temp_dep_mp}" != "${mp}" ] && [ "$mp" != "$dep_mp" ]; then
196 add_dependency "$type:$mp" "$dep_type:$dep_mp"
197 fi
198 done < <( grep -E '^fs |^btrfsmountedsubvol ' $LAYOUT_FILE )
199 ;;
200 swap)
201 dev=$(echo "$remainder" | cut -d " " -f "1")
202 add_dependency "swap:$dev" "$dev"
203 add_component "swap:$dev" "swap"
204 ;;
205 drbd)
206 dev=$(echo "$remainder" | cut -d " " -f "1")
207 disk=$(echo "$remainder" | cut -d " " -f "3")
208 add_dependency "$dev" "$disk"
209 add_component "$dev" "drbd"
210 ;;
211 crypt)
212 name=$(echo "$remainder" | cut -d " " -f "1")
213 dev=$(echo "$remainder" | cut -d " " -f "2")
214 add_dependency "$name" "$dev"
215 add_component "$name" "crypt"
216 ;;
217 multipath)
218 name=$(echo "$remainder" | cut -d " " -f "1")
219 disks=$(echo "$remainder" | cut -d " " -f "4" | tr "," " ")
220 add_component "$name" "multipath"
221 for disk in $disks ; do
222 add_dependency "$name" "$disk"
223 done
224 ;;
225 opaldisk)
226 dev=$(echo "$remainder" | cut -d " " -f "1")
227 add_component "opaldisk:$dev" "opaldisk"
228 for disk in $(opal_device_disks "$dev"); do
229 add_dependency "$disk" "opaldisk:$dev"
230 done
231 ;;
232 esac
233 done < $LAYOUT_FILE
234 }
235
236 # Add a dependency from one component on another
237 # add_dependency <from> <on>
238 add_dependency() {
239 echo "$1 $2" >> $LAYOUT_DEPS
240 }
241
242 # Add a component to be restored
243 # add_component <name> <type>
244 # The name must be equal to the one used in dependency resolution
245 # The type is needed to restore the component.
246 add_component() {
247 echo "todo $1 $2" >> $LAYOUT_TODO
248 }
249
250 # The distinction in the mark_as_done and mark_tree_as_done functions what messages should appear
251 # - only in the log file in debug '-d' mode via 'Debug'
252 # - in the log file and on the user's terminal in debug '-d' mode via 'DebugPrint'
253 # matches the same kind of distinction in the disable_component_... functions
254 # in layout/save/default/330_remove_exclusions.sh
255 # but no LogPrint is used in the lower-level mark_as_done and mark_tree_as_done functions.
256
257 # Mark component $1 as done.
258 mark_as_done() {
259 # The trailing blank in "... $1 " is crucial to not match wrong components
260 # for example the component "... /dev/sda1" must not match accidentally
261 # other components like "... /dev/sda12" in var/lib/rear/layout/disktodo.conf
262 if grep -q "done $1 " $LAYOUT_TODO ; then
263 DebugPrint "Component '$1' is marked as 'done $1' in $LAYOUT_TODO"
264 return 0
265 fi
266 if ! grep -q "todo $1 " $LAYOUT_TODO ; then
267 Debug "Cannot mark component '$1' as done because there is no 'todo $1 ' in $LAYOUT_TODO"
268 return 1
269 fi
270 DebugPrint "Marking component '$1' as done in $LAYOUT_TODO"
271 sed -i "s;todo\ $1\ ;done\ $1\ ;" $LAYOUT_TODO
272 }
273
274 # Mark all components that depend on component $1 as done.
275 mark_tree_as_done() {
276 for component in $( get_child_components "$1" ) ; do
277 DebugPrint "Dependent component $component is a child of component $1"
278 mark_as_done "$component"
279 done
280 }
281
282 # Return all the (grand-)child components of $1 [filtered by type $2]
283 get_child_components() {
284 declare -a devlist children
285 declare current child parent
286
287 devlist=( "$1" )
288 while (( ${#devlist[@]} )) ; do
289 current=${devlist[0]}
290
291 ### Find all direct child elements of the current component...
292 while read child parent junk ; do
293 if [[ "$parent" = "$current" ]] ; then
294 ### ...and add them to the list
295 if IsInArray "$child" "${children[@]}" ; then
296 continue
297 fi
298 devlist+=( "$child" )
299 children+=( "$child" )
300 fi
301 done < $LAYOUT_DEPS
302
303 # remove the current element from the array and re-index it because
304 # "unset does not remove the element it just sets null string to the particular index in array"
305 # see https://stackoverflow.com/questions/16860877/remove-an-element-from-a-bash-array
306 unset "devlist[0]"
307 devlist=( "${devlist[@]}" )
308 done
309
310 ### Filter for the wanted type
311 declare component type
312 for component in "${children[@]}" ; do
313 if [[ "$2" ]] ; then
314 type=$(get_component_type "$component")
315 if [[ "$type" != "$2" ]] ; then
316 continue
317 fi
318 fi
319 echo "$component"
320 done
321 }
322
323 # Return all ancestors of component $1 [ of type $2 [ skipping types $3 during resolution ] ]
324 get_parent_components() {
325 declare -a ancestors devlist ignoretypes
326 declare current child parent parenttype
327
328 devlist=( "$1" )
329 if [[ "$3" ]] ; then
330 # third argument should, if present, be a space-separated list
331 # of types to ignore when walking up the dependency tree.
332 # Convert it to array
333 ignoretypes=( $3 )
334 else
335 ignoretypes=()
336 fi
337 while (( ${#devlist[@]} )) ; do
338 current=${devlist[0]}
339
340 ### Find all direct parent elements of the current component...
341 while read child parent junk ; do
342 if [[ "$child" = "$current" ]] ; then
343 ### ...test if we visited them already...
344 if IsInArray "$parent" "${ancestors[@]}" ; then
345 continue
346 fi
347 ### ...test if parent is of a correct type if requested...
348 if [[ ${#ignoretypes[@]} -gt 0 ]] ; then
349 parenttype=$(get_component_type "$parent")
350 if IsInArray "$parenttype" "${ignoretypes[@]}" ; then
351 continue
352 fi
353 fi
354 ### ...and add them to the list
355 devlist+=( "$parent" )
356 ancestors+=( "$parent" )
357 fi
358 done < $LAYOUT_DEPS
359
360 # remove the current element from the array and re-index it because
361 # "unset does not remove the element it just sets null string to the particular index in array"
362 # see https://stackoverflow.com/questions/16860877/remove-an-element-from-a-bash-array
363 unset "devlist[0]"
364 devlist=( "${devlist[@]}" )
365 done
366
367 ### Filter the ancestors for the correct type.
368 declare component type
369 for component in "${ancestors[@]}" ; do
370 if [[ "$2" ]] ; then
371 type=$(get_component_type "$component")
372 if [[ "$type" != "$2" ]] ; then
373 continue
374 fi
375 fi
376 echo "$component"
377 done
378 }
379
380 # find_devices <other>
381 # ${2+"$2"} in the following functions ensures that $2 gets passed down quoted if present
382 # and ignored if not present
383 # Find the disk device(s) component $1 resides on.
384 find_disk() {
385 get_parent_components "$1" "disk" ${2+"$2"}
386 }
387
388 find_multipath() {
389 get_parent_components "$1" "multipath" ${2+"$2"}
390 }
391
392 find_disk_and_multipath() {
393 find_disk "$1" ${2+"$2"}
394 is_true "$AUTOEXCLUDE_MULTIPATH" || find_multipath "$1" ${2+"$2"}
395 }
396
397 find_partition() {
398 get_parent_components "$1" "part" ${2+"$2"}
399 }
400
401 # The get_partition_number function
402 # outputs the trailing digits of a partition block device as its partition number.
403 # Usually only the basename of the partition block device is used as function argument
404 # e.g. "get_partition_number sda2" instead of "get_partition_number /dev/sda2".
405 # The implementation requires grep v2.5 or higher (option -o is used).
406 # This function should support:
407 # /dev/mapper/36001438005deb05d0000e00005c40000p1
408 # /dev/mapper/36001438005deb05d0000e00005c40000_part1
409 # /dev/sda1
410 # /dev/cciss/c0d0p1
411 get_partition_number() {
412 local partition_block_device=$1
413
414 # The partition number is the trailing digits of the partition block device:
415 local partition_number=$( echo "$partition_block_device" | grep -o -E '[0-9]+$' )
416
417 # Test if partition_number is a positive integer, if not it is likely a bug in ReaR.
418 # Because the above 'grep' outputs only trailing digits this BugError gets triggred
419 # when partition_block_device device does not contain trailing digits so that partition_number is empty
420 # which can happen when get_partition_number is called with a block device as argument
421 # that is not a partition block device (e.g. /dev/sda instead of /dev/sda1) which is likely a bug in ReaR:
422 test $partition_number -gt 0 || BugError "Partition number '$partition_number' of partition $partition_block_device is not a valid partition number."
423
424 # Test if partition_number is greater than 128 and report it as a bug in ReaR.
425 # FIXME: Why are more than 128 partitions not supported?
426 # Why is it a bug in ReaR when more than 128 partitions are not supported?
427 # A GPT must be for at least 128 partitions but why does ReaR not support bigger GPT?
428 # I <[email protected]> found https://github.com/rear/rear/commit/e758bba0a415173952cc588e5cf80570a6385f7e that links to
429 # https://github.com/rear/rear/issues/263 that contains https://github.com/rear/rear/issues/263#issuecomment-20464763
430 # which reads (excerpt): "The GPT standard allows maximum of 128 partitions per disk" which is not true
431 # according to how I understand the German https://de.wikipedia.org/wiki/GUID_Partition_Table that reads
432 # (excerpt, umlauts written as 'ae' and 'ue' to get ASCII see https://github.com/rear/rear/wiki/Coding-Style#character-encoding)
433 # "Die EFI-Spezifikationen schreiben ein Minimum von 16384 Bytes fuer die Partitionstabelle vor, so dass es Platz fuer 128 Eintraege gibt."
434 # in English "EFI specification mandate a minimum of 16384 bytes for the partition table so that there is space for 128 entries"
435 # which matches the English https://en.wikipedia.org/wiki/GUID_Partition_Table that reads (excerpt)
436 # "The UEFI specification stipulates that a minimum of 16384 bytes ... are allocated for the Partition Entry Array. Each entry has a size of 128 bytes."
437 # and because 16384 / 128 = 128 it results that 128 partition table entries (each of 128 bytes) are possible as a minimum
438 # which means that the GPT standard requires a minimum of 128 possible partitions per disk.
439 # So the current BugError here might be changed into only a user notification, for example something like
440 # LogPrintError "Partition $partition_block_device is numbered '$partition_number'. More than 128 partitions may not work (GPT must be extra large)."
441 # But on the other hand ReaR errors out relatively often at that place here in particular
442 # when weird partition related errors before had been ignored and it proceeded until it finally errors out here
443 # cf. "Try hard to care about possible errors" in https://github.com/rear/rear/wiki/Coding-Style
444 # so we keep the BugError for the time being as some kind of generic safeguard to catch bugs in ReaR elsewhere
445 # until we fully understand what is going on in our partitioning related code, cf. https://github.com/rear/rear/pull/2260
446 test $partition_number -le 128 || BugError "Partition $partition_block_device is numbered '$partition_number'. More than 128 partitions are not supported."
447
448 # Output the trailing digits of the partition block device as its partition number:
449 echo $partition_number
450 }
451
452 # Extract the underlying device name from the full partition device name.
453 # Underlying device may be a disk, a multipath device or other devices that can be partitioned.
454 # Should we use the information in $LAYOUT_DEPS, like get_parent_component does,
455 # instead of string munging?
456 function get_device_from_partition() {
457 local partition_block_device
458 local device
459 local partition_number
460
461 partition_block_device=$1
462 test -b "$partition_block_device" || BugError "get_device_from_partition called with '$partition_block_device' that is no block device"
463 partition_number=${2-$(get_partition_number $partition_block_device )}
464 # /dev/sda or /dev/mapper/vol34_part or /dev/mapper/mpath99p or /dev/mmcblk0p
465 device=${partition_block_device%$partition_number}
466
467 # Strip trailing partition remainders like '_part' or '-part' or 'p'
468 # if we have 'mapper' in disk device name:
469 if [[ ${partition_block_device/mapper//} != $partition_block_device ]] ; then
470 # we only expect mpath_partX or mpathpX or mpath-partX
471 case $device in
472 (*p) device=${device%p} ;;
473 (*-part) device=${device%-part} ;;
474 (*_part) device=${device%_part} ;;
475 (*) Log "Unsupported kpartx partition delimiter for $partition_block_device"
476 esac
477 fi
478
479 # For eMMC devices the trailing 'p' in the $device value
480 # (as in /dev/mmcblk0p that is derived from /dev/mmcblk0p1)
481 # needs to be stripped (to get /dev/mmcblk0), otherwise the
482 # efibootmgr call fails because of a wrong disk device name.
483 # See also https://github.com/rear/rear/issues/2103
484 if [[ $device = *'/mmcblk'+([0-9])p ]] ; then
485 device=${device%p}
486 fi
487
488 # For NVMe devices the trailing 'p' in the $device value
489 # (as in /dev/nvme0n1p that is derived from /dev/nvme0n1p1)
490 # needs to be stripped (to get /dev/nvme0n1), otherwise the
491 # efibootmgr call fails because of a wrong disk device name.
492 # See also https://github.com/rear/rear/issues/1564
493 if [[ $device = *'/nvme'+([0-9])n+([0-9])p ]] ; then
494 device=${device%p}
495 fi
496
497 test -b "$device" && echo $device
498 }
499
500 # Returns partition start block or 'unknown'
501 # sda/sda1 or
502 # dm-XX
503 get_partition_start() {
504 local disk_name=$1
505 local start_block start
506
507 # When reading /sys/block/.../start or "dmsetup table", output is always in
508 # 512 bytes blocks
509 local block_size=512
510
511 if [[ -r /sys/block/$disk_name/start ]] ; then
512 start_block=$(< $path/start)
513 elif [[ $disk_name =~ ^dm- ]]; then
514 # /dev/mapper/mpath4-part1
515 local devname=$(get_device_name $disk_name)
516 devname=${devname#/dev/mapper/}
517
518 # 0 536846303 linear 253:7 536895488
519 read junk junk junk junk start_block < <( dmsetup table ${devname} 2>/dev/null )
520 fi
521 if [[ -z $start_block ]]; then
522 Log "Could not determine start of partition $partition_name."
523 start="unknown"
524 else
525 start=$(( start_block * block_size ))
526 fi
527
528 echo $start
529 }
530
531 # Get the type of a layout component
532 get_component_type() {
533 grep -E "^[^ ]+ $1 " $LAYOUT_TODO | cut -d " " -f 3
534 }
535
536 # Get the disklabel (partition table) type of the disk $1 from the layout file
537 # (NOT from the actual disk, so layout file must exist before calling this,
538 # and it is useful during recovery even before the disk layout has been recreated)
539 function get_disklabel_type () {
540 # from create_disk() in layout/prepare/GNU/Linux/100_include_partition_code.sh
541 local component disk size label junk
542
543 disk=''
544
545 read component disk size label junk < <(grep -E "^(disk|multipath) $1 " "$LAYOUT_FILE")
546 test $disk || return 1
547
548 echo $label
549 }
550
551 # Get partition flags from layout (space-separated) of partition given as $1
552 function get_partition_flags () {
553 local part disk size pstart name flags partition junk
554
555 while read part disk size pstart name flags partition junk; do
556 if [ "$partition" == "$1" ] ; then
557 echo "$flags" | tr ',' ' '
558 return 0
559 fi
560 done < <(grep "^part " $LAYOUT_FILE)
561 }
562
563 # Function returns 0 when v1 is greater or equal than v2
564 version_newer() {
565 local v1list=( ${1//[-.]/ } )
566 local v2list=( ${2//[-.]/ } )
567
568 ### Take largest
569 local max=${#v1list[@]}
570 if (( $max < ${#v2list[@]} )); then
571 max=${#v2list[@]}
572 fi
573
574 local pos
575 for pos in $(seq 0 $(( max -1 ))); do
576 ### Arithmetic comparison
577 if (( 10#0${v1list[$pos]} >= 0 && 10#0${v2list[$pos]} >= 0 )) 2>/dev/null; then
578 # echo "pos $pos: arithm ${v1list[$pos]} vs ${v2list[$pos]}"
579 if (( 10#0${v1list[$pos]} < 10#0${v2list[$pos]} )); then
580 return 1
581 elif (( 10#0${v1list[$pos]} > 10#0${v2list[$pos]} )); then
582 return 0
583 fi
584 ### String comparison
585 else
586 # echo "pos $pos: string ${v1list[$pos]} vs ${v2list[$pos]}"
587 if [[ "${v1list[$pos]}" < "${v2list[$pos]}" ]]; then
588 return 1
589 elif [[ "${v1list[$pos]}" > "${v2list[$pos]}" ]]; then
590 return 0
591 fi
592 fi
593 done
594
595 return 0
596 }
597
598 # Function to get version from tool.
599 get_version() {
600 TERM=dumb "$@" 2>&1 | sed -rn 's/^[^0-9\.]*([0-9]+\.[-0-9a-z\.]+).*$/\1/p' | head -1
601 }
602
603 # Translate a device name to a sysfs name.
604 get_sysfs_name() {
605 local name=${1#/dev/}
606 name=${name#/sys/block/}
607
608 if [[ -e /sys/block/${name//\//!} ]] ; then
609 echo "${name//\//!}"
610 return 0
611 fi
612
613 ### Follow symlinks.
614 if [[ -h /dev/$name ]] ; then
615 local target=$(readlink -f /dev/$name)
616 if [[ -e /sys/block/${target#/dev/} ]] ; then
617 echo "${target#/dev/}"
618 return 0
619 fi
620 fi
621
622 # Accommodate for mapper/test -> dm-? mapping.
623 local dev_number=$(dmsetup info -c --noheadings -o major,minor ${name##*/} 2>/dev/null )
624 if [[ "$dev_number" ]] ; then
625 local dev_name sysfs_device
626 for sysfs_device in /sys/block/*/dev ; do
627 if [[ "$dev_number" = "$( < $sysfs_device)" ]] ; then
628 dev_name=${sysfs_device#/sys/block/}
629 echo "${dev_name%/*}"
630 return 0
631 fi
632 done
633 fi
634
635 # Otherwise, it can be the case that we just want to translate the name.
636 echo "${name//\//!}"
637 return 1
638 }
639
640 ### Translate a sysfs name or device name to the name preferred in
641 ### Relax-and-Recover.
642 ### The device does not necessarily exist.
643 ### cciss!c0d0 -> /dev/cciss/c0d0
644 ### /dev/dm-3 -> /dev/mapper/system-tmp
645 ### /dev/dm-4 -> /dev/mapper/oralun
646 ### /dev/dm-5 -> /dev/mapper/oralunp1
647 ### /dev/sda -> /dev/sda
648 ###
649 ### Returns 0 on success, 1 if device is not existing
650 get_device_name() {
651 ### strip common prefixes
652 local name=${1#/dev/}
653 name=${name#/sys/block/}
654
655 contains_visible_char "$name" || BugError "Empty string passed to get_device_name"
656
657 if [[ "$name" =~ ^mapper/ ]]; then
658 echo "/dev/$name"
659 return 0
660 fi
661
662 if [[ -L "/dev/$name" ]] ; then
663 # Map vg/lv into dm-X, which will then be resolved later
664 name="$( basename $(readlink -f /dev/$name) )"
665 fi
666
667 if [[ "$name" =~ ^dm- ]] ; then
668 local device
669 if [[ -r /sys/block/$name/dm/name ]] ; then
670 ### recent kernels have a dm subfolder
671 device="$( < /sys/block/$name/dm/name )"
672 else
673 local dev_number=$( < /sys/block/$name/dev)
674 if [[ ! -r "$TMP_DIR/dmsetup_info.txt" ]] ; then
675 dmsetup info --noheadings -c -o name,major,minor > "$TMP_DIR/dmsetup_info.txt"
676 fi
677 device="$( awk -F ':' "/$dev_number\$/ { print \$1 }" < "$TMP_DIR/dmsetup_info.txt" )"
678 [[ -n "$device" ]] || BugError "No device returned for major/minor $dev_number"
679 fi
680 echo "/dev/mapper/$device"
681 return 0
682 fi
683
684 ### handle cciss sysfs naming
685 name=${name//!//}
686
687 ### just return the possibly nonexisting name
688 echo "/dev/$name"
689 [[ -r "/dev/$name" ]] && return 0
690 return 1
691 }
692
693 # check $VAR_LIB/recovery/diskbyid_mappings file to see whether we find
694 # a disk/by-id mapping to dm style (the by-id dev is not translated
695 # properly by get_device_name function - dm dev are better)
696 # 220_lvm_layout.sh uses get_device_mapping to translate lvmdev better
697 ### ciss-3600508b1001fffffa004f7b3f209000b-part2 -> cciss/c0d0p2
698 # see issue #305
699 get_device_mapping() {
700 if [[ ! -s "${VAR_DIR}/recovery/diskbyid_mappings" ]]; then
701 echo $1
702 else
703 local name=${1##*/} # /dev/disk/by-id/scsi-xxxx -> scsi-xxx
704 local disk_name=$(grep -w "^${name}" ${VAR_DIR}/recovery/diskbyid_mappings | awk '{print $2}')
705 if [[ -z "$disk_name" ]]; then
706 echo $1
707 else
708 echo "$disk_name"
709 fi
710 fi
711 }
712
713 # Get the size in bytes of a disk/partition.
714 # For disks, use "sda" as argument.
715 # For partitions, use "sda/sda1" as argument.
716 get_disk_size() {
717 local disk_name=$1
718 # When a partition is specified (e.g. sda/sda1)
719 # then it has to read /sys/block/sda/sda1/size in the old code below.
720 # In contrast the get_block_size() function below is different
721 # because it is non-sense asking for block size of a partition,
722 # so that the get_block_size() function below is stripping everything
723 # in front of the blockdev basename (e.g. /some/path/sda -> sda)
724 # cf. https://github.com/rear/rear/pull/1885#discussion_r207900308
725
726 # Preferably use blockdev, see https://github.com/rear/rear/issues/1884
727 if has_binary blockdev; then
728 # ${disk_name##*/} translates 'sda/sda1' into 'sda1' and 'sda' into 'sda'
729 blockdev --getsize64 /dev/${disk_name##*/} && return
730 # If blockdev fails do not error out but fall through to the old code below
731 # because blockdev fails e.g. for a CDROM device when no DVD or ISO is attached to
732 # cf. https://github.com/rear/rear/pull/1885#issuecomment-410676283
733 # and https://github.com/rear/rear/pull/1885#issuecomment-410697398
734 fi
735
736 # Linux always considers sectors to be 512 bytes long. See the note in the
737 # kernel source, specifically, include/linux/types.h regarding the sector_t
738 # type for details.
739 local block_size=512
740
741 retry_command test -r /sys/block/$disk_name/size || Error "Could not determine size of disk $disk_name"
742
743 local nr_blocks=$( < /sys/block/$disk_name/size)
744 local disk_size=$(( nr_blocks * block_size ))
745
746 ### Make sure we always return a number
747 echo $(( disk_size ))
748 }
749
750 # Get the block size of a disk.
751 get_block_size() {
752 local disk_name="${1##*/}" # /some/path/sda -> sda
753
754 # Preferably use blockdev, see https://github.com/rear/rear/issues/1884
755 if has_binary blockdev; then
756 blockdev --getss /dev/$disk_name && return
757 # If blockdev fails do not error out but fall through to the old code below
758 # because blockdev fails e.g. for a CDROM device when no DVD or ISO is attached to
759 # cf. https://github.com/rear/rear/pull/1885#issuecomment-410676283
760 # and https://github.com/rear/rear/pull/1885#issuecomment-410697398
761 fi
762
763 # Only newer kernels have an interface to get the block size
764 if [ -r /sys/block/$disk_name/queue/logical_block_size ] ; then
765 echo $( < /sys/block/$disk_name/queue/logical_block_size)
766 else
767 echo "512"
768 fi
769 }
770
771 # Get the number of cylinders of a DASD.
772 # The number of cylinders has the advantage of being fixed - size depends on formatting
773 # and number of cylinders is valid even for unformatted DASDs, size is not.
774 get_dasd_cylinders() {
775 local disk_name="${1##*/}" # /some/path/dasda -> dasda
776 local dasd_cyls
777
778 dasd_cyls=$(dasdview -i /dev/$disk_name | grep cylinders | cut -d ':' -f2 | awk '{print $4}')
779 ### Make sure we always return a number
780 echo $(( dasd_cyls ))
781 }
782
783 # Sometimes we know what the new device for the original device should be in a more reliable way
784 # than by looking at disk sizes. THis information is called "mapping hints". Let's pass them
785 # to the mapping code using the DISK_MAPPING_HINTS array. Each element of the array has the form
786 # "/dev/source /dev/target" (space-separated).
787
788 # Output the mapping hint for the original device.
789 function get_mapping_hint () {
790 local device="$1"
791 local hint mapping_hint_source mapping_hint_target
792
793 for hint in "${DISK_MAPPING_HINTS[@]}"; do
794 mapping_hint_source=${hint%% *}
795 mapping_hint_target=${hint##* }
796 if [ "${device}" == "${mapping_hint_source}" ] ; then
797 echo "$mapping_hint_target"
798 return 0
799 fi
800 done
801 return 1
802 }
803
804 # Determine if there is a mapping hint for the original device.
805 function has_mapping_hint () {
806 local device="$1"
807
808 get_mapping_hint "$device" > /dev/null
809 }
810
811 # Get the UUID of a device.
812 # Device is something like /dev/sda1.
813 blkid_uuid_of_device() {
814 local device=$1
815 local uuid=""
816 for LINE in $(blkid $device 2>/dev/null)
817 do
818 uuid=$( echo "$LINE" | grep "^UUID=" | cut -d= -f2 | sed -e 's/"//g')
819 [[ ! -z "$uuid" ]] && break
820 done
821 echo "$uuid"
822 }
823
824 # Get the LABEL of a device.
825 # Device is something like /dev/sda1.
826 blkid_label_of_device() {
827 local device=$1
828 local label=""
829 for LINE in $(blkid $device 2>/dev/null)
830 do
831 label=$( echo "$LINE" | grep "^LABEL=" | cut -d= -f2 | sed -e 's/"//g' | sed -e 's/ /\\\\b/g') # replace all " " with "\\b"
832 [[ ! -z "$label" ]] && break
833 done
834 echo "$label"
835 }
836
837 # Returns true if the device is an LVM physical volume
838 # Returns false otherwise or if the device doesn't exist
839 is_disk_a_pv() {
840 disk=$1
841
842 # Using awk, select the 'lvmdev' line for which $disk is the device (column 3),
843 # cf. https://github.com/rear/rear/pull/1897
844 # If exit == 1, then there is such line (so $disk is a PV),
845 # otherwise exit with default value '0', which falls through to 'return 1' below.
846 awk "\$1 == \"lvmdev\" && \$3 == \"${disk}\" { exit 1 }" "$LAYOUT_FILE" >/dev/null || return 0
847 return 1
848 }
849
850 # Check whether disk is suitable for being added to layout
851 # Can be used to skip obviously unsuitable/broken devices
852 # (missing device node, zero size, device can't be opened).
853 # Should not be used to skip potential mapping targets before layout restoration
854 # - an invalid disk may become valid later, for example if it is a DASD that needs
855 # low-level formatting (see 090_include_dasd_code.sh and 360_generate_dasd_format_code.sh),
856 # unformatted DASDs show zero size.
857 # Returns 0 if the device is ok
858 # Returns nonzero code if it should be skipped, and a text describing the error
859 # on stdout
860 # usage example:
861 # local err
862 # if ! err=$(is_disk_valid /dev/sda); then
863
864 function is_disk_valid {
865 local disk="$1"
866 local size
867
868 if ! test -b "$disk" ; then
869 echo "$disk is not a block device"
870 return 1
871 fi
872 # capture stdout in a variable and redirect stderr to stdout - the error message
873 # will be our output
874 if { size=$(blockdev --getsize64 "$disk") ; } 2>&1 ; then
875 if ! test "$size" -gt 0 2>/dev/null ; then
876 echo "$disk has invalid size $size"
877 return 1
878 fi
879 return 0
880 else
881 return 1
882 fi
883 }
884
885 function is_multipath_used {
886 # Return 'false' if there is no multipath command:
887 type multipath &>/dev/null || return 1
888 # 'multipath -l' is the only simple and reliably working command
889 # to find out in general whether or not multipath is used at all.
890 # But 'multipath -l' scans all devices and the time it takes is proportional
891 # to their number so that time would become rather long (seconds up to minutes)
892 # if 'multipath -l' was called for each one of hundreds or thousands of devices.
893 # So we call 'multipath -l' only once and remember the result
894 # in a global variable and then only use that global variable
895 # so we can call is_multipath_used very many times as often as needed.
896 is_true $MULTIPATH_IS_USED && return 0
897 is_false $MULTIPATH_IS_USED && return 1
898 # When MULTIPATH_IS_USED has neither a true nor false value set it and return accordingly.
899 # Because "multipath -l" always returns zero exit code we check if it has real output via grep -q '[[:alnum:]]'
900 # so that no "multipath -l" output could clutter the log (the "multipath -l" output is irrelevant here)
901 # in contrast to e.g. test "$( multipath -l )" that would falsely succeed with blank output
902 # and the output would appear in the log in 'set -x' debugscript mode:
903 if multipath -l | grep -q '[[:alnum:]]' ; then
904 MULTIPATH_IS_USED='yes'
905 return 0
906 else
907 MULTIPATH_IS_USED='no'
908 return 1
909 fi
910 }
911
912 function is_multipath_path {
913 # Return 'false' if there is no device as argument:
914 test "$1" || return 1
915 # Return 'false' if multipath is not used, see https://github.com/rear/rear/issues/2298
916 is_multipath_used || return 1
917 # Check if a block device should be a path in a multipath device:
918 multipath -c /dev/$1 &>/dev/null
919 }
920
921 # retry_command () is binded with REAR_SLEEP_DELAY and REAR_MAX_RETRIES.
922 # This function will do maximum of REAR_MAX_RETRIES command execution
923 # and will sleep REAR_SLEEP_DELAY after each unsuccessful command execution.
924 # It outputs command stdout if succeeded or returns 1 on failure.
925 retry_command ()
926 {
927 local retry=0
928
929 until command_stdout=$(eval "$@"); do
930 sleep $REAR_SLEEP_DELAY
931
932 let retry++
933
934 if (( retry >= REAR_MAX_RETRIES )) ; then
935 Log "retry_command '$*' failed"
936 return 1
937 fi
938 done
939 # Have no additional trailing newline for the command stdout:
940 echo -n "$command_stdout"
941 }
942
943 # UdevSymlinkName (device) return all the udev symlink created by udev to the device.
944 # example:
945 # UdevSymlinkName /dev/sda1
946 # /dev/disk/by-id/ata-SAMSUNG_MZNLN512HMJP-000L7_S2XANX0H603095-part1 /dev/disk/by-id/wwn-0x5002538d00000000-part1 /dev/disk/by-label/boot /dev/disk/by-partuuid/7d51513d-01 /dev/disk/by-path/pci-0000:00:17.0-ata-1-part1 /dev/disk/by-uuid/b3c0fd92-28cf-4591-b4f5-1a32913f4319
947 function UdevSymlinkName() {
948 unset device
949 device="$1"
950
951 # Exit with Error if no argument is provided to UdevSymlinkName
952 contains_visible_char "$device" || Error "Empty string passed to UdevSymlinkName()"
953
954 # udevinfo is deprecated by udevadm (SLES 10 still uses udevinfo)
955 type -p udevinfo >/dev/null && UdevSymlinkName="udevinfo -r / -q symlink -n"
956 type -p udevadm >/dev/null && UdevSymlinkName="udevadm info --root --query=symlink --name"
957
958 if test -z "$UdevSymlinkName" ; then
959 LogPrint "Could not find udevinfo nor udevadm. UdevSymlinkName($device) failed."
960 return 1
961 fi
962
963 $UdevSymlinkName $device
964 }
965
966 # UdevQueryName (device) return all the real device name from udev symlink.
967 # example:
968 # UdevQueryName /dev/disk/by-id/wwn-0x5002538d00000000-part1
969 # sda1
970 # WARNING: like udevadm, this function return device name (sda1) not absolute PATH (/dev/sda1)
971 function UdevQueryName() {
972 unset device_link
973 device_link="$1"
974
975 # Exit with Error if no argument is provided to UdevSymlinkName
976 contains_visible_char "$device_link" || Error "Empty string passed to UdevQueryName()"
977
978 # be careful udevinfo is old, now we have udevadm
979 # udevinfo -r -q name -n /dev/disk/by-id/scsi-360060e8015268c000001268c000065c0-part4
980 # udevadm info --query=name --name /dev/disk/by-id/dm-name-vg_fedora-lv_root
981 type -p udevinfo >/dev/null && UdevQueryName="udevinfo -r -q name -n"
982 type -p udevadm >/dev/null && UdevQueryName="udevadm info --query=name --name"
983
984 if test -z "$UdevQueryName" ; then
985 LogPrint "Could not find udevinfo nor udevadm. UdevQueryName($device_link) failed."
986 return 1
987 fi
988
989 $UdevQueryName $device_link
990 }
991
992 # Guess the part device name from a device, based on the OS distro Level.
993 # See https://github.com/rear/rear/commit/14c062627e15d3be799b1a8bd220634a0aa032b9
994 # which belongs to https://github.com/rear/rear/pull/1450
995 function get_part_device_name_format() {
996 if [ -z "$1" ] ; then
997 BugError "get_part_device_name_format function called without argument (device)"
998 else
999 device_name="$1"
1000 fi
1001
1002 part_name="$device_name"
1003
1004 case "$device_name" in
1005 (*mmcblk[0-9]*|*nvme[0-9]*n[1-9]*|*rd[/!]c[0-9]*d[0-9]*|*cciss[/!]c[0-9]*d[0-9]*|*ida[/!]c[0-9]*d[0-9]*|*amiraid[/!]ar[0-9]*|*emd[/!][0-9]*|*ataraid[/!]d[0-9]*|*carmel[/!][0-9]*)
1006 part_name="${device_name}p" # append p between main device and partitions
1007 ;;
1008 (*mapper[/!]*)
1009 # Every Linux distribution / version has their own rule to name the multipthed partition device.
1010 #
1011 # Suse:
1012 # Version <12 : always <device>_part<part_num> (same with/without user_friendly_names)
1013 # Version >=12 : always <device>-part<part_num> (same with/without user_friendly_names)
1014 # Question still open for sles10 ...
1015 # RedHat:
1016 # Version <7 : always <device>p<part_num> (same with/without user_friendly_names)
1017 # Version >=7 : if user_friendly_names (default) <device><part_num> else <device>p<part_num>
1018 # Debian:
1019 # if user_firendly_names (default) <device>-part<part_num>
1020 # if NOT user_firendly_names <device>p<part_num>
1021 #
1022
1023 # First we need to know if user_friendly_names is activated (for Fedora/RedHat and Debian/ubuntu)
1024 if multipathd ; then
1025 # check if multipath if using the "user_friendly_names" by default in the current configuration.
1026 user_friendly_names=$(echo "show config" | multipathd -k | awk '/user_friendly_names/ { gsub("\"","") ; print $2 }' | head -n 1 )
1027 fi
1028
1029 case $OS_MASTER_VENDOR in
1030
1031 (SUSE)
1032 # No need to check if user_friendly_names is activated or not as Suse always apply the same naming convention.
1033
1034 # SUSE Linux SLE12 put a "-part" between [mpath device name] and [part number].
1035 # For example /dev/mapper/3600507680c82004cf8000000000000d8-part1.
1036 # But SLES11 uses a "_part" instead. (Let's assume it is the same for SLES10 )
1037 if (( $OS_MASTER_VERSION < 12 )) ; then
1038 # For SUSE before version 12
1039 part_name="${device_name}_part" # append _part between main device and partitions
1040 else
1041 # For SUSE 12 or above
1042 part_name="${device_name}-part" # append -part between main device and partitions
1043 fi
1044 ;;
1045
1046 (Fedora)
1047 # RHEL 7 and above add a "p" after the device name when the device name ends
1048 # by a digit, see https://access.redhat.com/solutions/2354631.
1049 if (( $OS_MASTER_VERSION < 7 )) || [[ ${device_name: -1} =~ [0-9] ]]; then
1050 part_name="${device_name}p"
1051 fi
1052 ;;
1053
1054 (Debian)
1055 if is_false "$user_friendly_names" ; then
1056 # Exceptional case for Debian/ubuntu
1057 # When user_friendly_names is disable, debian based system will name partition
1058 # [mpath device UUID/WWID] + p + [part number]
1059 part_name="${device_name}p"
1060 else
1061 # Default case (user_friendly_name enable)
1062 # Ubuntu 16.04 (need to check for other version) named muiltipathed partitions with
1063 # [mpath device name] + "-part" + [part number]
1064 # for example : /dev/mapper/mpatha-part1
1065 part_name="${device_name}-part" # append -part between main device and partitions
1066 fi
1067 ;;
1068
1069 (*)
1070 # For all the other case, use /dev/mapper/mpatha1 type
1071 part_name="$device_name"
1072 ;;
1073 esac
1074 ;;
1075 esac
1076
1077 echo "$part_name"
1078 }
1079
1080 # The is_completely_identical_layout_mapping function checks
1081 # if there is a completely identical mapping in the mapping file
1082 # (usually $MAPPING_FILE is /var/lib/rear/layout/disk_mappings)
1083 # which is used to avoid that files (in particular restored files)
1084 # may get needlessly touched and modified for identical mappings
1085 # see https://github.com/rear/rear/issues/1847
1086 function is_completely_identical_layout_mapping() {
1087 # MAPPING_FILE is set in layout/prepare/default/300_map_disks.sh
1088 # only if MIGRATION_MODE is true.
1089 # When $MAPPING_FILE is empty the below command
1090 # grep -v '^#' "$MAPPING_FILE"
1091 # would hang up endlessly without user notification
1092 # because that command would become
1093 # grep -v '^#'
1094 # which reads from stdin (i.e. from the user's keyboard).
1095 # A non-existent mapping file is considered to be a completely identical mapping
1096 # (i.e. 'no mapping' means 'do not change anything' which is the identity map).
1097 test -f "$MAPPING_FILE" || return 0
1098 # Only non-commented and syntactically valid lines in the mapping file count
1099 # so that also an empty mapping file or when there is not at least one valid mapping
1100 # are considered to be completely identical mappings
1101 # (i.e. 'no valid mapping' means 'do not change anything' which is the identity map):
1102 while read source target junk ; do
1103 # Skip lines that have wrong syntax:
1104 test "$source" -a "$target" || continue
1105 test "$source" != "$target" && return 1
1106 done < <( grep -v '^#' "$MAPPING_FILE" )
1107 Log "Completely identical layout mapping in $MAPPING_FILE"
1108 return 0
1109 }
1110
1111 # apply_layout_mappings function migrate disk device references
1112 # from an old system and replace them with new ones (from current system).
1113 # The relationship between OLD and NEW device is provided by the mapping file
1114 # (usually $MAPPING_FILE is /var/lib/rear/layout/disk_mappings).
1115 function apply_layout_mappings() {
1116 local file_to_migrate="$1"
1117
1118 # Exit if MIGRATION_MODE is not true.
1119 is_true "$MIGRATION_MODE" || return 0
1120
1121 # apply_layout_mappings needs one argument:
1122 test "$file_to_migrate" || BugError "apply_layout_mappings function called without argument (file_to_migrate)."
1123
1124 # Only apply layout mapping on non-empty file:
1125 test -s "$file_to_migrate" || return 0
1126
1127 # Do not apply layout mappings when there is a completely identical mapping in the mapping file.
1128 # This test is run for each call of the apply_layout_mappings function because
1129 # in MIGRATION_MODE there are several user dialogs during "rear recover" where
1130 # the user can run the ReaR shell and edit the mapping file as he likes:
1131 is_completely_identical_layout_mapping && return 0
1132
1133 # Generate unique words (where unique means that those generated words cannot already exist in file_to_migrate)
1134 # as replacement placeholders to correctly handle circular replacements e.g. for "sda -> sdb and sdb -> sda"
1135 # in the mapping file those generated unique words would be _REAR0_ for sda and _REAR1_ for sdb.
1136 # The replacement strategy is:
1137 # Step 0:
1138 # For each original device in the mapping file generate a unique word (the "replacement").
1139 # Step 1:
1140 # In file_to_migrate replace (temporarily) all original devices with their matching unique word.
1141 # E.g. "disk sda and disk sdb" would become "disk _REAR0_ and disk _REAR1_" temporarily in file_to_migrate.
1142 # Step 2:
1143 # In file_to_migrate re-replace all unique replacement words with the matching target device of the source device.
1144 # E.g. for "sda -> sdb and sdb -> sda" in the mapping file and the unique words _REAR0_ for sda and _REAR1_ for sdb
1145 # "disk _REAR0_ and disk _REAR1_" would become "disk sdb and disk sda" in the final file_to_migrate
1146 # so that the circular replacement "sda -> sdb and sdb -> sda" is done in file_to_migrate.
1147 # Step 3:
1148 # In file_to_migrate verify that there are none of those temporary replacement words from step 1 left
1149 # to ensure the replacement was done correctly and completely.
1150
1151 # Replacement_file initialization.
1152 replacement_file="$TMP_DIR/replacement_file"
1153 : > "$replacement_file"
1154
1155 function add_replacement() {
1156 # We temporarily map all devices in the mapping to new names _REAR[0-9]+_
1157 echo "$1 _REAR${replacement_count}_" >> "$replacement_file"
1158 let replacement_count++
1159 }
1160
1161 function has_replacement() {
1162 grep -q "^$1 " "$replacement_file"
1163 }
1164
1165 function get_replacement() {
1166 local item replacement junk
1167 read item replacement junk < <( grep "^$1 " $replacement_file )
1168 test "$replacement" && echo "$replacement" || return 1
1169 }
1170
1171 # Step 0:
1172 # For each original device in the mapping file generate a unique word (the "replacement").
1173 # E.g. when the mapping file content is
1174 # /dev/sda /dev/sdb
1175 # /dev/sdb /dev/sda
1176 # /dev/sdd /dev/sdc
1177 # the replacement file will contain
1178 # /dev/sda _REAR0_
1179 # /dev/sdb _REAR1_
1180 # /dev/sdd _REAR2_
1181 # /dev/sdc _REAR3_
1182 replacement_count=0
1183 while read source target junk ; do
1184 # Skip lines that have wrong syntax:
1185 test "$source" -a "$target" || continue
1186 has_replacement "$source" || add_replacement "$source"
1187 has_replacement "$target" || add_replacement "$target"
1188 done < <( grep -v '^#' "$MAPPING_FILE" )
1189
1190 # Step 1:
1191 # Replace all original devices with their replacements.
1192 # E.g. when the file_to_migrate content is
1193 # disk /dev/sda
1194 # disk /dev/sdb
1195 # disk /dev/sdc
1196 # disk /dev/sdd
1197 # it will get temporarily replaced (with the replacement file content in step 0 above) by
1198 # disk _REAR0_
1199 # disk _REAR1_
1200 # disk _REAR3_
1201 # disk _REAR2_
1202 while read original replacement junk ; do
1203 # Skip lines that have wrong syntax:
1204 test "$original" -a "$replacement" || continue
1205 # Replace partitions with unique replacement words:
1206 # For example we normalize /dev/cciss/c0d1p2 to something like _REAR5_2
1207 # (therein the '5' is arbitrary but the '2' is the actual partition number).
1208 # Due to multipath partition naming complexity, all known partition naming types for example
1209 # /dev/mapper/mpatha4 /dev/mapper/mpathap4 /dev/mapper/mpatha-part4 /dev/mapper/mpatha_part4
1210 # are replaced by the same normalized replacement word like _REAR7_4
1211 # (therein the '7' is arbitrary but the '4' is the actual partition number)
1212 # that is then in step 2 re-replaced with the right partition naming scheme
1213 # via the get_part_device_name_format() function,
1214 # cf. https://github.com/rear/rear/pull/1765
1215 # Because $original (e.g. /dev/sda1) contains slashes sed '/regexp/' cannot be used
1216 # so sed '\|regexp|' is used (under the assumption that no | characters are in $original):
1217 sed -i -r "\|$original|s|$original(p)*([-_]part)*([0-9]+)|$replacement\3|g" "$file_to_migrate"
1218 # Replace whole devices with unique replacement words:
1219 # Note that / is a word boundary, so is matched by \<, hence the extra /
1220 sed -i -r "\|$original|s|/\<${original#/}\>|${replacement}|g" "$file_to_migrate"
1221 done < "$replacement_file"
1222
1223 # Step 2:
1224 # Re-replace all unique replacement words with the matching target device of the source device in the mapping file.
1225 # E.g. when the file_to_migrate content was in step 1 above temporarily changed to
1226 # disk _REAR0_
1227 # disk _REAR1_
1228 # disk _REAR3_
1229 # disk _REAR2_
1230 # it will now get finally re-replaced (with the replacement file and mapping file contents in step 0 above) by
1231 # disk /dev/sdb
1232 # disk /dev/sda
1233 # disk _REAR3_
1234 # disk /dev/sdc
1235 # where the temporary replacement "disk _REAR3_" from step 1 above is left because
1236 # there is (erroneously) no mapping for /dev/sdc (as source device) in the mapping file (in step 0 above).
1237 while read source target junk ; do
1238 # Skip lines that have wrong syntax:
1239 test "$source" -a "$target" || continue
1240 # Skip when there is no replacement:
1241 replacement=$( get_replacement "$source" ) || continue
1242 # Re-replace whole devices:
1243 # Use the same sed '\|regexp|s...' syntax as in step 1 above also here to be on the safe side
1244 # (there are no slashes in $replacement like '_REAR0_' but $target like '/dev/sda' contains slashes):
1245 sed -i -r "\|$replacement|s|$replacement\>|$target|g" "$file_to_migrate"
1246 # Re-replace partitions:
1247 target=$( get_part_device_name_format "$target" )
1248 sed -i -r "\|$replacement|s|$replacement([0-9]+)|$target\1|g" "$file_to_migrate"
1249 done < <( grep -v '^#' "$MAPPING_FILE" )
1250
1251 # Step 3:
1252 # Verify that there are none of those temporary replacement words from step 1 left in file_to_migrate
1253 # to ensure the replacement was done correctly and completely (cf. the above example where '_REAR3_' is left).
1254 apply_layout_mappings_succeeded="yes"
1255 while read original replacement junk ; do
1256 # Skip lines that have wrong syntax:
1257 test "$original" -a "$replacement" || continue
1258 # Only treat leftover temporary replacement words as an error
1259 # if they are in a non-comment line (comments have '#' as first non-space character)
1260 # cf. https://github.com/rear/rear/issues/2183
1261 if grep -v '^[[:space:]]*#' "$file_to_migrate" | grep -q "$replacement" ; then
1262 apply_layout_mappings_succeeded="no"
1263 LogPrintError "Failed to apply layout mappings to $file_to_migrate for $original (probably no mapping for $original in $MAPPING_FILE)"
1264 fi
1265 done < "$replacement_file"
1266 # It is the responsibility of the caller of this apply_layout_mappings function what to do when it failed
1267 # (e.g. error out, retry, show a user dialog, or whatever is appropriate in the caller's environment):
1268 is_true $apply_layout_mappings_succeeded && return 0 || return 1
1269 }
1270
1271 has_binary parted || Error "Cannot find 'parted' command"
1272
1273 FEATURE_PARTED_RESIZEPART=y
1274 FEATURE_PARTED_RESIZE=n
1275
1276 if parted --help | awk '$1 == "resizepart" { exit 1 }' ; then
1277 # No 'resizepart', check for 'resize'
1278 FEATURE_PARTED_RESIZEPART=n
1279 if ! parted --help | awk '$1 == "resize" { exit 1 }' ; then
1280 FEATURE_PARTED_RESIZE=y
1281 if ! parted --help | awk '$1 == "resize" && $3 == "START" { exit 1 }' ; then
1282 # 'parted resize NUM START END' tries resizing the file system,
1283 # which is known to fail, as shown below (output from parted):
1284 #
1285 # # parted -s -m /dev/sdc resize 3 1074790400B 2149580799B
1286 # WARNING: you are attempting to use parted to operate on (resize) a file system.
1287 # parted's file system manipulation code is not as robust as what you'll find in
1288 # dedicated, file-system-specific packages like e2fsprogs. We recommend
1289 # you use parted only to manipulate partition tables, whenever possible.
1290 # Support for performing most operations on most types of file systems
1291 # will be removed in an upcoming release.
1292 # No Implementation: Support for opening ext4 file systems is not implemented yet.
1293 FEATURE_PARTED_RESIZE=n
1294 fi
1295 fi
1296 fi
1297
1298 # Keeps track of the current disk being processed
1299 # e.g. /dev/sdb
1300 current_disk=""
1301
1302 # Keeps track of last partition created for the current disk
1303 # e.g. last_partition_number=1
1304 last_partition_number=0
1305
1306 # Keeps track of dummy partitions created and to be removed (due to parted limitation) for the current disk
1307 # Contains a list of partition numbers
1308 # e.g. dummy_partitions_to_delete=( 1 2 4 5 )
1309 dummy_partitions_to_delete=()
1310
1311 # Keeps track of partitions to resize to original size for the current disk
1312 # Contains a list of partition tuples (number, end_in_bytes)
1313 # e.g. partitions_to_resize=( 3 2096127 6 8388607 )
1314 partitions_to_resize=()
1315
1316 # Keeps track of the label for the current disk
1317 # e.g. disk_label="gpt"
1318 disk_label=""
1319
1320 #
1321 # create_disk_label(disk, label)
1322 #
1323 # Sets up the disk label. Must be called before calling create_disk_partition().
1324 #
1325 create_disk_label() {
1326 local disk="$1" label="$2"
1327
1328 if [[ "$current_disk" ]] && [[ "$current_disk" != "$disk" ]] ; then
1329 BugError "Current disk has changed from '$current_disk' to '$disk' without calling delete_dummy_partitions_and_resize_real_ones() first."
1330 fi
1331 current_disk="$disk"
1332
1333 if [[ "$disk_label" ]] && [[ "$disk_label" != "$label" ]] ; then
1334 BugError "Disk '$disk': disk label is being assigned multiple times for the same disk."
1335 fi
1336 disk_label="$label"
1337
1338 LogPrint "Disk '$disk': creating '$label' partition table"
1339 parted -s $disk mklabel $label
1340 my_udevsettle
1341 }
1342
1343 #
1344 # create_disk_partition(disk, name, partnumber, partstart, [partend])
1345 #
1346 # Creates a partition. When changing disk, user must call delete_dummy_partitions_and_resize_real_ones().
1347 #
1348 create_disk_partition() {
1349 local disk="$1" name="$2" number=$3 startB=$4 endB=$5
1350
1351 #
1352 # FIXME? This code assumes that "parted" is capable of handling sizes in
1353 # Bytes. parted supports partitions in Bytes since ages.
1354 #
1355
1356 if [[ "$current_disk" ]] && [[ "$current_disk" != "$disk" ]] ; then
1357 BugError "Current disk has changed from '$current_disk' to '$disk' without calling delete_dummy_partitions_and_resize_real_ones() first."
1358 fi
1359 current_disk="$disk"
1360
1361 if [[ ! "$disk_label" ]] ; then
1362 BugError "Disk '$disk': disk label is unknown."
1363 fi
1364
1365 # The duplicated quoting "'$name'" is there because
1366 # parted's internal parser needs single quotes for values with blanks.
1367 # In particular a GPT partition name that can contain spaces
1368 # like 'EFI System Partition' cf. https://github.com/rear/rear/issues/1563
1369 # so that when calling parted on command line it must be done like
1370 # parted -s /dev/sdb unit MiB mkpart "'partition name'" 12 34
1371 # where the outer quoting "..." is for bash so that
1372 # the inner quoting '...' is preserved for parted's internal parser:
1373 [ "$disk_label" == "msdos" ] || name="'$name'"
1374
1375 if [[ $number -le last_partition_number ]] ; then
1376 Error "Disk '$disk': trying to create partition number $number but last created partition was number $last_partition_number"
1377 fi
1378
1379 if [[ $(( $number - $last_partition_number - 1 )) -eq 0 ]] ; then
1380 LogPrint "Disk '$disk': creating partition number $number with name '$name'"
1381 # FIXME: I <[email protected]> think one cannot silently set the end of a partition to 100%
1382 # if there is no partition end value, I think in this case "rear recover" should error out:
1383 if [[ ! $endB ]] ; then
1384 parted -s $disk mkpart "$name" "${startB}B" 100%
1385 else
1386 parted -s $disk mkpart "$name" "${startB}B" "${endB}B"
1387 fi
1388 my_udevsettle
1389 last_partition_number=$number
1390 return 0
1391 fi
1392
1393 if is_false $FEATURE_PARTED_RESIZEPART && is_false $FEATURE_PARTED_RESIZE ; then
1394 Error "Disk '$disk': trying to create partition number $number which isn't consecutive with previous partition but 'parted' doesn't support this feature"
1395 fi
1396
1397 # "parted" is only capable of creating partitions consecutively. Since
1398 # there is a gap between the previous partition and this partition, dummy
1399 # partitions must be created, and later will be removed once disks are
1400 # fully partitioned (this is done in
1401 # delete_dummy_partitions_and_resize_real_ones()).
1402 #
1403 # Once the dummy partitions are removed, the real partition needs to be
1404 # resized to original size.
1405 # Unfortunately, "parted" is only capable of resizing a partition toward
1406 # its end, not the beginning, so the only way to create dummy partitions
1407 # appropriately is to use some space at the end of the real partition.
1408 #
1409 # Example: the GPT disk contains only 1 partition numbered 3 named PART
1410 #
1411 # # parted -m -s /dev/sda unit B print
1412 # /dev/sda:21474836480B:scsi:512:512:gpt:QEMU QEMU HARDDISK:;
1413 # 3:1048576B:2097151B:1048576B::PART:;
1414 #
1415 # We need to create these partitions to recreate the exact same partitions:
1416 #
1417 # # parted -m -s /dev/sda unit B print
1418 # /dev/sda:21474836480B:scsi:512:512:gpt:QEMU QEMU HARDDISK:;
1419 # 3:1048576B:2096127B:1047552B::PART:;
1420 # 2:2096128B:2096639B:512B::dummy2:;
1421 # 1:2096640B:2097151B:512B::dummy1:;
1422 #
1423 # Then delete dummy partition 1 and 2 and resize 3 to its original end.
1424 #
1425 # For 'msdos' disks, only non-logical partitions are affected.
1426
1427 if [[ ! $endB ]] ; then
1428 # We need to compute '$endB' based on disk size. To do so, create a
1429 # partition then get its end
1430 LogPrint "Disk '$disk': creating a temporary partition to find out the end of the disk"
1431 parted -s -m $disk mkpart "$name" ${startB}B 100%
1432 local num
1433 read num endB <<< $( parted -s -m $disk unit B print | tail -1 | awk -F ':' '{ print $1, $3 }' | sed 's/\([0-9]*\)B$/\1/' )
1434 LogPrint "Disk '$disk': last allocatable byte on disk is '$endB'"
1435 LogPrint "Disk '$disk': deleting the temporary partition number $num"
1436 parted -s -m $disk rm $num
1437 fi
1438
1439 partitions_to_resize+=( $number $endB )
1440
1441 local -i logical_sector_size=$( parted -m -s $disk unit B print | awk -F ':' "\$1 == \"$disk\" { print \$4 }" )
1442
1443 if [[ "$disk_label" != "msdos" ]] || [[ "$name" != "logical" ]] ; then
1444 local -i i=$last_partition_number+1
1445 while [[ $i -lt $number ]] ; do
1446 local partname="dummy$i"
1447 [[ "$disk_label" != "msdos" ]] || partname="primary"
1448 dummy_partitions_to_delete+=( $i )
1449 LogPrint "Disk '$disk': creating dummy partition number $i with name '$partname' (will be deleted later)"
1450 parted -s -m $disk mkpart "$partname" "${endB}B" "${endB}B"
1451 my_udevsettle
1452 let endB-=$logical_sector_size
1453 if [[ $endB -lt $startB ]] ; then
1454 # Not enough space left for real partition: this happens if the
1455 # partition to create is very small and we cannot create dummy
1456 # temporary partitions!
1457 # e.g. Partition table starts at partition number 2 and partition 2
1458 # has only 1 cylinder
1459 Error "Disk '$disk': Cannot create partition number $number, the partition is too small to create dummy partitions to work around parted's limitation (parted can only create consecutive partitions)"
1460 fi
1461 let i++
1462 done
1463 fi
1464
1465 LogPrint "Disk '$disk': creating partition number $number with name '$name'"
1466 parted -s $disk mkpart "$name" "${startB}B" "${endB}B"
1467 my_udevsettle
1468
1469 last_partition_number=$number
1470 }
1471
1472 #
1473 # delete_dummy_partitions_and_resize_real_ones()
1474 #
1475 # When current disk has non-consecutive partitions, delete temporary partitions
1476 # that have been created and resize the temporary shrunk partitions to their
1477 # expected size.
1478 #
1479 delete_dummy_partitions_and_resize_real_ones() {
1480 # If parted doesn't support resizing, this is a no-op function
1481 # (dummy_partitions_to_delete will be empty).
1482 if [[ ${#dummy_partitions_to_delete[@]} -eq 0 ]] ; then
1483 partitions_to_resize=()
1484 current_disk=""
1485 disk_label=""
1486 last_partition_number=0
1487 return 0
1488 fi
1489
1490 # Delete dummy partitions
1491 local -i num
1492 for num in "${dummy_partitions_to_delete[@]}" ; do
1493 LogPrint "Disk '$current_disk': deleting dummy partition number $num"
1494 parted -s -m $current_disk rm $num
1495 done
1496 dummy_partitions_to_delete=()
1497 my_udevsettle
1498
1499 # Resize previously shrunk partitions (to make place for dummy
1500 # partitions) to expected size
1501 local -i endB
1502 while read num endB ; do
1503 LogPrint "Disk '$current_disk': resizing partition number $num to original size"
1504 if is_true $FEATURE_PARTED_RESIZEPART ; then
1505 parted -s -m $current_disk resizepart $num "${endB}B"
1506 else
1507 parted -s -m $current_disk resize $num "${endB}B"
1508 fi
1509 done <<< "$(printf "%d %d\n" "${partitions_to_resize[@]}")"
1510 partitions_to_resize=()
1511 my_udevsettle
1512
1513 current_disk=""
1514 disk_label=""
1515 last_partition_number=0
1516 }
1517
1518 # vim: set et ts=4 sw=4: