github.com/manicqin/nomad@v0.9.5/command/agent/metrics_endpoint.go (about)

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