livebox-exporter/internal/poller/interface.go

95 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-03-04 13:34:10 +01:00
package poller
import (
"context"
"fmt"
"github.com/Tomy2e/livebox-api-client"
"github.com/Tomy2e/livebox-api-client/api/request"
2023-03-18 18:56:02 +01:00
"github.com/Tomy2e/livebox-exporter/pkg/bitrate"
2023-03-04 13:34:10 +01:00
"github.com/prometheus/client_golang/prometheus"
)
var _ Poller = &InterfaceMbits{}
// InterfaceMbits allows to poll the current bandwidth usage on the Livebox
// interfaces.
type InterfaceMbits struct {
2023-03-18 18:56:02 +01:00
client livebox.Client
txMbits, rxMbits *prometheus.GaugeVec
2023-03-04 13:34:10 +01:00
}
// NewInterfaceMbits returns a new InterfaceMbits poller.
func NewInterfaceMbits(client livebox.Client) *InterfaceMbits {
return &InterfaceMbits{
client: client,
txMbits: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "livebox_interface_tx_mbits",
Help: "Transmitted Mbits per second.",
}, []string{
// Name of the interface.
"interface",
}),
rxMbits: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "livebox_interface_rx_mbits",
Help: "Received Mbits per second.",
}, []string{
// Name of the interface.
"interface",
}),
}
}
// Collectors returns all metrics.
func (im *InterfaceMbits) Collectors() []prometheus.Collector {
2023-03-18 18:56:02 +01:00
return []prometheus.Collector{im.txMbits, im.rxMbits}
2023-03-04 13:34:10 +01:00
}
2023-03-18 18:56:02 +01:00
// Poll polls the current bandwidth usage.
func (im *InterfaceMbits) Poll(ctx context.Context) error {
var counters struct {
Status map[string]struct {
Traffic []struct {
Timestamp int `json:"Timestamp"`
RxCounter int `json:"Rx_Counter"`
TxCounter int `json:"Tx_Counter"`
} `json:"Traffic"`
2023-03-04 13:34:10 +01:00
} `json:"status"`
}
2023-03-18 18:56:02 +01:00
// Request latest rx/tx counters.
2023-03-04 13:34:10 +01:00
if err := im.client.Request(
ctx,
2023-03-18 18:56:02 +01:00
request.New(
"HomeLan",
"getResults",
map[string]interface{}{
"Seconds": 0,
"NumberOfReadings": 1,
},
),
&counters,
2023-03-04 13:34:10 +01:00
); err != nil {
2023-03-18 18:56:02 +01:00
return fmt.Errorf("failed to get interfaces: %w", err)
}
2023-03-18 18:56:02 +01:00
for iface, traffic := range counters.Status {
rxCounter := 0
txCounter := 0
2023-03-04 13:34:10 +01:00
2023-03-18 18:56:02 +01:00
if len(traffic.Traffic) > 0 {
rxCounter = traffic.Traffic[0].RxCounter
txCounter = traffic.Traffic[0].TxCounter
2023-03-04 13:34:10 +01:00
}
2023-03-18 18:56:02 +01:00
im.rxMbits.
With(prometheus.Labels{"interface": iface}).
Set(bitrate.BitsPer30SecsToMbits(rxCounter))
im.txMbits.
With(prometheus.Labels{"interface": iface}).
Set(bitrate.BitsPer30SecsToMbits(txCounter))
2023-03-04 13:34:10 +01:00
}
return nil
}