Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 3 additions & 1 deletion api/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
6 changes: 5 additions & 1 deletion api/views/overview/overview.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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":
Expand Down
55 changes: 49 additions & 6 deletions api/views/overview/traces.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
57 changes: 36 additions & 21 deletions api/views/tracing/tracing.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tracing
import (
"context"
"fmt"
"net"
"net/url"
"sort"
"strings"
Expand Down Expand Up @@ -64,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"}
}
Expand Down Expand Up @@ -129,19 +130,22 @@ 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)
spans, err = ch.GetSpansByTraceIdScoped(ctx, traceId, scope)
if allowService != nil {
spans = filterSpans(spans, allowService)
}

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() {
Expand All @@ -150,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)
Expand All @@ -170,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)
Expand All @@ -195,7 +201,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 {
Expand All @@ -206,13 +213,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 {
Expand Down Expand Up @@ -383,16 +391,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)
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions api/views/tracing/tracing_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tracing

import (
"sort"
"testing"

"github.com/coroot/coroot/model"
Expand All @@ -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)
}
4 changes: 2 additions & 2 deletions api/views/views.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
25 changes: 25 additions & 0 deletions clickhouse/clickhouse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Loading
Loading