Saturday, November 10, 2012

Linux Swap Create Init Script

I use an SSD as my primary drive.  I used to have a swap partition on it (I know, bad idea on SSD) and it had probs w/ data corruption and the swap randomly being disabled.  Linux supports trim for SSDs, but trim won't do anything for swap that's always on a specific set of blocks in the SSD...

If we need swap space, but don't want it to always hit the same part of the SSD, we should be able to use a swap file in /tmp, allocating 2GB at boot. At least in Ubuntu, /tmp is cleaned up each boot, so when we create our swap file, trim has the opportunity to put the file on some fresh SSD sectors.

Here's the init script for this:


#!/bin/sh
#
# setup swap file init script
#

### BEGIN INIT INFO
# Provides:          atop
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Should-Start:      $local_fs
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Monitor for system resources and process activity
# Description:       Atop is an ASCII full-screen performance monitor,
#                    similar to the top command, but atop only shows
#                    the active system-resources and processes, and
#                    only shows the deviations since the previous
#                    interval.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
SWAPFILE=/tmp/swapfile
NAME=init_swap.sh
DESC="tmp swapfile creator"

case "$1" in
        start)
                echo -n "Starting $DESC: "
                if $0 status >/dev/null
                then
                        echo "    Already Running."
                        exit 0
                fi

                test -f ${SWAPFILE} && rm ${SWAPFILE}
                dd if=/dev/zero of=${SWAPFILE} bs=1M count=2048
                mkswap ${SWAPFILE}
                swapon ${SWAPFILE}
                echo "        Done."
                ;;
        stop)
                echo -n "Stopping $DESC: "
                $0 status >/dev/null && swapoff ${SWAPFILE}
                test -f ${SWAPFILE} && rm ${SWAPFILE}
                echo "        Done."
                exit 0
                ;;
        status)
                if swapon -s | grep -q ^/tmp/swapfile
                then
                        echo "Swap is enabled"
                        exit 0
                else
                        echo "Swap is not enabled"
                        exit 1
                fi
                ;;
        *)
                N=/etc/init.d/$NAME
                echo "Usage: $N {start|status}" >&2
                exit 1
                ;;
esac

exit 0