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