forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nats.go
112 lines (95 loc) · 2.33 KB
/
nats.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
// +build !freebsd freebsd,cgo
package nats
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"path"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
gnatsd "github.com/nats-io/gnatsd/server"
)
type Nats struct {
Server string
ResponseTimeout internal.Duration
client *http.Client
}
var sampleConfig = `
## The address of the monitoring endpoint of the NATS server
server = "http://localhost:8222"
## Maximum time to receive response
# response_timeout = "5s"
`
func (n *Nats) SampleConfig() string {
return sampleConfig
}
func (n *Nats) Description() string {
return "Provides metrics about the state of a NATS server"
}
func (n *Nats) Gather(acc telegraf.Accumulator) error {
url, err := url.Parse(n.Server)
if err != nil {
return err
}
url.Path = path.Join(url.Path, "varz")
if n.client == nil {
n.client = n.createHTTPClient()
}
resp, err := n.client.Get(url.String())
if err != nil {
return err
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
stats := new(gnatsd.Varz)
err = json.Unmarshal([]byte(bytes), &stats)
if err != nil {
return err
}
acc.AddFields("nats",
map[string]interface{}{
"in_msgs": stats.InMsgs,
"out_msgs": stats.OutMsgs,
"in_bytes": stats.InBytes,
"out_bytes": stats.OutBytes,
"uptime": stats.Now.Sub(stats.Start).Nanoseconds(),
"cores": stats.Cores,
"cpu": stats.CPU,
"mem": stats.Mem,
"connections": stats.Connections,
"total_connections": stats.TotalConnections,
"subscriptions": stats.Subscriptions,
"slow_consumers": stats.SlowConsumers,
"routes": stats.Routes,
"remotes": stats.Remotes,
},
map[string]string{"server": n.Server},
time.Now())
return nil
}
func (n *Nats) createHTTPClient() *http.Client {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
}
timeout := n.ResponseTimeout.Duration
if timeout == time.Duration(0) {
timeout = 5 * time.Second
}
return &http.Client{
Transport: transport,
Timeout: timeout,
}
}
func init() {
inputs.Add("nats", func() telegraf.Input {
return &Nats{
Server: "http://localhost:8222",
}
})
}