fail2ban-prometheus-exporter/src/exporter.go
Hector 6e575aa0fd feat: rewrite cli flags and environment variables
Replace existing CLI flags to make them more consistent and follow a more
standard format.
Remove CLI flags and environment variables that are no longer relevant.
Add short `-v` option for version flag.
Update README with new documentation.

BREAKING CHANGE: Replace `--socket` flag with `--collector.f2b.socket`.
BREAKING CHANGE: Merge `--port` flag and `--web.listen-address` into a single flag.
BREAKING CHANGE: Remove `--collector.textfile` flag, its value is now derived from `--collector.textfile.directory`.
BREAKING CHANGE: Remove `F2B_COLLECTOR_TEXT` and `F2B_WEB_PORT` environment variables.
2022-02-19 17:01:49 +00:00

87 lines
2.2 KiB
Go

package main
import (
"fail2ban-prometheus-exporter/auth"
"fail2ban-prometheus-exporter/cfg"
"fail2ban-prometheus-exporter/collector/f2b"
"fail2ban-prometheus-exporter/collector/textfile"
"fmt"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
metricsPath = "/metrics"
)
var (
version = "dev"
commit = "none"
date = "unknown"
builtBy = "unknown"
)
func printAppVersion() {
fmt.Println(version)
fmt.Printf(" build date: %s\r\n commit hash: %s\r\n built by: %s\r\n", date, commit, builtBy)
}
func rootHtmlHandler(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(
`<html>
<head><title>Fail2Ban Exporter</title></head>
<body>
<h1>Fail2Ban Exporter</h1>
<p><a href="` + metricsPath + `">Metrics</a></p>
</body>
</html>`))
if err != nil {
log.Printf("error handling root url: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
func metricHandler(w http.ResponseWriter, r *http.Request, collector *textfile.Collector) {
promhttp.Handler().ServeHTTP(w, r)
collector.WriteTextFileMetrics(w, r)
}
func main() {
appSettings := cfg.Parse()
if appSettings.VersionMode {
printAppVersion()
} else {
log.Printf("fail2ban exporter version %s", version)
log.Printf("starting server at %s", appSettings.MetricsAddress)
f2bCollector := f2b.NewExporter(appSettings, version)
prometheus.MustRegister(f2bCollector)
textFileCollector := textfile.NewCollector(appSettings)
prometheus.MustRegister(textFileCollector)
http.HandleFunc("/", auth.BasicAuthMiddleware(rootHtmlHandler, appSettings.BasicAuthProvider))
http.HandleFunc(metricsPath, auth.BasicAuthMiddleware(
func(w http.ResponseWriter, r *http.Request) {
metricHandler(w, r, textFileCollector)
},
appSettings.BasicAuthProvider,
))
log.Printf("metrics available at '%s'", metricsPath)
if appSettings.BasicAuthProvider.Enabled() {
log.Printf("basic auth enabled")
}
svrErr := make(chan error)
go func() {
svrErr <- http.ListenAndServe(appSettings.MetricsAddress, nil)
}()
log.Print("ready")
err := <-svrErr
log.Print(err)
}
}