From 0628cd5caaa7897d2f239821e5d1d44933ef8006 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 2 Nov 2026 20:14:11 +0300 Subject: [PATCH 1/2] Tracing: hide monitoring and control-plane requests on the application tab The per-application Tracing tab now excludes spans whose client is a monitoring or control-plane application (metrics scrapes, kubelet probes), as the overview Traces page does by default. Applies to both the OpenTelemetry and the eBPF span sources; monitoring and control-plane applications themselves are not filtered. Agent: claude Co-Authored-By: Claude Fable 5.1 --- api/views/tracing/tracing.go | 51 +++++++++++++++++++------------ api/views/tracing/tracing_test.go | 21 +++++++++++++ 2 files changed, 53 insertions(+), 19 deletions(-) diff --git a/api/views/tracing/tracing.go b/api/views/tracing/tracing.go index e16949cc3..88fe9ed82 100644 --- a/api/views/tracing/tracing.go +++ b/api/views/tracing/tracing.go @@ -3,6 +3,7 @@ package tracing import ( "context" "fmt" + "net" "net/url" "sort" "strings" @@ -129,6 +130,13 @@ func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, var histogram []model.HistogramBucket var spans []*model.TraceSpan clients := map[spanKey]string{} + // Requests from monitoring and control-plane applications (metrics + // scrapes, kubelet probes) are not the application's own traffic; the + // overview Traces page hides them by default and this view always does. + var ignoredPeerAddrs []string + if !app.Category.Monitoring() && !app.Category.ControlPlane() { + ignoredPeerAddrs = getAuxPodIps(w) + } switch { case traceId != "": spans, err = ch.GetSpansByTraceId(ctx, traceId) @@ -138,10 +146,6 @@ func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, case (source == "" || source == model.TraceSourceOtel) && otelService != "": source = model.TraceSourceOtel - var ignoredPeerAddrs []string - if !app.Category.Monitoring() { - ignoredPeerAddrs = getMonitoringPodIps(w) - } wg := sync.WaitGroup{} wg.Add(2) go func() { @@ -195,7 +199,8 @@ func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, defer wg.Done() var e error sq := clickhouse.SpanQuery{ - Ctx: w.Ctx, + Ctx: w.Ctx, + ExcludePeerAddrs: ignoredPeerAddrs, } histogram, e = ch.GetInboundSpansHistogram(ctx, sq, maps.Keys(appClients), listens) if e != nil { @@ -206,13 +211,14 @@ func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, defer wg.Done() var e error sq := clickhouse.SpanQuery{ - Ctx: w.Ctx, - TsFrom: tsFrom, - TsTo: tsTo, - DurFrom: durFrom, - DurTo: durTo, - Errors: errors, - Limit: limit, + Ctx: w.Ctx, + TsFrom: tsFrom, + TsTo: tsTo, + DurFrom: durFrom, + DurTo: durTo, + Errors: errors, + Limit: limit, + ExcludePeerAddrs: ignoredPeerAddrs, } spans, e = ch.GetInboundSpans(ctx, sq, maps.Keys(appClients), listens) if e != nil { @@ -383,16 +389,23 @@ func getAppListens(app *model.Application) []model.Listen { return res } -func getMonitoringPodIps(w *model.World) []string { +// getAuxPodIps returns every address the monitoring and control-plane +// applications listen on: pod IPs, and the node IPs of host-network agents +// such as the kubelet, whose probes arrive from the node address. +func getAuxPodIps(w *model.World) []string { + seen := map[string]bool{} var res []string for _, a := range w.Applications { - if a.Category.Monitoring() { - for _, i := range a.Instances { - for l := range i.TcpListens { - if l.Port == "0" { - res = append(res, l.IP) - } + if !a.Category.Monitoring() && !a.Category.ControlPlane() { + continue + } + for _, i := range a.Instances { + for l := range i.TcpListens { + if ip := net.ParseIP(l.IP); ip == nil || ip.IsLoopback() || seen[l.IP] { + continue } + seen[l.IP] = true + res = append(res, l.IP) } } } diff --git a/api/views/tracing/tracing_test.go b/api/views/tracing/tracing_test.go index bf03e0e1d..09b523f65 100644 --- a/api/views/tracing/tracing_test.go +++ b/api/views/tracing/tracing_test.go @@ -1,6 +1,7 @@ package tracing import ( + "sort" "testing" "github.com/coroot/coroot/model" @@ -15,3 +16,23 @@ func TestFilterSpans(t *testing.T) { assert.Equal(t, "a", s.ServiceName) } } + +func TestGetAuxPodIpsCoversMonitoringAndControlPlane(t *testing.T) { + w := &model.World{Applications: map[model.ApplicationId]*model.Application{}} + add := func(ns, name string, category model.ApplicationCategory, ips ...string) { + app := model.NewApplication(model.NewApplicationId("", ns, model.ApplicationKindDeployment, name)) + app.Category = category + i := app.GetOrCreateInstance(name+"-0", nil) + for n, ip := range ips { + i.TcpListens[model.Listen{IP: ip, Port: []string{"0", "10250", "9100"}[n%3]}] = true + } + w.Applications[app.Id] = app + } + add("coroot", "coroot-cluster-agent", model.ApplicationCategoryMonitoring, "192.168.205.139", "127.0.0.1") + add("", "k3s-agent", model.ApplicationCategoryControlPlane, "10.10.33.34", "10.10.33.34", "10.10.33.35") + add("shop-production", "web", model.ApplicationCategoryApplication, "192.168.2.206") + + got := getAuxPodIps(w) + sort.Strings(got) + assert.Equal(t, []string{"10.10.33.34", "10.10.33.35", "192.168.205.139"}, got) +} From 517a8b39ace9ecbde12401f41dc3e65f1434ce17 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 2 Nov 2026 20:28:23 +0300 Subject: [PATCH 2/2] Traces: scope namespace-limited roles by the collector-set namespace attribute For a role limited to some namespaces, OpenTelemetry span queries (overview Traces page, application Tracing tab, trace by id, MCP) are now limited by the k8s.namespace.name resource attribute the platform's collector sets from the sending pod, instead of by service names guessed from the application names. The agent's own spans stay matched by their service names. Scoped queries read the spans table (the histogram and service-name tables carry no resource attributes). Agent: claude Co-Authored-By: Claude Fable 5.1 --- api/api.go | 20 +++++++- api/mcp.go | 4 +- api/views/overview/overview.go | 6 ++- api/views/overview/traces.go | 55 +++++++++++++++++++--- api/views/tracing/tracing.go | 6 ++- api/views/views.go | 4 +- clickhouse/clickhouse_test.go | 25 ++++++++++ clickhouse/traces.go | 86 +++++++++++++++++++++++++++++++--- 8 files changed, 185 insertions(+), 21 deletions(-) diff --git a/api/api.go b/api/api.go index 5477febbe..86d0dcc0f 100644 --- a/api/api.go +++ b/api/api.go @@ -529,13 +529,18 @@ func (api *Api) Overview(w http.ResponseWriter, r *http.Request, u *db.User) { renderWorld := world restrictTelemetry := false restricted := api.hasRestrictedAppAccess(u, projectId) + var scopeNamespaces []string if restricted && (view == "logs" || view == "traces" || view == "risks") { renderWorld = api.worldWithViewableApps(u, projectId, world) restrictTelemetry = view == "logs" || view == "traces" + if view == "traces" { + scopeNamespaces, _ = api.restrictedNamespaces(u, projectId, world) + } } ov := views.Overview(r.Context(), chs, project, renderWorld, view, r.URL.Query().Get("query"), views.OverviewOpts{ RestrictTelemetry: restrictTelemetry, FullWorld: world, + Namespaces: scopeNamespaces, }) ov = api.filterOverviewForUser(u, projectId, world, ov) utils.WriteJson(w, api.WithContext(u, project, cacheStatus, world, ov)) @@ -2392,13 +2397,24 @@ func (api *Api) Tracing(w http.ResponseWriter, r *http.Request, u *db.User) { } defer ch.Close() var allowService func(string) bool + var scope *clickhouse.NamespaceScope restricted := api.hasRestrictedAppAccess(u, projectId) if restricted { viewable := api.worldWithViewableApps(u, projectId, world) - allowed := utils.NewStringSet(overview.TraceServicesForApps(r.Context(), clickhouse.Clients{Clients: []*clickhouse.Client{ch}}, viewable, world)...) + chs := clickhouse.Clients{Clients: []*clickhouse.Client{ch}} + var services []string + if namespaces, _ := api.restrictedNamespaces(u, projectId, world); len(namespaces) > 0 { + // Spans are limited by the collector-set namespace attribute; + // the service list is what that scope contains. + scope = overview.TraceScope(viewable, namespaces) + services = overview.TraceServicesInNamespaces(r.Context(), chs, viewable, namespaces) + } else { + services = overview.TraceServicesForApps(r.Context(), chs, viewable, world) + } + allowed := utils.NewStringSet(services...) allowService = allowed.Has } - res := views.Tracing(r.Context(), ch, app, q, world, allowService) + res := views.Tracing(r.Context(), ch, app, q, world, allowService, scope) if restricted { limitTraceServices(res, allowService) } diff --git a/api/mcp.go b/api/mcp.go index a99a05537..bbcea411e 100644 --- a/api/mcp.go +++ b/api/mcp.go @@ -1323,10 +1323,12 @@ func (h *MCPHandler) runTracesQuery(ctx context.Context, req mcp.CallToolRequest queryJSON, _ := json.Marshal(q) renderWorld := world restricted := h.Api.hasRestrictedAppAccess(user, string(project.Id)) + var namespaces []string if restricted { renderWorld = h.Api.worldWithViewableApps(user, string(project.Id), world) + namespaces, _ = h.Api.restrictedNamespaces(user, string(project.Id), world) } - res := overview.RenderTraces(ctx, chs, renderWorld, string(queryJSON), restricted, world) + res := overview.RenderTraces(ctx, chs, renderWorld, string(queryJSON), restricted, world, namespaces) if res.Error != "" { return nil, mcp.NewToolResultError(res.Error) } diff --git a/api/views/overview/overview.go b/api/views/overview/overview.go index efc4b0d5a..c472fa9dd 100644 --- a/api/views/overview/overview.go +++ b/api/views/overview/overview.go @@ -30,6 +30,10 @@ type RenderOpts struct { RestrictTelemetry bool // FullWorld is used for GuessService uniqueness when w is a restricted copy. FullWorld *model.World + // Namespaces, with RestrictTelemetry, are the namespaces the viewer may + // see: OpenTelemetry spans are then limited by the collector-set + // namespace attribute instead of by guessed service names. + Namespaces []string } func Render(ctx context.Context, chs clickhouse.Clients, project *db.Project, w *model.World, view, query string, opts RenderOpts) *Overview { @@ -56,7 +60,7 @@ func Render(ctx context.Context, chs clickhouse.Clients, project *db.Project, w case "deployments": v.Deployments = renderDeployments(w) case "traces": - v.Traces = RenderTraces(ctx, chs, w, query, opts.RestrictTelemetry, fullWorld) + v.Traces = RenderTraces(ctx, chs, w, query, opts.RestrictTelemetry, fullWorld, opts.Namespaces) case "logs": v.Logs = renderLogs(ctx, chs, w, query, opts.RestrictTelemetry, fullWorld) case "costs": diff --git a/api/views/overview/traces.go b/api/views/overview/traces.go index 731970d5c..503db9b41 100644 --- a/api/views/overview/traces.go +++ b/api/views/overview/traces.go @@ -79,7 +79,7 @@ type Filter struct { Value string `json:"value"` } -func RenderTraces(ctx context.Context, chs clickhouse.Clients, w *model.World, query string, restrict bool, fullWorld *model.World) *Traces { +func RenderTraces(ctx context.Context, chs clickhouse.Clients, w *model.World, query string, restrict bool, fullWorld *model.World, namespaces []string) *Traces { res := &Traces{} if chs.Error != nil { @@ -101,12 +101,16 @@ func RenderTraces(ctx context.Context, chs clickhouse.Clients, w *model.World, q } if restrict { - services := traceServicesForApps(ctx, chs, w, fullWorld) - if len(services) == 0 { - res.Message = "not_found" - return res + if len(namespaces) > 0 { + sq.Scope = TraceScope(w, namespaces) + } else { + services := traceServicesForApps(ctx, chs, w, fullWorld) + if len(services) == 0 { + res.Message = "not_found" + return res + } + sq.Services = services } - sq.Services = services } if !q.IncludeAux { @@ -405,6 +409,45 @@ func TraceServicesForApps(ctx context.Context, chs clickhouse.Clients, appsWorld return traceServicesForApps(ctx, chs, appsWorld, fullWorld) } +// AgentTraceServices are the service names of the agent's (eBPF) spans for +// the applications in w: the container service names, as for logs. The agent +// names them from Kubernetes metadata, so they can be trusted. +func AgentTraceServices(w *model.World) []string { + out := utils.NewStringSet() + if w != nil { + for _, app := range w.Applications { + out.Add(app.LogServices()...) + } + } + return out.Items() +} + +// TraceScope limits span queries to the viewer's namespaces (collector-set +// attribute) and to the agent's spans of the applications in w. +func TraceScope(w *model.World, namespaces []string) *clickhouse.NamespaceScope { + return &clickhouse.NamespaceScope{Namespaces: namespaces, Services: AgentTraceServices(w)} +} + +// TraceServicesInNamespaces lists the trace services a viewer limited to +// namespaces may see: the agent's services of the applications in appsWorld +// and the OpenTelemetry services whose spans the collector tagged with one of +// the namespaces. +func TraceServicesInNamespaces(ctx context.Context, chs clickhouse.Clients, appsWorld *model.World, namespaces []string) []string { + out := utils.NewStringSet(AgentTraceServices(appsWorld)...) + if appsWorld == nil || len(namespaces) == 0 { + return out.Items() + } + for _, ch := range chs.Clients { + svcs, err := ch.GetServicesFromTracesInNamespaces(ctx, appsWorld.Ctx.From, namespaces) + if err != nil { + klog.Errorln(err) + continue + } + out.Add(svcs...) + } + return out.Items() +} + func traceServicesForApps(ctx context.Context, chs clickhouse.Clients, appsWorld, fullWorld *model.World) []string { if appsWorld == nil || len(appsWorld.Applications) == 0 { return nil diff --git a/api/views/tracing/tracing.go b/api/views/tracing/tracing.go index 88fe9ed82..762a6a058 100644 --- a/api/views/tracing/tracing.go +++ b/api/views/tracing/tracing.go @@ -65,7 +65,7 @@ type Event struct { // Render renders the tracing view of the application. When allowService is // not nil, spans returned by a trace-id lookup are limited to the services it // accepts. -func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, q url.Values, w *model.World, allowService func(string) bool) *View { +func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, q url.Values, w *model.World, allowService func(string) bool, scope *clickhouse.NamespaceScope) *View { if ch == nil { return &View{Status: model.WARNING, Message: "Clickhouse integration is not configured"} } @@ -139,7 +139,7 @@ func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, } switch { case traceId != "": - spans, err = ch.GetSpansByTraceId(ctx, traceId) + spans, err = ch.GetSpansByTraceIdScoped(ctx, traceId, scope) if allowService != nil { spans = filterSpans(spans, allowService) } @@ -154,6 +154,7 @@ func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, sq := clickhouse.SpanQuery{ Ctx: w.Ctx, ExcludePeerAddrs: ignoredPeerAddrs, + Scope: scope, } sq.AddFilter("ServiceName", "=", otelService) histogram, e = ch.GetSpansByServiceNameHistogram(ctx, sq) @@ -174,6 +175,7 @@ func Render(ctx context.Context, ch *clickhouse.Client, app *model.Application, Errors: errors, Limit: limit, ExcludePeerAddrs: ignoredPeerAddrs, + Scope: scope, } sq.AddFilter("ServiceName", "=", otelService) spans, e = ch.GetSpansByServiceName(ctx, sq) diff --git a/api/views/views.go b/api/views/views.go index a933cf1da..0ace62de8 100644 --- a/api/views/views.go +++ b/api/views/views.go @@ -57,8 +57,8 @@ func Profiling(ctx context.Context, ch *clickhouse.Client, app *model.Applicatio return profiling.Render(ctx, ch, app, q, w) } -func Tracing(ctx context.Context, ch *clickhouse.Client, app *model.Application, q url.Values, w *model.World, allowService func(string) bool) *tracing.View { - return tracing.Render(ctx, ch, app, q, w, allowService) +func Tracing(ctx context.Context, ch *clickhouse.Client, app *model.Application, q url.Values, w *model.World, allowService func(string) bool, scope *clickhouse.NamespaceScope) *tracing.View { + return tracing.Render(ctx, ch, app, q, w, allowService, scope) } func Logs(ctx context.Context, ch *clickhouse.Client, app *model.Application, q url.Values, w *model.World) *logs.View { diff --git a/clickhouse/clickhouse_test.go b/clickhouse/clickhouse_test.go index 1177a5c58..8538a08ea 100644 --- a/clickhouse/clickhouse_test.go +++ b/clickhouse/clickhouse_test.go @@ -75,3 +75,28 @@ func TestConvertIntervalToSeconds(t *testing.T) { assert.Equal(t, uint64(0), convertIntervalToSeconds(10, "INVALID")) assert.Equal(t, uint64(0), convertIntervalToSeconds(0, "DAY")) } + +func TestSpanQueryScopeFilter(t *testing.T) { + q := SpanQuery{Scope: &NamespaceScope{Namespaces: []string{"shop-production"}, Services: []string{"/k8s/shop-production/web"}}} + filter, args := q.Filter() + assert.Equal(t, []string{"(ResourceAttributes['k8s.namespace.name'] IN (@scopeNamespaces) OR ServiceName IN (@scopeServices))"}, filter) + assert.Len(t, args, 2) + assert.False(t, q.filtersOnHistogramDimensions()) + + // Scope and Services both apply. + q.Services = []string{"api"} + filter, _ = q.Filter() + assert.Len(t, filter, 2) + + // An empty scope matches nothing. + empty := SpanQuery{Scope: &NamespaceScope{}} + filter, args = empty.Filter() + assert.Equal(t, []string{"0"}, filter) + assert.Empty(t, args) + + // No scope: unchanged. + none := SpanQuery{} + filter, _ = none.Filter() + assert.Empty(t, filter) + assert.True(t, none.filtersOnHistogramDimensions()) +} diff --git a/clickhouse/traces.go b/clickhouse/traces.go index bf7626360..b861513bc 100644 --- a/clickhouse/traces.go +++ b/clickhouse/traces.go @@ -134,6 +134,11 @@ func (c *Client) GetParentSpans(ctx context.Context, spans []*model.TraceSpan) ( } func (c *Client) GetSpansByTraceId(ctx context.Context, traceId string) ([]*model.TraceSpan, error) { + return c.GetSpansByTraceIdScoped(ctx, traceId, nil) +} + +// GetSpansByTraceIdScoped is GetSpansByTraceId limited to scope (nil: all). +func (c *Client) GetSpansByTraceIdScoped(ctx context.Context, traceId string, scope *NamespaceScope) ([]*model.TraceSpan, error) { var minTs, maxTs time.Time err := c.QueryRow(ctx, "SELECT min(Start), max(End)+1 FROM @@table_otel_traces_trace_id_ts@@ WHERE TraceId = @traceId", @@ -145,13 +150,41 @@ func (c *Client) GetSpansByTraceId(ctx context.Context, traceId string) ([]*mode q := SpanQuery{ TsFrom: timeseries.TimeFromStandard(minTs), TsTo: timeseries.TimeFromStandard(maxTs), + Scope: scope, } - return c.getSpans(ctx, q, "Timestamp", - []string{"TraceId = @traceId"}, - []any{ - clickhouse.Named("traceId", traceId), - }, + filters, args := q.scopeFilter() + filters = append(filters, "TraceId = @traceId") + args = append(args, clickhouse.Named("traceId", traceId)) + return c.getSpans(ctx, q, "Timestamp", filters, args) +} + +// GetServicesFromTracesInNamespaces lists the services with spans tagged with +// one of namespaces since from. Reads the spans table: the service-name +// table has no ResourceAttributes. +func (c *Client) GetServicesFromTracesInNamespaces(ctx context.Context, from timeseries.Time, namespaces []string) ([]string, error) { + if len(namespaces) == 0 { + return nil, nil + } + rows, err := c.Query(ctx, + "SELECT DISTINCT ServiceName FROM @@table_otel_traces@@ WHERE Timestamp >= @from AND ResourceAttributes['"+TraceNamespaceAttr+"'] IN (@namespaces)", + clickhouse.DateNamed("from", from.ToStandard(), clickhouse.NanoSeconds), + clickhouse.Named("namespaces", namespaces), ) + if err != nil { + return nil, err + } + defer func() { + _ = rows.Close() + }() + var res []string + for rows.Next() { + var s string + if err = rows.Scan(&s); err != nil { + return nil, err + } + res = append(res, s) + } + return res, nil } func (c *Client) getOtelTracesServiceName(ctx context.Context, world *model.World, app *model.Application) (string, error) { @@ -674,6 +707,19 @@ type SpanFilter struct { Value string } +// TraceNamespaceAttr is the resource attribute the platform's OpenTelemetry +// collector sets on every span from the sending pod's address. Senders cannot +// choose it, so it is the attribute namespace-scoped viewers are limited by. +const TraceNamespaceAttr = "k8s.namespace.name" + +// NamespaceScope limits spans to those tagged with one of Namespaces +// (TraceNamespaceAttr) or, for the agent's own spans, to Services. An empty +// scope matches nothing. +type NamespaceScope struct { + Namespaces []string + Services []string +} + type SpanQuery struct { Ctx timeseries.Context @@ -690,6 +736,8 @@ type SpanQuery struct { Filters []SpanFilter ExcludePeerAddrs []string + // Scope, when set, is applied on top of Services and Filters. + Scope *NamespaceScope Diff bool } @@ -781,6 +829,10 @@ func (c *Client) useTracesHistogram(ctx context.Context, q SpanQuery, from times } func (q *SpanQuery) filtersOnHistogramDimensions() bool { + if q.Scope != nil { + // The histogram table has no ResourceAttributes. + return false + } for _, f := range q.Filters { switch f.Field { case "ServiceName", "SpanName", "SpanKind", "NetSockPeerAddr": @@ -801,9 +853,29 @@ func (q *SpanQuery) SpansByServiceNameFilter(fromMV bool) ([]string, []any) { return filter, args } -func (q *SpanQuery) Filter() ([]string, []any) { - var filter []string +// scopeFilter renders Scope; nothing when there is no scope. +func (q *SpanQuery) scopeFilter() ([]string, []any) { + if q.Scope == nil { + return nil, nil + } + var parts []string var args []any + if len(q.Scope.Namespaces) > 0 { + parts = append(parts, "ResourceAttributes['"+TraceNamespaceAttr+"'] IN (@scopeNamespaces)") + args = append(args, clickhouse.Named("scopeNamespaces", q.Scope.Namespaces)) + } + if len(q.Scope.Services) > 0 { + parts = append(parts, "ServiceName IN (@scopeServices)") + args = append(args, clickhouse.Named("scopeServices", q.Scope.Services)) + } + if len(parts) == 0 { + return []string{"0"}, nil + } + return []string{"(" + strings.Join(parts, " OR ") + ")"}, args +} + +func (q *SpanQuery) Filter() ([]string, []any) { + filter, args := q.scopeFilter() switch len(q.Services) { case 0: case 1: