From d5fd7a5c001111a99e496018ceb1c509f7806189 Mon Sep 17 00:00:00 2001 From: Nico Rey Date: Mon, 21 Feb 2022 12:50:15 -0300 Subject: [PATCH] metrics: add a new router and listener for Prometheus' metrics endpoint --- app.go | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/app.go b/app.go index ac350ec..4f910f0 100644 --- a/app.go +++ b/app.go @@ -68,6 +68,7 @@ const ( type Config struct { ServerURL string Addr string + MetricsAddr string GRPCAddr string GRPCAllowInsecure bool EphemeralNodeInactivityTimeout time.Duration @@ -406,11 +407,17 @@ func (h *Headscale) ensureUnixSocketIsAbsent() error { return os.Remove(h.cfg.UnixSocket) } -func (h *Headscale) createRouter(grpcMux *runtime.ServeMux) *gin.Engine { - router := gin.Default() +func (h *Headscale) createPrometheusRouter() *gin.Engine { + promRouter := gin.Default() prometheus := ginprometheus.NewPrometheus("gin") - prometheus.Use(router) + prometheus.Use(promRouter) + + return promRouter +} + +func (h *Headscale) createRouter(grpcMux *runtime.ServeMux) *gin.Engine { + router := gin.Default() router.GET( "/health", @@ -622,6 +629,27 @@ func (h *Headscale) Serve() error { log.Info(). Msgf("listening and serving HTTP on: %s", h.cfg.Addr) + promRouter := h.createPrometheusRouter() + + promHttpServer := &http.Server{ + Addr: h.cfg.MetricsAddr, + Handler: promRouter, + ReadTimeout: HTTPReadTimeout, + WriteTimeout: 0, + } + + var promHttpListener net.Listener + promHttpListener, err = net.Listen("tcp", h.cfg.MetricsAddr) + + if err != nil { + return fmt.Errorf("failed to bind to TCP address: %w", err) + } + + errorGroup.Go(func() error { return promHttpServer.Serve(promHttpListener) }) + + log.Info(). + Msgf("listening and serving metrics on: %s", h.cfg.MetricsAddr) + return errorGroup.Wait() }