-
Notifications
You must be signed in to change notification settings - Fork 26
/
influxdb-zabbix.go
446 lines (368 loc) · 8.89 KB
/
influxdb-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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package main
import (
"flag"
"fmt"
"math"
"os"
"os/signal"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
cfg "github.com/zensqlmonitor/influxdb-zabbix/config"
helpers "github.com/zensqlmonitor/influxdb-zabbix/helpers"
input "github.com/zensqlmonitor/influxdb-zabbix/input"
log "github.com/zensqlmonitor/influxdb-zabbix/log"
influx "github.com/zensqlmonitor/influxdb-zabbix/output/influxdb"
registry "github.com/zensqlmonitor/influxdb-zabbix/reg"
)
var m runtime.MemStats
var exitChan = make(chan int)
var wg sync.WaitGroup
type TOMLConfig cfg.TOMLConfig
var config cfg.TOMLConfig
type DynMap map[string]interface{}
type Param struct {
input Input
output Output
}
type Input struct {
provider string
address string
tablename string
interval int
hoursperbatch int
}
type Output struct {
address string
database string
username string
password string
precision string
outputrowsperbatch int
}
type InfluxDB struct {
output Output
}
var mapTables = make(registry.MapTable)
//
// Gather data
//
func (p *Param) gatherData() error {
var infoLogs []string
var currTable string = p.input.tablename
var currTableForLog string = helpers.RightPad(currTable, " ", 12-len(currTable))
// read registry
if err := registry.Read(&config, &mapTables); err != nil {
fmt.Println(err)
return err
}
// set times
starttimereg := registry.GetValueFromKey(mapTables, currTable)
startimerfc, err := time.Parse("2006-01-02T15:04:05", starttimereg)
if err != nil {
startimerfc, err = time.Parse(time.RFC3339, starttimereg)
if err != nil {
return err
}
}
var starttimestr string = strconv.FormatInt(startimerfc.Unix(), 10)
var endtimetmp time.Time = startimerfc.Add(time.Hour * time.Duration(p.input.hoursperbatch))
var endtimestr string = strconv.FormatInt(endtimetmp.Unix(), 10)
//
// <-- Extract
//
var tlen int = len(currTable)
infoLogs = append(infoLogs,
fmt.Sprintf(
"----------- | %s | [%v --> %v[",
currTableForLog,
startimerfc.Format("2006-01-02 15:04:00"),
endtimetmp.Format("2006-01-02 15:04:00")))
//start watcher
startwatch := time.Now()
ext := input.NewExtracter(
p.input.provider,
p.input.address,
currTable,
starttimestr,
endtimestr)
if err := ext.Extract(); err != nil {
log.Error(1, "Error while executing script: %s", err)
return err
}
// count rows
var rowcount int = len(ext.Result)
infoLogs = append(infoLogs,
fmt.Sprintf(
"<-- Extract | %s | %v rows in %s",
currTableForLog,
rowcount,
time.Since(startwatch)))
// set max clock time
var maxclock time.Time = startimerfc
if ext.Maxclock.IsZero() == false {
maxclock = ext.Maxclock
}
// no row
if rowcount == 0 {
infoLogs = append(infoLogs,
fmt.Sprintf(
"--> Load | %s | No data",
currTableForLog))
} else {
//
// --> Load
//
startwatch = time.Now()
inlineData := ""
if rowcount <= p.output.outputrowsperbatch {
inlineData = strings.Join(ext.Result[:], "\n")
loa := influx.NewLoader(
fmt.Sprintf(
"%s/write?db=%s&precision=%s",
p.output.address,
p.output.database,
p.output.precision),
p.output.username,
p.output.password,
inlineData)
if err := loa.Load(); err != nil {
log.Error(1, "Error while loading data for %s. %s", currTable, err)
return err
}
infoLogs = append(infoLogs,
fmt.Sprintf(
"--> Load | %s | %v rows in %s",
currTableForLog,
rowcount,
time.Since(startwatch)))
} else { // else split result in multiple batches
var batches float64 = float64(rowcount) / float64(p.output.outputrowsperbatch)
var batchesCeiled float64 = math.Ceil(batches)
var batchLoops int = 1
var minRange int = 0
var maxRange int = 0
for batches > 0 { // while
if batchLoops == 1 {
minRange = 0
} else {
minRange = maxRange
}
maxRange = batchLoops * p.output.outputrowsperbatch
if maxRange >= rowcount {
maxRange = rowcount
}
// create slide
datapart := []string{}
for i := minRange; i < maxRange; i++ {
datapart = append(datapart, ext.Result[i])
}
inlineData = strings.Join(datapart[:], "\n")
startwatch = time.Now()
loa := influx.NewLoader(
fmt.Sprintf(
"%s/write?db=%s&precision=%s",
p.output.address,
p.output.database,
p.output.precision),
p.output.username,
p.output.password,
inlineData)
if err := loa.Load(); err != nil {
log.Error(1, "Error while loading data for %s. %s", currTable, err)
return err
}
// log
tableBatchName := fmt.Sprintf("%s (%v/%v)",
currTable,
batchLoops,
batchesCeiled)
tlen = len(tableBatchName)
infoLogs = append(infoLogs,
fmt.Sprintf("--> Load | %s | %v rows in %s",
helpers.RightPad(tableBatchName, " ", 13-tlen),
len(datapart),
time.Since(startwatch)))
batchLoops += 1
batches -= 1
} // end while
}
}
// Save in registry
saveMaxTime(currTable, startimerfc, maxclock, p.input.hoursperbatch)
tlen = len(currTable)
infoLogs = append(infoLogs,
fmt.Sprintf("--- Waiting | %s | %v sec ",
currTableForLog,
p.input.interval))
if config.Logging.LevelFile == "Trace" || config.Logging.LevelConsole == "Trace" {
runtime.ReadMemStats(&m)
log.Trace(fmt.Sprintf("--- Memory usage: Alloc = %s | TotalAlloc = %s | Sys = %s | NumGC = %v",
helpers.IBytes(m.Alloc / 1024),
helpers.IBytes(m.TotalAlloc / 1024),
helpers.IBytes(m.Sys / 1024),
m.NumGC))
}
// print all log messages
print(infoLogs)
return nil
}
//
// Print all messages
//
func print(infoLogs []string) {
for i := 0; i < len(infoLogs); i++ {
log.Info(infoLogs[i])
}
}
//
// Save max time
//
func saveMaxTime(tablename string, starttime time.Time, maxtime time.Time, duration int) {
var timetosave time.Time
// if maxtime is greater than now, keep the maxclock returned
if (starttime.Add(time.Hour * time.Duration(duration))).After(time.Now()) {
timetosave = maxtime
} else {
timetosave = starttime.Add(time.Hour * time.Duration(duration))
}
registry.Save(config,
tablename,
timetosave.Format(time.RFC3339))
}
//
// Gather data loop
//
func (p *Param) gather() error {
for {
err := p.gatherData()
if err != nil {
return err
}
time.Sleep(time.Duration(p.input.interval) * time.Second)
}
return nil
}
//
// Init
//
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
//
// Read TOML configuration
//
func readConfig() {
// command-line flag parsing
flag.Parse()
// read configuration file
if err := cfg.Parse(&config); err != nil {
fmt.Println(err)
return
}
// validate configuration file
if err := cfg.Validate(&config); err != nil {
fmt.Println(err)
return
}
}
//
// Read registry file
//
func readRegistry() {
if err := registry.Read(&config, &mapTables); err != nil {
log.Error(0, err.Error())
return
}
}
//
// Init global logging
//
func initLog() {
log.Init(config)
}
//
// Listen to System Signals
//
func listenToSystemSignals() {
signalChan := make(chan os.Signal, 1)
code := 0
signal.Notify(signalChan, os.Interrupt)
signal.Notify(signalChan, os.Kill)
signal.Notify(signalChan, syscall.SIGTERM)
select {
case sig := <-signalChan:
log.Info("Received signal %s. shutting down", sig)
case code = <-exitChan:
switch code {
case 0:
log.Info("Shutting down")
default:
log.Warn("Shutting down")
}
}
log.Close()
os.Exit(code)
}
//
// Main
//
func main() {
log.Info("***** Starting influxdb-zabbix *****")
// listen to System Signals
go listenToSystemSignals()
readConfig()
readRegistry()
initLog()
// set of active tables
log.Trace("--- Active tables:")
var tables = []*cfg.Table{}
for _, table := range config.Tables {
if table.Active {
var tlen int = len(table.Name)
var durationh string
var duration time.Duration = time.Duration(table.Hoursperbatch) * time.Hour
if (duration.Hours() >= 24) {
durationh = fmt.Sprintf("%v days per batch", duration.Hours()/24)
} else {
durationh = fmt.Sprintf("%v hours per batch", duration.Hours())
}
log.Trace(
fmt.Sprintf(
"----------- | %s | Each %v sec | %s | Output by %v",
helpers.RightPad(table.Name, " ", 12-tlen),
table.Interval,
durationh,
table.Outputrowsperbatch))
tables = append(tables, table)
}
}
log.Info("--- Start polling")
var provider string = (reflect.ValueOf(config.Zabbix).MapKeys())[0].String()
var address string = config.Zabbix[provider].Address
log.Trace(fmt.Sprintf("--- Provider: %s", provider))
influxdb := config.InfluxDB
for _, table := range tables {
input := Input{
provider,
address,
table.Name,
table.Interval,
table.Hoursperbatch}
output := Output{
influxdb.Url,
influxdb.Database,
influxdb.Username,
influxdb.Password,
influxdb.Precision,
table.Outputrowsperbatch}
p := &Param{input, output}
wg.Add(1)
go p.gather()
}
wg.Wait()
}