-
Notifications
You must be signed in to change notification settings - Fork 488
/
http.go
470 lines (402 loc) · 13.4 KB
/
http.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package api
import (
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-logfmt/logfmt"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/grafana/tempo/pkg/tempopb"
"github.com/grafana/tempo/pkg/util"
"github.com/grafana/tempo/tempodb"
"github.com/grafana/tempo/tempodb/backend"
)
const (
URLParamTraceID = "traceID"
// search
urlParamTags = "tags"
urlParamMinDuration = "minDuration"
urlParamMaxDuration = "maxDuration"
urlParamLimit = "limit"
urlParamStart = "start"
urlParamEnd = "end"
// backend search (querier/serverless)
urlParamStartPage = "startPage"
urlParamPagesToSearch = "pagesToSearch"
urlParamBlockID = "blockID"
urlParamEncoding = "encoding"
urlParamIndexPageSize = "indexPageSize"
urlParamTotalRecords = "totalRecords"
urlParamDataEncoding = "dataEncoding"
urlParamVersion = "version"
urlParamSize = "size"
urlParamFooterSize = "footerSize"
// maxBytes (serverless only)
urlParamMaxBytes = "maxBytes"
HeaderAccept = "Accept"
HeaderContentType = "Content-Type"
HeaderAcceptProtobuf = "application/protobuf"
HeaderAcceptJSON = "application/json"
PathPrefixQuerier = "/querier"
PathTraces = "/api/traces/{traceID}"
PathSearch = "/api/search"
PathSearchTags = "/api/search/tags"
PathSearchTagValues = "/api/search/tag/{tagName}/values"
PathEcho = "/api/echo"
QueryModeKey = "mode"
QueryModeIngesters = "ingesters"
QueryModeBlocks = "blocks"
QueryModeAll = "all"
BlockStartKey = "blockStart"
BlockEndKey = "blockEnd"
defaultLimit = 20
)
func ParseTraceID(r *http.Request) ([]byte, error) {
vars := mux.Vars(r)
traceID, ok := vars[URLParamTraceID]
if !ok {
return nil, fmt.Errorf("please provide a traceID")
}
byteID, err := util.HexStringToTraceID(traceID)
if err != nil {
return nil, err
}
return byteID, nil
}
// ParseSearchRequest takes an http.Request and decodes query params to create a tempopb.SearchRequest
func ParseSearchRequest(r *http.Request) (*tempopb.SearchRequest, error) {
req := &tempopb.SearchRequest{
Tags: map[string]string{},
Limit: defaultLimit,
}
if s, ok := extractQueryParam(r, urlParamStart); ok {
start, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid start: %w", err)
}
req.Start = uint32(start)
}
if s, ok := extractQueryParam(r, urlParamEnd); ok {
end, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid end: %w", err)
}
req.End = uint32(end)
}
encodedTags, tagsFound := extractQueryParam(r, urlParamTags)
// if we have don't have tags and we don't see start or end treat this like an old style search
// if we have no tags but we DO have start/end we have to treat this like a range search with no
// tags specified.
if !tagsFound && req.Start == 0 && req.End == 0 {
// Passing tags as individual query parameters is not supported anymore, clients should use the tags
// query parameter instead. We still parse these tags since the initial Grafana implementation uses this.
// As Grafana gets updated and/or versions using this get old we can remove this section.
for k, v := range r.URL.Query() {
// Skip reserved keywords
if k == urlParamTags || k == urlParamMinDuration || k == urlParamMaxDuration || k == urlParamLimit {
continue
}
if len(v) > 0 && v[0] != "" {
req.Tags[k] = v[0]
}
}
} else {
decoder := logfmt.NewDecoder(strings.NewReader(encodedTags))
for decoder.ScanRecord() {
for decoder.ScanKeyval() {
key := string(decoder.Key())
if _, ok := req.Tags[key]; ok {
return nil, fmt.Errorf("invalid tags: tag %s has been set twice", key)
}
req.Tags[key] = string(decoder.Value())
}
}
if err := decoder.Err(); err != nil {
if syntaxErr, ok := err.(*logfmt.SyntaxError); ok {
return nil, fmt.Errorf("invalid tags: %s at pos %d", syntaxErr.Msg, syntaxErr.Pos)
}
return nil, fmt.Errorf("invalid tags: %w", err)
}
}
if s, ok := extractQueryParam(r, urlParamMinDuration); ok {
dur, err := time.ParseDuration(s)
if err != nil {
return nil, fmt.Errorf("invalid minDuration: %w", err)
}
req.MinDurationMs = uint32(dur.Milliseconds())
}
if s, ok := extractQueryParam(r, urlParamMaxDuration); ok {
dur, err := time.ParseDuration(s)
if err != nil {
return nil, fmt.Errorf("invalid maxDuration: %w", err)
}
req.MaxDurationMs = uint32(dur.Milliseconds())
if req.MinDurationMs != 0 && req.MinDurationMs > req.MaxDurationMs {
return nil, errors.New("invalid maxDuration: must be greater than minDuration")
}
}
if s, ok := extractQueryParam(r, urlParamLimit); ok {
limit, err := strconv.Atoi(s)
if err != nil {
return nil, fmt.Errorf("invalid limit: %w", err)
}
if limit <= 0 {
return nil, errors.New("invalid limit: must be a positive number")
}
req.Limit = uint32(limit)
}
// start and end == 0 is fine
if req.End == 0 && req.Start == 0 {
return req, nil
}
// if start or end are non-zero do some checks
if req.End <= req.Start {
return nil, fmt.Errorf("http parameter start must be before end. received start=%d end=%d", req.Start, req.End)
}
return req, nil
}
// ParseBlockSearchRequest parses all http parameters necessary to perform a block search.
func ParseSearchBlockRequest(r *http.Request) (*tempopb.SearchBlockRequest, error) {
searchReq, err := ParseSearchRequest(r)
if err != nil {
return nil, err
}
// start and end = 0 is NOT fine for a block search request
if searchReq.End == 0 {
return nil, errors.New("start and end required")
}
req := &tempopb.SearchBlockRequest{
SearchReq: searchReq,
}
s := r.URL.Query().Get(urlParamStartPage)
startPage, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid startPage: %w", err)
}
if startPage < 0 {
return nil, fmt.Errorf("startPage must be non-negative. received: %s", s)
}
req.StartPage = uint32(startPage)
s = r.URL.Query().Get(urlParamPagesToSearch)
pagesToSearch64, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid pagesToSearch %s: %w", s, err)
}
if pagesToSearch64 <= 0 {
return nil, fmt.Errorf("pagesToSearch must be greater than 0. received: %s", s)
}
req.PagesToSearch = uint32(pagesToSearch64)
s = r.URL.Query().Get(urlParamBlockID)
blockID, err := uuid.Parse(s)
if err != nil {
return nil, fmt.Errorf("invalid blockID: %w", err)
}
req.BlockID = blockID.String()
s = r.URL.Query().Get(urlParamEncoding)
encoding, err := backend.ParseEncoding(s)
if err != nil {
return nil, err
}
req.Encoding = encoding.String()
s = r.URL.Query().Get(urlParamIndexPageSize)
indexPageSize, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid indexPageSize %s: %w", s, err)
}
req.IndexPageSize = uint32(indexPageSize)
s = r.URL.Query().Get(urlParamTotalRecords)
totalRecords, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid totalRecords %s: %w", s, err)
}
if totalRecords <= 0 {
return nil, fmt.Errorf("totalRecords must be greater than 0. received %d", totalRecords)
}
req.TotalRecords = uint32(totalRecords)
// Data encoding can be blank for some block formats, therefore
// no validation on the param here. Eventually we may be able
// to remove this parameter entirely.
dataEncoding := r.URL.Query().Get(urlParamDataEncoding)
req.DataEncoding = dataEncoding
version := r.URL.Query().Get(urlParamVersion)
if version == "" {
return nil, errors.New("version required")
}
req.Version = version
s = r.URL.Query().Get(urlParamSize)
size, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid size %s: %w", s, err)
}
req.Size_ = size
// Footer size can be 0 for some blocks, just ensure we
// get a valid integer.
f := r.URL.Query().Get(urlParamFooterSize)
footerSize, err := strconv.ParseUint(f, 10, 32)
if err != nil {
return nil, fmt.Errorf("invalid footerSize %s: %w", f, err)
}
req.FooterSize = uint32(footerSize)
return req, nil
}
// BuildSearchRequest takes a tempopb.SearchRequest and populates the passed http.Request
// with the appropriate params. If no http.Request is provided a new one is created.
func BuildSearchRequest(req *http.Request, searchReq *tempopb.SearchRequest) (*http.Request, error) {
if req == nil {
req = &http.Request{
URL: &url.URL{},
}
}
if searchReq == nil {
return req, nil
}
q := req.URL.Query()
q.Set(urlParamStart, strconv.FormatUint(uint64(searchReq.Start), 10))
q.Set(urlParamEnd, strconv.FormatUint(uint64(searchReq.End), 10))
if searchReq.Limit != 0 {
q.Set(urlParamLimit, strconv.FormatUint(uint64(searchReq.Limit), 10))
}
if searchReq.MaxDurationMs != 0 {
q.Set(urlParamMaxDuration, strconv.FormatUint(uint64(searchReq.MaxDurationMs), 10)+"ms")
}
if searchReq.MinDurationMs != 0 {
q.Set(urlParamMinDuration, strconv.FormatUint(uint64(searchReq.MinDurationMs), 10)+"ms")
}
if len(searchReq.Tags) > 0 {
builder := &strings.Builder{}
encoder := logfmt.NewEncoder(builder)
for k, v := range searchReq.Tags {
err := encoder.EncodeKeyval(k, v)
if err != nil {
return nil, err
}
}
q.Set(urlParamTags, builder.String())
}
req.URL.RawQuery = q.Encode()
return req, nil
}
// BuildSearchBlockRequest takes a tempopb.SearchBlockRequest and populates the passed http.Request
// with the appropriate params. If no http.Request is provided a new one is created.
func BuildSearchBlockRequest(req *http.Request, searchReq *tempopb.SearchBlockRequest) (*http.Request, error) {
if req == nil {
req = &http.Request{
URL: &url.URL{},
}
}
req, err := BuildSearchRequest(req, searchReq.SearchReq)
if err != nil {
return nil, err
}
q := req.URL.Query()
q.Set(urlParamSize, strconv.FormatUint(searchReq.Size_, 10))
q.Set(urlParamBlockID, searchReq.BlockID)
q.Set(urlParamStartPage, strconv.FormatUint(uint64(searchReq.StartPage), 10))
q.Set(urlParamPagesToSearch, strconv.FormatUint(uint64(searchReq.PagesToSearch), 10))
q.Set(urlParamEncoding, searchReq.Encoding)
q.Set(urlParamIndexPageSize, strconv.FormatUint(uint64(searchReq.IndexPageSize), 10))
q.Set(urlParamTotalRecords, strconv.FormatUint(uint64(searchReq.TotalRecords), 10))
q.Set(urlParamDataEncoding, searchReq.DataEncoding)
q.Set(urlParamVersion, searchReq.Version)
q.Set(urlParamFooterSize, strconv.FormatUint(uint64(searchReq.FooterSize), 10))
req.URL.RawQuery = q.Encode()
return req, nil
}
// AddServerlessParams takes an already existing http.Request and adds maxBytes
// to it
func AddServerlessParams(req *http.Request, maxBytes int) *http.Request {
if req == nil {
req = &http.Request{
URL: &url.URL{},
}
}
q := req.URL.Query()
q.Set(urlParamMaxBytes, strconv.FormatInt(int64(maxBytes), 10))
req.URL.RawQuery = q.Encode()
return req
}
// ExtractServerlessParams extracts params for the serverless functions from
// an http.Request
func ExtractServerlessParams(req *http.Request) (int, error) {
s, exists := extractQueryParam(req, urlParamMaxBytes)
if !exists {
return 0, nil
}
maxBytes, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return 0, fmt.Errorf("invalid maxBytes: %w", err)
}
return int(maxBytes), nil
}
func extractQueryParam(r *http.Request, param string) (string, bool) {
value := r.URL.Query().Get(param)
return value, value != ""
}
// ValidateAndSanitizeRequest validates params for trace by id api
// return values are (blockStart, blockEnd, queryMode, start, end, error)
func ValidateAndSanitizeRequest(r *http.Request) (string, string, string, int64, int64, error) {
q, _ := extractQueryParam(r, QueryModeKey)
// validate queryMode. it should either be empty or one of (QueryModeIngesters|QueryModeBlocks|QueryModeAll)
var queryMode string
var startTime int64
var endTime int64
var blockStart string
var blockEnd string
if len(q) == 0 || q == QueryModeAll {
queryMode = QueryModeAll
} else if q == QueryModeIngesters {
queryMode = QueryModeIngesters
} else if q == QueryModeBlocks {
queryMode = QueryModeBlocks
} else {
return "", "", "", 0, 0, fmt.Errorf("invalid value for mode %s", q)
}
// no need to validate/sanitize other parameters if queryMode == QueryModeIngesters
if queryMode == QueryModeIngesters {
return "", "", queryMode, 0, 0, nil
}
if start, ok := extractQueryParam(r, BlockStartKey); ok {
_, err := uuid.Parse(start)
if err != nil {
return "", "", "", 0, 0, fmt.Errorf("invalid value for blockstart: %w", err)
}
blockStart = start
} else {
blockStart = tempodb.BlockIDMin
}
if end, ok := extractQueryParam(r, BlockEndKey); ok {
_, err := uuid.Parse(end)
if err != nil {
return "", "", "", 0, 0, fmt.Errorf("invalid value for blockEnd: %w", err)
}
blockEnd = end
} else {
blockEnd = tempodb.BlockIDMax
}
if s, ok := extractQueryParam(r, urlParamStart); ok {
var err error
startTime, err = strconv.ParseInt(s, 10, 64)
if err != nil {
return "", "", "", 0, 0, fmt.Errorf("invalid start: %w", err)
}
} else {
startTime = 0
}
if s, ok := extractQueryParam(r, urlParamEnd); ok {
var err error
endTime, err = strconv.ParseInt(s, 10, 64)
if err != nil {
return "", "", "", 0, 0, fmt.Errorf("invalid end: %w", err)
}
} else {
endTime = 0
}
if startTime != 0 && endTime != 0 && endTime <= startTime {
return "", "", "", 0, 0, fmt.Errorf("http parameter start must be before end. received start=%d end=%d", startTime, endTime)
}
return blockStart, blockEnd, queryMode, startTime, endTime, nil
}