forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatevents.go
438 lines (372 loc) · 9.41 KB
/
formatevents.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
package fmtstr
import (
"bytes"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/dtfmt"
"github.com/elastic/beats/libbeat/logp"
)
// EventFormatString implements format string support on events
// of type beat.Event.
//
// The concrete event expansion requires the field name enclosed by brackets.
// For example: '%{[field.name]}'. Field names can be separated by points or
// multiple braces. This format `%{[field.name]}` is equivalent to `%{[field][name]}`.
//
// Default values are given defined by the colon operator. For example:
// `%{[field.name]:default value}`.
type EventFormatString struct {
formatter StringFormatter
fields []fieldInfo
timestamp bool
}
type eventFieldEvaler struct {
index int
}
type defaultEventFieldEvaler struct {
index int
defaultValue string
}
type eventTimestampEvaler struct {
formatter *dtfmt.Formatter
}
type eventFieldCompiler struct {
keys map[string]keyInfo
timestamp bool
index int
}
type fieldInfo struct {
path string
required bool
}
type keyInfo struct {
index int
required bool
}
type eventEvalContext struct {
keys []string
ts time.Time
buf *bytes.Buffer
}
var (
errMissingKeys = errors.New("missing keys")
errConvertString = errors.New("can not convert to string")
)
var eventCtxPool = &sync.Pool{
New: func() interface{} { return &eventEvalContext{} },
}
func newEventCtx(sz int) *eventEvalContext {
ctx := eventCtxPool.Get().(*eventEvalContext)
if ctx.keys == nil || cap(ctx.keys) < sz {
ctx.keys = make([]string, 0, sz)
} else {
ctx.keys = ctx.keys[:0]
}
return ctx
}
func releaseCtx(c *eventEvalContext) {
eventCtxPool.Put(c)
}
// MustCompileEvent copmiles an event format string into an runnable
// EventFormatString. Generates a panic if compilation fails.
func MustCompileEvent(in string) *EventFormatString {
fs, err := CompileEvent(in)
if err != nil {
panic(err)
}
return fs
}
// CompileEvent compiles an event format string into an runnable
// EventFormatString. Returns error if parsing or compilation fails.
func CompileEvent(in string) (*EventFormatString, error) {
ctx := &eventEvalContext{}
efComp := &eventFieldCompiler{
keys: map[string]keyInfo{},
index: 0,
timestamp: false,
}
sf, err := Compile(in, efComp.compileExpression)
if err != nil {
return nil, err
}
keys := make([]fieldInfo, len(efComp.keys))
for path, info := range efComp.keys {
keys[info.index] = fieldInfo{
path: path,
required: info.required,
}
}
ctx.keys = make([]string, len(keys))
efs := &EventFormatString{
formatter: sf,
fields: keys,
timestamp: efComp.timestamp,
}
return efs, nil
}
// Unpack tries to initialize the EventFormatString from provided value
// (which must be a string). Unpack method satisfies go-ucfg.Unpacker interface
// required by common.Config, in order to use EventFormatString with
// `common.(*Config).Unpack()`.
func (fs *EventFormatString) Unpack(v interface{}) error {
s, err := tryConvString(v)
if err != nil {
return err
}
tmp, err := CompileEvent(s)
if err != nil {
return err
}
// init fs from tmp
*fs = *tmp
return nil
}
// NumFields returns number of unique event fields used by the format string.
func (fs *EventFormatString) NumFields() int {
return len(fs.fields)
}
// Fields returns list of unique event fields required by the format string.
func (fs *EventFormatString) Fields() []string {
var fields []string
for _, fi := range fs.fields {
if fi.required {
fields = append(fields, fi.path)
}
}
return fields
}
// Run executes the format string returning a new expanded string or an error
// if execution or event field expansion fails.
func (fs *EventFormatString) Run(event *beat.Event) (string, error) {
ctx := newEventCtx(len(fs.fields))
defer releaseCtx(ctx)
if ctx.buf == nil {
ctx.buf = bytes.NewBuffer(nil)
} else {
ctx.buf.Reset()
}
if err := fs.collectFields(ctx, event); err != nil {
return "", err
}
err := fs.formatter.Eval(ctx, ctx.buf)
if err != nil {
return "", err
}
return ctx.buf.String(), nil
}
// RunBytes executes the format string returning a new expanded string of type
// `[]byte` or an error if execution or event field expansion fails.
func (fs *EventFormatString) RunBytes(event *beat.Event) ([]byte, error) {
ctx := newEventCtx(len(fs.fields))
defer releaseCtx(ctx)
buf := bytes.NewBuffer(nil)
if err := fs.collectFields(ctx, event); err != nil {
return nil, err
}
err := fs.formatter.Eval(ctx, buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Eval executes the format string, writing the resulting string into the provided output buffer. Returns error if execution or event field expansion fails.
func (fs *EventFormatString) Eval(out *bytes.Buffer, event *beat.Event) error {
ctx := newEventCtx(len(fs.fields))
defer releaseCtx(ctx)
if err := fs.collectFields(ctx, event); err != nil {
return err
}
return fs.formatter.Eval(ctx, out)
}
// IsConst checks the format string always returning the same constant string
func (fs *EventFormatString) IsConst() bool {
return fs.formatter.IsConst()
}
// collectFields tries to extract and convert all required fields into an array
// of strings.
func (fs *EventFormatString) collectFields(
ctx *eventEvalContext,
event *beat.Event,
) error {
for _, fi := range fs.fields {
s, err := fieldString(event, fi.path)
if err != nil {
if fi.required {
return err
}
s = ""
}
ctx.keys = append(ctx.keys, s)
}
if fs.timestamp {
ctx.ts = event.Timestamp
}
return nil
}
func (e *eventFieldCompiler) compileExpression(
s string,
opts []VariableOp,
) (FormatEvaler, error) {
if len(s) == 0 {
return nil, errors.New("empty expression")
}
switch s[0] {
case '[':
return e.compileEventField(s, opts)
case '+':
return e.compileTimestamp(s, opts)
default:
return nil, fmt.Errorf(`unsupported format expression "%v"`, s)
}
}
func (e *eventFieldCompiler) compileEventField(
field string,
ops []VariableOp,
) (FormatEvaler, error) {
if len(ops) > 1 {
return nil, errors.New("Too many format modifiers given")
}
defaultValue := ""
if len(ops) == 1 {
op := ops[0]
if op.op != ":" {
return nil, fmt.Errorf("unsupported format operator: %v", op.op)
}
defaultValue = op.param
}
path, err := parseEventPath(field)
if err != nil {
return nil, err
}
info, found := e.keys[path]
if !found {
info = keyInfo{
required: len(ops) == 0,
index: e.index,
}
e.index++
e.keys[path] = info
} else if !info.required && len(ops) == 0 {
info.required = true
e.keys[path] = info
}
idx := info.index
if len(ops) == 0 {
return &eventFieldEvaler{idx}, nil
}
return &defaultEventFieldEvaler{idx, defaultValue}, nil
}
func (e *eventFieldCompiler) compileTimestamp(
expression string,
ops []VariableOp,
) (FormatEvaler, error) {
if expression[0] != '+' {
return nil, errors.New("No timestamp expression")
}
formatter, err := dtfmt.NewFormatter(expression[1:])
if err != nil {
return nil, fmt.Errorf("%v in timestamp expression", err)
}
e.timestamp = true
return &eventTimestampEvaler{formatter}, nil
}
func (e *eventFieldEvaler) Eval(c interface{}, out *bytes.Buffer) error {
type stringer interface {
String() string
}
ctx := c.(*eventEvalContext)
s := ctx.keys[e.index]
_, err := out.WriteString(s)
return err
}
func (e *defaultEventFieldEvaler) Eval(c interface{}, out *bytes.Buffer) error {
type stringer interface {
String() string
}
ctx := c.(*eventEvalContext)
s := ctx.keys[e.index]
if s == "" {
s = e.defaultValue
}
_, err := out.WriteString(s)
return err
}
func (e *eventTimestampEvaler) Eval(c interface{}, out *bytes.Buffer) error {
ctx := c.(*eventEvalContext)
_, err := e.formatter.Write(out, ctx.ts)
return err
}
func parseEventPath(field string) (string, error) {
field = strings.Trim(field, " \n\r\t")
var fields []string
for len(field) > 0 {
if field[0] != '[' {
return "", errors.New("expected field extractor start with '['")
}
idx := strings.IndexByte(field, ']')
if idx < 0 {
return "", errors.New("missing closing ']'")
}
path := field[1:idx]
if path == "" {
return "", errors.New("empty fields selector '[]'")
}
fields = append(fields, path)
field = field[idx+1:]
}
path := strings.Join(fields, ".")
return path, nil
}
// TODO: move to libbeat/common?
func fieldString(event *beat.Event, field string) (string, error) {
v, err := event.GetValue(field)
if err != nil {
return "", err
}
s, err := tryConvString(v)
if err != nil {
logp.Warn("Can not convert key '%v' value to string", v)
}
return s, err
}
func tryConvString(v interface{}) (string, error) {
type stringer interface {
String() string
}
switch s := v.(type) {
case string:
return s, nil
case common.Time:
return s.String(), nil
case time.Time:
return common.Time(s).String(), nil
case []byte:
return string(s), nil
case stringer:
return s.String(), nil
case bool:
if s {
return "true", nil
}
return "false", nil
case int8, int16, int32, int64, int:
i := reflect.ValueOf(s).Int()
return strconv.FormatInt(i, 10), nil
case uint8, uint16, uint32, uint64, uint:
u := reflect.ValueOf(s).Uint()
return strconv.FormatUint(u, 10), nil
case float32:
return strconv.FormatFloat(float64(s), 'g', -1, 32), nil
case float64:
return strconv.FormatFloat(s, 'g', -1, 64), nil
default:
return "", errConvertString
}
}