forked from grafana/tempo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.go
More file actions
413 lines (352 loc) · 10.7 KB
/
engine.go
File metadata and controls
413 lines (352 loc) · 10.7 KB
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package traceql
import (
"context"
"fmt"
"io"
"math"
"time"
"github.com/opentracing/opentracing-go"
"github.com/grafana/tempo/pkg/tempopb"
common_v1 "github.com/grafana/tempo/pkg/tempopb/common/v1"
"github.com/grafana/tempo/pkg/util"
)
const (
DefaultSpansPerSpanSet int = 3
)
type Engine struct {
}
func NewEngine() *Engine {
return &Engine{}
}
func (e *Engine) Compile(query string) (func(input []*Spanset) (result []*Spanset, err error), *FetchSpansRequest, error) {
expr, err := Parse(query)
if err != nil {
return nil, nil, err
}
req := &FetchSpansRequest{
AllConditions: true,
}
expr.Pipeline.extractConditions(req)
return expr.Pipeline.evaluate, req, nil
}
func (e *Engine) ExecuteSearch(ctx context.Context, searchReq *tempopb.SearchRequest, spanSetFetcher SpansetFetcher) (*tempopb.SearchResponse, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "traceql.Engine.ExecuteSearch")
defer span.Finish()
rootExpr, err := e.parseQuery(searchReq)
if err != nil {
return nil, err
}
fetchSpansRequest := e.createFetchSpansRequest(searchReq, rootExpr.Pipeline)
span.SetTag("pipeline", rootExpr.Pipeline)
span.SetTag("fetchSpansRequest", fetchSpansRequest)
// calculate search meta conditions.
metaConditions := SearchMetaConditionsWithout(fetchSpansRequest.Conditions)
spansetsEvaluated := 0
// set up the expression evaluation as a filter to reduce data pulled
fetchSpansRequest.SecondPassConditions = append(fetchSpansRequest.SecondPassConditions, metaConditions...)
fetchSpansRequest.SecondPass = func(inSS *Spanset) ([]*Spanset, error) {
if len(inSS.Spans) == 0 {
return nil, nil
}
evalSS, err := rootExpr.Pipeline.evaluate([]*Spanset{inSS})
if err != nil {
span.LogKV("msg", "pipeline.evaluate", "err", err)
return nil, err
}
spansetsEvaluated++
if len(evalSS) == 0 {
return nil, nil
}
// reduce all evalSS to their max length to reduce meta data lookups
for i := range evalSS {
l := len(evalSS[i].Spans)
evalSS[i].AddAttribute(attributeMatched, NewStaticInt(l))
spansPerSpanSet := int(searchReq.SpansPerSpanSet)
if spansPerSpanSet == 0 {
spansPerSpanSet = DefaultSpansPerSpanSet
}
if l > spansPerSpanSet {
evalSS[i].Spans = evalSS[i].Spans[:spansPerSpanSet]
}
}
return evalSS, nil
}
fetchSpansResponse, err := spanSetFetcher.Fetch(ctx, fetchSpansRequest)
if err != nil {
return nil, err
}
iterator := fetchSpansResponse.Results
defer iterator.Close()
res := &tempopb.SearchResponse{
Traces: nil,
Metrics: &tempopb.SearchMetrics{},
}
combiner := NewMetadataCombiner()
for {
spanset, err := iterator.Next(ctx)
if err != nil && err != io.EOF {
span.LogKV("msg", "iterator.Next", "err", err)
return nil, err
}
if spanset == nil {
break
}
combiner.AddMetadata(e.asTraceSearchMetadata(spanset))
if combiner.Count() >= int(searchReq.Limit) && searchReq.Limit > 0 {
break
}
}
res.Traces = combiner.Metadata()
span.SetTag("spansets_evaluated", spansetsEvaluated)
span.SetTag("spansets_found", len(res.Traces))
// Bytes can be nil when callback is no set
if fetchSpansResponse.Bytes != nil {
// InspectedBytes is used to compute query throughput and SLO metrics
res.Metrics.InspectedBytes = fetchSpansResponse.Bytes()
span.SetTag("inspectedBytes", res.Metrics.InspectedBytes)
}
return res, nil
}
func (e *Engine) ExecuteTagValues(
ctx context.Context,
tag Attribute,
query string,
cb func(v Static) bool,
fetcher SpansetFetcher,
) error {
span, ctx := opentracing.StartSpanFromContext(ctx, "traceql.Engine.ExecuteTagValues")
defer span.Finish()
span.SetTag("sanitized query", query)
rootExpr, err := Parse(query)
if err != nil {
return err
}
if err := rootExpr.validate(); err != nil {
return err
}
searchReq := &tempopb.SearchRequest{
Start: 0, // TODO: Should add Start and End
End: math.MaxUint32,
}
fetchSpansRequest := e.createFetchSpansRequest(searchReq, rootExpr.Pipeline)
// TODO: remove other conditions for the wantAttr we're searching for
// for _, cond := range fetchSpansRequest.Conditions {
// if cond.Attribute == wantAttr {
// return fmt.Errorf("cannot search for tag values for tag that is already used in query")
// }
// }
fetchSpansRequest.Conditions = append(fetchSpansRequest.Conditions, Condition{
Attribute: tag,
Op: OpNone,
})
span.SetTag("pipeline", rootExpr.Pipeline)
span.SetTag("fetchSpansRequest", fetchSpansRequest)
var collectAttributeValue func(s Span) bool
switch tag.Scope {
case AttributeScopeResource,
AttributeScopeSpan: // If tag is scoped, we can check the map directly
collectAttributeValue = func(s Span) bool {
if v, ok := s.Attributes()[tag]; ok {
return cb(v)
}
return false
}
case AttributeScopeNone:
// If tag is unscoped, it can either be an intrinsic (eg. `name`) or an unscoped attribute (eg. `.namespace`)
//
// If the tag is intrinsic Attribute.Intrinsic is set to the Intrinsic it corresponds,
// so we can check against `!= IntrinsicNone` and use tag directly.
//
// If the tag is unscoped, we need to check resource and span scoped manually by building a new Attribute with each scope.
collectAttributeValue = func(s Span) bool {
if tag.Intrinsic != IntrinsicNone { // it's intrinsic
if v, ok := s.Attributes()[tag]; ok {
return cb(v)
}
} else { // it's unscoped
for _, scope := range []AttributeScope{AttributeScopeResource, AttributeScopeSpan} {
scopedAttr := Attribute{Scope: scope, Parent: tag.Parent, Name: tag.Name}
if v, ok := s.Attributes()[scopedAttr]; ok {
return cb(v)
}
}
}
return false
}
default:
return fmt.Errorf("unknown attribute scope: %s", tag)
}
fetchSpansResponse, err := fetcher.Fetch(ctx, fetchSpansRequest)
if err != nil {
return err
}
iterator := fetchSpansResponse.Results
defer iterator.Close()
for {
spanset, err := iterator.Next(ctx)
if err != nil && err != io.EOF {
span.LogKV("msg", "iterator.Next", "err", err)
return err
}
if spanset == nil {
break
}
if len(spanset.Spans) == 0 {
continue
}
evalSS, err := rootExpr.Pipeline.evaluate([]*Spanset{spanset})
if err != nil {
span.LogKV("msg", "pipeline.evaluate", "err", err)
return err
}
if len(evalSS) == 0 {
continue
}
for _, ss := range evalSS {
for _, s := range ss.Spans {
if collectAttributeValue(s) {
return nil // exit early if we've exceed max bytes
}
}
}
}
return nil
}
func (e *Engine) parseQuery(searchReq *tempopb.SearchRequest) (*RootExpr, error) {
r, err := Parse(searchReq.Query)
if err != nil {
return nil, err
}
return r, r.validate()
}
// createFetchSpansRequest will flatten the SpansetFilter in simple conditions the storage layer
// can work with.
func (e *Engine) createFetchSpansRequest(searchReq *tempopb.SearchRequest, pipeline Pipeline) FetchSpansRequest {
// TODO handle SearchRequest.MinDurationMs and MaxDurationMs, this refers to the trace level duration which is not the same as the intrinsic duration
req := FetchSpansRequest{
StartTimeUnixNanos: unixSecToNano(searchReq.Start),
EndTimeUnixNanos: unixSecToNano(searchReq.End),
Conditions: nil,
AllConditions: true,
}
pipeline.extractConditions(&req)
return req
}
func (e *Engine) asTraceSearchMetadata(spanset *Spanset) *tempopb.TraceSearchMetadata {
metadata := &tempopb.TraceSearchMetadata{
TraceID: util.TraceIDToHexString(spanset.TraceID),
RootServiceName: spanset.RootServiceName,
RootTraceName: spanset.RootSpanName,
StartTimeUnixNano: spanset.StartTimeUnixNanos,
DurationMs: uint32(spanset.DurationNanos / 1_000_000),
SpanSet: &tempopb.SpanSet{},
}
for _, span := range spanset.Spans {
tempopbSpan := &tempopb.Span{
SpanID: util.SpanIDToHexString(span.ID()),
StartTimeUnixNano: span.StartTimeUnixNanos(),
DurationNanos: span.DurationNanos(),
Attributes: nil,
}
atts := span.Attributes()
if name, ok := atts[NewIntrinsic(IntrinsicName)]; ok {
tempopbSpan.Name = name.S
}
for attribute, static := range atts {
if attribute.Intrinsic == IntrinsicName ||
attribute.Intrinsic == IntrinsicDuration ||
attribute.Intrinsic == IntrinsicTraceDuration ||
attribute.Intrinsic == IntrinsicTraceRootService ||
attribute.Intrinsic == IntrinsicTraceRootSpan {
continue
}
staticAnyValue := static.asAnyValue()
keyValue := &common_v1.KeyValue{
Key: attribute.Name,
Value: staticAnyValue,
}
tempopbSpan.Attributes = append(tempopbSpan.Attributes, keyValue)
}
metadata.SpanSet.Spans = append(metadata.SpanSet.Spans, tempopbSpan)
}
// create a new slice and add the spanset to it. eventually we will deprecate
// metadata.SpanSet. populating both the SpanSet and the []SpanSets is for
// backwards compatibility with Grafana. since this method only translates one
// spanset into a TraceSearchMetadata Spansets[0] == Spanset. Higher up the chain
// we will combine Spansets with the same trace id.
metadata.SpanSets = []*tempopb.SpanSet{metadata.SpanSet}
// add attributes
for _, att := range spanset.Attributes {
if att.Name == attributeMatched {
metadata.SpanSet.Matched = uint32(att.Val.N)
continue
}
staticAnyValue := att.Val.asAnyValue()
keyValue := &common_v1.KeyValue{
Key: att.Name,
Value: staticAnyValue,
}
metadata.SpanSet.Attributes = append(metadata.SpanSet.Attributes, keyValue)
}
return metadata
}
func unixSecToNano(ts uint32) uint64 {
return uint64(ts) * uint64(time.Second/time.Nanosecond)
}
func (s Static) asAnyValue() *common_v1.AnyValue {
switch s.Type {
case TypeInt:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_IntValue{
IntValue: int64(s.N),
},
}
case TypeString:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_StringValue{
StringValue: s.S,
},
}
case TypeFloat:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_DoubleValue{
DoubleValue: s.F,
},
}
case TypeBoolean:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_BoolValue{
BoolValue: s.B,
},
}
case TypeDuration:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_StringValue{
StringValue: s.D.String(),
},
}
case TypeStatus:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_StringValue{
StringValue: s.Status.String(),
},
}
case TypeNil:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_StringValue{
StringValue: "nil",
},
}
case TypeKind:
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_StringValue{
StringValue: s.Kind.String(),
},
}
}
return &common_v1.AnyValue{
Value: &common_v1.AnyValue_StringValue{
StringValue: fmt.Sprintf("error formatting val: static has unexpected type %v", s.Type),
},
}
}