Skip to content

Commit

Permalink
Update Mongodb server status check (#1038)
Browse files Browse the repository at this point in the history
  • Loading branch information
shloka-bhalgat-unskript authored Apr 3, 2024
1 parent 138872f commit ea18671
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 94 deletions.
5 changes: 1 addition & 4 deletions Mongo/legos/mongodb_get_server_status/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,9 @@ This Lego Gets Mongo Server Status

## Lego Details

mongodb_get_server_status(handle, connection_threshold: int = 1000, memory_threshold: int = 2048, cache_usage_threshold: int = 80)
mongodb_get_server_status(handle)

handle: Object of type unSkript Mongodb Connector.
connection_threshold: Threshold for the number of connections considered abnormal
memory_threshold: Threshold for the megabytes of resident memory usage considered abnormal (in megabytes)
cache_usage_threshold: Threshold for the percentage of WiredTiger cache usage considered abnormal

## Lego Input
This Lego take only one input handle.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"action_title": "Get Mongo Server Status",
"action_description": "Get Mongo Server Status and check for any abnormalities.",
"action_description": "Status indicating server reachability of mongo server",
"action_type": "LEGO_TYPE_MONGODB",
"action_entry_function": "mongodb_get_server_status",
"action_needs_credential": true,
Expand Down
103 changes: 14 additions & 89 deletions Mongo/legos/mongodb_get_server_status/mongodb_get_server_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,106 +8,31 @@


class InputSchema(BaseModel):
connection_threshold: Optional[int] = Field(
10000,
title='Connection threshold',
description='Threshold for the number of connections considered abnormal. Default- 10000 clients')
memory_threshold: Optional[int] = Field(
15360, # 15GB in MB
title='Memory threshold (in MB)',
description='Threshold for the megabytes of resident memory usage considered abnormal (in megabytes). Default- 15360MB')
cache_usage_threshold: Optional[int] = Field(
80,
title='Cache usage threshold (in %)',
description='Threshold for the percentage of WiredTiger cache usage considered abnormal. Default- 80%')
pass



def mongodb_get_server_status_printer(output):
if output is None or not output[1]:
print("No MongoDB server status information available.")
return

status, listAnalysis = output

print("\nMongoDB Server Status:")
if status:
print("Status: Healthy")
if output[0]:
print("MongoDB Server Status: Reachable")
else:
print("Status: Unhealthy")

for analysis in listAnalysis:
for key, value in analysis.items():
if key == 'wiredTiger_cache':
print("WiredTiger Cache:")
for subkey, subvalue in value.items():
print(f" {subkey}: {subvalue}")
elif key == 'replication_info':
print(f"Replication Hosts:{value}")
elif key == 'locks':
print("Locks:")
for subkey, subvalue in value.items():
print(f" {subkey}: {subvalue}")
else:
print(f"{key}: {value}")

print("MongoDB Server Status: Unreachable")
if output[1]:
print(f"Error: {output[1]}")

def mongodb_get_server_status(handle, connection_threshold: int = 10000, memory_threshold: int = 15360, cache_usage_threshold: int = 80) -> Tuple:
def mongodb_get_server_status(handle) -> Tuple:
"""Returns the status of the MongoDB instance.
:type handle: object
:param handle: MongoDB connection object
:type connection_threshold: int
:param connection_threshold: Threshold for the number of connections considered abnormal
:type memory_threshold: int
:param memory_threshold: Threshold for the megabytes of resident memory usage considered abnormal (in megabytes)
:type cache_usage_threshold: int
:param cache_usage_threshold: Threshold for the percentage of WiredTiger cache usage considered abnormal
:return: Status indicating overall health and a dictionary with detailed information
:return: Status indicating server reachability of mongo server
"""
server_status_info = {}
abnormal_metrics = []

try:
server_status = handle.admin.command("serverStatus")

# Essential metrics
server_status_info['version'] = server_status['version']
server_status_info['uptime'] = server_status['uptime']
server_status_info['connections'] = server_status.get('connections', {}).get('current')
server_status_info['resident_memory'] = server_status.get('mem', {}).get('resident')
server_status_info['asserts'] = server_status['asserts']
server_status_info['replication_info'] = server_status.get('repl').get('hosts')

# Check if connections exceed the threshold
if server_status_info['connections'] > connection_threshold:
abnormal_metrics.append(f"High number of connections: {server_status_info['connections']}")

# Check if resident memory usage exceeds the threshold (in megabytes)
if server_status_info['resident_memory'] > memory_threshold:
abnormal_metrics.append(f"Resident memory utilization is above {memory_threshold} MB: {server_status_info['resident_memory']}")

# Check if WiredTiger cache usage exceeds the threshold
wired_tiger_cache = server_status.get('wiredTiger', {}).get('cache')
if wired_tiger_cache:
used_bytes = wired_tiger_cache.get('bytes currently in the cache')
total_bytes = wired_tiger_cache.get('maximum bytes configured')
if used_bytes is not None and total_bytes is not None:
cache_usage = (used_bytes / total_bytes) * 100
server_status_info['wiredTiger_cache_usage'] = cache_usage
if cache_usage > cache_usage_threshold:
abnormal_metrics.append(f"Cache utilization is above {cache_usage_threshold}%")

# Append abnormal metrics if any are found
if abnormal_metrics:
server_status_info['abnormal_metrics'] = abnormal_metrics
return False, [server_status_info]

return True, None

# Check server reachability
result = handle.admin.command("ping")
if result and result.get("ok"):
return (True, None)
except Exception as e:
raise e
return (False, str(e))
return (False, "Unable to check Mongo server status")

0 comments on commit ea18671

Please sign in to comment.