This article mainly introduces a simple monitoring system written in Python. This article describes the detailed coding steps and provides the corresponding implementation code, for more information, see the following open-source monitoring systems on the market: Cacti, nagios, and zabbix. I don't feel like it meets my needs. why don't I do it myself?
I spent two hours using Python to prepare a simple monitoring system. I hope it will inspire you.
First, create a database table.
Create a database "falcon". The table creation statement is as follows:
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;
First, we design a web service to implement the following functions:
1. complete the monitoring page display
2. accept the data submitted by POST
3. provides the GET interface for json data
The directory structure is as follows:
web├── flask_web.py└── templates └── mon.html[/code]flask_web.py[code]import MySQLdb as mysqlimport jsonfrom flask import Flask, request, render_templateapp = 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)
This templatepage is a copy of the highstocks' example, mon.html
For simplicity, we only display mem_usage information to the page.
Jb51.net
Highstock Example