Zabbix Go 接口
最近在写一个集合 Bosun 和 Zabbix 上报警的简单看板。
因为之前用了 Go 来写,所以就想用 Go 来写 Zabbix 的接口。到 github 上搜了下,找到了很多 Zabbix Go接口。
最后根据我自己的需要,我选择了 https://github.com/rday/zabbix 。
不过这个项目,缺少了 Trigger 的接口,git 下来之后,根据源码的结构,手动加上即可:
type ZabbixTrigger map[string]interface{}
...
/**
Interface to the trigger.* calls
*/
func (api *API) Trigger(method string, data interface{}) ([]ZabbixTrigger, error) {
response, err := api.ZabbixRequest("trigger."+method, data)
if err != nil {
return nil, err
}
if response.Error.Code != 0 {
return nil, &response.Error
}
res, err := json.Marshal(response.Result)
var ret []ZabbixTrigger
err = json.Unmarshal(res, &ret)
return ret, nil
}
然后就可以调用封装了:
package zabbix
import (
"fmt"
"time"
"strconv"
"github.com/rday/zabbix"
)
var (
ZabbixAPIUrl = "http://ZABBIXSERVER/api_jsonrpc.php"
ZabbixUser = "user"
ZabbixPasswd = "password"
)
type ZabbixAlert struct {
Description string
Host string
Priority string
Lastchange string
}
func TimestampToFormatTime(t string) (ft string, err error) {
i, err := strconv.Atoi(t)
if err != nil {
return
}
tm := time.Unix(int64(i), 0)
ft = tm.Format("2006/01/02 15:04:05")
return
}
func GetTriggers() ([]ZabbixAlert, error) {
ret := make([]ZabbixAlert, 0)
api, err := zabbix.NewAPI(ZabbixAPIUrl, ZabbixUser, ZabbixPasswd)
if err != nil {
fmt.Println(err)
return nil, err
}
_, err = api.Login()
if err != nil {
fmt.Println(err)
return nil, err
}
params := make(map[string]interface{}, 0)
filter := make(map[string]string, 0)
filter["value"] = "1"
params["filter"] = filter
params["monitored"] = "1"
params["min_severity"] = "2"
params["only_true"] = "1"
params["output"] = "extend"
params["selectHosts"] = "extend"
params["sortfield"] = "priority"
params["sortorder"] = "DESC"
triggers, err := api.Trigger("get", params)
if err != nil {
return nil, err
}
if len(triggers) > 0 {
for _, v := range triggers {
//fmt.Println(v)
d := v["description"].(string)
p := v["priority"].(string)
l := v["lastchange"].(string)
var t string
t, e := TimestampToFormatTime(l)
if e != nil {
t = "NaN"
}
h := v["hosts"].([]interface{})
hh := h[0].(map[string]interface{})
ret = append(ret, ZabbixAlert{d, hh["host"].(string), p, t})
}
return ret, err
}
return nil, err
}
json 解析这里写得太渣,不想说了 ...
前端:
效果: