mongodbtornado-motor

Testing motor.MotorClient() connection


I want to know how to check that a Motor connection is successful. If i kill the mongod process and perform a:

con = motor.MotorClient(host,port)

I get "[W 150619 00:38:38 iostream:1126] Connect error on fd 11: ECONNREFUSED"

Makes sense since there's no server running. However because this isn't an exception I'm not sure how to check for this case?

I thought I could check the con.is_mongos however it seems it's always False (also stated in the documentation).

How do I check above error scenario?


Solution

  • Generally, the answer is don't. Don't check if a connection to MongoDB is working. You might find out that it's working right now, but the next operation might fail anyway--your sysadmin might pull your cable, the server crashes, whatever. Since you need to handle errors later in your application no matter, there's no point checking ahead of time whether Motor has connected successfully or not.

    If you insist on this pointless check, even knowing that it gains you nothing, then you could do:

    @gen.coroutine
    def am_i_momentarily_connected_to_mongodb():
        yield MotorClient().admin.command('ismaster')
    

    If your IOLoop has already started and you're in a coroutine you can then do:

    yield am_i_momentarily_connected_to_mongodb()
    

    Or if you haven't started the loop yet:

    IOLoop.instance().run_sync(am_i_momentarily_connected_to_mongodb)
    

    But like I said, it's the nature of distributed systems that discovering a server is available now doesn't tell you anything certain about what will happen next.