How to check whether MongoDB is running from a shell script? - mongodb

Here is the shell script that I am using to check MongoDB's status. checkmongo.sh through a cron job every two minutes.
#!/bin/bash
echo "shell script called"
if pgrep mongo > /dev/null
then
echo "MongoDB Running"
else
echo "Stopped .. starting MongoDB"
sudo service mongodb start
fi
Cron job is as follows :
*/2 * * * * /etc/init.d/checkmongo.sh> /etc/init.d/cronjob.log 2>&1
No matter MongoDb is running or not cronjob.log always has the content as "MongoDB Running". What am I doing wrong ? Please help. Thanks

Vinay,
A couple of things:
1 -- Do you want to check if MongoDB is running or do you want to check if it is responding to queries?
Your current design will only tell if there is a process whose name includes the word "mongo" running.
I would design a "canary query" that you can run with the mongo shell and use the result to determine if MongoDB is running or not. So in the rare case where MongoDB daemon might be running but not responsive you could be alerted.
2 --Your process is checking for the word "mongo", the executable for the mongoDB database is "mongod".
Your script is called "checkmongo". Every time you script runs there is a "checkmongo" process running and the if conditions will always be true. The script is detecting itself instead of the mongod process.
Change your search condition to mongod
if pgrep mongod > /dev/null

#!/bin/bash
mongod_status=`service mongod status`
echo "${mongod_status}"
if [[ "${mongod_status}" == *"start/running"* ]]
then
echo "MongoDB is already running."
else
sudo service mongod start
echo "Start MongoDB."
fi

Related

Upstart / init script not working

I'm trying to create a service / script to automatically start and controll my nodejs server, but it doesnt seem to work at all.
First of all, I used this source as main reference http://kvz.io/blog/2009/12/15/run-nodejs-as-a-service-on-ubuntu-karmic/
After testing around, I minimzed the content of the actual file to avoid any kind of error, resulting in this (the bare minimum, but it doesnt work)
description "server"
author "blah"
start on started mountall
stop on shutdown
respawn
respawn limit 99 5
script
export HOME="/var/www"
exec nodejs /var/www/server/server.js >> /var/log/node.log 2>&1
end script
The file is saved in /etc/init/server.conf
when trying to start the script (as root, or normal user), I get:
root#iof304:/etc/init# start server
start: Job failed to start
Then, I tried to check my syntax with init-checkconf, resulting in:
$ init-checkconf /etc/init/server.conf
File /etc/init/server.conf: syntax ok
I tried different other things, like initctl reload-configuration with no result.
What can I do? How can I get this to work? It can't be that hard, right?
This is what our typical startup script looks like. As you can see we're running our node processes as user nodejs. We're also using the pre-start script to make sure all of the log file directories and .tmp directories are created with the right permissions.
#!upstart
description "grabagadget node.js server"
author "Jeffrey Van Alstine"
start on started mysql
stop on shutdown
respawn
script
export HOME="/home/nodejs"
exec start-stop-daemon --start --chuid nodejs --make-pidfile --pidfile /var/run/nodejs/grabagadget.pid --startas /usr/bin/node -- /var/nodejs/grabagadget/app.js --environment production >> /var/log/nodejs/grabagadget.log 2>&1
end script
pre-start script
mkdir -p /var/log/nodejs
chown nodejs:root /var/log/nodejs
mkdir -p /var/run/nodejs
mkdir -p /var/nodejs/grabagadget/.tmp
# Git likes to reset permissions on this file, but it really needs to be writable on server start
chown nodejs:root /var/nodejs/grabagadget/views/layout.ejs
chown -R nodejs:root /var/nodejs/grabagadget/.tmp
# Date format same as (new Date()).toISOString() for consistency
sudo -u nodejs echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Starting" >> /var/log/nodejs/grabagadget.log
end script
pre-stop script
rm /var/run/nodejs/grabagadget.pid
sudo -u nodejs echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Stopping" >> /var/log/nodejs/grabgadget.log
end script
As of Ubuntu 15, upstart is no longer being used, see systemd.

Why is sleep needed after fabric call to pg_ctl restart

