make raid1 default over raid0
[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 # this is larger than needed for several /boot subvols,
97 # becuase I keep a minimal debian install on it, for
98 # recovery needs, and for doing pxe-kexec.
99 boot_mib=10000
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
144
145 hdds=()
146 ssds=()
147 cd /sys/block
148 for disk in [sv]d[a-z]; do
149 case $(cat $disk/queue/rotational) in
150 0) ssds+=(/dev/$disk) ;;
151 1) hdds+=(/dev/$disk) ;;
152 *) echo "$0: error: unknown /sys/block/$disk/queue/rotational: \
153 $(cat $disk/queue/rotational)"; exit 1 ;;
154 esac
155 done
156
157 # install all ssds, or if there are none, all hdds.
158 # Note, usb flash disks are seen as rotational, which is
159 # very odd, but convenient for ignoring them here.
160 # TODO: find a reliable way to ignore them.
161 if ! ifclass ROTATIONAL && (( ${#ssds[@]} > 0 )); then
162 short_devs=( ${ssds[@]} )
163 else
164 short_devs=( ${hdds[@]} )
165 fi
166
167 # check if the partitions exist have the right filesystems
168 #blkid="$(blkid -s TYPE)"
169 for dev in ${short_devs[@]}; do
170 if $partition; then break; fi
171 y=$(readlink -f $dev)
172 arr=($y[0-9])
173 [[ ${#arr[@]} == "${lastn}" ]] || partition=true
174 for (( i=1; i <= lastn; i++ )); do
175 [[ -e ${dev}$i ]] || partition=true
176 done
177 # On one system, blkid is missing some partitions.
178 # maybe we need a flag, like FUZZY_BLKID or something, so we
179 # can check that at least some exist.
180 # for x in "`rootdev`: TYPE=\"crypto_LUKS\"" "`bootdev`: TYPE=\"btrfs\""; do
181 # echo "$blkid" | grep -Fx "$x" &>/dev/null || partition=true
182 # done
183 done
184
185 if $partition && ifclass PARTITION_PROMPT; then
186 echo "Press any key except ctrl-c to continue and partition these drives:"
187 echo " ${short_devs[*]}"
188 read -r
189 fi
190
191 devs=()
192 shopt -s extglob
193 for short_dev in ${short_devs[@]}; do
194 devs+=($(devbyid $short_dev))
195 done
196 if [[ ! ${devs[@]} ]]; then
197 echo "$0: error: failed to detect devs" >&2
198 exit 1
199 fi
200
201
202 first=false
203 boot_devs=()
204 for dev in ${devs[@]}; do
205 if ifclass frodo; then
206 # I ran into a machine where the bios doesn't know about some disks,
207 # so 1st stage of grub also doesn't know about them.
208 # Also, grub does not support mounting degraded btrfs as far as
209 # I can tell with some googling.
210 # From within an arch install env, I could detect them by noting
211 # their partitions were mixed with the next disk in /dev/disk/by-path,
212 # and I have mixed model disks, and I could see the 8 models which showed
213 # up in the bios, and thus see which 2 models were missing.
214 # hdparm -I /dev/sdh will give model info in linux.
215 # However, in fai on jessie, /dev/disk/by-path dir doesn't exist,
216 # and I don't see another way, so I'm hardcoding them.
217 # We still put grub on them and partition them the same, for uniformity
218 # and in case they get moved to a system that can recognize them,
219 # we just exclude them from the boot filesystem.
220 cd /dev/disk/by-id/
221 bad_disk=false
222 for id in ata-TOSHIBA_MD04ACA500_8539K4TQFS9A \
223 ata-TOSHIBA_MD04ACA500_Y5IFK6IJFS9A; do
224 if [[ $(readlink -f $id) == "$(readlink -f $dev)" ]]; then
225 bad_disk=true
226 break
227 fi
228 done
229 $bad_disk || boot_devs+=(`bootdev`)
230 else
231 boot_devs+=(`bootdev`)
232 fi
233 if [[ $boot_devs && $first ]]; then
234 first_grub_extdev=`grub_extdev`
235 first=false
236 fi
237 done
238
239 if ifclass RAID0 || (( ${#boot_devs[@]} == 1 )); then
240 raid_level=0
241 elif ifclass RAID1 || (( ${#boot_devs[@]} <= 3 )); then
242 raid_level=1
243 else
244 raid_level=10
245 # need double the space if we are raid 10, and then
246 # might as well give some extra.
247 boot_mib=$((boot_mib * 3))
248 fi
249
250
251
252 if [[ ! $DISTRO ]]; then
253 if ifclass VOL_STRETCH_BOOTSTRAP; then
254 DISTRO=debianstretch_bootstrap
255 elif ifclass VOL_STRETCH; then
256 DISTRO=debianstretch
257 elif ifclass VOL_TESTING; then
258 DISTRO=debiantesting
259 elif ifclass VOL_XENIAL; then
260 DISTRO=ubuntuxenial
261 elif ifclass VOL_BELENOS; then
262 DISTRO=trisquelbelenos
263 elif ifclass VOL_FLIDAS; then
264 DISTRO=trisquelflidas
265 else
266 echo "PARTITIONER ERROR: no distro class/var set" >&2
267 exit 1
268 fi
269 fi
270 first_boot_dev=${boot_devs[0]}
271
272
273 bpart() { # btrfs a partition
274 case $raid_level in
275 0) mkfs.btrfs -f $@ ;;
276 1) mkfs.btrfs -f -m raid1 -d raid1 $@ ;;
277 10) mkfs.btrfs -f -m raid10 -d raid10 $@ ;;
278 esac
279 }
280
281
282 # keyfiles generated like:
283 # head -c 2048 /dev/urandom | od | s dd of=/q/root/luks/host-demohost
284 luks_dir=${LUKS_DIR:-/var/lib/fai/config/distro-install-common/luks}
285
286 if [[ ! -e $luks_dir/host-$HOSTNAME ]]; then
287 echo "$0: error: no key for hostname at $luks_dir/host-$HOSTNAME" >&2
288 exit 1
289 fi
290
291 lukspw=$(cat $luks_dir/iank)
292 # # ian: disabled by chaning to tpnew while I use the tp host.
293 # # note, corresponding changes in /b/ds/keyscript-{on,off}
294 if ifclass tpnew; then
295 lukspw=$(cat $luks_dir/traci)
296 fi
297 if ifclass demohost; then
298 lukspw=x
299 fi
300
301
302 first_root_crypt=$(root-cryptdev ${devs[0]})
303
304 # 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
305 swap_mib=$(( $(grep ^MemTotal: /proc/meminfo | \
306 awk '{print $2}') * 3/(${#devs[@]} * 2 ) / 1024 ))
307
308 mkdir -p /tmp/fai
309 root_devs=()
310 for dev in ${devs[@]}; do
311 root_devs+=(`rootdev`)
312 done
313 shopt -s nullglob
314 if $partition; then
315
316 ### begin wipefs
317 if [[ ! $SPECIAL_DISK ]]; then
318 for dev in ${devs[@]}; do
319 # if we repartition to the same as an old partition,
320 # we don't want any old fses hanging around.
321 for (( i=1; i <= lastn; i++ )); do
322 x=$(add-part $dev $i)
323 [[ -e $x ]] || continue
324 count_down=10
325 # wipefs has failed, manual run works, google suggests timing issue
326 while ! wipefs -a $x; do
327 sleep 2
328 count_down=$((count_down - 1))
329 (( count_down > 0 )) || exit 1
330 done
331 done
332 done
333 fi
334 ### end wipefs
335
336 for dev in ${devs[@]}; do
337 if [[ $SPECIAL_DISK ]]; then
338 dev=$(devbyid $SPECIAL_DISK)
339 fi
340
341 # parted will round up the disk size. Do -1 so we can have
342 # fully 1MiB unit partitions for easy resizing of the last partition.
343 # Otherwise we would pass in -0 for the end argument for the last partition.
344 #
345 # Note: parted print error output is expected. example:
346 # Error: /dev/vda: unrecognised disk label
347 disk_mib=$(( $(parted -m $dev unit MiB print | \
348 sed -nr "s#^/dev/[^:]+:([0-9]+).*#\1#p") - 1))
349 root_end=$(( disk_mib - swap_mib - boot_mib / ${#boot_devs[@]} ))
350 swap_end=$(( root_end + swap_mib))
351
352 parted -s $dev mklabel gpt
353 # MiB because parted complains about alignment otherwise.
354 pcmd="parted -a optimal -s -- $dev"
355 $pcmd mkpart primary ext3 12MiB ${root_end}MiB
356 # without naming, systemd gives us misc errors like:
357 # dev-disk-by\x2dpartlabel-primary.device: Dev dev-disk-by\x2dpartlabel-primary.device appeared twice
358 $pcmd name $rootn root
359 # normally a swap is type "linux-swap", but this is encrypted swap. using that
360 # label will confuse systemd.
361 $pcmd mkpart primary "" ${root_end}MiB ${swap_end}MiB
362 $pcmd name $swapn swap
363 $pcmd mkpart primary "" ${swap_end}MiB ${disk_mib}MiB
364 $pcmd name $bootn boot
365 # i only need a few k, but googling min size,
366 # I found someone saying that gparted required
367 # required at least 8 because of their hard drive cylinder size.
368 # And 8 is still very tiny.
369 $pcmd mkpart primary "ext2" 4MiB 12MiB
370 $pcmd name $grub_extn grubext
371 # gpt ubuntu cloud image uses ~4 mb for this partition. fai uses 1 MiB.
372 # so, I use 3, whatever.
373 # note: parted manual saying cheap flash media
374 # should to start at 4.
375 $pcmd mkpart primary "" 1MiB 4MiB
376 $pcmd name $bios_grubn biosgrub
377 $pcmd set $bios_grubn bios_grub on
378 $pcmd set $bootn boot on # generally not needed on modern systems
379 # the mkfs failed before on a vm, which prompted me to add
380 # sleep .1
381 # then it failed again on a physical machine
382 # with:
383 # Device /dev/disk/by-id/foo doesn't exist or access denied,
384 # so I added a wait until it existed.
385 # Then I added the mkfs.ext2, which claimed to succeed,
386 # but then couldn't be found upon reboot. In that case we didn't
387 # wait at all. So I've added a 3 second minimum wait.
388 sleep 3
389 secs=0
390 while [[ ! -e `rootdev` ]] && (( secs < 10 )); do
391 sleep 1
392 secs=$((secs +1))
393 done
394 # Holds just a single file, rarely written, so
395 # use ext2, like was often used for the /boot partition.
396 # This exists because grub can only persist data to a non-cow fs.
397 # And we use persisting a var in grub to do a one time boot.
398 # We could pass the data on the kernel command line and persist it
399 # to grubenv after booting, but that relies on the boot always succeeding.
400 # This is just a bit more robust, and it could work for booting
401 # into ipxe which can't persist data, if we ever got that working.
402 mkfs.ext2 `grub_extdev`
403 # when we move to newer than trisquel 8, we can remove
404 # --type luks1. We can also check on cryptsetup --help | less /compil
405 # to see about the other settings. Default in debian 9 is luks2.
406 # You can convert from luks2 to luks 1 by adding a temporary key:
407 # cryptsetup luksAddKey --pbkdf pbkdf2
408 # then remove the new format keys with cryptsetup luksRemoveKey
409 # then cryptsetup convert DEV --type luks1, then readd old keys and remove temp.
410 yes YES | cryptsetup luksFormat `rootdev` $luks_dir/host-$HOSTNAME \
411 --type luks1 -c aes-cbc-essiv:sha256 -s 256 || [[ $? == 141 ]]
412 yes "$lukspw" | \
413 cryptsetup luksAddKey --key-file $luks_dir/host-$HOSTNAME \
414 `rootdev` || [[ $? == 141 ]]
415 # background: Keyfile and password are treated just
416 # like 2 ways to input a passphrase, so we don't actually need to have
417 # different contents of keyfile and passphrase, but it makes some
418 # security sense to a really big randomly generated passphrase
419 # as much as possible, so we have both.
420 #
421 # This would remove the keyfile.
422 # yes 'test' | cryptsetup luksRemoveKey /dev/... \
423 # /key/file || [[ $? == 141 ]]
424
425 cryptsetup luksOpen `rootdev` `root-cryptname` \
426 --key-file $luks_dir/host-$HOSTNAME
427
428 if [[ $SPECIAL_DISK ]]; then
429 exit 0
430 fi
431 done
432 ls -la /dev/btrfs-control # this was probably for debugging...
433 sleep 1
434 bpart $(for dev in ${devs[@]}; do root-cryptdev; done)
435 bpart ${boot_devs[@]}
436 else
437 for dev in ${devs[@]}; do
438 mkfs.ext2 `grub_extdev`
439 cryptsetup luksOpen `rootdev` `root-cryptname` \
440 --key-file $luks_dir/host-$HOSTNAME
441 done
442 sleep 1
443 fi
444
445
446 if [[ $DISTRO != debianstretch_bootstrap ]]; then
447 # bootstrap distro doesn't use separate encrypted root.
448 mount -o subvolid=0 $first_root_crypt /mnt
449 # systemd creates subvolumes we want to delete.
450 s=($(btrfs subvolume list --sort=-path /mnt |
451 sed -rn "s#^.*path\s*(root_$DISTRO/\S+)\s*\$#\1#p"))
452 for subvol in ${s[@]}; do btrfs subvolume delete /mnt/$subvol; done
453 btrfs subvolume set-default 0 /mnt
454 [[ ! -e /mnt/root_$DISTRO ]] || btrfs subvolume delete /mnt/root_$DISTRO
455
456 ## create subvols ##
457 cd /mnt
458
459 btrfs subvolume create root_$DISTRO
460
461 mkdir -p /mnt/root_$DISTRO/boot
462 # could set default subvol like this, but no reason to.
463 # btrfs subvolume set-default \
464 # $(btrfs subvolume list . | grep "root_$DISTRO$" | awk '{print $2}') .
465
466 # no cow on the root filesystem. it's setup is fully scripted,
467 # if it's messed up, we will just recreated it,
468 # and we can get better perf with this.
469 # I can't remember exactly why, but this is preferable to mounting with
470 # -o nodatacow, I think because subvolumes inherit that.
471 chattr -Rf +C root_$DISTRO
472 cd /
473 umount /mnt
474 fi
475
476 mount -o subvolid=0 $first_boot_dev /mnt
477 cd /mnt
478 btrfs subvolume set-default 0 /mnt # already default, just ensuring it.
479
480 # for libreboot systems. grub2 only reads from subvolid=0
481 mkdir -p /mnt/grub2
482 cp $FAI/distro-install-common/libreboot_grub.cfg /mnt/grub2
483
484 if [[ $DISTRO == debianstretch_bootstrap ]]; then
485 # this is just convenience for the libreboot_grub config
486 # so we can glob the other ones easier.
487 boot_vol=$DISTRO
488 else
489 boot_vol=boot_$DISTRO
490 fi
491 [[ ! -e /mnt/$boot_vol ]] || btrfs subvolume delete /mnt/$boot_vol
492 btrfs subvolume create $boot_vol
493 cd /
494 umount /mnt
495 ## end create subvols ##
496
497 dev=${boot_devs[0]}
498 mount $first_grub_extdev /mnt
499 grub-editenv /mnt/grubenv set did_fai_check=true
500 grub-editenv /mnt/grubenv set last_boot=/$boot_vol
501 umount /mnt
502
503 if [[ $DISTRO == debianstretch_bootstrap ]]; then
504 cat > /tmp/fai/fstab <<EOF
505 $first_boot_dev / btrfs noatime,subvol=$boot_vol 0 0
506 EOF
507 cat >/tmp/fai/disk_var.sh <<EOF
508 BOOT_DEVICE="${short_devs[@]}"
509 ROOT_PARTITION=$first_boot_dev
510 EOF
511 else
512 # note, fai creates the mountpoints listed here
513 cat > /tmp/fai/fstab <<EOF
514 $first_root_crypt / btrfs noatime,subvol=root_$DISTRO 0 0
515 $first_root_crypt /mnt/root btrfs noatime,subvolid=0 0 0
516 $first_boot_dev /boot btrfs noatime,subvol=$boot_vol 0 0
517 EOF
518 swaps=()
519 for dev in ${devs[@]}; do
520 swaps+=(`swap-cryptname`)
521 cat >>/tmp/fai/crypttab <<EOF
522 `root-cryptname` `rootdev` none keyscript=/root/keyscript,discard,luks
523 `swap-cryptname` `swapdev` /dev/urandom swap,cipher=aes-xts-plain64,size=256,hash=ripemd160
524 EOF
525 cat >> /tmp/fai/fstab <<EOF
526 `swap-cryptdev` none swap sw 0 0
527 EOF
528 done
529
530 # fai would do this:
531 #BOOT_DEVICE=\${BOOT_DEVICE:-"${devs[0]}"}
532
533 # note: swaplist seems to do nothing.
534 cat >/tmp/fai/disk_var.sh <<EOF
535 BOOT_DEVICE="${short_devs[@]}"
536 BOOT_PARTITION=\${BOOT_PARTITION:-$first_boot_dev}
537 # ROOT_PARTITIONS is added by me, used in arch setup.
538 ROOT_PARTITIONS="${root_devs[@]}"
539 ROOT_PARTITION=\${ROOT_PARTITION:-$first_root_crypt}
540 SWAPLIST=\${SWAPLIST:-"${swaps[@]}"}
541 EOF
542 fi