How to use the new hello interface for availability

Hi All!

With ismaster now deprecated in the latest driver what is the best way to check server availability using the new hello command and pymongo.

In the old documentation it was recommended to use client.admin.command(“ismaster”) for availability, what would be the correct way to it so that it would do the correct command for each mongo version?

I was reading through the source code and could find that you can get the right command for the mongo version with sock_info.hello_cmd(). Is the best to do it somehow using hello_cmd method?

This is old instruction is still in the latest source code as comment: mongo-python-driver/pymongo/mongo_client.py at c93194a2e6a5a4e3caada9e7e288cb2ab373f4cd · mongodb/mongo-python-driver · GitHub

You can check if the server is available
like this::

        from pymongo.errors import ConnectionFailure
        client = MongoClient()
        try:
            # The ismaster command is cheap and does not require auth.
            client.admin.command('ismaster')
        except ConnectionFailure:
            print("Server not available")

From the 3.12 change log:

  • Deprecated [ IsMaster ]which will be removed in PyMongo 4.0 and are replaced by [ Hello ](and hello which provide the same API.

You can replace the string ‘ismaster’ in the example with the string ‘hello’. As the deprecation warning mentions, they provide the same API and result. If you aren’t interested in the content of the result document you can instead replace ‘ismaster’ with ‘ping’. The ping command has existed for forever.

1 Like

Hi,

Thanks for the quick answer.

We are running some older mongos along with newer ones. The older ones will fail with “no such cmd: hello” in that case. Looks like SockInfo.hello_cmd could give you the right version appropriate command but using it feels very hacky and getting the socket requires using internal methods.

SockInfo is a private api so you should not rely on it. Using the ping command is a better option. We will update the documentation like this:

        from pymongo.errors import ConnectionFailure
        client = MongoClient()
        try:
            # The ping command is cheap and does not require auth.
            client.admin.command('ping')
        except ConnectionFailure:
            print("Server not available")
2 Likes