#!/bin/sh # quick and dirty script for checking dates of zfs snapshots and removing old snapshots # achtung, this is made with FreeBSD's `date', won't work with gnuuuu and other `date's... # rev 1.5 lopez@yellowspace.net 11.12.2007 # abstract: # given pool $POOL, check if available space is less than $MINSPACE. # If yes, remove snapshots $KEEPTIME days older than the newest one MINSPACE=20 # in GigaBytes KEEPTIME=15 # in days POOL="zentank" giveStamp() { /bin/date -j -f "%a %b %d %T %Z %Y" "$1" "+%s" } removeSnap() { if [ "$3" = "-v" ] ; then echo "Removing $1, it is old, made on $2"; fi snaponly=`echo "$1" | /usr/bin/egrep -c '@.+'` if [ $snaponly -gt 0 ] ; then /sbin/zfs destroy "$1" else echo "$1 is not a valid snapshot name, dont destroy your pool! *g*" exit 1 fi } # see how many gigs are available availgigs=`/sbin/zfs list -H -o available $POOL | /usr/bin/tr 'G' ' '` if [ $availgigs -gt $MINSPACE ] ; then if [ "$1" = "-v" ] ; then echo "$availgigs GB available, $MINSPACE required, no need to delete"; fi exit 0 fi # get the timestamp of the newest snapshot # damned list verb does not accept a pool name with -t snapshot lastsnapdate=`/sbin/zfs list -t snapshot -H -o name,creation -s creation | \ /usr/bin/egrep "^${POOL}" | \ /usr/bin/cut -f 2 | \ /usr/bin/tail -n 1` lastsnapstamp=`giveStamp "$lastsnapdate"` subtrsec=$((KEEPTIME*86400)) minstamp=$((lastsnapstamp-subtrsec)) # minstamp=`/bin/date -j -v -${KEEPTIME}d +%s` # older than KEEPTIME from now removedsomething=0 /sbin/zfs list -t snapshot -H -o name,creation -s name | /usr/bin/egrep "^${POOL}" | while read snapname snapdate ; do if [ "$1" = "-v" ] ; then echo "Name: $snapname, Date is $snapdate"; fi stamp=`giveStamp "$snapdate"` if [ $stamp -lt $minstamp ] ; then removeSnap "$snapname" "$stamp" "$1" removedsomething=1 fi done if [ $removedsomething -eq 0 ] ; then echo -n "WARNING: $0 did not find snapshots of $POOL older than $KEEPTIME days, " echo "yet available space is $availgigs, which is below $MINSPACE." exit 1 fi exit 0