Skip to content

Instantly share code, notes, and snippets.

@kainam00
Created May 6, 2022 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kainam00/3ab3715468744f364fa0847b5e54b88d to your computer and use it in GitHub Desktop.
Save kainam00/3ab3715468744f364fa0847b5e54b88d to your computer and use it in GitHub Desktop.
Simple MongoDB Nagios plugin
#!/usr/bin/env python3
"""
check_mongod.py: Check master mongod instance
-h, --host Host to query
-p, --port Port
-d, --db Database and collection to use
-w, --warn Time to warn (seconds)
-c, --crit Time to crit (seconds)
-v, --verbose verbose
"""
import sys
import getopt
import time
import datetime
from pymongo import MongoClient
verbose = False
def usage():
print(__doc__)
def check_mongod(mongohost, mongoport, database, warn, crit):
starttime = time.time()
try:
if verbose:
print("Connecting to: {}:{}".format(str(mongohost), str(mongoport)))
connection = MongoClient(mongohost, mongoport, serverSelectionTimeoutMS=int(crit*1000), connectTimeoutMS=int(crit*1000),
socketTimeoutMS=int(crit*1000))
if verbose:
print("Connected to: {}:{}".format(str(connection.host), str(connection.port)))
print("nodes:")
for node in connection.nodes:
print("{}:{}".format(str(node[0]), str(node[1])))
except Exception as e:
print('CRITICAL: Unable to connect to {}:{}'.format(str(mongohost), str(mongoport)))
print(str(e))
sys.exit(2)
try:
db = connection[database]
if verbose:
print("Databases:")
for k in connection.list_database_names():
print(str(k))
except Exception as e:
print('CRITICAL: Unable to list DBs or use monitoring database on {}:{}. Server may be down.'.format(str(mongohost),
str(mongoport)))
print(e)
sys.exit(2)
try:
collection = db[database]
except Exception as e:
print('CRITICAL: Unable to use monitoring collection on {}:{}'.format(str(mongohost), str(mongoport)))
print(str(e))
sys.exit(2)
testdoc = {"date": datetime.datetime.utcnow(), "text": "monitoring test record"}
try:
if verbose:
print("Adding test record")
document_id = collection.insert_one(testdoc).inserted_id
try:
cursor = collection.find_one({'_id': document_id})
if verbose:
print("Querying our test record")
for key, value in cursor.items():
print(key, value)
finally:
if verbose:
print("Removing test record")
collection.delete_one({'_id': document_id})
except Exception as e:
print('CRITICAL: Unable to save test record on {}:{}'.format(str(mongohost), str(mongoport)))
print(str(e))
sys.exit(2)
endtime = time.time()
elapsed = endtime - starttime
if elapsed >= crit:
print("CRITICAL: elapsed time: {:.4f}s".format(elapsed))
sys.exit(2)
elif elapsed >= warn:
print("WARNING: elapsed time: {:.4f}s".format(elapsed))
sys.exit(1)
elif elapsed < warn:
print("OK: Test record successfully added and removed. Total elapsed time: {:.4f}s".format(elapsed))
sys.exit(0)
def main(argv):
try:
opts, args = getopt.getopt(argv, "h:p:d:w:c:v", ["host", "port", "db", "warn", "crit", "verbose"])
except getopt.GetoptError as e:
print(str(e))
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--host"):
mongohost = arg
elif opt in ("-p", "--port"):
mongoport = int(arg)
elif opt in ("-d", "--db"):
database = arg
elif opt in ("-w", "--warn"):
warn = float(arg)
elif opt in ("-c", "--crit"):
crit = float(arg)
elif opt in ("-v", "--verbose"):
global verbose
verbose = True
if len(opts) < 5:
usage()
sys.exit(2)
check_mongod(mongohost, mongoport, database, warn, crit)
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment