2019-10-09 15:04:16 +00:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/log"
|
|
|
|
"github.com/ethereum/go-ethereum/metrics"
|
2019-10-22 17:32:05 +00:00
|
|
|
gethprom "github.com/ethereum/go-ethereum/metrics/prometheus"
|
|
|
|
|
|
|
|
prom "github.com/prometheus/client_golang/prometheus"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2019-10-09 15:04:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Server runs and controls a HTTP pprof interface.
|
|
|
|
type Server struct {
|
|
|
|
server *http.Server
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMetricsServer(port int, r metrics.Registry) *Server {
|
|
|
|
mux := http.NewServeMux()
|
2019-11-04 14:43:48 +00:00
|
|
|
mux.Handle("/health", healthHandler())
|
2019-10-22 17:32:05 +00:00
|
|
|
mux.Handle("/metrics", Handler(r))
|
2019-10-09 15:04:16 +00:00
|
|
|
p := Server{
|
|
|
|
server: &http.Server{
|
|
|
|
Addr: fmt.Sprintf(":%d", port),
|
|
|
|
Handler: mux,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
return &p
|
|
|
|
}
|
|
|
|
|
2019-11-04 14:43:48 +00:00
|
|
|
func healthHandler() http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
_, err := w.Write([]byte("OK"))
|
|
|
|
if err != nil {
|
|
|
|
log.Error("health handler error", "err", err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-10-22 17:32:05 +00:00
|
|
|
func Handler(reg metrics.Registry) http.Handler {
|
|
|
|
// we disable compression because geth doesn't support it
|
|
|
|
opts := promhttp.HandlerOpts{DisableCompression: true}
|
|
|
|
// we are combining handlers to avoid having 2 endpoints
|
|
|
|
statusMetrics := promhttp.HandlerFor(prom.DefaultGatherer, opts) // our metrics
|
|
|
|
gethMetrics := gethprom.Handler(reg) // geth metrics
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
statusMetrics.ServeHTTP(w, r)
|
|
|
|
gethMetrics.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-10-09 15:04:16 +00:00
|
|
|
// Listen starts the HTTP server in the background.
|
|
|
|
func (p *Server) Listen() {
|
|
|
|
log.Info("metrics server stopped", "err", p.server.ListenAndServe())
|
|
|
|
}
|