Last active
January 3, 2022 16:00
-
-
Save isaaclw/22f279d648ee12be212c1fe609b2648d to your computer and use it in GitHub Desktop.
Use LVM Snapshots to rollback Postgresq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This was to create a quick snapshot of the database, make the changes I | |
# wanted, and then revert the database to exactly the way it was before I | |
# snapshotted it. | |
LV=pg_ot | |
VG=$(/sbin/vgdisplay -s | sed -e 's/ "\([^"]*\)" .*/\1/') | |
MTPT=/var/lib/postgresql/11/main | |
PROC=postgres | |
VERSION=11 | |
SIZE=100G | |
LVM_DEV="/dev/$VG/$LV" | |
LVM_SNAP="$LVM_DEV-snap" | |
if [ "$(whoami)" != "root" ]; then | |
echo "Run as root!" | |
exit 1 | |
fi | |
un_mount () { | |
mount | grep "$MTPT" | cut -d' ' -f 3 | sort -r | while read dir; do | |
while findmnt "$dir" > /dev/null; do | |
echo "found $dir to unmount" | |
umount "$dir" || { echo "relevant processes: "; lsof +D "$dir" 2>/dev/null; } | |
/sbin/fsck -fy "$LVM_DEV" | |
sleep 2 | |
done | |
done | |
} | |
start_snapshot() { | |
un_mount | |
lvcreate --snapshot --size $SIZE --name $LV-snap "$LVM_DEV" | |
mount "$LVM_SNAP" "$MTPT" 2>/dev/null | |
} | |
stop_snapshot() { | |
un_mount | |
/sbin/lvremove --force "$LVM_SNAP" | |
mount "$LVM_DEV" "$MTPT" 2>/dev/null | |
} | |
startproc() { | |
pg_ctlcluster $VERSION main start | |
/etc/init.d/pgpool2 restart | |
} | |
stopproc() { | |
/etc/init.d/pgpool2 stop | |
pg_ctlcluster $VERSION main stop | |
sleep 2 | |
} | |
case $1 in | |
start) | |
if [ -b "$LVM_SNAP" ]; then | |
echo "Already set up" | |
exit 1 | |
fi | |
stopproc | |
start_snapshot | |
systemctl start postgresql | |
startproc | |
;; | |
stop) | |
if ! [ -b "$LVM_SNAP" ]; then | |
echo "None Exists" | |
exit 1 | |
fi | |
stopproc | |
stop_snapshot | |
startproc | |
;; | |
restart) | |
stopproc | |
stop_snapshot | |
start_snapshot | |
startproc | |
;; | |
*) | |
echo "start|stop|restart"; | |
;; | |
esac; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment