rename apiserver trace span to http server guidelines

Signed-off-by: Ziqi Zhao <zhaoziqi9146@gmail.com>
This commit is contained in:
Ziqi Zhao 2024-02-29 19:03:43 +08:00
parent 3ec6a38795
commit 84b9fbbdef

View File

@ -22,6 +22,7 @@ import (
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"go.opentelemetry.io/otel/trace"
"k8s.io/apiserver/pkg/endpoints/request"
tracing "k8s.io/component-base/tracing"
)
@ -32,6 +33,14 @@ func WithTracing(handler http.Handler, tp trace.TracerProvider) http.Handler {
otelhttp.WithPropagators(tracing.Propagators()),
otelhttp.WithPublicEndpoint(),
otelhttp.WithTracerProvider(tp),
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
ctx := r.Context()
info, exist := request.RequestInfoFrom(ctx)
if !exist {
return "KubernetesAPI"
}
return getSpanNameFromRequestInfo(info)
}),
}
wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Add the http.target attribute to the otelhttp span
@ -45,3 +54,22 @@ func WithTracing(handler http.Handler, tp trace.TracerProvider) http.Handler {
// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough
return otelhttp.NewHandler(wrappedHandler, "KubernetesAPI", opts...)
}
func getSpanNameFromRequestInfo(info *request.RequestInfo) string {
spanName := "/" + info.APIPrefix
if info.APIGroup != "" {
spanName += "/" + info.APIGroup
}
spanName += "/" + info.APIVersion
if info.Namespace != "" {
spanName += "/namespaces/{:namespace}"
}
spanName += "/" + info.Resource
if info.Name != "" {
spanName += "/" + "{:id}"
}
if info.Subresource != "" {
spanName += "/" + info.Subresource
}
return spanName
}