Wednesday 12 October 2011

Detecting if Mongo is running in your app (by K)

We use MongoDB for a load of stuff.
One thing that is a problem is that, in the dev environment, the mongo service needs to be restarted.
(In production we have different mechanisms of course)
So for a period of time while developing an app, Mongo may not be running.
And if you make any call to it in your app you get a shed load of exceptions that, for some reason, can't be caught.

This kind of thing:

[#|2011-10-11T17:44:58.420+1000|WARNING|glassfish3.1.1|com.mongodb.tcp|_ThreadID=27;_ThreadName=Thread-3;|Exception determining maxBSON size using0
java.io.IOException: couldn't connect to [your-app.com/your-ip:27017] bc:java.net.ConnectException: Connection refused
at com.mongodb.DBPort._open(DBPort.java:224)
at com.mongodb.DBPort.go(DBPort.java:101)
at com.mongodb.DBPort.go(DBPort.java:82)
at com.mongodb.DBPort.findOne(DBPort.java:142)
at com.mongodb.DBPort.runCommand(DBPort.java:151)
at com.mongodb.DBTCPConnector.fetchMaxBsonObjectSize(DBTCPConnector.java:429)
at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:416)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:193)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:303)
at com.mongodb.DBCollection.findOne(DBCollection.java:565)
at com.mongodb.DBCollection.findOne(DBCollection.java:554)

So I did some digging to find out what's going on and how to programmatically checking if the service is available.
I found this:

http://groups.google.com/group/mongodb-user/browse_thread/thread/2b3c1d4bdb1314e3

And made my own version which is called before any persistent action.
Here are the bones of it so you can modify it to suit your needs.

boolean mongoRunning = false;
ServerAddress serverAddress = new ServerAddress(dbHost);  // dbHost is the mongo host name
DBPortPool pool = mongo.getConnector().getDBPortPool(serverAddress); // mongo is the instance
DBPort port = pool.get();
try {
  port.ensureOpen();
  mongoRunning = true;
} catch (IOException e) {
  // Uh oh. Mongo not running. Do something meaningful...
  log.error("MongoDB isn't running on [" + dbHost + "][" + dbPort + "]"); // or just log it
} finally {
  port.close(); // should do try/catch here...
}

It's overkill of course, but it does help.
Just to help out.

No comments:

Post a Comment