core-agent-linux/init/resize-rootfs-if-needed.sh
AJ Jordan 593724c05b
Use dumpe2fs for filesystem size calculations
The previous approach used `df` to get usable space and then added a
fixed size to that number in order to account for filesystem
overhead. However, at some point that stopped working for me. It
appears that ext4 filesystem overhead can vary over time or because of
other factors. (Certainly now that I think about it the old code would
only work well for people with the exact same filesystem size as me.)

So the new approach is to just completely ignore what `df` tells us
and instead go directly to the source: the filesystem's internal
notion of exactly how much space it takes up. We use `dumpe2fs` to
retrieve this information and calculate the on-disk size dynamically
from that. Then we add the space that boot data takes up (unchanged),
and we add 5MB padding because when I tested this it didn't quite add
up otherwise. https://unix.stackexchange.com/a/13551/29146 suggests
that this unaccounted-for data may be e.g. additional copies of the
superblock.
2019-02-07 16:04:11 -05:00

37 lines
1.3 KiB
Bash
Executable File

#!/bin/sh
# Possibly resize root device (partition, filesystem), if underlying device was
# enlarged.
set -e
# if underlying root device is read-only, don't do anything
if [ "$(blockdev --getro /dev/xvda)" -eq "1" ]; then
echo "xvda is read-only, not resizing" >&2
exit 0
fi
sysfs_xvda="/sys/class/block/xvda"
# if root filesystem is already using (almost) the whole disk
# 203M for BIOS and /boot data
boot_data_size=$((203 * 2 * 1024))
# rootfs size is calculated on-the-fly. `df` doesn't work because it doesn't
# include fs overhead, and calculating a static size for overhead doesn't work
# because that can change dynamically over the filesystem's lifetime.
# See QubesOS/qubes-core-agent-linux#146 and QubesOS/qubes-core-agent-linux#152
# for more details
ext4_block_count=$(dumpe2fs /dev/mapper/dmroot | grep '^Block count:' | sed -E 's/Block count:[[:space:]]+//')
ext4_block_size=$(dumpe2fs /dev/mapper/dmroot | grep '^Block size:' | sed -E 's/Block size:[[:space:]]+//')
rootfs_size=$((ext4_block_count * ext4_block_size / 512))
# 5 MB in 512-byte units for some random extra bits
size_margin=$((5 * 1024 * 2))
if [ "$(cat $sysfs_xvda/size)" -lt \
$(( rootfs_size + boot_data_size + size_margin )) ]; then
echo "root filesystem already at $rootfs_size blocks" >&2
exit 0
fi
# resize needed, do it
/usr/lib/qubes/resize-rootfs