Expanding HAProxy health check to monitor MongoDB primary and secondary state

haproxymongodbwireshark

Follow up question regarding the MongoDB health check with HAProxy

How to construct a MongoDB Health Check in HAProxy?

The current solution works well when the focus is on determining if mongo responds, but I am trying to expand the functionality to track based on the status of the database for primary or secondary. I have tried variations of isMaster without success. On the MongoDB side with mongosniff or wireshark, the results come across as a query parsing error and no response is posted back to the HAProxy host.

Using the Mongo wire protocol, is there a query available to get the status of a given MongoDB server instead of a the current solution which only allows for tracking on a database response?

Best Answer

I've created this tcp check following the guide from the MongoDB health check question (How to construct a MongoDB Health Check in HAProxy?) and using the isMaster command (https://docs.mongodb.com/manual/reference/command/isMaster/#isMaster.ismaster) in mongodb as mentioned by Adam C in a comment above :

tcp-check send-binary 3d00000001000000ffffffffd407000000000000746573742e24636d640000000000ffffffff170000000169734d617374657200000000000000f03f00
tcp-check expect binary 0869736d61737465720001

The sent binary is this command:

mongo --host <IP> --port <port> --eval 'db.isMaster().ismaster'

The expected binary is the 'ismaster' element of the response document. The important part is the ending value which is 01 if it's a primary db and 00 if it's a secondary.

I used MongodDB 3.4.4 and HAproxy 1.5.18 .