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