This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
parse.go
478 lines (393 loc) · 10.9 KB
/
parse.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
package expr
import (
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/grafana/metrictank/api/models"
"github.com/grafana/metrictank/errors"
"github.com/grafana/metrictank/util"
log "github.com/sirupsen/logrus"
)
var (
ErrMissingArg = errors.NewBadRequest("argument missing")
ErrTooManyArg = errors.NewBadRequest("too many arguments")
ErrMissingTimeseries = errors.NewBadRequest("missing time series argument")
ErrWildcardNotAllowed = errors.NewBadRequest("found wildcard where series expected")
ErrMissingExpr = errors.NewBadRequest("missing expression")
ErrMissingComma = errors.NewBadRequest("missing comma")
ErrMissingQuote = errors.NewBadRequest("missing quote")
ErrUnexpectedCharacter = errors.NewBadRequest("unexpected character")
ErrIllegalCharacter = errors.NewBadRequest("illegal character for function name")
)
type ErrBadArgument struct {
exp reflect.Type
got reflect.Type
}
func (e ErrBadArgument) Error() string {
return fmt.Sprintf("argument bad type. expected %s - got %s", e.exp, e.got)
}
func (e ErrBadArgument) HTTPStatusCode() int {
return http.StatusBadRequest
}
type ErrBadArgumentStr struct {
exp string
got string
}
func (e ErrBadArgumentStr) Error() string {
return fmt.Sprintf("argument bad type. expected %s - got %s", e.exp, e.got)
}
func (e ErrBadArgumentStr) HTTPStatusCode() int {
return http.StatusBadRequest
}
type ErrBadRegex struct {
error
}
func (e ErrBadRegex) HTTPStatusCode() int {
return http.StatusBadRequest
}
type ErrUnknownFunction string
func (e ErrUnknownFunction) Error() string {
return fmt.Sprintf("unknown function %q", string(e))
}
func (e ErrUnknownFunction) HTTPStatusCode() int {
return http.StatusBadRequest
}
type ErrUnknownKwarg struct {
key string
}
func (e ErrUnknownKwarg) Error() string {
return fmt.Sprintf("unknown keyword argument %q", e.key)
}
func (e ErrUnknownKwarg) HTTPStatusCode() int {
return http.StatusBadRequest
}
type ErrBadKwarg struct {
key string
exp Arg
got exprType
}
func (e ErrBadKwarg) Error() string {
return fmt.Sprintf("keyword argument %q bad type. expected %T - got %s", e.key, e.exp, e.got)
}
func (e ErrBadKwarg) HTTPStatusCode() int {
return http.StatusBadRequest
}
type ErrKwargSpecifiedTwice struct {
key string
}
func (e ErrKwargSpecifiedTwice) Error() string {
return fmt.Sprintf("keyword argument %q specified twice", e.key)
}
func (e ErrKwargSpecifiedTwice) HTTPStatusCode() int {
return http.StatusBadRequest
}
type MetricRequest struct {
Metric string
From int32
Until int32
}
// ParseMany parses a slice of strings into a slice of expressions (recursively)
// not included: validation that requested functions exist, correct args are passed, etc.
func ParseMany(targets []string) ([]*expr, error) {
var out []*expr
for _, target := range targets {
e, leftover, err := Parse(target)
if err != nil {
return nil, err
}
if leftover != "" {
return nil, errors.NewBadRequestf("failed to parse %q fully. got leftover %q", target, leftover)
}
out = append(out, e)
}
return out, nil
}
// Parses an expression string and turns it into an expression
// also returns any leftover data that could not be parsed
func Parse(e string) (*expr, string, error) {
// skip whitespace
for len(e) > 1 && e[0] == ' ' {
e = e[1:]
}
if len(e) == 0 {
return nil, "", ErrMissingExpr
}
if '0' <= e[0] && e[0] <= '9' || e[0] == '-' || e[0] == '+' {
return parseConst(e)
}
if val, ok := strToBool(e); ok {
// 'false' is 5 chars, 'true' is 4
size := 5
if val {
size = 4
}
return &expr{bool: val, str: e[:size], etype: etBool}, e[size:], nil
}
if e[0] == '\'' || e[0] == '"' {
val, e, err := parseString(e)
return &expr{str: val, etype: etString}, e, err
}
name, e := parseName(e)
if name == "" {
return nil, e, ErrMissingArg
}
if e != "" && e[0] == '(' {
for i := range name {
if !isFnChar(name[i]) {
return nil, "", ErrIllegalCharacter
}
}
exp := &expr{str: name, etype: etFunc}
ArgString, posArgs, namedArgs, e, err := parseArgList(e)
exp.argsStr = ArgString
exp.args = posArgs
exp.namedArgs = namedArgs
return exp, e, err
}
return &expr{str: name, etype: etName}, e, nil
}
func strToBool(val string) (bool, bool) {
if strings.HasPrefix(val, "True") || strings.HasPrefix(val, "true") {
return true, true
}
if strings.HasPrefix(val, "False") || strings.HasPrefix(val, "false") {
return false, true
}
return false, false
}
func strToInt(val string) (int, bool) {
i, err := strconv.Atoi(val)
if err != nil {
return 0, false
}
return i, true
}
func strToFloat(val string) (float64, bool) {
f, err := strconv.ParseFloat(val, 64)
if err != nil {
return 0, false
}
return f, true
}
// caller must assure s starts with opening paren
func parseArgList(e string) (string, []*expr, map[string]*expr, string, error) {
var (
posArgs []*expr
namedArgs map[string]*expr
)
if e[0] != '(' {
panic("arg list should start with paren. calling code should have asserted this")
}
ArgString := e[1:]
e = e[1:]
for {
var arg *expr
var err error
arg, e, err = Parse(e)
if err != nil {
return "", nil, nil, e, err
}
if e == "" {
return "", nil, nil, "", ErrMissingComma
}
// we now know we're parsing a key-value pair
// in the future we should probably add validation here that the key
// can't contain otherwise-valid-name chars like {, }, etc
if arg.etype == etName && e[0] == '=' {
e = e[1:]
argCont, eCont, errCont := Parse(e)
if errCont != nil {
return "", nil, nil, eCont, errCont
}
if eCont == "" {
return "", nil, nil, "", ErrMissingComma
}
if argCont.etype != etInt && argCont.etype != etFloat && argCont.etype != etName && argCont.etype != etString && argCont.etype != etBool {
return "", nil, nil, eCont, ErrBadArgumentStr{"int, float, name, bool or string", string(argCont.etype)}
}
if namedArgs == nil {
namedArgs = make(map[string]*expr)
}
namedArgs[arg.str] = argCont
e = eCont
} else {
posArgs = append(posArgs, arg)
}
// after the argument, trim any trailing spaces
for len(e) > 0 && e[0] == ' ' {
e = e[1:]
}
if e[0] == ')' {
return ArgString[:len(ArgString)-len(e)], posArgs, namedArgs, e[1:], nil
}
if e[0] != ',' && e[0] != ' ' {
return "", nil, nil, "", ErrUnexpectedCharacter
}
e = e[1:]
}
}
var nameChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&*+-/:;<>?@[]^_|~."
func isNameChar(r byte) bool {
return strings.IndexByte(nameChar, r) >= 0
}
func isFnChar(r byte) bool {
return false ||
'a' <= r && r <= 'z' ||
'A' <= r && r <= 'Z' ||
'0' <= r && r <= '9'
}
func parseConst(s string) (*expr, string, error) {
var i int
var float bool
// All valid characters for a floating-point constant
// Just slurp them all in and let ParseFloat sort 'em out
for i < len(s) && (util.IsDigit(s[i]) || s[i] == '.' || s[i] == '+' || s[i] == '-' || s[i] == 'e' || s[i] == 'E') {
// note that exponent syntax results into a float value.
// so even values like 1e3 (1000) or 2000e-3 (2) which can be expressed as integers,
// are considered floating point values. if a function expets an int, then just don't use 'e' syntax.
if s[i] == '.' || s[i] == 'e' || s[i] == 'E' {
float = true
}
i++
}
if float {
v, err := strconv.ParseFloat(s[:i], 64)
return &expr{float: v, str: s[:i], etype: etFloat}, s[i:], err
}
v, err := strconv.ParseInt(s[:i], 10, 64)
return &expr{int: v, str: s[:i], etype: etInt}, s[i:], err
}
// parseName parses a "name" which is either:
// 1) a metric expression
// 2) the key of a keyword argument
// 3) a function name
// It's up to the caller to determine which, based on context. E.g.:
// * if leftover data starts with '(' then assume 3 and validate function name
// * if leftover data starts with '=' assume 2
// * fallback to assuming 1.
// it returns the parsed name and any leftover data
func parseName(s string) (string, string) {
var i int
allowEqual := false
FOR:
for braces := 0; i < len(s); i++ {
// if the current expression is a metric name with ";" (59) we should
// allow the "=" (61) character to be part of the metric name
if isNameChar(s[i]) || (allowEqual && s[i] == 61) {
if s[i] == 59 {
allowEqual = true
}
continue
}
switch s[i] {
case '{':
braces++
case '}':
if braces == 0 {
break FOR
}
braces--
case ',':
if braces == 0 {
break FOR
}
default:
break FOR
}
}
if i == len(s) {
return s, ""
}
return s[:i], s[i:]
}
// caller must assure s starts with a single or double quote
func parseString(s string) (string, string, error) {
if s[0] != '\'' && s[0] != '"' {
panic("string should start with open quote. calling code should have asserted this")
}
match := s[0]
s = s[1:]
var i int
for i < len(s) && s[i] != match {
i++
}
if i == len(s) {
return "", "", ErrMissingQuote
}
return s[:i], s[i+1:], nil
}
// extractMetric searches for a metric name or path Expression in `m'
// metric name / path expression is defined by the following criteria:
// 1. Not a function name
// 2. Consists only of name characters
// 2.1 '=' and ' ' are conditionally allowed if ';' is found (denoting tag format)
// 2.2 ',' is conditionally allowed within matching '{}'
// 3. Is not a string literal (i.e. contained within single/double quote pairs)
func extractMetric(m string) string {
start := 0
end := 0
curlyBraces := 0
quoteChar := byte(0)
allowTagChars := false
for end < len(m) {
c := m[end]
if (c == '\'' || c == '"') && (end == 0 || m[end-1] != '\\') {
// Found a non-escaped quote char
if quoteChar == 0 {
quoteChar = c
start = end + 1
} else if c == quoteChar {
quoteChar = byte(0)
start = end + 1
}
} else if quoteChar == 0 {
if c == '{' {
curlyBraces++
} else if c == '}' {
curlyBraces--
} else if c == ')' || (c == ',' && curlyBraces == 0) {
return m[start:end]
} else if !(isNameChar(c) || c == ',' || (allowTagChars && strings.IndexByte("= ", c) >= 0)) {
start = end + 1
allowTagChars = false
} else if c == ';' {
allowTagChars = true
}
}
end++
}
if quoteChar != 0 {
log.Warnf("extractMetric: encountered unterminated string literal in %s", m)
return ""
}
return m[start:end]
}
// aggKey returns a string key by applying the selectors
// (integers for node positions or strings for tag names) to the given serie
func aggKey(serie models.Series, nodes []expr) string {
metric := extractMetric(serie.Target)
if len(metric) == 0 {
metric = serie.Tags["name"]
}
// Trim off tags (if they are there) and split on '.'
parts := strings.Split(strings.SplitN(metric, ";", 2)[0], ".")
var name []string
for _, n := range nodes {
if n.etype == etInt {
idx := int(n.int)
if idx < 0 {
idx += len(parts)
}
if idx >= len(parts) || idx < 0 {
continue
}
name = append(name, parts[idx])
} else if n.etype == etString {
s := n.str
name = append(name, serie.Tags[s])
}
}
return strings.Join(name, ".")
}