forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ast.go
102 lines (86 loc) · 1.89 KB
/
ast.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
package logql
import (
"bytes"
"fmt"
"regexp"
"github.com/prometheus/prometheus/model/labels"
)
// Filter is a line filter sent to a querier to filter out log line.
type Filter func([]byte) bool
// Expr is a LogQL expression.
type Expr interface {
Filter() (Filter, error)
Matchers() []*labels.Matcher
}
type matchersExpr struct {
matchers []*labels.Matcher
}
func (e *matchersExpr) Matchers() []*labels.Matcher {
return e.matchers
}
func (e *matchersExpr) Filter() (Filter, error) {
return nil, nil
}
type filterExpr struct {
left Expr
ty labels.MatchType
match string
}
func (e *filterExpr) Matchers() []*labels.Matcher {
return e.left.Matchers()
}
// NewFilterExpr wraps an existing Expr with a next filter expression.
func NewFilterExpr(left Expr, ty labels.MatchType, match string) Expr {
return &filterExpr{
left: left,
ty: ty,
match: match,
}
}
func (e *filterExpr) Filter() (Filter, error) {
var f func([]byte) bool
switch e.ty {
case labels.MatchRegexp:
re, err := regexp.Compile(e.match)
if err != nil {
return nil, err
}
f = re.Match
case labels.MatchNotRegexp:
re, err := regexp.Compile(e.match)
if err != nil {
return nil, err
}
f = func(line []byte) bool {
return !re.Match(line)
}
case labels.MatchEqual:
f = func(line []byte) bool {
return bytes.Contains(line, []byte(e.match))
}
case labels.MatchNotEqual:
f = func(line []byte) bool {
return !bytes.Contains(line, []byte(e.match))
}
default:
return nil, fmt.Errorf("unknow matcher: %v", e.match)
}
next, ok := e.left.(*filterExpr)
if ok {
nextFilter, err := next.Filter()
if err != nil {
return nil, err
}
return func(line []byte) bool {
return nextFilter(line) && f(line)
}, nil
}
return f, nil
}
func mustNewMatcher(t labels.MatchType, n, v string) *labels.Matcher {
m, err := labels.NewMatcher(t, n, v)
if err != nil {
panic(err)
}
return m
}