使用Flask结合python实现多台服务的内存监控

 

简介:使用flask结合python可以很好的实现服务资源的监控,而且Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug 模板引擎则使用 Jinja2 Flask使用 BSD 授权。

接下来我们实现多台服务器的内存监控,并出图。

环境:centos1-6.5  ip:172.25.0.31   ##flask python数据获取

      Centos2-6.5  ip:172.25.0.32   ##做本地内存消耗数据的获取

实现过程:

一、内存数据的获取,并写入到数据库

1、我们先查看一下内存的信息

[root@centos mem]# cat /proc/meminfo
MemTotal:        1528700 kB
MemFree:          221028 kB
Buffers:          130764 kB
Cached:           604596 kB
SwapCached:         8440 kB

说明:

buffers是指用来给块设备做的缓冲大小

cached是用来给文件做缓冲。

MemFree 是空闲内存

 

已使用内存算法:

已使用内存 = MemTotal - MemFree - Buffers - Cached

2、安装数据库,并创建数据库和表。

为了减少资源的开销,所以我们两台机器都装上mysqlcentos1-6.5Centos2-6.5同时执行以下命令。

[root@centos ~]#yum  install  -y  mysql-server  mysql-devel

#启动mysql

[root@centos ~]#/etc/init.d/mysqld  start

 

#快速配置,设置root密码:

[root@centos ~]#mysql_secure_installation

创建数据库:

[root@centos ~]# mysql  -uroot  -p123456
mysql> create database  memory;
mysql> use memory;
mysql> create table memory (memory int, time int);

注意1:用time字段表示时间戳,使用int类型为简单化,这里的数据库名和表名,还有字段名,都使用memory,含义不同

注意2:我们在centos需要在centos2上获取到写入的数据,所以我们要添加权限,让别的主机登录连接到centos2的数据库;

过程如下:

   直接授权

  从任何主机上使用root用户,密码:123456(你的root密码)连接到mysql服务器:


[root@centos2 ~]# mysql -u root –p123456   ##给予其它用户以root远程登录到本地mysql 
mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
mysql>FLUSH PRIVILEGES


3安装MySQL模块,编写脚本。

[root@centos ~]# yum  install  MySQL-python   -y
[root@centos2 ~]# yum  install  MySQL-python   -y


编写脚本监控内存脚本:

Centos

[root@centos~]# cat mem/mysql.py    ##同时把脚本复制到centos2就可以了
# -*- coding:utf-8 -*-
 
import time
import os
import MySQLdb as mysql
 
db = mysql.connect(user="root", passwd="123456", db="memory", host="localhost")
db.autocommit(True)
cur=db.cursor()
 
def saveMem():
     a="awk 'NR==1{print $2}' /proc/meminfo"
     file = os.popen(a)
     total=int(file.read())
 
     b="awk 'NR==2{print $2}' /proc/meminfo"
     file =os.popen(b)
     free =int(file.read())
 
     c="awk 'NR==3{print $2}' /proc/meminfo"
     file = os.popen(c)
     buffer =int(file.read())
 
     d="awk 'NR==4{print $2}' /proc/meminfo"
     file =os.popen(d)
     cache =int(file.read())
 
     mem_used=total-free-buffer-cache
     print mem_used/1024
     #mem = mem_used/1024 
     cur_time = int(time.time())
     sql = 'insert into memory (memory, time) value (%s,%s)'%(mem_used,cur_time)
     cur.execute(sql)
while True:
         saveMem()
         time.sleep(1)   # sleep 1 second

二、展现信息

 1、构建web服务:

安装flask

centos1上执行

使用flask框架构建web服务

 

#安装pip

[root@centos ~]# mkdir /root/tools
[root@centos ~]# cd   /root/tools
[root@centos ~]#wget  --no-check-certificate  https://bootstrap.pypa.io/get-pip.py
[root@centos ~]#python  get-pip.py

#使用pip安装pythonflask模块:

[root@centos ~]#pip  install  flask

2、编辑后台页面

 

[root@centos ~]# cat /mem/flask_web.py
# -*- coding:utf-8 -*-
from flask import Flask,render_template   
import MySQLdb as mysql
import  json
con1 = mysql.connect(user="mysql", passwd="123456", db="memory", host="172.25.0.32")
con1.autocommit(True)
cur1 = con1.cursor()
 
con2 = mysql.connect(user="root", passwd="123456", db="memory", host="localhost")
con2.autocommit(True)
cur2 = con2.cursor()
 
app = Flask(__name__) 
last_time1 = 0
last_time2 = 0
@app.route('/')  
def index():
         return render_template('index.html')
