-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
494 lines (403 loc) · 11.9 KB
/
main.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
package main
// Copyright 2016 Nils Decker
//
// 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.
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/namsral/flag"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
upnp "gitlab.com/dekarl/fritzbox_exporter/fritzbox_upnp"
)
const serviceLoadRetryTime = 1 * time.Minute
var (
flagTest = flag.Bool("test", false, "print all available metrics to stdout")
flagCollect = flag.Bool("collect", false, "print configured metrics to stdout and exit")
flagJsonOut = flag.String("json-out", "", "store metrics also to JSON file when running test")
flagAddr = flag.String("listen-address", "127.0.0.1:9042", "The address to listen on for HTTP requests.")
flagMetricsFile = flag.String("metrics-file", "metrics.json", "The JSON file with the metric definitions.")
flagGatewayUrl = flag.String("gateway-url", "http://fritz.box:49000", "The URL of the FRITZ!Box")
flagGatewayUsername = flag.String("username", "", "The user for the FRITZ!Box UPnP service")
flagGatewayPassword = flag.String("password", "", "The password for the FRITZ!Box UPnP service")
flagGatewayVerifyTLS = flag.Bool("verifyTls", false, "Verify the tls connection when connecting to the FRITZ!Box")
)
var (
collectErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "fritzbox_exporter_collect_errors",
Help: "Number of collection errors.",
})
)
type JsonPromDesc struct {
FqName string `json:"fqName"`
Help string `json:"help"`
VarLabels []string `json:"varLabels"`
}
type ActionArg struct {
Name string `json:"Name"`
IsIndex bool `json:"IsIndex"`
ProviderAction string `json:"ProviderAction"`
Value string `json:"Value"`
}
type Metric struct {
// initialized loading JSON
Service string `json:"service"`
Action string `json:"action"`
ActionArgument *ActionArg `json:"actionArgument"`
Result string `json:"result"`
OkValue string `json:"okValue"`
PromDesc JsonPromDesc `json:"promDesc"`
PromType string `json:"promType"`
// initialized at startup
Desc *prometheus.Desc
MetricType prometheus.ValueType
}
var metrics []*Metric
type FritzboxCollector struct {
Url string
Gateway string
Username string
Password string
VerifyTls bool
sync.Mutex // protects Root
Root *upnp.Root
}
// simple ResponseWriter to collect output
type TestResponseWriter struct {
header http.Header
statusCode int
body bytes.Buffer
}
func (w *TestResponseWriter) Header() http.Header {
return w.header
}
func (w *TestResponseWriter) Write(b []byte) (int, error) {
return w.body.Write(b)
}
func (w *TestResponseWriter) WriteHeader(statusCode int) {
w.statusCode = statusCode
}
func (w *TestResponseWriter) String() string {
return w.body.String()
}
// LoadServices tries to load the service information. Retries until success.
func (fc *FritzboxCollector) LoadServices() {
for {
root, err := upnp.LoadServices(fc.Url, fc.Username, fc.Password, fc.VerifyTls)
if err != nil {
fmt.Printf("cannot load services: %s\n", err)
time.Sleep(serviceLoadRetryTime)
continue
}
fmt.Printf("services loaded\n")
fc.Lock()
fc.Root = root
fc.Unlock()
return
}
}
func (fc *FritzboxCollector) Describe(ch chan<- *prometheus.Desc) {
for _, m := range metrics {
ch <- m.Desc
}
}
func (fc *FritzboxCollector) ReportMetric(ch chan<- prometheus.Metric, m *Metric, result upnp.Result) {
val, ok := result[m.Result]
if !ok {
fmt.Printf("%s.%s has no result %s", m.Service, m.Action, m.Result)
collectErrors.Inc()
return
}
var floatval float64
switch tval := val.(type) {
case uint64:
floatval = float64(tval)
case bool:
if tval {
floatval = 1
} else {
floatval = 0
}
case string:
if tval == m.OkValue {
floatval = 1
} else {
floatval = 0
}
default:
fmt.Println("unknown type", val)
collectErrors.Inc()
return
}
labels := make([]string, len(m.PromDesc.VarLabels))
for i, l := range m.PromDesc.VarLabels {
if l == "gateway" {
labels[i] = fc.Gateway
} else {
lval, ok := result[l]
if !ok {
fmt.Printf("%s.%s has no resul for label %s", m.Service, m.Action, l)
lval = ""
}
// convert to lower to avoid problems with labels like hostname
labels[i] = strings.ToLower(fmt.Sprintf("%v", lval))
}
}
ch <- prometheus.MustNewConstMetric(
m.Desc,
m.MetricType,
floatval,
labels...)
}
func (fc *FritzboxCollector) GetActionResult(resultMap map[string]upnp.Result, serviceType string, actionName string, actionArg *upnp.ActionArgument) (upnp.Result, error) {
mKey := serviceType + "|" + actionName
// for calls with argument also add arguement name and value to key
if actionArg != nil {
mKey += "|" + actionArg.Name + "|" + fmt.Sprintf("%v", actionArg.Value)
}
lastResult := resultMap[mKey]
if lastResult == nil {
service, ok := fc.Root.Services[serviceType]
if !ok {
return nil, errors.New(fmt.Sprintf("service %s not found", serviceType))
}
action, ok := service.Actions[actionName]
if !ok {
return nil, errors.New(fmt.Sprintf("action %s not found in service %s", actionName, serviceType))
}
var err error
lastResult, err = action.Call(actionArg)
if err != nil {
return nil, err
}
resultMap[mKey] = lastResult
}
return lastResult, nil
}
func (fc *FritzboxCollector) Collect(ch chan<- prometheus.Metric) {
fc.Lock()
root := fc.Root
fc.Unlock()
if root == nil {
// Services not loaded yet
return
}
// create a map for caching results
var resultMap = make(map[string]upnp.Result)
for _, m := range metrics {
var actArg *upnp.ActionArgument
if m.ActionArgument != nil {
aa := m.ActionArgument
var value interface{}
value = aa.Value
if aa.ProviderAction != "" {
provRes, err := fc.GetActionResult(resultMap, m.Service, aa.ProviderAction, nil)
if err != nil {
fmt.Printf("Error getting provider action %s result for %s.%s: %s\n", aa.ProviderAction, m.Service, m.Action, err.Error())
collectErrors.Inc()
continue
}
var ok bool
value, ok = provRes[aa.Value] // Value contains the result name for provider actions
if !ok {
fmt.Printf("provider action %s for %s.%s has no result", m.Service, m.Action, aa.Value)
collectErrors.Inc()
continue
}
}
if aa.IsIndex {
sval := fmt.Sprintf("%v", value)
count, err := strconv.Atoi(sval)
if err != nil {
fmt.Println(err.Error())
collectErrors.Inc()
continue
}
for i := 0; i < count; i++ {
actArg = &upnp.ActionArgument{Name: aa.Name, Value: i}
result, err := fc.GetActionResult(resultMap, m.Service, m.Action, actArg)
if err != nil {
fmt.Println(err.Error())
collectErrors.Inc()
continue
}
fc.ReportMetric(ch, m, result)
}
continue
} else {
actArg = &upnp.ActionArgument{Name: aa.Name, Value: value}
}
}
result, err := fc.GetActionResult(resultMap, m.Service, m.Action, actArg)
if err != nil {
fmt.Println(err.Error())
collectErrors.Inc()
continue
}
fc.ReportMetric(ch, m, result)
}
}
func test() {
root, err := upnp.LoadServices(*flagGatewayUrl, *flagGatewayUsername, *flagGatewayPassword, *flagGatewayVerifyTLS)
if err != nil {
panic(err)
}
var newEntry bool = false
var json bytes.Buffer
json.WriteString("[\n")
serviceKeys := []string{}
for k, _ := range root.Services {
serviceKeys = append(serviceKeys, k)
}
sort.Strings(serviceKeys)
for _, k := range serviceKeys {
s := root.Services[k]
fmt.Printf("Service: %s (Url: %s)\n", k, s.ControlUrl)
var actionKeys []string
for l, _ := range s.Actions {
actionKeys = append(actionKeys, l)
}
sort.Strings(actionKeys)
for _, l := range actionKeys {
a := s.Actions[l]
fmt.Printf(" %s - arguments: variable [direction] (soap name, soap type)\n", a.Name)
for _, arg := range a.Arguments {
sv := arg.StateVariable
fmt.Printf(" %s [%s] (%s, %s)\n", arg.RelatedStateVariable, arg.Direction, arg.Name, sv.DataType)
}
if !a.IsGetOnly() {
fmt.Printf(" %s - not calling, since arguments required or no output\n", a.Name)
continue
}
// only create JSON for Get
// TODO also create JSON templates for input actionParams
for _, arg := range a.Arguments {
// create new json entry
if newEntry {
json.WriteString(",\n")
} else {
newEntry = true
}
json.WriteString("\t{\n\t\t\"service\": \"")
json.WriteString(k)
json.WriteString("\",\n\t\t\"action\": \"")
json.WriteString(a.Name)
json.WriteString("\",\n\t\t\"result\": \"")
json.WriteString(arg.RelatedStateVariable)
json.WriteString("\"\n\t}")
}
fmt.Printf(" %s - calling - results: variable: value\n", a.Name)
res, err := a.Call(nil)
if err != nil {
fmt.Printf(" FAILED:%s\n", err.Error())
continue
}
for _, arg := range a.Arguments {
fmt.Printf(" %s: %v\n", arg.RelatedStateVariable, res[arg.StateVariable.Name])
}
}
}
json.WriteString("\n]")
if *flagJsonOut != "" {
err := ioutil.WriteFile(*flagJsonOut, json.Bytes(), 0644)
if err != nil {
fmt.Printf("Failed writing JSON file '%s': %s\n", *flagJsonOut, err.Error())
}
}
}
func getValueType(vt string) prometheus.ValueType {
switch vt {
case "CounterValue":
return prometheus.CounterValue
case "GaugeValue":
return prometheus.GaugeValue
case "UntypedValue":
return prometheus.UntypedValue
}
return prometheus.UntypedValue
}
func main() {
flag.Parse()
u, err := url.Parse(*flagGatewayUrl)
if err != nil {
fmt.Println("invalid URL:", err)
return
}
if *flagTest {
test()
return
}
// read metrics
jsonData, err := ioutil.ReadFile(*flagMetricsFile)
if err != nil {
fmt.Println("error reading metric file:", err)
return
}
err = json.Unmarshal(jsonData, &metrics)
if err != nil {
fmt.Println("error parsing JSON:", err)
return
}
// init metrics
for _, m := range metrics {
pd := m.PromDesc
// make labels lower case
labels := make([]string, len(pd.VarLabels))
for i, l := range pd.VarLabels {
labels[i] = strings.ToLower(l)
}
m.Desc = prometheus.NewDesc(pd.FqName, pd.Help, labels, nil)
m.MetricType = getValueType(m.PromType)
}
collector := &FritzboxCollector{
Url: *flagGatewayUrl,
Gateway: u.Hostname(),
Username: *flagGatewayUsername,
Password: *flagGatewayPassword,
VerifyTls: *flagGatewayVerifyTLS,
}
if *flagCollect {
collector.LoadServices()
prometheus.MustRegister(collector)
prometheus.MustRegister(collectErrors)
fmt.Println("collecting metrics via http")
// simulate HTTP request without starting actual http server
writer := TestResponseWriter{header: http.Header{}}
request := http.Request{}
promhttp.Handler().ServeHTTP(&writer, &request)
fmt.Println(writer.String())
return
}
go collector.LoadServices()
prometheus.MustRegister(collector)
prometheus.MustRegister(collectErrors)
healthChecks := createHealthChecks(*flagGatewayUrl)
http.Handle("/metrics", promhttp.Handler())
fmt.Printf("metrics available at http://%s/metrics\n", *flagAddr)
http.HandleFunc("/ready", healthChecks.ReadyEndpoint)
fmt.Printf("readyness check available at http://%s/ready\n", *flagAddr)
http.HandleFunc("/live", healthChecks.LiveEndpoint)
fmt.Printf("liveness check available at http://%s/live\n", *flagAddr)
log.Fatal(http.ListenAndServe(*flagAddr, nil))
}