change stable to stretch, makes more sense
[automated-distro-installer] / fai / config / hooks / partition.DEFAULT
index e8f0c401850232165c3fbdc5b006a936c62e36d4..fdcfe6d1238e2f5f0c98d3f123fe4746b1a1ba1b 100755 (executable)
 #!/bin/bash -x
+# Copyright (C) 2016 Ian Kelling
+
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 set -eE -o pipefail
-trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?"' ERR
+trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
 
 # # fai's setup-storage won't do btrfs on luks,
 # # so we do it ourself :)
+# inspiration taken from files in fai-setup-storage package
+
 
 skiptask partition || ! type skiptask # for running not in fai
 
 #### begin configuration
 
-bootn=3
 rootn=1
 swapn=2
-bios_grubn=4
-boot_mib=1500
+bootn=3
+# ext partition so grub can write persistent variables,
+# so it can do a one time boot. grub can't write to
+# btrfs or any cow fs because it's more
+# more complicated to do and they don't want to.
+grub_extn=4
+# bios boot partition,
+# https://wiki.archlinux.org/index.php/GRUB
+bios_grubn=5
+lastn=$bios_grubn
+# this is larger than needed for several /boot subvols,
+# becuase I keep a minimal debian install on it, for
+# recovery needs, and for doing pxe-kexec.
+boot_mib=10000
 
 
 ##### end configuration
 
