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