/
tracing.go
392 lines (358 loc) · 12.1 KB
/
tracing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package business
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/kiali/kiali/config"
"github.com/kiali/kiali/log"
"github.com/kiali/kiali/models"
"github.com/kiali/kiali/observability"
"github.com/kiali/kiali/tracing"
"github.com/kiali/kiali/tracing/jaeger/model"
jaegerModels "github.com/kiali/kiali/tracing/jaeger/model/json"
)
type (
SpanFilter = func(span *jaegerModels.Span) bool
)
type TracingService struct {
conf *config.Config
svc *SvcService
tracing tracing.ClientInterface
workload *WorkloadService
}
func NewTracingService(conf *config.Config, tracing tracing.ClientInterface, svcService *SvcService, workloadService *WorkloadService) TracingService {
return TracingService{
conf: conf,
svc: svcService,
tracing: tracing,
workload: workloadService,
}
}
func (in *TracingService) client() (tracing.ClientInterface, error) {
if !in.conf.ExternalServices.Tracing.Enabled {
return nil, fmt.Errorf("Tracing is not enabled")
}
if in.tracing == nil {
return nil, fmt.Errorf("Tracing client is not initialized")
}
return in.tracing, nil
}
func (in *TracingService) getFilteredSpans(ns, app string, query models.TracingQuery, filter SpanFilter) ([]model.TracingSpan, error) {
// This is info needed for Tempo as it is not in the results by default
if in.conf.ExternalServices.Tracing.Provider == config.TempoProvider {
query.Tags["http.method"] = ".*"
}
r, err := in.GetAppTraces(ns, app, query)
if err != nil {
return []model.TracingSpan{}, err
}
spans := tracesToSpans(app, r, filter, in.conf)
return spans, nil
}
func mergeResponses(dest *model.TracingResponse, src *model.TracingResponse) {
dest.TracingServiceName = src.TracingServiceName
dest.Errors = append(dest.Errors, src.Errors...)
traceIds := make(map[jaegerModels.TraceID]bool)
for _, prev := range dest.Data {
traceIds[prev.TraceID] = true
}
for _, trace := range src.Data {
if _, ok := traceIds[trace.TraceID]; !ok {
dest.Data = append(dest.Data, trace)
traceIds[trace.TraceID] = true
}
}
}
func (in *TracingService) GetAppSpans(ns, app string, query models.TracingQuery) ([]model.TracingSpan, error) {
return in.getFilteredSpans(ns, app, query, nil /*no post-filtering for apps*/)
}
func (in *TracingService) GetServiceSpans(ctx context.Context, ns, service string, query models.TracingQuery) ([]model.TracingSpan, error) {
var end observability.EndFunc
ctx, end = observability.StartSpan(ctx, "GetServiceSpans",
observability.Attribute("package", "business"),
observability.Attribute("cluster", query.Cluster),
observability.Attribute("namespace", ns),
observability.Attribute("service", service),
)
defer end()
app, err := in.svc.GetServiceAppName(ctx, query.Cluster, ns, service)
if err != nil {
return nil, err
}
var postFilter SpanFilter
// Run post-filter only for service != app
if app != service {
postFilter = operationSpanFilter(ns, service)
}
return in.getFilteredSpans(ns, app, query, postFilter)
}
func operationSpanFilter(ns, service string) SpanFilter {
fqService := service + "." + ns
// Filter out app spans based on operation name.
// For envoy traces, operation name is like "service-name.namespace.svc.cluster.local:8000/*"
return func(span *jaegerModels.Span) bool {
return strings.HasPrefix(span.OperationName, fqService)
}
}
func (in *TracingService) GetWorkloadSpans(ctx context.Context, ns, workload string, query models.TracingQuery) ([]model.TracingSpan, error) {
var end observability.EndFunc
ctx, end = observability.StartSpan(ctx, "GetWorkloadSpans",
observability.Attribute("package", "business"),
observability.Attribute("cluster", query.Cluster),
observability.Attribute("namespace", ns),
observability.Attribute("workload", workload),
)
defer end()
app, err := in.workload.GetWorkloadAppName(ctx, query.Cluster, ns, workload)
if err != nil {
return nil, err
}
return in.getFilteredSpans(ns, app, query, wkdSpanFilter(ns, workload))
}
func wkdSpanFilter(ns, workload string) SpanFilter {
// Filter out app traces based on the node_id tag, that contains workload information.
return func(span *jaegerModels.Span) bool {
return spanMatchesWorkload(span, ns, workload)
}
}
func (in *TracingService) GetAppTraces(ns, app string, query models.TracingQuery) (*model.TracingResponse, error) {
client, err := in.client()
if err != nil {
return nil, err
}
r, err := client.GetAppTraces(ns, app, query)
if err != nil {
return nil, err
}
if len(r.Data) == query.Limit {
// Reached the limit, use split & join mode to spread traces over the requested interval
log.Trace("Limit of traces was reached, using split & join mode")
more, err := in.getAppTracesSlicedInterval(ns, app, query)
if err != nil {
// Log error but continue to process results (might still have some data fetched)
log.Errorf("Traces split & join failed: %v", err)
}
if more != nil {
mergeResponses(r, more)
}
}
return r, nil
}
// GetServiceTraces returns traces involving the requested service. Note that because the tracing API pulls traces by "App", only a
// subset of the traces may actually involve the requested service. Callers may need to upwardly adjust TracingQuery.Limit to get back
// the number of desired traces. It depends on the number of services backing the app. For example, if there are 2 services for the
// app, if evenly distributed, a query limit of 20 may return only 10 traces. The ratio is typically not as bad as it is with
// GetWorkloadTraces.
func (in *TracingService) GetServiceTraces(ctx context.Context, ns, service string, query models.TracingQuery) (*model.TracingResponse, error) {
var end observability.EndFunc
ctx, end = observability.StartSpan(ctx, "GetServiceTraces",
observability.Attribute("package", "business"),
observability.Attribute("cluster", query.Cluster),
observability.Attribute("namespace", ns),
observability.Attribute("service", service),
)
defer end()
app, err := in.svc.GetServiceAppName(ctx, query.Cluster, ns, service)
if err != nil {
return nil, err
}
if app == service {
// No post-filtering
return in.GetAppTraces(ns, app, query)
}
r, err := in.GetAppTraces(ns, app, query)
if r != nil && err == nil {
// Filter out app traces based on operation name.
// For envoy traces, operation name is like "service-name.namespace.svc.cluster.local:8000/*"
filter := operationSpanFilter(ns, service)
traces := []jaegerModels.Trace{}
for _, trace := range r.Data {
for _, span := range trace.Spans {
if filter(&span) {
traces = append(traces, trace)
break
}
}
}
r.Data = traces
}
return r, err
}
// GetWorkloadTraces returns traces involving the requested workload. Note that because the tracing API pulls traces by "App", only
// a subset of the traces may actually involve the requested workload. Callers may need to upwardly adjust TracingQuery.Limit to get back
// the number of desired traces. It depends on the number of workloads backing the app. For example, if there are 5 workloads for the
// app, if evenly distributed, a query limit of 25 may return only 5 traces.
func (in *TracingService) GetWorkloadTraces(ctx context.Context, ns, workload string, query models.TracingQuery) (*model.TracingResponse, error) {
var end observability.EndFunc
ctx, end = observability.StartSpan(ctx, "GetWorkloadTraces",
observability.Attribute("package", "business"),
observability.Attribute("cluster", query.Cluster),
observability.Attribute("namespace", ns),
observability.Attribute("workload", workload),
)
defer end()
app, err := in.workload.GetWorkloadAppName(ctx, query.Cluster, ns, workload)
if err != nil {
return nil, err
}
r, err := in.GetAppTraces(ns, app, query)
// Filter out app traces based on the node_id tag, that contains workload information.
if r != nil && err == nil {
traces := []jaegerModels.Trace{}
for _, trace := range r.Data {
if matchesWorkload(&trace, ns, workload) {
traces = append(traces, trace)
}
}
r.Data = traces
}
return r, err
}
func (in *TracingService) getAppTracesSlicedInterval(ns, app string, query models.TracingQuery) (*model.TracingResponse, error) {
client, err := in.client()
if err != nil {
return nil, err
}
// Spread queries over 10 interval slices
nSlices := 10
limit := query.Limit / nSlices
if limit == 0 {
limit = 1
}
diff := query.End.Sub(query.Start)
duration := diff / time.Duration(nSlices)
type tracesChanResult struct {
resp *model.TracingResponse
err error
}
tracesChan := make(chan tracesChanResult, nSlices)
var wg sync.WaitGroup
for i := 0; i < nSlices; i++ {
q := query
q.Limit = limit
q.Start = query.Start.Add(duration * time.Duration(i))
q.End = q.Start.Add(duration)
wg.Add(1)
go func(q models.TracingQuery) {
defer wg.Done()
r, err := client.GetAppTraces(ns, app, q)
tracesChan <- tracesChanResult{resp: r, err: err}
}(q)
}
wg.Wait()
// All slices are fetched, close channel
close(tracesChan)
merged := &model.TracingResponse{}
for r := range tracesChan {
if r.err != nil {
err = r.err
continue
}
mergeResponses(merged, r.resp)
}
return merged, err
}
func (in *TracingService) GetTraceDetail(traceID string) (trace *model.TracingSingleTrace, err error) {
client, err := in.client()
if err != nil {
return nil, err
}
return client.GetTraceDetail(traceID)
}
func (in *TracingService) GetErrorTraces(ns, app string, duration time.Duration) (errorTraces int, err error) {
client, err := in.client()
if err != nil {
return 0, err
}
return client.GetErrorTraces(ns, app, duration)
}
func (in *TracingService) GetStatus() (accessible bool, err error) {
client, err := in.client()
if err != nil {
return false, err
}
return client.GetServiceStatus()
}
func matchesWorkload(trace *jaegerModels.Trace, namespace, workload string) bool {
for _, span := range trace.Spans {
if process, ok := trace.Processes[span.ProcessID]; ok {
span.Process = &process
}
if spanMatchesWorkload(&span, namespace, workload) {
return true
}
}
return false
}
func spanMatchesWorkload(span *jaegerModels.Span, namespace, workload string) bool {
// For envoy traces, with a workload named "ai-locals", node_id is like:
// sidecar~172.17.0.20~ai-locals-6d8996bff-ztg6z.default~default.svc.cluster.local
for _, tag := range span.Tags {
if tag.Key == "node_id" {
if v, ok := tag.Value.(string); ok {
parts := strings.Split(v, "~")
if len(parts) >= 3 && strings.HasPrefix(parts[2], workload) && strings.HasSuffix(parts[2], namespace) {
return true
}
}
}
}
// Tag not found => try with 'hostname' in process' tags
if span.Process != nil {
for _, tag := range span.Process.Tags {
if tag.Key == "hostname" {
if v, ok := tag.Value.(string); ok {
if strings.HasPrefix(v, workload) {
return true
}
}
}
}
}
return false
}
func tracesToSpans(app string, r *model.TracingResponse, filter SpanFilter, conf *config.Config) []model.TracingSpan {
spans := []model.TracingSpan{}
for _, trace := range r.Data {
// Diferent for Tempo & Jaeger
// For Tempo the proccess matched with the service name of the trace batch
// So t is already filtered in the query
if conf.ExternalServices.Tracing.Provider == config.TempoProvider {
// Second, find spans for these processes
for _, span := range trace.Spans {
if span.Process.ServiceName == r.TracingServiceName {
if filter == nil || filter(&span) {
spans = append(spans, model.TracingSpan{
Span: span,
TraceSize: len(trace.Spans),
})
}
}
}
} else {
// First, get the desired processes for our service
processes := make(map[jaegerModels.ProcessID]jaegerModels.Process)
for pId, process := range trace.Processes {
if process.ServiceName == app || process.ServiceName == r.TracingServiceName {
processes[pId] = process
}
}
// Second, find spans for these processes
for _, span := range trace.Spans {
if p, ok := processes[span.ProcessID]; ok {
span.Process = &p
if filter == nil || filter(&span) {
spans = append(spans, model.TracingSpan{
Span: span,
TraceSize: len(trace.Spans),
})
}
}
}
}
}
log.Tracef("Found %d spans in the %d traces for app %s", len(spans), len(r.Data), app)
return spans
}