2020-10-18 18:16:02 +02:00
|
|
|
package metric
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/goharbor/harbor/src/core/config"
|
2020-11-05 08:14:53 +01:00
|
|
|
"github.com/goharbor/harbor/src/lib"
|
2020-10-18 18:16:02 +02:00
|
|
|
"github.com/goharbor/harbor/src/lib/metric"
|
|
|
|
)
|
|
|
|
|
|
|
|
func instrumentHandler(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2020-11-05 08:14:53 +01:00
|
|
|
now, url := time.Now(), r.URL.EscapedPath()
|
2020-10-18 18:16:02 +02:00
|
|
|
|
|
|
|
metric.TotalInFlightGauge.WithLabelValues(url).Inc()
|
|
|
|
defer metric.TotalInFlightGauge.WithLabelValues(url).Dec()
|
2020-11-05 08:14:53 +01:00
|
|
|
rc := lib.NewResponseRecorder(w)
|
|
|
|
next.ServeHTTP(rc, r)
|
2020-10-18 18:16:02 +02:00
|
|
|
metric.TotalReqDurSummary.WithLabelValues(r.Method, url).Observe(time.Since(now).Seconds())
|
2020-11-05 08:14:53 +01:00
|
|
|
metric.TotalReqCnt.WithLabelValues(r.Method, strconv.Itoa(rc.StatusCode), url).Inc()
|
2020-10-18 18:16:02 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Middleware returns a middleware for handling requests
|
|
|
|
func Middleware() func(http.Handler) http.Handler {
|
|
|
|
if config.Metric().Enabled {
|
2020-12-01 10:12:19 +01:00
|
|
|
return instrumentHandler
|
2020-10-18 18:16:02 +02:00
|
|
|
}
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
|
|
|
next.ServeHTTP(rw, req)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|