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