-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
including a unit test to verify that the new `sandbox_promhttp_*` metrics are exposed on the `/metrics` endpoint Signed-off-by: Xavier Coulon <xcoulon@redhat.com>
- Loading branch information
Showing
7 changed files
with
225 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package middleware | ||
|
||
import ( | ||
"strconv" | ||
"time" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/prometheus/client_golang/prometheus" | ||
) | ||
|
||
// see https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp#example-InstrumentRoundTripperDuration | ||
|
||
func InstrumentRoundTripperInFlight(gauge prometheus.Gauge) gin.HandlerFunc { | ||
return func(c *gin.Context) { | ||
gauge.Inc() | ||
defer func() { | ||
gauge.Dec() | ||
}() | ||
c.Next() | ||
} | ||
} | ||
|
||
func InstrumentRoundTripperCounter(counter *prometheus.CounterVec) gin.HandlerFunc { | ||
return func(c *gin.Context) { | ||
defer func() { | ||
counter.With(prometheus.Labels{ | ||
"code": strconv.Itoa(c.Writer.Status()), | ||
"method": c.Request.Method, | ||
"path": c.Request.URL.Path, | ||
}).Inc() | ||
}() | ||
c.Next() | ||
} | ||
} | ||
|
||
func InstrumentRoundTripperDuration(histVec *prometheus.HistogramVec) gin.HandlerFunc { | ||
return func(c *gin.Context) { | ||
start := time.Now() | ||
defer func() { | ||
duration := time.Since(start) | ||
histVec.With(prometheus.Labels{ | ||
"code": strconv.Itoa(c.Writer.Status()), | ||
"method": c.Request.Method, | ||
"path": c.Request.URL.Path, | ||
}).Observe(float64(duration.Milliseconds())) | ||
}() | ||
c.Next() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
package middleware_test | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/codeready-toolchain/registration-service/pkg/configuration" | ||
"github.com/codeready-toolchain/registration-service/pkg/proxy" | ||
"github.com/codeready-toolchain/registration-service/pkg/server" | ||
"github.com/codeready-toolchain/registration-service/test" | ||
"github.com/codeready-toolchain/registration-service/test/fake" | ||
authsupport "github.com/codeready-toolchain/toolchain-common/pkg/test/auth" | ||
testconfig "github.com/codeready-toolchain/toolchain-common/pkg/test/config" | ||
|
||
prommodel "github.com/prometheus/client_model/go" | ||
promcommon "github.com/prometheus/common/expfmt" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"github.com/stretchr/testify/suite" | ||
) | ||
|
||
type PromHTTPMiddlewareSuite struct { | ||
test.UnitTestSuite | ||
} | ||
|
||
func TestPromHTTPMiddlewareSuite(t *testing.T) { | ||
suite.Run(t, &PromHTTPMiddlewareSuite{test.UnitTestSuite{}}) | ||
} | ||
|
||
func (s *PromHTTPMiddlewareSuite) TestPromHTTPMiddleware() { | ||
// given | ||
tokengenerator := authsupport.NewTokenManager() | ||
srv := server.New(fake.NewMockableApplication(nil)) | ||
keysEndpointURL := tokengenerator.NewKeyServer().URL | ||
s.SetConfig(testconfig.RegistrationService(). | ||
Environment(configuration.UnitTestsEnvironment). | ||
Auth().AuthClientPublicKeysURL(keysEndpointURL)) | ||
|
||
cfg := configuration.GetRegistrationServiceConfig() | ||
assert.Equal(s.T(), keysEndpointURL, cfg.Auth().AuthClientPublicKeysURL(), "key url not set correctly") | ||
err := srv.SetupRoutes(proxy.DefaultPort) | ||
require.NoError(s.T(), err) | ||
|
||
s.Run("call endpoint", func() { | ||
// making a call on an HTTP endpoint | ||
resp := httptest.NewRecorder() | ||
req, err := http.NewRequest(http.MethodGet, "/api/v1/segment-write-key", nil) | ||
require.NoError(s.T(), err) | ||
|
||
// when | ||
srv.Engine().ServeHTTP(resp, req) | ||
|
||
// then | ||
assert.Equal(s.T(), http.StatusOK, resp.Code, "request returned wrong status code") | ||
|
||
s.Run("check metrics", func() { | ||
// also, we should have some HTTP metrics | ||
|
||
resp = httptest.NewRecorder() | ||
req, err = http.NewRequest(http.MethodGet, "/metrics", nil) | ||
require.NoError(s.T(), err) | ||
|
||
// when | ||
srv.Engine().ServeHTTP(resp, req) | ||
|
||
// then | ||
assert.Equal(s.T(), http.StatusOK, resp.Code, "request returned wrong status code") | ||
require.NoError(s.T(), err) | ||
|
||
_, err := getMetric(resp.Body.Bytes(), "sandbox_promhttp_client_in_flight_requests", nil) | ||
assert.NoError(s.T(), err) | ||
|
||
_, err = getMetric(resp.Body.Bytes(), "sandbox_promhttp_client_api_requests_total", map[string]string{ | ||
"code": "200", | ||
"method": "GET", | ||
"path": "/api/v1/segment-write-key", | ||
}) | ||
assert.NoError(s.T(), err) | ||
|
||
_, err = getMetric(resp.Body.Bytes(), "sandbox_promhttp_request_duration_seconds", map[string]string{ | ||
"code": "200", | ||
"method": "GET", | ||
"path": "/api/v1/segment-write-key", | ||
}) | ||
assert.NoError(s.T(), err) | ||
}) | ||
}) | ||
} | ||
|
||
func getMetric(data []byte, name string, labels map[string]string) (*prommodel.Metric, error) { | ||
p := &promcommon.TextParser{} | ||
metrics, err := p.TextToMetricFamilies(bytes.NewReader(data)) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
metric, found := metrics[name] | ||
if !found { | ||
return nil, fmt.Errorf("unable to find metric '%s'", name) | ||
} | ||
for _, m := range metric.Metric { | ||
if matchesLabels(m.Label, labels) { | ||
return m, nil | ||
} | ||
} | ||
|
||
return nil, fmt.Errorf("unable to find metric '%s' with labels '%v'", name, labels) | ||
} | ||
|
||
func matchesLabels(x []*prommodel.LabelPair, y map[string]string) bool { | ||
if len(x) != len(y) { | ||
return false | ||
} | ||
for _, l := range x { | ||
if v, found := y[*l.Name]; !found || *l.Value != v { | ||
return false | ||
} | ||
} | ||
return true | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters