市面上有很多开源的监控系统:cacti、nagios、zabbix。感觉都不符合我的需求,为什么不自己做一个呢
用python两个小时徒手撸了一个简易的监控系统,给大家分享一下,希望能对大家有所启发
首先数据库建表
建立一个数据库“falcon”,建表语句如下:
create table `stat` (
`id` int(11) unsigned not null auto_increment,
`host` varchar(256) default null,
`mem_free` int(11) default null,
`mem_usage` int(11) default null,
`mem_total` int(11) default null,
`load_avg` varchar(128) default null,
`time` bigint(11) default null,
primary key (`id`),
key `host` (`host`(255))
) engine=innodb auto_increment=0 default charset=utf8;
首先我们设计一个web服务,实现如下功能:
1.完成监控页面展示
2.接受post提交上来的数据
3.提供json数据get接口
目录结构如下:
web
├── flask_web.py
└── templates
└── mon.html
[/code]
flask_web.py
[code]
import mysqldb as mysql
import json
from flask import flask, request, render_template
app = flask(__name__)
db = mysql.connect(user=”reboot”, passwd=”reboot123″, \
db=”falcon”, charset=”utf8″)
db.autocommit(true)
c = db.cursor()
@app.route(“/”, methods=[“get”, “post”])
def hello():
sql = “”
if request.method == “post”:
data = request.json
try:
sql = “insert into `stat` (`host`,`mem_free`,`mem_usage`,`mem_total`,`load_avg`,`time`) values(‘%s’, ‘%d’, ‘%d’, ‘%d’, ‘%s’, ‘%d’)” % (data[‘host’], data[‘memfree’], data[‘memusage’], data[‘memtotal’], data[‘loadavg’], int(data[‘time’]))
ret = c.execute(sql)
except mysql.integrityerror:
pass
return “ok”
else:
return render_template(“mon.html”)
@app.route(“/data”, methods=[“get”])
def getdata():
c.execute(“select `time`,`mem_usage` from `stat`”)
ones = [[i[0]*1000, i[1]] for i in c.fetchall()]
return “%s(%s);” % (request.args.get(‘callback’), json.dumps(ones))
if __name__ == “__main__”:
app.run(host=”0.0.0.0″, port=8888, debug=true)
这个template页面是我抄的highstock的示例,mon.html
简单起见我们只展示mem_usage信息到页面上
jb51.net
highstock example
《script》
$(function () {
$.getjson(‘/data?callback=?’, function (data) {
// create the chart
$(‘#container’).highcharts(‘stockchart’, {
rangeselector: {
inputenabled: $(‘#container’).width() > 480,
selected: 1
},
title: {
text: ‘jb51.net’
},
series: [{
name: ‘jb51.net’,
data: data,
type: ‘spline’,
tooltip: {
valuedecimals: 2
}
}]
});
});
});
《script》
《script》
《script》
web展示页面完成了,运行起来:
python flask_web.py 监听在8888端口上
我们需要做一个agent来采集数据,并上传数据库
moniitems.py
#!/usr/bin/env python
import inspect
import time
import urllib, urllib2
import json
import socket
class mon:
def __init__(self):
self.data = {}
def gettime(self):
return str(int(time.time()) + 8 * 3600)
def gethost(self):
return socket.gethostname()
def getloadavg(self):
with open(‘/proc/loadavg’) as load_open:
a = load_open.read().split()[:3]
return ‘,’.join(a)
def getmemtotal(self):
with open(‘/proc/meminfo’) as mem_open:
a = int(mem_open.readline().split()[1])
return a / 1024
def getmemusage(self, nobuffercache=true):
if nobuffercache:
with open(‘/proc/meminfo’) as mem_open:
t = int(mem_open.readline().split()[1])
f = int(mem_open.readline().split()[1])
b = int(mem_open.readline().split()[1])
c = int(mem_open.readline().split()[1])
return (t-f-b-c)/1024
else:
with open(‘/proc/meminfo’) as mem_open:
a = int(mem_open.readline().split()[1]) – int(mem_open.readline().split()[1])
return a / 1024
def getmemfree(self, nobuffercache=true):
if nobuffercache:
with open(‘/proc/meminfo’) as mem_open:
t = int(mem_open.readline().split()[1])
f = int(mem_open.readline().split()[1])
b = int(mem_open.readline().split()[1])
c = int(mem_open.readline().split()[1])
return (f+b+c)/1024
else:
with open(‘/proc/meminfo’) as mem_open:
mem_open.readline()
a = int(mem_open.readline().split()[1])
return a / 1024
def runallget(self):
#自动获取mon类里的所有getxxx方法,用xxx作为key,getxxx()的返回值作为value,构造字典
for fun in inspect.getmembers(self, predicate=inspect.ismethod):
if fun[0][:3] == ‘get’:
self.data[fun[0][3:]] = fun[1]()
return self.data
if __name__ == “__main__”:
while true:
m = mon()
data = m.runallget()
print data
req = urllib2.request(“http://jb51.net:8888”, json.dumps(data), {‘content-type’: ‘application/json’})
f = urllib2.urlopen(req)
response = f.read()
print response
f.close()
time.sleep(60)
nohup python moniitems.py >/dev/null 2>&1 & 运行起来
访问 http://jb51.net:8888 就可以看到我们的监控数据了:效果图如下