forked from kumina/openvpn_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openvpn_exporter.go
371 lines (345 loc) · 12.3 KB
/
openvpn_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
// 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"
"bytes"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type OpenvpnServerHeader struct {
LabelColumns []string
Metrics []OpenvpnServerHeaderField
}
type OpenvpnServerHeaderField struct {
Column string
Desc *prometheus.Desc
ValueType prometheus.ValueType
}
var (
// Metrics exported both for client and server statistics.
openvpnUpDesc = prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "", "up"),
"Whether scraping OpenVPN's metrics was successful.",
[]string{"status_path"}, nil)
openvpnStatusUpdateTimeDesc = prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "", "status_update_time_seconds"),
"UNIX timestamp at which the OpenVPN statistics were updated.",
[]string{"status_path"}, nil)
// Metrics specific to OpenVPN servers.
openvpnConnectedClientsDesc = prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "", "openvpn_server_connected_clients"),
"Number Of Connected Clients", []string{"status_path"}, nil)
openvpnServerHeaders = map[string]OpenvpnServerHeader{
"CLIENT_LIST": {
LabelColumns: []string{
"Common Name",
"Connected Since (time_t)",
"Real Address",
"Virtual Address",
"Username",
},
Metrics: []OpenvpnServerHeaderField{
{
Column: "Bytes Received",
Desc: prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "server", "client_received_bytes_total"),
"Amount of data received over a connection on the VPN server, in bytes.",
[]string{"status_path", "common_name", "connection_time", "real_address", "virtual_address", "username"}, nil),
ValueType: prometheus.CounterValue,
},
{
Column: "Bytes Sent",
Desc: prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "server", "client_sent_bytes_total"),
"Amount of data sent over a connection on the VPN server, in bytes.",
[]string{"status_path", "common_name", "connection_time", "real_address", "virtual_address", "username"}, nil),
ValueType: prometheus.CounterValue,
},
},
},
"ROUTING_TABLE": {
LabelColumns: []string{
"Common Name",
"Real Address",
"Virtual Address",
},
Metrics: []OpenvpnServerHeaderField{
{
Column: "Last Ref (time_t)",
Desc: prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "server", "route_last_reference_time_seconds"),
"Time at which a route was last referenced, in seconds.",
[]string{"status_path", "common_name", "real_address", "virtual_address"}, nil),
ValueType: prometheus.GaugeValue,
},
},
},
}
// Metrics specific to OpenVPN clients.
openvpnClientDescs = map[string]*prometheus.Desc{
"TUN/TAP read bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "tun_tap_read_bytes_total"),
"Total amount of TUN/TAP traffic read, in bytes.",
[]string{"status_path"}, nil),
"TUN/TAP write bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "tun_tap_write_bytes_total"),
"Total amount of TUN/TAP traffic written, in bytes.",
[]string{"status_path"}, nil),
"TCP/UDP read bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "tcp_udp_read_bytes_total"),
"Total amount of TCP/UDP traffic read, in bytes.",
[]string{"status_path"}, nil),
"TCP/UDP write bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "tcp_udp_write_bytes_total"),
"Total amount of TCP/UDP traffic written, in bytes.",
[]string{"status_path"}, nil),
"Auth read bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "auth_read_bytes_total"),
"Total amount of authentication traffic read, in bytes.",
[]string{"status_path"}, nil),
"pre-compress bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "pre_compress_bytes_total"),
"Total amount of data before compression, in bytes.",
[]string{"status_path"}, nil),
"post-compress bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "post_compress_bytes_total"),
"Total amount of data after compression, in bytes.",
[]string{"status_path"}, nil),
"pre-decompress bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "pre_decompress_bytes_total"),
"Total amount of data before decompression, in bytes.",
[]string{"status_path"}, nil),
"post-decompress bytes": prometheus.NewDesc(
prometheus.BuildFQName("openvpn", "client", "post_decompress_bytes_total"),
"Total amount of data after decompression, in bytes.",
[]string{"status_path"}, nil),
}
)
// Converts OpenVPN status information into Prometheus metrics. This
// function automatically detects whether the file contains server or
// client metrics. For server metrics, it also distinguishes between the
// version 2 and 3 file formats.
func CollectStatusFromReader(statusPath string, file io.Reader, ch chan<- prometheus.Metric) error {
reader := bufio.NewReader(file)
buf, _ := reader.Peek(18)
if bytes.HasPrefix(buf, []byte("TITLE,")) {
// Server statistics, using format version 2.
return CollectServerStatusFromReader(statusPath, reader, ch, ",")
} else if bytes.HasPrefix(buf, []byte("TITLE\t")) {
// Server statistics, using format version 3. The only
// difference compared to version 2 is that it uses tabs
// instead of spaces.
return CollectServerStatusFromReader(statusPath, reader, ch, "\t")
} else if bytes.HasPrefix(buf, []byte("OpenVPN STATISTICS")) {
// Client statistics.
return CollectClientStatusFromReader(statusPath, reader, ch)
} else {
return fmt.Errorf("unexpected file contents: %q", buf)
}
}
// Converts OpenVPN server status information into Prometheus metrics.
func CollectServerStatusFromReader(statusPath string, file io.Reader, ch chan<- prometheus.Metric, separator string) error {
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
headersFound := map[string][]string{}
// counter of connected client
numberConnectedClient := 0
for scanner.Scan() {
fields := strings.Split(scanner.Text(), separator)
if fields[0] == "END" && len(fields) == 1 {
// Stats footer.
} else if fields[0] == "GLOBAL_STATS" {
// Global server statistics.
} else if fields[0] == "HEADER" && len(fields) > 2 {
// Column names for CLIENT_LIST and ROUTING_TABLE.
headersFound[fields[1]] = fields[2:]
} else if fields[0] == "TIME" && len(fields) == 3 {
// Time at which the statistics were updated.
timeStartStats, err := strconv.ParseFloat(fields[2], 64)
if err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(
openvpnStatusUpdateTimeDesc,
prometheus.GaugeValue,
timeStartStats,
statusPath)
} else if fields[0] == "TITLE" && len(fields) == 2 {
// OpenVPN version number.
} else if header, ok := openvpnServerHeaders[fields[0]]; ok {
if fields[0] == "CLIENT_LIST" {
numberConnectedClient ++
}
// Entry that depends on a preceding HEADERS directive.
columnNames, ok := headersFound[fields[0]]
if !ok {
return fmt.Errorf("%s should be preceded by HEADERS", fields[0])
}
if len(fields) != len(columnNames)+1 {
return fmt.Errorf("HEADER for %s describes a different number of columns", fields[0])
}
// Store entry values in a map indexed by column name.
columnValues := map[string]string{}
for _, column := range header.LabelColumns {
columnValues[column] = ""
}
for i, column := range columnNames {
columnValues[column] = fields[i+1]
}
// Extract columns that should act as entry labels.
labels := []string{statusPath}
for _, column := range header.LabelColumns {
labels = append(labels, columnValues[column])
}
// Export relevant columns as individual metrics.
for _, metric := range header.Metrics {
if columnValue, ok := columnValues[metric.Column]; ok {
value, err := strconv.ParseFloat(columnValue, 64)
if err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(
metric.Desc,
metric.ValueType,
value,
labels...)
}
}
} else {
return fmt.Errorf("unsupported key: %q", fields[0])
}
}
// add the number of connected client
ch <- prometheus.MustNewConstMetric(
openvpnConnectedClientsDesc,
prometheus.GaugeValue,
float64(numberConnectedClient),
statusPath)
return scanner.Err()
}
// Converts OpenVPN client status information into Prometheus metrics.
func CollectClientStatusFromReader(statusPath string, file io.Reader, ch chan<- prometheus.Metric) error {
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
fields := strings.Split(scanner.Text(), ",")
if fields[0] == "END" && len(fields) == 1 {
// Stats footer.
} else if fields[0] == "OpenVPN STATISTICS" && len(fields) == 1 {
// Stats header.
} else if fields[0] == "Updated" && len(fields) == 2 {
// Time at which the statistics were updated.
location, _ := time.LoadLocation("Local")
timeParser, err := time.ParseInLocation("Mon Jan 2 15:04:05 2006", fields[1], location)
if err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(
openvpnStatusUpdateTimeDesc,
prometheus.GaugeValue,
float64(timeParser.Unix()),
statusPath)
} else if desc, ok := openvpnClientDescs[fields[0]]; ok && len(fields) == 2 {
// Traffic counters.
value, err := strconv.ParseFloat(fields[1], 64)
if err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(
desc,
prometheus.CounterValue,
value,
statusPath)
} else {
return fmt.Errorf("unsupported key: %q", fields[0])
}
}
return scanner.Err()
}
func CollectStatusFromFile(statusPath string, ch chan<- prometheus.Metric) error {
conn, err := os.Open(statusPath)
defer conn.Close()
if err != nil {
return err
}
return CollectStatusFromReader(statusPath, conn, ch)
}
type OpenVPNExporter struct {
statusPaths []string
}
func NewOpenVPNExporter(statusPaths []string) (*OpenVPNExporter, error) {
return &OpenVPNExporter{
statusPaths: statusPaths,
}, nil
}
func (e *OpenVPNExporter) Describe(ch chan<- *prometheus.Desc) {
ch <- openvpnUpDesc
}
func (e *OpenVPNExporter) Collect(ch chan<- prometheus.Metric) {
for _, statusPath := range e.statusPaths {
err := CollectStatusFromFile(statusPath, ch)
if err == nil {
ch <- prometheus.MustNewConstMetric(
openvpnUpDesc,
prometheus.GaugeValue,
1.0,
statusPath)
} else {
log.Printf("Failed to scrape showq socket: %s", err)
ch <- prometheus.MustNewConstMetric(
openvpnUpDesc,
prometheus.GaugeValue,
0.0,
statusPath)
}
}
}
func main() {
var (
listenAddress = flag.String("web.listen-address", ":9176", "Address to listen on for web interface and telemetry.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
openvpnStatusPaths = flag.String("openvpn.status_paths", "examples/client.status,examples/server2.status,examples/server3.status", "Paths at which OpenVPN places its status files.")
)
flag.Parse()
log.Printf("Starting OpenVPN Exporter\n")
log.Printf("Listen address: %v\n", *listenAddress)
log.Printf("Metrics path: %v\n", *metricsPath)
log.Printf("openvpn.status_path: %v\n", *openvpnStatusPaths)
exporter, err := NewOpenVPNExporter(strings.Split(*openvpnStatusPaths, ","))
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>OpenVPN Exporter</title></head>
<body>
<h1>OpenVPN Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}