#!/bin/bash if [[ $EUID -ne 0 ]]; then echo "This script must be run as root" exit 1 fi if [ -z "${MONGO_PASSWORD}" ]; then echo "You need to set then environment variable MONGO_PASSWORD" exit 1 fi COMMAND=${1} if [ -z "${COMMAND}" ]; then echo "Please pass one of the following commands: create, restore, remove." exit 1 fi MONGO_VOLUME="/dev/host-vg/mongo-data" MONGO_SNAPSHOT_VOLUME="/dev/host-vg/mongo-snapshot" MONGO_USER="administrator" MONGO_CMD="/usr/bin/mongo --username $MONGO_USER --password $MONGO_PASSWORD --authenticationDatabase admin --quiet" function print_error() { RED="\033[0;31m" NC="\033[0m" message=$1 echo -e "${RED}${message}${NC}" } function create_snapshot() { echo -n "Locking database before creating snapshot. You're using MongoDB " $MONGO_CMD --eval "db.version();" $MONGO_CMD -eval "d=db.fsyncLock(); printjson(d.info);" | sed s/\"//g >/dev/null 2>&1 if [ $? -ne 0 ]; then print_error " Error: Could not lock DB. Aborting." exit 1 else echo "Database is locked for creating snapshot." fi lvcreate -L 10GB --snapshot -n mongo-snapshot ${MONGO_VOLUME} if [ $? -ne 0 ]; then print_error "Creation of snapshot failed" else echo "Snapshot created successfully" fi echo -en " Unlocking MongoDB. " $MONGO_CMD -eval "d=db.fsyncUnlock(); printjson(d);" >/dev/null 2>&1 mkdir -p /mongo-snapshot echo "You can mount the snapshot with mount -t xfs -o nouuid ${MONGO_SNAPSHOT_VOLUME} /mongo-snapshot" lvdisplay ${MONGO_SNAPSHOT_VOLUME} } function remove_snapshot() { echo "Removing snapshot ${MONGO_SNAPSHOT_VOLUME}..." lvremove ${MONGO_SNAPSHOT_VOLUME} } function restore_snapshot() { echo -n "Do you really want to restore the snapshot (y/n)? " read answer if [ "${answer}" == "y" ]; then echo "Unmounting mongodb volume and restoring snapshot..." unmount ${MONGO_VOLUME} lvconvert --merge ${MONGO_SNAPSHOT_VOLUME} fi } case "${COMMAND}" in "create" ) create_snapshot;; "restore" ) restore_snapshot;; "remove" ) remove_snapshot;; *) print_error "The command ${COMMAND} is not supported..." ;; esac