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
|
package collector
import (
"fmt"
"log/slog"
"strconv"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/tynany/frr_exporter/internal/frrsockets"
)
const (
metricNamespace = "frr"
enabledByDefault = true
disabledByDefault = false
)
var (
socketConn *frrsockets.Connection
frrTotalScrapeCount = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: metricNamespace,
Name: "scrapes_total",
Help: "Total number of times FRR has been scraped.",
})
frrLabels = []string{"collector"}
frrDesc = map[string]*prometheus.Desc{
"frrScrapeDuration": promDesc("scrape_duration_seconds", "Time it took for a collector's scrape to complete.", frrLabels),
"frrCollectorUp": promDesc("collector_up", "Whether the collector's last scrape was successful (1 = successful, 0 = unsuccessful).", frrLabels),
}
socketDirPath = kingpin.Flag("frr.socket.dir-path", "Path of of the localstatedir containing each daemon's Unix socket.").Default("/run/frr").String()
socketTimeout = kingpin.Flag("frr.socket.timeout", "Timeout when connecting to the FRR daemon Unix sockets").Default("20s").Duration()
factories = make(map[string]func(logger *slog.Logger) (Collector, error))
initiatedCollectorsMtx = sync.Mutex{}
initiatedCollectors = make(map[string]Collector)
collectorState = make(map[string]*bool)
)
func registerCollector(name string, enabledByDefaultStatus bool, factory func(logger *slog.Logger) (Collector, error)) {
defaultState := "disabled"
if enabledByDefaultStatus {
defaultState = "enabled"
}
help := fmt.Sprintf("Enable the %s collector (default: %s).", name, defaultState)
if enabledByDefaultStatus {
help = fmt.Sprintf("Enable the %s collector (default: %s, to disable use --no-collector.%s).", name, defaultState, name)
}
factories[name] = factory
collectorState[name] = kingpin.Flag(fmt.Sprintf("collector.%s", name), help).Default(strconv.FormatBool(enabledByDefaultStatus)).Bool()
}
// Collector is the interface a collector has to implement.
type Collector interface {
// Update metrics and sends to the Prometheus.Metric channel.
Update(ch chan<- prometheus.Metric) error
}
// Exporter collects all collector metrics, implemented as per the prometheus.Collector interface.
type Exporter struct {
Collectors map[string]Collector
logger *slog.Logger
}
// NewExporter returns a new Exporter.
func NewExporter(logger *slog.Logger) (*Exporter, error) {
collectors := make(map[string]Collector)
initiatedCollectorsMtx.Lock()
defer initiatedCollectorsMtx.Unlock()
socketConn = frrsockets.NewConnection(*socketDirPath, *socketTimeout)
for name, enabled := range collectorState {
if !*enabled {
continue
}
if collector, exists := initiatedCollectors[name]; exists {
collectors[name] = collector
} else {
collector, err := factories[name](logger.With("collector", name))
if err != nil {
return nil, err
}
collectors[name] = collector
initiatedCollectors[name] = collector
}
}
return &Exporter{
Collectors: collectors,
logger: logger,
}, nil
}
// Collect implemented as per the prometheus.Collector interface.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
frrTotalScrapeCount.Inc()
ch <- frrTotalScrapeCount
wg := &sync.WaitGroup{}
wg.Add(len(e.Collectors))
for name, collector := range e.Collectors {
go runCollector(ch, name, collector, wg, e.logger)
}
wg.Wait()
}
func runCollector(ch chan<- prometheus.Metric, name string, collector Collector, wg *sync.WaitGroup, logger *slog.Logger) {
defer wg.Done()
startTime := time.Now()
err := collector.Update(ch)
scrapeDurationSeconds := time.Since(startTime).Seconds()
ch <- prometheus.MustNewConstMetric(frrDesc["frrScrapeDuration"], prometheus.GaugeValue, float64(scrapeDurationSeconds), name)
success := 0.0
if err != nil {
logger.Error("collector scrape failed", "name", name, "duration_seconds", scrapeDurationSeconds, "err", err)
} else {
logger.Debug("collector succeeded", "name", name, "duration_seconds", scrapeDurationSeconds)
success = 1
}
ch <- prometheus.MustNewConstMetric(frrDesc["frrCollectorUp"], prometheus.GaugeValue, success, name)
}
// Describe implemented as per the prometheus.Collector interface.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, desc := range frrDesc {
ch <- desc
}
}
func promDesc(metricName string, metricDescription string, labels []string) *prometheus.Desc {
return prometheus.NewDesc(metricNamespace+"_"+metricName, metricDescription, labels, nil)
}
func colPromDesc(subsystem string, metricName string, metricDescription string, labels []string) *prometheus.Desc {
return prometheus.NewDesc(prometheus.BuildFQName(metricNamespace, subsystem, metricName), metricDescription, labels, nil)
}
func newGauge(ch chan<- prometheus.Metric, descName *prometheus.Desc, metric float64, labels ...string) {
ch <- prometheus.MustNewConstMetric(descName, prometheus.GaugeValue, metric, labels...)
}
func newCounter(ch chan<- prometheus.Metric, descName *prometheus.Desc, metric float64, labels ...string) {
ch <- prometheus.MustNewConstMetric(descName, prometheus.CounterValue, metric, labels...)
}
func cmdOutputProcessError(cmd, output string, err error) error {
return fmt.Errorf("cannot process output of %s: %w: command output: %s", cmd, err, output)
}
|