Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
petrushinvs committed Dec 10, 2018
0 parents commit 48ed6e7
Show file tree
Hide file tree
Showing 8 changed files with 2,928 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Vasily Petrushin, Sunwind, Moscow

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# mongodb-zabbix-templates

#Zabbix templates for mongodb monitoring

The main tasks of monitoring for us:

1. Watch and notify the support team if mongodb instances is not running or not reachable
2. Watch a basic mongodb and mongos opcounters
3. Watch and notify for Mongodb Replicasets health
4. Watch DiskIO counters - it runs well with outstanding third party Iostat-Disk-Utilization-Template (https://github.com/lesovsky/zabbix-extensions/tree/master/files/iostat)
5. Provide easy-to-use and easy-to-understand user view for staff.

Technically, for fine mongodb performance tuning you need much more information than provides this templates, but its harder to
collect, store and visualize with Zabbix, and anyway it would be better to use specially designed mongodb tools.
Google it for more information.

This package contains 3 templates for monitoring mongodb instances (Mongo-DB template), mongos instance (Mongos template) and replicaset health (Mongo-RS Health template).
By customising your hosts configurations with this templates you can monitor lagre mongodb clusters. For us it monitors 10 mongodb instances in sharded 5 big replicasets, 4 instances of small metadata database, config database replicaset, 5 mongos routers and backup server.

##How to install Mongo-DB template

Mongo-DB template is used to collect the basic mongodb server opcounters and notify if the instance is gone.

Server requirements:
Ubuntu 14.04 (tested, but should work on any linux, Centos 6,7, Ubuntu 12.04, 16.04, 18.04 etc.)
Zabbix server 2.4 - 4.0 (tested, but should work with any Zabbix 2.x)
Latest mongodb-org-tools and mongodb-org-shell linux packages installed

1. Downoad package from github.
2. Import xml templates to Zabbix server via browser
Configuration -> Templates -> Import template
3. Upload \*.py files to zabbix server, put it to external scrips folder (/usr/lib/zabbix/externalscrips for my server), and
chown +x mongo\*.py
4. Install on zabbix server required python modules via command line
<pre><code>
sudo pip install pymongo
sudo pip install py-zabbix
</code></pre>
5. Navigate to hosts configuration in zabbix server and add Mongo-DB template to host with mongodb instance.
6. In Macros tab add the following data
<pre><code>
{$MONGODB_HOSTNAME} IP or DNS name of interface used by mongodb instance
{$MONGODB_USER} User name
{$MONGODB_PASS} Password
{$MONGODB_PORT} Port used by mongodb instance
{$MONGODB_ZABBIX_NAME} Server hostname, as it registered in zabbix (I use two different interfaces for each mongodb server, mongodb instance is using one, other services including zabbix agent - another).
</code></pre>

In a few minutes it starts to collect data. See the Misc: Data collector in zabbix latest data for easy debug.

For Mongo-DB zabbix graphs go to Monitoring -> Graphs, then select the host with mongodb instance and select Mongo-DB Opcounters and Mongo-DB Network IO graphs. The best way to use this data by your team is to compose special zabbix screens with this graphs with all your servers. How to do this see https://www.zabbix.com/documentation/2.4/manual/config/visualisation/screens

##How to install Mongos template

Mongos template is used to collect the basic mongos server opcounters and notify if the instance is gone.

In case you run mongos instance on the same hardware with any mongodb instance and have the same hostname, user and pass Mongos template will use the Macros data from previously configured Mongo-DB template. You have to do only two steps to get Mongos template running.
1. Navigate to hosts configuration in zabbix server and add Mongos template to host with mongos instance.
2. In Macros tab add the following data
<pre><code>{$MONGOS_PORT} Port used by mongodb instance</code></pre>
In case the mongos instance is running on dedicated hardware or VM you have to add in Macros tab the following data
<pre><code>{$MONGODB_HOSTNAME} IP or DNS name of interface used by mongodb instance
{$MONGODB_USER} User name
{$MONGODB_PASS} Password
{$MONGOS_PORT} Port used by mongodb instance
{$MONGODB_ZABBIX_NAME} Server hostname, as it registered in zabbix (I use two different interfaces for each mongodb server, mongodb instance is using one, other services including zabbix agent - another).
</code></pre>

In a few minutes it starts to collect data. See the Mongos Misc: Mongos data collector in zabbix latest data for easy debug.

##How to install Mongo-RS probe template

Mongo-RS probe template is used to watch for replicasets. It watch at entire replicaset, then tries to insert a test record and notify if replicaset or one of replicaset members goes unreachable.
Create new host in zabbix named like replicaset, for example rs0, then add Mongo-RS template to this host.
In Macros tab add the Macroses

<pre><code>
{$MONGO_USER} User
{$MONGO_PASS} Password
{$RS_NAME} rs0
{$RS_STRING} mongo00.domain.com:port,mongo01.domain.com:port,mongo02.domain.com:port
{$RS_ZABBIX_NAME} rs0
</code></pre>

See RS data collector in Mongo Replica Set section in zabbix latest data for debug.

## How to monitor more than one mongodb instance

The easiest way to monitor more than one mongodb instance is to create new host in zabbix then add a MongoDB template with different {$MONGODB_PORT}

## Contacts

Vasily Petrushin
petrushinvs@gmail.com
172 changes: 172 additions & 0 deletions mongod-db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
#!/usr/bin/python
#
from __future__ import print_function
import sys, getopt
from pyzabbix import ZabbixMetric, ZabbixSender
from pymongo import MongoClient
import time
import subprocess
import re

ZBSERVER = 'localhost'
ZBPORT = 10051

try:
opts, args = getopt.getopt(sys.argv[1:],"h:n:p:u:s:")
except getopt.GetoptError:
print ("Usage:\nmongod-db.py -h <hostname or ip mongod is listening to> -n <hostname in zabbix> -u <user> -s <secret pass> -p <mongod port>")
sys.exit(2)

for opt, arg in opts:
if opt == '-h':
mongohost = arg
elif opt == '-n':
zbhost = arg
elif opt == '-p':
mongoport = arg
elif opt == '-u':
muser = arg
elif opt == '-s':
mpass = arg

arg = "-u " + muser + " -p " + mpass + " -h " + mongohost + ":" + mongoport + " --authenticationDatabase=admin --rowcount 1 --noheaders"
cmd = ['mongostat', "-u", muser, "-p", mpass, "-h", mongohost + ":" + mongoport, "--authenticationDatabase=admin", "--rowcount", "1", "--noheaders"]
r = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = r.communicate()
res = out + err

#print("DEBUG: STR: " + arg)
#print("DEBUG: RES: " + res)
#print("DEBUG: ERR: " + err + str(len(err)))

state = 0
if len(err) > 0:
packet = [ ZabbixMetric(zbhost, 'mongodb_state', state),
ZabbixMetric(zbhost, 'mongodb_errstr', err) ]
result = ZabbixSender(zabbix_port = ZBPORT, zabbix_server = ZBSERVER).send(packet)
print(err)
sys.exit(1)
res = res.rstrip()
res = res.replace('*','')
res = re.sub("^ +","",res)
arr = re.split(" +", res)

def str_to_int(s):
m = re.match('(\d+)(\[a-z]|[A-Z])', s)
r = re.match('(\d+).(\d+)(\[a-z]|[A-Z])', s)
if r:
m = r
if m:
i = int(m.group(1))
if m.group(2) == 'k':
i = i * 1000
elif m.group(2) == 'm':
i = i * 1000 * 1000
else:
try:
i = int(s)
except:
i = 0
return i

def str_to_bytes(s):
m = re.match('(\d+)(\[a-z]|[A-Z])', s)
r = re.match('(\d+).(\d+)(\[a-z]|[A-Z])', s)
if r:
m = r
if m:
i = int(m.group(1))
if m.group(2) == 'k' or m.group(2) == 'K':
i = i * 1024
elif m.group(2) == 'm' or m.group(2) == 'M':
i = i * 1024 * 1024
elif m.group(2) == 'g' or m.group(2) == 'G':
i = i * 1024 * 1024 * 1024
else:
try:
i = int(s)
except:
i = 0
return i

if len(arr) < 18:
err = 'Unknown error!'
packet = [ ZabbixMetric(zbhost, 'mongodb_state', state),
ZabbixMetric(zbhost, 'mongodb_errstr', err) ]
result = ZabbixSender(zabbix_port = ZBPORT, zabbix_server = ZBSERVER).send(packet)
print(err)
sys.exit(1)

# Human readable names for better understanding
insert, query, update, delete, getmore, command, dirty, used, flushes, vsize, resm, qr, ar, netin, netout, conn, rset, repl = arr[:18]
# Add known opcounters to zabbix packet
err = 'OK'
state = 1
packet = [ ZabbixMetric(zbhost, 'mongodb_state', state),
ZabbixMetric(zbhost, 'mongodb_errstr', err) ]
conn = str_to_int(conn)
packet.append(ZabbixMetric(zbhost, "mongodb_conn", conn))
packet.append(ZabbixMetric(zbhost, "mongodb_rs_name", rset))
packet.append(ZabbixMetric(zbhost, "mongodb_rs_status", repl))
m = re.match('(\d+)\|(\d+)',ar)
if m:
ar = m.group(1)
aw = m.group(2)
else:
ar = 0
aw = 0
packet.append(ZabbixMetric(zbhost, "mongodb_aclients_read", ar))
packet.append(ZabbixMetric(zbhost, "mongodb_aclients_write", aw))
vsize = str_to_bytes(vsize)
packet.append(ZabbixMetric(zbhost, "mongodb_vsize", vsize))
netin = str_to_bytes(netin)
packet.append(ZabbixMetric(zbhost, "mongodb_netin", netin))
netout = str_to_bytes(netout)
packet.append(ZabbixMetric(zbhost, "mongodb_netout", netout))

# Read saved opcounters from previous check
try:
f = open("/tmp/" + mongohost + "-opcounters")
s = f.read()
f.close()
ts, insert, update, delete, query, getmore, command = s.split(" ")
except Exception as e:
ts, insert, update, delete, query, getmore, command = [1,0,0,0,0,0,0]
print(e)

print("History opcounters")
print(ts, insert, update, delete, query, getmore, command)

# Get serverStatus stats
try:
mo = MongoClient('mongodb://' + muser + ':' + mpass + '@' + mongohost + ':' + mongoport + '/admin', connectTimeoutMS=5000)
except Exception as e:
print ('Can\'t connect to '+mongohost)
print ("ERROR:", e)
sys.exit(1)
res = mo.admin.command('serverStatus')
now = time.time()
#$zab->send("mongodb_insert", int(($res->{opcounters}->{insert} - $insert)/(($now-$ts)/60)));
packet.append(ZabbixMetric(zbhost, "mongodb_insert", int((float(res['opcounters']['insert']) - float(insert))/((now - float(ts))/60))))
packet.append(ZabbixMetric(zbhost, "mongodb_update", int((float(res['opcounters']['update']) - float(update))/((now - float(ts))/60))))
packet.append(ZabbixMetric(zbhost, "mongodb_delete", int((float(res['opcounters']['delete']) - float(delete))/((now - float(ts))/60))))
packet.append(ZabbixMetric(zbhost, "mongodb_query", int((float(res['opcounters']['query']) - float(query))/((now - float(ts))/60))))
packet.append(ZabbixMetric(zbhost, "mongodb_getmore", int((float(res['opcounters']['getmore']) - float(getmore))/((now - float(ts))/60))))
packet.append(ZabbixMetric(zbhost, "mongodb_command", int((float(res['opcounters']['command']) - float(command))/((now - float(ts))/60))))
# Total ops since last run (per minute approx)
total_ops = res['opcounters']['insert'] + res['opcounters']['update'] + res['opcounters']['delete'] + res['opcounters']['query'] + \
res['opcounters']['getmore'] + res['opcounters']['command'] - int(insert) - int(update) - int(delete) - int(query) - int(getmore) - int(command)
packet.append(ZabbixMetric(zbhost, "mongodb_total_ops", total_ops))

# Save opcounters
try:
f = open("/tmp/" + mongohost + "-opcounters", 'w')
f.write(str(int(now)) + ' ' + str(res['opcounters']['insert']) + ' ' + str(res['opcounters']['update']) + ' ' + str(res['opcounters']['delete']) + ' ' + \
str(res['opcounters']['query']) + ' ' + str(res['opcounters']['getmore']) + ' ' + str(res['opcounters']['command']))
f.close()
except Exception as e:
print("Can't update stats!")
print(e)

t = ZabbixSender(zabbix_port = ZBPORT, zabbix_server = ZBSERVER).send(packet)
print(t)
Loading

0 comments on commit 48ed6e7

Please sign in to comment.