@app.route('/data/a')
def data_a():
        global last_time1
         if (last_time1 > 0):
                   sql = 'select * from memory where time>%s' %(last_time1/1000)
         else:
                 sql = 'select * from memory'
         cur1.execute(sql)
         arr = []
         for i in cur1.fetchall():
                #print i    #在启动flask web服务的终端打印
                arr.append([i[1]*1000, i[0]/1024])   #再除以1024,以MB为单位
         #return 'ok'
        if (len(arr) > 0):
                   last_time1 = arr[-1][0]
 
         return json.dumps(arr)
@app.route('/data/b')
def data_b():
        global last_time2
        if (last_time2 > 0):
                sql = 'select * from memory where time>%s' %(last_time2/1000)
        else:
                sql = 'select * from memory'
        cur2.execute(sql)
        arr = []
        for i in cur2.fetchall():
               #print i    #在启动flask web服务的终端打印
                arr.append([i[1]*1000, i[0]/1024])   #再除以1024,以MB为单位
        #return 'ok'
        if (len(arr) > 0):
                last_time2 = arr[-1][0]
 
        return json.dumps(arr)
 
 
if __name__=='__main__':
        app.run(host='172.25.0.31', port=9092, debug=True)

3、使用图表展现

1)         准备用于显示图片的基础js文件

          jquery.js highstock.js   ##这个网上很多有下载

          并把这两个文件保存到网站根目录下的static子目录下,导入以上两个基础js文件,用来渲染页面。


2)         我们可以看看结构:

[root@centos mem]# tree
.
├── flask_web.py
├── mysql.py
├── static
│   ├── highstock.js
│   └── jquery.js
└── templates
    └── index.html

 

3)         接下来,使用highchats图标,选择图表模板,选择一个基本的图,然后把js代码复制带index.html文件中

https://www.hcharts.cn/demo/highstock/basic-line

 

 

4)         修改前端页面中,配置网页index.html

[root@centos ~]# cat /mem/templates/index.html
<html>
<head>
        <title> my memory monitor </title>
</head>
 
<body>
<div id="container" style="min-width:400px;height:400px"></div>
 
<script src='/static/jquery.js'></script>
<script src='/static/highstock.js'></script>
<script type="text/javascript"> 
     Highcharts.setOptions({ global: { useUTC: false } });  
</script>              
<script>
$(function () {
    var seriesOptions = [],
        seriesCounter = 0,
        names = ['a','b'],
        // create the chart when all data is loaded
        createChart = function () {
            $('#container').highcharts('StockChart', {
                rangeSelector: {
                    selected: 4
                },
                yAxis: {
                    labels: {
                        formatter: function () {
                            return (this.value > 0 ? ' + ' : '') + this.value + '%';
                        }
                    },
                    plotLines: [{
                        value: 0,
                        width: 2,
                        color: 'silver'
                    }]
                },
                plotOptions: {
                    series: {
                        compare: 'percent'
                    }
                },
                tooltip: {
                    pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
                    valueDecimals: 2
                },
                series: seriesOptions
            });
        };
    $.each(names, function (i, name) {
        $.getJSON('/data/' + name.toLowerCase(),    function (data) {
            seriesOptions[i] = {
                name: name,
                data: data
            };
            // As we're loading the data asynchronously, we don't know what order it will arrive. So
            // we keep a counter and create the chart when all the data is loaded.
            seriesCounter += 1;
            if (seriesCounter === names.length) {
                createChart();
            }
        });
    });
});
 
</script>
</body>
</html>

四、执行脚本使用调试模式(google浏览器),查看网页的数据

[root@centos mem]# python mysql.py
[root@centos2 mem]# python mysql.py
[root@centos mem]# python flask_web.py
 * Running on http://172.25.0.31:9092/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 171-534-904
172.25.0.2 - - [28/Nov/2017 21:35:57] "GET / HTTP/1.1" 200 -
172.25.0.2 - - [28/Nov/2017 21:35:57] "GET /data/a HTTP/1.1" 200 -
172.25.0.2 - - [28/Nov/2017 21:35:57] "GET /data/b HTTP/1.1" 200 -
172.25.0.2 - - [28/Nov/2017 21:35:59] "GET / HTTP/1.1" 200 -
172.25.0.2 - - [28/Nov/2017 21:35:59] "GET /data/a HTTP/1.1" 200 -
172.25.0.2 - - [28/Nov/2017 21:35:59] "GET /data/b HTTP/1.1" 200 –

捕获.JPG

我们可以发现,我们已经获取到两台主机的内存得使用情况了。以上是本人的实现监控的搭建过程希望能帮到大家。