metrics.go42 lines, 1.3 KB
| 1 | // Package metrics is the one place in Murmur that knows about Prometheus. |
| 2 | package metrics |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/http/pprof" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/prometheus/client_golang/prometheus" |
| 12 | "github.com/prometheus/client_golang/prometheus/collectors" |
| 13 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 14 | ) |
| 15 | |
| 16 | // New returns a registry that already holds what the Go runtime and the |
| 17 | // operating system know about this process. |
| 18 | func New() *prometheus.Registry { |
| 19 | reg := prometheus.NewRegistry() |
| 20 | reg.MustRegister(collectors.NewGoCollector(), |
| 21 | collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) |
| 22 | return reg |
| 23 | } |
| 24 | |
| 25 | // Serve answers on a port of its own, away from the API's, until ctx is cancelled. |
| 26 | // Nothing on it is for clients, so the load balancer doesn't know this port. |
| 27 | func Serve(ctx context.Context, addr string, reg *prometheus.Registry, more func(*http.ServeMux)) error { |
| 28 | mux := http.NewServeMux() |
| 29 | more(mux) |
| 30 | mux.Handle("GET /metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) |
| 31 | mux.HandleFunc("GET /debug/pprof/", pprof.Index) |
| 32 | mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile) |
| 33 | srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second} |
| 34 | go func() { |
| 35 | <-ctx.Done() |
| 36 | srv.Close() |
| 37 | }() |
| 38 | if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { |
| 39 | return err |
| 40 | } |
| 41 | return nil |
| 42 | } |