-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathquery.go
496 lines (434 loc) · 11.4 KB
/
query.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package loghttp
import (
"errors"
"fmt"
"net/http"
"time"
"unsafe"
"github.com/grafana/loki/pkg/storage/stores/index/seriesvolume"
"github.com/buger/jsonparser"
json "github.com/json-iterator/go"
"github.com/prometheus/common/model"
"github.com/grafana/loki/pkg/logproto"
"github.com/grafana/loki/pkg/logqlmodel/stats"
)
var (
errEndBeforeStart = errors.New("end timestamp must not be before or equal to start time")
errNegativeStep = errors.New("zero or negative query resolution step widths are not accepted. Try a positive integer")
errStepTooSmall = errors.New("exceeded maximum resolution of 11,000 points per time series. Try increasing the value of the step parameter")
errNegativeInterval = errors.New("interval must be >= 0")
)
// QueryStatus holds the status of a query
type QueryStatus string
// QueryStatus values
const (
QueryStatusSuccess = "success"
QueryStatusFail = "fail"
)
// QueryResponse represents the http json response to a Loki range and instant query
type QueryResponse struct {
Status string `json:"status"`
Data QueryResponseData `json:"data"`
}
func (q *QueryResponse) UnmarshalJSON(data []byte) error {
return jsonparser.ObjectEach(data, func(key, value []byte, dataType jsonparser.ValueType, offset int) error {
switch string(key) {
case "status":
q.Status = string(value)
case "data":
var responseData QueryResponseData
if err := responseData.UnmarshalJSON(value); err != nil {
return err
}
q.Data = responseData
}
return nil
})
}
// PushRequest models a log stream push but is unmarshalled to proto push format.
type PushRequest struct {
Streams []LogProtoStream `json:"streams"`
}
// LogProtoStream helps with unmarshalling of each log stream for push request.
// This might look un-necessary but without it the CPU usage in benchmarks was increasing by ~25% :shrug:
type LogProtoStream struct {
logproto.Stream
}
func (s *LogProtoStream) UnmarshalJSON(data []byte) error {
err := jsonparser.ObjectEach(data, func(key, val []byte, ty jsonparser.ValueType, _ int) error {
switch string(key) {
case "stream":
labels := make(LabelSet)
err := jsonparser.ObjectEach(val, func(key, val []byte, _ jsonparser.ValueType, _ int) error {
labels[yoloString(key)] = yoloString(val)
return nil
})
if err != nil {
return err
}
s.Labels = labels.String()
case "values":
if ty == jsonparser.Null {
return nil
}
entries, err := unmarshalHTTPToLogProtoEntries(val)
if err != nil {
return err
}
s.Entries = entries
}
return nil
})
return err
}
func unmarshalHTTPToLogProtoEntries(data []byte) ([]logproto.Entry, error) {
var (
entries []logproto.Entry
parseError error
)
_, err := jsonparser.ArrayEach(data, func(value []byte, ty jsonparser.ValueType, _ int, err error) {
if err != nil || parseError != nil {
return
}
if ty == jsonparser.Null {
return
}
e, err := unmarshalHTTPToLogProtoEntry(value)
if err != nil {
parseError = err
return
}
entries = append(entries, e)
})
if parseError != nil {
return nil, parseError
}
if err != nil {
return nil, parseError
}
return entries, nil
}
func unmarshalHTTPToLogProtoEntry(data []byte) (logproto.Entry, error) {
var (
i int
parseError error
e logproto.Entry
)
_, err := jsonparser.ArrayEach(data, func(value []byte, t jsonparser.ValueType, _ int, _ error) {
// assert that both items in array are of type string
if (i == 0 || i == 1) && t != jsonparser.String {
parseError = jsonparser.MalformedStringError
return
} else if i == 2 && t != jsonparser.Object {
parseError = jsonparser.MalformedObjectError
return
}
switch i {
case 0: // timestamp
ts, err := jsonparser.ParseInt(value)
if err != nil {
parseError = err
return
}
e.Timestamp = time.Unix(0, ts)
case 1: // value
v, err := jsonparser.ParseString(value)
if err != nil {
parseError = err
return
}
e.Line = v
case 2: // labels
labels := make(LabelSet)
err := jsonparser.ObjectEach(value, func(key, val []byte, _ jsonparser.ValueType, _ int) error {
labels[yoloString(key)] = yoloString(val)
return nil
})
if err != nil {
parseError = err
return
}
e.Labels = labels.String()
}
i++
})
if parseError != nil {
return e, parseError
}
return e, err
}
// ResultType holds the type of the result
type ResultType string
// ResultType values
const (
ResultTypeStream = "streams"
ResultTypeScalar = "scalar"
ResultTypeVector = "vector"
ResultTypeMatrix = "matrix"
)
// ResultValue interface mimics the promql.Value interface
type ResultValue interface {
Type() ResultType
}
// QueryResponseData represents the http json response to a label query
type QueryResponseData struct {
ResultType ResultType `json:"resultType"`
Result ResultValue `json:"result"`
Statistics stats.Result `json:"stats"`
}
// Type implements the promql.Value interface
func (Streams) Type() ResultType { return ResultTypeStream }
// Type implements the promql.Value interface
func (Scalar) Type() ResultType { return ResultTypeScalar }
// Type implements the promql.Value interface
func (Vector) Type() ResultType { return ResultTypeVector }
// Type implements the promql.Value interface
func (Matrix) Type() ResultType { return ResultTypeMatrix }
// Streams is a slice of Stream
type Streams []Stream
func (ss *Streams) UnmarshalJSON(data []byte) error {
var parseError error
_, err := jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
var stream Stream
if err := stream.UnmarshalJSON(value); err != nil {
parseError = err
return
}
*ss = append(*ss, stream)
})
if parseError != nil {
return parseError
}
return err
}
func (s Streams) ToProto() []logproto.Stream {
if len(s) == 0 {
return nil
}
result := make([]logproto.Stream, 0, len(s))
for _, s := range s {
entries := *(*[]logproto.Entry)(unsafe.Pointer(&s.Entries))
result = append(result, logproto.Stream{Labels: s.Labels.String(), Entries: entries})
}
return result
}
// Stream represents a log stream. It includes a set of log entries and their labels.
type Stream struct {
Labels LabelSet `json:"stream"`
Entries []Entry `json:"values"`
}
func (s *Stream) UnmarshalJSON(data []byte) error {
if s.Labels == nil {
s.Labels = LabelSet{}
}
if len(s.Entries) > 0 {
s.Entries = s.Entries[:0]
}
return jsonparser.ObjectEach(data, func(key, value []byte, ty jsonparser.ValueType, _ int) error {
switch string(key) {
case "stream":
if err := s.Labels.UnmarshalJSON(value); err != nil {
return err
}
case "values":
if ty == jsonparser.Null {
return nil
}
var parseError error
_, err := jsonparser.ArrayEach(value, func(value []byte, ty jsonparser.ValueType, _ int, _ error) {
if ty == jsonparser.Null {
return
}
var entry Entry
if err := entry.UnmarshalJSON(value); err != nil {
parseError = err
return
}
s.Entries = append(s.Entries, entry)
})
if parseError != nil {
return parseError
}
return err
}
return nil
})
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (q *QueryResponseData) UnmarshalJSON(data []byte) error {
resultType, err := jsonparser.GetString(data, "resultType")
if err != nil {
return err
}
q.ResultType = ResultType(resultType)
return jsonparser.ObjectEach(data, func(key, value []byte, dataType jsonparser.ValueType, _ int) error {
switch string(key) {
case "result":
switch q.ResultType {
case ResultTypeStream:
ss := Streams{}
if err := ss.UnmarshalJSON(value); err != nil {
return err
}
q.Result = ss
case ResultTypeMatrix:
var m Matrix
if err = json.Unmarshal(value, &m); err != nil {
return err
}
q.Result = m
case ResultTypeVector:
var v Vector
if err = json.Unmarshal(value, &v); err != nil {
return err
}
q.Result = v
case ResultTypeScalar:
var v Scalar
if err = json.Unmarshal(value, &v); err != nil {
return err
}
q.Result = v
default:
return fmt.Errorf("unknown type: %s", q.ResultType)
}
case "stats":
if err := json.Unmarshal(value, &q.Statistics); err != nil {
return err
}
}
return nil
})
}
// Scalar is a single timestamp/float with no labels
type Scalar model.Scalar
func (s Scalar) MarshalJSON() ([]byte, error) {
return model.Scalar(s).MarshalJSON()
}
func (s *Scalar) UnmarshalJSON(b []byte) error {
var v model.Scalar
if err := v.UnmarshalJSON(b); err != nil {
return err
}
*s = Scalar(v)
return nil
}
// Vector is a slice of Samples
type Vector []model.Sample
// Matrix is a slice of SampleStreams
type Matrix []model.SampleStream
// InstantQuery defines a log instant query.
type InstantQuery struct {
Query string
Ts time.Time
Limit uint32
Direction logproto.Direction
Shards []string
}
// ParseInstantQuery parses an InstantQuery request from an http request.
func ParseInstantQuery(r *http.Request) (*InstantQuery, error) {
var err error
request := &InstantQuery{
Query: query(r),
}
request.Limit, err = limit(r)
if err != nil {
return nil, err
}
request.Ts, err = ts(r)
if err != nil {
return nil, err
}
request.Shards = shards(r)
request.Direction, err = direction(r)
if err != nil {
return nil, err
}
return request, nil
}
// RangeQuery defines a log range query.
type RangeQuery struct {
Start time.Time
End time.Time
Step time.Duration
Interval time.Duration
Query string
Direction logproto.Direction
Limit uint32
Shards []string
}
// ParseRangeQuery parses a RangeQuery request from an http request.
func ParseRangeQuery(r *http.Request) (*RangeQuery, error) {
var result RangeQuery
var err error
result.Query = query(r)
result.Start, result.End, err = bounds(r)
if err != nil {
return nil, err
}
if result.End.Before(result.Start) {
return nil, errEndBeforeStart
}
result.Limit, err = limit(r)
if err != nil {
return nil, err
}
result.Direction, err = direction(r)
if err != nil {
return nil, err
}
result.Step, err = step(r, result.Start, result.End)
if err != nil {
return nil, err
}
if result.Step <= 0 {
return nil, errNegativeStep
}
result.Shards = shards(r)
// For safety, limit the number of returned points per timeseries.
// This is sufficient for 60s resolution for a week or 1h resolution for a year.
if (result.End.Sub(result.Start) / result.Step) > 11000 {
return nil, errStepTooSmall
}
result.Interval, err = interval(r)
if err != nil {
return nil, err
}
if result.Interval < 0 {
return nil, errNegativeInterval
}
return &result, nil
}
func ParseIndexStatsQuery(r *http.Request) (*RangeQuery, error) {
// TODO(owen-d): use a specific type/validation instead
// of using range query parameters (superset)
return ParseRangeQuery(r)
}
func ParseSeriesVolumeQuery(r *http.Request) (*RangeQuery, error) {
err := labelVolumeLimit(r)
if err != nil {
return nil, err
}
result, err := ParseRangeQuery(r)
if err != nil {
return nil, err
}
return result, nil
}
func labelVolumeLimit(r *http.Request) error {
l, err := parseInt(r.Form.Get("limit"), seriesvolume.DefaultLimit)
if err != nil {
return err
}
if l == 0 {
r.Form.Set("limit", fmt.Sprint(seriesvolume.DefaultLimit))
return nil
}
if l <= 0 {
return errors.New("limit must be a positive value")
}
return nil
}
func yoloString(buf []byte) string {
return *((*string)(unsafe.Pointer(&buf)))
}