From 5640c6e406aa31124dbae821fd073ca10be13412 Mon Sep 17 00:00:00 2001 From: Kanika Rana <46766610+ranakan19@users.noreply.github.com> Date: Tue, 17 Oct 2023 10:49:59 -0400 Subject: [PATCH] move proxy metrics to a separate server (#352) * move metrics to a new server * remove metricController * rename metrics service * refactor test * remove public variables, use struct for metrics * lint error fix * remove leftover comment --------- Co-authored-by: Matous Jobanek Co-authored-by: Francisc Munteanu Co-authored-by: Alexey Kazakov --- build/Dockerfile | 2 +- cmd/main.go | 9 ++-- deploy/registration-service.yaml | 19 ++++++++ pkg/metrics/metrics.go | 67 ++++++++++++++------------ pkg/metrics/metrics_test.go | 45 +++++++++++++---- pkg/proxy/handlers/metrics.go | 20 -------- pkg/proxy/handlers/metrics_test.go | 37 -------------- pkg/proxy/handlers/spacelister.go | 14 +++--- pkg/proxy/handlers/spacelister_test.go | 8 +++ pkg/proxy/proxy.go | 21 ++++---- pkg/proxy/proxy_test.go | 38 ++++++++------- 11 files changed, 142 insertions(+), 138 deletions(-) delete mode 100644 pkg/proxy/handlers/metrics.go delete mode 100644 pkg/proxy/handlers/metrics_test.go diff --git a/build/Dockerfile b/build/Dockerfile index 193d75e4..91bbb90a 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -16,6 +16,6 @@ COPY build/_output/bin/registration-service ${REG_SERVICE} ENTRYPOINT ["/usr/local/bin/registration-service"] -EXPOSE 8080 8081 +EXPOSE 8080 8081 8082 USER ${USER_UID} diff --git a/cmd/main.go b/cmd/main.go index 4bbc3919..f48b8c72 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "github.com/codeready-toolchain/registration-service/pkg/metrics" + "github.com/prometheus/client_golang/prometheus" "net/http" "os" "os/signal" @@ -98,10 +99,12 @@ func main() { } // Register metrics - metrics.RegisterCustomMetrics() + proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) + // Start metrics server + metricsSrv := proxyMetrics.StartMetricsServer() // Start the proxy server - p, err := proxy.NewProxy(app) + p, err := proxy.NewProxy(app, proxyMetrics) if err != nil { panic(errs.Wrap(err, "failed to create proxy")) } @@ -141,7 +144,7 @@ func main() { } }() - gracefulShutdown(configuration.GracefulTimeout, srv.HTTPServer(), proxySrv) + gracefulShutdown(configuration.GracefulTimeout, srv.HTTPServer(), proxySrv, metricsSrv) } func gracefulShutdown(timeout time.Duration, hs ...*http.Server) { diff --git a/deploy/registration-service.yaml b/deploy/registration-service.yaml index 53e49f9e..c1e9d25c 100644 --- a/deploy/registration-service.yaml +++ b/deploy/registration-service.yaml @@ -98,6 +98,7 @@ objects: ports: - containerPort: 8080 - containerPort: 8081 + - containerPort: 8082 command: - registration-service imagePullPolicy: IfNotPresent @@ -214,6 +215,24 @@ objects: tls: termination: edge wildcardPolicy: None + - kind: Service + apiVersion: v1 + metadata: + name: proxy-metrics-service + namespace: ${NAMESPACE} + labels: + provider: codeready-toolchain + run: registration-service + spec: + ports: + - name: "8082" + protocol: TCP + port: 80 + targetPort: 8082 + selector: + run: registration-service + type: ClusterIP + sessionAffinity: null parameters: - name: NAMESPACE value: 'toolchain-host-operator' diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index ef4e32b2..fbd4e80f 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -1,48 +1,45 @@ package metrics import ( + "errors" + "github.com/labstack/echo/v4" + glog "github.com/labstack/gommon/log" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "net/http" logf "sigs.k8s.io/controller-runtime/pkg/log" ) var log = logf.Log.WithName("registration_metrics") -var Reg *prometheus.Registry const ( MetricLabelRejected = "Rejected" MetricsLabelVerbGet = "Get" MetricsLabelVerbList = "List" + MetricsPort = "8082" ) -// histogram with labels -var ( +type ProxyMetrics struct { // RegServProxyAPIHistogramVec measures the time taken by proxy before forwarding the request RegServProxyAPIHistogramVec *prometheus.HistogramVec // RegServWorkspaceHistogramVec measures the response time for either response or error from proxy when there is no routing RegServWorkspaceHistogramVec *prometheus.HistogramVec -) - -// collections -var ( - allHistogramVecs = []*prometheus.HistogramVec{} -) + Reg *prometheus.Registry +} const metricsPrefix = "sandbox_" -func init() { - initMetrics() -} -func initMetrics() { - log.Info("initializing custom metrics") - RegServProxyAPIHistogramVec = newHistogramVec("proxy_api_http_request_time", "time taken by proxy to route to a target cluster", "status_code", "route_to") - RegServWorkspaceHistogramVec = newHistogramVec("proxy_workspace_http_request_time", "time for response of a request to proxy ", "status_code", "kube_verb") - log.Info("custom metrics initialized") -} - -// Reset resets all metrics. For testing purpose only! -func Reset() { - log.Info("resetting custom metrics") - initMetrics() +func NewProxyMetrics(reg *prometheus.Registry) *ProxyMetrics { + regServProxyAPIHistogramVec := newHistogramVec("proxy_api_http_request_time", "time taken by proxy to route to a target cluster", "status_code", "route_to") + regServWorkspaceHistogramVec := newHistogramVec("proxy_workspace_http_request_time", "time for response of a request to proxy ", "status_code", "kube_verb") + metrics := &ProxyMetrics{ + RegServWorkspaceHistogramVec: regServWorkspaceHistogramVec, + RegServProxyAPIHistogramVec: regServProxyAPIHistogramVec, + Reg: reg, + } + metrics.Reg.MustRegister(metrics.RegServProxyAPIHistogramVec) + metrics.Reg.MustRegister(metrics.RegServWorkspaceHistogramVec) + return metrics } func newHistogramVec(name, help string, labels ...string) *prometheus.HistogramVec { @@ -51,16 +48,22 @@ func newHistogramVec(name, help string, labels ...string) *prometheus.HistogramV Help: help, Buckets: []float64{0.05, 0.1, 0.25, 0.5, 1, 5, 10}, }, labels) - allHistogramVecs = append(allHistogramVecs, v) return v } -// RegisterCustomMetrics registers the custom metrics -func RegisterCustomMetrics() { - Reg = prometheus.NewRegistry() - // register metrics - for _, v := range allHistogramVecs { - Reg.MustRegister(v) - } - log.Info("custom metrics registered") +func (p *ProxyMetrics) StartMetricsServer() *http.Server { + // start server + srv := echo.New() + srv.Logger.SetLevel(glog.INFO) + srv.GET("/metrics", echo.WrapHandler(promhttp.HandlerFor(p.Reg, promhttp.HandlerOpts{DisableCompression: true, Registry: p.Reg}))) + + log.Info("Starting the Registration-Service Metrics server...") + // listen concurrently to allow for graceful shutdown + go func() { + if err := srv.Start(":" + MetricsPort); !errors.Is(err, http.ErrServerClosed) { + log.Error(err, err.Error()) + } + }() + + return srv.Server } diff --git a/pkg/metrics/metrics_test.go b/pkg/metrics/metrics_test.go index 8a24efb8..57ed71e9 100644 --- a/pkg/metrics/metrics_test.go +++ b/pkg/metrics/metrics_test.go @@ -1,10 +1,13 @@ package metrics import ( + "bytes" + "github.com/prometheus/client_golang/prometheus" promtestutil "github.com/prometheus/client_golang/prometheus/testutil" clientmodel "github.com/prometheus/client_model/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "net/http" "strings" "testing" "time" @@ -12,9 +15,10 @@ import ( func TestHistogramVec(t *testing.T) { // given + reg := prometheus.NewRegistry() m := newHistogramVec("test_histogram_vec", "test histogram description", "status_code", "kube_verb") getSuccess, getFailure, listSuccess, listFailure := getExpectedLabelPairs() - RegisterCustomMetrics() + reg.MustRegister(m) // when m.WithLabelValues("200", "get").Observe((5 * time.Second).Seconds()) @@ -28,7 +32,7 @@ func TestHistogramVec(t *testing.T) { err := promtestutil.CollectAndCompare(m, strings.NewReader(expectedResponseMetadata+expectedResponse), "sandbox_test_histogram_vec") require.NoError(t, err) - g, er := Reg.Gather() + g, er := reg.Gather() require.NoError(t, er) require.Equal(t, 1, len(g)) require.Equal(t, "sandbox_test_histogram_vec", g[0].GetName()) @@ -51,17 +55,33 @@ func TestHistogramVec(t *testing.T) { require.Equal(t, 2, len(g[0].Metric[3].Label)) compareLabelPairValues(t, listFailure, g[0].GetMetric()[3].GetLabel()) require.Equal(t, uint64(2), *g[0].Metric[3].Histogram.SampleCount) + } -func TestRegisterCustomMetrics(t *testing.T) { - // when - RegisterCustomMetrics() +func TestMetricsServer(t *testing.T) { + reg := prometheus.NewRegistry() + testMetrics := NewProxyMetrics(reg) + server := testMetrics.StartMetricsServer() + require.NotNil(t, server) + defer func() { + _ = server.Close() + }() + + req, err := http.NewRequest("GET", "http://localhost:8082/metrics", nil) + require.NoError(t, err) + require.NotNil(t, req) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + require.NotNil(t, resp) + require.Equal(t, http.StatusOK, resp.StatusCode) + require.Equal(t, "text/plain; version=0.0.4; charset=utf-8", resp.Header.Get("Content-Type")) + // compare the body of the response as well + defer resp.Body.Close() + buf := new(bytes.Buffer) + _, err = buf.ReadFrom(resp.Body) + require.NoError(t, err) + assert.Equal(t, expectedServerBlankResponse, buf.String()) - // then - // verify all metrics were registered successfully - for _, m := range allHistogramVecs { - assert.True(t, Reg.Unregister(m)) - } } var expectedResponseMetadata = ` @@ -109,6 +129,11 @@ var expectedResponse = ` sandbox_test_histogram_vec_sum{kube_verb="list",status_code="500"} 3.001 sandbox_test_histogram_vec_count{kube_verb="list",status_code="500"} 2 ` +var expectedServerBlankResponse = `# HELP promhttp_metric_handler_errors_total Total number of internal errors encountered by the promhttp metric handler. +# TYPE promhttp_metric_handler_errors_total counter +promhttp_metric_handler_errors_total{cause="encoding"} 0 +promhttp_metric_handler_errors_total{cause="gathering"} 0 +` func compareLabelPairValues(t *testing.T, expected []clientmodel.LabelPair, labelPairs []*clientmodel.LabelPair) { for i := range labelPairs { diff --git a/pkg/proxy/handlers/metrics.go b/pkg/proxy/handlers/metrics.go deleted file mode 100644 index 5ee1b8aa..00000000 --- a/pkg/proxy/handlers/metrics.go +++ /dev/null @@ -1,20 +0,0 @@ -package handlers - -import ( - "github.com/codeready-toolchain/registration-service/pkg/metrics" - "github.com/labstack/echo/v4" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -type Metrics struct{} - -func NewMetrics() *Metrics { - return &Metrics{} -} - -//nolint:unparam -func (m *Metrics) PrometheusHandler(ctx echo.Context) error { - h := promhttp.HandlerFor(metrics.Reg, promhttp.HandlerOpts{DisableCompression: true, Registry: metrics.Reg}) - h.ServeHTTP(ctx.Response().Writer, ctx.Request()) - return nil -} diff --git a/pkg/proxy/handlers/metrics_test.go b/pkg/proxy/handlers/metrics_test.go deleted file mode 100644 index 7003ac4b..00000000 --- a/pkg/proxy/handlers/metrics_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package handlers - -import ( - "github.com/codeready-toolchain/registration-service/pkg/metrics" - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/require" - "net/http" - "net/http/httptest" - "testing" -) - -func TestMetricsHandler(t *testing.T) { - // Create a request to pass to our handler. We don't have any query parameters, so we'll - // pass 'nil' as the third parameter. - req, err := http.NewRequest(http.MethodGet, "/metrics", nil) - require.NoError(t, err) - - // Create handler instance. - metricsCtrl := NewMetrics() - metrics.RegisterCustomMetrics() - - t.Run("valid metrics json", func(t *testing.T) { - // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. - e := echo.New() - rec := httptest.NewRecorder() - ctx := e.NewContext(req, rec) - - //when - err := metricsCtrl.PrometheusHandler(ctx) - require.NoError(t, err) - // then - // check the status code is what we expect. - require.Equal(t, http.StatusOK, rec.Code) - // check response content-type. - require.Equal(t, "text/plain; version=0.0.4; charset=utf-8", rec.Header().Get("Content-Type")) - }) -} diff --git a/pkg/proxy/handlers/spacelister.go b/pkg/proxy/handlers/spacelister.go index 80d05c0d..5496d252 100644 --- a/pkg/proxy/handlers/spacelister.go +++ b/pkg/proxy/handlers/spacelister.go @@ -40,12 +40,14 @@ const ( type SpaceLister struct { GetSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupCompleted bool) (*signup.Signup, error) GetInformerServiceFunc func() service.InformerService + ProxyMetrics *metrics.ProxyMetrics } -func NewSpaceLister(app application.Application) *SpaceLister { +func NewSpaceLister(app application.Application, proxyMetrics *metrics.ProxyMetrics) *SpaceLister { return &SpaceLister{ GetSignupFunc: app.SignupService().GetSignupFromInformer, GetInformerServiceFunc: app.InformerService, + ProxyMetrics: proxyMetrics, } } @@ -54,10 +56,10 @@ func (s *SpaceLister) HandleSpaceListRequest(ctx echo.Context) error { requestReceivedTime := ctx.Get(context.RequestReceivedTime).(time.Time) workspaces, err := s.ListUserWorkspaces(ctx) if err != nil { - metrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusInternalServerError), metrics.MetricsLabelVerbList).Observe(time.Since(requestReceivedTime).Seconds()) // using list as the default value for verb to minimize label combinations for prometheus to process + s.ProxyMetrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusInternalServerError), metrics.MetricsLabelVerbList).Observe(time.Since(requestReceivedTime).Seconds()) // using list as the default value for verb to minimize label combinations for prometheus to process return errorResponse(ctx, apierrors.NewInternalError(err)) } - metrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusOK), metrics.MetricsLabelVerbList).Observe(time.Since(requestReceivedTime).Seconds()) + s.ProxyMetrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusOK), metrics.MetricsLabelVerbList).Observe(time.Since(requestReceivedTime).Seconds()) return listWorkspaceResponse(ctx, workspaces) } @@ -66,16 +68,16 @@ func (s *SpaceLister) HandleSpaceGetRequest(ctx echo.Context) error { requestReceivedTime := ctx.Get(context.RequestReceivedTime).(time.Time) workspace, err := s.GetUserWorkspace(ctx) if err != nil { - metrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusInternalServerError), metrics.MetricsLabelVerbGet).Observe(time.Since(requestReceivedTime).Seconds()) // using list as the default value for verb to minimize label combinations for prometheus to process + s.ProxyMetrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusInternalServerError), metrics.MetricsLabelVerbGet).Observe(time.Since(requestReceivedTime).Seconds()) // using list as the default value for verb to minimize label combinations for prometheus to process return errorResponse(ctx, apierrors.NewInternalError(err)) } if workspace == nil { // not found - metrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusNotFound), metrics.MetricsLabelVerbGet).Observe(time.Since(requestReceivedTime).Seconds()) + s.ProxyMetrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusNotFound), metrics.MetricsLabelVerbGet).Observe(time.Since(requestReceivedTime).Seconds()) r := schema.GroupResource{Group: "toolchain.dev.openshift.com", Resource: "workspaces"} return errorResponse(ctx, apierrors.NewNotFound(r, ctx.Param("workspace"))) } - metrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusOK), metrics.MetricsLabelVerbGet).Observe(time.Since(requestReceivedTime).Seconds()) + s.ProxyMetrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusOK), metrics.MetricsLabelVerbGet).Observe(time.Since(requestReceivedTime).Seconds()) return getWorkspaceResponse(ctx, workspace) } diff --git a/pkg/proxy/handlers/spacelister_test.go b/pkg/proxy/handlers/spacelister_test.go index ca345f5f..d7125301 100644 --- a/pkg/proxy/handlers/spacelister_test.go +++ b/pkg/proxy/handlers/spacelister_test.go @@ -3,6 +3,8 @@ package handlers_test import ( "context" "fmt" + "github.com/codeready-toolchain/registration-service/pkg/metrics" + "github.com/prometheus/client_golang/prometheus" "net/http" "net/http/httptest" "strings" @@ -177,9 +179,12 @@ func TestSpaceLister(t *testing.T) { informerFunc = tc.overrideInformerFunc } + proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) + s := &handlers.SpaceLister{ GetSignupFunc: signupProvider, GetInformerServiceFunc: informerFunc, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -498,9 +503,12 @@ func TestSpaceLister(t *testing.T) { informerFunc = tc.overrideInformerFunc } + proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) + s := &handlers.SpaceLister{ GetSignupFunc: signupProvider, GetInformerServiceFunc: informerFunc, + ProxyMetrics: proxyMetrics, } e := echo.New() diff --git a/pkg/proxy/proxy.go b/pkg/proxy/proxy.go index 62da7707..1461d710 100644 --- a/pkg/proxy/proxy.go +++ b/pkg/proxy/proxy.go @@ -45,8 +45,7 @@ const ( bearerProtocolPrefix = "base64url.bearer.authorization.k8s.io." //nolint:gosec proxyHealthEndpoint = "/proxyhealth" - - pluginsEndpoint = "/plugins/" + pluginsEndpoint = "/plugins/" ) type Proxy struct { @@ -54,18 +53,18 @@ type Proxy struct { cl client.Client tokenParser *auth.TokenParser spaceLister *handlers.SpaceLister - metrics *handlers.Metrics + metrics *metrics.ProxyMetrics } -func NewProxy(app application.Application) (*Proxy, error) { +func NewProxy(app application.Application, proxyMetrics *metrics.ProxyMetrics) (*Proxy, error) { cl, err := newClusterClient() if err != nil { return nil, err } - return newProxyWithClusterClient(app, cl) + return newProxyWithClusterClient(app, cl, proxyMetrics) } -func newProxyWithClusterClient(app application.Application, cln client.Client) (*Proxy, error) { +func newProxyWithClusterClient(app application.Application, cln client.Client, proxyMetrics *metrics.ProxyMetrics) (*Proxy, error) { // Initiate toolchain cluster cache service cacheLog := controllerlog.Log.WithName("registration-service") cluster.NewToolchainClusterService(cln, cacheLog, configuration.Namespace(), 5*time.Second) @@ -76,14 +75,13 @@ func newProxyWithClusterClient(app application.Application, cln client.Client) ( } // init handlers - spaceLister := handlers.NewSpaceLister(app) - metrics := handlers.NewMetrics() + spaceLister := handlers.NewSpaceLister(app, proxyMetrics) return &Proxy{ app: app, cl: cln, tokenParser: tokenParser, spaceLister: spaceLister, - metrics: metrics, + metrics: proxyMetrics, }, nil } @@ -132,7 +130,6 @@ func (p *Proxy) StartProxy() *http.Server { wg.GET("/:workspace", p.spaceLister.HandleSpaceGetRequest) wg.GET("", p.spaceLister.HandleSpaceListRequest) router.GET(proxyHealthEndpoint, p.health) - router.GET("/metrics", p.metrics.PrometheusHandler) router.Any("/*", p.handleRequestAndRedirect) // Insert the CORS preflight middleware @@ -188,12 +185,12 @@ func (p *Proxy) handleRequestAndRedirect(ctx echo.Context) error { requestReceivedTime := ctx.Get(context.RequestReceivedTime).(time.Time) proxyPluginName, cluster, err := p.processRequest(ctx) if err != nil { - metrics.RegServProxyAPIHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusNotAcceptable), metrics.MetricLabelRejected).Observe(time.Since(requestReceivedTime).Seconds()) + p.metrics.RegServProxyAPIHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusNotAcceptable), metrics.MetricLabelRejected).Observe(time.Since(requestReceivedTime).Seconds()) return err } reverseProxy := p.newReverseProxy(ctx, cluster, len(proxyPluginName) > 0) routeTime := time.Since(requestReceivedTime) - metrics.RegServProxyAPIHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusAccepted), cluster.APIURL().Host).Observe(routeTime.Seconds()) + p.metrics.RegServProxyAPIHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusAccepted), cluster.APIURL().Host).Observe(routeTime.Seconds()) // Note that ServeHttp is non-blocking and uses a go routine under the hood reverseProxy.ServeHTTP(ctx.Response().Writer, ctx.Request()) return nil diff --git a/pkg/proxy/proxy_test.go b/pkg/proxy/proxy_test.go index f20bee06..e64bcaff 100644 --- a/pkg/proxy/proxy_test.go +++ b/pkg/proxy/proxy_test.go @@ -7,6 +7,8 @@ import ( "encoding/base64" "errors" "fmt" + "github.com/codeready-toolchain/registration-service/pkg/metrics" + "github.com/prometheus/client_golang/prometheus" "io" "log" "net/http" @@ -69,7 +71,8 @@ func (s *TestProxySuite) TestProxy() { s.SetConfig(testconfig.RegistrationService(). Environment(string(environment))) fakeApp := &fake.ProxyFakeApp{} - p, err := newProxyWithClusterClient(fakeApp, nil) + proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) + p, err := newProxyWithClusterClient(fakeApp, nil, proxyMetrics) require.NoError(s.T(), err) server := p.StartProxy() @@ -120,21 +123,6 @@ func (s *TestProxySuite) TestProxy() { s.assertResponseBody(resp, `{"alive": true}`) }) - s.Run("check metrics not ok", func() { - req, err := http.NewRequest("GET", "http://localhost:8081/metrics", nil) - require.NoError(s.T(), err) - require.NotNil(s.T(), req) - - // when - resp, err := http.DefaultClient.Do(req) - - // then - require.NoError(s.T(), err) - require.NotNil(s.T(), resp) - defer resp.Body.Close() - assert.Equal(s.T(), 401, resp.StatusCode) - }) - s.Run("plain http error", func() { s.Run("unauthorized if no token present", func() { req, err := http.NewRequest("GET", "http://localhost:8081/api/mycoolworkspace/pods", nil) @@ -219,6 +207,22 @@ func (s *TestProxySuite) TestProxy() { assert.Equal(s.T(), http.StatusInternalServerError, resp.StatusCode) s.assertResponseBody(resp, "unable to get target cluster: some-error") }) + + s.Run("internal error if accessing incorrect url", func() { + // given + req := s.request() + req.URL.Path = "http://localhost:8081/metrics" + require.NotNil(s.T(), req) + + // when + resp, err := http.DefaultClient.Do(req) + + // then + require.NoError(s.T(), err) + require.NotNil(s.T(), resp) + defer resp.Body.Close() + assert.Equal(s.T(), http.StatusInternalServerError, resp.StatusCode) + }) }) s.Run("websockets error", func() { @@ -603,6 +607,7 @@ func (s *TestProxySuite) TestProxy() { GetInformerServiceFunc: func() appservice.InformerService { return inf }, + ProxyMetrics: p.metrics, } } @@ -631,7 +636,6 @@ func (s *TestProxySuite) TestProxy() { }) } }) - }) } }