From e4169d7f4381595152f6fa862af2227950f3fc76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Banaszewski?= Date: Tue, 8 Nov 2022 11:22:57 +0000 Subject: [PATCH] Added scope as tracing attribute --- .../pkg/endpoints/handlers/helpers.go | 18 ++++++++++++++++++ .../pkg/endpoints/handlers/helpers_test.go | 12 ++++++++++++ .../pkg/endpoints/handlers/trace_util.go | 1 + 3 files changed, 31 insertions(+) diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go index 81e34a717da..7f85563699d 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go @@ -121,3 +121,21 @@ func (lazy *lazyResource) String() string { return "unknown" } + +// lazyScope implements String() string and it will +// lazily get Scope from request info +type lazyScope struct { + req *http.Request +} + +func (lazy *lazyScope) String() string { + if lazy.req != nil { + ctx := lazy.req.Context() + requestInfo, ok := apirequest.RequestInfoFrom(ctx) + if ok { + return metrics.CleanScope(requestInfo) + } + } + + return "unknown" +} diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers_test.go index 4666524bcd1..cdde785ea36 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers_test.go @@ -96,3 +96,15 @@ func TestLazyResource(t *testing.T) { resourceWithReq := &lazyResource{req: req.WithContext(ctx)} assert.Equal(t, "resource", fmt.Sprintf("%v", resourceWithReq)) } + +func TestLazyScope(t *testing.T) { + assert.Equal(t, "unknown", fmt.Sprintf("%v", &lazyScope{})) + + scopeWithEmptyReq := &lazyScope{&http.Request{}} + assert.Equal(t, "unknown", fmt.Sprintf("%v", scopeWithEmptyReq)) + + req := &http.Request{} + ctx := request.WithRequestInfo(context.TODO(), &request.RequestInfo{Namespace: "ns"}) + scopeWithReq := &lazyScope{req: req.WithContext(ctx)} + assert.Equal(t, "namespace", fmt.Sprintf("%v", scopeWithReq)) +} diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/trace_util.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/trace_util.go index 32790d1419f..7d273d62248 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/trace_util.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/trace_util.go @@ -29,6 +29,7 @@ func traceFields(req *http.Request) []attribute.KeyValue { attribute.Stringer("client", &lazyClientIP{req: req}), attribute.String("protocol", req.Proto), attribute.Stringer("resource", &lazyResource{req: req}), + attribute.Stringer("scope", &lazyScope{req: req}), attribute.String("url", req.URL.Path), attribute.Stringer("user-agent", &lazyTruncatedUserAgent{req: req}), attribute.Stringer("verb", &lazyVerb{req: req}),