MongoDB watchdog simple control script.

It often happens that working with different development environments and with a large amount of data on the database, the MongoDB service crashes or does not respond correctly.

MongoDB watchdog simple control script.

mongodb

Below is a simple Linux Bash Script that checks if the MongoDB database is running on your server.

Github https://github.com/garanet/mongowdog

This simple bash script checks if the MongoDB service is running on your server, if the service is not responding, it will automatically start it and notify the event by email.

Create a file named watchdogdb.sh and paste the following code:

~:$ sudo vi /usr/local/bin/watchdogdb.sh

#!/bin/bash
# SEMPLICE WATCHDOG DB
# www.garanet.net

EMAIL=esempio@email.tld;
date=$(date +"%d/%m/%Y");
time=$(date +"%T");
netstat='netstat -an | grep 27017 | wc -l';
nproc="499";
if [[ $(netstat -an | grep 27017 | wc -l) != ${nproc} ]]; then
    echo "mongodb running!"
    exit 0;
else
    echo "mongodb has 499 connections"
    service mongodb restart
    wait
    echo "${date} - $time - MongoDB server is DOWN" >> /tmp/mongocheck.log
    mail -s "Server down: MongoDB" ${EMAIL} < /tmp/mongocheck.log
    wait
    exit 1;
fi

Assign execute privileges to the newly created file:

~:$ sudo chmod a+x /usr/local/bin/watchdogdb.sh

You can insert the following script into a cronjob.

~:$ sudo crontab -e