-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnats_exporter.go
385 lines (350 loc) · 10.6 KB
/
nats_exporter.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
// Copyright 2016 Markus Lindenberg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
)
const (
namespace = "nats"
)
var (
upLabelNames = []string{"version"}
requestsLabelNames = []string{"path"}
)
// Exporter collects gnatsd stats from the given URI and exports them using
// the prometheus metrics package.
type Exporter struct {
VarzURI, SubszURI string
mutex sync.RWMutex
client *http.Client
totalScrapes, jsonParseFailures prometheus.Counter
up prometheus.Gauge
startTime, cpu, mem, connections, routes, remotes, slowConsumers prometheus.Gauge
totalConnections, inMsgs, outMsgs, inBytes, outBytes prometheus.Gauge
httpRequests *prometheus.GaugeVec
numSubscriptions, numCache, numInserts, numRemoves, numMatches prometheus.Gauge
cacheHitRate, maxFanout, avgFanout prometheus.Gauge
}
// NewExporter returns an initialized Exporter.
func NewExporter(baseURI string, timeout time.Duration) *Exporter {
return &Exporter{
VarzURI: strings.TrimRight(baseURI, "/") + "/varz",
SubszURI: strings.TrimRight(baseURI, "/") + "/subsz",
up: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "up",
Help: "Was the last scrape of Nats Server successful.",
}),
totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_total_scrapes",
Help: "Current total Nats Server scrapes.",
}),
jsonParseFailures: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_json_parse_failures",
Help: "Number of errors while parsing JSON.",
}),
startTime: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "server_start",
Help: "Timestamp of Nats Server startup.",
}),
mem: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "mem",
Help: "mem",
}),
cpu: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "cpu",
Help: "cpu",
}),
connections: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "connections",
Help: "connections",
}),
totalConnections: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "connections_total",
Help: "connections_total",
}),
routes: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "routes",
Help: "routes",
}),
remotes: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "remotes",
Help: "remotes",
}),
inMsgs: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "msgs_in",
Help: "msgs_in",
}),
outMsgs: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "msgs_out",
Help: "msgs_out",
}),
inBytes: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "bytes_in",
Help: "bytes_in",
}),
outBytes: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "bytes_out",
Help: "bytes_out",
}),
slowConsumers: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "slow_consumers",
Help: "slow_consumers",
}),
httpRequests: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "http_requests",
Help: "http_requests",
}, requestsLabelNames),
numSubscriptions: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "total",
Help: "subscriptions_total",
}),
numCache: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "cache",
Help: "subscriptions_cache",
}),
numInserts: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "inserts",
Help: "subscription_inserts",
}),
numRemoves: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "removes",
Help: "subscription_removes",
}),
numMatches: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "matches",
Help: "subscription_matches",
}),
cacheHitRate: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "cache_hit_rate",
Help: "subscription_cache_hit_rate",
}),
maxFanout: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "fanout_max",
Help: "subscription_fanout_max",
}),
avgFanout: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "subscriptions",
Name: "fanout_avg",
Help: "subscription_fanout_avg",
}),
client: &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, timeout)
if err != nil {
return nil, err
}
if err := c.SetDeadline(time.Now().Add(timeout)); err != nil {
return nil, err
}
return c, nil
},
},
},
}
}
// Describe describes all the metrics ever exported by the NATS exporter.
// It implements prometheus.Collector.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
ch <- e.up.Desc()
ch <- e.totalScrapes.Desc()
ch <- e.jsonParseFailures.Desc()
ch <- e.startTime.Desc()
ch <- e.mem.Desc()
ch <- e.cpu.Desc()
ch <- e.connections.Desc()
ch <- e.totalConnections.Desc()
ch <- e.routes.Desc()
ch <- e.remotes.Desc()
ch <- e.inMsgs.Desc()
ch <- e.outMsgs.Desc()
ch <- e.inBytes.Desc()
ch <- e.outBytes.Desc()
ch <- e.slowConsumers.Desc()
e.httpRequests.Describe(ch)
ch <- e.numSubscriptions.Desc()
ch <- e.numCache.Desc()
ch <- e.numInserts.Desc()
ch <- e.numRemoves.Desc()
ch <- e.numMatches.Desc()
ch <- e.cacheHitRate.Desc()
ch <- e.maxFanout.Desc()
ch <- e.avgFanout.Desc()
}
// Collect fetches the stats from gnatsd and delivers them
// as Prometheus metrics. It implements prometheus.Collector.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
e.mutex.Lock() // To protect metrics from concurrent collects.
defer e.mutex.Unlock()
e.httpRequests.Reset()
e.scrape()
ch <- e.up
ch <- e.totalScrapes
ch <- e.jsonParseFailures
ch <- e.startTime
ch <- e.mem
ch <- e.cpu
ch <- e.connections
ch <- e.totalConnections
ch <- e.routes
ch <- e.remotes
ch <- e.inMsgs
ch <- e.outMsgs
ch <- e.inBytes
ch <- e.outBytes
ch <- e.slowConsumers
e.httpRequests.Collect(ch)
ch <- e.numSubscriptions
ch <- e.numCache
ch <- e.numInserts
ch <- e.numRemoves
ch <- e.numMatches
ch <- e.cacheHitRate
ch <- e.maxFanout
ch <- e.avgFanout
}
func (e *Exporter) scrape() {
e.totalScrapes.Inc()
var err error
var varz Varz
err = e.fetch(e.VarzURI, &varz)
if err != nil {
e.up.Set(0)
log.Errorf("Can't scrape varz: %s", err)
return
}
var subsz Subsz
err = e.fetch(e.SubszURI, &subsz)
if err != nil {
e.up.Set(0)
log.Errorf("Can't scrape subsz: %s", err)
return
}
e.up.Set(1)
e.startTime.Set(float64(varz.Start.Unix()))
e.mem.Set(float64(varz.Mem))
e.cpu.Set(varz.CPU)
e.connections.Set(float64(varz.Connections))
e.totalConnections.Set(float64(varz.TotalConnections))
e.routes.Set(float64(varz.Routes))
e.remotes.Set(float64(varz.Remotes))
e.inMsgs.Set(float64(varz.InMsgs))
e.outMsgs.Set(float64(varz.OutMsgs))
e.inBytes.Set(float64(varz.InBytes))
e.outBytes.Set(float64(varz.OutBytes))
e.slowConsumers.Set(float64(varz.SlowConsumers))
for path, requests := range varz.HTTPReqStats {
e.httpRequests.WithLabelValues(path).Set(float64(requests))
}
e.numSubscriptions.Set(float64(subsz.NumSubs))
e.numCache.Set(float64(subsz.NumCache))
e.numInserts.Set(float64(subsz.NumInserts))
e.numRemoves.Set(float64(subsz.NumRemoves))
e.numMatches.Set(float64(subsz.NumMatches))
e.cacheHitRate.Set(subsz.CacheHitRate)
e.maxFanout.Set(float64(subsz.MaxFanout))
e.avgFanout.Set(subsz.AvgFanout)
}
func (e *Exporter) fetch(uri string, v interface{}) error {
resp, err := e.client.Get(uri)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("status %d", resp.StatusCode)
}
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
e.jsonParseFailures.Inc()
return fmt.Errorf("Can't read JSON: %v", err)
}
return nil
}
func main() {
var (
listenAddress = flag.String("web.listen-address", ":9148", "Address to listen on for web interface and telemetry.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
natsScrapeURI = flag.String("nats.scrape-uri", "http://localhost:8222/", "Base URI on which to scrape nats server.")
natsTimeout = flag.Duration("nats.timeout", 5*time.Second, "Timeout for trying to get stats from nats server.")
)
flag.Parse()
// Listen to signals
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGTERM, syscall.SIGINT)
exporter := NewExporter(*natsScrapeURI, *natsTimeout)
prometheus.MustRegister(exporter)
// Setup HTTP server
http.Handle(*metricsPath, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>NATS Exporter</title></head>
<body>
<h1>NATS Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
go func() {
log.Infof("Starting Server: %s", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}()
s := <-sigchan
log.Infof("Received %v, terminating", s)
os.Exit(0)
}