metrics: add a new router and listener for Prometheus' metrics endpoint

This commit is contained in:
Nico Rey 2022-02-21 12:50:15 -03:00
parent 602291df61
commit d5fd7a5c00

34
app.go
View file

@ -68,6 +68,7 @@ const (
type Config struct { type Config struct {
ServerURL string ServerURL string
Addr string Addr string
MetricsAddr string
GRPCAddr string GRPCAddr string
GRPCAllowInsecure bool GRPCAllowInsecure bool
EphemeralNodeInactivityTimeout time.Duration EphemeralNodeInactivityTimeout time.Duration
@ -406,11 +407,17 @@ func (h *Headscale) ensureUnixSocketIsAbsent() error {
return os.Remove(h.cfg.UnixSocket) return os.Remove(h.cfg.UnixSocket)
} }
func (h *Headscale) createRouter(grpcMux *runtime.ServeMux) *gin.Engine { func (h *Headscale) createPrometheusRouter() *gin.Engine {
router := gin.Default() promRouter := gin.Default()
prometheus := ginprometheus.NewPrometheus("gin") 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( router.GET(
"/health", "/health",
@ -622,6 +629,27 @@ func (h *Headscale) Serve() error {
log.Info(). log.Info().
Msgf("listening and serving HTTP on: %s", h.cfg.Addr) 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() return errorGroup.Wait()
} }