-
Notifications
You must be signed in to change notification settings - Fork 693
Expand file tree
/
Copy pathblock_findtracebyid.go
More file actions
306 lines (259 loc) · 8.46 KB
/
block_findtracebyid.go
File metadata and controls
306 lines (259 loc) · 8.46 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
package vparquet4
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"github.com/bits-and-blooms/bloom/v3"
"github.com/google/uuid"
"github.com/parquet-go/parquet-go"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/grafana/tempo/pkg/cache"
"github.com/grafana/tempo/pkg/parquetquery"
"github.com/grafana/tempo/pkg/tempopb"
"github.com/grafana/tempo/pkg/util"
"github.com/grafana/tempo/tempodb/backend"
"github.com/grafana/tempo/tempodb/encoding/common"
)
const (
SearchPrevious = -1
SearchNext = -2
NotFound = -3
TraceIDColumnName = "TraceID"
EnvVarIndexName = "VPARQUET_INDEX"
EnvVarIndexEnabledValue = "1"
)
func (b *backendBlock) checkBloom(ctx context.Context, id common.ID) (found bool, err error) {
derivedCtx, span := tracer.Start(ctx, "parquet.backendBlock.checkBloom",
trace.WithAttributes(
attribute.String("blockID", b.meta.BlockID.String()),
attribute.String("tenantID", b.meta.TenantID),
))
defer span.End()
shardKey := common.ShardKeyForTraceID(id, int(b.meta.BloomShardCount))
nameBloom := common.BloomName(shardKey)
span.SetAttributes(attribute.String("bloom", nameBloom))
bloomBytes, err := b.r.Read(derivedCtx, nameBloom, (uuid.UUID)(b.meta.BlockID), b.meta.TenantID, &backend.CacheInfo{
Meta: b.meta,
Role: cache.RoleBloom,
})
if err != nil {
return false, fmt.Errorf("error retrieving bloom %s (%s, %s): %w", nameBloom, b.meta.TenantID, b.meta.BlockID, err)
}
filter := &bloom.BloomFilter{}
_, err = filter.ReadFrom(bytes.NewReader(bloomBytes))
if err != nil {
return false, fmt.Errorf("error parsing bloom (%s, %s): %w", b.meta.TenantID, b.meta.BlockID, err)
}
return filter.Test(id), nil
}
func (b *backendBlock) checkIndex(ctx context.Context, id common.ID) (bool, int, error) {
if os.Getenv(EnvVarIndexName) != EnvVarIndexEnabledValue {
// Index lookup disabled
return true, -1, nil
}
derivedCtx, span := tracer.Start(ctx, "parquet4.backendBlock.checkIndex",
trace.WithAttributes(
attribute.String("blockID", b.meta.BlockID.String()),
attribute.String("tenantID", b.meta.TenantID),
))
defer span.End()
indexBytes, err := b.r.Read(derivedCtx, common.NameIndex, (uuid.UUID)(b.meta.BlockID), b.meta.TenantID, &backend.CacheInfo{
Meta: b.meta,
Role: cache.RoleTraceIDIdx,
})
if errors.Is(err, backend.ErrDoesNotExist) {
return true, -1, nil
}
if err != nil {
return false, -1, fmt.Errorf("error retrieving index (%s, %s): %w", b.meta.TenantID, b.meta.BlockID, err)
}
index, err := unmarshalIndex(indexBytes)
if err != nil {
return false, -1, fmt.Errorf("error parsing index (%s, %s): %w", b.meta.TenantID, b.meta.BlockID, err)
}
rowGroup := index.Find(id)
if rowGroup == -1 {
// Ruled out by index
return false, -1, nil
}
return true, rowGroup, nil
}
func (b *backendBlock) FindTraceByID(ctx context.Context, traceID common.ID, opts common.SearchOptions) (_ *tempopb.TraceByIDResponse, err error) {
derivedCtx, span := tracer.Start(ctx, "parquet.backendBlock.FindTraceByID",
trace.WithAttributes(
attribute.String("blockID", b.meta.BlockID.String()),
attribute.String("tenantID", b.meta.TenantID),
attribute.Int64("blockSize", int64(b.meta.Size_)),
))
defer span.End()
found, err := b.checkBloom(derivedCtx, traceID)
if err != nil {
return nil, err
}
if !found {
return nil, nil
}
ok, rowGroup, err := b.checkIndex(derivedCtx, traceID)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
pf, rr, err := b.openForSearch(derivedCtx, opts)
if err != nil {
return nil, fmt.Errorf("unexpected error opening parquet file: %w", err)
}
foundTrace, err := findTraceByID(derivedCtx, traceID, b.meta, pf, rowGroup)
result := &tempopb.TraceByIDResponse{
Trace: foundTrace,
Metrics: &tempopb.TraceByIDMetrics{},
}
bytesRead := rr.BytesRead()
result.Metrics.InspectedBytes += bytesRead
span.SetAttributes(attribute.Int64("inspectedBytes", int64(bytesRead)))
return result, err
}
func findTraceByID(ctx context.Context, traceID common.ID, meta *backend.BlockMeta, pf *parquet.File, rowGroup int) (*tempopb.Trace, error) {
// traceID column index
colIndex, _, maxDef := parquetquery.GetColumnIndexByPath(pf, TraceIDColumnName)
if colIndex == -1 {
return nil, fmt.Errorf("unable to get index for column: %s", TraceIDColumnName)
}
// If no index then fallback to binary searching the rowgroups.
if rowGroup == -1 {
var (
numRowGroups = len(pf.RowGroups())
buf = make(parquet.Row, 1)
err error
)
// Cache of row group bounds
rowGroupMins := make([]common.ID, numRowGroups+1)
// todo: restore using meta min/max id once it works
// https://github.com/grafana/tempo/issues/1903
rowGroupMins[0] = bytes.Repeat([]byte{0}, 16)
rowGroupMins[numRowGroups] = bytes.Repeat([]byte{255}, 16) // This is actually inclusive and the logic is special for the last row group below
// Gets the minimum trace ID within the row group. Since the column is sorted
// ascending we just read the first value from the first page.
getRowGroupMin := func(rgIdx int) (common.ID, error) {
minID := rowGroupMins[rgIdx]
if len(minID) > 0 {
// Already loaded
return minID, nil
}
pages := pf.RowGroups()[rgIdx].ColumnChunks()[colIndex].Pages()
defer pages.Close()
page, err := pages.ReadPage()
if err != nil {
return nil, err
}
defer parquet.Release(page)
c, err := page.Values().ReadValues(buf)
if err != nil && !errors.Is(err, io.EOF) {
return nil, err
}
if c < 1 {
return nil, fmt.Errorf("failed to read value from page: traceID: %s blockID:%v rowGroupIdx:%d", util.TraceIDToHexString(traceID), meta.BlockID, rgIdx)
}
// Clone ensures that the byte array is disconnected
// from the underlying i/o buffers.
minID = buf[0].Clone().ByteArray()
rowGroupMins[rgIdx] = minID
return minID, nil
}
rowGroup, err = binarySearch(numRowGroups, func(rgIdx int) (int, error) {
minID, err := getRowGroupMin(rgIdx)
if err != nil {
return 0, err
}
if check := bytes.Compare(traceID, minID); check <= 0 {
// Trace is before or in this group
return check, nil
}
maxID, err := getRowGroupMin(rgIdx + 1)
if err != nil {
return 0, err
}
// This is actually the min of the next group, so check is exclusive not inclusive like min
// Except for the last group, it is inclusive
check := bytes.Compare(traceID, maxID)
if check > 0 || (check == 0 && rgIdx < (numRowGroups-1)) {
// Trace is after this group
return 1, nil
}
// Must be in this group
return 0, nil
})
if err != nil {
return nil, fmt.Errorf("error binary searching row groups: %w", err)
}
}
if rowGroup == -1 {
// Not within the bounds of any row group
return nil, nil
}
// Now iterate the matching row group
iter := parquetquery.NewSyncIterator(ctx, pf.RowGroups()[rowGroup:rowGroup+1], colIndex,
parquetquery.SyncIteratorOptPredicate(parquetquery.NewStringInPredicate([]string{string(traceID)})),
parquetquery.SyncIteratorOptMaxDefinitionLevel(maxDef),
)
defer iter.Close()
res, err := iter.Next()
if err != nil {
return nil, err
}
if res == nil {
// TraceID not found in this block
return nil, nil
}
// The row number coming out of the iterator is relative,
// so offset it using the num rows in all previous groups
rowMatch := int64(0)
for _, rg := range pf.RowGroups()[0:rowGroup] {
rowMatch += rg.NumRows()
}
rowMatch += int64(res.RowNumber[0])
// seek to row and read
r := parquet.NewGenericReader[*Trace](pf)
defer r.Close()
err = r.SeekToRow(rowMatch)
if err != nil {
return nil, fmt.Errorf("seek to row: %w", err)
}
tr := new(Trace)
_, err = r.Read([]*Trace{tr})
if err != nil && !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("error reading row from backend: %w", err)
}
// convert to proto trace and return
return ParquetTraceToTempopbTrace(meta, tr), nil
}
// binarySearch that finds exact matching entry. Returns non-zero index when found, or -1 when not found
// Inspired by sort.Search but makes uses of tri-state comparator to eliminate the last comparison when
// we want to find exact match, not insertion point.
func binarySearch(n int, compare func(int) (int, error)) (int, error) {
i, j := 0, n
for i < j {
h := int(uint(i+j) >> 1) // avoid overflow when computing h
c, err := compare(h)
if err != nil {
return -1, err
}
// i ≤ h < j
switch c {
case 0:
// Found exact match
return h, nil
case -1:
j = h
case 1:
i = h + 1
}
}
// No match
return -1, nil
}