+
+add-part() { # add partition suffix to $dev
+    local d ret
+    if [[ $# == 1 ]]; then
+        d=$dev
+        part=$1
+    else
+        d=$1
+        part=$2
+    fi
+    if [[ $d == /dev/disk/by-id/* ]]; then
+        ret=$d-part$part
+    else
+        ret=$d$part
+    fi
+    echo $ret
+}
+
+bootdev() { add-part $@ $bootn; }
+rootdev() { add-part $@ $rootn; }
+swapdev() { add-part $@ $swapn; }
+grub_extdev() { add-part $@ $grub_extn; }
+bios_grubdev() { add-part $@ $bios_grubn; }
+
+crypt-dev() { echo /dev/mapper/crypt_dev_${1##*/}; }
+crypt-name() { echo crypt_dev_${1##*/}; }
+root-cryptdev() { crypt-dev $(rootdev $@); }
+swap-cryptdev() { crypt-dev $(swapdev $@); }
+root-cryptname() { crypt-name $(rootdev $@); }
+swap-cryptname() { crypt-name $(swapdev $@); }
+devbyid() {
+    local f
+    for f in $FAI/distro-install-common/devbyid \
+                 /a/bin/fai/fai/config/distro-install-common/devbyid; do
+        if [[ -e $f ]]; then $f "$@"; fi
+    done
+
+}
+
+##### end function defs
+
 if ifclass REPARTITION;then
     partition=true # force a full wipe
 else
     partition=false # change to true to force a full wipe
 fi
 
-lastn=$bios_grubn
 
 
-hds=()
+hdds=()
 ssds=()
 cd /sys/block
 for disk in [sv]d[a-z]; do
     case $(cat $disk/queue/rotational) in
         0) ssds+=(/dev/$disk) ;;
-        1) hds+=(/dev/$disk) ;;
+        1) hdds+=(/dev/$disk) ;;
         *) echo "$0: error: unknown /sys/block/$disk/queue/rotational: \
 $(cat $disk/queue/rotational)"; exit 1 ;;
     esac
 done
 
 # install all ssds, or if there are none, all hdds
-if (( ${#ssds[@]} > 0 )); then
-    devs=( ${ssds[@]} )
+if ! ifclass ROTATIONAL && (( ${#ssds[@]} > 0 )); then
+    short_devs=( ${ssds[@]} )
 else
-    devs=( ${hds[@]} )
+    short_devs=( ${hdds[@]} )
 fi
 
+# check if the partitions exist have the right filesystems
+#blkid="$(blkid -s TYPE)"
+for dev in ${short_devs[@]}; do
+    if $partition; then break; fi
+    y=$(readlink -f $dev)
+    arr=($y[0-9])
+    [[ ${#arr[@]}  == "${lastn}" ]] || partition=true
+    for (( i=1; i <= lastn; i++ )); do
+        [[ -e ${dev}$i ]] || partition=true
+    done
+    # On one system, blkid is missing some partitions.
+    # maybe we need a flag, like FUZZY_BLKID or something, so we
+    # can check that at least some exist.
+    # for x in "`rootdev`: TYPE=\"crypto_LUKS\"" "`bootdev`: TYPE=\"btrfs\""; do
+    #     echo "$blkid" | grep -Fx "$x" &>/dev/null || partition=true
+    # done
+done
 
-if [[ ! $DISTRO ]]; then
-    if ifclass STABLE; then
-        DISTRO=debianjessie
+if $partition && ifclass PARTITION_PROMPT; then
+    echo "Press any key except ctrl-c to continue and partition these drives:"
+    echo "  ${short_devs[*]}"
+    read -r
+fi
+
+devs=()
+shopt -s extglob
+for short_dev in ${short_devs[@]}; do
+    devs+=($(devbyid $short_dev))
+done
+
+
+first=false
+boot_devs=()
+for dev in ${devs[@]}; do
+    if ifclass frodo; then
+        # I ran into a machine where the bios doesn't know about some disks,
+        # so 1st stage of grub also doesn't know about them.
+        # Also, grub does not support mounting degraded btrfs as far as
+        # I can tell with some googling.
+        # From within an arch install env, I could detect them by noting
+        # their partitions were mixed with the next disk in /dev/disk/by-path,
+        # and I have mixed model disks, and I could see the 8 models which showed
+        # up in the bios, and thus see which 2 models were missing.
+        # hdparm -I /dev/sdh will give model info in linux.
+        # However, in fai on jessie, /dev/disk/by-path dir doesn't exist,
+        # and I don't see another way, so I'm hardcoding them.
+        # We still put grub on them and partition them the same, for uniformity
+        # and in case they get moved to a system that can recognize them,
+        # we just exclude them from the boot filesystem.
+        cd /dev/disk/by-id/
+        bad_disk=false
+        for id in ata-TOSHIBA_MD04ACA500_8539K4TQFS9A \
+                      ata-TOSHIBA_MD04ACA500_Y5IFK6IJFS9A; do
+            if [[ $(readlink -f $id) == "$(readlink -f $dev)" ]]; then
+                bad_disk=true
+                break
+            fi
+        done
+        $bad_disk || boot_devs+=(`bootdev`)
     else
-        DISTRO=debiantesting
+        boot_devs+=(`bootdev`)
+    fi
+    if [[ $boot_devs && $first ]]; then
+        first_grub_extdev=`grub_extdev`
+        first=false
     fi
+done
+
+if ifclass RAID0 || (( ${#boot_devs[@]} < 4 )); then
+    raid_level=0
+else
+    raid_level=10
+    # need double the space if we are raid 10, and then
+    # might as well give some extra.
+    boot_mib=$((boot_mib * 3))
 fi
 
 
 
+if [[ ! $DISTRO ]]; then
+    if ifclass VOL_STRETCH_BOOTSTRAP; then
+        DISTRO=stretch_bootstrap
+    elif ifclass VOL_STRETCH; then
+        DISTRO=debianstretch
+    elif ifclass VOL_XENIAL; then
+        DISTRO=ubuntuxenial
+    elif ifclass VOL_BELENOS; then
+        DISTRO=trisquelbelenos
+    elif ifclass VOL_FLIDAS; then
+        DISTRO=trisquelflidas
+    else
+        echo "PARTITIONER ERROR: no distro class/var set" >&2
+        exit 1
+    fi
+fi
+first_boot_dev=${boot_devs[0]}
+
+
 bpart() { # btrfs a partition
-    dev_n=$1
-    case ${#@} in
-        [1-3]) mkfs.btrfs -f $@ ;;
-        [4-9]*|[1-3]?*) mkfs.btrfs -f -m raid10 -d raid10 $@ ;;
+    case $raid_level in
+        0) mkfs.btrfs -f $@ ;;
+        10) mkfs.btrfs -f -m raid10 -d raid10 $@ ;;
     esac
 }
 
-first_boot_dev=${devs[0]}$bootn
-
-crypt_devs=()
-# somewhat crude detection of whether to partition
-for dev in ${devs[@]}; do
-    crypt_devs+=( /dev/mapper/crypt_dev_${dev#/dev/} )
-    x=($dev[0-9])
-    [[ ${#x[@]}  == ${lastn} ]] || partition=true
-    for (( i=1; i <= $lastn; i++ )); do
-        [[ -e ${dev}$i ]] || partition=true
-    done
-    for part in $dev$rootn $dev$bootn; do
-        # type tells us it's not totally blank
-        blkid | grep "^${part}:.*TYPE=" &>/dev/null || partition=true
-    done
-done
 
 # keyfiles generated like:
 # head -c 2048 /dev/urandom | od | s dd of=/q/root/luks/host-demohost
 luks_dir=${LUKS_DIR:-/var/lib/fai/config/distro-install-common/luks}
+
+if [[ ! -e $luks_dir/host-$HOSTNAME ]]; then
+    echo "$0: error: no key for hostname at $luks_dir/host-$HOSTNAME" >&2
+    exit 1
+fi
+
 if ifclass tp; then
     lukspw=$(cat $luks_dir/traci)
 else
-    lukspw=$(cat $luks_dir/ian)
+    lukspw=$(cat $luks_dir/iank)
 fi
 if ifclass demohost; then
     lukspw=x
 fi
 
 
-crypt=${crypt_devs[0]}$rootn
+first_root_crypt=$(root-cryptdev ${devs[0]})
 
-bios_grub_end=4
 # 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
 swap_mib=$(( $(grep ^MemTotal: /proc/meminfo | \
-                      awk '{print $2}') * 3/(${#devs[@]} * 2 ) / 1024 ))
-# parted will round up the disk size. Do -1 so we can have
-# fully 1MiB unit partitions for easy resizing of the last partition.
-# Otherwise we would pass in -0 for the end argument for the last partition.
-disk_mib=$(( $(parted -m ${devs[0]} unit MiB print | \
-                      sed -nr "s#^${devs[0]}:([0-9]+).*#\1#p") - 1))
-root_end=$(( disk_mib - swap_mib - boot_mib /  ${#devs[@]} ))
-swap_end=$(( root_end + swap_mib))
+                   awk '{print $2}') * 3/(${#devs[@]} * 2 ) / 1024 ))
 
 mkdir -p /tmp/fai
+root_devs=()
+for dev in ${devs[@]}; do
+    root_devs+=(`rootdev`)
+done
 shopt -s nullglob
 if $partition; then
     for dev in ${devs[@]}; do
-        for x in $dev[0-9]; do
+        # if we repartition to the same as an old partition,
+        # we don't want any old fses hanging around.
+        for (( i=1; i <= lastn; i++ )); do
+            x=$(add-part $dev $i)
+            [[ -e $x ]] || continue
             count_down=10
             # wipefs has failed, manual run works, google suggests timing issue
             while ! wipefs -a $x; do
@@ -125,27 +269,73 @@ if $partition; then
         done
     done
     for dev in ${devs[@]}; do
+        # parted will round up the disk size. Do -1 so we can have
+        # fully 1MiB unit partitions for easy resizing of the last partition.
+        # Otherwise we would pass in -0 for the end argument for the last partition.
+        #
+        # parted print error output is expected. example:
+        # Error: /dev/vda: unrecognised disk label
+        disk_mib=$(( $(parted -m $dev unit MiB print | \
+                           sed -nr "s#^/dev/[^:]+:([0-9]+).*#\1#p") - 1))
+        root_end=$(( disk_mib - swap_mib - boot_mib /  ${#boot_devs[@]} ))
+        swap_end=$(( root_end + swap_mib))
+
         parted -s $dev mklabel gpt
-        # gpt ubuntu cloud image uses ~4. fai uses 1 MiB.
-        # I read something in the parted manual saying cheap flash media
-        # likes to start at 4.
         # MiB because parted complains about alignment otherwise.
         pcmd="parted -a optimal -s -- $dev"
-        $pcmd mkpart primary "ext3" 4MiB ${root_end}MiB
-        $pcmd mkpart primary "linux-swap" ${root_end}MiB ${swap_end}MiB
+        $pcmd mkpart primary ext3 12MiB ${root_end}MiB
+        # without naming, systemd gives us misc errors like:
+        # dev-disk-by\x2dpartlabel-primary.device: Dev dev-disk-by\x2dpartlabel-primary.device appeared twice
+        $pcmd name $rootn root
+        # normally a swap is type "linux-swap", but this is encrypted swap. using that
+        # label will confuse systemd.
+        $pcmd mkpart primary "" ${root_end}MiB ${swap_end}MiB
+        $pcmd name $swapn swap
         $pcmd mkpart primary "" ${swap_end}MiB ${disk_mib}MiB
+        $pcmd name $bootn boot
+        # i only need a few k, but googling min size,
+        # I found someone saying that gparted required
+        # required at least 8 because of their hard drive cylinder size.
+        # And 8 is still very tiny.
+        $pcmd mkpart primary "ext2" 4MiB 12MiB
+        $pcmd name $grub_extn grubext
+        # gpt ubuntu cloud image uses ~4 mb for this partition. fai uses 1 MiB.
+        # so, I use 3, whatever.
+        # note: parted manual saying cheap flash media
+        # should to start at 4.
         $pcmd mkpart primary "" 1MiB 4MiB
+        $pcmd name $bios_grubn biosgrub
         $pcmd set $bios_grubn bios_grub on
         $pcmd set $bootn boot on # generally not needed on modern systems
-        # the mkfs failed randomly on a vm, so I threw a sleep in here.
-        sleep .1
-
-        luks_dev=$dev$rootn
-        yes YES | cryptsetup luksFormat $luks_dev $luks_dir/host-$HOSTNAME \
+        # the mkfs failed before on a vm, which prompted me to add
+        # sleep .1
+        # then it failed again on a physical machine
+        # with:
+        # Device /dev/disk/by-id/foo doesn't exist or access denied,
+        # so I added a wait until it existed.
+        # Then I added the mkfs.ext2, which claimed to succeed,
+        # but then couldn't be found upon reboot. In that case we didn't
+        # wait at all. So I've added a 3 second minimum wait.
+        sleep 3
+        secs=0
+        while [[ ! -e `rootdev` ]] && (( secs < 10 )); do
+            sleep 1
+            secs=$((secs +1))
+        done
+        # Holds just a single file, rarely written, so
+        # use ext2, like was often used for the /boot partition.
+        # This exists because grub can only persist data to a non-cow fs.
+        # And we use persisting a var in grub to do a one time boot.
+        # We could pass the data on the kernel command line and persist it
+        # to grubenv after booting, but that relies on the boot always succeeding.
+        # This is just a bit more robust, and it could work for booting
+        # into ipxe which can't persist data, if we ever got that working.
+        mkfs.ext2 `grub_extdev`
+        yes YES | cryptsetup luksFormat `rootdev` $luks_dir/host-$HOSTNAME \
                              -c aes-cbc-essiv:sha256 -s 256 || [[ $? == 141 ]]
         yes "$lukspw" | \
             cryptsetup luksAddKey --key-file $luks_dir/host-$HOSTNAME \
-                       $luks_dev || [[ $? == 141 ]]
+                       `rootdev` || [[ $? == 141 ]]
         # background: Keyfile and password are treated just
         # like 2 ways to input a passphrase, so we don't actually need to have
         # different contents of keyfile and passphrase, but it makes some
@@ -156,83 +346,117 @@ if $partition; then
         #    yes 'test' | cryptsetup luksRemoveKey /dev/... \
             #                            /key/file || [[ $? == 141 ]]
 
-        cryptsetup luksOpen $luks_dev crypt_dev_${luks_dev##/dev/} \
+        cryptsetup luksOpen `rootdev` `root-cryptname` \
                    --key-file $luks_dir/host-$HOSTNAME
     done
-    bpart ${crypt_devs[@]/%/$rootn}
-    bpart ${devs[@]/%/$bootn}
+    ls -la /dev/btrfs-control # this was probably for debugging...
+    sleep 1
+    bpart $(for dev in ${devs[@]}; do root-cryptdev; done)
+    bpart ${boot_devs[@]}
 else
     for dev in ${devs[@]}; do
-        cryptsetup luksOpen $dev$rootn crypt_dev_${dev##/dev/}$rootn \
-                   --key-file $luks_dir/host-$HOSTNAME || [[ $? == 141 ]]
+        mkfs.ext2 `grub_extdev`
+        cryptsetup luksOpen `rootdev` `root-cryptname` \
+                   --key-file $luks_dir/host-$HOSTNAME
     done
     sleep 1
 fi
 
-mount -o subvolid=0 $crypt /mnt
-# systemd creates subvolumes we want to delete.
-s=($(btrfs subvolume list --sort=-path /mnt |
-            sed -rn "s#^.*path\s*(root_$DISTRO/\S+)\s*\$#\1#p"))
-for subvol in ${s[@]}; do btrfs subvolume delete /mnt/$subvol; done
-btrfs subvolume set-default 0 /mnt
-[[ ! -e /mnt/root_$DISTRO ]] || btrfs subvolume delete /mnt/root_$DISTRO
 
+if [[ $DISTRO != stretch_bootstrap ]]; then
+    # bootstrap distro doesn't use separate encrypted root.
+    mount -o subvolid=0 $first_root_crypt /mnt
+    # systemd creates subvolumes we want to delete.
+    s=($(btrfs subvolume list --sort=-path /mnt |
+             sed -rn "s#^.*path\s*(root_$DISTRO/\S+)\s*\$#\1#p"))
+    for subvol in ${s[@]}; do btrfs subvolume delete /mnt/$subvol; done
+    btrfs subvolume set-default 0 /mnt
+    [[ ! -e /mnt/root_$DISTRO ]] || btrfs subvolume delete /mnt/root_$DISTRO
+
+    ## create subvols ##
+    cd /mnt
+
+    btrfs subvolume create root_$DISTRO
+
+    mkdir -p /mnt/root_$DISTRO/boot
+    # could set default subvol like this, but no reason to.
+    # btrfs subvolume set-default \
+        #       $(btrfs subvolume list . | grep "root_$DISTRO$" | awk '{print $2}') .
+
+    # no cow on the root filesystem. it's setup is fully scripted,
+    # if it's messed up, we will just recreated it,
+    # and we can get better perf with this.
+    # I can't remember exactly why, but this is preferable to mounting with
+    # -o nodatacow, I think because subvolumes inherit that.
+    chattr -Rf +C root_$DISTRO
+    cd /
+    umount /mnt
+fi
 
-## create subvols ##
-cd /mnt
-for x in q home_$DISTRO root_$DISTRO; do
-    btrfs subvolume list . | grep "$x$" >/dev/null || btrfs subvolume create $x
-    chown root:1000 q
-done
-mkdir -p /mnt/root_$DISTRO/boot
-for x in root/a q/a; do
-    mkdir -p $x
-    chown 1000:1000 $x
-    chmod 755 $x
-done
-# could set default like this, but no reason to.
-# btrfs subvolume set-default \
-    #       $(btrfs subvolume list . | grep "root_$DISTRO$" | awk '{print $2}') .
-chattr -Rf +C root_$DISTRO
-cd /
-umount /mnt
 mount -o subvolid=0 $first_boot_dev /mnt
 cd /mnt
-btrfs subvolume set-default 0 /mnt
-[[ ! -e /mnt/boot_$DISTRO ]] || btrfs subvolume delete /mnt/boot_$DISTRO
-btrfs subvolume create boot_$DISTRO
+btrfs subvolume set-default 0 /mnt # already default, just ensuring it.
+
+# for libreboot systems. grub2 only reads from subvolid=0
+mkdir -p /mnt/grub2
+cp $FAI/distro-install-common/libreboot_grub.cfg /mnt/grub2
+
+if [[ $DISTRO == stretch_bootstrap ]]; then
+    # this is just convenience for the libreboot_grub config
+    # so we can glob the other ones easier.
+    boot_vol=$DISTRO
+else
+    boot_vol=boot_$DISTRO
+fi
+[[ ! -e /mnt/$boot_vol ]] || btrfs subvolume delete /mnt/$boot_vol
+btrfs subvolume create $boot_vol
 cd /
 umount /mnt
 ## end create subvols ##
 
+dev=${boot_devs[0]}
+mount $first_grub_extdev /mnt
+grub-editenv /mnt/grubenv set did_fai_check=true
+grub-editenv /mnt/grubenv set last_boot=/$boot_vol
+umount /mnt
 
-
-cat > /tmp/fai/fstab <<EOF
-$crypt  /  btrfs  noatime,subvol=root_$DISTRO  0 0
-$crypt  /q  btrfs  noatime,subvol=q  0 0
-/q/a  /a  none  bind  0 0
-$crypt  /home  btrfs  noatime,subvol=home_$DISTRO  0 0
-$first_boot_dev  /boot  btrfs  noatime,subvol=boot_$DISTRO  0 0
+if [[ $DISTRO == stretch_bootstrap ]]; then
+    cat > /tmp/fai/fstab <<EOF
+$first_boot_dev  /  btrfs  noatime,subvol=$boot_vol  0 0
 EOF
-
-swaps=()
-for dev in ${devs[@]}; do
-    s=crypt_swap_${dev##/dev/}$swapn
-    swaps+=(/dev/mapper/$s)
-    cat >>/tmp/fai/crypttab <<EOF
-crypt_dev_${dev##/dev/}$rootn  $dev$rootn  none  keyscript=/root/keyscript,discard,luks
-$s $dev$swapn  /dev/urandom  swap,cipher=aes-xts-plain64,size=256,hash=ripemd160
+    cat >/tmp/fai/disk_var.sh <<EOF
+BOOT_DEVICE="${short_devs[@]}"
+ROOT_PARTITION=$first_boot_dev
 EOF
-    cat >> /tmp/fai/fstab <<EOF
-/dev/mapper/$s  none  swap  sw  0 0
+else
+    # note, fai creates the mountpoints listed here
+    cat > /tmp/fai/fstab <<EOF
+$first_root_crypt  /  btrfs  noatime,subvol=root_$DISTRO  0 0
+$first_root_crypt  /mnt/root  btrfs  noatime,subvolid=0  0 0
+$first_boot_dev  /boot  btrfs  noatime,subvol=$boot_vol  0 0
 EOF
-done
+    swaps=()
+    for dev in ${devs[@]}; do
+        swaps+=(`swap-cryptname`)
+        cat >>/tmp/fai/crypttab <<EOF
+`root-cryptname`  `rootdev`  none  keyscript=/root/keyscript,discard,luks
+`swap-cryptname` `swapdev`  /dev/urandom  swap,cipher=aes-xts-plain64,size=256,hash=ripemd160
+EOF
+        cat >> /tmp/fai/fstab <<EOF
+`swap-cryptdev`  none  swap  sw  0 0
+EOF
+    done
 
+    # fai would do this:
+    #BOOT_DEVICE=\${BOOT_DEVICE:-"${devs[0]}"}
 
-# swaplist seems to do nothing.
-cat >/tmp/fai/disk_var.sh <<EOF
-ROOT_PARTITION=\${ROOT_PARTITION:-$crypt}
+    # note: swaplist seems to do nothing.
+    cat >/tmp/fai/disk_var.sh <<EOF
+BOOT_DEVICE="${short_devs[@]}"
 BOOT_PARTITION=\${BOOT_PARTITION:-$first_boot_dev}
-BOOT_DEVICE=\${BOOT_DEVICE:-"${devs[0]}"}
+# ROOT_PARTITIONS is added by me, used in arch setup.
+ROOT_PARTITIONS="${root_devs[@]}"
+ROOT_PARTITION=\${ROOT_PARTITION:-$first_root_crypt}
 SWAPLIST=\${SWAPLIST:-"${swaps[@]}"}
 EOF
+fi