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