-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
245 lines (203 loc) · 5.88 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
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/Tomy2e/livebox-api-client"
"github.com/Tomy2e/livebox-exporter/internal/collector"
"github.com/Tomy2e/livebox-exporter/internal/poller"
exporterLivebox "github.com/Tomy2e/livebox-exporter/pkg/livebox"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/exp/slices"
)
const indexPage = `<html>
<head>
<meta charset="utf-8">
<title>Livebox exporter</title>
</head>
<body>
<h1>The livebox-exporter is working!</h1>
<p>See <a href="/metrics">/metrics</a> for metrics.</p>
</body>
</html>
`
const defaultPollingFrequency = 30
const (
ExperimentalMetricsInterfaceHomeLan = "livebox_interface_homelan"
ExperimentalMetricsInterfaceNetDev = "livebox_interface_netdev"
ExperimentalMetricsWAN = "livebox_wan"
)
var experimentalMetrics = []string{
ExperimentalMetricsInterfaceHomeLan,
ExperimentalMetricsInterfaceNetDev,
ExperimentalMetricsWAN,
}
func parseExperimentalFlag(
client *livebox.Client,
interfaces []*exporterLivebox.Interface,
experimental string,
pollingFrequency *uint,
) (pollers []poller.Poller) {
if experimental == "" {
return nil
}
enabled := make(map[string]bool)
for _, exp := range strings.Split(experimental, ",") {
exp = strings.TrimSpace(exp)
if !slices.Contains(experimentalMetrics, exp) {
log.Printf("WARN: Unknown experimental metrics: %s", exp)
continue
}
if enabled[exp] {
continue
}
switch exp {
case ExperimentalMetricsInterfaceHomeLan:
pollers = append(pollers, poller.NewInterfaceHomeLanMbits(client, interfaces))
case ExperimentalMetricsInterfaceNetDev:
pollers = append(pollers, poller.NewInterfaceNetDevMbits(client, interfaces))
if *pollingFrequency > 5 {
log.Printf(
"WARN: The %s experimental metrics require a lower polling frequency, "+
"setting polling frequency to 5 seconds\n",
ExperimentalMetricsInterfaceNetDev,
)
*pollingFrequency = 5
}
case ExperimentalMetricsWAN:
pollers = append(pollers, poller.NewWANMbits(client))
}
log.Printf("INFO: enabled experimental metrics: %s\n", exp)
enabled[exp] = true
}
return
}
func getHTTPClient() (*http.Client, error) {
liveboxCACertPath := os.Getenv("LIVEBOX_CACERT")
if liveboxCACertPath == "" {
return http.DefaultClient, nil
}
// Get the SystemCertPool, continue with an empty pool on error.
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
certs, err := os.ReadFile(liveboxCACertPath)
if err != nil {
return nil, fmt.Errorf("failed to read livebox CA cert: %w", err)
}
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
return nil, errors.New("no livebox CA cert was successfully added")
}
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: rootCAs,
},
},
}, nil
}
func isFatalError(err error) bool {
if errors.Is(err, livebox.ErrInvalidCredentials) {
return true
}
var certError *tls.CertificateVerificationError
return errors.As(err, &certError)
}
func main() {
pollingFrequency := flag.Uint("polling-frequency", defaultPollingFrequency, "Polling frequency")
listen := flag.String("listen", ":8080", "Listening address")
experimental := flag.String("experimental", "", fmt.Sprintf(
"Comma separated list of experimental metrics to enable (available metrics: %s)",
strings.Join(experimentalMetrics, ","),
))
flag.Parse()
adminPassword := os.Getenv("ADMIN_PASSWORD")
if adminPassword == "" {
log.Fatal("ADMIN_PASSWORD environment variable must be set")
}
liveboxAddress := os.Getenv("LIVEBOX_ADDRESS")
if liveboxAddress == "" {
liveboxAddress = livebox.DefaultAddress
}
if *pollingFrequency == 0 || *pollingFrequency > 300 {
log.Fatal("polling-frequency must be between 1 and 300 seconds")
}
httpClient, err := getHTTPClient()
if err != nil {
log.Fatal(err)
}
client, err := livebox.NewClient(
adminPassword,
livebox.WithAddress(liveboxAddress),
livebox.WithHTTPClient(httpClient),
)
if err != nil {
log.Fatalf("Failed to create Livebox client: %v", err)
}
var (
ctx = context.Background()
registry = prometheus.NewRegistry()
pollers = poller.Pollers{
poller.NewInterfaceMbits(client),
}
)
interfaces, err := exporterLivebox.DiscoverInterfaces(ctx, client)
if err != nil {
log.Fatalf("Failed to discover Livebox interfaces: %s\n", err)
}
// Add experimental pollers.
pollers = append(pollers, parseExperimentalFlag(client, interfaces, *experimental, pollingFrequency)...)
registry.MustRegister(
append(
pollers.Collectors(),
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)...,
)
writeHeaderVec := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "promhttp_metric_handler_write_header_duration_seconds",
Help: "A histogram of time to first write latencies.",
Buckets: prometheus.DefBuckets,
},
[]string{"code"},
)
registry.MustRegister(
collector.NewDeviceInfo(client),
collector.NewDevices(client, interfaces),
collector.NewONT(client, interfaces),
writeHeaderVec,
)
go func() {
for {
if err := pollers.Poll(ctx); err != nil {
if isFatalError(err) {
log.Fatal(err)
}
log.Printf("WARN: polling failed: %s\n", err)
}
time.Sleep(time.Duration(*pollingFrequency) * time.Second)
}
}()
http.Handle("/metrics", promhttp.InstrumentHandlerTimeToWriteHeader(writeHeaderVec,
promhttp.InstrumentMetricHandler(
registry, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}),
)),
)
http.HandleFunc("/{$}", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(indexPage))
})
log.Printf("Listening on %s\n", *listen)
log.Fatal(http.ListenAndServe(*listen, nil))
}