open-nomad/command/agent/metrics_endpoint.go
Michael Schurter 0a496c845e
Task API via Unix Domain Socket (#15864)
This change introduces the Task API: a portable way for tasks to access Nomad's HTTP API. This particular implementation uses a Unix Domain Socket and, unlike the agent's HTTP API, always requires authentication even if ACLs are disabled.

This PR contains the core feature and tests but followup work is required for the following TODO items:

- Docs - might do in a followup since dynamic node metadata / task api / workload id all need to interlink
- Unit tests for auth middleware
- Caching for auth middleware
- Rate limiting on negative lookups for auth middleware

---------

Co-authored-by: Seth Hoenig <shoenig@duck.com>
2023-02-06 11:31:22 -08:00

50 lines
1.4 KiB
Go

package agent
import (
"net/http"
"sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
// Only create the prometheus handler once
promHandler http.Handler
promOnce sync.Once
)
// 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) {
if req.Method != "GET" {
return nil, CodedError(405, ErrInvalidMethod)
}
if format := req.URL.Query().Get("format"); format == "prometheus" {
// Only return Prometheus formatted metrics if the user has enabled
// this functionality.
if !s.agent.GetConfig().Telemetry.PrometheusMetrics {
return nil, CodedError(http.StatusUnsupportedMediaType, "Prometheus is not enabled")
}
s.prometheusHandler().ServeHTTP(resp, req)
return nil, nil
}
return s.agent.GetMetricsSink().DisplayMetrics(resp, req)
}
func (s *HTTPServer) prometheusHandler() http.Handler {
promOnce.Do(func() {
handlerOptions := promhttp.HandlerOpts{
ErrorLog: s.logger.Named("prometheus_handler").StandardLogger(nil),
ErrorHandling: promhttp.ContinueOnError,
DisableCompression: true,
}
promHandler = promhttp.HandlerFor(prometheus.DefaultGatherer, handlerOptions)
})
return promHandler
}