forked from adubkov/go-zabbix
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzabbix.go
314 lines (268 loc) · 8.62 KB
/
zabbix.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// Package zabbix implements the sender protocol to send values to zabbix
// Taken from github.com/blacked/go-zabbix (discontinued)
package zabbix
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"strconv"
"strings"
"time"
)
const (
defaultConnectTimeout = 5 * time.Second
defaultWriteTimeout = 5 * time.Second
// A heavy loaded Zabbix server processing several metrics,
// containing LLDs, could take several seconds to respond
defaultReadTimeout = 15 * time.Second
)
// Metric struct.
type Metric struct {
Host string `json:"host"`
Key string `json:"key"`
Value string `json:"value"`
Clock int64 `json:"clock,omitempty"`
Active bool `json:"-"`
}
// NewMetric return a zabbix Metric with the values specified
// agentActive should be set to true if we are sending to a Zabbix Agent (active) item
func NewMetric(host, key, value string, agentActive bool, clock ...int64) *Metric {
m := &Metric{Host: host, Key: key, Value: value, Active: agentActive}
// do not send clock if not defined
if len(clock) > 0 {
m.Clock = int64(clock[0])
}
return m
}
// Packet struct.
type Packet struct {
Request string `json:"request"`
Data []*Metric `json:"data,omitempty"`
Clock int64 `json:"clock,omitempty"`
Host string `json:"host,omitempty"`
HostMetadata string `json:"host_metadata,omitempty"`
}
// Response is the data returned from zabbix-server
type Response struct {
Response string
Info string
}
type ResponseInfo struct {
Processed int
Failed int
Total int
Spent time.Duration
}
func (r *Response) GetInfo() (*ResponseInfo, error) {
ret := ResponseInfo{}
if r.Response != "success" {
return &ret, fmt.Errorf("Can not process info if response not Success (%s)", r.Response)
}
sp := strings.Split(r.Info, ";")
if len(sp) != 4 {
return &ret, fmt.Errorf("Error in split data, expected 4 got %d for data (%s)", len(sp), r.Info)
}
for _, s := range sp {
sp2 := strings.Split(s, ":")
if len(sp2) != 2 {
return &ret, fmt.Errorf("Error in split data, expected 2 got %d for data (%s)", len(sp2), s)
}
key := strings.TrimSpace(sp2[0])
value := strings.TrimSpace(sp2[1])
var err error
switch key {
case "processed":
ret.Processed, err = strconv.Atoi(value)
case "failed":
ret.Failed, err = strconv.Atoi(value)
case "total":
ret.Total, err = strconv.Atoi(value)
case "seconds spent":
var f float64
if f, err = strconv.ParseFloat(value, 64); err != nil {
return &ret, fmt.Errorf("Error in parsing seconds spent value [%s] error: %s", value, err)
}
ret.Spent = time.Duration(int64(f * 1000000000.0))
}
}
return &ret, nil
}
// NewPacket return a zabbix packet with a list of metrics
func NewPacket(data []*Metric, agentActive bool, clock ...int64) *Packet {
var request string
if agentActive {
request = "agent data"
} else {
request = "sender data"
}
p := &Packet{Request: request, Data: data}
// do not send clock if not defined
if len(clock) > 0 {
p.Clock = int64(clock[0])
}
return p
}
// DataLen Packet method, return 8 bytes with packet length in little endian order.
func (p *Packet) DataLen() []byte {
dataLen := make([]byte, 8)
JSONData, _ := json.Marshal(p)
binary.LittleEndian.PutUint32(dataLen, uint32(len(JSONData)))
return dataLen
}
// Sender struct.
type Sender struct {
ServerAddr string
ConnectTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
}
// NewSenderAddr return a sender object to send metrics using default values for timeouts using a server string.
// Server could be a hostname or ip address with, optional, port. Same format as https://pkg.go.dev/net#Dial
func NewSenderAddr(addr string) *Sender {
return &Sender{
ServerAddr: addr,
ConnectTimeout: defaultConnectTimeout,
ReadTimeout: defaultReadTimeout,
WriteTimeout: defaultWriteTimeout,
}
}
// NewSender return a sender object to send metrics using default values for timeouts
func NewSender(host string, port int) *Sender {
return &Sender{
ServerAddr: host + ":" + strconv.Itoa(port),
ConnectTimeout: defaultConnectTimeout,
ReadTimeout: defaultReadTimeout,
WriteTimeout: defaultWriteTimeout,
}
}
// NewSenderAddrTimeout return a sender object to send metrics defining values for timeouts using a server string
// Server could be a hostname or ip address with, optional, port. Same format as https://pkg.go.dev/net#Dial
func NewSenderAddrTimeout(
server string,
connectTimeout time.Duration,
readTimeout time.Duration,
writeTimeout time.Duration,
) *Sender {
return &Sender{
ServerAddr: server,
ConnectTimeout: connectTimeout,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
}
}
// NewSenderTimeout return a sender object to send metrics defining values for timeouts
func NewSenderTimeout(
host string,
port int,
connectTimeout time.Duration,
readTimeout time.Duration,
writeTimeout time.Duration,
) *Sender {
return &Sender{
ServerAddr: host + ":" + strconv.Itoa(port),
ConnectTimeout: connectTimeout,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
}
}
// getHeader return zabbix header.
// https://www.zabbix.com/documentation/4.0/manual/appendix/protocols/header_datalen
func (s *Sender) getHeader() []byte {
return []byte("ZBXD\x01")
}
// read data from connection.
func (s *Sender) read(conn net.Conn) ([]byte, error) {
res, err := ioutil.ReadAll(conn)
if err != nil {
return res, fmt.Errorf("receiving data: %s", err.Error())
}
return res, nil
}
// SendMetrics send an array of metrics, making different packets for
// trapper and active items.
// The response for trapper metrics is in the first element of the res array and err array
// Response for active metrics is in the second element of the res array and error array
func (s *Sender) SendMetrics(metrics []*Metric) (resActive Response, errActive error, resTrapper Response, errTrapper error) {
var trapperMetrics []*Metric
var activeMetrics []*Metric
for i := 0; i < len(metrics); i++ {
if metrics[i].Active {
activeMetrics = append(activeMetrics, metrics[i])
} else {
trapperMetrics = append(trapperMetrics, metrics[i])
}
}
if len(trapperMetrics) > 0 {
packetTrapper := NewPacket(trapperMetrics, false)
resTrapper, errTrapper = s.Send(packetTrapper)
}
if len(activeMetrics) > 0 {
packetActive := NewPacket(activeMetrics, true)
resActive, errActive = s.Send(packetActive)
}
return resActive, errActive, resTrapper, errTrapper
}
// Send connects to Zabbix, send the data, return the response and close the connection
func (s *Sender) Send(packet *Packet) (res Response, err error) {
// Timeout to resolve and connect to the server
conn, err := net.DialTimeout("tcp", s.ServerAddr, s.ConnectTimeout)
if err != nil {
return res, fmt.Errorf("connecting to server (timeout=%v): %v", s.ConnectTimeout, err)
}
defer conn.Close()
dataPacket, _ := json.Marshal(packet)
// Fill buffer
buffer := append(s.getHeader(), packet.DataLen()...)
buffer = append(buffer, dataPacket...)
// Write timeout
conn.SetWriteDeadline(time.Now().Add(s.WriteTimeout))
// Send packet to zabbix
_, err = conn.Write(buffer)
if err != nil {
return res, fmt.Errorf("sending the data (timeout=%v): %s", s.WriteTimeout, err.Error())
}
// Read timeout
conn.SetReadDeadline(time.Now().Add(s.ReadTimeout))
// Read response from server
response, err := s.read(conn)
if err != nil {
return res, fmt.Errorf("reading the response (timeout=%v): %s", s.ReadTimeout, err)
}
if len(response) < 14 {
return res, fmt.Errorf("invalid response length: %s", response)
}
header := response[:5]
data := response[13:]
if !bytes.Equal(header, s.getHeader()) {
return res, fmt.Errorf("got no valid header [%+v] , expected [%+v]", header, s.getHeader())
}
if err := json.Unmarshal(data, &res); err != nil {
return res, fmt.Errorf("zabbix response is not valid: %v", err)
}
return res, nil
}
// RegisterHost provides a register a Zabbix's host with Autoregister method.
func (s *Sender) RegisterHost(host, hostmetadata string) error {
p := &Packet{Request: "active checks", Host: host, HostMetadata: hostmetadata}
res, err := s.Send(p)
if err != nil {
return fmt.Errorf("sending packet: %v", err)
}
if res.Response == "success" {
return nil
}
// The autoregister process always return fail the first time
// We retry the process to get success response to verify the host registration properly
p = &Packet{Request: "active checks", Host: host, HostMetadata: hostmetadata}
res, err = s.Send(p)
if err != nil {
return fmt.Errorf("sending packet: %v", err)
}
if res.Response == "failed" {
return fmt.Errorf("autoregistration failed, verify hostmetadata")
}
return nil
}