-
Notifications
You must be signed in to change notification settings - Fork 246
/
metrics.go
57 lines (49 loc) · 1.55 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package metrics
import (
"fmt"
"net/http"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/metrics"
gethprom "github.com/ethereum/go-ethereum/metrics/prometheus"
prom "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// 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()
mux.Handle("/health", healthHandler())
mux.Handle("/metrics", Handler(r))
p := Server{
server: &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
},
}
return &p
}
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)
}
})
}
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)
})
}
// Listen starts the HTTP server in the background.
func (p *Server) Listen() {
log.Info("metrics server stopped", "err", p.server.ListenAndServe())
}