Skip to content

Instantly share code, notes, and snippets.

@jackeyGao
Created August 10, 2016 07:21
Show Gist options
  • Select an option

  • Save jackeyGao/28900ab2f866a45c5ea02d7660f6308f to your computer and use it in GitHub Desktop.

Select an option

Save jackeyGao/28900ab2f866a45c5ea02d7660f6308f to your computer and use it in GitHub Desktop.
函数式编程初试
# -*- coding: utf-8 -*-
'''
File Name: client.py
Author: JackeyGao
mail: [email protected]
Created Time: 三 8/10 10:35:02 2016
'''
import json
import sys
from collections import defaultdict
from pyzabbix import ZabbixAPI
ZABBIX_API_USERNAME="admin"
ZABBIX_API_PASSWORD="admin"
ZABBIX_API_URL="http://xx.xxx.xxx.xx/zabbix/"
DB_SERVERS = (
"172.xx.xx.xxx",
"172.xx.xx.xxx",
"172.xx.xx.xxx",
"172.xx.xx.xxx",
"172.xx.xx.xxx",
"172.xx.xx.xxx",
"172.xx.xx.xxx",
"172.xx.xx.xxx",
)
ITEM_KEYS = {
('system.cpu.load[all,avg1]', 'cpuload'),
('vfs.fs.size[/,used]', 'diskusage'),
('mysql.status[Com_connected]', 'com_conned'),
('mysql.status[Com_runconn]', 'com_connedrun'),
('mysql.status[Com_select]', 'select'),
('mysql.status[Com_insert]', 'insert'),
('mysql.status[Com_update]', 'update'),
('mysql.status[Com_delete]', 'delete'),
}
ITEM_KEYS = dict(ITEM_KEYS)
interfaces = []
# Create one zabbix connection of zabbix server
z = ZabbixAPI(ZABBIX_API_URL)
# Login authentication
z.login(ZABBIX_API_USERNAME, ZABBIX_API_PASSWORD)
# Get hostid list based on ip list .
for interface in z.hostinterface.get(
output="extend",
selectItems="extend",
filter={"ip": DB_SERVERS}
):
interfaces.append(interface)
def history(itemid):
return z.history.get(
output="extend",
itemids=itemid,
limit=1,
sortfield = "clock",
sortorder = "DESC",
)
def build_create(ob):
""" 计算OPS, TPS 并推送到接口"""
entry = {}
def get_value(key, default=0):
historys = ob[key]
if not historys:
return 0
history = historys[0]
return history.get("value", default)
select = get_value("select")
insert = get_value("insert")
update = get_value("update")
delete = get_value("delete")
entry["tps"] = delete + insert + update
entry["qps"] = select
entry["com_conned"] = get_value("com_conned")
entry["com_connedrun"] = get_value("com_connedrun")
entry["cpuload"] = get_value("cpuload")
entry["diskusage"] = get_value("diskusage")
return entry
def handler(interface, callback, *args, **kwargs):
ob = {}
for i in interface["items"]:
if i["key_"] not in ITEM_KEYS.keys():
continue
# Get item key by the item object key_
item_key = ITEM_KEYS[i["key_"]]
# Get last history
last_history = history(i["itemid"])
ob[item_key] = last_history
return callback(ob, *args, **kwargs)
if __name__ == '__main__':
for interface in interfaces:
print handler(interface, build_create)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment