Skip to content

Instantly share code, notes, and snippets.

@sbimikesmullin
Last active September 15, 2015 21:02
Show Gist options
  • Save sbimikesmullin/a427fdaee2ce447cc848 to your computer and use it in GitHub Desktop.
Save sbimikesmullin/a427fdaee2ce447cc848 to your computer and use it in GitHub Desktop.
Upstart Automatic Swap Recovery
# /etc/init/recover-swap.conf
# author: mike smullin <mike dot smullin at wildworks dot com>
# see also: http://askubuntu.com/a/90399
# usage: start recover-swap; tailf /var/log/upstart/recover-swap.log
#
# WARNING: it is a little bit dangerous to swapoff while your service is still running;
# means OOM killer may come reap your process if it need to swap again while swapoff is going,
# which does take over an hour in our case.
#
respawn
start on startup
stop on shutdown
script
log(){
echo "`date --rfc-3339=ns` $1";
}
while true; do
free_data="$(free)"
mem_data="$(echo "$free_data" | grep 'Mem:')"
free_mem="$(echo "$mem_data" | awk '{print $4}')"
buffers="$(echo "$mem_data" | awk '{print $6}')"
cache="$(echo "$mem_data" | awk '{print $7}')"
total_free=$((free_mem + buffers + cache))
used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')"
log "Free: $total_free kB ($((total_free / 1024)) MB), Swap: $used_swap kB ($((used_swap / 1024)) MB)"
if [ $used_swap -eq 0 ]; then
log "No swap is in use. Will check later.";
elif [ $used_swap -lt $total_free ]; then
log "Swap in use, and enough free memory. Freeing swap...";
swapoff -a;
swapon -a;
log "Done.";
else
log "Swap in use, but not enough free memory. Will try later.";
fi
sleep 3600; # retry once an hour
done;
end script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment