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