80 lines
2.1 KiB
Go
80 lines
2.1 KiB
Go
package PrometheusCollector
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"minie4.de/tplinkswitchexporter/TPLinkClient"
|
|
)
|
|
|
|
type TPLinkCollector struct {
|
|
client *TPLinkClient.TPLinkClient
|
|
portMetrics map[string](*prometheus.GaugeVec)
|
|
}
|
|
|
|
var portFields = []string{
|
|
"Enabled",
|
|
"LinkStatus",
|
|
"TxGoodPkt",
|
|
"TxBadPkt",
|
|
"RxGoodPkt",
|
|
"RxBadPkt",
|
|
}
|
|
|
|
func NewPrometheusCollector(client *TPLinkClient.TPLinkClient) *TPLinkCollector {
|
|
portMetrics := make(map[string](*prometheus.GaugeVec))
|
|
|
|
for _, field := range portFields {
|
|
portMetrics[field] = prometheus.NewGaugeVec(
|
|
prometheus.GaugeOpts{
|
|
Name: strings.ToLower(field),
|
|
Namespace: "tplinkexporter",
|
|
Subsystem: "portstats",
|
|
Help: fmt.Sprintf("Value of the '%s' metric from the TP-Link switch", field),
|
|
},
|
|
[]string{"portnum", "host", "mac", "name", "type"},
|
|
)
|
|
}
|
|
|
|
return &TPLinkCollector{
|
|
client: client,
|
|
portMetrics: portMetrics,
|
|
}
|
|
}
|
|
|
|
func (collector *TPLinkCollector) Collect(ch chan<- prometheus.Metric) {
|
|
info := collector.client.QueryInfo()
|
|
stats := collector.client.QueryStats()
|
|
|
|
addLabels := func(g *prometheus.GaugeVec, port TPLinkClient.StatsData) prometheus.Gauge {
|
|
return g.With(prometheus.Labels{
|
|
"portnum": strconv.Itoa(int(port.Port)),
|
|
"host": info.IPAddr,
|
|
"mac": info.Mac,
|
|
"name": info.Hostname,
|
|
"type": info.Type,
|
|
})
|
|
}
|
|
|
|
for _, port := range stats {
|
|
addLabels(collector.portMetrics["Enabled"], port).Set(map[bool]float64{true: 1, false: 0}[port.Enabled])
|
|
addLabels(collector.portMetrics["LinkStatus"], port).Set(float64(port.LinkStatus))
|
|
addLabels(collector.portMetrics["TxGoodPkt"], port).Set(float64(port.TxGoodPkt))
|
|
addLabels(collector.portMetrics["TxBadPkt"], port).Set(float64(port.TxBadPkt))
|
|
addLabels(collector.portMetrics["RxGoodPkt"], port).Set(float64(port.RxGoodPkt))
|
|
addLabels(collector.portMetrics["RxBadPkt"], port).Set(float64(port.RxBadPkt))
|
|
}
|
|
|
|
for _, metric := range collector.portMetrics {
|
|
metric.Collect(ch)
|
|
}
|
|
}
|
|
|
|
func (collector *TPLinkCollector) Describe(ch chan<- *prometheus.Desc) {
|
|
for _, field := range collector.portMetrics {
|
|
field.Describe(ch)
|
|
}
|
|
}
|