zabbix 预测数据

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author : liuyu
# date : 2018/9/4 0004
import requests

import math,json,time
import matplotlib.pyplot as plt

class ZabbixApi(object):

    def __init__(self, username, password, apiurl):
        self.apiurl = apiurl
        self.username = username
        self.password = password
        self.token = ""

    def gettoken(self):
        data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": self.username,
                "password": self.password
            },
            "id": 1,
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        if errormsg:
            return errormsg
        self.token = jsonrequest.get("result", "")
        return self.token

    def getidfromgroupname(self, groupname):
        data = {
            "jsonrpc": "2.0",
            "method": "hostgroup.get",
            "params": {
                "output": "extend",
                "filter": {
                    "name": groupname,
                }
            },
            "auth": self.token,
            "id": 1
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        if errormsg:
            return errormsg
        return jsonrequest.get("result", "")[0].get("groupid", "")

    def gethostfromgid(self, groupid):
        data = {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": "extend",
                "groupids": groupid
            },
            "auth": self.token,
            "id": 1
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        hostinfos = {}
        if errormsg:
            return errormsg
        for hostinfo in jsonrequest.get("result", ""):
            hostinfos[hostinfo.get("hostid")] = hostinfo.get("host")
        return hostinfos

    def getvaluesformkey(self, itemkey, gid):
        data = {
            "jsonrpc": "2.0",
            "method": "item.get",
            "params": {
                "output": "extend",
                "groupids": gid,
                "search": {
                    "key_": itemkey
                },
                "sortfield": "name"
            },
            "auth": self.token,
            "id": 1
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        hostinfos = {}
        if errormsg:
            return errormsg
        for hostinfo in jsonrequest.get("result", ""):
            hostinfos[hostinfo.get("hostid")] = {"lastvalue": hostinfo.get("lastvalue"), "error": hostinfo.get("error"),
                                                 "units": hostinfo.get("units"),"itemid":hostinfo.get("itemid")}
        return hostinfos


    def gethistoryinfo(self,itemids,limit):
        data={
            "jsonrpc": "2.0",
            "method": "history.get",
            "params": {
                "output": "extend",
                "history": 3,
                "itemids": itemids,
                "sortfield": "clock",
                "sortorder": "DESC",
                "limit": limit
            },
            "auth": self.token,
            "id": 13
        }

        r = requests.post(self.apiurl, json=data, timeout=25)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        if errormsg:
            return errormsg
        return jsonrequest.get("result")

class HuiTu(object):

    @staticmethod
    def linefit(x, y):
        N = float(len(x))
        sx, sy, sxx, syy, sxy = 0, 0, 0, 0, 0
        for i in range(0, int(N)):
            sx += x[i]
            sy += y[i]
            sxx += x[i] * x[i]
            syy += y[i] * y[i]
            sxy += x[i] * y[i]
        a = (sy * sx / N - sxy) / (sx * sx / N - sxx)
        b = (sy - a * sx) / N
        r = abs(sy * sx / N - sxy) / math.sqrt((sxx - sx * sx / N) * (syy - sy * sy / N))
        return a, b, r

    def showpic(self,result):
        xArr = []
        yArr = []
        for data in result:
            # print(data)

            xArr.append(int(data.get("clock")))
            yArr.append(int(data.get("value")))
        x = xArr
        y = yArr

        a, b, r = self.linefit(x, y)

        print("X=", x)
        print("Y=", y)
        print("拟合结果: y = %10.15f x + %10.15f , r=%10.15f" % (a, b, r))
        plt.plot(x, y, "r:", linewidth=2)
        plt.grid(True)
        # plt.title(hostname, color='#123456')
        plt.show()
        timestamp = int((102400.00 - b) / a)

        time_local = time.localtime(timestamp)
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        return timestamp

    def run(self,result,hostname):
        # deal with data
        xArr = []
        yArr = []
        for data in result:
            # print(data)

            xArr.append(int(data.get("clock")))
            yArr.append(int(data.get("value")))
        x = xArr
        y = yArr

        a, b, r = self.linefit(x, y)

        # print("X=", x)
        # print("Y=", y)
        # print("拟合结果: y = %10.15f x + %10.15f , r=%10.15f" % (a, b, r))

        timestamp = int((102400.00 - b)/a)

        time_local = time.localtime(timestamp)
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        # time_local = time.localtime(int(key))
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        print("== 预计下次维护时间: {}".format(str(dt)))
        plt.plot(x, y, "r:", linewidth=2)
        plt.grid(True)
        plt.title("{}  {}".format(hostname,str(dt)), color='#123456')
        plt.savefig(hostname+".png")
        plt.show()
        return timestamp




zabbix_obj = ZabbixApi("Admin", "ZabbiX", "http://localhost/zabbix/api_jsonrpc.php")

zabbix_obj.gettoken()
gid = zabbix_obj.getidfromgroupname("tg_hosts")
hostinfos = zabbix_obj.gethostfromgid(gid)



def showpics():
    results=zabbix_obj.gethistoryinfo("33169",48*30)
    huitu=HuiTu()
    key=huitu.showpic(results)
    time_local = time.localtime(int(key))
    print(time_local)
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
    print("预计下次维护时间: {}".format(str(dt)))
    # print("主机:{} == 数据库大小:{} M == 预计下次维护时间: {}".format(value[0],value[1].get("lastvalue"),str(dt)))


# showpics()
# exit()

def keyss(ks):
    key, = ks.keys()
    return int(key)

def tablesget():
    iteminfos = zabbix_obj.getvaluesformkey("table.amount", gid)
    infos = {}
    for k in iteminfos:
        infos[hostinfos.get(k)] = iteminfos[k]

    # print(infos)
    # 按照lastvalue 的大小进行排序输出
    infos = sorted(infos.items(), key=lambda d: int(d[1].get("lastvalue")), reverse=True)

    for i in infos:
       print(i)

    print(infos)


tablesget()


def getmysqldata():
    iteminfos = zabbix_obj.getvaluesformkey("mysql.data.size", gid)
    infos = {}
    for k in iteminfos:
        infos[hostinfos.get(k)] = iteminfos[k]

    # print(infos)
    # 按照lastvalue 的大小进行排序输出
    infos = sorted(infos.items(), key=lambda d: int(d[1].get("lastvalue")), reverse=True)
    reinfolists=[]
    for i in infos:
        if 'No such file or directory]' in json.dumps(i[1]):
            continue

        if int(i[1].get("lastvalue"))>1024000:
            yugaodate="0"
        else:
            itemid = i[1].get("itemid")
            results = zabbix_obj.gethistoryinfo(itemid, 48 * 30)
            huitu=HuiTu()
            yugaodate=str(huitu.run(results,i[0]))
            reinfolists.append({yugaodate:i})
        # print("{} === 预计时间:  {}".format(str(i),yugaodate))
        time.sleep(3)

    print(reinfolists)


    reinfosort=sorted(reinfolists, key=keyss)
    for i in reinfosort :
        (key, value), = i.items()
        time_local = time.localtime(int(key))
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        print("城市:{} == 数据库大小:{} M == 预计下次维护时间: {}".format(value[0],value[1].get("lastvalue"),str(dt)))

getmysqldata()

图片.png

  • zabbix 预测数据已关闭评论
  • 950 views
    A+
发布日期:2018年09月13日  所属分类:Python