github.com/hernad/nomad@v1.6.112/command/agent/metrics_endpoint.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package agent
     5  
     6  import (
     7  	"net/http"
     8  	"sync"
     9  
    10  	"github.com/prometheus/client_golang/prometheus"
    11  	"github.com/prometheus/client_golang/prometheus/promhttp"
    12  )
    13  
    14  var (
    15  	// Only create the prometheus handler once
    16  	promHandler http.Handler
    17  	promOnce    sync.Once
    18  )
    19  
    20  // MetricsRequest returns metrics for the agent. Metrics are JSON by default
    21  // but Prometheus is an optional format.
    22  func (s *HTTPServer) MetricsRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
    23  	if req.Method != "GET" {
    24  		return nil, CodedError(405, ErrInvalidMethod)
    25  	}
    26  
    27  	if format := req.URL.Query().Get("format"); format == "prometheus" {
    28  
    29  		// Only return Prometheus formatted metrics if the user has enabled
    30  		// this functionality.
    31  		if !s.agent.GetConfig().Telemetry.PrometheusMetrics {
    32  			return nil, CodedError(http.StatusUnsupportedMediaType, "Prometheus is not enabled")
    33  		}
    34  		s.prometheusHandler().ServeHTTP(resp, req)
    35  		return nil, nil
    36  	}
    37  
    38  	return s.agent.GetMetricsSink().DisplayMetrics(resp, req)
    39  }
    40  
    41  func (s *HTTPServer) prometheusHandler() http.Handler {
    42  	promOnce.Do(func() {
    43  		handlerOptions := promhttp.HandlerOpts{
    44  			ErrorLog:           s.logger.Named("prometheus_handler").StandardLogger(nil),
    45  			ErrorHandling:      promhttp.ContinueOnError,
    46  			DisableCompression: true,
    47  		}
    48  
    49  		promHandler = promhttp.HandlerFor(prometheus.DefaultGatherer, handlerOptions)
    50  	})
    51  	return promHandler
    52  }