1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
| """ Date: 01/18/2020 Author: Xinsheng Wang Description: A custom script to get MongoDB metrics and send data to Azure Monitor Requires: MongoClient in python """
from calendar import timegm from time import gmtime
from pymongo import MongoClient, errors from sys import exit
import json import requests import datetime import hashlib import hmac import base64 import os from glob import glob
customer_id = '86df0cbc-076c-4483-8a32-c59c6550a771'
shared_key = "b3uLsEOXBFBqTiAHDGp9boTeKR6v86f/9cLPWWsWUvs+LcjBIqjDp9CDJL+7vxlKDDRxqXIf1jjjKcZbdV0H/Q=="
log_type = 'MongoDBMonitorLog'
class MongoDB(object): """main script class"""
def delete_temporary_files(self): """delete temporary files""" for file in glob('/tmp/mongometrics000*'): os.remove(file)
def __init__(self): self.mongo_host = "10.11.0.4" self.mongo_port = 27017 self.mongo_db = ["admin", ] self.mongo_user = None self.mongo_password = None self.__conn = None self.__dbnames = None self.__metrics = []
def connect(self): """Connect to MongoDB""" if self.__conn is None: if self.mongo_user is None: try: self.__conn = MongoClient('mongodb://%s:%s' % (self.mongo_host, self.mongo_port)) except errors.PyMongoError as py_mongo_error: print('Error in MongoDB connection: %s' % str(py_mongo_error)) else: try: self.__conn = MongoClient('mongodb://%s:%s@%s:%s' % (self.mongo_user, self.mongo_password, self.mongo_host, self.mongo_port)) except errors.PyMongoError as py_mongo_error: print('Error in MongoDB connection: %s' % str(py_mongo_error))
def add_metrics(self, k, v): """add each metric to the metrics list""" global body dict_metrics = {} dict_metrics["key"] = k dict_metrics["value"] = v self.__metrics.append(dict_metrics) dic = json.dumps(dict_metrics, sort_keys=True, indent=4, separators=(',', ':')).replace('}', '},') f = open('/tmp/mongometrics0001.txt','a') f.write(dic) f.close os.system("cat /tmp/mongometrics0001.txt |sed '$s/\}\,/\}\]/g;1s/{/[{/' > /tmp/mongometrics0002.txt") with open('/tmp/mongometrics0002.txt','r') as src: body = src.read() print(body)
def get_db_names(self): """get a list of DB names""" if self.__conn is None: self.connect() db_handler = self.__conn[self.mongo_db[0]]
master = db_handler.command('isMaster')['ismaster'] dict_metrics = {} dict_metrics['key'] = 'mongodb.ismaster' if master: dict_metrics['value'] = 1 db_names = self.__conn.database_names() self.__dbnames = db_names else: dict_metrics['value'] = 0 self.__metrics.append(dict_metrics)
def get_mongo_db_lld(self): """print DB list in json format, to be used for mongo db discovery""" if self.__dbnames is None: db_names = self.get_db_names() else: db_names = self.__dbnames dict_metrics = {} db_list = [] dict_metrics['key'] = 'mongodb.discovery' dict_metrics['value'] = {"data": db_list} if db_names is not None: for db_name in db_names: dict_lld_metric = {} dict_lld_metric['{#MONGODBNAME}'] = db_name db_list.append(dict_lld_metric) dict_metrics['value'] = '{"data": ' + json.dumps(db_list) + '}' self.__metrics.insert(0, dict_metrics)
def get_oplog(self): """get replica set oplog information""" if self.__conn is None: self.connect() db_handler = self.__conn['local']
coll = db_handler.oplog.rs
op_first = (coll.find().sort('$natural', 1).limit(1)) op_last = (coll.find().sort('$natural', -1).limit(1))
if op_first.count() > 0 and op_last.count() > 0: op_fst = (op_first.next())['ts'].time op_last_st = op_last[0]['ts'] op_lst = (op_last.next())['ts'].time
status = round(float(op_lst - op_fst), 1) self.add_metrics('mongodb.oplog', status)
current_time = timegm(gmtime()) oplog = int(((str(op_last_st).split('('))[1].split(','))[0]) self.add_metrics('mongodb.oplog-sync', (current_time - oplog))
def get_maintenance(self): """get replica set maintenance info""" if self.__conn is None: self.connect() db_handler = self.__conn
fsync_locked = int(db_handler.is_locked) self.add_metrics('mongodb.fsync-locked', fsync_locked)
try: config = db_handler.admin.command("replSetGetConfig", 1) connstring = (self.mongo_host + ':' + str(self.mongo_port)) connstrings = list()
for i in range(0, len(config['config']['members'])): host = config['config']['members'][i]['host'] connstrings.append(host)
if connstring in host: priority = config['config']['members'][i]['priority'] hidden = int(config['config']['members'][i]['hidden'])
self.add_metrics('mongodb.priority', priority) self.add_metrics('mongodb.hidden', hidden) except errors.PyMongoError: print ('Error while fetching replica set configuration.' 'Not a member of replica set?') except UnboundLocalError: print ('Cannot use this mongo host: must be one of ' + ','.join(connstrings)) exit(1)
def get_server_status_metrics(self): """get server status""" if self.__conn is None: self.connect() db_handler = self.__conn[self.mongo_db[0]] ss = db_handler.command('serverStatus')
self.add_metrics('mongodb.version', ss['version']) self.add_metrics('mongodb.storageEngine', ss['storageEngine']['name']) self.add_metrics('mongodb.uptime', int(ss['uptime'])) self.add_metrics('mongodb.okstatus', int(ss['ok']))
for k, v in ss['asserts'].items(): self.add_metrics('mongodb.asserts.' + k, v)
for k, v in ss['opcounters'].items(): self.add_metrics('mongodb.operation.' + k, v)
for k, v in ss['connections'].items(): self.add_metrics('mongodb.connection.' + k, v)
self.add_metrics('mongodb.page.faults', ss['extra_info']['page_faults'])
if ss['storageEngine']['name'] == 'wiredTiger': self.add_metrics('mongodb.used-cache', ss['wiredTiger']['cache'] ["bytes currently in the cache"]) self.add_metrics('mongodb.total-cache', ss['wiredTiger']['cache'] ["maximum bytes configured"]) self.add_metrics('mongodb.dirty-cache', ss['wiredTiger']['cache'] ["tracked dirty bytes in the cache"])
lock_total_time = ss['globalLock']['totalTime'] self.add_metrics('mongodb.globalLock.totalTime', lock_total_time) for k, v in ss['globalLock']['currentQueue'].items(): self.add_metrics('mongodb.globalLock.currentQueue.' + k, v) for k, v in ss['globalLock']['activeClients'].items(): self.add_metrics('mongodb.globalLock.activeClients.' + k, v)
def get_db_stats_metrics(self): """get DB stats for each DB""" if self.__conn is None: self.connect() if self.__dbnames is None: self.get_db_names() if self.__dbnames is not None: for mongo_db in self.__dbnames: db_handler = self.__conn[mongo_db] dbs = db_handler.command('dbstats') for k, v in dbs.items(): if k in ['storageSize', 'ok', 'avgObjSize', 'indexes', 'objects', 'collections', 'fileSize', 'numExtents', 'dataSize', 'indexSize', 'nsSizeMB']: self.add_metrics('mongodb.stats.' + k + '[' + mongo_db + ']', int(v)) def close(self): """close connection to mongo""" if self.__conn is not None: self.__conn.close()
def build_signature(customer_id, shared_key, date, content_length, method, content_type, resource): x_headers = 'x-ms-date:' + date string_to_hash = method + "\n" + str(content_length) + "\n" + content_type + "\n" + x_headers + "\n" + resource bytes_to_hash = bytes(string_to_hash).encode('utf-8') decoded_key = base64.b64decode(shared_key) encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest()) authorization = "SharedKey {}:{}".format(customer_id,encoded_hash) return authorization
def mongodb_azuremonitor_loganalysis_post_data(customer_id, shared_key, body, log_type): method = 'POST' content_type = 'application/json' resource = '/api/logs' rfc1123date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT') content_length = len(body) signature = build_signature(customer_id, shared_key, rfc1123date, content_length, method, content_type, resource) uri = 'https://' + customer_id + '.ods.opinsights.azure.com' + resource + '?api-version=2016-04-01'
headers = { 'content-type': content_type, 'Authorization': signature, 'Log-Type': log_type, 'x-ms-date': rfc1123date }
response = requests.post(uri,data=body, headers=headers) if (response.status_code >= 200 and response.status_code <= 299): print 'Accepted' else: print "Response code: {}".format(response.status_code)
if __name__ == '__main__': mongodb = MongoDB() mongodb.delete_temporary_files() mongodb.get_db_names() mongodb.get_mongo_db_lld() mongodb.get_oplog() mongodb.get_maintenance() mongodb.get_server_status_metrics() mongodb.get_db_stats_metrics() mongodb.close() mongodb_azuremonitor_loganalysis_post_data(customer_id, shared_key, body, log_type)
|