forked from itzg/mc-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegraf.go
96 lines (77 loc) · 2.17 KB
/
telegraf.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
package main
import (
"errors"
mcpinger "github.com/Raqbit/mc-pinger"
lpsender "github.com/itzg/line-protocol-sender"
"go.uber.org/zap"
"log"
"strconv"
"time"
)
const (
MetricName = "minecraft_status"
TagHost = "host"
TagPort = "port"
TagStatus = "status"
TagVersion = "version"
FieldError = "error"
FieldOnline = "online"
FieldMax = "max"
FieldResponseTime = "response_time"
StatusError = "error"
StatusSuccess = "success"
)
type TelegrafGatherer struct {
host string
port string
pinger mcpinger.Pinger
logger *zap.Logger
lpClient lpsender.Client
}
func NewTelegrafGatherer(host string, port uint16, lpClient lpsender.Client, logger *zap.Logger) *TelegrafGatherer {
return &TelegrafGatherer{
host: host,
port: strconv.FormatInt(int64(port), 10),
pinger: mcpinger.New(host, uint16(port)),
lpClient: lpClient,
logger: logger,
}
}
func (g *TelegrafGatherer) Gather() {
g.logger.Debug("gathering", zap.String("host", g.host), zap.String("port", g.port))
startTime := time.Now()
info, err := g.pinger.Ping()
elapsed := time.Now().Sub(startTime)
if err != nil {
g.sendFailedMetrics(err, elapsed)
} else if info.Players.Max == 0 {
g.sendFailedMetrics(errors.New("server not ready"), elapsed)
} else {
err := g.sendInfoMetrics(info, elapsed)
if err != nil {
log.Printf("failed to send metrics: %s", err)
}
}
}
func (g *TelegrafGatherer) sendInfoMetrics(info *mcpinger.ServerInfo, elapsed time.Duration) error {
m := lpsender.NewSimpleMetric(MetricName)
m.AddTag(TagHost, g.host)
m.AddTag(TagPort, g.port)
m.AddTag(TagStatus, StatusSuccess)
m.AddTag(TagVersion, info.Version.Name)
m.AddField(FieldResponseTime, elapsed.Seconds())
m.AddField(FieldOnline, uint64(info.Players.Online))
m.AddField(FieldMax, uint64(info.Players.Max))
g.lpClient.Send(m)
return nil
}
func (g *TelegrafGatherer) sendFailedMetrics(err error, elapsed time.Duration) {
m := lpsender.NewSimpleMetric(MetricName)
m.AddTag(TagHost, g.host)
m.AddTag(TagPort, g.port)
m.AddTag(TagStatus, StatusError)
m.AddField(FieldError, err.Error())
m.AddField(FieldResponseTime, elapsed.Seconds())
g.lpClient.Send(m)
return
}