-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzabbix-getter.go
113 lines (93 loc) · 2.42 KB
/
zabbix-getter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/imdario/mergo"
"github.com/yakumo-saki/zabbix-getter/config"
"github.com/yakumo-saki/zabbix-getter/ylog"
"github.com/yakumo-saki/zabbix-getter/zabbix"
)
var logger = ylog.GetLogger()
var Flags config.ConfigStruct // dotenv + flags
func main() {
ylog.Init()
logger = ylog.GetLogger()
ylog.SetLogLevel("WARN")
ylog.SetLogOutput("STDERR")
cfg := config.LoadConfig()
cfgerr := config.CheckConfig(cfg)
if cfgerr != nil {
fmt.Fprint(os.Stderr, cfgerr.Error()+". see help for detail.\n")
os.Exit(10)
return
}
err := ylog.SetLogLevel(cfg.Loglevel)
if err != nil {
ylog.SetLogLevel("WARN")
}
token, autherr := zabbix.Authenticate(cfg.Url, cfg.Username, cfg.Password)
if autherr != nil {
logger.F(autherr)
logger.F("Error occured at Authenticate")
os.Exit(11)
return
}
hostId, hosterr := zabbix.GetHostId(cfg.Url, token, cfg.Hostname)
if hosterr != nil {
logger.F(hosterr)
logger.F("Error occured at GetHostId. Hostname is wrong ?")
os.Exit(12)
return
}
logger.D("Hostname is OK. ID=" + hostId)
item, itemerr := zabbix.GetItem(cfg.Url, token, hostId, cfg.Key)
if itemerr != nil {
logger.F(itemerr)
logger.F("Error occured at GetItemId")
os.Exit(13)
return
}
logger.D("Itemname is OK. ID=" + item.Itemid)
latestValue, latestClock := item.Lastvalue, item.Lastclock
if latestClock == "0" {
// Overwrite item.lastvalue because zabbix sometime return lastValue = ""
logger.D("Lastclock on item is 0.(maybe last data is little old) Try getting history.")
val, clk, histerr := zabbix.GetLatestHistoryValue(cfg.Url, token, item.Itemid)
if histerr != nil {
logger.F(histerr)
logger.F("Error occured at GetHistory")
os.Exit(14)
return
}
logger.D("Getting history success.")
latestValue = val
latestClock = clk
}
item.Lastvalue = latestValue
item.Lastclock = latestClock
// TODO result check
zabbix.Logout(cfg.Url, token)
// 出力
if strings.ToUpper(cfg.Output) == "VALUE" {
fmt.Println(string(item.Lastvalue))
} else {
unixtime, e := strconv.ParseInt(item.Lastclock, 0, 0)
timeStr := ""
if e == nil {
timeStr = fmt.Sprint(time.Unix(unixtime, 0))
}
r := make(map[string]interface{})
mergo.Map(&r, item, mergo.WithOverride)
r["lastclockString"] = timeStr
json, err := json.Marshal(r)
if err != nil {
logger.F(err)
panic(err)
}
fmt.Println(string(json))
}
}