check_mongo/check_mongo.py

109 lines
2.5 KiB
Python
Executable File

#!/usr/bin/env python2
"""
Checks mongo health
"""
import os
import sys
import configparser
import pymongo
from pprint import pprint
def readconfig():
home = os.getenv("HOME")
cfile = home + os.sep + ".check_mongo"
config = configparser.ConfigParser()
if os.path.isfile(cfile):
config.read(cfile)
else:
print("Config file {} not found".format(cfile))
sys.exit(2)
hostname = config.get('mongodb', 'hostname', fallback='localhost')
port = config.get('mongodb', 'port', fallback=27017)
username = config.get('mongodb', 'username', fallback='admin')
password = config.get('mongodb', 'password', fallback=False)
if not password:
print("Password not present in config")
sys.exit(2)
ret = dict()
ret['username'] = username
ret['hostname'] = hostname
ret['port'] = port
ret['password'] = password
return ret
def state_text(state):
if state == 8:
return "Down"
elif state == 4:
return "Fatal error"
elif state == 0:
return "Starting up, phase1"
elif state == 3:
return "Recovering"
elif state == 5:
return "Starting up, phase2"
elif state == 1:
return "Primary"
elif state == 2:
return "Secondary"
elif state == 7:
return "Arbiter"
elif state == -1:
return "Not running with replSet"
else:
return "Unknown state"
def main():
""" Main function """
config = readconfig()
connectstring = "mongodb://{}:{}@{}:{}".format(config['username'],
config['password'],
config['hostname'],
config['port'])
crit = warn = False
retval = 0;
try:
mdb = pymongo.MongoClient(connectstring)
ret = mdb.admin.command("replSetGetStatus");
except Exception as ex:
print("CRITICAL: Error while connecting: {}".format(ex))
sys.exit(2)
status = ""
for host in ret["members"]:
state = host["state"]
if state < 0 or state == 4 or state == 8:
crit = True
if state == 3:
warn = True
status += "{} ({}) ".format(host["name"], state_text(state))
if crit:
retval = 2
status = "CRITICAL: " + status
elif warn:
retval = 1
status = "WARNING: " + status
else:
status = "OK: " + status
print(status)
sys.exit(retval)
if __name__ == '__main__':
sys.exit(main())