| •1 |
|
| 2 |
"""MongoDB Nagios check script |
| 3 |
|
| 4 |
This program is part of $PROJECT_NAME$ |
| 5 |
License: GPL License (see COPYING) |
| 6 |
|
| 7 |
Author David Murphy |
| 8 |
Copyright 2014-2015 Percona LLC and/or its affiliates |
| 9 |
""" |
| 10 |
|
| 11 |
import sys |
| 12 |
import time |
| 13 |
import optparse |
| 14 |
import os |
| 15 |
import stat |
| 16 |
import pickle |
| 17 |
import traceback |
| 18 |
import pprint |
| 19 |
|
| 20 |
from types import FunctionType |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
try: |
| 25 |
import pymongo |
| •26 |
except ImportError, e: |
| 27 |
print e |
| 28 |
sys.exit(2) |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
if pymongo.version >= "1.9": |
| 33 |
import bson.son as son |
| 34 |
else: |
| 35 |
import pymongo.son as son |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
class OptionParsingError(RuntimeError): |
| 40 |
def __init__(self, msg): |
| 41 |
self.msg = msg |
| 42 |
|
| 43 |
|
| 44 |
class ModifiedOptionParser(optparse.OptionParser): |
| 45 |
def error(self, msg): |
| 46 |
raise OptionParsingError(msg) |
| 47 |
|
| 48 |
def unicode_truncate(s, length, encoding='utf-8'): |
| 49 |
encoded = s.encode(encoding)[:length] |
| 50 |
return encoded.decode(encoding, 'ignore') |
| 51 |
|
| 52 |
def parse_options(args): |
| 53 |
funcList = [] |
| •54 |
for item_name, item_type in NagiosMongoChecks.__dict__.items(): |
| 55 |
if type(item_type) is FunctionType and item_name.startswith("check_") and item_name is not 'check_levels': |
| 56 |
funcList.append(item_name) |
| 57 |
p = ModifiedOptionParser() |
| 58 |
|
| 59 |
p.add_option('-H', '--host', action='store', type='string', dest='host', default='127.0.0.1', help='The hostname you want to connect to') |
| 60 |
p.add_option('-P', '--port', action='store', type='int', dest='port', default=27017, help='The port mongodb is running on') |
| 61 |
p.add_option('-u', '--user', action='store', type='string', dest='user', default=None, help='The username you want to login as') |
| 62 |
p.add_option('-p', '--password', action='store', type='string', dest='passwd', default=None, help='The password you want to use for that user') |
| 63 |
p.add_option('-W', '--warning', action='store', dest='warning', default=None, help='The warning threshold you want to set') |
| 64 |
p.add_option('-C', '--critical', action='store', dest='critical', default=None, help='The critical threshold you want to set') |
| 65 |
p.add_option('-A', '--action', action='store', type='choice', dest='action', default='check_connect', |
| 66 |
choices=funcList, help="The action you want to take. Valid choices are (%s) Default: %s" % (", ".join(funcList), 'check_connect')) |
| 67 |
p.add_option('-s', '--ssl', dest='ssl', default=False, help='Connect using SSL') |
| 68 |
p.add_option('-r', '--replicaset', dest='replicaset', default=None, help='Connect to replicaset') |
| 69 |
p.add_option('-c', '--collection', action='store', dest='collection', default='foo', help='Specify the collection in check_cannary_test') |
| 70 |
p.add_option('-d', '--database', action='store', dest='database', default='tmp', help='Specify the database in check_cannary_test') |
| 71 |
p.add_option('-q', '--query', action='store', dest='query', default='{"_id":1}', help='Specify the query in check_cannary_test') |
| 72 |
p.add_option('--statusfile', action='store', dest='status_filename', default='status.dat', help='File to current store state data in for delta checks') |
| 73 |
p.add_option('--backup-statusfile', action='store', dest='status_filename_backup', default='status_backup.dat', |
| 74 |
help='File to previous store state data in for delta checks') |
| 75 |
p.add_option('--max-stale', action='store', dest='max_stale', type='int', default=60, help='Age of status file to make new checks (seconds)') |
| 76 |
|
| 77 |
try: |
| 78 |
result = p.parse_args() |
| •79 |
except OptionParsingError, e: |
| 80 |
if 'no such option' in e.msg: |
| 81 |
sys.exit("UNKNOWN - No such options of %s" % e.msg.split(":")[1]) |
| 82 |
if 'invalid choice' in e.msg: |
| 83 |
error_item = e.msg.split(":")[2].split("'")[1] |
| 84 |
sys.exit('UNKNOWN - No such action of %s found!' % error_item) |
| 85 |
return result |
| 86 |
|
| 87 |
|
| 88 |
def return_result(result_type, message): |
| 89 |
if result_type == "ok": |
| •90 |
print "OK - " + message |
| 91 |
sys.exit(0) |
| 92 |
elif result_type == "critical": |
| •93 |
print "CRITICAL - " + message |
| 94 |
sys.exit(2) |
| 95 |
elif result_type == "warning": |
| •96 |
print "WARNING - " + message |
| 97 |
sys.exit(1) |
| 98 |
else: |
| •99 |
print "UNKNOWN - " + message |
| 100 |
sys.exit(2) |
| 101 |
|
| 102 |
|
| 103 |
def main(argv): |
| 104 |
options, arguments = parse_options(argv) |
| 105 |
check(options, options.action) |
| 106 |
|
| 107 |
|
| 108 |
def check(args, check_name): |
| 109 |
try: |
| 110 |
checksObj = globals()['NagiosMongoChecks'](args) |
| 111 |
run_check = getattr(checksObj, check_name) |
| 112 |
result_type, message = run_check(args, args.warning, args.critical) |
| •113 |
except Exception, e: |
| 114 |
raise |
| •115 |
print(traceback.extract_tb(sys.exc_info()[-1], 1)) |
| 116 |
return_result("critical", str(e)) |
| 117 |
return_result(result_type, message) |
| 118 |
|
| 119 |
|
| 120 |
class NagiosMongoChecks: |
| 121 |
|
| 122 |
def __init__(self, args): |
| 123 |
|
| 124 |
self.host = '127.0.0.1' |
| 125 |
self.port = 27017 |
| 126 |
self.user = None |
| 127 |
self.password = None |
| 128 |
self.warning = None |
| 129 |
self.critical = None |
| 130 |
self.action = 'check_connect' |
| 131 |
self.ssl = False |
| 132 |
self.replicaset = None |
| 133 |
self.collection = 'foo' |
| 134 |
self.database = 'tmp' |
| 135 |
self.query = '{"_id":1}' |
| 136 |
self.status_filename = 'status.dat' |
| 137 |
self.status_filename_backup = 'status_backup.dat' |
| 138 |
self.max_stale = 60 |
| 139 |
|
| 140 |
for option in vars(args): |
| 141 |
setattr(self, option, getattr(args, option)) |
| 142 |
|
| 143 |
|
| 144 |
if not self.status_filename.startswith("/") or not self.status_filename.startswith(".."): |
| 145 |
self.status_filename_backup = "%s/%s" % (os.curdir, self.status_filename_backup) |
| 146 |
self.status_filename = "%s/%s" % (os.curdir, self.status_filename) |
| 147 |
|
| 148 |
|
| 149 |
self.current_status = {} |
| 150 |
self.last_status = {} |
| 151 |
self.connection = None |
| 152 |
self.connection_time = None |
| 153 |
self.pyMongoError = None |
| 154 |
|
| 155 |
self.connect() |
| 156 |
|
| 157 |
if self.file_age(self.status_filename) <= self.max_stale: |
| 158 |
|
| 159 |
self.get_last_status(True) |
| 160 |
|
| 161 |
self.get_last_status(False, self.status_filename_backup) |
| 162 |
else: |
| 163 |
if self.connection is None: |
| 164 |
raise pymongo.errors.ConnectionFailure(self.pyMongoError or "No connection Found, did connect fail?") |
| 165 |
|
| 166 |
self.current_status = self.sanatize(self.get_server_status()) |
| 167 |
|
| 168 |
self.get_last_status(False, self.status_filename) |
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
pass |
| 176 |
|
| 177 |
def get_last_status(self, returnAsCurrent, forceFile=None): |
| 178 |
|
| 179 |
try: |
| 180 |
file_name = forceFile if forceFile is not None else self.status_filename |
| 181 |
fileObject = open(file_name, 'r') |
| 182 |
if returnAsCurrent is None or returnAsCurrent is False: |
| 183 |
self.last_status = pickle.load(fileObject) |
| 184 |
else: |
| 185 |
self.current_status = pickle.load(fileObject) |
| 186 |
except Exception: |
| 187 |
return False |
| 188 |
return True |
| 189 |
|
| 190 |
def get_server_status(self): |
| 191 |
try: |
| 192 |
data = self.connection['admin'].command(pymongo.son_manipulator.SON([('serverStatus', 1)])) |
| 193 |
except: |
| 194 |
try: |
| 195 |
data = self.connection['admin'].command(son.SON([('serverStatus', 1)])) |
| •196 |
except Exception, e: |
| 197 |
if type(e).__name__ == "OperationFailure": |
| 198 |
sys.exit("UNKNOWN - Not authorized!") |
| 199 |
else: |
| 200 |
sys.exit("UNKNOWN - Unable to run serverStatus: %s::%s" % (type(e).__name__, unicode_truncate(e.message, 45))) |
| 201 |
|
| 202 |
if self.current_status is None: |
| 203 |
self.current_status = data |
| 204 |
|
| 205 |
return data |
| 206 |
|
| 207 |
|
| 208 |
def rotate_files(self): |
| 209 |
|
| 210 |
|
| 211 |
if self.last_status == {}: |
| 212 |
|
| 213 |
self.save_file(self.status_filename_backup, self.current_status) |
| 214 |
|
| 215 |
self.save_file(self.status_filename, {}) |
| 216 |
sys.exit("UNKNOWN - No status data present, please try again in %s seconds" % self.max_stale) |
| 217 |
else: |
| 218 |
self.save_file(self.status_filename_backup, self.last_status) |
| 219 |
self.save_file(self.status_filename, self.current_status) |
| 220 |
|
| 221 |
|
| 222 |
def save_file(self, filename, contents): |
| 223 |
try: |
| 224 |
pickle.dump(contents, open(filename, "wb")) |
| •225 |
except Exception, e: |
| 226 |
sys.exit("UNKNOWN - Error saving stat file %s: %s" % (filename, e.message)) |
| 227 |
|
| 228 |
|
| 229 |
def get_default(self, key, level): |
| 230 |
|
| 231 |
defaults = { |
| 232 |
'check_connections': {'warning': 15000, 'critical': 19000}, |
| 233 |
'check_connect': {'warning': 50, 'critical': 100}, |
| 234 |
'check_queues': {'warning': 30, 'critical': 100}, |
| 235 |
'check_lock_pct': {'warning': 30, 'critical': 50}, |
| 236 |
'check_repl_lag': {'warning': 200, 'critical': 500}, |
| 237 |
|
| 238 |
'check_total_indexes': {'warning': 100, 'critical': 300}, |
| 239 |
'check_cannary_test': {'warning': 30, 'critical': 50}, |
| 240 |
'check_oplog': {'warning': 36, 'critical': 24}, |
| 241 |
'check_index_ratio': {'warning': .9, 'critical': .8}, |
| 242 |
} |
| 243 |
try: |
| 244 |
return defaults[key][level] |
| 245 |
except KeyError: |
| 246 |
sys.exit("UNKNOWN - Missing defaults found for %s please use -w and -c" % key) |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
def file_age(self, filename): |
| 263 |
try: |
| 264 |
age = time.time() - os.stat(filename)[stat.ST_CTIME] |
| 265 |
except OSError: |
| 266 |
age = 999999 |
| 267 |
return age |
| 268 |
|
| 269 |
|
| 270 |
def sanatize(self, status_output): |
| 271 |
return status_output |
| 272 |
|
| 273 |
def connect(self): |
| 274 |
start_time = time.time() |
| 275 |
try: |
| 276 |
|
| 277 |
if self.replicaset is None: |
| 278 |
con = pymongo.MongoClient(self.host, self.port, ssl=self.ssl, serverSelectionTimeoutMS=2500) |
| 279 |
else: |
| 280 |
con = pymongo.MongoClient(self.host, self.port, ssl=self.ssl, replicaSet=self.replicaset, serverSelectionTimeoutMS=2500) |
| 281 |
if (self.user and self.passwd) and not con['admin'].authenticate(self.user, self.passwd): |
| 282 |
sys.exit("CRITICAL - Username and password incorrect") |
| •283 |
except Exception, e: |
| 284 |
raise |
| 285 |
if isinstance(e, pymongo.errors.AutoReconnect) and str(e).find(" is an arbiter") != -1: |
| 286 |
|
| 287 |
|
| •288 |
print "OK - State: 7 (Arbiter)" |
| 289 |
sys.exit(0) |
| 290 |
con = None |
| 291 |
self.pyMongoError = str(e) |
| 292 |
if con is not None: |
| 293 |
try: |
| 294 |
con['admin'].command(pymongo.son_manipulator.SON([('ping', 1)])) |
| •295 |
except Exception, e: |
| 296 |
sys.exit("UNKNOWN - Unable to run commands, possible auth issue: %s" % e.message) |
| 297 |
self.connection_time = round(time.time() - start_time, 2) |
| 298 |
version = con.server_info()['version'].split('.') |
| 299 |
self.mongo_version = (version[0], version[1], version[2]) |
| 300 |
self.connection = con |
| 301 |
|
| 302 |
def check_levels(self, check_result, warning_level, critical_level, message): |
| 303 |
if check_result < warning_level: |
| 304 |
return "ok", message |
| 305 |
elif check_result > critical_level: |
| 306 |
return "critical", message |
| 307 |
elif check_result > warning_level and check_result < critical_level: |
| 308 |
return "warning", message |
| 309 |
else: |
| 310 |
return "unknown", "Unable to parse %s into a result" % check_result |
| 311 |
|
| 312 |
def check_connect(self, args, warning_level, critical_level): |
| 313 |
warning_level = warning_level or self.get_default('check_connect', 'warning') |
| 314 |
critical_level = critical_level or self.get_default('check_connect', 'critical') |
| 315 |
con_time = self.connection_time |
| 316 |
message = "Connection time %.2f ms" % con_time |
| 317 |
return self.check_levels(float(con_time), float(warning_level), float(critical_level), message) |
| 318 |
|
| 319 |
def check_connections(self, args, warning_level, critical_level): |
| 320 |
warning_level = warning_level or self.get_default('check_connections', 'warning') |
| 321 |
critical_level = critical_level or self.get_default('check_connections', 'critical') |
| 322 |
connections = self.current_status['connections'] |
| 323 |
connections['total'] = connections['available'] + connections['current'] |
| 324 |
used_percent = int((connections['current'] / connections['total']) * 100) |
| 325 |
message = "%i%% connections used ( %d of %d )" % (used_percent, connections['current'], connections['total']) |
| 326 |
return self.check_levels(float(used_percent), int(warning_level), int(critical_level), message) |
| 327 |
|
| 328 |
def check_lock_pct(self, args, warning_level, critical_level): |
| 329 |
warning_level = warning_level or self.get_default('check_lock_pct', 'warning') |
| 330 |
critical_level = critical_level or self.get_default('check_lock_pct', 'critical') |
| 331 |
if self.mongo_version >= ('2', '7', '0'): |
| 332 |
return "ok", "Mongo 3.0 and above do not have lock %" |
| 333 |
lockTime = self.current_status['globalLock']['lockTime'] - self.last_status['globalLock']['lockTime'] |
| 334 |
totalTime = self.current_status['globalLock']['totalTime'] - self.last_status['globalLock']['totalTime'] |
| 335 |
lock_percent = int((lockTime / totalTime) * 100) |
| 336 |
message = "%i%% locking found (over 100%% is possible)" % (lock_percent) |
| 337 |
return self.check_levels(lock_percent, warning_level, critical_level, message) |
| 338 |
|
| 339 |
def check_flushing(self, args, warning_level, critical_level): |
| 340 |
warning_level = warning_level or self.get_default('check_flushing', 'warning') |
| 341 |
critical_level = critical_level or self.get_default('check_flushing', 'critical') |
| 342 |
flushData = self.current_status['backgroundFlushing'] |
| 343 |
if args.average: |
| 344 |
flush_time = flushData['average_ms'] |
| 345 |
stat_type = "Average" |
| 346 |
else: |
| 347 |
flush_time = flushData['last_ms'] |
| 348 |
stat_type = "Last" |
| 349 |
|
| 350 |
message = "%s Flush Time: %.2fms" % (stat_type, flush_time) |
| 351 |
return self.check_levels(flush_time, warning_level, critical_level, message) |
| 352 |
|
| 353 |
def check_index_ratio(self, args, warning_level, critical_level): |
| 354 |
warning_level = warning_level or self.get_default('check_index_ratio', 'warning') |
| 355 |
critical_level = critical_level or self.get_default('check_index_ratio', 'critical') |
| 356 |
message = None |
| 357 |
|
| 358 |
indexCounters = self.current_status['indexCounters'] |
| 359 |
if 'note' in indexCounters: |
| 360 |
ratio = 1.0 |
| 361 |
message = "not supported defaulting to 1.0 ratio" |
| 362 |
elif self.mongo_version >= ('2', '4', '0'): |
| 363 |
ratio = indexCounters['missRatio'] |
| 364 |
else: |
| 365 |
ratio = indexCounters['btree']['missRatio'] |
| 366 |
if message is None: |
| 367 |
message = "Miss Ratio: %.2f" % ratio |
| 368 |
return self.check_levels(ratio, warning_level, critical_level, message) |
| 369 |
|
| 370 |
def check_have_primary(self, args, warning_level, critical_level): |
| 371 |
replset_status = self.connection['admin'].command("replSetGetStatus") |
| 372 |
for member in replset_status['members']: |
| 373 |
if member['state'] == 1: |
| 374 |
return "ok", "Cluster has primary" |
| 375 |
return "critical", "Cluster has no primary!" |
| 376 |
|
| 377 |
def check_total_indexes(self, args, warning_level, critical_level): |
| 378 |
warning_level = warning_level or self.get_default('check_total_indexes', 'warning') |
| 379 |
critical_level = critical_level or self.get_default('check_total_indexes', 'critical') |
| 380 |
index_count = 0 |
| 381 |
database_count = 0 |
| 382 |
for database in self.connection.database_names(): |
| 383 |
if database not in ["admin", "local"]: |
| 384 |
database_count += 1 |
| 385 |
self.connection[database]['system.indexes'].count() |
| 386 |
index_count += self.connection[database]['system.indexes'].count() |
| 387 |
message = "Found %d indexes in %d databases" % (index_count, database_count) |
| 388 |
return self.check_levels(index_count, warning_level, critical_level, message) |
| 389 |
|
| 390 |
def check_queues(self, args, warning_level, critical_level): |
| 391 |
warning_level = warning_level or self.get_default('check_queues', 'warning') |
| 392 |
critical_level = critical_level or self.get_default('check_queues', 'critical') |
| 393 |
currentQueue = self.current_status['globalLock']['currentQueue'] |
| 394 |
currentQueue['total'] = currentQueue['readers'] + currentQueue['writers'] |
| 395 |
message = "Queue Sizes: read (%d) write(%d) total (%d)" % (currentQueue['readers'], currentQueue['writers'], currentQueue['total']) |
| 396 |
return self.check_levels(currentQueue['total'], warning_level, critical_level, message) |
| 397 |
|
| 398 |
def check_oplog(self, args, warning_level, critical_level): |
| 399 |
warning_level = warning_level or self.get_default('check_oplog', 'warning') |
| 400 |
critical_level = critical_level or self.get_default('check_oplog', 'critical') |
| 401 |
if 'local' not in self.connection.database_names() or 'oplog.rs' not in self.connection['local'].collection_names(): |
| 402 |
return "critical", "We do not seem to be in a replset!" |
| 403 |
oplog = self.connection['local']['oplog.rs'] |
| 404 |
first_ts = oplog.find().sort("$natural", pymongo.ASCENDING).limit(1)[0]['ts'] |
| 405 |
last_ts = oplog.find().sort("$natural", pymongo.DESCENDING).limit(1)[0]['ts'] |
| 406 |
oplog_range = (last_ts.as_datetime() - first_ts.as_datetime()) |
| 407 |
oplog_range_hours = oplog_range.total_seconds() / 60 / 60 |
| 408 |
message = "Oplog Time is %d hours" % (oplog_range_hours) |
| 409 |
return self.check_levels(int(oplog_range_hours), warning_level, critical_level, message) |
| 410 |
|
| 411 |
def check_election(self, args, warning_level, critical_level): |
| 412 |
replset_status = self.connection['admin'].command("replSetGetStatus") |
| 413 |
for member in replset_status['members']: |
| 414 |
if member['stateStr'] == "PRIMARY": |
| 415 |
|
| 416 |
last_primary = member['name'] |
| 417 |
for member in replset_status['members']: |
| 418 |
if member['stateStr'] == "PRIMARY": |
| 419 |
current_primary = member['name'] |
| 420 |
message = "Old PRI: %s New PRI: %s" % (last_primary, current_primary) |
| 421 |
if current_primary == last_primary: |
| 422 |
return "ok", message |
| 423 |
else: |
| 424 |
return "critical", message |
| 425 |
|
| 426 |
def is_balanced(self): |
| 427 |
chunks = {} |
| 428 |
|
| 429 |
|
| 430 |
for chunk in self.connection["config"]["chunks"].find(): |
| 431 |
namespace = chunk['ns'] |
| 432 |
shard = chunk['shard'] |
| 433 |
if namespace not in chunks: |
| 434 |
chunks[namespace] = {'shards': {}, 'total': 0} |
| 435 |
if shard not in chunks[namespace]['shards']: |
| 436 |
chunks[namespace]['shards'][shard] = 0 |
| 437 |
chunks[namespace]['shards'][shard] += 1 |
| 438 |
chunks[namespace]['total'] += 1 |
| 439 |
|
| 440 |
shardsCount = self.connection["config"]["shards"].count() |
| 441 |
chunksCount = self.connection["config"]["chunks"].count() |
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
if chunksCount < 20: |
| 446 |
threshold = 2 |
| 447 |
elif chunksCount < 80 and chunksCount > 21: |
| 448 |
threshold = 4 |
| 449 |
else: |
| 450 |
threshold = 8 |
| 451 |
|
| 452 |
|
| 453 |
isBalanced = True |
| 454 |
|
| 455 |
for ns in chunks: |
| 456 |
balanced = chunks[ns]['total'] / shardsCount |
| 457 |
for shard in chunks[ns]['shards']: |
| 458 |
if shard > balanced - threshold and shard < balanced + threshold: |
| 459 |
pass |
| 460 |
else: |
| 461 |
isBalanced = False |
| 462 |
|
| 463 |
return isBalanced |
| 464 |
|
| 465 |
def check_balance(self, args, warning_level, critical_level): |
| 466 |
if self.is_balanced() is True: |
| 467 |
return "ok", "Shards are balanced by chunk counts" |
| 468 |
else: |
| 469 |
return "critcal", "Shards are not balanced by chunk and need review" |
| 470 |
|
| 471 |
def check_cannary_test(self, args, warning_level, critical_level): |
| 472 |
warning_level = warning_level or self.get_default('check_cannary_test', 'warning') |
| 473 |
critical_level = critical_level or self.get_default('check_cannary_test', 'critical') |
| 474 |
|
| 475 |
try: |
| 476 |
start = time.time() |
| 477 |
self.connection[self.database][self.collection].find_one(self.query) |
| 478 |
time_range = (time.time() - start).total_seconds |
| 479 |
message = "Collection %s.%s query took: %d s" % (self.database, self.collection, time_range) |
| 480 |
return self.check_levels(time_range, warning_level, critical_level, message) |
| •481 |
except Exception, e: |
| 482 |
message = "Collection %s.%s query FAILED: %s" % (self.database, self.collection, e) |
| 483 |
return "critical", message |
| 484 |
|
| 485 |
def check_repl_lag(self, args, warning_level, critical_level): |
| 486 |
warning_level = warning_level or self.get_default('check_repl_lag', 'warning') |
| 487 |
critical_level = critical_level or self.get_default('check_repl_lag', 'critical') |
| 488 |
|
| 489 |
|
| 490 |
self.connection['test']['lag_check'].update({"_id":1}, {"_id": 1, "x": 1}) |
| 491 |
|
| 492 |
try: |
| 493 |
replset_status = self.connection['admin'].command("replSetGetStatus") |
| •494 |
except Exception, e: |
| 495 |
return "critical", "Are your running with --replset? - %s" % (e) |
| 496 |
|
| 497 |
for member in replset_status['members']: |
| 498 |
if member['stateStr'] == "PRIMARY": |
| 499 |
primary = member |
| 500 |
if 'self' in member and member['self'] is True: |
| 501 |
hostOptimeDate = member['optimeDate'] |
| 502 |
|
| 503 |
if primary is not None: |
| 504 |
highest_optimeDate = primary['optimeDate'] |
| 505 |
highest_name = primary['name'] |
| 506 |
else: |
| 507 |
|
| 508 |
highest_optimeDate = time.gmtime(0) |
| 509 |
for member in replset_status['members']: |
| 510 |
if member['optimeDate'] > highest_optimeDate: |
| 511 |
highest_optimeDate = member['optimeDate'] |
| 512 |
highest_name = member['name'] |
| 513 |
|
| 514 |
rep_lag_seconds = (highest_optimeDate - hostOptimeDate).seconds |
| 515 |
rep_lag_hours = round(rep_lag_seconds/60/60, 4) |
| 516 |
message = "Lagging %s by %.4f hours" % (highest_name, rep_lag_hours) |
| 517 |
return self.check_levels(rep_lag_hours, warning_level, critical_level, message) |
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
if __name__ == "__main__": |
| 523 |
sys.exit(main(sys.argv[1:])) |
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
""" |
| 529 |
=pod |
| 530 |
|
| 531 |
=head1 NAME |
| 532 |
|
| 533 |
pmp-check-mongo.py - MongoDB Nagios check script. |
| 534 |
|
| 535 |
=head1 SYNOPSIS |
| 536 |
|
| 537 |
Usage: pmp-check-mongo.py [options] |
| 538 |
|
| 539 |
Options: |
| 540 |
-h, --help show this help message and exit |
| 541 |
-H HOST, --host=HOST The hostname you want to connect to |
| 542 |
-P PORT, --port=PORT The port mongodb is running on |
| 543 |
-u USER, --user=USER The username you want to login as |
| 544 |
-p PASSWD, --password=PASSWD |
| 545 |
The password you want to use for that user |
| 546 |
-W WARNING, --warning=WARNING |
| 547 |
The warning threshold you want to set |
| 548 |
-C CRITICAL, --critical=CRITICAL |
| 549 |
The critical threshold you want to set |
| 550 |
-A ACTION, --action=ACTION |
| 551 |
The action you want to take. Valid choices are |
| 552 |
(check_connections, check_election, check_lock_pct, |
| 553 |
check_repl_lag, check_flushing, check_total_indexes, |
| 554 |
check_balance, check_queues, check_cannary_test, |
| 555 |
check_have_primary, check_oplog, check_index_ratio, |
| 556 |
check_connect) Default: check_connect |
| 557 |
-s SSL, --ssl=SSL Connect using SSL |
| 558 |
-r REPLICASET, --replicaset=REPLICASET |
| 559 |
Connect to replicaset |
| 560 |
-c COLLECTION, --collection=COLLECTION |
| 561 |
Specify the collection in check_cannary_test |
| 562 |
-d DATABASE, --database=DATABASE |
| 563 |
Specify the database in check_cannary_test |
| 564 |
-q QUERY, --query=QUERY |
| 565 |
Specify the query in check_cannary_test |
| 566 |
--statusfile=STATUS_FILENAME |
| 567 |
File to current store state data in for delta checks |
| 568 |
--backup-statusfile=STATUS_FILENAME_BACKUP |
| 569 |
File to previous store state data in for delta checks |
| 570 |
--max-stale=MAX_STALE |
| 571 |
Age of status file to make new checks (seconds) |
| 572 |
|
| 573 |
=head1 COPYRIGHT, LICENSE, AND WARRANTY |
| 574 |
|
| 575 |
This program is copyright 2014 Percona LLC and/or its affiliates. |
| 576 |
Feedback and improvements are welcome. |
| 577 |
|
| 578 |
THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED |
| 579 |
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF |
| 580 |
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. |
| 581 |
|
| 582 |
This program is free software; you can redistribute it and/or modify it under |
| 583 |
the terms of the GNU General Public License as published by the Free Software |
| 584 |
Foundation, version 2. You should have received a copy of the GNU General |
| 585 |
Public License along with this program; if not, write to the Free Software |
| 586 |
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. |
| 587 |
|
| 588 |
=head1 VERSION |
| 589 |
|
| 590 |
$PROJECT_NAME$ pmp-check-mongo.py $VERSION$ |
| 591 |
|
| 592 |
=cut |
| 593 |
|
| 594 |
""" |