2021-02-27 18:49:24 +01:00
|
|
|
// Package metrics implements a standalone HTTP server for serving pprof
|
|
|
|
// profiles and Prometheus metrics.
|
|
|
|
package metrics
|
2017-04-30 04:28:44 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-01-16 05:28:52 +01:00
|
|
|
"errors"
|
2017-04-30 04:28:44 +02:00
|
|
|
"net/http"
|
2021-02-27 18:49:24 +01:00
|
|
|
"net/http/pprof"
|
2017-04-30 04:28:44 +02:00
|
|
|
|
2020-05-01 01:29:51 +02:00
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2018-10-23 20:06:52 +02:00
|
|
|
|
2017-06-20 14:58:44 +02:00
|
|
|
"github.com/chihaya/chihaya/pkg/log"
|
2018-09-09 17:14:24 +02:00
|
|
|
"github.com/chihaya/chihaya/pkg/stop"
|
2017-04-30 04:28:44 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// Server represents a standalone HTTP server for serving a Prometheus metrics
|
|
|
|
// endpoint.
|
|
|
|
type Server struct {
|
|
|
|
srv *http.Server
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop shuts down the server.
|
2018-09-09 17:14:24 +02:00
|
|
|
func (s *Server) Stop() stop.Result {
|
|
|
|
c := make(stop.Channel)
|
2017-04-30 04:28:44 +02:00
|
|
|
go func() {
|
2018-09-09 17:14:24 +02:00
|
|
|
c.Done(s.srv.Shutdown(context.Background()))
|
2017-04-30 04:28:44 +02:00
|
|
|
}()
|
|
|
|
|
2018-09-09 17:14:24 +02:00
|
|
|
return c.Result()
|
2017-04-30 04:28:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewServer creates a new instance of a Prometheus server that asynchronously
|
|
|
|
// serves requests.
|
|
|
|
func NewServer(addr string) *Server {
|
2021-02-27 18:49:24 +01:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
|
|
|
mux.Handle("/metrics", promhttp.Handler())
|
|
|
|
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
|
|
|
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
|
|
|
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
|
|
|
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
|
|
|
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
|
|
|
|
2017-04-30 04:28:44 +02:00
|
|
|
s := &Server{
|
|
|
|
srv: &http.Server{
|
|
|
|
Addr: addr,
|
2021-02-27 18:49:24 +01:00
|
|
|
Handler: mux,
|
2017-04-30 04:28:44 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
2022-01-16 05:28:52 +01:00
|
|
|
if err := s.srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
|
2017-06-20 14:58:44 +02:00
|
|
|
log.Fatal("failed while serving prometheus", log.Err(err))
|
2017-04-30 04:28:44 +02:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|