db and socket paths are now optional

When running the exporter at least one path is required (db, or socket),
but not both.
When one of the paths is not provided, the metrics that correspond to that
source are not exporter. For example, if the database path is not set, the
database metrics will not be shown.
At least one path is required. Startup will fail if neither path provided.
This commit is contained in:
Hector 2021-08-29 12:21:44 +01:00
parent 172971a055
commit ef740512ca

View File

@ -64,21 +64,29 @@ type Exporter struct {
} }
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
if e.db != nil {
ch <- metricUp ch <- metricUp
ch <- metricBadIpsPerJail ch <- metricBadIpsPerJail
ch <- metricBannedIpsPerJail ch <- metricBannedIpsPerJail
ch <- metricEnabledJails ch <- metricEnabledJails
ch <- metricErrorCount ch <- metricErrorCount
}
if e.socket != nil {
ch <- metricServerPing ch <- metricServerPing
}
} }
func (e *Exporter) Collect(ch chan<- prometheus.Metric) { func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
if e.db != nil {
e.collectBadIpsPerJailMetrics(ch) e.collectBadIpsPerJailMetrics(ch)
e.collectBannedIpsPerJailMetrics(ch) e.collectBannedIpsPerJailMetrics(ch)
e.collectEnabledJailMetrics(ch) e.collectEnabledJailMetrics(ch)
e.collectUpMetric(ch) e.collectUpMetric(ch)
e.collectErrorCountMetric(ch) e.collectErrorCountMetric(ch)
}
if e.socket != nil {
e.collectServerPingMetric(ch) e.collectServerPingMetric(ch)
}
} }
func (e *Exporter) collectUpMetric(ch chan<- prometheus.Metric) { func (e *Exporter) collectUpMetric(ch chan<- prometheus.Metric) {
@ -168,9 +176,12 @@ func main() {
} else { } else {
log.Print("starting fail2ban exporter") log.Print("starting fail2ban exporter")
exporter := &Exporter{ exporter := &Exporter{}
db: fail2banDb.MustConnectToDb(appSettings.Fail2BanDbPath), if appSettings.Fail2BanDbPath != "" {
socket: socket.MustConnectToSocket(appSettings.Fail2BanSocketPath), exporter.db = fail2banDb.MustConnectToDb(appSettings.Fail2BanDbPath)
}
if appSettings.Fail2BanSocketPath != "" {
exporter.socket = socket.MustConnectToSocket(appSettings.Fail2BanSocketPath)
} }
prometheus.MustRegister(exporter) prometheus.MustRegister(exporter)