Advertisement
devinteske

zsnap.sh

Jun 12th, 2017
763
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.62 KB | None | 0 0
  1. #!/bin/sh
  2. ############################################################ CONFIGURATION
  3.  
  4. #
  5. # Create snapshot if delta becomes at least this many bytes
  6. #
  7. MIN_SIZE=$(( 1024 * 1024 * 10 )) # 10MB
  8.  
  9. #
  10. # Create snapshot if previous is at least this old
  11. #
  12. MIN_AGE=$(( 3600 * 24 )) # 24 hours
  13.  
  14. #
  15. # Snapshot name
  16. #
  17. SNAPNAME_FORMAT="zsnap-%Y-%m-%d_%H.%M.%S"
  18.  
  19. ############################################################ MAIN
  20.  
  21. set -e # make any/all errors fatal
  22.  
  23. #
  24. # Get current epoch and pre-create snapname
  25. #
  26. now=$( date +%s )
  27. newsnapname=$( date -r $now +"$SNAPNAME_FORMAT" )
  28.  
  29. #
  30. # Operate on the datasets
  31. #
  32. for dataset in $( zfs list -Ht filesystem | awk '$0=$1' ); do
  33.     #
  34.     # Get the date/time and name of the most recent snapshot for dataset
  35.     #
  36.     read -r creation snapname <<-EOF
  37.     $( zfs get -pHrt snapshot creation "$dataset" 2> /dev/null |
  38.         awk -v dataset="$dataset" '
  39.         BEGIN { last_epoch = 0 }
  40.         (ds = $1) sub(/@.*/, "", ds) && ds == dataset {
  41.             if ((epoch = $--NF) < last_epoch) next
  42.             last_epoch = epoch
  43.             last_snapshot = $1
  44.             sub(/^[^@]*@/, "", last_snapshot)
  45.         }
  46.         END { print last_epoch, last_snapshot }
  47.     ' | sort -nr )
  48.     EOF
  49.  
  50.     #
  51.     # Skip filesystem if still young and few bytes written
  52.     #
  53.     age=$(( $now - $creation ))
  54.     written=$( zfs get -Hp written "$dataset" | awk '{print $--NF}' )
  55.     [ $age -lt $MIN_AGE -a $written -lt $MIN_SIZE ] && continue
  56.  
  57.     #
  58.     # Create new snapshot
  59.     #
  60.     echo "zfs snapshot $dataset@$newsnapname"
  61. done
  62.  
  63. ################################################################################
  64. # END
  65. ################################################################################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement