forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
267 lines (237 loc) · 6.37 KB
/
parser.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
package syntax
import (
"errors"
"fmt"
"sort"
"strings"
"sync"
"github.com/prometheus/prometheus/model/labels"
promql_parser "github.com/prometheus/prometheus/promql/parser"
"github.com/grafana/loki/pkg/logqlmodel"
"github.com/grafana/loki/pkg/util"
)
const (
EmptyMatchers = "{}"
errAtleastOneEqualityMatcherRequired = "queries require at least one regexp or equality matcher that does not have an empty-compatible value. For instance, app=~\".*\" does not meet this requirement, but app=~\".+\" will"
)
var parserPool = sync.Pool{
New: func() interface{} {
p := &parser{
p: &exprParserImpl{},
Reader: strings.NewReader(""),
lexer: &lexer{},
}
return p
},
}
const maxInputSize = 5120
func init() {
// Improve the error messages coming out of yacc.
exprErrorVerbose = true
// uncomment when you need to understand yacc rule tree.
// exprDebug = 3
for str, tok := range tokens {
exprToknames[tok-exprPrivate+1] = str
}
}
type parser struct {
p *exprParserImpl
*lexer
expr Expr
*strings.Reader
}
func (p *parser) Parse() (Expr, error) {
p.lexer.errs = p.lexer.errs[:0]
p.lexer.Scanner.Error = func(_ *Scanner, msg string) {
p.lexer.Error(msg)
}
e := p.p.Parse(p)
if e != 0 || len(p.lexer.errs) > 0 {
return nil, p.lexer.errs[0]
}
return p.expr, nil
}
// ParseExpr parses a string and returns an Expr.
func ParseExpr(input string) (Expr, error) {
expr, err := ParseExprWithoutValidation(input)
if err != nil {
return nil, err
}
if err := validateExpr(expr); err != nil {
return nil, err
}
return expr, nil
}
func ParseExprWithoutValidation(input string) (expr Expr, err error) {
if len(input) >= maxInputSize {
return nil, logqlmodel.NewParseError(fmt.Sprintf("input size too long (%d > %d)", len(input), maxInputSize), 0, 0)
}
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); ok {
if errors.Is(err, logqlmodel.ErrParse) {
return
}
err = logqlmodel.NewParseError(err.Error(), 0, 0)
}
}
}()
p := parserPool.Get().(*parser)
defer parserPool.Put(p)
p.Reader.Reset(input)
p.lexer.Init(p.Reader)
return p.Parse()
}
func MustParseExpr(input string) Expr {
expr, err := ParseExpr(input)
if err != nil {
panic(err)
}
return expr
}
func validateExpr(expr Expr) error {
switch e := expr.(type) {
case SampleExpr:
return validateSampleExpr(e)
case LogSelectorExpr:
return validateLogSelectorExpression(e)
default:
return logqlmodel.NewParseError(fmt.Sprintf("unexpected expression type: %v", e), 0, 0)
}
}
// validateMatchers checks whether a query would touch all the streams in the query range or uses at least one matcher to select specific streams.
func validateMatchers(matchers []*labels.Matcher) error {
_, matchers = util.SplitFiltersAndMatchers(matchers)
if len(matchers) == 0 {
return logqlmodel.NewParseError(errAtleastOneEqualityMatcherRequired, 0, 0)
}
return nil
}
// ParseMatchers parses a string and returns labels matchers, if the expression contains
// anything else it will return an error.
func ParseMatchers(input string, validate bool) ([]*labels.Matcher, error) {
var (
expr Expr
err error
)
if validate {
expr, err = ParseExpr(input)
} else {
expr, err = ParseExprWithoutValidation(input)
}
if err != nil {
return nil, err
}
matcherExpr, ok := expr.(*MatchersExpr)
if !ok {
return nil, logqlmodel.ErrParseMatchers
}
return matcherExpr.Mts, nil
}
func MatchersString(xs []*labels.Matcher) string {
return newMatcherExpr(xs).String()
}
// ParseSampleExpr parses a string and returns the sampleExpr
func ParseSampleExpr(input string) (SampleExpr, error) {
expr, err := ParseExpr(input)
if err != nil {
return nil, err
}
sampleExpr, ok := expr.(SampleExpr)
if !ok {
return nil, errors.New("only sample expression supported")
}
return sampleExpr, nil
}
func validateSampleExpr(expr SampleExpr) error {
switch e := expr.(type) {
case *BinOpExpr:
if e.err != nil {
return e.err
}
if err := validateSampleExpr(e.SampleExpr); err != nil {
return err
}
return validateSampleExpr(e.RHS)
case *LiteralExpr:
if e.err != nil {
return e.err
}
return nil
case *VectorExpr:
if e.err != nil {
return e.err
}
return nil
case *VectorAggregationExpr:
if e.err != nil {
return e.err
}
if e.Operation == OpTypeSort || e.Operation == OpTypeSortDesc {
if err := validateSortGrouping(e.Grouping); err != nil {
return err
}
}
return validateSampleExpr(e.Left)
default:
selector, err := e.Selector()
if err != nil {
return err
}
return validateLogSelectorExpression(selector)
}
}
func validateLogSelectorExpression(expr LogSelectorExpr) error {
switch e := expr.(type) {
case *VectorExpr:
return nil
default:
return validateMatchers(e.Matchers())
}
}
// validateSortGrouping prevent by|without groupings on sort operations.
// This will keep compatibility with promql and allowing sort by (foo) doesn't make much sense anyway when sort orders by value instead of labels.
func validateSortGrouping(grouping *Grouping) error {
if grouping != nil && len(grouping.Groups) > 0 {
return logqlmodel.NewParseError("sort and sort_desc doesn't allow grouping by ", 0, 0)
}
return nil
}
// ParseLogSelector parses a log selector expression `{app="foo"} |= "filter"`
func ParseLogSelector(input string, validate bool) (LogSelectorExpr, error) {
expr, err := ParseExprWithoutValidation(input)
if err != nil {
return nil, err
}
logSelector, ok := expr.(LogSelectorExpr)
if !ok {
return nil, errors.New("only log selector is supported")
}
if validate {
if err := validateExpr(expr); err != nil {
return nil, err
}
}
return logSelector, nil
}
// ParseLabels parses labels from a string using logql parser.
func ParseLabels(lbs string) (labels.Labels, error) {
ls, err := promql_parser.ParseMetric(lbs)
if err != nil {
return nil, err
}
// Sort labels to ensure functionally equivalent
// inputs map to the same output
sort.Sort(ls)
// Use the label builder to trim empty label values.
// Empty label values are equivalent to absent labels
// in Prometheus, but they unfortunately alter the
// Hash values created. This can cause problems in Loki
// if we can't rely on a set of labels to have a deterministic
// hash value.
// Therefore we must normalize early in the write path.
// See https://github.com/grafana/loki/pull/7355
// for more information
return labels.NewBuilder(ls).Labels(), nil
}