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