From ad7be843cc87beec1cd1a3ca486963b7f16b7f19 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Wed, 5 Feb 2020 05:48:37 +0100 Subject: [PATCH] Add zfs_snapshot_cron.sh --- zfs_snapshot_cron.sh | 79 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100755 zfs_snapshot_cron.sh diff --git a/zfs_snapshot_cron.sh b/zfs_snapshot_cron.sh new file mode 100755 index 0000000..2b454e6 --- /dev/null +++ b/zfs_snapshot_cron.sh @@ -0,0 +1,79 @@ +#!/bin/bash + +PREFIX="zsc-" +CONFIG_FILE="$HOME/.zfs_snapshot_cron" + +FORMAT='+%Y-%m-%d' +DATE=$(date $FORMAT) + +split_date() { + echo "$1" | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\1\n\2\n\3/' +} + +handle_pool() { + POOL=$1 + D=$2 + W=$3 + M=$4 + Y=$5 + echo "--- $POOL --- $D $W $M $Y" + + SNAPSHOTS=($(zfs list -t snapshot -o name | grep "$POOL@$PREFIX" | sort -r)) + echo "Snapshots: ${#SNAPSHOTS[@]}" + + EXISTS=0 + + for s in "${SNAPSHOTS[@]}"; do + sdate=$(echo "$s" | awk 'match($0, /.+@'"$PREFIX"'(.+)/, a) {print a[1]}') + + if [ "$sdate" = $DATE ]; then + EXISTS=1 + fi + + scomp=($(split_date "$sdate") $(date -d "$sdate" "+%u %W")) + + echo -n "${scomp[3]} ${scomp[4]} | " + + echo -n "${sdate}: " + + if [ $D -gt 0 ]; then + D=$(( D-1 )) + echo "KEEP; D: $D" + elif [ $W -gt 0 ] && [ ${scomp[3]} -eq 1 ]; then + W=$(( W-1 )) + echo "KEEP; W: $W" + elif [ $M -gt 0 ] && [ ${scomp[3]} -eq 1 ] && [ $(( scomp[4] % 4 )) -eq 0 ]; then + M=$(( M-1 )) + echo "KEEP; M: $M" + elif [ $Y -gt 0 ] && [ ${scomp[3]} -eq 1 ] && [ ${scomp[4]} -eq 4 ]; then + Y=$(( Y-1 )) + echo "KEEP; Y: $Y" + else + zfs destroy "$s" + echo "DISCARD" + fi + done + + if [ $EXISTS -eq 0 ]; then + echo -e "Creating snapshot $POOL@$PREFIX$DATE" + zfs snapshot $POOL@$PREFIX$DATE + fi +} + +cat "$CONFIG_FILE" | while IFS=: read pool recursive d w m y; do + echo "| ##### Pool: $pool Recursive: $recursive d: $d w: $w m: $m y: $y #####" + + if [ $recursive = "true" ]; then + SUBPOOLS=($(zfs list -o name | grep "$pool/")) + echo -e "Subpools: ${SUBPOOLS[@]}" + echo -e '|' + for p in "${SUBPOOLS[@]}"; do + handle_pool $p $d $w $m $y | awk '{print "| " $0}' + echo -e '|' + done + fi + + handle_pool $pool $d $w $m $y | awk '{print "| " $0}' + + echo -e "----------------------------------------------------------------------" +done