Repository navigation
Expand file tree
/
Copy pathsnapshot-chroot.sh
More file actions
executable file
·547 lines (427 loc) · 16.5 KB
/
Copy pathsnapshot-chroot.sh
File metadata and controls
executable file
·547 lines (427 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
#!/usr/bin/env bash
#
# snapshot-chroot
#
# Recovery utility for building a writable chroot environment from a
# selected Btrfs/Snapper root snapshot.
#
# Version: 2.0.0
# License: GPL-3.0-or-later
#
# Copyright (C) 2026 Scott McClain
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
if (( EUID != 0 )); then
echo "Error: This script must be run as root."
echo "Run: $0"
exit 1
fi
###############################################################################
# Configuration
###############################################################################
# Optional overrides. Leave blank for automatic discovery.
ROOT_PARTITION=""
EFI_PARTITION=""
MOUNT_POINT="/mnt"
###############################################################################
# Runtime State
###############################################################################
BTRFS_TOP=""
HOME_PARTITION=""
HOME_SUBVOLUME_PATH=""
HAS_SEPARATE_HOME=false
SNAPSHOT_ROOT=""
SNAPSHOT_STORE=""
SNAPSHOT_PATH=""
SNAPSHOT_ID=""
SNAPSHOT_STORE_ID=""
HOME_SUBVOLUME_ID=""
declare -a SUBVOLUME_PATHS=()
declare -A SUBVOLUME_IDS=()
###############################################################################
# Discovery Helpers
###############################################################################
fail() {
echo "Error: $1"
exit 1
}
derive_snapshot_root() {
local path="${1#/}"
local expected_snapshot="${2:-}"
local root
local snapshot
if [[ "$path" =~ ^(.+)/\.snapshots/([0-9]+)/snapshot$ ]]; then
root="${BASH_REMATCH[1]}"
snapshot="${BASH_REMATCH[2]}"
else
return 1
fi
[[ -z "$expected_snapshot" || "$snapshot" == "$expected_snapshot" ]] || return 1
[[ -n "$root" ]] || return 1
[[ "$root" =~ ^[a-zA-Z0-9_@.+/-]+$ ]] || return 1
case "/$root/" in
*//*|*/./*|*/../*|*/.snapshots/*)
return 1
;;
esac
printf '%s\n' "$root"
}
mount_top_level() {
local device="$1"
local target="$2"
local mounted_root
mkdir -p "$target"
mount -t btrfs -o ro,subvolid=5 "$device" "$target" || return 1
mounted_root=$(findmnt -no FSROOT "$target")
if [[ "$mounted_root" != "/" ]]; then
umount "$target" 2>/dev/null || true
return 1
fi
return 0
}
load_subvolume_table() {
local id
local path
SUBVOLUME_PATHS=()
SUBVOLUME_IDS=()
while IFS=$'\t' read -r id path; do
[[ "$id" =~ ^[0-9]+$ && -n "$path" ]] || continue
SUBVOLUME_PATHS+=("$path")
SUBVOLUME_IDS["$path"]="$id"
done < <(
btrfs subvolume list "$BTRFS_TOP" | awk '
$1 == "ID" && $2 ~ /^[0-9]+$/ && index($0, " path ") {
id=$2
path=$0
sub(/^.* path /, "", path)
printf "%s\t%s\n", id, path
}
'
)
}
filesystem_has_snapshots() {
local mount_point="$1"
local path
while IFS= read -r path; do
derive_snapshot_root "$path" >/dev/null 2>&1 && return 0
done < <(
btrfs subvolume list "$mount_point" | awk '
$1 == "ID" && index($0, " path ") {
sub(/^.* path /, "")
print
}
'
)
return 1
}
select_from_list() {
local prompt="$1"
local array_name="$2"
local -n choices="$array_name"
local selection
local index
(( ${#choices[@]} > 0 )) || return 1
if (( ${#choices[@]} == 1 )); then
printf '%s\n' "${choices[0]}"
return 0
fi
echo "$prompt" >&2
for index in "${!choices[@]}"; do
printf " %d. %s\n" "$((index + 1))" "${choices[index]}" >&2
done
read -rp "Selection: " selection
[[ "$selection" =~ ^[0-9]+$ ]] || return 1
(( selection >= 1 && selection <= ${#choices[@]} )) || return 1
printf '%s\n' "${choices[selection - 1]}"
}
verify_mount_root() {
local target="$1"
local expected="$2"
local actual
actual=$(findmnt -no FSROOT "$target")
actual="${actual#/}"
[[ "$actual" == "$expected" ]]
}
snapshot_number_from_path() {
local path="${1#/}"
derive_snapshot_root "$path" >/dev/null || return 1
[[ "$path" =~ /\.snapshots/([0-9]+)/snapshot$ ]] || return 1
printf '%s\n' "${BASH_REMATCH[1]}"
}
###############################################################################
# Cleanup
###############################################################################
cleanup() {
echo
echo "Unmounting..."
umount "$MOUNT_POINT/run" 2>/dev/null || true
umount "$MOUNT_POINT/dev/pts" 2>/dev/null || true
umount "$MOUNT_POINT/dev" 2>/dev/null || true
umount "$MOUNT_POINT/proc" 2>/dev/null || true
umount "$MOUNT_POINT/sys" 2>/dev/null || true
umount "$MOUNT_POINT/.snapshots" 2>/dev/null || true
umount "$MOUNT_POINT/boot/efi" 2>/dev/null || true
umount "$MOUNT_POINT/home" 2>/dev/null || true
umount "$BTRFS_TOP" 2>/dev/null || true
umount "$MOUNT_POINT" 2>/dev/null || true
if [[ -n "$BTRFS_TOP" && -d "$BTRFS_TOP" ]]; then
rmdir "$BTRFS_TOP" 2>/dev/null || true
fi
echo "Cleanup complete."
}
trap cleanup EXIT
###############################################################################
# Validation
###############################################################################
for cmd in awk btrfs chroot find findmnt lsblk mktemp mount mountpoint readlink sort umount; do
command -v "$cmd" >/dev/null 2>&1 || fail "Required command '$cmd' not found."
done
if mountpoint -q "$MOUNT_POINT"; then
fail "Recovery mount point is already in use: $MOUNT_POINT"
fi
BTRFS_TOP=$(mktemp -d /run/snapshot-chroot-top.XXXXXX)
###############################################################################
# Discover Installed Btrfs Filesystem
###############################################################################
if [[ -z "$ROOT_PARTITION" ]]; then
ROOT_CHOICES=()
declare -A SEEN_BTRFS_FILESYSTEMS=()
while read -r device fstype uuid; do
[[ "$fstype" == "btrfs" && -b "$device" ]] || continue
key="${uuid:-$device}"
[[ -z "${SEEN_BTRFS_FILESYSTEMS[$key]:-}" ]] || continue
SEEN_BTRFS_FILESYSTEMS["$key"]=1
if mount_top_level "$device" "$BTRFS_TOP"; then
if filesystem_has_snapshots "$BTRFS_TOP"; then
ROOT_CHOICES+=("$device")
fi
umount "$BTRFS_TOP"
fi
done < <(lsblk -prno NAME,FSTYPE,UUID)
ROOT_PARTITION=$(select_from_list "Multiple Btrfs installations contain nested root snapshots:" ROOT_CHOICES) || fail "No Btrfs installation with nested root snapshots was selected."
fi
[[ -b "$ROOT_PARTITION" ]] || fail "Root partition not found: $ROOT_PARTITION"
echo "Mounting the discovered Btrfs top level read-only..."
mount_top_level "$ROOT_PARTITION" "$BTRFS_TOP" || fail "Unable to mount the Btrfs top level: $ROOT_PARTITION"
load_subvolume_table
(( ${#SUBVOLUME_PATHS[@]} > 0 )) || fail "No Btrfs subvolumes were discovered."
###############################################################################
# Determine Recovery Snapshot
###############################################################################
DEFAULT_INFO=$(btrfs subvolume get-default "$BTRFS_TOP")
DEFAULT_SUBVOLUME_ID=$(awk '$1 == "ID" {print $2}' <<< "$DEFAULT_INFO")
DEFAULT_SUBVOLUME_PATH=""
DEFAULT_SNAPSHOT=""
if [[ "$DEFAULT_SUBVOLUME_ID" =~ ^[0-9]+$ ]]; then
for path in "${SUBVOLUME_PATHS[@]}"; do
if [[ "${SUBVOLUME_IDS[$path]}" == "$DEFAULT_SUBVOLUME_ID" ]]; then
DEFAULT_SUBVOLUME_PATH="$path"
break
fi
done
fi
if [[ -n "$DEFAULT_SUBVOLUME_PATH" ]]; then
DEFAULT_SNAPSHOT=$(snapshot_number_from_path "$DEFAULT_SUBVOLUME_PATH") || true
fi
if [[ "$DEFAULT_SNAPSHOT" =~ ^[0-9]+$ ]]; then
echo
echo "Btrfs default snapshot: $DEFAULT_SNAPSHOT"
echo "Default subvolume path: $DEFAULT_SUBVOLUME_PATH"
echo
read -rp "Use default snapshot $DEFAULT_SNAPSHOT for the recovery chroot? [Y/n] " answer
case "$answer" in
""|[Yy])
TARGET_SNAPSHOT="$DEFAULT_SNAPSHOT"
;;
[Nn])
read -rp "Enter snapshot number to use: " TARGET_SNAPSHOT
;;
*)
echo "Error: Invalid response."
exit 1
;;
esac
else
echo
echo "The Btrfs default is not a supported nested root snapshot."
echo
read -rp "Enter snapshot number to use: " TARGET_SNAPSHOT
fi
if [[ ! "$TARGET_SNAPSHOT" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid snapshot number."
exit 1
fi
echo
echo "Selected snapshot: $TARGET_SNAPSHOT"
###############################################################################
# Derive Snapshot Root and Required Mounts
###############################################################################
SNAPSHOT_MATCHES=()
for path in "${SUBVOLUME_PATHS[@]}"; do
if root=$(derive_snapshot_root "$path" "$TARGET_SNAPSHOT"); then
SNAPSHOT_MATCHES+=("$root"$'\t'"$path")
fi
done
if (( ${#SNAPSHOT_MATCHES[@]} == 0 )); then
fail "Snapshot $TARGET_SNAPSHOT was not found in a supported root layout."
fi
if (( ${#SNAPSHOT_MATCHES[@]} > 1 )); then
echo "Matching snapshot paths:"
printf " %s\n" "${SNAPSHOT_MATCHES[@]}"
fail "Snapshot $TARGET_SNAPSHOT is ambiguous."
fi
IFS=$'\t' read -r SNAPSHOT_ROOT SNAPSHOT_PATH <<< "${SNAPSHOT_MATCHES[0]}"
SNAPSHOT_STORE="$SNAPSHOT_ROOT/.snapshots"
SNAPSHOT_ID="${SUBVOLUME_IDS[$SNAPSHOT_PATH]:-}"
SNAPSHOT_STORE_ID="${SUBVOLUME_IDS[$SNAPSHOT_STORE]:-}"
SNAPSHOT_FULL_PATH="$BTRFS_TOP/$SNAPSHOT_PATH"
[[ "$SNAPSHOT_ID" =~ ^[0-9]+$ ]] || fail "Unable to resolve the selected snapshot's subvolume ID."
[[ "$SNAPSHOT_STORE_ID" =~ ^[0-9]+$ ]] || fail "Unable to resolve the snapshot-store subvolume ID."
FSTAB="$SNAPSHOT_FULL_PATH/etc/fstab"
[[ -f "$FSTAB" ]] || fail "Selected snapshot does not contain /etc/fstab."
if HOME_TARGET=$(findmnt --fstab --tab-file "$FSTAB" --target /home --noheadings --output TARGET 2>/dev/null); then
[[ "$HOME_TARGET" == "/home" ]] || fail "The selected snapshot does not define a valid separate /home mount."
HAS_SEPARATE_HOME=true
HOME_FSTYPE=$(findmnt --fstab --tab-file "$FSTAB" --target /home --noheadings --output FSTYPE) || fail "Unable to determine the /home filesystem type."
[[ "$HOME_FSTYPE" == "btrfs" ]] || fail "The discovered /home filesystem is not Btrfs."
HOME_OPTIONS=$(findmnt --fstab --tab-file "$FSTAB" --target /home --noheadings --output OPTIONS) || fail "Unable to determine the /home mount options."
IFS=',' read -ra option_list <<< "$HOME_OPTIONS"
home_subvolid=""
for option in "${option_list[@]}"; do
case "$option" in
subvol=*)
HOME_SUBVOLUME_PATH="${option#subvol=}"
HOME_SUBVOLUME_PATH="${HOME_SUBVOLUME_PATH#/}"
;;
subvolid=*)
home_subvolid="${option#subvolid=}"
;;
esac
done
if [[ -z "$HOME_SUBVOLUME_PATH" && "$home_subvolid" =~ ^[0-9]+$ ]]; then
for path in "${SUBVOLUME_PATHS[@]}"; do
if [[ "${SUBVOLUME_IDS[$path]}" == "$home_subvolid" ]]; then
HOME_SUBVOLUME_PATH="$path"
break
fi
done
fi
[[ -n "$HOME_SUBVOLUME_PATH" ]] || fail "Unable to derive the /home subvolume from fstab."
[[ "$HOME_SUBVOLUME_PATH" =~ ^[a-zA-Z0-9_@.+/-]+$ ]] || fail "The discovered /home subvolume path is unsafe."
HOME_SUBVOLUME_ID="${SUBVOLUME_IDS[$HOME_SUBVOLUME_PATH]:-}"
[[ "$HOME_SUBVOLUME_ID" =~ ^[0-9]+$ ]] || fail "Unable to resolve the /home subvolume ID."
HOME_PARTITION=$(findmnt --fstab --evaluate --tab-file "$FSTAB" --target /home --noheadings --output SOURCE) || fail "Unable to resolve the /home filesystem device."
HOME_PARTITION="${HOME_PARTITION%%[*}"
[[ -b "$HOME_PARTITION" ]] || fail "The discovered /home device is unavailable: $HOME_PARTITION"
if [[ "$(readlink -f "$HOME_PARTITION")" != "$(readlink -f "$ROOT_PARTITION")" ]]; then
fail "A separate /home filesystem is not supported by this prototype."
fi
fi
if [[ -z "$EFI_PARTITION" ]]; then
EFI_TARGET=$(findmnt --fstab --tab-file "$FSTAB" --target /boot/efi --noheadings --output TARGET) || fail "No /boot/efi entry was found in the selected snapshot's fstab."
[[ "$EFI_TARGET" == "/boot/efi" ]] || fail "The selected snapshot does not define an EFI mount at /boot/efi."
EFI_PARTITION=$(findmnt --fstab --evaluate --tab-file "$FSTAB" --target /boot/efi --noheadings --output SOURCE) || fail "Unable to resolve the EFI system partition from fstab."
EFI_PARTITION="${EFI_PARTITION%%[*}"
fi
[[ -b "$EFI_PARTITION" ]] || fail "EFI partition not found: $EFI_PARTITION"
SNAPSHOT_RO=$(btrfs property get -ts "$SNAPSHOT_FULL_PATH" ro)
echo
echo "Discovered Recovery Layout"
echo "--------------------------"
echo "Root Device : $ROOT_PARTITION"
echo "Root Subvolume : $SNAPSHOT_ROOT"
echo "Snapshot Store : $SNAPSHOT_STORE"
echo "Snapshot : $TARGET_SNAPSHOT (ID $SNAPSHOT_ID)"
if $HAS_SEPARATE_HOME; then
echo "Home Device : $HOME_PARTITION"
echo "Home Subvolume : $HOME_SUBVOLUME_PATH"
else
echo "Home Mount : No separate fstab entry"
fi
echo "EFI Device : $EFI_PARTITION"
echo "Recovery Mount : $MOUNT_POINT"
echo
read -rp "Use this discovered layout? [y/N] " answer
case "$answer" in
[Yy])
;;
*)
echo "Recovery chroot cancelled."
exit 1
;;
esac
###############################################################################
# Verify Snapshot Writable State
###############################################################################
if [[ "$SNAPSHOT_RO" == "ro=true" ]]; then
echo
echo "Snapshot $TARGET_SNAPSHOT is read-only."
echo "A writable snapshot is required for system repairs from this chroot."
echo
read -rp "Make snapshot $TARGET_SNAPSHOT writable? [y/N] " answer
case "$answer" in
[Yy])
umount "$BTRFS_TOP"
mount -t btrfs -o rw,subvolid=5 "$ROOT_PARTITION" "$BTRFS_TOP"
[[ "$(findmnt -no FSROOT "$BTRFS_TOP")" == "/" ]] || fail "Writable top-level mount verification failed."
btrfs property set -ts "$SNAPSHOT_FULL_PATH" ro false
echo "Snapshot $TARGET_SNAPSHOT is now writable."
;;
*)
echo "Snapshot left read-only. Recovery chroot cancelled."
exit 1
;;
esac
else
echo "Snapshot $TARGET_SNAPSHOT is writable."
fi
umount "$BTRFS_TOP"
###############################################################################
# Mount recovery environment
###############################################################################
echo
echo "Mounting Btrfs root snapshot $TARGET_SNAPSHOT..."
mount \
-t btrfs \
-o "subvolid=$SNAPSHOT_ID" \
"$ROOT_PARTITION" "$MOUNT_POINT"
verify_mount_root "$MOUNT_POINT" "$SNAPSHOT_PATH" || fail "Mounted root does not match the selected snapshot."
echo "Mounting Btrfs snapshots subvolume..."
mkdir -p "$MOUNT_POINT/.snapshots"
mount \
-t btrfs \
-o "subvolid=$SNAPSHOT_STORE_ID" \
"$ROOT_PARTITION" "$MOUNT_POINT/.snapshots"
verify_mount_root "$MOUNT_POINT/.snapshots" "$SNAPSHOT_STORE" || fail "Mounted snapshot store does not match the discovered path."
if $HAS_SEPARATE_HOME; then
echo "Mounting Btrfs home subvolume ($HOME_SUBVOLUME_PATH)..."
mkdir -p "$MOUNT_POINT/home"
mount -t btrfs -o "subvolid=$HOME_SUBVOLUME_ID" "$HOME_PARTITION" "$MOUNT_POINT/home"
verify_mount_root "$MOUNT_POINT/home" "$HOME_SUBVOLUME_PATH" || fail "Mounted home does not match the discovered subvolume."
fi
echo "Mounting EFI partition..."
mkdir -p "$MOUNT_POINT/boot/efi"
mount "$EFI_PARTITION" "$MOUNT_POINT/boot/efi"
###############################################################################
# Bind virtual filesystems
###############################################################################
echo "Binding virtual filesystems..."
mkdir -p \
"$MOUNT_POINT/dev/pts" \
"$MOUNT_POINT/proc" \
"$MOUNT_POINT/sys" \
"$MOUNT_POINT/run"
mount --bind /dev "$MOUNT_POINT/dev"
mount --bind /dev/pts "$MOUNT_POINT/dev/pts"
mount --bind /proc "$MOUNT_POINT/proc"
mount --bind /sys "$MOUNT_POINT/sys"
mount --bind /run "$MOUNT_POINT/run"
###############################################################################
# Enter chroot
###############################################################################
echo
echo "Entering recovery chroot for snapshot $TARGET_SNAPSHOT..."
echo
chroot "$MOUNT_POINT"
echo
echo "Exited chroot."