| 1 |
package ginprometheus |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"io/ioutil" |
| 6 |
"net/http" |
| 7 |
"os" |
| 8 |
"strconv" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/gin-gonic/gin" |
| 12 |
"github.com/prometheus/client_golang/prometheus" |
| 13 |
"github.com/prometheus/client_golang/prometheus/promhttp" |
| 14 |
log "github.com/sirupsen/logrus" |
| 15 |
) |
| 16 |
|
| 17 |
var defaultMetricPath = "/metrics" |
| 18 |
|
| 19 |
// Standard default metrics |
| 20 |
// counter, counter_vec, gauge, gauge_vec, |
| 21 |
// histogram, histogram_vec, summary, summary_vec |
| 22 |
var reqCnt = &Metric{ |
| 23 |
ID: "reqCnt", |
| 24 |
Name: "requests_total", |
| 25 |
Description: "How many HTTP requests processed, partitioned by status code and HTTP method.", |
| 26 |
Type: "counter_vec", |
| 27 |
Args: []string{"code", "method", "handler", "host", "url"}} |
| 28 |
|
| 29 |
var reqDur = &Metric{ |
| 30 |
ID: "reqDur", |
| 31 |
Name: "request_duration_seconds", |
| 32 |
Description: "The HTTP request latencies in seconds.", |
| 33 |
Type: "summary"} |
| 34 |
|
| 35 |
var resSz = &Metric{ |
| 36 |
ID: "resSz", |
| 37 |
Name: "response_size_bytes", |
| 38 |
Description: "The HTTP response sizes in bytes.", |
| 39 |
Type: "summary"} |
| 40 |
|
| 41 |
var reqSz = &Metric{ |
| 42 |
ID: "reqSz", |
| 43 |
Name: "request_size_bytes", |
| 44 |
Description: "The HTTP request sizes in bytes.", |
| 45 |
Type: "summary"} |
| 46 |
|
| 47 |
var standardMetrics = []*Metric{ |
| 48 |
reqCnt, |
| 49 |
reqDur, |
| 50 |
resSz, |
| 51 |
reqSz, |
| 52 |
} |
| 53 |
|
| 54 |
/* |
| 55 |
RequestCounterURLLabelMappingFn is a function which can be supplied to the middleware to control |
| 56 |
the cardinality of the request counter's "url" label, which might be required in some contexts. |
| 57 |
For instance, if for a "/customer/:name" route you don't want to generate a time series for every |
| 58 |
possible customer name, you could use this function: |
| 59 |
|
| 60 |
func(c *gin.Context) string { |
| 61 |
url := c.Request.URL.Path |
| 62 |
for _, p := range c.Params { |
| 63 |
if p.Key == "name" { |
| 64 |
url = strings.Replace(url, p.Value, ":name", 1) |
| 65 |
break |
| 66 |
} |
| 67 |
} |
| 68 |
return url |
| 69 |
} |
| 70 |
|
| 71 |
which would map "/customer/alice" and "/customer/bob" to their template "/customer/:name". |
| 72 |
*/ |
| 73 |
type RequestCounterURLLabelMappingFn func(c *gin.Context) string |
| 74 |
|
| 75 |
// Metric is a definition for the name, description, type, ID, and |
| 76 |
// prometheus.Collector type (i.e. CounterVec, Summary, etc) of each metric |
| 77 |
type Metric struct { |
| 78 |
MetricCollector prometheus.Collector |
| 79 |
ID string |
| 80 |
Name string |
| 81 |
Description string |
| 82 |
Type string |
| 83 |
Args []string |
| 84 |
} |
| 85 |
|
| 86 |
// Prometheus contains the metrics gathered by the instance and its path |
| 87 |
type Prometheus struct { |
| 88 |
reqCnt *prometheus.CounterVec |
| 89 |
reqDur, reqSz, resSz prometheus.Summary |
| 90 |
router *gin.Engine |
| 91 |
listenAddress string |
| 92 |
Ppg PrometheusPushGateway |
| 93 |
|
| 94 |
MetricsList []*Metric |
| 95 |
MetricsPath string |
| 96 |
|
| 97 |
ReqCntURLLabelMappingFn RequestCounterURLLabelMappingFn |
| 98 |
|
| 99 |
// gin.Context string to use as a prometheus URL label |
| 100 |
URLLabelFromContext string |
| 101 |
} |
| 102 |
|
| 103 |
// PrometheusPushGateway contains the configuration for pushing to a Prometheus pushgateway (optional) |
| 104 |
type PrometheusPushGateway struct { |
| 105 |
|
| 106 |
// Push interval in seconds |
| 107 |
PushIntervalSeconds time.Duration |
| 108 |
|
| 109 |
// Push Gateway URL in format http://domain:port |
| 110 |
// where JOBNAME can be any string of your choice |
| 111 |
PushGatewayURL string |
| 112 |
|
| 113 |
// Local metrics URL where metrics are fetched from, this could be ommited in the future |
| 114 |
// if implemented using prometheus common/expfmt instead |
| 115 |
MetricsURL string |
| 116 |
|
| 117 |
// pushgateway job name, defaults to "gin" |
| 118 |
Job string |
| 119 |
} |
| 120 |
|
| 121 |
// NewPrometheus generates a new set of metrics with a certain subsystem name |
| 122 |
func NewPrometheus(subsystem string, customMetricsList ...[]*Metric) *Prometheus { |
| 123 |
|
| 124 |
var metricsList []*Metric |
| 125 |
|
| 126 |
if len(customMetricsList) > 1 { |
| 127 |
panic("Too many args. NewPrometheus( string, <optional []*Metric> ).") |
| 128 |
} else if len(customMetricsList) == 1 { |
| 129 |
metricsList = customMetricsList[0] |
| 130 |
} |
| 131 |
|
| 132 |
for _, metric := range standardMetrics { |
| 133 |
metricsList = append(metricsList, metric) |
| 134 |
} |
| 135 |
|
| 136 |
p := &Prometheus{ |
| 137 |
MetricsList: metricsList, |
| 138 |
MetricsPath: defaultMetricPath, |
| 139 |
ReqCntURLLabelMappingFn: func(c *gin.Context) string { |
| 140 |
return c.Request.URL.Path // i.e. by default do nothing, i.e. return URL as is |
| 141 |
}, |
| 142 |
} |
| 143 |
|
| 144 |
p.registerMetrics(subsystem) |
| 145 |
|
| 146 |
return p |
| 147 |
} |
| 148 |
|
| 149 |
// SetPushGateway sends metrics to a remote pushgateway exposed on pushGatewayURL |
| 150 |
// every pushIntervalSeconds. Metrics are fetched from metricsURL |
| 151 |
func (p *Prometheus) SetPushGateway(pushGatewayURL, metricsURL string, pushIntervalSeconds time.Duration) { |
| 152 |
p.Ppg.PushGatewayURL = pushGatewayURL |
| 153 |
p.Ppg.MetricsURL = metricsURL |
| 154 |
p.Ppg.PushIntervalSeconds = pushIntervalSeconds |
| 155 |
p.startPushTicker() |
| 156 |
} |
| 157 |
|
| 158 |
// SetPushGatewayJob job name, defaults to "gin" |
| 159 |
func (p *Prometheus) SetPushGatewayJob(j string) { |
| 160 |
p.Ppg.Job = j |
| 161 |
} |
| 162 |
|
| 163 |
// SetListenAddress for exposing metrics on address. If not set, it will be exposed at the |
| 164 |
// same address of the gin engine that is being used |
| 165 |
func (p *Prometheus) SetListenAddress(address string) { |
| 166 |
p.listenAddress = address |
| 167 |
if p.listenAddress != "" { |
| 168 |
p.router = gin.Default() |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
// SetListenAddressWithRouter for using a separate router to expose metrics. (this keeps things like GET /metrics out of |
| 173 |
// your content's access log). |
| 174 |
func (p *Prometheus) SetListenAddressWithRouter(listenAddress string, r *gin.Engine) { |
| 175 |
p.listenAddress = listenAddress |
| 176 |
if len(p.listenAddress) > 0 { |
| 177 |
p.router = r |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
// SetMetricsPath set metrics paths |
| 182 |
func (p *Prometheus) SetMetricsPath(e *gin.Engine) { |
| 183 |
|
| 184 |
if p.listenAddress != "" { |
| 185 |
p.router.GET(p.MetricsPath, prometheusHandler()) |
| 186 |
p.runServer() |
| 187 |
} else { |
| 188 |
e.GET(p.MetricsPath, prometheusHandler()) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
// SetMetricsPathWithAuth set metrics paths with authentication |
| 193 |
func (p *Prometheus) SetMetricsPathWithAuth(e *gin.Engine, accounts gin.Accounts) { |
| 194 |
|
| 195 |
if p.listenAddress != "" { |
| 196 |
p.router.GET(p.MetricsPath, gin.BasicAuth(accounts), prometheusHandler()) |
| 197 |
p.runServer() |
| 198 |
} else { |
| 199 |
e.GET(p.MetricsPath, gin.BasicAuth(accounts), prometheusHandler()) |
| 200 |
} |
| 201 |
|
| 202 |
} |
| 203 |
|
| 204 |
func (p *Prometheus) runServer() { |
| 205 |
if p.listenAddress != "" { |
| 206 |
go p.router.Run(p.listenAddress) |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
func (p *Prometheus) getMetrics() []byte { |
| 211 |
response, _ := http.Get(p.Ppg.MetricsURL) |
| 212 |
|
| 213 |
defer response.Body.Close() |
| 214 |
body, _ := ioutil.ReadAll(response.Body) |
| 215 |
|
| 216 |
return body |
| 217 |
} |
| 218 |
|
| 219 |
func (p *Prometheus) getPushGatewayURL() string { |
| 220 |
h, _ := os.Hostname() |
| 221 |
if p.Ppg.Job == "" { |
| 222 |
p.Ppg.Job = "gin" |
| 223 |
} |
| 224 |
return p.Ppg.PushGatewayURL + "/metrics/job/" + p.Ppg.Job + "/instance/" + h |
| 225 |
} |
| 226 |
|
| 227 |
func (p *Prometheus) sendMetricsToPushGateway(metrics []byte) { |
| 228 |
req, err := http.NewRequest("POST", p.getPushGatewayURL(), bytes.NewBuffer(metrics)) |
| 229 |
client := &http.Client{} |
| 230 |
if _, err = client.Do(req); err != nil { |
| 231 |
log.WithError(err).Errorln("Error sending to push gateway") |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
func (p *Prometheus) startPushTicker() { |
| 236 |
ticker := time.NewTicker(time.Second * p.Ppg.PushIntervalSeconds) |
| 237 |
go func() { |
| 238 |
for range ticker.C { |
| 239 |
p.sendMetricsToPushGateway(p.getMetrics()) |
| 240 |
} |
| 241 |
}() |
| 242 |
} |
| 243 |
|
| 244 |
// NewMetric associates prometheus.Collector based on Metric.Type |
| 245 |
func NewMetric(m *Metric, subsystem string) prometheus.Collector { |
| 246 |
var metric prometheus.Collector |
| 247 |
switch m.Type { |
| 248 |
case "counter_vec": |
| 249 |
metric = prometheus.NewCounterVec( |
| 250 |
prometheus.CounterOpts{ |
| 251 |
Subsystem: subsystem, |
| 252 |
Name: m.Name, |
| 253 |
Help: m.Description, |
| 254 |
}, |
| 255 |
m.Args, |
| 256 |
) |
| 257 |
case "counter": |
| 258 |
metric = prometheus.NewCounter( |
| 259 |
prometheus.CounterOpts{ |
| 260 |
Subsystem: subsystem, |
| 261 |
Name: m.Name, |
| 262 |
Help: m.Description, |
| 263 |
}, |
| 264 |
) |
| 265 |
case "gauge_vec": |
| 266 |
metric = prometheus.NewGaugeVec( |
| 267 |
prometheus.GaugeOpts{ |
| 268 |
Subsystem: subsystem, |
| 269 |
Name: m.Name, |
| 270 |
Help: m.Description, |
| 271 |
}, |
| 272 |
m.Args, |
| 273 |
) |
| 274 |
case "gauge": |
| 275 |
metric = prometheus.NewGauge( |
| 276 |
prometheus.GaugeOpts{ |
| 277 |
Subsystem: subsystem, |
| 278 |
Name: m.Name, |
| 279 |
Help: m.Description, |
| 280 |
}, |
| 281 |
) |
| 282 |
case "histogram_vec": |
| 283 |
metric = prometheus.NewHistogramVec( |
| 284 |
prometheus.HistogramOpts{ |
| 285 |
Subsystem: subsystem, |
| 286 |
Name: m.Name, |
| 287 |
Help: m.Description, |
| 288 |
}, |
| 289 |
m.Args, |
| 290 |
) |
| 291 |
case "histogram": |
| 292 |
metric = prometheus.NewHistogram( |
| 293 |
prometheus.HistogramOpts{ |
| 294 |
Subsystem: subsystem, |
| 295 |
Name: m.Name, |
| 296 |
Help: m.Description, |
| 297 |
}, |
| 298 |
) |
| 299 |
case "summary_vec": |
| 300 |
metric = prometheus.NewSummaryVec( |
| 301 |
prometheus.SummaryOpts{ |
| 302 |
Subsystem: subsystem, |
| 303 |
Name: m.Name, |
| 304 |
Help: m.Description, |
| 305 |
}, |
| 306 |
m.Args, |
| 307 |
) |
| 308 |
case "summary": |
| 309 |
metric = prometheus.NewSummary( |
| 310 |
prometheus.SummaryOpts{ |
| 311 |
Subsystem: subsystem, |
| 312 |
Name: m.Name, |
| 313 |
Help: m.Description, |
| 314 |
}, |
| 315 |
) |
| 316 |
} |
| 317 |
return metric |
| 318 |
} |
| 319 |
|
| 320 |
func (p *Prometheus) registerMetrics(subsystem string) { |
| 321 |
|
| 322 |
for _, metricDef := range p.MetricsList { |
| 323 |
metric := NewMetric(metricDef, subsystem) |
| 324 |
if err := prometheus.Register(metric); err != nil { |
| 325 |
log.WithError(err).Errorf("%s could not be registered in Prometheus", metricDef.Name) |
| 326 |
} |
| 327 |
switch metricDef { |
| 328 |
case reqCnt: |
| 329 |
p.reqCnt = metric.(*prometheus.CounterVec) |
| 330 |
case reqDur: |
| 331 |
p.reqDur = metric.(prometheus.Summary) |
| 332 |
case resSz: |
| 333 |
p.resSz = metric.(prometheus.Summary) |
| 334 |
case reqSz: |
| 335 |
p.reqSz = metric.(prometheus.Summary) |
| 336 |
} |
| 337 |
metricDef.MetricCollector = metric |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
// Use adds the middleware to a gin engine. |
| 342 |
func (p *Prometheus) Use(e *gin.Engine) { |
| 343 |
e.Use(p.HandlerFunc()) |
| 344 |
p.SetMetricsPath(e) |
| 345 |
} |
| 346 |
|
| 347 |
// UseWithAuth adds the middleware to a gin engine with BasicAuth. |
| 348 |
func (p *Prometheus) UseWithAuth(e *gin.Engine, accounts gin.Accounts) { |
| 349 |
e.Use(p.HandlerFunc()) |
| 350 |
p.SetMetricsPathWithAuth(e, accounts) |
| 351 |
} |
| 352 |
|
| 353 |
// HandlerFunc defines handler function for middleware |
| 354 |
func (p *Prometheus) HandlerFunc() gin.HandlerFunc { |
| 355 |
return func(c *gin.Context) { |
| 356 |
if c.Request.URL.Path == p.MetricsPath { |
| 357 |
c.Next() |
| 358 |
return |
| 359 |
} |
| 360 |
|
| 361 |
start := time.Now() |
| 362 |
reqSz := computeApproximateRequestSize(c.Request) |
| 363 |
|
| 364 |
c.Next() |
| 365 |
|
| 366 |
status := strconv.Itoa(c.Writer.Status()) |
| 367 |
elapsed := float64(time.Since(start)) / float64(time.Second) |
| 368 |
resSz := float64(c.Writer.Size()) |
| 369 |
|
| 370 |
p.reqDur.Observe(elapsed) |
| 371 |
url := p.ReqCntURLLabelMappingFn(c) |
| 372 |
// jlambert Oct 2018 - sidecar specific mod |
| 373 |
if len(p.URLLabelFromContext) > 0 { |
| 374 |
u, found := c.Get(p.URLLabelFromContext) |
| 375 |
if !found { |
| 376 |
u = "unknown" |
| 377 |
} |
| 378 |
url = u.(string) |
| 379 |
} |
| 380 |
p.reqCnt.WithLabelValues(status, c.Request.Method, c.HandlerName(), c.Request.Host, url).Inc() |
| 381 |
p.reqSz.Observe(float64(reqSz)) |
| 382 |
p.resSz.Observe(resSz) |
| 383 |
} |
| 384 |
} |
| 385 |
|
| 386 |
func prometheusHandler() gin.HandlerFunc { |
| 387 |
h := promhttp.Handler() |
| 388 |
return func(c *gin.Context) { |
| 389 |
h.ServeHTTP(c.Writer, c.Request) |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
// From https://github.com/DanielHeckrath/gin-prometheus/blob/master/gin_prometheus.go |
| 394 |
func computeApproximateRequestSize(r *http.Request) int { |
| 395 |
s := 0 |
| 396 |
if r.URL != nil { |
| 397 |
s = len(r.URL.Path) |
| 398 |
} |
| 399 |
|
| 400 |
s += len(r.Method) |
| 401 |
s += len(r.Proto) |
| 402 |
for name, values := range r.Header { |
| 403 |
s += len(name) |
| 404 |
for _, value := range values { |
| 405 |
s += len(value) |
| 406 |
} |
| 407 |
} |
| 408 |
s += len(r.Host) |
| 409 |
|
| 410 |
// N.B. r.Form and r.MultipartForm are assumed to be included in r.URL. |
| 411 |
|
| 412 |
if r.ContentLength != -1 { |
| 413 |
s += int(r.ContentLength) |
| 414 |
} |
| 415 |
return s |
| 416 |
} |