livebox-exporter/main.go

225 lines
5.3 KiB
Go
Raw Permalink Normal View History

2021-11-13 19:36:28 +01:00
package main
import (
"context"
2023-06-02 00:42:35 +02:00
"crypto/tls"
"crypto/x509"
2023-03-04 13:34:10 +01:00
"errors"
2021-11-13 19:36:28 +01:00
"flag"
2023-04-21 18:58:34 +02:00
"fmt"
2023-06-02 00:42:35 +02:00
"io/ioutil"
2021-11-13 19:36:28 +01:00
"log"
"net/http"
"os"
2023-04-21 18:58:34 +02:00
"strings"
2021-11-13 19:36:28 +01:00
"time"
"github.com/Tomy2e/livebox-api-client"
2023-05-23 20:55:05 +02:00
"github.com/Tomy2e/livebox-exporter/internal/collector"
2023-03-04 13:34:10 +01:00
"github.com/Tomy2e/livebox-exporter/internal/poller"
2023-04-21 18:58:34 +02:00
exporterLivebox "github.com/Tomy2e/livebox-exporter/pkg/livebox"
2021-11-13 19:36:28 +01:00
"github.com/prometheus/client_golang/prometheus"
2023-03-04 13:34:10 +01:00
"github.com/prometheus/client_golang/prometheus/collectors"
2021-11-13 19:36:28 +01:00
"github.com/prometheus/client_golang/prometheus/promhttp"
2023-04-21 18:58:34 +02:00
"golang.org/x/exp/slices"
2021-11-13 19:36:28 +01:00
)
const defaultPollingFrequency = 30
2023-04-21 18:58:34 +02:00
const (
ExperimentalMetricsInterfaceHomeLan = "livebox_interface_homelan"
ExperimentalMetricsInterfaceNetDev = "livebox_interface_netdev"
ExperimentalMetricsWAN = "livebox_wan"
)
var experimentalMetrics = []string{
ExperimentalMetricsInterfaceHomeLan,
ExperimentalMetricsInterfaceNetDev,
ExperimentalMetricsWAN,
}
func parseExperimentalFlag(
ctx context.Context,
2023-06-02 00:42:35 +02:00
client *livebox.Client,
2023-04-21 18:58:34 +02:00
experimental string,
pollingFrequency *uint,
) (pollers []poller.Poller) {
2023-06-02 00:42:35 +02:00
if experimental == "" {
return nil
}
2023-04-21 18:58:34 +02:00
var (
interfaces []*exporterLivebox.Interface
err error
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
}
// Discover interfaces for experimental pollers that require interfaces.
switch exp {
case ExperimentalMetricsInterfaceHomeLan, ExperimentalMetricsInterfaceNetDev:
if interfaces == nil {
interfaces, err = exporterLivebox.DiscoverInterfaces(ctx, client)
if err != nil {
log.Fatalf("Failed to discover Livebox interfaces: %s\n", err)
}
}
}
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
}
2023-06-02 00:42:35 +02:00
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 := ioutil.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.ErrInvalidPassword) {
return true
}
var certError *tls.CertificateVerificationError
if errors.As(err, &certError) {
return true
}
return false
}
2021-11-13 19:36:28 +01:00
func main() {
pollingFrequency := flag.Uint("polling-frequency", defaultPollingFrequency, "Polling frequency")
listen := flag.String("listen", ":8080", "Listening address")
2023-04-21 18:58:34 +02:00
experimental := flag.String("experimental", "", fmt.Sprintf(
"Comma separated list of experimental metrics to enable (available metrics: %s)",
strings.Join(experimentalMetrics, ","),
))
2021-11-13 19:36:28 +01:00
flag.Parse()
adminPassword := os.Getenv("ADMIN_PASSWORD")
if adminPassword == "" {
log.Fatal("ADMIN_PASSWORD environment variable must be set")
}
2023-06-02 00:42:35 +02:00
liveboxAddress := os.Getenv("LIVEBOX_ADDRESS")
if liveboxAddress == "" {
liveboxAddress = livebox.DefaultAddress
}
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)
}
2023-03-04 13:34:10 +01:00
var (
ctx = context.Background()
registry = prometheus.NewRegistry()
pollers = poller.Pollers{
poller.NewDevicesTotal(client),
poller.NewInterfaceMbits(client),
}
)
2023-04-21 18:58:34 +02:00
// Add experimental pollers.
pollers = append(pollers, parseExperimentalFlag(ctx, client, *experimental, pollingFrequency)...)
2023-03-04 13:34:10 +01:00
registry.MustRegister(
append(
pollers.Collectors(),
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)...,
)
2021-11-13 19:36:28 +01:00
2023-05-23 20:55:05 +02:00
registry.MustRegister(collector.NewDeviceInfo(client))
2021-11-13 19:36:28 +01:00
go func() {
for {
2023-03-04 13:34:10 +01:00
if err := pollers.Poll(ctx); err != nil {
if isFatalError(err) {
2023-03-04 13:34:10 +01:00
log.Fatal(err)
2021-11-13 19:36:28 +01:00
}
2023-03-04 13:34:10 +01:00
log.Printf("WARN: polling failed: %s\n", err)
2021-11-13 19:36:28 +01:00
}
time.Sleep(time.Duration(*pollingFrequency) * time.Second)
}
}()
2023-03-04 13:34:10 +01:00
http.Handle("/metrics", promhttp.InstrumentMetricHandler(
registry, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}),
))
2021-11-13 19:36:28 +01:00
log.Printf("Listening on %s\n", *listen)
log.Fatal(http.ListenAndServe(*listen, nil))
}