open-nomad/command/agent/metrics_endpoint.go

44 lines
1.1 KiB
Go
Raw Normal View History

package agent
import (
"net/http"
2018-09-13 17:43:40 +00:00
"sync"
2017-09-10 14:43:36 +00:00
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
2018-09-13 17:43:40 +00:00
var (
// Only create the prometheus handler once
promHandler http.Handler
promOnce sync.Once
)
2017-09-11 16:10:09 +00:00
// MetricsRequest returns metrics for the agent. Metrics are JSON by default
// but Prometheus is an optional format.
func (s *HTTPServer) MetricsRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
2017-09-10 14:43:36 +00:00
if req.Method != "GET" {
return nil, CodedError(405, ErrInvalidMethod)
}
2017-09-10 14:43:36 +00:00
if format := req.URL.Query().Get("format"); format == "prometheus" {
2018-09-13 17:43:40 +00:00
s.prometheusHandler().ServeHTTP(resp, req)
return nil, nil
}
return s.agent.InmemSink.DisplayMetrics(resp, req)
}
func (s *HTTPServer) prometheusHandler() http.Handler {
promOnce.Do(func() {
2017-09-10 14:43:36 +00:00
handlerOptions := promhttp.HandlerOpts{
2018-09-13 17:43:40 +00:00
ErrorLog: s.logger.Named("prometheus_handler").StandardLogger(nil),
2017-09-10 14:43:36 +00:00
ErrorHandling: promhttp.ContinueOnError,
DisableCompression: true,
}
2018-09-13 17:43:40 +00:00
promHandler = promhttp.HandlerFor(prometheus.DefaultGatherer, handlerOptions)
})
return promHandler
}