MongoDB graceful shutdown script.
[root@hostname bin]$ cat new_shutdown.sh
#!/bin/bash
BIN=/tmp/mongodb/bin
DB=admin
HOST=`hostname`
cd $BIN
MONGOPID=`ps -ef | egrep 'mongod|mongos' | grep -v egrep | awk '{print $2}'`
if [ -z $MONGOPID ];
then echo "There are no Mongo processes are running, shutdown script has nothing to do now";
exit;
fi
####################### To stop Router Services #################################################################
for i in `ps -ef | grep 'mongos' | grep -v grep | awk '{print $2}'`;
do
kill -9 $i;
echo "Router service with PID $i has been stopped";
done
#### Identifying the Primary, Secondary, Config & Arbiter service port numbers #####
port=`ps -ef | grep 'shardsvr' | grep -v grep | awk -F "--port " '{print $2}' | cut -d' ' -f1 | head -1`
PRIMARYPORT=`$BIN/mongo --port $port --eval "printjson(rs.isMaster())" | grep "primary" | cut -d: -f3 | cut -d'"' -f1`
SECONDARYPORTS=`ps -ef | grep 'shardsvr' | grep -v grep | awk -F "--port " '{print $2}' | cut -d' ' -f1 | grep -v $PRIMARYPORT`
CONFIGPORTs=`ps -ef | grep mongo | grep 'configsvr' | awk -F "--port " '{print $2}' | cut -d' ' -f1`
ARBITERPORT=`$BIN/mongo --port $port --eval "printjson(rs.status())"|grep -B 3 ARBITER|head -1|awk -F":" '{print $3}'|awk -F"\"" '{print $1}'`
#### To check the nodes health #####
HEALTH=`$BIN/mongo $HOST:$PRIMARYPORT/admin --eval "printjson(rs.status())" | grep 'health' | grep -v '"health" : 1,'`
if [ -z $HEALTH ];
then echo "Your Replica set nodes are in Good Health."
else echo "It seems, one/more node server are not in good health, please check & fix them.";
exit;
fi
#### To lock the writes on Primary ######
$BIN/mongo $HOST:$PRIMARYPORT/admin --eval "db.fsyncLock()"
#### To check the Replciation Lag ######
lag=`$BIN/mongo $HOST:$PRIMARYPORT/admin --eval "printjson(rs.status())" | grep "optimeDate" |sort -u|wc -l`
while [ $lag -ne 1 ]
do
sleep 5
lag=`$BIN/mongo $HOST:$PRIMARYPORT/admin --eval "printjson(rs.status())" | grep "optimeDate" |sort -u|wc -l`
done
##### To get the Secondaries' Ports ####
for i in $SECONDARYPORTS
do
$BIN/mongo localhost:$i/admin --eval "db.shutdownServer()";
done
##### To unlock the write lock and shutdown Primary #####
$BIN/mongo $HOST:$PRIMARYPORT/admin --eval "db.fsyncUnlock()";
$BIN/mongo localhost:$PRIMARYPORT/admin --eval "db.shutdownServer()";
#### To stop the Config servers ######
for i in $CONFIGPORTs
do
$BIN/mongo localhost:$i/admin --eval "db.shutdownServer()";
done
#### To stop Arbiter service ######
$BIN/mongo localhost:$ARBITERPORT/admin --eval "db.shutdownServer()";
[root@hostname bin]$
Ask Question