-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathfmt.go
510 lines (462 loc) · 11.7 KB
/
fmt.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
package log
import (
"bytes"
"fmt"
"net/url"
"strconv"
"strings"
"text/template"
"text/template/parse"
"time"
"github.com/Masterminds/sprig/v3"
"github.com/grafana/regexp"
"github.com/grafana/loki/v3/pkg/logqlmodel"
)
const (
functionLineName = "__line__"
functionTimestampName = "__timestamp__"
)
var (
_ Stage = &LineFormatter{}
_ Stage = &LabelsFormatter{}
// Available map of functions for the text template engine.
functionMap = template.FuncMap{
// olds functions deprecated.
"ToLower": strings.ToLower,
"ToUpper": strings.ToUpper,
"Replace": strings.Replace,
"Trim": strings.Trim,
"TrimLeft": strings.TrimLeft,
"TrimRight": strings.TrimRight,
"TrimPrefix": strings.TrimPrefix,
"TrimSuffix": strings.TrimSuffix,
"TrimSpace": strings.TrimSpace,
"regexReplaceAll": func(regex string, s string, repl string) (string, error) {
r, err := regexp.Compile(regex)
if err != nil {
return "", err
}
return r.ReplaceAllString(s, repl), nil
},
"regexReplaceAllLiteral": func(regex string, s string, repl string) (string, error) {
r, err := regexp.Compile(regex)
if err != nil {
return "", err
}
return r.ReplaceAllLiteralString(s, repl), nil
},
"count": func(regexsubstr string, s string) (int, error) {
r, err := regexp.Compile(regexsubstr)
if err != nil {
return 0, err
}
matches := r.FindAllStringIndex(s, -1)
return len(matches), nil
},
"urldecode": url.QueryUnescape,
"urlencode": url.QueryEscape,
"bytes": convertBytes,
"duration": convertDuration,
"duration_seconds": convertDuration,
"unixEpochMillis": unixEpochMillis,
"unixEpochNanos": unixEpochNanos,
"toDateInZone": toDateInZone,
"unixToTime": unixToTime,
"alignLeft": alignLeft,
"alignRight": alignRight,
}
// sprig template functions
templateFunctions = []string{
"b64enc",
"b64dec",
"lower",
"upper",
"title",
"trunc",
"substr",
"contains",
"hasPrefix",
"hasSuffix",
"indent",
"nindent",
"replace",
"repeat",
"trim",
"trimAll",
"trimSuffix",
"trimPrefix",
"int",
"float64",
"add",
"sub",
"mul",
"div",
"mod",
"addf",
"subf",
"mulf",
"divf",
"max",
"min",
"maxf",
"minf",
"ceil",
"floor",
"round",
"fromJson",
"date",
"toDate",
"now",
"unixEpoch",
"default",
}
)
func addLineAndTimestampFunctions(currLine func() string, currTimestamp func() int64) map[string]interface{} {
functions := make(map[string]interface{}, len(functionMap)+2)
for k, v := range functionMap {
functions[k] = v
}
functions[functionLineName] = func() string {
return currLine()
}
functions[functionTimestampName] = func() time.Time {
return time.Unix(0, currTimestamp())
}
return functions
}
// toEpoch converts a string with Unix time to an time Value
func unixToTime(epoch string) (time.Time, error) {
var ct time.Time
l := len(epoch)
i, err := strconv.ParseInt(epoch, 10, 64)
if err != nil {
return ct, fmt.Errorf("unable to parse time '%v': %w", epoch, err)
}
switch l {
case 5:
// days 19373
return time.Unix(i*86400, 0), nil
case 10:
// seconds 1673798889
return time.Unix(i, 0), nil
case 13:
// milliseconds 1673798889902
return time.Unix(0, i*1000*1000), nil
case 16:
// microseconds 1673798889902000
return time.Unix(0, i*1000), nil
case 19:
// nanoseconds 1673798889902000000
return time.Unix(0, i), nil
default:
return ct, fmt.Errorf("unable to parse time '%v': %w", epoch, err)
}
}
func unixEpochMillis(date time.Time) string {
return strconv.FormatInt(date.UnixMilli(), 10)
}
func unixEpochNanos(date time.Time) string {
return strconv.FormatInt(date.UnixNano(), 10)
}
func toDateInZone(fmt, zone, str string) time.Time {
loc, err := time.LoadLocation(zone)
if err != nil {
loc, _ = time.LoadLocation("UTC")
}
t, _ := time.ParseInLocation(fmt, str, loc)
return t
}
func init() {
sprigFuncMap := sprig.GenericFuncMap()
for _, v := range templateFunctions {
if function, ok := sprigFuncMap[v]; ok {
functionMap[v] = function
}
}
}
type LineFormatter struct {
*template.Template
buf *bytes.Buffer
currentLine []byte
currentTs int64
}
// NewFormatter creates a new log line formatter from a given text template.
func NewFormatter(tmpl string) (*LineFormatter, error) {
lf := &LineFormatter{
buf: bytes.NewBuffer(make([]byte, 4096)),
}
functions := addLineAndTimestampFunctions(func() string {
return unsafeGetString(lf.currentLine)
}, func() int64 {
return lf.currentTs
})
t, err := template.New("line").Option("missingkey=zero").Funcs(functions).Parse(tmpl)
if err != nil {
return nil, fmt.Errorf("invalid line template: %w", err)
}
lf.Template = t
return lf, nil
}
func (lf *LineFormatter) Process(ts int64, line []byte, lbs *LabelsBuilder) ([]byte, bool) {
lf.buf.Reset()
lf.currentLine = line
lf.currentTs = ts
// map now is taking from a pool
m, ret := lbs.Map()
defer func() {
if ret { // if we return the base map from the labels builder we should not put it back in the pool
smp.Put(m)
}
}()
if err := lf.Template.Execute(lf.buf, m); err != nil {
lbs.SetErr(errTemplateFormat)
lbs.SetErrorDetails(err.Error())
return line, true
}
return lf.buf.Bytes(), true
}
func (lf *LineFormatter) RequiredLabelNames() []string {
return uniqueString(listNodeFields([]parse.Node{lf.Root}))
}
func listNodeFields(nodes []parse.Node) []string {
var res []string
for _, node := range nodes {
switch node.Type() {
case parse.NodePipe:
res = append(res, listNodeFieldsFromPipe(node.(*parse.PipeNode))...)
case parse.NodeAction:
res = append(res, listNodeFieldsFromPipe(node.(*parse.ActionNode).Pipe)...)
case parse.NodeList:
res = append(res, listNodeFields(node.(*parse.ListNode).Nodes)...)
case parse.NodeCommand:
res = append(res, listNodeFields(node.(*parse.CommandNode).Args)...)
case parse.NodeIf, parse.NodeWith, parse.NodeRange:
res = append(res, listNodeFieldsFromBranch(node)...)
case parse.NodeField:
res = append(res, node.(*parse.FieldNode).Ident...)
}
}
return res
}
func listNodeFieldsFromBranch(node parse.Node) []string {
var res []string
var b parse.BranchNode
switch node.Type() {
case parse.NodeIf:
b = node.(*parse.IfNode).BranchNode
case parse.NodeWith:
b = node.(*parse.WithNode).BranchNode
case parse.NodeRange:
b = node.(*parse.RangeNode).BranchNode
default:
return res
}
if b.Pipe != nil {
res = append(res, listNodeFieldsFromPipe(b.Pipe)...)
}
if b.List != nil {
res = append(res, listNodeFields(b.List.Nodes)...)
}
if b.ElseList != nil {
res = append(res, listNodeFields(b.ElseList.Nodes)...)
}
return res
}
func listNodeFieldsFromPipe(p *parse.PipeNode) []string {
var res []string
for _, c := range p.Cmds {
res = append(res, listNodeFields(c.Args)...)
}
return res
}
// LabelFmt is a configuration struct for formatting a label.
type LabelFmt struct {
Name string
Value string
Rename bool
}
// NewRenameLabelFmt creates a configuration to rename a label.
func NewRenameLabelFmt(dst, target string) LabelFmt {
return LabelFmt{
Name: dst,
Rename: true,
Value: target,
}
}
// NewTemplateLabelFmt creates a configuration to format a label using text template.
func NewTemplateLabelFmt(dst, template string) LabelFmt {
return LabelFmt{
Name: dst,
Rename: false,
Value: template,
}
}
type labelFormatter struct {
tmpl *template.Template
LabelFmt
}
type LabelsFormatter struct {
formats []labelFormatter
buf *bytes.Buffer
currentLine []byte
currentTs int64
}
// NewLabelsFormatter creates a new formatter that can format multiple labels at once.
// Either by renaming or using text template.
// It is not allowed to reformat the same label twice within the same formatter.
func NewLabelsFormatter(fmts []LabelFmt) (*LabelsFormatter, error) {
if err := validate(fmts); err != nil {
return nil, err
}
formats := make([]labelFormatter, 0, len(fmts))
lf := &LabelsFormatter{
buf: bytes.NewBuffer(make([]byte, 1024)),
}
functions := addLineAndTimestampFunctions(func() string {
return unsafeGetString(lf.currentLine)
}, func() int64 {
return lf.currentTs
})
for _, fm := range fmts {
toAdd := labelFormatter{LabelFmt: fm}
if !fm.Rename {
t, err := template.New("label").Option("missingkey=zero").Funcs(functions).Parse(fm.Value)
if err != nil {
return nil, fmt.Errorf("invalid template for label '%s': %s", fm.Name, err)
}
toAdd.tmpl = t
}
formats = append(formats, toAdd)
}
lf.formats = formats
return lf, nil
}
func validate(fmts []LabelFmt) error {
// it would be too confusing to rename and change the same label value.
// To avoid confusion we allow to have a label name only once per stage.
uniqueLabelName := map[string]struct{}{}
for _, f := range fmts {
if f.Name == logqlmodel.ErrorLabel {
return fmt.Errorf("%s cannot be formatted", f.Name)
}
if _, ok := uniqueLabelName[f.Name]; ok {
return fmt.Errorf("multiple label name '%s' not allowed in a single format operation", f.Name)
}
uniqueLabelName[f.Name] = struct{}{}
}
return nil
}
func (lf *LabelsFormatter) Process(ts int64, l []byte, lbs *LabelsBuilder) ([]byte, bool) {
lf.currentLine = l
lf.currentTs = ts
var m = smp.Get()
defer smp.Put(m)
for _, f := range lf.formats {
if f.Rename {
v, category, ok := lbs.GetWithCategory(f.Value)
if ok {
lbs.Set(category, f.Name, v)
lbs.Del(f.Value)
}
continue
}
lf.buf.Reset()
if len(m) == 0 {
lbs.IntoMap(m)
}
if err := f.tmpl.Execute(lf.buf, m); err != nil {
lbs.SetErr(errTemplateFormat)
lbs.SetErrorDetails(err.Error())
continue
}
lbs.Set(ParsedLabel, f.Name, lf.buf.String())
}
return l, true
}
func (lf *LabelsFormatter) RequiredLabelNames() []string {
var names []string
for _, fm := range lf.formats {
if fm.Rename {
names = append(names, fm.Value)
continue
}
names = append(names, listNodeFields([]parse.Node{fm.tmpl.Root})...)
}
return uniqueString(names)
}
func trunc(c int, s string) string {
runes := []rune(s)
l := len(runes)
if c < 0 && l+c > 0 {
return string(runes[l+c:])
}
if c >= 0 && l > c {
return string(runes[:c])
}
return s
}
func alignLeft(count int, src string) string {
runes := []rune(src)
l := len(runes)
if count < 0 || count == l {
return src
}
pad := count - l
if pad > 0 {
return src + strings.Repeat(" ", pad)
}
return string(runes[:count])
}
func alignRight(count int, src string) string {
runes := []rune(src)
l := len(runes)
if count < 0 || count == l {
return src
}
pad := count - l
if pad > 0 {
return strings.Repeat(" ", pad) + src
}
return string(runes[l-count:])
}
type Decolorizer struct{}
// RegExp to select ANSI characters courtesy of https://github.com/acarl005/stripansi
const ansiPattern = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
var ansiRegex = regexp.MustCompile(ansiPattern)
func NewDecolorizer() (*Decolorizer, error) {
return &Decolorizer{}, nil
}
func (Decolorizer) Process(_ int64, line []byte, _ *LabelsBuilder) ([]byte, bool) {
return ansiRegex.ReplaceAll(line, []byte{}), true
}
func (Decolorizer) RequiredLabelNames() []string { return []string{} }
// substring creates a substring of the given string.
//
// If start is < 0, this calls string[:end].
//
// If start is >= 0 and end < 0 or end bigger than s length, this calls string[start:]
//
// Otherwise, this calls string[start, end].
func substring(start, end int, s string) string {
runes := []rune(s)
l := len(runes)
if end > l {
end = l
}
if start > l {
start = l
}
if start < 0 {
if end < 0 {
return ""
}
return string(runes[:end])
}
if end < 0 {
return string(runes[start:])
}
if start > end {
return ""
}
return string(runes[start:end])
}