From 319c9c44f05be8b05eddd556c215dd13e3fa09e5 Mon Sep 17 00:00:00 2001 From: Clark Boylan Date: Tue, 16 Jul 2019 09:07:30 -0700 Subject: [PATCH] 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 --- make_swap.sh | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/make_swap.sh b/make_swap.sh index 0713cf8905..259aa68a6b 100644 --- a/make_swap.sh +++ b/make_swap.sh @@ -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