-
Notifications
You must be signed in to change notification settings - Fork 1
/
exporter.go
489 lines (449 loc) · 15.5 KB
/
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
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"path"
"strconv"
//"strings"
"crypto/md5"
"crypto/tls"
"strings"
"sync"
"time"
//"crypto/sha256"
"encoding/hex"
"encoding/json"
"encoding/xml"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/text/encoding/unicode"
//"golang.org/x/crypto/pbkdf2"
"github.com/prometheus/common/log"
)
var (
channelLabelNames = []string{"channel"}
// interfaceLabelNames = []string{"interface"}
)
func newChannelMetric(subsystemName, metricName, docString string, extraLabels ...string) *prometheus.Desc {
return prometheus.NewDesc(prometheus.BuildFQName(namespace, subsystemName, metricName), docString, append(channelLabelNames, extraLabels...), nil)
}
type metrics map[int]*prometheus.Desc
var (
targetUpMetric = prometheus.NewDesc(prometheus.BuildFQName(namespace, "", "up"), "Was the last scrape of Fritzbox succesful.", nil, nil)
// FIXME: not parsed yet.
networkMetrics = metrics{
1: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "receive_bytes_total"), "", []string{"interface"}, nil),
2: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "receive_packets_total"), "", []string{"interface"}, nil),
3: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "receive_errs_total"), "", []string{"interface"}, nil),
4: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "receive_drop_total"), "", []string{"interface"}, nil),
5: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "transmit_bytes_total"), "", []string{"interface"}, nil),
6: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "transmit_packets_total"), "", []string{"interface"}, nil),
7: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "transmit_errs_total"), "", []string{"interface"}, nil),
8: prometheus.NewDesc(prometheus.BuildFQName(namespace, "network", "transmit_drop_total"), "", []string{"interface"}, nil),
}
downstreamChannelMetrics = metrics{
2: newChannelMetric("downstream", "locked", "Downstream Lock Status"),
3: newChannelMetric("downstream", "channel_type", "Downstream Channel Type", "type"),
4: newChannelMetric("downstream", "bonded", "Downstream Bonding Status"),
5: newChannelMetric("downstream", "center_frequency_hz", "Downstream Center Frequency"),
6: newChannelMetric("downstream", "width_hz", "Downstream Width"),
7: newChannelMetric("downstream", "snr_threshold_db", "Downstream SNR/MER Threshold Value"),
8: newChannelMetric("downstream", "receive_level_dbmv", "Downstream Receive Level"),
9: newChannelMetric("downstream", "modulation", "Downstream Modulation/Profile ID", "modulation"),
10: newChannelMetric("downstream", "codewords_unerrored_total", "Downstream Unerrored Codewords"),
11: newChannelMetric("downstream", "codewords_corrected_total", "Downstream Corrected Codewords"),
12: newChannelMetric("downstream", "codewords_uncorrectable_total", "Downstream Uncorrectable Codewords"),
13: newChannelMetric("downstream", "latency", "Downstream latency"),
14: newChannelMetric("downstream", "modulation_clear", "Downstream Modulation in clear value"),
}
upstreamChannelMetrics = metrics{
2: newChannelMetric("upstream", "locked", "Upstream Lock Status"),
3: newChannelMetric("upstream", "channel_type", "Downstream Channel Type", "type"),
4: newChannelMetric("upstream", "bonded", "Upstream Bonding Status"),
5: newChannelMetric("upstream", "center_frequency_hz", "Upstream Center Frequency"),
6: newChannelMetric("upstream", "width_hz", "Upstream Width"),
7: newChannelMetric("upstream", "transmit_level_dbmv", "Upstream Transmit Level"),
8: newChannelMetric("upstream", "modulation", "Upstream Modulation/Profile ID", "modulation"),
9: newChannelMetric("upstream", "modulation_clear", "Upstream Modulation in clear value"),
}
)
type SessionInfo struct {
Sid string `xml:"SID"`
Challenge string `xml:"Challenge"`
BlockTime string `xml:"BlockTime"`
}
type FritzRoot struct {
Data FritzData `json:"data"`
Hide FritzHide `json:"hide"`
// pid string `json:"pid"`
// sid string `json:"sid"`
}
type FritzData struct {
ChannelsDown FritzChannelD `json:"channelDs"`
ChannelsUp FritzChannelUs `json:"channelUs"`
Oem string `json:"oem"`
}
type FritzChannelD struct {
Channel30 []FritzChannel `json:"docsis30"`
Channel31 []FritzChannel `json:"docsis31"`
}
type FritzChannelUs struct {
Channel30 []FritzChannel `json:"docsis30"`
Channel31 []FritzChannel `json:"docsis31"`
}
type FritzChannel struct {
Channel int `json:"channel"`
ChannelId int `json:"channelID"`
CorrErrors int `json:"corrErrors"`
Frequency string `json:"frequency"`
Latency float32 `json:"latency"`
Mse string `json:"mse"`
NonCorrErrors int `json:"nonCorrErrors"`
Powerlevel string `json:"powerLevel"`
Multiplex string `json:"multiplex"`
Type string `json:"modulation"`
}
type FritzHide struct {
Chan bool `json:"chan"`
Dectmail bool `json:"dectMail"`
Dectmoni bool `json:"dectMoni"`
Dectmoniex bool `json:"dectMoniEx"`
Dvbset bool `json:"dvbSet"`
Dvbsig bool `json:"dvbSig"`
Dvbradio bool `json:"dvbradio"`
Faxset bool `json:"faxSet"`
Liveimg bool `json:"liveImg"`
Livetv bool `json:"liveTv"`
Mobile bool `json:"mobile"`
Rss bool `json:"rss"`
Shareusb bool `json:"shareUsb"`
Ssoset bool `json:"ssoSet"`
Tvhd bool `json:"tvhd"`
Tvsd bool `json:"tvsd"`
Wguest bool `json:"wGuest"`
Wkey bool `json:"wKey"`
Wlanmesh bool `json:"wlanmesh"`
Wps bool `json:"wps"`
}
type Exporter struct {
baseURL string
username string
password string
ignoreCert bool
sid string
client *http.Client
mutex sync.RWMutex
totalScrapes prometheus.Counter
parseFailures *prometheus.CounterVec
clientRequestCount *prometheus.CounterVec
clientRequestDuration *prometheus.HistogramVec
}
func NewExporter(uri string, username string, password string, timeout time.Duration, ignoreCert bool) (*Exporter, error) {
clientTransport := http.DefaultTransport.(*http.Transport).Clone()
clientTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: ignoreCert}
client := &http.Client{Transport: clientTransport, Timeout: timeout}
clientRequestCount := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_client_requests_total",
Help: "HTTP requests to Fritzbox Cable",
}, []string{"code", "method"})
clientRequestDuration := prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: namespace,
Name: "exporter_client_request_duration_seconds",
Help: "Histogram of Fritzbox Cable HTTP request latencies.",
}, []string{"code", "method"})
client.Transport = promhttp.InstrumentRoundTripperCounter(clientRequestCount,
promhttp.InstrumentRoundTripperDuration(clientRequestDuration, http.DefaultTransport))
return &Exporter{
baseURL: uri,
client: client,
username: username,
password: password,
ignoreCert: ignoreCert,
totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_scrapes_total",
Help: "Current total Fritzbox Cable scrapes.",
}),
parseFailures: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_parse_errors_total",
Help: "Number of errors while parsing statistics.",
}, []string{"file"}),
clientRequestCount: clientRequestCount,
clientRequestDuration: clientRequestDuration,
}, nil
}
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, m := range networkMetrics {
ch <- m
}
for _, m := range downstreamChannelMetrics {
ch <- m
}
for _, m := range upstreamChannelMetrics {
ch <- m
}
ch <- targetUpMetric
ch <- e.totalScrapes.Desc()
e.parseFailures.Describe(ch)
e.clientRequestCount.Describe(ch)
e.clientRequestDuration.Describe(ch)
}
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
e.mutex.Lock()
defer e.mutex.Unlock()
up := e.scrape(ch)
ch <- prometheus.MustNewConstMetric(targetUpMetric, prometheus.GaugeValue, up)
ch <- e.totalScrapes
e.parseFailures.Collect(ch)
e.clientRequestCount.Collect(ch)
e.clientRequestDuration.Collect(ch)
}
func (e *Exporter) fetch(filename string) (io.ReadCloser, error) {
u, err := url.Parse(e.baseURL)
if err != nil {
return nil, err
}
u.Path = path.Join(u.Path, filename)
resp, err := e.client.PostForm(u.String(), url.Values{
"xhr": {"1"},
"sid": {e.sid},
"lang": {"de"},
"page": {"docInfo"},
"xhrId": {"all"}})
if err != nil {
return nil, err
}
if !(resp.StatusCode >= 200 && resp.StatusCode < 300) {
resp.Body.Close()
return nil, fmt.Errorf("scraping %s failed: http status %d", u.String(), resp.StatusCode)
}
return resp.Body, nil
}
func (e *Exporter) login() error {
u, err := url.Parse(e.baseURL)
if err != nil {
return err
}
u.Path = path.Join(u.Path, "login_sid.lua")
resp, err := e.client.Get(u.String())
if err != nil {
return err
}
byteValue, _ := io.ReadAll(resp.Body)
resp.Body.Close()
var sessionInfo SessionInfo
if err := xml.Unmarshal(byteValue, &sessionInfo); err != nil {
return err
}
if string(sessionInfo.Challenge[0:2]) == "2$" {
// SHA256, pbkdf2 hash
//string(sessionInfo.Challenge[0:2]))
//salt := []byte("asdf")
//dk := pbkdf2.Key([]byte(e.password), salt, 256, 32, sha256.New)
//fmt.Println(dk)
return fmt.Errorf("pbkdf2 hash algorithm for login is not supported")
}
utf16 := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
prepPassword := sessionInfo.Challenge + "-" + e.password
encoded, err := utf16.NewEncoder().String(prepPassword)
if err != nil {
log.Error(err)
return err
}
md5Hex := md5.Sum([]byte(encoded))
md5Challenge := sessionInfo.Challenge + "-" + hex.EncodeToString(md5Hex[:])
log.Debugf("MD5 challenge: %s", md5Challenge)
// no login via Post
resp, err = e.client.PostForm(u.String(), url.Values{
"username": {e.username},
"response": {md5Challenge}})
if err != nil {
return err
}
if !(resp.StatusCode >= 200 && resp.StatusCode < 300) {
resp.Body.Close()
return fmt.Errorf("scraping %s failed: http status %d", u.String(), resp.StatusCode)
}
byteValue, _ = io.ReadAll(resp.Body)
if err := xml.Unmarshal(byteValue, &sessionInfo); err != nil {
return err
}
e.sid = sessionInfo.Sid
resp.Body.Close()
return nil
}
func parseDownstreamChannels(ch chan<- prometheus.Metric, e *Exporter, channelType string, cableChan FritzChannel) {
log.Debugf("ChannelId: %s", strconv.Itoa(cableChan.ChannelId))
channelLabel := ""
if channelType == "OFDM" {
channelLabel = "O"
}
channelLabel = channelLabel + fmt.Sprintf("%02d", cableChan.ChannelId)
for i, metric := range downstreamChannelMetrics {
var err error = nil
var value float64
var labelValues = []string{channelLabel}
switch i {
case 2:
// We have no knowledge about locked / ... in fritzbox.
value = 1
case 3:
labelValues = append(labelValues, channelType)
value = 1
case 4:
// We have no knowledge about bonded / ... in fritzbox.
value = 1
case 5:
if channelType == "OFDM" {
// Its a range for OFDM ?
freqSplit := strings.Split(cableChan.Frequency, " - ")
value, err = strconv.ParseFloat(freqSplit[0], 64)
} else {
value, err = strconv.ParseFloat(cableChan.Frequency, 64)
}
// Fritzbox shows it always in Mhz
value = value * 1000000
case 6:
value = 0.0
case 7:
value, err = strconv.ParseFloat(cableChan.Mse, 64)
// For OFDM, error is fine!
if channelType == "OFDM" && err != nil {
value = 0.0
err = nil
}
case 8:
value, err = strconv.ParseFloat(cableChan.Powerlevel, 64)
case 9:
labelValues = append(labelValues, cableChan.Type)
value = 1
case 10:
value = 0
case 11:
value = float64(cableChan.CorrErrors)
case 12:
value = float64(cableChan.NonCorrErrors)
case 13:
value = float64(cableChan.Latency)
case 14:
numval := strings.Replace(cableChan.Type, "QAM", "", -1)
ofdmK := false
if strings.Contains(numval, "K") {
numval = strings.Replace(numval, "K", "", -1)
ofdmK = true
}
convval, _ := strconv.ParseInt(numval, 10, 0)
if ofdmK {
convval = convval * 1024
}
value = float64(convval)
default:
continue
}
if err != nil {
log.Errorln(err)
e.parseFailures.WithLabelValues("docInfo").Inc()
continue
}
ch <- prometheus.MustNewConstMetric(metric, prometheus.CounterValue, value, labelValues...)
}
}
func parseUpstreamChannels(ch chan<- prometheus.Metric, e *Exporter, channelType string, cableChan FritzChannel) {
log.Debugf("ChannelId: %s", strconv.Itoa(cableChan.ChannelId))
channelLabel := ""
if channelType == "OFDM" {
channelLabel = "O"
}
channelLabel = channelLabel + fmt.Sprintf("%02d", cableChan.ChannelId)
for i, metric := range upstreamChannelMetrics {
var err error = nil
var value float64
var labelValues = []string{channelLabel}
switch i {
case 2:
// We have no knowledge about locked / ... in fritzbox.
value = 1
case 3:
labelValues = append(labelValues, channelType)
value = 1
case 4:
// We have no knowledge about bonded / ... in fritzbox.
value = 1
case 5:
if channelType == "OFDM" {
// Its a range for OFDM ?
freqSplit := strings.Split(cableChan.Frequency, " - ")
value, err = strconv.ParseFloat(freqSplit[0], 64)
} else {
value, err = strconv.ParseFloat(cableChan.Frequency, 64)
}
// Fritzbox shows it always in Mhz
value = value * 1000000
case 6:
value = 0.0
case 7:
value, err = strconv.ParseFloat(cableChan.Powerlevel, 64)
case 8:
labelValues = append(labelValues, cableChan.Type)
value = 1
case 9:
numval := strings.Replace(cableChan.Type, "QAM", "", -1)
ofdmK := false
if strings.Contains(numval, "K") {
numval = strings.Replace(numval, "K", "", -1)
ofdmK = true
}
convval, _ := strconv.ParseInt(numval, 10, 0)
if ofdmK {
convval = convval * 1024
}
value = float64(convval)
default:
continue
}
if err != nil {
log.Errorln(err)
e.parseFailures.WithLabelValues("docInfo").Inc()
continue
}
ch <- prometheus.MustNewConstMetric(metric, prometheus.CounterValue, value, labelValues...)
}
}
func (e *Exporter) scrape(ch chan<- prometheus.Metric) (up float64) {
e.totalScrapes.Inc()
if err := e.login(); err != nil {
log.Errorf("failed to login - scraping not possible: %s", err.Error())
return 0
}
body, err := e.fetch("data.lua")
if err == nil {
var docInfo FritzRoot
byteValue, _ := io.ReadAll(body)
if err := json.Unmarshal(byteValue, &docInfo); err != nil {
log.Errorf("failed parsing metrics details as JSON document: %s", err.Error())
return 0
}
for i := 0; i < len(docInfo.Data.ChannelsDown.Channel30); i++ {
log.Debugf("ChannelId: %s", strconv.Itoa(docInfo.Data.ChannelsDown.Channel30[i].ChannelId))
}
body.Close()
// downstreamChannelMetrics
for i := 0; i < len(docInfo.Data.ChannelsDown.Channel30); i++ {
parseDownstreamChannels(ch, e, "SC-QAM", docInfo.Data.ChannelsDown.Channel30[i])
}
for i := 0; i < len(docInfo.Data.ChannelsDown.Channel31); i++ {
parseDownstreamChannels(ch, e, "OFDM", docInfo.Data.ChannelsDown.Channel31[i])
}
for i := 0; i < len(docInfo.Data.ChannelsUp.Channel30); i++ {
parseUpstreamChannels(ch, e, "ATDMA", docInfo.Data.ChannelsUp.Channel30[i])
}
for i := 0; i < len(docInfo.Data.ChannelsUp.Channel31); i++ {
parseUpstreamChannels(ch, e, "OFDM", docInfo.Data.ChannelsUp.Channel31[i])
}
}
return 1
}