From e6b7e5908112d61a209433a4c99915b98d4dbaf8 Mon Sep 17 00:00:00 2001 From: Hector Date: Mon, 30 Aug 2021 07:48:18 +0100 Subject: [PATCH] set the up metric to 0 if the socket connection fails --- src/exporter.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/exporter.go b/src/exporter.go index 007fb51..54adc6d 100644 --- a/src/exporter.go +++ b/src/exporter.go @@ -50,7 +50,7 @@ var ( []string{"type"}, nil, ) - metricServerPing = prometheus.NewDesc( + metricServerUp = prometheus.NewDesc( prometheus.BuildFQName(sockNamespace, "", "up"), "Check if the fail2ban server is up", nil, nil, @@ -98,7 +98,7 @@ func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { ch <- metricErrorCount } if e.socketPath != "" { - ch <- metricServerPing + ch <- metricServerUp ch <- metricJailCount ch <- metricJailFailedCurrent ch <- metricJailFailedTotal @@ -121,7 +121,9 @@ func (e *Exporter) Collect(ch chan<- prometheus.Metric) { log.Printf("error opening socket: %v", err) } else { defer s.Close() - e.collectServerPingMetric(ch, s) + } + e.collectServerUpMetric(ch, s) + if err == nil && s != nil { e.collectJailMetrics(ch, s) } } @@ -191,14 +193,16 @@ func (e *Exporter) collectEnabledJailMetrics(ch chan<- prometheus.Metric) { } } -func (e *Exporter) collectServerPingMetric(ch chan<- prometheus.Metric, s *socket.Fail2BanSocket) { - pingSuccess := s.Ping() - var pingSuccessInt float64 = 1 - if !pingSuccess { - pingSuccessInt = 0 +func (e *Exporter) collectServerUpMetric(ch chan<- prometheus.Metric, s *socket.Fail2BanSocket) { + var serverUp float64 = 0 + if s != nil { + pingSuccess := s.Ping() + if pingSuccess { + serverUp = 1 + } } ch <- prometheus.MustNewConstMetric( - metricServerPing, prometheus.GaugeValue, pingSuccessInt, + metricServerUp, prometheus.GaugeValue, serverUp, ) }