NAME MongoDB Replication Lag

    Connects to a single mongo instance and retrieve
    replication lag for all connected members.


    MongoDB 3.X and 4.X with pymongo installed.


    defaults for host is and port 27017
    and will work without being defined :

    env.port 27017
    env.username user
    env.password P@55w0rd


    Stefan Andersen <>
    Updated by Alban Espie-Guillon <>

LICENSE The Beer Ware License (Revision 42) <> wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. """ import os import sys import pymongo

def _get_members(): host = os.environ.get('host', '') port = os.environ.get('port', 27017) username = os.environ.get('username', '') password = os.environ.get('password', '') conn = pymongo.MongoClient(host, int(port)) if username: connAuth = conn['admin'] connAuth.authenticate(username, password)

    repl_status = conn.admin.command("replSetGetStatus")

    members = {}
    for member in repl_status['members']:
        if member['stateStr'] != 'ARBITER' :
            name = member['name'].split('.')[0]
            members[name] = {'state': member['state'], 'optimeDate': member['optimeDate']}
    return members

def run(): members = _get_members(); for member in members: if members[member]['state'] == 1: primary_optime = members[member]['optimeDate']

    for member in members:
        lag = (primary_optime - members[member]['optimeDate']).seconds
        print("{0}.value {1}".format(member, lag))

def config(): print("""graph_title MongoDB replication lag graph_args --base 1000 graph_vlabel Replication lag (seconds) graph_category db """)

    for member in _get_members():
        print("{0}.label {0}".format(member))

if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "config": config() else: run()