Skip to content

Instantly share code, notes, and snippets.

@m87h
Created July 7, 2013 15:02
Show Gist options
  • Save m87h/5943735 to your computer and use it in GitHub Desktop.
Save m87h/5943735 to your computer and use it in GitHub Desktop.
#!/bin/bash
CONFIG_FILE="/etc/backup.conf"
print_error() {
echo "error: $1" 1>&2;
}
source $CONFIG_FILE 2>/dev/null || { print_error "could not read config file $CONFIG_FILE"; exit 127; }
volume_node() {
echo "/dev/mapper/$1"
}
check_requirements() {
local ret node
ret=0
[[ $EUID -eq 0 ]] || { print_error "this script must be run as root"; ret=1; }
which lvcreate > /dev/null || { print_error "lvm tools not in PATH"; ret=2; }
which duplicity > /dev/null || { print_error "duplicity not in PATH"; ret=2; }
if [ -z "$1" ]; then
print_error "must specify a volume to back up"
ret=3;
else
node=$(volume_node $1)
lvdisplay $node 2>&1 > /dev/null || { print_error "$node is not an LVM volume"; ret=3; }
fi
return $ret
}
create_snapshot() {
lvcreate --verbose --size $2 -s $(volume_node $1) 2>&1 | grep -o -E \".*\" | tr -d \" | paste -s | awk '{print "/dev/"$1"/"$5}'
}
mount_snapshot() {
local mountpoint
mountpoint="/mnt/backup/$2"
mkdir -p $mountpoint
mount -r $1 $mountpoint
echo $mountpoint
}
duplicity_do() {
local cache
cache="/var/cache/duplicity"
for e in $BACKUP_EXCLUDES; do echo "./$e"; done \
| AWS_ACCESS_KEY_ID=$BACKUP_AWS_KEY AWS_SECRET_ACCESS_KEY=$BACKUP_AWS_SECRET PASSPHRASE= duplicity \
--exclude-device-files --exclude-other-filesystems --exclude-if-present "./$cache" --exclude-filelist-stdin \
--archive-dir $cache --encrypt-secret-keyring $BACKUP_KEYRING --encrypt-sign-key $BACKUP_KEY \
--extra-clean --full-if-older-than $BACKUP_INTERVAL_FULL --s3-european-buckets --s3-unencrypted-connection \
--s3-use-new-style --s3-use-rrs --s3-use-multiprocessing --asynchronous-upload --extra-clean "$@"
}
backup() {
(cd $1; duplicity_do incremental . $2)
duplicity_do remove-older-than ${BACKUP_RETENTION:-3M} --force $2
duplicity_do cleanup --force $2
}
backup_to_s3() {
backup $1 "s3://s3-eu-west-1.amazonaws.com/$BACKUP_BUCKET/$(basename $1)"
}
unmount_snapshot() {
umount -f $1
rm -rf $1
}
remove_snapshot() {
lvremove -f $1 > /dev/null
}
VOLUME=$(basename $1 2>/dev/null)
SNAPSHOT_SIZE=${2:-1G}
check_requirements $VOLUME || exit $?
SNAPSHOT=$(create_snapshot $VOLUME $SNAPSHOT_SIZE)
SNAPSHOT_MOUNT=$(mount_snapshot $SNAPSHOT $VOLUME)
backup_to_s3 $SNAPSHOT_MOUNT
unmount_snapshot $SNAPSHOT_MOUNT
remove_snapshot $SNAPSHOT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment