-
Notifications
You must be signed in to change notification settings - Fork 118
/
metrics.go
135 lines (110 loc) · 2.58 KB
/
metrics.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
package main
import (
_ "embed"
"fmt"
upnp "github.com/ndecker/fritzbox_exporter/fritzbox_upnp"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/yaml.v3"
"io"
"log"
"os"
"strings"
)
//go:embed default-metrics.yaml
var defaultMetricsYaml []byte
type Metric struct {
Metric string
Help string
Type string
Service string
Action string
Result string
OkValue string `yaml:",omitempty"`
LabelName string `yaml:",omitempty"`
Source string `yaml:",omitempty"`
ExampleValue string `yaml:",omitempty"`
metricType prometheus.ValueType
desc *prometheus.Desc
}
func (m *Metric) String() string {
var res strings.Builder
if m.Metric != "" {
res.WriteString(fmt.Sprintf("%s: ", m.Metric))
}
res.WriteString(fmt.Sprintf("%s/%s/%s", m.Service, m.Action, m.Result))
return res.String()
}
func loadMetrics(data []byte) ([]*Metric, error) {
var metrics []*Metric
err := yaml.Unmarshal(data, &metrics)
if err != nil {
return nil, err
}
// Filter valid metrics
var metrics2 []*Metric
for _, m := range metrics {
if m.Metric == "" {
log.Printf("skipping metric %s: no metric name\n", m)
continue
}
switch m.Type {
case "counter":
m.metricType = prometheus.CounterValue
case "gauge":
m.metricType = prometheus.GaugeValue
default:
log.Printf("skipping metric %s: invalid metric type: %s", m, m.Type)
continue
}
labels := []string{"gateway"}
if m.LabelName != "" {
labels = append(labels, m.LabelName)
}
m.desc = prometheus.NewDesc(m.Metric, m.Help, labels, nil)
metrics2 = append(metrics2, m)
}
return metrics2, nil
}
func writeMetrics(w io.Writer, metrics []*Metric) error {
data, err := yaml.Marshal(metrics)
if err != nil {
return err
}
_, err = w.Write(data)
return err
}
func testMetrics(p upnp.ConnectionParameters, desc string) error {
root, err := upnp.LoadServiceRoot(p, desc)
if err != nil {
return err
}
var metrics []*Metric
for _, s := range root.Services {
for _, a := range s.Actions {
if !a.IsGetOnly() {
continue
}
res, err := a.Call()
if err != nil {
log.Printf("unexpected error: %v\n", err)
continue
}
for _, arg := range a.Arguments {
value := res[arg.StateVariable.Name]
m := &Metric{
Metric: "",
Help: "",
Type: "",
Service: s.ServiceType,
Action: a.Name,
Result: arg.StateVariable.Name,
ExampleValue: fmt.Sprintf("%v", value),
OkValue: "",
Source: desc,
}
metrics = append(metrics, m)
}
}
}
return writeMetrics(os.Stdout, metrics)
}