I'm using Fabric to initialize a postgres server. I have to add a "sleep 1" at the end of the command or the postgres server processes die without explanation or an entry in the log:
sudo('%(pgbin)s/pg_ctl -D %(pgdata)s -l /tmp/pg.log restart && sleep 1' % env, user='postgres')
That is, I see this output on the terminal:
[dbserv] Executing task 'setup_postgres'
[dbserv] run: /bin/bash -l -c "sudo -u postgres /usr/lib/postgresql/9.1/bin/pg_ctl -D /data/pg -l /tmp/pg.log restart && sleep 1"
[dbserv] out: waiting for server to shut down.... done
[dbserv] out: server stopped
[dbserv] out: server starting
Without the && sleep 1, there's nothing in /tmp/pg.log (though the file is created), and no postgres processes are running. With the sleep, everything works fine.
(And if I execute the same command directly on target machine's command line, it works fine without the sleep.)
Since it's working, it doesn't really matter, but I'm asking anyway: Does someone know what the sleep is allowing to happen and why?
You might try also using the pty option set it to false and see if it's related to how fabric handles pseudo-ttys.

Repair Mongodb using ruby-mongodb-driver

Is there an API know to anyone to repair mongodb is case of corrupt databases through ruby-mongodb-driver.
Looking through the documentation seem that there isn't
can anyone confirm.
Or can anyone suggest me a better way to repair mongod database .
the currently I knew
./mongod --repair options
./mongo
> use [database]
> db.repairDatabase()
I also see a shell options
./mongo --help
options:
--shell run the shell after executing files
How can I write a script(.js) to repair the given database
For the mongo shell, the database name can be given as an optional argument. Here is a shell script that should make this clear.
repair.sh
#!/bin/sh
if [ $# -lt 1 ]
then echo "$0 - repair mongodb database"
echo "usage: $0 database-name"
exit 1
fi
mongo $1 --eval 'printjson(db.repairDatabase())'
Here is a ruby 1.9 equivalent.
repair.rb
#!/bin/env ruby
require 'mongo'
if ARGV.length < 1
puts "$0 - repair mongodb database"
puts "usage: $0 database-name"
exit 1
end
db = Mongo::Connection.new[ARGV[0]]
puts db.command({repairDatabase: 1})
There's more info in the FAQ and documentation for DB.
http://api.mongodb.org/ruby/current/file.FAQ.html
http://api.mongodb.org/ruby/current/Mongo/DB.html
Navigation to some documentation isn't obvious - we'll look into making it better.

Boto - how do I wait for a background process (e.g. mdadm) to finish before running a new command?

I'm scripting up my amazon deployment, and I haven't managed to automate a step in it.
The step is between setting up RAID (via mdadm) and then installing my db (mongo) on the new mounted directory. This is because I have to wait for mdadm to finish in the background before installing mongo. I know when mdadm is finished by running the following command:
sudo mdadm --detail /dev/md0
When mdadm is still in progress this command will produce a progress indicator e.g.:
Rebuild Status : 2% complete
When mdadm is finished this status will be gone.
Does anyone have a clean solution for being able to tell when mdadm is finished, so that the script can run entirely on its own, and then continue on to install mongo once mdadm is done?
At the moment I'm contemplating placing a script of sorts on the box using boto, running the script from boto, and having the script exit once it parses and reads that mdadm is finished...
Thanks a lot for your help!
I am using:
mdadm --wait /dev/md0
Note that the above command will return a non-zero exit status if it did not have to wait...you might need to take that into account in the script.
Ok... so as I said I'll post up my solution (I'm completely new to writing bash scripts, so if you have any advice for improvement I'm all ears!!!)
#!/bin/bash
false=1
true=0
function drives_are_ready {
RAID_INFO=`sudo mdadm --detail /dev/md0`
rebuild_status_line_count=`echo "$RAID_INFO" | grep "Rebuild Status" | wc -l`
echo `echo "$RAID_INFO" | grep "Rebuild Status"`
if (( rebuild_status_line_count == 0 )); then
return $true
else
return $false
fi
}
drives_are_ready
raid_is_finished=$?
while (( raid_is_finished == $false )); do
echo "RAID isn't finished yet... will check again in 10s"
sleep 10s
drives_are_ready
raid_is_finished=$?
done
echo "RAID is done."
I scp the file to my instance, and then chmod and run the script via boto.
You don't necessarily need to wait for the superblock resynchronization before using the disks, but in my (and I'm sure yours as well) experience, it is a very good idea with ec2 instances.
You could simply check for it in a bash while loop
#!/bin/bash
... stuff in your script that doesn't require raid ...
# Pause until mdadm --detail returns nothing
while [[ `sudo mdadm --detail /dev/md0 | grep 'Rebuild Status'` != '' ]] do
sleep 30
done
echo "Raid superblock resynchronization complete"
... stuff in your script that requires raid synchronization to be complete...

start mongodb and return to terminal

I can start mongodb on terminal via command
./mongod
It starts the mongodb server and then display me information that server is running on this port. but It does not give my terminal back. How can I start mongodb and can get terminal back so mongodb is running the background.
Also how to shutdown if its running in background
Use
./mongod --fork
or
./mongod &
To shutdown you have to send it a TERM signal.
ps aux | grep mongod - to find a PID
kill -TERM PID - send it a TERM signal, and using the first example we can use the PID file:
kill -TERM $(cat /var/run/mongodb/mongod.pid)
Also you can shut it down from the shell.
$ ./mongo
> use admin
> db.shutdownServer()
--
And another method:
./mongod --fork --pidfilepath /var/run/mongodb/mongod.pid
then (please notice the ticks around the cat)
kill -9 `cat /var/run/mongodb/mongod.pid`
./mongod &
You will see a number in the output, something similar to
[1]+ ./mongod &
To kill the process execute a kill %1 where 1 is the number between the angular brackets.