-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
if_expression.go
344 lines (314 loc) · 7.71 KB
/
if_expression.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
package promrelabel
import (
"encoding/json"
"fmt"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/prompbmarshal"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/regexutil"
"github.com/VictoriaMetrics/metricsql"
)
// IfExpression represents PromQL-like label filters such as `metric_name{filters...}`.
//
// It may contain either a single filter or multiple filters, which are executed with `or` operator.
//
// Examples:
//
// if: 'foo{bar="baz"}'
//
// if:
// - 'foo{bar="baz"}'
// - '{x=~"y"}'
type IfExpression struct {
ies []*ifExpression
}
// Match returns true if labels match at least a single label filter inside ie.
//
// Match returns true for empty ie.
func (ie *IfExpression) Match(labels []prompbmarshal.Label) bool {
if ie == nil || len(ie.ies) == 0 {
return true
}
for _, ie := range ie.ies {
if ie.Match(labels) {
return true
}
}
return false
}
// Parse parses ie from s.
func (ie *IfExpression) Parse(s string) error {
ieLocal, err := newIfExpression(s)
if err != nil {
return err
}
ie.ies = []*ifExpression{ieLocal}
return nil
}
// UnmarshalJSON unmarshals ie from JSON data.
func (ie *IfExpression) UnmarshalJSON(data []byte) error {
var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
return err
}
return ie.unmarshalFromInterface(v)
}
// MarshalJSON marshals ie to JSON.
func (ie *IfExpression) MarshalJSON() ([]byte, error) {
if ie == nil || len(ie.ies) == 0 {
return nil, nil
}
if len(ie.ies) == 1 {
return json.Marshal(ie.ies[0])
}
return json.Marshal(ie.ies)
}
// UnmarshalYAML unmarshals ie from YAML passed to f.
func (ie *IfExpression) UnmarshalYAML(f func(interface{}) error) error {
var v interface{}
if err := f(&v); err != nil {
return fmt.Errorf("cannot unmarshal `match` option: %w", err)
}
return ie.unmarshalFromInterface(v)
}
func (ie *IfExpression) unmarshalFromInterface(v interface{}) error {
ies := ie.ies[:0]
switch t := v.(type) {
case string:
ieLocal, err := newIfExpression(t)
if err != nil {
return fmt.Errorf("unexpected `match` option: %w", err)
}
ies = append(ies, ieLocal)
case []interface{}:
for _, x := range t {
s, ok := x.(string)
if !ok {
return fmt.Errorf("unexpected `match` item type; got %#v; want string", x)
}
ieLocal, err := newIfExpression(s)
if err != nil {
return fmt.Errorf("unexpected `match` item: %w", err)
}
ies = append(ies, ieLocal)
}
default:
return fmt.Errorf("unexpected `match` type; got %#v; want string or an array of strings", t)
}
ie.ies = ies
return nil
}
// MarshalYAML marshals ie to YAML
func (ie *IfExpression) MarshalYAML() (interface{}, error) {
if ie == nil || len(ie.ies) == 0 {
return nil, nil
}
if len(ie.ies) == 1 {
return ie.ies[0].MarshalYAML()
}
a := make([]string, 0, len(ie.ies))
for _, ieLocal := range ie.ies {
v, err := ieLocal.MarshalYAML()
if err != nil {
logger.Panicf("BUG: unexpected error: %s", err)
}
s := v.(string)
a = append(a, s)
}
return a, nil
}
func newIfExpression(s string) (*ifExpression, error) {
var ie ifExpression
if err := ie.Parse(s); err != nil {
return nil, err
}
return &ie, nil
}
// String returns string representation of ie.
func (ie *IfExpression) String() string {
if ie == nil {
return "{}"
}
if len(ie.ies) == 1 {
return ie.ies[0].String()
}
return fmt.Sprintf("%s", ie.ies)
}
type ifExpression struct {
s string
lfss [][]*labelFilter
}
func (ie *ifExpression) String() string {
if ie == nil {
return ""
}
return ie.s
}
func (ie *ifExpression) Parse(s string) error {
expr, err := metricsql.Parse(s)
if err != nil {
return err
}
me, ok := expr.(*metricsql.MetricExpr)
if !ok {
return fmt.Errorf("expecting series selector; got %q", expr.AppendString(nil))
}
lfss, err := metricExprToLabelFilterss(me)
if err != nil {
return fmt.Errorf("cannot parse series selector: %w", err)
}
ie.s = s
ie.lfss = lfss
return nil
}
// UnmarshalJSON unmarshals ie from JSON data.
func (ie *ifExpression) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
return ie.Parse(s)
}
// MarshalJSON marshals ie to JSON.
func (ie *ifExpression) MarshalJSON() ([]byte, error) {
return json.Marshal(ie.s)
}
// UnmarshalYAML unmarshals ie from YAML passed to f.
func (ie *ifExpression) UnmarshalYAML(f func(interface{}) error) error {
var s string
if err := f(&s); err != nil {
return fmt.Errorf("cannot unmarshal `if` option: %w", err)
}
if err := ie.Parse(s); err != nil {
return fmt.Errorf("cannot parse `if` series selector: %w", err)
}
return nil
}
// MarshalYAML marshals ie to YAML.
func (ie *ifExpression) MarshalYAML() (interface{}, error) {
return ie.s, nil
}
// Match returns true if ie matches the given labels.
func (ie *ifExpression) Match(labels []prompbmarshal.Label) bool {
if ie == nil {
return true
}
for _, lfs := range ie.lfss {
if matchLabelFilters(lfs, labels) {
return true
}
}
return false
}
func matchLabelFilters(lfs []*labelFilter, labels []prompbmarshal.Label) bool {
for _, lf := range lfs {
if !lf.match(labels) {
return false
}
}
return true
}
func metricExprToLabelFilterss(me *metricsql.MetricExpr) ([][]*labelFilter, error) {
lfssNew := make([][]*labelFilter, len(me.LabelFilterss))
for i, lfs := range me.LabelFilterss {
lfsNew := make([]*labelFilter, len(lfs))
for j := range lfs {
lf, err := newLabelFilter(&lfs[j])
if err != nil {
return nil, fmt.Errorf("cannot parse %s: %w", me.AppendString(nil), err)
}
lfsNew[j] = lf
}
lfssNew[i] = lfsNew
}
return lfssNew, nil
}
// labelFilter contains PromQL filter for `{label op "value"}`
type labelFilter struct {
label string
op string
value string
// re contains compiled regexp for `=~` and `!~` op.
re *regexutil.PromRegex
}
func newLabelFilter(mlf *metricsql.LabelFilter) (*labelFilter, error) {
lf := &labelFilter{
label: toCanonicalLabelName(mlf.Label),
op: getFilterOp(mlf),
value: mlf.Value,
}
if lf.op == "=~" || lf.op == "!~" {
re, err := regexutil.NewPromRegex(lf.value)
if err != nil {
return nil, fmt.Errorf("cannot parse regexp for %s: %w", mlf.AppendString(nil), err)
}
lf.re = re
}
return lf, nil
}
func (lf *labelFilter) match(labels []prompbmarshal.Label) bool {
switch lf.op {
case "=":
return lf.equalValue(labels)
case "!=":
return !lf.equalValue(labels)
case "=~":
return lf.matchRegexp(labels)
case "!~":
return !lf.matchRegexp(labels)
default:
logger.Panicf("BUG: unexpected operation for label filter: %s", lf.op)
}
return false
}
func (lf *labelFilter) equalValue(labels []prompbmarshal.Label) bool {
labelNameMatches := 0
for _, label := range labels {
if toCanonicalLabelName(label.Name) != lf.label {
continue
}
labelNameMatches++
if label.Value == lf.value {
return true
}
}
if labelNameMatches == 0 {
// Special case for {non_existing_label=""}, which matches anything except of non-empty non_existing_label
return lf.value == ""
}
return false
}
func (lf *labelFilter) matchRegexp(labels []prompbmarshal.Label) bool {
labelNameMatches := 0
for _, label := range labels {
if toCanonicalLabelName(label.Name) != lf.label {
continue
}
labelNameMatches++
if lf.re.MatchString(label.Value) {
return true
}
}
if labelNameMatches == 0 {
// Special case for {non_existing_label=~"something|"}, which matches empty non_existing_label
return lf.re.MatchString("")
}
return false
}
func toCanonicalLabelName(labelName string) string {
if labelName == "__name__" {
return ""
}
return labelName
}
func getFilterOp(mlf *metricsql.LabelFilter) string {
if mlf.IsNegative {
if mlf.IsRegexp {
return "!~"
}
return "!="
}
if mlf.IsRegexp {
return "=~"
}
return "="
}