-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystemd_resolved_exporter.go
264 lines (225 loc) · 6.55 KB
/
systemd_resolved_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
package main
import (
"bufio"
"fmt"
"net/http"
"os/exec"
"regexp"
"strconv"
"strings"
"github.com/godbus/dbus/v5"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"gopkg.in/alecthomas/kingpin.v2"
)
var log *zap.SugaredLogger
const (
namespace = "systemd_resolved"
resolvedCommand = "systemd-resolve"
resolvedArgs = "--statistics"
)
type Collector struct {
namespace string
metrics map[string]prometheus.Collector
collectMode string
gatherDNSSec bool
}
func (c Collector) Describe(ch chan<- *prometheus.Desc) {
for _, metric := range c.metrics {
metric.Describe(ch)
}
}
func (c Collector) Collect(ch chan<- prometheus.Metric) {
var stats map[string]float64
switch c.collectMode {
case "cli":
stats = gatherStats()
case "dbus":
stats = gatherStatsDbus(c.gatherDNSSec)
default:
log.Fatal("invalid collect mode:" + c.collectMode)
}
log.Debug(stats)
for k, v := range stats {
if metric, exist := c.metrics[k]; exist {
switch m := metric.(type) {
case prometheus.Gauge:
ch <- prometheus.MustNewConstMetric(
m.Desc(),
prometheus.GaugeValue,
v)
case prometheus.Counter:
ch <- prometheus.MustNewConstMetric(
m.Desc(),
prometheus.CounterValue,
v)
default:
log.Fatal("invalid metric type")
}
}
}
}
func NewCollector(namespace string, gatherDNSSec bool, collectMode string) *Collector {
metrics := make(map[string]prometheus.Collector)
metrics["Current Transactions"] = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "current_transactions",
Help: "Current Transactions",
})
metrics["Total Transactions"] = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "transactions_total",
Help: "Total Transactions",
})
metrics["Current Cache Size"] = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "current_cache_size",
Help: "Current Cache Size",
})
metrics["Cache Hits"] = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "cache_hits_total",
Help: "Total Cache Hits",
})
metrics["Cache Misses"] = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "cache_misses_total",
Help: "Total Cache Misses",
})
if gatherDNSSec {
metrics["Secure"] = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "dnssec_secure_total",
Help: "Total number of DNSSEC Verdicts Secure",
})
metrics["Insecure"] = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "dnssec_insecure_total",
Help: "Total number of DNSSEC Verdicts Insecure",
})
metrics["Bogus"] = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "dnssec_bogus_total",
Help: "Total number of DNSSEC Verdicts Bogus",
})
metrics["Indeterminate"] = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "dnssec_indeterminate_total",
Help: "Total number of DNSSEC Verdicts Indeterminate",
})
}
return &Collector{
namespace: namespace,
metrics: metrics,
collectMode: collectMode,
gatherDNSSec: gatherDNSSec,
}
}
func gatherStats() map[string]float64 {
stats := make(map[string]float64)
statusLineRegex := regexp.MustCompile(`[a-zA-Z ]+: ?[0-9]+`)
cmd := exec.Command(resolvedCommand, resolvedArgs)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
l := scanner.Text()
if statusLineRegex.Match([]byte(l)) {
f := strings.Split(l, ":")
k := strings.TrimSpace(f[0])
v, _ := strconv.ParseFloat(strings.TrimSpace(f[1]), 64)
stats[k] = v
}
}
err = cmd.Wait()
if err != nil {
log.Fatal(err)
}
return stats
}
func gatherStatsDbus(gatherDNSSec bool) map[string]float64 {
stats := make(map[string]float64)
conn, err := dbus.ConnectSystemBus()
if err != nil {
log.Fatal(err)
}
defer conn.Close()
obj := conn.Object("org.freedesktop.resolve1", "/org/freedesktop/resolve1")
cacheStats, err := parseProperty(obj, "org.freedesktop.resolve1.Manager.CacheStatistics")
if err != nil {
log.Fatal(err)
}
stats["Current Cache Size"] = cacheStats[0]
stats["Cache Hits"] = cacheStats[1]
stats["Cache Misses"] = cacheStats[2]
transactionStats, err := parseProperty(obj, "org.freedesktop.resolve1.Manager.TransactionStatistics")
if err != nil {
log.Fatal(err)
}
stats["Current Transactions"] = transactionStats[0]
stats["Total Transactions"] = transactionStats[1]
if gatherDNSSec {
dnssecStats, err := parseProperty(obj, "org.freedesktop.resolve1.Manager.DNSSECStatistics")
if err != nil {
log.Fatal(err)
}
stats["Secure"] = dnssecStats[0]
stats["Insecure"] = dnssecStats[1]
stats["Bogus"] = dnssecStats[2]
stats["Indeterminate"] = dnssecStats[3]
}
return stats
}
func parseProperty(object dbus.BusObject, path string) (ret []float64, err error) {
variant, err := object.GetProperty(path)
if err != nil {
return nil, err
}
for _, v := range variant.Value().([]interface{}) {
i := v.(uint64)
ret = append(ret, float64(i))
}
return ret, err
}
func main() {
var (
listenAddress = kingpin.Flag("listen-address", "The address to listen on for HTTP requests.").Default(":9924").String()
debug = kingpin.Flag("debug", "Debug mode.").Bool()
gatherDNSSec = kingpin.Flag("gather-dnssec", "Collect DNSSEC statistics.").Bool()
collectMode = kingpin.Flag("collect-mode", "Define how to collect stats. (dbus/cli)").Default("dbus").String()
)
kingpin.HelpFlag.Short('h')
kingpin.Parse()
// set up logger
logger, _ := zap.NewProduction()
if *debug {
logger, _ = zap.NewDevelopment()
}
defer func() { err := logger.Sync(); fmt.Printf("Error: %v\n", err) }()
log = logger.Sugar()
collector := NewCollector(namespace, *gatherDNSSec, *collectMode)
prometheus.MustRegister(collector)
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(`<html>
<head><title>Systemd Resolved Exporter</title></head>
<body>
<h1>Systemd Resolved Exporter</h1>
<p><a href=/metrics'>Metrics</a></p>
</body>
</html>`))
if err != nil {
return
}
})
log.Info("collect:mode " + *collectMode)
log.Info("start http handler on " + *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}