Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Prometheus URL label #2503

Merged
merged 9 commits into from
May 19, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions cmd/server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ func RunServeAdmin(cmd *cobra.Command, args []string) {
admin, _, adminmw, _ := setup(d, cmd)
cert := GetOrCreateTLSCertificate(cmd, d, config.AdminInterface) // we do not want to run this concurrently.

d.PrometheusManager().RegisterRouter(admin.Router)

var wg sync.WaitGroup
wg.Add(1)

Expand All @@ -118,6 +120,8 @@ func RunServePublic(cmd *cobra.Command, args []string) {
_, public, _, publicmw := setup(d, cmd)
cert := GetOrCreateTLSCertificate(cmd, d, config.PublicInterface) // we do not want to run this concurrently.

d.PrometheusManager().RegisterRouter(public.Router)

var wg sync.WaitGroup
wg.Add(1)

Expand All @@ -140,6 +144,9 @@ func RunServeAll(cmd *cobra.Command, args []string) {

admin, public, adminmw, publicmw := setup(d, cmd)

d.PrometheusManager().RegisterRouter(admin.Router)
d.PrometheusManager().RegisterRouter(public.Router)

var wg sync.WaitGroup
wg.Add(2)

Expand Down
46 changes: 45 additions & 1 deletion metrics/prometheus/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ package prometheus

import (
"net/http"
"strings"
"time"

"github.com/julienschmidt/httprouter"
)

type MetricsManager struct {
prometheusMetrics *Metrics
routers []*httprouter.Router
}

func NewMetricsManager(version, hash, buildTime string) *MetricsManager {
Expand All @@ -27,5 +31,45 @@ func (pmm *MetricsManager) ServeHTTP(rw http.ResponseWriter, r *http.Request, ne
start := time.Now()
next(rw, r)

pmm.prometheusMetrics.ResponseTime.WithLabelValues(r.URL.Path).Observe(time.Since(start).Seconds())
pmm.prometheusMetrics.ResponseTime.WithLabelValues(
pmm.getLabelForPath(r),
).Observe(time.Since(start).Seconds())
}

func (pmm *MetricsManager) RegisterRouter(router *httprouter.Router) {
pmm.routers = append(pmm.routers, router)
}

func (pmm *MetricsManager) getLabelForPath(r *http.Request) string {
// looking for a match in one of registered routers
for _, router := range pmm.routers {
handler, params, _ := router.Lookup(r.Method, r.URL.Path)
if handler != nil {
return reconstructEndpoint(r.URL.Path, params)
}
}
return "{unmatched}"
}

// To reduce cardinality of labels, values of matched path parameters must be replaced with {param}
func reconstructEndpoint(path string, params httprouter.Params) string {
// if map is empty, then nothing to change in the path
if len(params) == 0 {
return path
}

// construct a list of parameter values
paramValues := make(map[string]struct{}, len(params))
for _, param := range params {
paramValues[param.Value] = struct{}{}
}

parts := strings.Split(path, "/")
for index, part := range parts {
if _, ok := paramValues[part]; ok {
parts[index] = "{param}"
}
}

return strings.Join(parts, "/")
}
90 changes: 90 additions & 0 deletions metrics/prometheus/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package prometheus

import (
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

func EmptyHandle(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// do nothing
}

func TestMetricsManagerGetLabelForPath(t *testing.T) {
t.Run("case=no-router", func(t *testing.T) {
mm := NewMetricsManager("", "", "")
r := httptest.NewRequest("GET", "/test", strings.NewReader(""))
assert.Equal(t, "{unmatched}", mm.getLabelForPath(r))
})

t.Run("case=registered-routers-no-match", func(t *testing.T) {
router := httprouter.New()
mm := MetricsManager{}
mm.RegisterRouter(router)
r := httptest.NewRequest("GET", "/test", strings.NewReader(""))
assert.Equal(t, "{unmatched}", mm.getLabelForPath(r))
})

t.Run("case=registered-routers-match-no-params", func(t *testing.T) {
router := httprouter.New()
router.GET("/test", EmptyHandle)
mm := MetricsManager{}
mm.RegisterRouter(router)
r := httptest.NewRequest("GET", "/test", strings.NewReader(""))
assert.Equal(t, "/test", mm.getLabelForPath(r))
})

t.Run("case=registered-routers-match-with-param", func(t *testing.T) {
router := httprouter.New()
router.GET("/test/:id", EmptyHandle)
mm := MetricsManager{}
mm.RegisterRouter(router)
r := httptest.NewRequest("GET", "/test/randomId", strings.NewReader(""))
assert.Equal(t, "/test/{param}", mm.getLabelForPath(r))
})
}


func TestEndpointsReconstruction(t *testing.T) {
//c := internal.NewConfigurationWithDefaults()

t.Run("case=reconstruct-endpoint-no-params", func(t *testing.T) {
assert.Equal(t, "/test", reconstructEndpoint("/test", httprouter.Params{}))
})

t.Run("case=reconstruct-endpoint-one-param", func(t *testing.T) {
assert.Equal(t, "/test/{param}/test", reconstructEndpoint("/test/12345/test", httprouter.Params{httprouter.Param{
Key: "id",
Value: "12345",
}}))
})

t.Run("case=reconstruct-endpoint-multiple-param", func(t *testing.T) {
assert.Equal(t, "/test/{param}/{param}", reconstructEndpoint("/test/12345/abcdef", httprouter.Params{
httprouter.Param{
Key: "id",
Value: "12345",
},
httprouter.Param{
Key: "id2",
Value: "abcdef",
},
}))
})

// FIXME: parameter value in some caese can match with a static part of URL, which produces a wrong label.
// As of now, httprouter does not provide enough information in the context or in results of Lookup() call,
// so this issue can't be fixed.
t.Run("case=reconstruct-endpoint-param-matches-path-part", func(t *testing.T) {
assert.Equal(t, "/{param}/{param}", reconstructEndpoint("/test/test", httprouter.Params{
httprouter.Param{
Key: "id",
Value: "test",
},
}))
})
}