Use swapfile if no extra device is present

We are booting instances outside of rax and they don't always come with
extra devices that can be repurposed for swap. If in that case then
create a swapfile instead.

Note we do not use fallocate as swapon's manpage says this is suboptimal
with the linux kernel's swap implementation.

Change-Id: I8b9ce18c18e4069aba7de27bb6a9927627b15b49
This commit is contained in:
Clark Boylan 2019-07-16 09:07:30 -07:00
parent 4e050d981e
commit 319c9c44f0
1 changed files with 16 additions and 5 deletions

View File

@ -21,13 +21,14 @@ if [ `grep SwapTotal /proc/meminfo | awk '{ print $2; }'` -eq 0 ]; then
elif [ -b /dev/xvde ]; then
DEV='/dev/xvde'
fi
SWAPFILE=/swapfile
MEMKB=`grep MemTotal /proc/meminfo | awk '{print $2; }'`
# Use the nearest power of two in MB as the swap size.
# This ensures that the partitions below are aligned properly.
MEM=`python3 -c "import math ; print(2**int(round(math.log($MEMKB/1024, 2))))"`
# Avoid using config drive device for swap
if [ -n "$DEV" ] && ! blkid | grep $DEV | grep TYPE ; then
MEMKB=`grep MemTotal /proc/meminfo | awk '{print $2; }'`
# Use the nearest power of two in MB as the swap size.
# This ensures that the partitions below are aligned properly.
MEM=`python3 -c "import math ; print(2**int(round(math.log($MEMKB/1024, 2))))"`
if mount | grep ${DEV} > /dev/null; then
echo "*** ${DEV} appears to already be mounted"
echo "*** ${DEV} unmounting and reformating"
@ -61,6 +62,16 @@ if [ `grep SwapTotal /proc/meminfo | awk '{ print $2; }'` -eq 0 ]; then
perl -nle "m,${DEV}, || print" -i /etc/fstab
echo "${DEV}1 none swap sw 0 0" >> /etc/fstab
echo "${DEV}2 /opt ext4 errors=remount-ro,barrier=0 0 2" >> /etc/fstab
mount -a
elif [ ! -f "$SWAPFILE" ] ; then
# We don't have real devices to use so we make a swap file instead.
# Note you can skip this by precreating /swapfile.
# bs here is 1Mb
sudo dd if=/dev/zero of=${SWAPFILE} bs=1048576 count=${MEM}
sudo chown root:root $SWAPFILE
sudo chmod 600 $SWAPFILE
sudo mkswap $SWAPFILE
echo "${SWAPFILE} none swap sw 0 0" >> /etc/fstab
fi
swapon -a
mount -a
fi