Mongo Backup

#!/bin/sh

# This script is run on every mongo node. However, it checks to see if this node is the primary mongo node.
# If it is, mongo db is backed up and deleted the user session collection files.
# If this node is not primary mong node, nothing is done.

MONGO_BACKUP_FOLDER=/backup/mongo-prod

HOST_IP=`/sbin/ifconfig | sed -n 's/.*inet addr:\([0-9.]\+\)\s.*/\1/p' | head -n1`
echo "HOST_IP: " $HOST_IP

HOST_NAME=`hostname`
echo "HOST_NAME: " $HOST_NAME

IS_PRIMARY=`mongo --quiet $HOST_IP --eval "print(db.isMaster().ismaster);"`
echo "IS_PRIMARY: " $IS_PRIMARY

PRIMARY_HOST=`mongo --quiet $HOST_IP --eval " var primary = db.isMaster().primary;
if(primary && primary.indexOf(':') > 0 ) primary = primary.substring(0, primary.indexOf(':'));
print(primary);"`
if [ $PRIMARY_HOST == "undefined" ]
then
    PRIMARY_HOST=`hostname`
fi
echo "PRIMARY_HOST: " $PRIMARY_HOST

if [ "${IS_PRIMARY}" == "false" ]
then
    echo "$PRIMARY_HOST is primary mongo node. Backing up data...."
    BACKUP_FOLDER=`date +'%Y-%m-%d_%H%M%S'`
    BACKUP_DIR=$MONGO_BACKUP_FOLDER/$BACKUP_FOLDER/$PRIMARY_HOST

    mkdir -p $BACKUP_DIR
    cd $BACKUP_DIR
    echo "PWD:" `pwd`

    EXPORT_RESULT=`mongodump -h $HOST_IP`
    echo "Backed up data in $BACKUP_DIR"

    #delete user session collection
    if [ -d ${BACKUP_DIR}/dump/sxa ]
    then
        if [ -f  ${BACKUP_DIR}/dump/sxa/userSessionCollection.bson ]
        then
            rm -f ${BACKUP_DIR}/dump/sxa/userSessionCollection.bson
            echo "Deleted user session data bson"
        fi
        if [ -f  ${BACKUP_DIR}/dump/sxa/userSessionCollection.metadata.json ]
        then
            rm -f ${BACKUP_DIR}/dump/sxa/userSessionCollection.metadata.json
            echo "Deleted user session metadata json"
        fi
    fi

    KEEP_DAYS=15
    #Delete back-up folder olders than KEEP_DAYS
    echo "Removing backup data older than $KEEP_DAYS days....."
    find $MONGO_BACKUP_FOLDER -mtime +$KEEP_DAYS -exec rm {} \;
    echo "Done removing backup data older than $KEEP_DAYS days"
else
    echo "$HOST_NAME is not primary mongo server ($PRIMARY_HOST is primary). Back-ups are run only on the primary."
fi

echo "Complete!!!"

 

转载于:https://www.cnblogs.com/tben/p/8985041.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值