-
Notifications
You must be signed in to change notification settings - Fork 3
/
tempohandler.go
311 lines (274 loc) · 8.08 KB
/
tempohandler.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
// Package tempohandler provides Tempo API implementation.
package tempohandler
import (
"bytes"
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-logfmt/logfmt"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
"go.uber.org/zap"
"github.com/go-faster/errors"
"github.com/go-faster/sdk/zctx"
"github.com/go-faster/oteldb/internal/iterators"
"github.com/go-faster/oteldb/internal/otelstorage"
"github.com/go-faster/oteldb/internal/tempoapi"
"github.com/go-faster/oteldb/internal/traceql/traceqlengine"
"github.com/go-faster/oteldb/internal/tracestorage"
)
var _ tempoapi.Handler = (*TempoAPI)(nil)
// TempoAPI implements tempoapi.Handler.
type TempoAPI struct {
q tracestorage.Querier
engine *traceqlengine.Engine
}
// NewTempoAPI creates new TempoAPI.
func NewTempoAPI(q tracestorage.Querier, engine *traceqlengine.Engine) *TempoAPI {
return &TempoAPI{
q: q,
engine: engine,
}
}
// Echo request for testing, issued by Grafana.
//
// GET /api/echo
func (h *TempoAPI) Echo(_ context.Context) (tempoapi.EchoOK, error) {
return tempoapi.EchoOK{Data: strings.NewReader("echo")}, nil
}
// Search implements search operation.
// Execute TraceQL query.
//
// GET /api/search
func (h *TempoAPI) Search(ctx context.Context, params tempoapi.SearchParams) (resp *tempoapi.Traces, _ error) {
var (
traceQLQuery = params.Q.Value
logfmtQuery = params.Tags.Value
)
ctx = zctx.With(ctx,
zap.String("q", traceQLQuery),
zap.String("tags", logfmtQuery),
)
switch {
case traceQLQuery != "":
return h.searchTraceQL(ctx, traceQLQuery, params)
case logfmtQuery != "":
return h.searchTags(ctx, logfmtQuery, params)
default:
return nil, &tempoapi.ErrorStatusCode{
StatusCode: http.StatusBadRequest,
Response: `either of parameters "q" and "tags" should be set`,
}
}
}
func (h *TempoAPI) searchTraceQL(ctx context.Context, query string, params tempoapi.SearchParams) (resp *tempoapi.Traces, _ error) {
if h.engine == nil {
return nil, &tempoapi.ErrorStatusCode{
StatusCode: http.StatusInternalServerError,
Response: "TraceQL engine is disabled",
}
}
return h.engine.Eval(ctx, query, traceqlengine.EvalParams{
MinDuration: params.MinDuration.Or(0),
MaxDuration: params.MinDuration.Or(0),
Start: timeToTimestamp(params.Start),
End: timeToTimestamp(params.End),
Limit: params.Limit.Or(20),
})
}
func (h *TempoAPI) searchTags(ctx context.Context, query string, params tempoapi.SearchParams) (resp *tempoapi.Traces, _ error) {
tags, err := parseLogfmt(query)
if err != nil {
return nil, &tempoapi.ErrorStatusCode{
StatusCode: http.StatusBadRequest,
Response: tempoapi.Error(fmt.Sprintf("parse logfmt: %s", err)),
}
}
i, err := h.q.SearchTags(ctx, tags, tracestorage.SearchTagsOptions{
MinDuration: params.MinDuration.Or(0),
MaxDuration: params.MaxDuration.Or(0),
Start: timeToTimestamp(params.Start),
End: timeToTimestamp(params.End),
})
if err != nil {
return nil, errors.Wrap(err, "search tags")
}
defer func() {
_ = i.Close()
}()
c := metadataCollector{
limit: params.Limit.Or(20),
}
if err := iterators.ForEach(i, c.AddSpan); err != nil {
return nil, errors.Wrap(err, "map spans")
}
return &tempoapi.Traces{
Traces: c.Result(),
}, nil
}
func parseLogfmt(q string) (tags map[string]string, _ error) {
tags = make(map[string]string)
d := logfmt.NewDecoder(strings.NewReader(q))
for d.ScanRecord() {
for d.ScanKeyval() {
// TODO(tdakkota): bruh allocations
tags[string(d.Key())] = string(d.Value())
}
}
if err := d.Err(); err != nil {
return nil, err
}
return tags, nil
}
// SearchTagValues implements search_tag_values operation.
//
// This endpoint retrieves all discovered values for the given tag, which can be used in search.
//
// GET /api/search/tag/{tag_name}/values
func (h *TempoAPI) SearchTagValues(ctx context.Context, params tempoapi.SearchTagValuesParams) (resp *tempoapi.TagValues, _ error) {
lg := zctx.From(ctx)
iter, err := h.q.TagValues(ctx, params.TagName)
if err != nil {
return nil, errors.Wrap(err, "query")
}
defer func() {
_ = iter.Close()
}()
var values []string
if err := iterators.ForEach(iter, func(tag tracestorage.Tag) error {
values = append(values, tag.Value)
return nil
}); err != nil {
return nil, errors.Wrap(err, "map tags")
}
lg.Debug("Got tag values",
zap.String("tag_name", params.TagName),
zap.Int("count", len(values)),
)
return &tempoapi.TagValues{
TagValues: values,
}, nil
}
// SearchTagValuesV2 implements search_tag_values_v2 operation.
//
// This endpoint retrieves all discovered values and their data types for the given TraceQL
// identifier.
//
// GET /api/v2/search/tag/{tag_name}/values
func (h *TempoAPI) SearchTagValuesV2(ctx context.Context, params tempoapi.SearchTagValuesV2Params) (resp *tempoapi.TagValuesV2, _ error) {
lg := zctx.From(ctx)
iter, err := h.q.TagValues(ctx, params.TagName)
if err != nil {
return nil, errors.Wrap(err, "query")
}
defer func() {
_ = iter.Close()
}()
var values []tempoapi.TagValue
if err := iterators.ForEach(iter, func(tag tracestorage.Tag) error {
// TODO(tdakkota): handle duration/status and things
// https://github.com/grafana/tempo/blob/991d72281e5168080f426b3f1c9d5c4b88f7c460/modules/ingester/instance_search.go#L379
var typ string
switch pcommon.ValueType(tag.Type) {
case pcommon.ValueTypeStr:
typ = "string"
case pcommon.ValueTypeInt:
typ = "int"
case pcommon.ValueTypeDouble:
typ = "float"
case pcommon.ValueTypeBool:
typ = "bool"
case pcommon.ValueTypeBytes:
typ = "string"
case pcommon.ValueTypeMap, pcommon.ValueTypeSlice:
// what?
return nil
}
values = append(values, tempoapi.TagValue{
Type: typ,
Value: tag.Value,
})
return nil
}); err != nil {
return nil, errors.Wrap(err, "map tags")
}
lg.Debug("Got tag types and values",
zap.String("tag_name", params.TagName),
zap.Int("count", len(values)),
)
return &tempoapi.TagValuesV2{
TagValues: values,
}, nil
}
// SearchTags implements search_tags operation.
//
// This endpoint retrieves all discovered tag names that can be used in search.
//
// GET /api/search/tags
func (h *TempoAPI) SearchTags(ctx context.Context) (resp *tempoapi.TagNames, _ error) {
lg := zctx.From(ctx)
names, err := h.q.TagNames(ctx)
if err != nil {
return nil, errors.Wrap(err, "query")
}
lg.Debug("Got tag names", zap.Int("count", len(names)))
return &tempoapi.TagNames{
TagNames: names,
}, nil
}
// TraceByID implements traceByID operation.
//
// Querying traces by id.
//
// GET /api/traces/{traceID}
func (h *TempoAPI) TraceByID(ctx context.Context, params tempoapi.TraceByIDParams) (resp tempoapi.TraceByIDRes, _ error) {
lg := zctx.From(ctx)
traceID, err := otelstorage.ParseTraceID(params.TraceID)
if err != nil {
return nil, errors.Wrapf(err, "invalid traceID %q", params.TraceID)
}
iter, err := h.q.TraceByID(ctx, traceID, tracestorage.TraceByIDOptions{
Start: timeToTimestamp(params.Start),
End: timeToTimestamp(params.End),
})
if err != nil {
return nil, errors.Wrap(err, "query traceID")
}
defer func() {
_ = iter.Close()
}()
var c batchCollector
if err := iterators.ForEach(iter, c.AddSpan); err != nil {
return nil, errors.Wrap(err, "map spans")
}
traces := c.Result()
spanCount := traces.SpanCount()
lg.Debug("Got trace by ID", zap.Int("span_count", spanCount))
if spanCount < 1 {
return &tempoapi.TraceByIDNotFound{}, nil
}
m := ptrace.ProtoMarshaler{}
data, err := m.MarshalTraces(traces)
if err != nil {
return resp, errors.Wrap(err, "marshal traces")
}
return &tempoapi.TraceByID{Data: bytes.NewReader(data)}, nil
}
// NewError creates *ErrorStatusCode from error returned by handler.
//
// Used for common default response.
func (h *TempoAPI) NewError(_ context.Context, err error) *tempoapi.ErrorStatusCode {
return &tempoapi.ErrorStatusCode{
StatusCode: http.StatusBadRequest,
Response: tempoapi.Error(err.Error()),
}
}
func timeToTimestamp[O interface{ Get() (time.Time, bool) }](o O) otelstorage.Timestamp {
t, ok := o.Get()
if !ok {
return 0
}
return otelstorage.NewTimestampFromTime(t)
}