#!/bin/bash MAIN_LVMS="backups" VGS=LVM SNAPSHOTS_SIZE=10G SNAPSHOTS_CYCLE=10 SUFFIX=_snapshot_ function error() { echo -e "Subject: [$(cat /etc/hostname)] Error rotating LVM snapshots\n\nOn $(date)\nError: $1\n" | sendmail root echo "ERROR: $1" exit 1 } # some functions function removeSnapshot() { local name=$1${SUFFIX}$2 echo "Removing snapshot $name" lvremove -f $VGS/$name || error "Removing Snapshot $name" } function updateSnapshot() { local from=${1}${SUFFIX}$2 local to=${1}${SUFFIX}$(($2+1)) echo "Rename snapshot $from -> $to" lvrename $VGS $from $to || error "Updating Snapshot $from -> $to" } function createSnapshot() { local name=${1}${SUFFIX}1 echo "Create snapshot $name" lvcreate --snapshot --size $SNAPSHOTS_SIZE --name $name /dev/$VGS/$1 || error "Creating the new snapshot $name" } function rotateSnapshot() { # calc the number of current snapshots local current=$(lvs --noheadings | grep ${1}${SUFFIX} | wc -l ) echo "Number of snapshots: $current" # discard the latests snapshot if [ $current -ge $SNAPSHOTS_CYCLE ]; then echo "Discarding Snapshots..." for i in $(seq $current -1 $SNAPSHOTS_CYCLE) ; do removeSnapshot $1 $i current=$(( $current - 1 )) done fi # rotate snapshots if [ $current -gt 0 ]; then echo "Rotating Snapshots..." for i in $(seq $current -1 1); do updateSnapshot $1 $i done fi # create new snapshot createSnapshot $1 } for l in $MAIN_LVMS; do rotateSnapshot $l done