echo "

Swap clean up script (update)

Today I had a machine that had no swap space left which in return triggered a monitoring alert. Since the pressure was already gone but the swap wasn't cleared fast enough I searched and found this script as a nice solution. The script was a bit older and was made for a version of free that seperated buffers and caches. In newer versions they are combined as "buff/cache" and a new field is introduced that shows the combined available memory. Which gave me a chance to simplify the script.


free_mem="$(free | grep 'Mem:' | awk '{print $7}')"
used_swap="$(free | grep 'Swap:' | awk '{print $3}')"

echo -e "Free memory:\t$free_mem kB ($((free_mem / 1024)) MiB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MiB)"
if [[ $used_swap -eq 0 ]]; then
    echo "Congratulations! No swap is in use."
elif [[ $used_swap -lt $free_mem ]]; then
    echo "Freeing swap..."
    sudo swapoff -a
    sudo swapon -a
    echo "Not enough free memory. Exiting."
    exit 1

 Thx Scott Severance for the initial script

Automatically clean up logs with a cron job

Since a lot of our applications generate enormous log files while running on Tomcat, Play, ... We have to intervene and clean them up and since zipping those logs makes a huge improvement on disk space consumption this is how I do it. Of course you can use ZFS with native disk compression too :)

I install this cron (as the user that runs the application). It will clean up all the logs that aren't in use and will clean up the archived logs after 30 days. And the neat thing is that recent versions of Vim kan still read the log while zipped, deflating it on the fly.

find /opt/ -type f \( -mtime +30 -iname "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].log.gz" -exec rm -f {} \; -o -iname "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].log" -exec gzip {} \; \)