diff --git a/internal/prometheus/prometheus.go b/internal/prometheus/prometheus.go index 8c6d4f7..5b83dfd 100644 --- a/internal/prometheus/prometheus.go +++ b/internal/prometheus/prometheus.go @@ -1,13 +1,27 @@ package prometheus import ( + "net/http" "strconv" "github.com/aceberg/WatchYourLAN/internal/models" + "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prometheus/client_golang/prometheus/promhttp" ) +func Handler(appConfig *models.Conf) func(c *gin.Context) { + h := promhttp.Handler() + return func(c *gin.Context) { + if !appConfig.PrometheusEnable { + c.AbortWithStatus(http.StatusNotFound) + return + } + h.ServeHTTP(c.Writer, c.Request) + } +} + var up *prometheus.GaugeVec func NewMetrics() { @@ -18,6 +32,10 @@ func NewMetrics() { }, []string{"ip", "iface", "name", "mac", "known"}) } +func RemoveMetrics() { + up = nil +} + // Add a Prometheus metric func Add(oneHist models.Host) { if up == nil { diff --git a/internal/web/config.go b/internal/web/config.go index 9cf8b0e..6684215 100644 --- a/internal/web/config.go +++ b/internal/web/config.go @@ -109,3 +109,15 @@ func saveInfluxHandler(c *gin.Context) { c.Redirect(http.StatusFound, "/config") } + +func savePrometheusHandler(c *gin.Context) { + enable := c.PostForm("enable") + + appConfig.PrometheusEnable = enable == "on" + + conf.Write(appConfig) + + slog.Info("Writing new config to " + appConfig.ConfPath) + + c.Redirect(http.StatusFound, "/config") +} diff --git a/internal/web/routines-upd.go b/internal/web/routines-upd.go index d06604f..7a015f7 100644 --- a/internal/web/routines-upd.go +++ b/internal/web/routines-upd.go @@ -21,6 +21,8 @@ func updateRoutines() { if appConfig.PrometheusEnable { prometheus.NewMetrics() + } else { + prometheus.RemoveMetrics() } quitScan = make(chan bool) diff --git a/internal/web/templates/config.html b/internal/web/templates/config.html index 1d001c0..b32631e 100644 --- a/internal/web/templates/config.html +++ b/internal/web/templates/config.html @@ -179,6 +179,33 @@ +