-
Notifications
You must be signed in to change notification settings - Fork 80
/
unbound_exporter.go
572 lines (538 loc) · 16.3 KB
/
unbound_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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Copyright 2017 Kumina, https://kumina.nl/
// 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 (
"bufio"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sort"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/promlog"
)
var (
log = promlog.New(&promlog.Config{})
unboundUpDesc = prometheus.NewDesc(
prometheus.BuildFQName("unbound", "", "up"),
"Whether scraping Unbound's metrics was successful.",
nil, nil)
unboundHistogram = prometheus.NewDesc(
prometheus.BuildFQName("unbound", "", "response_time_seconds"),
"Query response time in seconds.",
nil, nil)
unboundMetrics = []*unboundMetric{
newUnboundMetric(
"answer_rcodes_total",
"Total number of answers to queries, from cache or from recursion, by response code.",
prometheus.CounterValue,
[]string{"rcode"},
"^num\\.answer\\.rcode\\.(\\w+)$"),
newUnboundMetric(
"answers_bogus",
"Total number of answers that were bogus.",
prometheus.CounterValue,
nil,
"^num\\.answer\\.bogus$"),
newUnboundMetric(
"answers_secure_total",
"Total number of answers that were secure.",
prometheus.CounterValue,
nil,
"^num\\.answer\\.secure$"),
newUnboundMetric(
"cache_hits_total",
"Total number of queries that were successfully answered using a cache lookup.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.cachehits$"),
newUnboundMetric(
"cache_misses_total",
"Total number of cache queries that needed recursive processing.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.cachemiss$"),
newUnboundMetric(
"queries_cookie_client_total",
"Total number of queries with a client cookie.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.queries_cookie_client$"),
newUnboundMetric(
"queries_cookie_invalid_total",
"Total number of queries with a invalid cookie.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.queries_invalid_client$"),
newUnboundMetric(
"queries_cookie_valid_total",
"Total number of queries with a valid cookie.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.queries_cookie_valid$"),
newUnboundMetric(
"memory_caches_bytes",
"Memory in bytes in use by caches.",
prometheus.GaugeValue,
[]string{"cache"},
"^mem\\.cache\\.(\\w+)$"),
newUnboundMetric(
"memory_modules_bytes",
"Memory in bytes in use by modules.",
prometheus.GaugeValue,
[]string{"module"},
"^mem\\.mod\\.(\\w+)$"),
newUnboundMetric(
"memory_sbrk_bytes",
"Memory in bytes allocated through sbrk.",
prometheus.GaugeValue,
nil,
"^mem\\.total\\.sbrk$"),
newUnboundMetric(
"prefetches_total",
"Total number of cache prefetches performed.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.prefetch$"),
newUnboundMetric(
"queries_total",
"Total number of queries received.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.queries$"),
newUnboundMetric(
"expired_total",
"Total number of expired entries served.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.expired$"),
newUnboundMetric(
"query_classes_total",
"Total number of queries with a given query class.",
prometheus.CounterValue,
[]string{"class"},
"^num\\.query\\.class\\.([\\w]+)$"),
newUnboundMetric(
"query_flags_total",
"Total number of queries that had a given flag set in the header.",
prometheus.CounterValue,
[]string{"flag"},
"^num\\.query\\.flags\\.([\\w]+)$"),
newUnboundMetric(
"query_ipv6_total",
"Total number of queries that were made using IPv6 towards the Unbound server.",
prometheus.CounterValue,
nil,
"^num\\.query\\.ipv6$"),
newUnboundMetric(
"query_opcodes_total",
"Total number of queries with a given query opcode.",
prometheus.CounterValue,
[]string{"opcode"},
"^num\\.query\\.opcode\\.([\\w]+)$"),
newUnboundMetric(
"query_edns_DO_total",
"Total number of queries that had an EDNS OPT record with the DO (DNSSEC OK) bit set present.",
prometheus.CounterValue,
nil,
"^num\\.query\\.edns\\.DO$"),
newUnboundMetric(
"query_edns_present_total",
"Total number of queries that had an EDNS OPT record present.",
prometheus.CounterValue,
nil,
"^num\\.query\\.edns\\.present$"),
newUnboundMetric(
"query_tcp_total",
"Total number of queries that were made using TCP towards the Unbound server, including DoT and DoH queries.",
prometheus.CounterValue,
nil,
"^num\\.query\\.tcp$"),
newUnboundMetric(
"query_tcpout_total",
"Total number of queries that the Unbound server made using TCP outgoing towards other servers.",
prometheus.CounterValue,
nil,
"^num\\.query\\.tcpout$"),
newUnboundMetric(
"query_tls_total",
"Total number of queries that were made using TCP TLS towards the Unbound server, including DoT and DoH queries.",
prometheus.CounterValue,
nil,
"^num\\.query\\.tls$"),
newUnboundMetric(
"query_tls_resume_total",
"Total number of queries that were made using TCP TLS Resume towards the Unbound server.",
prometheus.CounterValue,
nil,
"^num\\.query\\.tls\\.resume$"),
newUnboundMetric(
"query_https_total",
"Total number of DoH queries that were made towards the Unbound server.",
prometheus.CounterValue,
nil,
"^num\\.query\\.https$"),
newUnboundMetric(
"query_types_total",
"Total number of queries with a given query type.",
prometheus.CounterValue,
[]string{"type"},
"^num\\.query\\.type\\.([\\w]+)$"),
newUnboundMetric(
"query_udpout_total",
"Total number of queries that the Unbound server made using UDP outgoing towardsother servers.",
prometheus.CounterValue,
nil,
"^num\\.query\\.udpout$"),
newUnboundMetric(
"query_aggressive_nsec",
"Total number of queries that the Unbound server generated response using Aggressive NSEC.",
prometheus.CounterValue,
[]string{"rcode"},
"^num\\.query\\.aggressive\\.(\\w+)$"),
newUnboundMetric(
"request_list_current_all",
"Current size of the request list, including internally generated queries.",
prometheus.GaugeValue,
[]string{"thread"},
"^thread([0-9]+)\\.requestlist\\.current\\.all$"),
newUnboundMetric(
"request_list_current_user",
"Current size of the request list, only counting the requests from client queries.",
prometheus.GaugeValue,
[]string{"thread"},
"^thread([0-9]+)\\.requestlist\\.current\\.user$"),
newUnboundMetric(
"request_list_exceeded_total",
"Number of queries that were dropped because the request list was full.",
prometheus.CounterValue,
[]string{"thread"},
"^thread([0-9]+)\\.requestlist\\.exceeded$"),
newUnboundMetric(
"request_list_overwritten_total",
"Total number of requests in the request list that were overwritten by newer entries.",
prometheus.CounterValue,
[]string{"thread"},
"^thread([0-9]+)\\.requestlist\\.overwritten$"),
newUnboundMetric(
"recursive_replies_total",
"Total number of replies sent to queries that needed recursive processing.",
prometheus.CounterValue,
[]string{"thread"},
"^thread(\\d+)\\.num\\.recursivereplies$"),
newUnboundMetric(
"rrset_bogus_total",
"Total number of rrsets marked bogus by the validator.",
prometheus.CounterValue,
nil,
"^num\\.rrset\\.bogus$"),
newUnboundMetric(
"rrset_cache_max_collisions_total",
"Total number of rrset cache hashtable collisions.",
prometheus.CounterValue,
nil,
"^rrset\\.cache\\.max_collisions$"),
newUnboundMetric(
"time_elapsed_seconds",
"Time since last statistics printout in seconds.",
prometheus.CounterValue,
nil,
"^time\\.elapsed$"),
newUnboundMetric(
"time_now_seconds",
"Current time in seconds since 1970.",
prometheus.GaugeValue,
nil,
"^time\\.now$"),
newUnboundMetric(
"time_up_seconds_total",
"Uptime since server boot in seconds.",
prometheus.CounterValue,
nil,
"^time\\.up$"),
newUnboundMetric(
"unwanted_queries_total",
"Total number of queries that were refused or dropped because they failed the access control settings.",
prometheus.CounterValue,
nil,
"^unwanted\\.queries$"),
newUnboundMetric(
"unwanted_replies_total",
"Total number of replies that were unwanted or unsolicited.",
prometheus.CounterValue,
nil,
"^unwanted\\.replies$"),
newUnboundMetric(
"recursion_time_seconds_avg",
"Average time it took to answer queries that needed recursive processing (does not include in-cache requests).",
prometheus.GaugeValue,
nil,
"^total\\.recursion\\.time\\.avg$"),
newUnboundMetric(
"recursion_time_seconds_median",
"The median of the time it took to answer queries that needed recursive processing.",
prometheus.GaugeValue,
nil,
"^total\\.recursion\\.time\\.median$"),
newUnboundMetric(
"msg_cache_count",
"The Number of Messages cached",
prometheus.GaugeValue,
nil,
"^msg\\.cache\\.count$"),
newUnboundMetric(
"msg_cache_max_collisions_total",
"Total number of msg cache hashtable collisions.",
prometheus.CounterValue,
nil,
"^msg\\.cache\\.max_collisions$"),
newUnboundMetric(
"rrset_cache_count",
"The Number of rrset cached",
prometheus.GaugeValue,
nil,
"^rrset\\.cache\\.count$"),
newUnboundMetric(
"rpz_action_count",
"Total number of triggered Response Policy Zone actions, by type.",
prometheus.CounterValue,
[]string{"type"},
"^num\\.rpz\\.action\\.rpz-([\\w-]+)$"),
newUnboundMetric(
"memory_doh_bytes",
"Memory used by DoH buffers, in bytes.",
prometheus.GaugeValue,
[]string{"buffer"},
"^mem\\.http\\.(\\w+)$"),
}
)
type unboundMetric struct {
desc *prometheus.Desc
valueType prometheus.ValueType
pattern *regexp.Regexp
}
func newUnboundMetric(name string, description string, valueType prometheus.ValueType, labels []string, pattern string) *unboundMetric {
return &unboundMetric{
desc: prometheus.NewDesc(
prometheus.BuildFQName("unbound", "", name),
description,
labels,
nil),
valueType: valueType,
pattern: regexp.MustCompile(pattern),
}
}
func CollectFromReader(file io.Reader, ch chan<- prometheus.Metric) error {
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
histogramPattern := regexp.MustCompile(`^histogram\.\d+\.\d+\.to\.(\d+\.\d+)$`)
histogramCount := uint64(0)
histogramAvg := float64(0)
histogramBuckets := make(map[float64]uint64)
for scanner.Scan() {
fields := strings.Split(scanner.Text(), "=")
if len(fields) != 2 {
return fmt.Errorf(
"%q is not a valid key-value pair",
scanner.Text())
}
for _, metric := range unboundMetrics {
if matches := metric.pattern.FindStringSubmatch(fields[0]); matches != nil {
value, err := strconv.ParseFloat(fields[1], 64)
if err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(
metric.desc,
metric.valueType,
value,
matches[1:]...)
break
}
}
if matches := histogramPattern.FindStringSubmatch(fields[0]); matches != nil {
end, err := strconv.ParseFloat(matches[1], 64)
if err != nil {
return err
}
value, err := strconv.ParseUint(fields[1], 10, 64)
if err != nil {
return err
}
histogramBuckets[end] = value
histogramCount += value
} else if fields[0] == "total.recursion.time.avg" {
value, err := strconv.ParseFloat(fields[1], 64)
if err != nil {
return err
}
histogramAvg = value
}
}
// Convert the metrics to a cumulative Prometheus histogram.
// Reconstruct the sum of all samples from the average value
// provided by Unbound. Hopefully this does not break
// monotonicity.
keys := []float64{}
for k := range histogramBuckets {
keys = append(keys, k)
}
sort.Float64s(keys)
prev := uint64(0)
for _, i := range keys {
histogramBuckets[i] += prev
prev = histogramBuckets[i]
}
ch <- prometheus.MustNewConstHistogram(
unboundHistogram,
histogramCount,
histogramAvg*float64(histogramCount),
histogramBuckets)
return scanner.Err()
}
func CollectFromSocket(socketFamily string, host string, tlsConfig *tls.Config, ch chan<- prometheus.Metric) error {
var (
conn net.Conn
err error
)
if socketFamily == "unix" || tlsConfig == nil {
conn, err = net.Dial(socketFamily, host)
} else {
conn, err = tls.Dial(socketFamily, host, tlsConfig)
}
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Write([]byte("UBCT1 stats_noreset\n"))
if err != nil {
return err
}
return CollectFromReader(conn, ch)
}
type UnboundExporter struct {
socketFamily string
host string
tlsConfig *tls.Config
}
func NewUnboundExporter(host string, ca string, cert string, key string) (*UnboundExporter, error) {
u, err := url.Parse(host)
if err != nil {
return &UnboundExporter{}, err
}
if u.Scheme == "unix" {
return &UnboundExporter{
socketFamily: u.Scheme,
host: u.Path,
}, nil
}
if ca == "" && cert == "" {
return &UnboundExporter{
socketFamily: u.Scheme,
host: u.Host,
}, nil
}
/* Server authentication. */
caData, err := os.ReadFile(ca)
if err != nil {
return &UnboundExporter{}, err
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caData) {
return &UnboundExporter{}, fmt.Errorf("Failed to parse CA")
}
/* Client authentication. */
certData, err := os.ReadFile(cert)
if err != nil {
return &UnboundExporter{}, err
}
keyData, err := os.ReadFile(key)
if err != nil {
return &UnboundExporter{}, err
}
keyPair, err := tls.X509KeyPair(certData, keyData)
if err != nil {
return &UnboundExporter{}, err
}
return &UnboundExporter{
socketFamily: u.Scheme,
host: u.Host,
tlsConfig: &tls.Config{
Certificates: []tls.Certificate{keyPair},
RootCAs: roots,
ServerName: "unbound",
},
}, nil
}
func (e *UnboundExporter) Describe(ch chan<- *prometheus.Desc) {
ch <- unboundUpDesc
for _, metric := range unboundMetrics {
ch <- metric.desc
}
}
func (e *UnboundExporter) Collect(ch chan<- prometheus.Metric) {
err := CollectFromSocket(e.socketFamily, e.host, e.tlsConfig, ch)
if err == nil {
ch <- prometheus.MustNewConstMetric(
unboundUpDesc,
prometheus.GaugeValue,
1.0)
} else {
_ = level.Error(log).Log("Failed to scrape socket: ", err)
ch <- prometheus.MustNewConstMetric(
unboundUpDesc,
prometheus.GaugeValue,
0.0)
}
}
func main() {
var (
listenAddress = flag.String("web.listen-address", ":9167", "Address to listen on for web interface and telemetry.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
unboundHost = flag.String("unbound.host", "tcp://localhost:8953", "Unix or TCP address of Unbound control socket.")
unboundCa = flag.String("unbound.ca", "/etc/unbound/unbound_server.pem", "Unbound server certificate.")
unboundCert = flag.String("unbound.cert", "/etc/unbound/unbound_control.pem", "Unbound client certificate.")
unboundKey = flag.String("unbound.key", "/etc/unbound/unbound_control.key", "Unbound client key.")
)
flag.Parse()
_ = level.Info(log).Log("Starting unbound_exporter")
exporter, err := NewUnboundExporter(*unboundHost, *unboundCa, *unboundCert, *unboundKey)
if err != nil {
panic(err)
}
prometheus.MustRegister(exporter)
http.Handle(*metricsPath, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`
<html>
<head><title>Unbound Exporter</title></head>
<body>
<h1>Unbound Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
_ = level.Info(log).Log("Listening on address:port => ", *listenAddress)
_ = level.Error(log).Log(http.ListenAndServe(*listenAddress, nil))
os.Exit(1)
}