various fixes, upgrade nfsroot to buster
[automated-distro-installer] / fai / config / hooks / partition.DEFAULT
1 #!/bin/bash -x
2 # Copyright (C) 2016 Ian Kelling
3
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 set -eE -o pipefail
19 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
20
21 # for calling outside of FAI:
22 # # need to redep and set that location so that we get luks keys
23 # export FAI=/srv/fai/config
24 # fai-redep
25 # source /b/fai/fai-wrapper
26 # - set any appropriate classes with: fai-setclass OPT1... which sets CLASS_OPT1=true...
27 # or run eval-fai-classfile FILE
28 #
29 # OPTIONS:
30 #
31 # environment variables:
32 #
33 # HOSTNAME: if frodo, we exclude 2 devices from the /boot array, which
34 # the bios does not see. if demohost, we set the luks password to just
35 # 'x'.
36 #
37 # SPECIAL_DISK: For use outside of fai. A base disk name like
38 # /dev/sdk. If set, we just cryptsetup and partition this one disk then
39 # exit. This is useful for partitioning a disk in preparation to replace
40 # a failed or failing disk from a raid10 array.
41 #
42 # classes:
43 #
44 # REPARTITION: forces repartitioning even if we detect the proper amount
45 # of partitions already exist.
46 #
47 # ROTATIONAL: forces to install onto hdds instead of sdds. normally sdds
48 # are chosen if they exist.
49 #
50 # PARTITION_PROMPT: command line prompt before partitioning
51 #
52 # RAID0: forces raid0 filesystem. Normally with 4+ devices, we use
53 # raid10.
54 # RAID1: forces raid1 filesystem.
55
56 if [[ $SPECIAL_DISK ]]; then
57 export CLASS_REPARTITION=true
58 fi
59
60 # # fai's setup-storage won't do btrfs on luks,
61 # # so we do it ourself :)
62 # inspiration taken from files in fai-setup-storage package
63
64 # if we are not running in fai, skiptask won't be defined, so carry on.
65 skiptask partition || ! type skiptask
66
67 if ! type -p devbyid; then
68 for d in $FAI/distro-install-common \
69 /a/bin/fai/fai/config/distro-install-common $FAI $PWD; do
70 [[ -d $d ]] || continue
71 if [[ -e $d/devbyid ]]; then
72 devbyid=$d/devbyid
73 devbyid() { $devbyid "$@"; }
74 break
75 fi
76 done
77 if [[ ! $devbyid ]]; then
78 echo "$0: error: failed to find devbyid script" >&2
79 exit 1
80 fi
81 fi
82
83
84
85 #### begin configuration
86
87 rootn=1
88 swapn=2
89 bootn=3
90 # ext partition so grub can write persistent variables,
91 # so it can do a one time boot. grub can't write to
92 # btrfs or any cow fs because it's more
93 # more complicated to do and they don't want to.
94 grub_extn=4
95 # bios boot partition,
96 # https://wiki.archlinux.org/index.php/GRUB
97 bios_grubn=5
98 lastn=$bios_grubn
99
100
101
102 ##### end configuration
103
104
105 add-part() { # add partition suffix to $dev
106 local d ret
107 if [[ $# == 1 ]]; then
108 d=$dev
109 part=$1
110 else
111 d=$1
112 part=$2
113 fi
114 if [[ $d == /dev/disk/by-id/* ]]; then
115 ret=$d-part$part
116 else
117 ret=$d$part
118 fi
119 echo $ret
120 }
121
122 bootdev() { add-part $@ $bootn; }
123 rootdev() { add-part $@ $rootn; }
124 swapdev() { add-part $@ $swapn; }
125 grub_extdev() { add-part $@ $grub_extn; }
126 bios_grubdev() { add-part $@ $bios_grubn; }
127
128 crypt-dev() { echo /dev/mapper/crypt_dev_${1##*/}; }
129 crypt-name() { echo crypt_dev_${1##*/}; }
130 root-cryptdev() { crypt-dev $(rootdev $@); }
131 swap-cryptdev() { crypt-dev $(swapdev $@); }
132 root-cryptname() { crypt-name $(rootdev $@); }
133 swap-cryptname() { crypt-name $(swapdev $@); }
134
135 ##### end function defs
136
137 if ifclass REPARTITION;then
138 partition=true # force a full wipe
139 else
140 partition=false # change to true to force a full wipe
141 fi
142
143 ## ignore disks that are mounted, eg when running from fai-cd
144 declare -A disk_excludes
145 while read -r l; do
146 eval "$l"
147 if [[ ! $PKNAME ]]; then
148 PKNAME="$KNAME"
149 fi
150 if [[ $MOUNTPOINT ]]; then
151 disk_excludes[$PKNAME]=true
152 fi
153 done < <(lsblk -nP -o KNAME,MOUNTPOINT,PKNAME)
154
155
156 hdds=()
157 ssds=()
158 cd /sys/block
159 for disk in [sv]d[a-z]; do
160 if [[ ${disk_excludes[$disk]} ]]; then
161 continue
162 fi
163 case $(cat $disk/queue/rotational) in
164 0) ssds+=(/dev/$disk) ;;
165 1) hdds+=(/dev/$disk) ;;
166 *) echo "$0: error: unknown /sys/block/$disk/queue/rotational: \
167 $(cat $disk/queue/rotational)"; exit 1 ;;
168 esac
169 done
170
171 # install all ssds, or if there are none, all hdds.
172 # Note, usb flash disks are seen as rotational, which is
173 # very odd, but convenient for ignoring them here.
174 # TODO: find a reliable way to ignore them.
175 if ! ifclass ROTATIONAL && (( ${#ssds[@]} > 0 )); then
176 short_devs=( ${ssds[@]} )
177 else
178 short_devs=( ${hdds[@]} )
179 fi
180
181 # check if the partitions exist have the right filesystems
182 #blkid="$(blkid -s TYPE)"
183 for dev in ${short_devs[@]}; do
184 if $partition; then break; fi
185 y=$(readlink -f $dev)
186 arr=($y[0-9])
187 [[ ${#arr[@]} == "$lastn" ]] || partition=true
188 for (( i=1; i <= lastn; i++ )); do
189 [[ -e ${dev}$i ]] || partition=true
190 done
191 # On one system, blkid is missing some partitions.
192 # maybe we need a flag, like FUZZY_BLKID or something, so we
193 # can check that at least some exist.
194 # for x in "`rootdev`: TYPE=\"crypto_LUKS\"" "`bootdev`: TYPE=\"btrfs\""; do
195 # echo "$blkid" | grep -Fx "$x" &>/dev/null || partition=true
196 # done
197 done
198
199 if $partition && ifclass PARTITION_PROMPT; then
200 echo "Press any key except ctrl-c to continue and partition these drives:"
201 echo " ${short_devs[*]}"
202 read -r
203 fi
204
205 devs=()
206 shopt -s extglob
207 for short_dev in ${short_devs[@]}; do
208 devs+=($(devbyid $short_dev))
209 done
210 if [[ ! ${devs[0]} ]]; then
211 echo "$0: error: failed to detect devs" >&2
212 exit 1
213 fi
214
215 boot_space=0
216 first=false
217 boot_devs=()
218 for dev in ${devs[@]}; do
219 if ifclass frodo; then
220 # I ran into a machine where the bios doesn't know about some disks,
221 # so 1st stage of grub also doesn't know about them.
222 # Also, grub does not support mounting degraded btrfs as far as
223 # I can tell with some googling.
224 # From within an arch install env, I could detect them by noting
225 # their partitions were mixed with the next disk in /dev/disk/by-path,
226 # and I have mixed model disks, and I could see the 8 models which showed
227 # up in the bios, and thus see which 2 models were missing.
228 # hdparm -I /dev/sdh will give model info in linux.
229 # However, in fai on jessie, /dev/disk/by-path dir doesn't exist,
230 # and I don't see another way, so I'm hardcoding them.
231 # We still put grub on them and partition them the same, for uniformity
232 # and in case they get moved to a system that can recognize them,
233 # we just exclude them from the boot filesystem.
234 cd /dev/disk/by-id/
235 bad_disk=false
236 for id in ata-TOSHIBA_MD04ACA500_8539K4TQFS9A \
237 ata-TOSHIBA_MD04ACA500_Y5IFK6IJFS9A; do
238 if [[ $(readlink -f $id) == "$(readlink -f $dev)" ]]; then
239 bad_disk=true
240 break
241 fi
242 done
243 $bad_disk || boot_devs+=($(bootdev))
244 else
245 boot_space=$(( boot_space + $(parted -m $dev unit MiB print | \
246 sed -nr "s#^/dev/[^:]+:([0-9]+).*#\1#p") - 1))
247 boot_devs+=($(bootdev))
248 fi
249 if [[ $boot_devs && $first ]]; then
250 first_grub_extdev=$(grub_extdev)
251 first=false
252 fi
253 done
254
255 if ifclass RAID0 || (( ${#boot_devs[@]} == 1 )); then
256 raid_level=0
257 elif ifclass RAID1 || (( ${#boot_devs[@]} <= 3 )); then
258 raid_level=1
259 else
260 raid_level=10
261 fi
262
263 ### Begin calculate boot partition space
264 # due to raid duplication
265 case $raid_level in
266 1*) boot_space=$(( boot_space / 2 )) ;;
267 esac
268 if (( boot_space > 60000 )); then
269 # this is larger than needed for several /boot subvols,
270 # becuase I keep a minimal debian install on it for
271 # recovery needs and for doing pxe-kexec.
272 boot_mib=10000
273 elif (( boot_space > 30000 )); then
274 boot_mib=$(( 5000 + (boot_space - 30000) / 2 ))
275 else
276 # Small vms don't have room for /boot recovery. With 3 kernels
277 # installed, i'm using 132M on t8, so this seems like plenty of
278 # room. note: rhel 8 recomments 1g for /boot.
279 boot_mib=500
280 #
281 fi
282 case $raid_level in
283 1*) boot_mib=$(( boot_mib * 2 )) ;;
284 esac
285 ### end calculate boot partition space
286
287
288
289 if [[ ! $DISTRO ]]; then
290 if ifclass VOL_STRETCH_BOOTSTRAP; then
291 DISTRO=debianstretch_bootstrap
292 elif ifclass VOL_STRETCH; then
293 DISTRO=debianstretch
294 elif ifclass VOL_BUSTER; then
295 DISTRO=debianbuster
296 elif ifclass VOL_TESTING; then
297 DISTRO=debiantesting
298 elif ifclass VOL_XENIAL; then
299 DISTRO=ubuntuxenial
300 elif ifclass VOL_BELENOS; then
301 DISTRO=trisquelbelenos
302 elif ifclass VOL_FLIDAS; then
303 DISTRO=trisquelflidas
304 elif ifclass VOL_ETIONA; then
305 DISTRO=trisqueletiona
306 else
307 echo "PARTITIONER ERROR: no distro class/var set" >&2
308 exit 1
309 fi
310 fi
311 first_boot_dev=${boot_devs[0]}
312
313
314 bpart() { # btrfs a partition
315 case $raid_level in
316 0) mkfs.btrfs -f $@ ;;
317 1) mkfs.btrfs -f -m raid1 -d raid1 $@ ;;
318 10) mkfs.btrfs -f -m raid10 -d raid10 $@ ;;
319 esac
320 }
321
322
323 # see README for docs about how to create these
324 luks_dir=$FAI/distro-install-common/luks
325
326
327 luks_file=$luks_dir/host-$HOSTNAME
328 if [[ ! -e $luks_file ]]; then
329 hostkeys=($luks_dir/host-*)
330 # if there is only one key, we might be deploying somewhere
331 # where dhcp doesnt give us a proper hostname, so use that.
332 if [[ ${#hostkeys[@]} == 1 && -e ${hostkeys[0]} ]]; then
333 luks_file=${hostkeys[0]}
334 else
335 echo "$0: error: no key for hostname at $luks_file" >&2
336 exit 1
337 fi
338 fi
339
340 # # note, corresponding changes in /b/ds/keyscript-{on,off}
341 if ifclass tpnew; then
342 lukspw=$(cat $luks_dir/traci)
343 elif ifclass ziva; then
344 lukspw=$(cat $luks_dir/ziva)
345 elif ifclass demohost; then
346 lukspw=x
347 elif [[ -e $luks_dir/$HOSTNAME ]]; then
348 lukspw=$(cat $luks_dir/$HOSTNAME)
349 else
350 lukspw=$(cat $luks_dir/iank)
351 fi
352
353
354 first_root_crypt=$(root-cryptdev ${devs[0]})
355
356 # 1.5 x based on https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/sect-disk-partitioning-setup-x86.html#sect-custom-partitioning-x86
357 swap_mib=$(( $(grep ^MemTotal: /proc/meminfo | \
358 awk '{print $2}') * 3/(${#devs[@]} * 2 ) / 1024 ))
359
360 mkdir -p /tmp/fai
361 root_devs=()
362 for dev in ${devs[@]}; do
363 root_devs+=($(rootdev))
364 done
365 shopt -s nullglob
366 if $partition; then
367
368 ### begin wipefs
369 if [[ ! $SPECIAL_DISK ]]; then
370 for dev in ${devs[@]}; do
371 # if we repartition to the same as an old partition,
372 # we don't want any old fses hanging around.
373 for (( i=1; i <= lastn; i++ )); do
374 x=$(add-part $dev $i)
375 [[ -e $x ]] || continue
376 count_down=10
377 # wipefs has failed, manual run works, google suggests timing issue
378 while ! wipefs -a $x; do
379 sleep 2
380 count_down=$((count_down - 1))
381 (( count_down > 0 )) || exit 1
382 done
383 done
384 done
385 fi
386 ### end wipefs
387
388 for dev in ${devs[@]}; do
389 if [[ $SPECIAL_DISK ]]; then
390 dev=$(devbyid $SPECIAL_DISK)
391 fi
392
393 # parted will round up the disk size. Do -1 so we can have
394 # fully 1MiB unit partitions for easy resizing of the last partition.
395 # Otherwise we would pass in -0 for the end argument for the last partition.
396 #
397 # Note: parted print error output is expected. example:
398 # Error: /dev/vda: unrecognised disk label
399 disk_mib=$(( $(parted -m $dev unit MiB print | \
400 sed -nr "s#^/dev/[^:]+:([0-9]+).*#\1#p") - 1))
401 root_end=$(( disk_mib - swap_mib - boot_mib / ${#boot_devs[@]} ))
402 swap_end=$(( root_end + swap_mib))
403
404 parted -s $dev mklabel gpt
405 # MiB because parted complains about alignment otherwise.
406 pcmd="parted -a optimal -s -- $dev"
407 $pcmd mkpart primary ext3 12MiB ${root_end}MiB
408 # without naming, systemd gives us misc errors like:
409 # dev-disk-by\x2dpartlabel-primary.device: Dev dev-disk-by\x2dpartlabel-primary.device appeared twice
410 $pcmd name $rootn root
411 # normally a swap is type "linux-swap", but this is encrypted swap. using that
412 # label will confuse systemd.
413 $pcmd mkpart primary "" ${root_end}MiB ${swap_end}MiB
414 $pcmd name $swapn swap
415 $pcmd mkpart primary "" ${swap_end}MiB ${disk_mib}MiB
416 $pcmd name $bootn boot
417 # i only need a few k, but googling min size,
418 # I found someone saying that gparted required
419 # required at least 8 because of their hard drive cylinder size.
420 # And 8 is still very tiny.
421 $pcmd mkpart primary "ext2" 4MiB 12MiB
422 $pcmd name $grub_extn grubext
423 # gpt ubuntu cloud image uses ~4 mb for this partition. fai uses 1 MiB.
424 # so, I use 3, whatever.
425 # note: parted manual saying cheap flash media
426 # should to start at 4.
427 $pcmd mkpart primary "" 1MiB 4MiB
428 $pcmd name $bios_grubn biosgrub
429 $pcmd set $bios_grubn bios_grub on
430 $pcmd set $bootn boot on # generally not needed on modern systems
431 # the mkfs failed before on a vm, which prompted me to add
432 # sleep .1
433 # then it failed again on a physical machine
434 # with:
435 # Device /dev/disk/by-id/foo doesn't exist or access denied,
436 # so I added a wait until it existed.
437 # Then I added the mkfs.ext2, which claimed to succeed,
438 # but then couldn't be found upon reboot. In that case we didn't
439 # wait at all. So I've added a 3 second minimum wait.
440 sleep 3
441 secs=0
442 while [[ ! -e $(rootdev) ]] && (( secs < 10 )); do
443 sleep 1
444 secs=$((secs +1))
445 done
446 # Holds just a single file, rarely written, so
447 # use ext2, like was often used for the /boot partition.
448 # This exists because grub can only persist data to a non-cow fs.
449 # And we use persisting a var in grub to do a one time boot.
450 # We could pass the data on the kernel command line and persist it
451 # to grubenv after booting, but that relies on the boot always succeeding.
452 # This is just a bit more robust, and it could work for booting
453 # into ipxe which can't persist data, if we ever got that working.
454 mkfs.ext2 $(grub_extdev)
455 # when we move to newer than trisquel 8, we can remove
456 # --type luks1. We can also check on cryptsetup --help | less /compil
457 # to see about the other settings. Default in debian 9 is luks2.
458 # You can convert from luks2 to luks 1 by adding a temporary key:
459 # cryptsetup luksAddKey --pbkdf pbkdf2
460 # then remove the new format keys with cryptsetup luksRemoveKey
461 # then cryptsetup convert DEV --type luks1, then readd old keys and remove temp.
462 yes YES | cryptsetup luksFormat $(rootdev) $luks_file \
463 --type luks1 -c aes-cbc-essiv:sha256 -s 256 || [[ $? == 141 ]]
464 yes "$lukspw" | \
465 cryptsetup luksAddKey --key-file $luks_file \
466 $(rootdev) || [[ $? == 141 ]]
467 # background: Keyfile and password are treated just
468 # like 2 ways to input a passphrase, so we don't actually need to have
469 # different contents of keyfile and passphrase, but it makes some
470 # security sense to a really big randomly generated passphrase
471 # as much as possible, so we have both.
472 #
473 # This would remove the keyfile.
474 # yes 'test' | cryptsetup luksRemoveKey /dev/... \
475 # /key/file || [[ $? == 141 ]]
476
477 cryptsetup luksOpen $(rootdev) $(root-cryptname) \
478 --key-file $luks_file
479
480 if [[ $SPECIAL_DISK ]]; then
481 exit 0
482 fi
483 done
484 ls -la /dev/btrfs-control # this was probably for debugging...
485 sleep 1
486 bpart $(for dev in ${devs[@]}; do root-cryptdev; done)
487 bpart ${boot_devs[@]}
488 else
489 for dev in ${devs[@]}; do
490 if [[ -e /a/bin/fai/fai-wrapper && -e /dev/mapper/$(root-cryptname) ]]; then
491 continue
492 fi
493 cryptsetup luksOpen $(rootdev) $(root-cryptname) \
494 --key-file $luks_file
495 done
496 sleep 1
497 fi
498
499
500 if [[ $DISTRO != debianstretch_bootstrap ]]; then
501 # bootstrap distro doesn't use separate encrypted root.
502 mount -o subvolid=0 $first_root_crypt /mnt
503 # systemd creates subvolumes we want to delete.
504 s=($(btrfs subvolume list --sort=-path /mnt |
505 sed -rn "s#^.*path\s*(root_$DISTRO/\S+)\s*\$#\1#p"))
506 for subvol in ${s[@]}; do btrfs subvolume delete /mnt/$subvol; done
507 btrfs subvolume set-default 0 /mnt
508 [[ ! -e /mnt/root_$DISTRO ]] || btrfs subvolume delete /mnt/root_$DISTRO
509
510 ## create subvols ##
511 cd /mnt
512
513 btrfs subvolume create root_$DISTRO
514
515 # could set default subvol like this, but no reason to.
516 # btrfs subvolume set-default \
517 # $(btrfs subvolume list . | grep "root_$DISTRO$" | awk '{print $2}') .
518
519 # no cow on the root filesystem. it's setup is fully scripted,
520 # if it's messed up, we will just recreated it,
521 # and we can get better perf with this.
522 # I can't remember exactly why, but this is preferable to mounting with
523 # -o nodatacow, I think because subvolumes inherit that.
524 chattr -Rf +C root_$DISTRO
525 cd /
526 umount /mnt
527 fi
528
529 mount -o subvolid=0 $first_boot_dev /mnt
530 cd /mnt
531 btrfs subvolume set-default 0 /mnt # already default, just ensuring it.
532
533 # for libreboot systems. grub2 only reads from subvolid=0
534 mkdir -p /mnt/grub2
535 cp $FAI/distro-install-common/libreboot_grub.cfg /mnt/grub2
536
537 if [[ $DISTRO == debianstretch_bootstrap ]]; then
538 # this is just convenience for the libreboot_grub config
539 # so we can glob the other ones easier.
540 boot_vol=$DISTRO
541 else
542 boot_vol=boot_$DISTRO
543 fi
544 [[ ! -e /mnt/$boot_vol ]] || btrfs subvolume delete /mnt/$boot_vol
545 btrfs subvolume create $boot_vol
546 cd /
547 umount /mnt
548 ## end create subvols ##
549
550 dev=${boot_devs[0]}
551 mount $first_grub_extdev /mnt
552 grub-editenv /mnt/grubenv set did_fai_check=true
553 grub-editenv /mnt/grubenv set last_boot=/$boot_vol
554 umount /mnt
555
556 if [[ $DISTRO == debianstretch_bootstrap ]]; then
557 cat > /tmp/fai/fstab <<EOF
558 $first_boot_dev / btrfs noatime,subvol=$boot_vol 0 0
559 EOF
560 cat >/tmp/fai/disk_var.sh <<EOF
561 BOOT_DEVICE="${short_devs[@]}"
562 ROOT_PARTITION=$first_boot_dev
563 EOF
564 else
565 # note, fai creates the mountpoints listed here
566 cat > /tmp/fai/fstab <<EOF
567 $first_root_crypt / btrfs noatime,subvol=root_$DISTRO 0 0
568 $first_root_crypt /mnt/root btrfs nofail,noatime,subvolid=0 0 0
569 $first_boot_dev /boot btrfs nofail,noatime,subvol=$boot_vol 0 0
570 $first_boot_dev /mnt/boot btrfs nofail,noatime,subvolid=0 0 0
571 EOF
572 swaps=()
573 for dev in ${devs[@]}; do
574 swaps+=($(swap-cryptname))
575 cat >>/tmp/fai/crypttab <<EOF
576 $(root-cryptname) $(rootdev) none keyscript=/root/keyscript,discard,luks,initramfs
577 $(swap-cryptname) $(swapdev) /dev/urandom swap,cipher=aes-xts-plain64,size=256,hash=ripemd160
578 EOF
579 cat >> /tmp/fai/fstab <<EOF
580 $(swap-cryptdev) none swap nofail,sw 0 0
581 EOF
582 done
583
584 # fai would do this:
585 #BOOT_DEVICE=\${BOOT_DEVICE:-"${devs[0]}"}
586
587 # note: swaplist seems to do nothing.
588 cat >/tmp/fai/disk_var.sh <<EOF
589 BOOT_DEVICE="${short_devs[@]}"
590 BOOT_PARTITION=\${BOOT_PARTITION:-$first_boot_dev}
591 # ROOT_PARTITIONS is added by me, used in arch setup.
592 ROOT_PARTITIONS="${root_devs[@]}"
593 ROOT_PARTITION=\${ROOT_PARTITION:-$first_root_crypt}
594 SWAPLIST=\${SWAPLIST:-"${swaps[@]}"}
595 EOF
596 fi