-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
prettier.go
422 lines (343 loc) · 10.9 KB
/
prettier.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
// LogQL formatter is inspired from PromQL formatter
// https://github.com/prometheus/prometheus/blob/release-2.40/promql/parser/prettier.go
// https://youtu.be/pjkWzDVxWk4?t=24469
package syntax
import (
"fmt"
"strconv"
"strings"
"github.com/prometheus/common/model"
)
// How LogQL formatter works?
// =========================
// General idea is to parse the LogQL query(string) and converts it into AST(expressions) first, then format each expression from bottom up (from leaf expressions to the root expression). Every expression in AST has a level/depth (distance from the root), that is passed by it's parent.
//
// While prettifying an expression, we consider two things:
// 1. Did the current expression's parent add a new line?
// 2. Does the current expression exceeds `maxCharsPerLine` limit?
//
// The level of a expression determines if it should be indented or not.
// The answer to the 1 is NO if the level passed is 0. This means, the
// parent expression did not apply a new line, so the current Node must not
// apply any indentation as prefix.
// If level > 1, a new line is applied by the parent. So, the current expression
// should prefix an indentation before writing any of its content. This indentation
// will be ([level/depth of current expression] * " ").
//
// The answer to 2 is YES if the normalized length of the current expression exceeds
// the `maxCharsPerLine` limit. Hence, it applies the indentation equal to
// its depth and increments the level by 1 before passing down the child.
// If the answer is NO, the current expression returns the normalized string value of itself.
//
var (
// maxCharsPerLine is used to qualify whether some LogQL expressions are worth `splitting` into new lines.
maxCharsPerLine = 100
)
func Prettify(e Expr) string {
return e.Pretty(0)
}
// e.g: `{foo="bar"}`
func (e *MatchersExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: `{foo="bar"} | logfmt | level="error"`
// Here, left = `{foo="bar"}` and multistages would collection of each stage in pipeline, here `logfmt` and `level="error"`
func (e *PipelineExpr) Pretty(level int) string {
if !needSplit(e) {
return indent(level) + e.String()
}
s := fmt.Sprintf("%s\n", e.Left.Pretty(level))
for i, ms := range e.MultiStages {
s += ms.Pretty(level + 1)
//NOTE: Needed because, we tend to format multiple stage in pipeline as each stage in single line
// e.g:
// | logfmt
// | level = "error"
// But all the stages will have same indent level. So here we don't increase level.
if i < len(e.MultiStages)-1 {
s += "\n"
}
}
return s
}
// e.g: `|= "error" != "memcache" |= ip("192.168.0.1")`
// NOTE: here `ip` is Op in this expression.
func (e *LineFilterExpr) Pretty(level int) string {
if !needSplit(e) {
return indent(level) + e.String()
}
var s string
if e.Left != nil {
// s += indent(level)
s += e.Left.Pretty(level)
// NOTE: Similar to PiplelinExpr, we also have to format every LineFilterExpr in new line. But with same indendation level.
// e.g:
// |= "error"
// != "memcached"
// |= ip("192.168.0.1")
s += "\n"
}
s += indent(level)
// We re-use LineFilterExpr's String() implementation to avoid duplication.
// We create new LineFilterExpr without `Left`.
ne := newLineFilterExpr(e.Ty, e.Op, e.Match)
s += ne.String()
return s
}
func (e *LogfmtParserExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g:
// `| json`
// `| regexp`
// `| pattern`
// `| unpack`
func (e *LabelParserExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
func (e *DropLabelsExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
func (e *KeepLabelsExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: | level!="error"
func (e *LabelFilterExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: | line_format "{{ .label }}"
func (e *LineFmtExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: | decolorize
func (e *DecolorizeExpr) Pretty(_ int) string {
return e.String()
}
// e.g: | label_format dst="{{ .src }}"
func (e *LabelFmtExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: | json label="expression", another="expression"
func (e *JSONExpressionParser) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: | logfmt label="expression", another="expression"
func (e *LogfmtExpressionParser) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: sum_over_time({foo="bar"} | logfmt | unwrap bytes_processed [5m])
func (e *UnwrapExpr) Pretty(level int) string {
s := indent(level)
if e.Operation != "" {
s += fmt.Sprintf("%s %s %s(%s)", OpPipe, OpUnwrap, e.Operation, e.Identifier)
} else {
s += fmt.Sprintf("%s %s %s", OpPipe, OpUnwrap, e.Identifier)
}
for _, f := range e.PostFilters {
s += fmt.Sprintf("\n%s%s %s", indent(level), OpPipe, f)
}
return s
}
// e.g: `{foo="bar"}|logfmt[5m]`
// TODO(kavi): Rename `LogRange` -> `LogRangeExpr` (to be consistent with other expressions?)
func (e *LogRange) Pretty(level int) string {
s := e.Left.Pretty(level)
if e.Unwrap != nil {
// NOTE: | unwrap should go to newline
s += "\n"
s += e.Unwrap.Pretty(level + 1)
}
// TODO: this will put [1m] on the same line, not in new line as people used to now.
s = fmt.Sprintf("%s [%s]", s, model.Duration(e.Interval))
if e.Offset != 0 {
oe := OffsetExpr{Offset: e.Offset}
s += oe.Pretty(level)
}
return s
}
// e.g: count_over_time({foo="bar"}[5m] offset 3h)
// TODO(kavi): why does offset not work in log queries? e.g: `{foo="bar"} offset 1h`? is it bug? or anything else?
// NOTE: Also offset expression never to be indented. It always goes with its parent expression (usually RangeExpr).
func (e *OffsetExpr) Pretty(_ int) string {
// using `model.Duration` as it can format ignoring zero units.
// e.g: time.Duration(2 * Hour) -> "2h0m0s"
// but model.Duration(2 * Hour) -> "2h"
return fmt.Sprintf(" %s %s", OpOffset, model.Duration(e.Offset))
}
// e.g: count_over_time({foo="bar"}[5m])
func (e *RangeAggregationExpr) Pretty(level int) string {
s := indent(level)
if !needSplit(e) {
return s + e.String()
}
s += e.Operation // e.g: quantile_over_time
s += "(\n"
// print args to the function.
if e.Params != nil {
s = fmt.Sprintf("%s%s%s,", s, indent(level+1), fmt.Sprint(*e.Params))
s += "\n"
}
s += e.Left.Pretty(level + 1)
s += "\n" + indent(level) + ")"
if e.Grouping != nil {
s += e.Grouping.Pretty(level)
}
return s
}
// e.g:
// sum(count_over_time({foo="bar"}[5m])) by (container)
// topk(10, count_over_time({foo="bar"}[5m])) by (container)
// Syntax: <aggr-op>([parameter,] <vector expression>) [without|by (<label list>)]
// <aggr-op> - sum, avg, bottomk, topk, etc.
// [parameters,] - optional params, used only by bottomk and topk for now.
// <vector expression> - vector on which aggregation is done.
// [without|by (<label list)] - optional labels to aggregate either with `by` or `without` clause.
func (e *VectorAggregationExpr) Pretty(level int) string {
s := indent(level)
if !needSplit(e) {
return s + e.String()
}
var params []string
// level + 1 because arguments to function will be in newline.
left := e.Left.Pretty(level + 1)
switch e.Operation {
// e.Params default value (0) can mean a legit param for topk and bottomk
case OpTypeBottomK, OpTypeTopK:
params = []string{fmt.Sprintf("%s%d", indent(level+1), e.Params), left}
default:
if e.Params != 0 {
params = []string{fmt.Sprintf("%s%d", indent(level+1), e.Params), left}
} else {
params = []string{left}
}
}
s += e.Operation
if e.Grouping != nil {
s += e.Grouping.Pretty(level)
}
// (\n [params,\n])
s += "(\n"
for i, v := range params {
s += v
// LogQL doesn't allow `,` at the end of last argument.
if i < len(params)-1 {
s += ","
}
s += "\n"
}
s += indent(level) + ")"
return s
}
// e.g: Any operations involving
// "or", "and" and "unless" (logical/set)
// "+", "-", "*", "/", "%", "^" (arithmetic)
// "==", "!=", ">", ">=", "<", "<=" (comparison)
func (e *BinOpExpr) Pretty(level int) string {
s := indent(level)
if !needSplit(e) {
return s + e.String()
}
s = e.SampleExpr.Pretty(level+1) + "\n"
op := formatBinaryOp(e.Op, e.Opts)
s += indent(level) + op + "\n"
s += e.RHS.Pretty(level + 1)
return s
}
// e.g: 4.6
func (e *LiteralExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// e.g: label_replace(rate({job="api-server",service="a:c"}[5m]), "foo", "$1", "service", "(.*):.*")
func (e *LabelReplaceExpr) Pretty(level int) string {
s := indent(level)
if !needSplit(e) {
return s + e.String()
}
s += OpLabelReplace
s += "(\n"
params := []string{
e.Left.Pretty(level + 1),
indent(level+1) + strconv.Quote(e.Dst),
indent(level+1) + strconv.Quote(e.Replacement),
indent(level+1) + strconv.Quote(e.Src),
indent(level+1) + strconv.Quote(e.Regex),
}
for i, v := range params {
s += v
// LogQL doesn't allow `,` at the end of last argument.
if i < len(params)-1 {
s += ","
}
s += "\n"
}
s += indent(level) + ")"
return s
}
// e.g: vector(5)
func (e *VectorExpr) Pretty(level int) string {
return commonPrefixIndent(level, e)
}
// Grouping is technically not expression type. But used in both range and vector aggregations (`by` and `without` clause)
// So by implenting `Pretty` for Grouping, we can re use it for both.
// NOTE: indent is ignored for `Grouping`, because grouping always stays in the same line of it's parent expression.
// e.g:
// by(container,namespace) -> by (container, namespace)
func (g *Grouping) Pretty(_ int) string {
var s string
if g.Without {
s += " without"
} else if len(g.Groups) > 0 {
s += " by"
}
if len(g.Groups) > 0 {
s += " ("
s += strings.Join(g.Groups, ", ")
s += ")"
}
return s
}
// Helpers
func commonPrefixIndent(level int, current Expr) string {
return fmt.Sprintf("%s%s", indent(level), current.String())
}
func needSplit(e Expr) bool {
if e == nil {
return false
}
return len(e.String()) > maxCharsPerLine
}
const indentString = " "
func indent(level int) string {
return strings.Repeat(indentString, level)
}
func formatBinaryOp(op string, opts *BinOpOptions) string {
if opts == nil {
return op
}
if opts.ReturnBool {
// e.g: ">= bool 1"
op += " bool"
}
if opts.VectorMatching != nil {
group := "" // default one-to-one
if opts.VectorMatching.Card == CardManyToOne {
group = OpGroupLeft
}
if opts.VectorMatching.Card == CardOneToMany {
group = OpGroupRight
}
if len(opts.VectorMatching.Include) > 0 {
// e.g: group_left (node, name)
group = fmt.Sprintf("%s (%s)", group, strings.Join(opts.VectorMatching.Include, ", "))
}
if len(opts.VectorMatching.MatchingLabels) > 0 {
on := OpOn
if !opts.VectorMatching.On {
on = OpIgnoring
}
// e.g: * on (cluster, namespace) group_left
op = fmt.Sprintf("%s %s (%s) %s", op, on, strings.Join(opts.VectorMatching.MatchingLabels, ", "), group)
}
}
return op
}