2023-07-08 18:45:01 +00:00
|
|
|
package metricsserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2023-07-09 04:13:31 +00:00
|
|
|
"golang.org/x/sync/errgroup"
|
2023-07-08 18:45:01 +00:00
|
|
|
|
|
|
|
"go.ntppool.org/common/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Metrics struct {
|
|
|
|
r *prometheus.Registry
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() *Metrics {
|
|
|
|
r := prometheus.NewRegistry()
|
|
|
|
|
|
|
|
m := &Metrics{
|
|
|
|
r: r,
|
|
|
|
}
|
|
|
|
|
|
|
|
return m
|
|
|
|
}
|
|
|
|
|
2023-08-06 19:34:56 +00:00
|
|
|
func (m *Metrics) Registry() *prometheus.Registry {
|
2023-07-08 18:45:01 +00:00
|
|
|
return m.r
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Metrics) Handler() http.Handler {
|
|
|
|
|
|
|
|
log := logger.NewStdLog("prom http", false, nil)
|
|
|
|
|
|
|
|
return promhttp.HandlerFor(m.r, promhttp.HandlerOpts{
|
|
|
|
ErrorLog: log,
|
|
|
|
Registry: m.r,
|
|
|
|
EnableOpenMetrics: true,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-07-09 04:13:31 +00:00
|
|
|
// ListenAndServe starts a goroutine with a server running on
|
|
|
|
// the specified port. The server will shutdown and return when
|
|
|
|
// the provided context is done
|
|
|
|
func (m *Metrics) ListenAndServe(ctx context.Context, port int) error {
|
2023-07-08 18:45:01 +00:00
|
|
|
|
|
|
|
log := logger.Setup()
|
|
|
|
|
|
|
|
srv := &http.Server{
|
|
|
|
Addr: ":" + strconv.Itoa(port),
|
|
|
|
ReadTimeout: 10 * time.Second,
|
|
|
|
WriteTimeout: 20 * time.Second,
|
|
|
|
IdleTimeout: 120 * time.Second,
|
|
|
|
Handler: m.Handler(),
|
|
|
|
}
|
|
|
|
|
2023-07-09 04:13:31 +00:00
|
|
|
g, ctx := errgroup.WithContext(ctx)
|
|
|
|
|
|
|
|
g.Go(func() error {
|
2023-07-08 18:45:01 +00:00
|
|
|
err := srv.ListenAndServe()
|
2023-07-09 04:13:31 +00:00
|
|
|
if err != nil && err != http.ErrServerClosed {
|
2023-07-08 18:45:01 +00:00
|
|
|
log.Warn("metrics server done listening", "err", err)
|
2023-07-09 04:13:31 +00:00
|
|
|
return err
|
2023-07-08 18:45:01 +00:00
|
|
|
}
|
2023-07-09 04:13:31 +00:00
|
|
|
return nil
|
|
|
|
})
|
2023-07-08 18:45:01 +00:00
|
|
|
|
|
|
|
<-ctx.Done()
|
|
|
|
|
|
|
|
if err := srv.Shutdown(ctx); err != nil {
|
|
|
|
log.Error("metrics server shutdown failed", "err", err)
|
2023-07-09 04:13:31 +00:00
|
|
|
return err
|
2023-07-08 18:45:01 +00:00
|
|
|
}
|
2023-07-09 04:13:31 +00:00
|
|
|
|
|
|
|
return g.Wait()
|
2023-07-08 18:45:01 +00:00
|
|
|
}
|