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