2017-09-04 03:50:05 +00:00
|
|
|
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"
|
2017-09-04 03:50:05 +00:00
|
|
|
)
|
|
|
|
|
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.
|
2017-09-04 03:50:05 +00:00
|
|
|
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-04 03:50:05 +00:00
|
|
|
}
|
2017-09-10 14:43:36 +00:00
|
|
|
|
|
|
|
if format := req.URL.Query().Get("format"); format == "prometheus" {
|
2021-03-09 14:28:58 +00:00
|
|
|
|
|
|
|
// Only return Prometheus formatted metrics if the user has enabled
|
|
|
|
// this functionality.
|
2023-02-06 19:31:22 +00:00
|
|
|
if !s.agent.GetConfig().Telemetry.PrometheusMetrics {
|
2021-03-09 14:28:58 +00:00
|
|
|
return nil, CodedError(http.StatusUnsupportedMediaType, "Prometheus is not enabled")
|
|
|
|
}
|
2018-09-13 17:43:40 +00:00
|
|
|
s.prometheusHandler().ServeHTTP(resp, req)
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2023-02-06 19:31:22 +00:00
|
|
|
return s.agent.GetMetricsSink().DisplayMetrics(resp, req)
|
2018-09-13 17:43:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2017-09-04 03:50:05 +00:00
|
|
|
}
|