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